UNPKG

25.6 kBSource Map (JSON)View Raw
1{"version":3,"sources":["../src/timeline-window.js"],"names":["EventTimeline","require","DEBUG","debuglog","console","log","bind","DEFAULT_PAGINATE_LOOP_LIMIT","TimelineWindow","client","timelineSet","opts","_client","_timelineSet","_start","_end","_eventCount","_windowLimit","windowLimit","prototype","load","initialEventId","initialWindowSize","self","initFields","timeline","eventIndex","events","getEvents","length","i","getId","undefined","Error","endIndex","Math","min","ceil","startIndex","max","TimelineIndex","getBaseIndex","prom","getEventTimeline","isFulfilled","value","Promise","resolve","then","tl","getLiveTimeline","canPaginate","direction","BACKWARDS","FORWARDS","index","minIndex","maxIndex","Boolean","getNeighbouringTimeline","getPaginationToken","paginate","size","makeRequest","requestLimit","pendingPaginate","count","retreat","advance","excess","unpaginate","token","paginateEventTimeline","backwards","limit","finally","r","delta","startOfTimeline","result","push","cappedDelta","neighbour","module","exports"],"mappings":"AAAA;;;;;;;;;;;;;;;AAeA;;AAEA;;AAEA;;;;;;AACA,IAAMA,gBAAgBC,QAAQ,yBAAR,CAAtB;;AAEA;;;AAGA,IAAMC,QAAQ,KAAd;;AAEA;;;AAGA,IAAMC,WAAWD,QAAQE,QAAQC,GAAR,CAAYC,IAAZ,CAAiBF,OAAjB,CAAR,GAAoC,YAAW,CAAE,CAAlE;;AAEA;;;;;AAKA,IAAMG,8BAA8B,CAApC;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAASC,cAAT,CAAwBC,MAAxB,EAAgCC,WAAhC,EAA6CC,IAA7C,EAAmD;AAC/CA,WAAOA,QAAQ,EAAf;AACA,SAAKC,OAAL,GAAeH,MAAf;AACA,SAAKI,YAAL,GAAoBH,WAApB;;AAEA;AACA;AACA;AACA;AACA,SAAKI,MAAL,GAAc,IAAd;AACA,SAAKC,IAAL,GAAY,IAAZ;;AAEA,SAAKC,WAAL,GAAmB,CAAnB;AACA,SAAKC,YAAL,GAAoBN,KAAKO,WAAL,IAAoB,IAAxC;AACH;;AAED;;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,KAAKzD,QAAL,CAAckC,uBAAd,CACdkB,QAAQ,CAAR,GAAY7E,cAAcqD,SAA1B,GAAsCrD,cAAcsD,QADtC,CAAlB;AAEA,QAAI4B,SAAJ,EAAe;AACX,aAAKzD,QAAL,GAAgByD,SAAhB;AACA,YAAIL,QAAQ,CAAZ,EAAe;AACX,iBAAKtB,KAAL,GAAa,KAAKE,QAAL,EAAb;AACH,SAFD,MAEO;AACH,iBAAKF,KAAL,GAAa,KAAKC,QAAL,EAAb;AACH;;AAEDrD,iBAAS,qCAAT;;AAEA;AACA,eAAO,KAAKiE,OAAL,CAAaS,KAAb,CAAP;AACH;;AAED,WAAO,CAAP;AACH,CApDD;;AAsDA;;;;;;AAMArC,cAAcrB,SAAd,CAAwBgD,OAAxB,GAAkC,UAASU,KAAT,EAAgB;AAC9C,WAAO,KAAKT,OAAL,CAAaS,QAAQ,CAAC,CAAtB,IAA2B,CAAC,CAAnC;AACH,CAFD;;AAIA;;;AAGAM,OAAOC,OAAP,CAAe5E,cAAf,GAAgCA,cAAhC;;AAEA;;;AAGA2E,OAAOC,OAAP,CAAe5C,aAAf,GAA+BA,aAA/B","file":"timeline-window.js","sourcesContent":["/*\nCopyright 2016 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\"use strict\";\n\n/** @module timeline-window */\n\nimport Promise from 'bluebird';\nconst EventTimeline = require(\"./models/event-timeline\");\n\n/**\n * @private\n */\nconst DEBUG = false;\n\n/**\n * @private\n */\nconst debuglog = DEBUG ? console.log.bind(console) : function() {};\n\n/**\n * the number of times we ask the server for more events before giving up\n *\n * @private\n */\nconst DEFAULT_PAGINATE_LOOP_LIMIT = 5;\n\n/**\n * Construct a TimelineWindow.\n *\n * <p>This abstracts the separate timelines in a Matrix {@link\n * module:models/room|Room} into a single iterable thing. It keeps track of\n * the start and endpoints of the window, which can be advanced with the help\n * of pagination requests.\n *\n * <p>Before the window is useful, it must be initialised by calling {@link\n * module:timeline-window~TimelineWindow#load|load}.\n *\n * <p>Note that the window will not automatically extend itself when new events\n * are received from /sync; you should arrange to call {@link\n * module:timeline-window~TimelineWindow#paginate|paginate} on {@link\n * module:client~MatrixClient.event:\"Room.timeline\"|Room.timeline} events.\n *\n * @param {MatrixClient} client MatrixClient to be used for context/pagination\n * requests.\n *\n * @param {EventTimelineSet} timelineSet The timelineSet to track\n *\n * @param {Object} [opts] Configuration options for this window\n *\n * @param {number} [opts.windowLimit = 1000] maximum number of events to keep\n * in the window. If more events are retrieved via pagination requests,\n * excess events will be dropped from the other end of the window.\n *\n * @constructor\n */\nfunction TimelineWindow(client, timelineSet, opts) {\n opts = opts || {};\n this._client = client;\n this._timelineSet = timelineSet;\n\n // these will be TimelineIndex objects; they delineate the 'start' and\n // 'end' of the window.\n //\n // _start.index is inclusive; _end.index is exclusive.\n this._start = null;\n this._end = null;\n\n this._eventCount = 0;\n this._windowLimit = opts.windowLimit || 1000;\n}\n\n/**\n * Initialise the window to point at a given event, or the live timeline\n *\n * @param {string} [initialEventId] If given, the window will contain the\n * given event\n * @param {number} [initialWindowSize = 20] Size of the initial window\n *\n * @return {module:client.Promise}\n */\nTimelineWindow.prototype.load = function(initialEventId, initialWindowSize) {\n const self = this;\n initialWindowSize = initialWindowSize || 20;\n\n // given an EventTimeline, find the event we were looking for, and initialise our\n // fields so that the event in question is in the middle of the window.\n const initFields = function(timeline) {\n let eventIndex;\n\n const events = timeline.getEvents();\n\n if (!initialEventId) {\n // we were looking for the live timeline: initialise to the end\n eventIndex = events.length;\n } else {\n for (let i = 0; i < events.length; i++) {\n if (events[i].getId() == initialEventId) {\n eventIndex = i;\n break;\n }\n }\n\n if (eventIndex === undefined) {\n throw new Error(\"getEventTimeline result didn't include requested event\");\n }\n }\n\n const endIndex = Math.min(events.length,\n eventIndex + Math.ceil(initialWindowSize / 2));\n const startIndex = Math.max(0, endIndex - initialWindowSize);\n self._start = new TimelineIndex(timeline, startIndex - timeline.getBaseIndex());\n self._end = new TimelineIndex(timeline, endIndex - timeline.getBaseIndex());\n self._eventCount = endIndex - startIndex;\n };\n\n // We avoid delaying the resolution of the promise by a reactor tick if\n // we already have the data we need, which is important to keep room-switching\n // feeling snappy.\n //\n if (initialEventId) {\n const prom = this._client.getEventTimeline(this._timelineSet, initialEventId);\n\n if (prom.isFulfilled()) {\n initFields(prom.value());\n return Promise.resolve();\n } else {\n return prom.then(initFields);\n }\n } else {\n const tl = this._timelineSet.getLiveTimeline();\n initFields(tl);\n return Promise.resolve();\n }\n};\n\n/**\n * Check if this window can be extended\n *\n * <p>This returns true if we either have more events, or if we have a\n * pagination token which means we can paginate in that direction. It does not\n * necessarily mean that there are more events available in that direction at\n * this time.\n *\n * @param {string} direction EventTimeline.BACKWARDS to check if we can\n * paginate backwards; EventTimeline.FORWARDS to check if we can go forwards\n *\n * @return {boolean} true if we can paginate in the given direction\n */\nTimelineWindow.prototype.canPaginate = function(direction) {\n let tl;\n if (direction == EventTimeline.BACKWARDS) {\n tl = this._start;\n } else if (direction == EventTimeline.FORWARDS) {\n tl = this._end;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n\n if (!tl) {\n debuglog(\"TimelineWindow: no timeline yet\");\n return false;\n }\n\n if (direction == EventTimeline.BACKWARDS) {\n if (tl.index > tl.minIndex()) {\n return true;\n }\n } else {\n if (tl.index < tl.maxIndex()) {\n return true;\n }\n }\n\n return Boolean(tl.timeline.getNeighbouringTimeline(direction) ||\n tl.timeline.getPaginationToken(direction));\n};\n\n/**\n * Attempt to extend the window\n *\n * @param {string} direction EventTimeline.BACKWARDS to extend the window\n * backwards (towards older events); EventTimeline.FORWARDS to go forwards.\n *\n * @param {number} size number of events to try to extend by. If fewer than this\n * number are immediately available, then we return immediately rather than\n * making an API call.\n *\n * @param {boolean} [makeRequest = true] whether we should make API calls to\n * fetch further events if we don't have any at all. (This has no effect if\n * the room already knows about additional events in the relevant direction,\n * even if there are fewer than 'size' of them, as we will just return those\n * we already know about.)\n *\n * @param {number} [requestLimit = 5] limit for the number of API requests we\n * should make.\n *\n * @return {module:client.Promise} Resolves to a boolean which is true if more events\n * were successfully retrieved.\n */\nTimelineWindow.prototype.paginate = function(direction, size, makeRequest,\n requestLimit) {\n // Either wind back the message cap (if there are enough events in the\n // timeline to do so), or fire off a pagination request.\n\n if (makeRequest === undefined) {\n makeRequest = true;\n }\n\n if (requestLimit === undefined) {\n requestLimit = DEFAULT_PAGINATE_LOOP_LIMIT;\n }\n\n let tl;\n if (direction == EventTimeline.BACKWARDS) {\n tl = this._start;\n } else if (direction == EventTimeline.FORWARDS) {\n tl = this._end;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n\n if (!tl) {\n debuglog(\"TimelineWindow: no timeline yet\");\n return Promise.resolve(false);\n }\n\n if (tl.pendingPaginate) {\n return tl.pendingPaginate;\n }\n\n // try moving the cap\n const count = (direction == EventTimeline.BACKWARDS) ?\n tl.retreat(size) : tl.advance(size);\n\n if (count) {\n this._eventCount += count;\n debuglog(\"TimelineWindow: increased cap by \" + count +\n \" (now \" + this._eventCount + \")\");\n // remove some events from the other end, if necessary\n const excess = this._eventCount - this._windowLimit;\n if (excess > 0) {\n this.unpaginate(excess, direction != EventTimeline.BACKWARDS);\n }\n return Promise.resolve(true);\n }\n\n if (!makeRequest || requestLimit === 0) {\n // todo: should we return something different to indicate that there\n // might be more events out there, but we haven't found them yet?\n return Promise.resolve(false);\n }\n\n // try making a pagination request\n const token = tl.timeline.getPaginationToken(direction);\n if (!token) {\n debuglog(\"TimelineWindow: no token\");\n return Promise.resolve(false);\n }\n\n debuglog(\"TimelineWindow: starting request\");\n const self = this;\n\n const prom = this._client.paginateEventTimeline(tl.timeline, {\n backwards: direction == EventTimeline.BACKWARDS,\n limit: size,\n }).finally(function() {\n tl.pendingPaginate = null;\n }).then(function(r) {\n debuglog(\"TimelineWindow: request completed with result \" + r);\n if (!r) {\n // end of timeline\n return false;\n }\n\n // recurse to advance the index into the results.\n //\n // If we don't get any new events, we want to make sure we keep asking\n // the server for events for as long as we have a valid pagination\n // token. In particular, we want to know if we've actually hit the\n // start of the timeline, or if we just happened to know about all of\n // the events thanks to https://matrix.org/jira/browse/SYN-645.\n //\n // On the other hand, we necessarily want to wait forever for the\n // server to make its mind up about whether there are other events,\n // because it gives a bad user experience\n // (https://github.com/vector-im/vector-web/issues/1204).\n return self.paginate(direction, size, true, requestLimit - 1);\n });\n tl.pendingPaginate = prom;\n return prom;\n};\n\n\n/**\n * Remove `delta` events from the start or end of the timeline.\n *\n * @param {number} delta number of events to remove from the timeline\n * @param {boolean} startOfTimeline if events should be removed from the start\n * of the timeline.\n */\nTimelineWindow.prototype.unpaginate = function(delta, startOfTimeline) {\n const tl = startOfTimeline ? this._start : this._end;\n\n // sanity-check the delta\n if (delta > this._eventCount || delta < 0) {\n throw new Error(\"Attemting to unpaginate \" + delta + \" events, but \" +\n \"only have \" + this._eventCount + \" in the timeline\");\n }\n\n while (delta > 0) {\n const count = startOfTimeline ? tl.advance(delta) : tl.retreat(delta);\n if (count <= 0) {\n // sadness. This shouldn't be possible.\n throw new Error(\n \"Unable to unpaginate any further, but still have \" +\n this._eventCount + \" events\");\n }\n\n delta -= count;\n this._eventCount -= count;\n debuglog(\"TimelineWindow.unpaginate: dropped \" + count +\n \" (now \" + this._eventCount + \")\");\n }\n};\n\n\n/**\n * Get a list of the events currently in the window\n *\n * @return {MatrixEvent[]} the events in the window\n */\nTimelineWindow.prototype.getEvents = function() {\n if (!this._start) {\n // not yet loaded\n return [];\n }\n\n const result = [];\n\n // iterate through each timeline between this._start and this._end\n // (inclusive).\n let timeline = this._start.timeline;\n while (true) {\n const events = timeline.getEvents();\n\n // For the first timeline in the chain, we want to start at\n // this._start.index. For the last timeline in the chain, we want to\n // stop before this._end.index. Otherwise, we want to copy all of the\n // events in the timeline.\n //\n // (Note that both this._start.index and this._end.index are relative\n // to their respective timelines' BaseIndex).\n //\n let startIndex = 0, endIndex = events.length;\n if (timeline === this._start.timeline) {\n startIndex = this._start.index + timeline.getBaseIndex();\n }\n if (timeline === this._end.timeline) {\n endIndex = this._end.index + timeline.getBaseIndex();\n }\n\n for (let i = startIndex; i < endIndex; i++) {\n result.push(events[i]);\n }\n\n // if we're not done, iterate to the next timeline.\n if (timeline === this._end.timeline) {\n break;\n } else {\n timeline = timeline.getNeighbouringTimeline(EventTimeline.FORWARDS);\n }\n }\n\n return result;\n};\n\n\n/**\n * a thing which contains a timeline reference, and an index into it.\n *\n * @constructor\n * @param {EventTimeline} timeline\n * @param {number} index\n * @private\n */\nfunction TimelineIndex(timeline, index) {\n this.timeline = timeline;\n\n // the indexes are relative to BaseIndex, so could well be negative.\n this.index = index;\n}\n\n/**\n * @return {number} the minimum possible value for the index in the current\n * timeline\n */\nTimelineIndex.prototype.minIndex = function() {\n return this.timeline.getBaseIndex() * -1;\n};\n\n/**\n * @return {number} the maximum possible value for the index in the current\n * timeline (exclusive - ie, it actually returns one more than the index\n * of the last element).\n */\nTimelineIndex.prototype.maxIndex = function() {\n return this.timeline.getEvents().length - this.timeline.getBaseIndex();\n};\n\n/**\n * Try move the index forward, or into the neighbouring timeline\n *\n * @param {number} delta number of events to advance by\n * @return {number} number of events successfully advanced by\n */\nTimelineIndex.prototype.advance = function(delta) {\n if (!delta) {\n return 0;\n }\n\n // first try moving the index in the current timeline. See if there is room\n // to do so.\n let cappedDelta;\n if (delta < 0) {\n // we want to wind the index backwards.\n //\n // (this.minIndex() - this.index) is a negative number whose magnitude\n // is the amount of room we have to wind back the index in the current\n // timeline. We cap delta to this quantity.\n cappedDelta = Math.max(delta, this.minIndex() - this.index);\n if (cappedDelta < 0) {\n this.index += cappedDelta;\n return cappedDelta;\n }\n } else {\n // we want to wind the index forwards.\n //\n // (this.maxIndex() - this.index) is a (positive) number whose magnitude\n // is the amount of room we have to wind forward the index in the current\n // timeline. We cap delta to this quantity.\n cappedDelta = Math.min(delta, this.maxIndex() - this.index);\n if (cappedDelta > 0) {\n this.index += cappedDelta;\n return cappedDelta;\n }\n }\n\n // the index is already at the start/end of the current timeline.\n //\n // next see if there is a neighbouring timeline to switch to.\n const neighbour = this.timeline.getNeighbouringTimeline(\n delta < 0 ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS);\n if (neighbour) {\n this.timeline = neighbour;\n if (delta < 0) {\n this.index = this.maxIndex();\n } else {\n this.index = this.minIndex();\n }\n\n debuglog(\"paginate: switched to new neighbour\");\n\n // recurse, using the next timeline\n return this.advance(delta);\n }\n\n return 0;\n};\n\n/**\n * Try move the index backwards, or into the neighbouring timeline\n *\n * @param {number} delta number of events to retreat by\n * @return {number} number of events successfully retreated by\n */\nTimelineIndex.prototype.retreat = function(delta) {\n return this.advance(delta * -1) * -1;\n};\n\n/**\n * The TimelineWindow class.\n */\nmodule.exports.TimelineWindow = TimelineWindow;\n\n/**\n * The TimelineIndex class. exported here for unit testing.\n */\nmodule.exports.TimelineIndex = TimelineIndex;\n"]}
\No newline at end of file