// A long list lets go of the items far from what is in view, as a feed // scrolled through many pages would otherwise hold every post, its // pictures and players, at once; and it never reads where its items are // while scrolling. The browser tells it, as it lays out anyway // (IntersectionObservers): an item let go (idle, a space of the height it // was last drawn at) is drawn again as it comes within `NEAR` screens of // the view, well before it shows; one drawn is let go once more than // `FAR` screens away, but only when the scroller has been still a moment // (`QUIET`), never while scrolling. Nothing between the two changes, so an // item never flaps. A page more is let go but for its first few, so it is // never drawn whole at once. The browser itself skips drawing what is out // of view (the tree's List's `content-visibility: auto`), each item keeping its // height as last drawn (`heights`, by its data, so a list drawn again, its // column back near, has its heights and the scroll in it lands where it // was). The scroller is the list's nearest ancestor that scrolls, else the // page. A view in a frame (an MCP App's, which its host sizes to it) is // not windowed at all (`FRAMED`): its page is the scroller, and a frame // from another origin is told nothing of where its host's screen is // (IntersectionObservers there ignore their margins, and are clipped by // the host's view, as is `content-visibility`), so its items would be // drawn only once on the host's screen, blank as they scroll in. import { SvelteSet } from 'svelte/reactivity'; /** Whether this document is in a frame: its lists draw every item, as the browser draws them, never windowed. */ export const FRAMED = typeof window !== 'undefined' && window !== window.top; /** Lists of more items than this let go of those far. */ export const WINDOWED = 24; /** The items drawn at first, before anything is measured. */ const FIRST = 12; /** An item never drawn is taken as this tall (its content), until some of its list's are measured: then as tall as those are on average. */ const GUESS = 240; /** Within this many screens of the view, an item is drawn. */ const NEAR = 2; /** Past this many screens of the view, an item drawn is let go. */ const FAR = 4; /** How long the scroller is still before the far are let go, in ms. */ const QUIET = 150; /** The most items drawn again, or let go, a frame, the nearest drawn first: many come near at once (a page more) are drawn over frames, and a screenful far let go, never in one long task. */ const PER_FRAME = 2; /** Each item's height (its content's) as last drawn, by its data. */ const heights = new WeakMap(); const key = (item: unknown) => (typeof item === 'object' && item !== null ? item : null); const indexOf = (element: Element) => Number((element as HTMLElement).dataset.index); /** The nearest ancestor of `element` that scrolls up and down, or null for the page. */ export function scroller(element: Element): Element | null { for (let at = element.parentElement; at; at = at.parentElement) { const { overflowY } = getComputedStyle(at); if (overflowY === 'auto' || overflowY === 'scroll') return at; } return null; } export class ListWindow { /** The indices of the items let go: drawn as a space of their height. */ idle = new SvelteSet(); #items: () => readonly unknown[]; #list: HTMLElement | null = null; #root: Element | null = null; #frame = 0; /** The frame letting go of more far items is waiting for. */ #going = 0; #timer = 0; /** Measures the items drawn, while the list is attached (in a browser: a server draws a list but never attaches it). */ #sizes: ResizeObserver | null = null; /** Watches the items let go, to draw one as it comes near. */ #near: IntersectionObserver | null = null; /** Watches the items drawn, to know which are far. */ #far: IntersectionObserver | null = null; /** The items watched before the list was attached: idle or not, by element. */ #waiting = new Map(); /** The items drawn last seen far. */ #outside = new Set(); /** How many items the list had when last grown. */ #known = 0; /** The heights measured in this list, added up, and how many: what an item never drawn is taken to be. */ #total = 0; #measured = 0; constructor(items: () => readonly unknown[]) { this.#items = items; this.grow(items().length); } /** Each item measured: its height kept, by its data. */ #measure = (entries: ResizeObserverEntry[]) => { const items = this.#items(); for (const entry of entries) { // One the browser skips drawing (out of view, never drawn) is only as tall as it was taken to be. if (!entry.target.checkVisibility({ contentVisibilityAuto: true })) continue; const k = key(items[indexOf(entry.target)]); const size = entry.contentBoxSize[0]?.blockSize; if (!k || !size) continue; if (!heights.has(k)) { this.#total += size; this.#measured++; } heights.set(k, size); } }; /** The list is `length` items long now: of those added, the first are drawn (`FIRST` at first, a frame's worth of a page more) and the rest let go until they come near, so a page is never drawn whole at once. Call before the items are drawn. */ grow(length: number) { const drawn = this.#known ? PER_FRAME : FIRST; if (length > WINDOWED) for (let i = this.#known + drawn; i < length; i++) this.idle.add(i); this.#known = length; } /** The height an item's content holds, let go or out of view: its own as last drawn, else a guess. */ height(item: unknown): number { const k = key(item); return (k && heights.get(k)) ?? (this.#measured ? Math.round(this.#total / this.#measured) : GUESS); } /** Watch an item's element, its index in `data-index`, as `idle` or drawn, until the returned function is called. */ watch = (element: HTMLElement, idle: boolean) => { if (!this.#near) this.#waiting.set(element, idle); else this.#observe(element, idle); return () => { this.#waiting.delete(element); this.#near?.unobserve(element); this.#far?.unobserve(element); this.#sizes?.unobserve(element); this.#outside.delete(indexOf(element)); }; }; #observe(element: Element, idle: boolean) { if (idle) this.#near?.observe(element); else { this.#far?.observe(element); this.#sizes?.observe(element); } } /** Watch the list `element` in its scroller, until the returned function is called. */ attach = (element: HTMLElement) => { this.#list = element; this.#root = scroller(element); // The page as the root, not the top window's view: a view in a frame has margins too. const root = this.#root ?? document; this.#sizes = new ResizeObserver(this.#measure); this.#near = new IntersectionObserver( (entries) => { const near = entries.filter((entry) => entry.isIntersecting); const off = ({ boundingClientRect: at, rootBounds: view }: IntersectionObserverEntry) => view ? Math.abs(at.top + at.bottom - view.top - view.bottom) : 0; near.sort((a, b) => off(a) - off(b)); for (const [n, entry] of near.entries()) { if (n < PER_FRAME) this.idle.delete(indexOf(entry.target)); else { // Watched afresh, it is told of again next frame. this.#near?.unobserve(entry.target); this.#near?.observe(entry.target); } } }, { root, rootMargin: `${NEAR * 100}% 0px` } ); this.#far = new IntersectionObserver( (entries) => { for (const entry of entries) { if (entry.isIntersecting) this.#outside.delete(indexOf(entry.target)); else this.#outside.add(indexOf(entry.target)); } }, { root, rootMargin: `${FAR * 100}% 0px` } ); for (const [item, idle] of this.#waiting) this.#observe(item, idle); this.#waiting.clear(); const target: EventTarget = this.#root ?? window; const quiet = () => { window.clearTimeout(this.#timer); cancelAnimationFrame(this.#going); this.#timer = window.setTimeout(() => this.#letGo(), QUIET); }; target.addEventListener('scroll', quiet, { passive: true }); // Drawn again away from its top, the first items it draws are far: let go of them too. quiet(); // As it mounts (drawn again, its scroll put back): which are near, before the browser paints. this.#frame = requestAnimationFrame(() => { this.#frame = 0; this.#drawNear(); }); return () => { cancelAnimationFrame(this.#frame); cancelAnimationFrame(this.#going); window.clearTimeout(this.#timer); target.removeEventListener('scroll', quiet); this.#near?.disconnect(); this.#far?.disconnect(); this.#near = this.#far = null; this.#sizes?.disconnect(); this.#sizes = null; this.#outside.clear(); this.#list = null; }; }; /** Draw the items within `NEAR` screens of the view, from where they are now: one read of them all. */ #drawNear() { const list = this.#list; if (!list) return; const box = this.#root ? this.#root.getBoundingClientRect() : { top: 0, bottom: window.innerHeight }; const screen = box.bottom - box.top; // A list in a box of no height (hidden) changes nothing. if (screen <= 0) return; const children = list.children; const places = Array.from({ length: Math.min(children.length, this.#items().length) }, (_, i) => children[i].getBoundingClientRect()); places.forEach((at, i) => { if (at.bottom >= box.top - NEAR * screen && at.top <= box.bottom + NEAR * screen) this.idle.delete(i); }); } /** Let go of the items drawn and far, once the list is long, a few a frame until scrolling starts again: each held at its height, as measured or as it was taken to be, never drawn. */ #letGo() { this.#going = 0; if (this.#items().length <= WINDOWED) return; let n = 0; for (const i of this.#outside) { if (!this.idle.has(i)) { if (n === PER_FRAME) { this.#going = requestAnimationFrame(() => this.#letGo()); return; } this.idle.add(i); n++; } this.#outside.delete(i); } } }