// Paging of the 대화 screen (app/src/admin.spec.md, "Screens"). Pure, so app/tests/ui checks it. // // The screen keeps a live window, every item from the cursor `from` on (re-read on each tick, at // most PAGE_MAX), and before it the `older` pages kept as loaded. Items are ordered like // history_query: time, then records (`h`) before traces (`t`), then id. export const PAGE = 200, PAGE_MAX = 2000; export const cursorOf = (i) => ({ at: i.at, key: i.key }); export function compare(a, b) { return a.at - b.at || (a.key[0] === b.key[0] ? 0 : a.key[0] < b.key[0] ? -1 : 1) || Number(a.key.slice(1)) - Number(b.key.slice(1)); } export const empty = () => ({ shown: [], older: [], from: null, hasOlder: false }); /** A live answer: the items from `from` on (the newest page while there is no `from`), and * whether there were more than it holds. */ export function withLive(s, items, more) { let { older, hasOlder } = s; if (!s.from) hasOlder = more; else if (more && items.length) { // More new items than the window holds: the shown ones it no longer reaches join the pages // kept as loaded, so nothing the user had on screen disappears. const seen = new Set(older.map((i) => i.key)); older = older.concat(s.shown.filter((i) => compare(i, items[0]) < 0 && !seen.has(i.key))); } return { shown: items, older, hasOlder, from: items.length ? cursorOf(items[0]) : s.from }; } /** The page before the oldest item loaded: it joins the live window while that stays within * PAGE_MAX, else the older pages. Items already loaded are not added again. */ export function withOlder(s, page, more) { const seen = new Set(s.older.concat(s.shown).map((i) => i.key)); const fresh = page.filter((i) => !seen.has(i.key)); if (!s.older.length && s.shown.length + fresh.length <= PAGE_MAX) { const shown = fresh.concat(s.shown); return { ...s, shown, hasOlder: more, from: shown.length ? cursorOf(shown[0]) : s.from }; } return { ...s, older: fresh.concat(s.older), hasOlder: more }; }