@bazariodev/scrollback
v1.0.1
Published
React engine for bounded, paged, end-anchored scrollback timelines: a capped render window over cached history, page prefetch, reading-anchor preservation, tail following, and scroll memory.
Maintainers
Readme
@bazariodev/scrollback
A React engine for bounded, paged, end-anchored timelines, such as a chat history. It renders a capped window over cached history, loads older pages before the reader reaches them, and keeps the reading position stable while the list changes.
Install
pnpm add @bazariodev/scrollback reactSupports React 18 and 19. react is a peer dependency. The package has no runtime dependencies.
Version 1.0.0 is the first stable release.
Usage
import { useScrollback } from '@bazariodev/scrollback';
type Row = { id: string; time: number; text: string };
// `rows`, `hasMore`, `isLoadingMore`, `version`, and `loadMore` come from your own data layer.
function Timeline() {
const result = useScrollback<Row>({
source: {
items: rows,
older: { hasMore, isLoading: isLoadingMore, version, load: loadMore },
},
});
return (
<div
ref={result.scrollContainerRef}
onScroll={result.onScroll}
style={{ overflowY: 'auto', height: 400 }}
>
<div ref={result.olderSentinelRef} />
<div ref={result.itemListRef}>
{result.items.map((item) => (
<div key={item.id} ref={(element) => result.registerItemElement(item.id, element)}>
{item.text}
</div>
))}
</div>
<div ref={result.newerSentinelRef} />
</div>
);
}The engine does not fetch data. You keep the history cache and the server paging. The engine decides
which part of items to render and when to call older.load.
Behavior
- The render window has a cap. The default is 150 items. The window grows or moves by one reveal
step. The default step is 30 items. The first window has 60 items by default. Use
limitsto change these values. Limits are positive integers. The engine capsinitialPageSizeatmaxRenderedItems. It capspageSizeat half ofmaxRenderedItems, so each reveal keeps at least half of the rendered rows. - A reveal of items that are already in
source.itemsdoes not call the server. The engine callsolder.loadonly when the cache has no more older items andolder.hasMoreis true. - One scroll gesture reveals or loads at most one page. When a reveal still drops the reading row, automatic paging stops until the next user scroll. This is also true for a small render cap: a reveal whose offset the engine cannot restore pauses automatic paging until the next user scroll.
- The engine keeps the reading anchor in place when items are added before the window, when items leave the window, and when the container width changes.
- When the reader is at the end of the timeline, the view follows new items. When the reader is not
at the end, the view stays in place.
followsAppendcan force a follow for a new last item. Use it for an item that the reader created. - A change of
layout.bottomInsetkeeps a pinned tail in view. - In WebKit, the view can move away from the end if React removes an unregistered element, such as a date divider, before it replaces the last row while layout changes are pending.
- The engine reports the scroll state through
memory.onChange. Give a stored value tomemory.initialto restore it. The engine restores the anchor item and its offset when the reader was not at the end. Otherwise it scrolls to the end. targets.initialIdopens the timeline at an item, scrolls to it, and highlights it. Addtargets.initialTimeandsource.loadThroughto load history until the item is cached.navigateToscrolls to an item. It centers the item in the timeline's own scroll container. Ancestors and the page do not scroll. When the item is cached, the engine scrolls to it. When you givetimeandsource.loadThrough, the engine loads history through that time first. When you give no time, the engine walks older pages for a bounded number of pages. When an older page brings the target into the cache, the engine waits for the row of the target, as for any cached item. If it does not find the item, the outcome isfar-back, ornot-foundwhen no older items remain. When the engine loads history, it waits until the loaded item is insource.itemsand its row registers. This is the same commit-driven wait as for a cached item. The outcome isnot-foundonly after an internal failsafe. The engine waits for the target row to register before it scrolls. CallregisterItemElementfor every rendered item. For a grouped row, call it under each item id that the row represents. If the reveal does not put the item in the window, the outcome isfar-back.targets.focusIdkeeps the window around an item. It does not scroll. When the item is cached, the window opens around it. When the item is not cached, the window that is on screen stays. If no window is on screen, the default window opens: the saved scroll anchor, else the latest items. A focus item that arrives later does not move the window.isReadTargetReachedis true whentargets.readIdis older than the rendered window, or when its row is rendered and has reached the viewport (its top is at or above the viewport bottom). It stays true untiltargets.readIdchanges.targets.initialIdalso scrolls only the timeline's own scroll container, and centers the item in it.- Routine prefetch follows the
IntersectionObserverentries of the two sentinels. The engine measures the list only after a change that can make those entries old: a scroll that the engine made, a change of the rendered items at a boundary, a resize of the container or of the item list, or a new observer. WithoutIntersectionObserver, the engine measures on each scroll. - The engine keeps one reading position: the row you read and its offset from the top of the scroll container, or the end when you are pinned there. Every layout change puts that row back at its offset: a page of older or newer rows, rows that leave the window at the cap, a change of the container width or height, a row above the reading row that gets taller, and a replaced scroll container. A page request does not hold a position of its own, so a request that fails or lands later cannot move the view. Only your own scrolling changes the reading position and whether you are pinned to the end.
- Whether you follow the end (
isAtBottom) is an intent, not a distance. Your own scrolling and the commands (scrollToBottom,navigateTo, the opening position) set it. A layout change keeps it, also when the browser moves the offset to the end because the viewport got taller. It ends when the window does not render the latest items. - One command owns the view at a time.
navigateToandscrollToBottomshare one command token: a later command ends an earlier one that still waits for a page, a history load, or the latest items. - The engine owns scroll anchoring. It sets
overflow-anchor: noneon the scroll container. Do not override it with an!importantrule. Native anchoring would move the view a second time when older rows are added. - The engine shares one
ResizeObserverregistry and one measurement scheduler by default. Useplatformto share the ones that the rest of your page uses. - The engine writes internal position corrections as instant jumps. This is true also when the
container has CSS
scroll-behavior: smooth. - The scroll container, the item list, and the sentinels can mount in a later render than the hook. The engine positions the view and binds its observers when they attach.
- You can compose
scrollContainerRefand the other refs with your own ref or with an inline callback ref. A callback that is new on each render does not cause extra renders. - A new scroll container (for example after a key change) gets the current position: the end when the reader was at the end, else the reading anchor. This also holds when an older page lands in the same render.
- A navigation is not moved back by a pending correction of an earlier page restore.
- Safari can change the scroll offset after paint. The engine corrects the offset after the next paint.
- Items outside the window are not in the DOM. Browser Find in page cannot find them.
API
useScrollback(options)
Returns the result object. The item type is generic: useScrollback<Item extends ScrollbackItem>.
Options
| Option | Type | Description |
| --- | --- | --- |
| source.items | readonly Item[] | The full cached history, oldest first. |
| source.isLoading | boolean | True while the first load runs. Default: false. |
| source.older.hasMore | boolean | True when the server has more older items. |
| source.older.isLoading | boolean | True while an older page loads. |
| source.older.version | number | A change counter. Any change marks a new page. It does not have to increase. |
| source.older.load | () => Promise<boolean> | Loads one older page. Resolves true when it added items. |
| source.loadThrough | (target) => Promise<boolean> | Loads history until target (id and time) is cached. Resolves true when found. |
| targets.initialId | Item['id'] | Opens the timeline at this item. |
| targets.initialTime | number | The time of initialId. |
| targets.focusId | Item['id'] | Keeps the window around this item when it is cached. No scrolling. |
| targets.readId | Item['id'] | The item for isReadTargetReached. |
| memory.initial | ScrollbackMemory | The scroll state to restore. |
| memory.onChange | (memory) => void | Called when the scroll state changes. |
| layout.bottomInset | number | The height that an overlay covers at the end of the container. |
| followsAppend | (item) => boolean | Returns true for a new last item that the view must follow. Default: always false. |
| limits.pageSize | number | Reveal step and page size. A positive integer. Capped at half of maxRenderedItems. Default: 30. |
| limits.initialPageSize | number | Size of the first window. A positive integer. Capped at maxRenderedItems. Default: 60. |
| limits.maxRenderedItems | number | Render cap. A positive integer. Default: 150. |
| thresholds.atBottom | number | Distance in px from the end that counts as at the end. Default: 56. |
| thresholds.prefetchMin | number | Smallest prefetch distance in px. Default: 480. |
| thresholds.prefetchMax | number | Largest prefetch distance in px. Default: 1200. |
| navigation.maxOlderPages | number | Older pages that a navigation without time walks. An integer, 0 or more. Default: 5. |
| navigation.highlightDuration | number | Highlight time in ms. Default: 1400. |
| platform.observeResize | (element, listener) => (() => void) \| null | Watches an element size. Return null when unsupported. |
| platform.scheduleMeasurement | (key, read) => () => void | Schedules a keyed measurement. read returns the write function. Returns a cancel function. |
| onNavigation | (navigation) => ((outcome) => void) \| void | Called when a navigation starts. The returned function is called once with scrolled, not-found, or far-back. It is not called when a newer command replaces the first. |
A navigation has trigger (open or navigate), id, and an optional time.
Result
| Field | Type | Description |
| --- | --- | --- |
| items | readonly Item[] | The rendered window, oldest first. |
| isWaitingForInitialItem | boolean | True while the engine waits for the initial target. |
| isLoadingOlder | boolean | True while an older page loads. |
| hasMoreOlder | boolean | True when more older items exist. |
| hasMoreNewer | boolean | True when newer items exist outside the window. |
| isAtBottom | boolean | True when the reader follows the end of the timeline. Only reader scrolling and commands change it. |
| isReadTargetReached | boolean | True when the read target is older than the rendered window, or its rendered row reached the viewport. |
| isInitialTargetPending | boolean | True while the initial target is not yet shown. |
| highlightedId | Item['id'] \| undefined | The item that a navigation highlights. |
| scrollContainerRef | RefObject<HTMLDivElement \| null> | Attach to the scroll container. |
| itemListRef | RefObject<HTMLDivElement \| null> | Attach to the element that holds the rows. |
| olderSentinelRef | RefObject<HTMLDivElement \| null> | Attach before the list. |
| newerSentinelRef | RefObject<HTMLDivElement \| null> | Attach after the list. |
| onScroll | () => void | Give to the onScroll prop of the scroll container. |
| registerItemElement | (id, element) => void | Register a row element. Call it with null on unmount. |
| navigateTo | ({ id, time? }) => void | Scrolls to an item. It ends an earlier navigateTo or scrollToBottom. |
| scrollToBottom | (options?) => void | Scrolls to the end. It jumps instantly unless options.behavior is 'smooth'. It ends an earlier navigateTo or scrollToBottom. |
The prefetch distance is 1.5 times the viewport height. The engine clamps it to the range from
thresholds.prefetchMin to thresholds.prefetchMax. All thresholds values are finite numbers, 0 or
more. prefetchMin must not be more than prefetchMax. Invalid values throw RangeError.
Errors
The package defines no error classes. A rejected older.load or source.loadThrough promise counts as
a load that found nothing. This is the same as resolving false. The engine does not rethrow. When an
initial target cannot be loaded, the outcome is not-found and the timeline opens at the latest items. A
navigation to an item that cannot be found ends with not-found or far-back.
A loader must resolve or reject. A loader that stays pending can keep navigation pending.
Invalid limits, thresholds, or navigation values throw RangeError.
TypeScript
The package includes declarations. Item ids can be a narrow string type:
import { type ScrollbackItem, useScrollback } from '@bazariodev/scrollback';
type Row = { id: `m-${string}`; time: number; text: string };
// `items` and `older` come from your own data layer.
const result = useScrollback<Row>({ source: { items, older } });
result.navigateTo({ id: 'm-1' }); // `id` must match `Row['id']`.Exported types: ScrollbackRef, ScrollbackItem, ItemIdOf, ScrollbackMemory, ScrollbackLimits,
ScrollbackThresholds, ScrollbackNavigationSettings, ScrollbackPlatform, ScrollbackNavigation, ScrollbackNavigationTrigger,
ScrollbackNavigationOutcome, ScrollToBottomOptions, UseScrollbackOptions, UseScrollbackResult.
License
MIT
