@bazariodev/scrollback 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - Add `useScrollback` for bounded timeline windows, cached page reveals and older-page loading.
8
+ - Keep the reading row in place across page commits, row size changes and container replacement.
9
+ - Keep the reader's follow intent through layout changes. Support jumps to the latest items.
10
+ - Add item navigation, initial targets, read-target reporting, highlights and scroll memory.
11
+ - Add configurable limits, thresholds, navigation settings and browser services.
12
+ - Supply ESM, CommonJS and TypeScript declarations. Require React 18 or 19 as a peer, with no runtime dependencies.
13
+ - Group fixed runtime strings in named constant maps. Keep browser values and diagnostic text unchanged.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bazario
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,225 @@
1
- # Temporary Holding Version
1
+ # @bazariodev/scrollback
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A React engine for bounded, paged, end-anchored timelines, such as a chat history. It renders a capped
4
+ window over cached history, loads older pages before the reader reaches them, and keeps the reading
5
+ position stable while the list changes.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pnpm add @bazariodev/scrollback react
11
+ ```
12
+
13
+ Supports React 18 and 19. `react` is a peer dependency. The package has no runtime dependencies.
14
+ Version 1.0.0 is the first stable release.
15
+
16
+ ## Usage
17
+
18
+ ```tsx
19
+ import { useScrollback } from '@bazariodev/scrollback';
20
+
21
+ type Row = { id: string; time: number; text: string };
22
+
23
+ // `rows`, `hasMore`, `isLoadingMore`, `version`, and `loadMore` come from your own data layer.
24
+ function Timeline() {
25
+ const result = useScrollback<Row>({
26
+ source: {
27
+ items: rows,
28
+ older: { hasMore, isLoading: isLoadingMore, version, load: loadMore },
29
+ },
30
+ });
31
+
32
+ return (
33
+ <div
34
+ ref={result.scrollContainerRef}
35
+ onScroll={result.onScroll}
36
+ style={{ overflowY: 'auto', height: 400 }}
37
+ >
38
+ <div ref={result.olderSentinelRef} />
39
+ <div ref={result.itemListRef}>
40
+ {result.items.map((item) => (
41
+ <div key={item.id} ref={(element) => result.registerItemElement(item.id, element)}>
42
+ {item.text}
43
+ </div>
44
+ ))}
45
+ </div>
46
+ <div ref={result.newerSentinelRef} />
47
+ </div>
48
+ );
49
+ }
50
+ ```
51
+
52
+ The engine does not fetch data. You keep the history cache and the server paging. The engine decides
53
+ which part of `items` to render and when to call `older.load`.
54
+
55
+ ## Behavior
56
+
57
+ - The render window has a cap. The default is 150 items. The window grows or moves by one reveal
58
+ step. The default step is 30 items. The first window has 60 items by default. Use `limits` to change these values.
59
+ Limits are positive integers. The engine caps `initialPageSize` at `maxRenderedItems`. It caps
60
+ `pageSize` at half of `maxRenderedItems`, so each reveal keeps at least half of the rendered rows.
61
+ - A reveal of items that are already in `source.items` does not call the server. The engine calls
62
+ `older.load` only when the cache has no more older items and `older.hasMore` is true.
63
+ - One scroll gesture reveals or loads at most one page. When a reveal still drops the reading row,
64
+ automatic paging stops until the next user scroll. This is also true for a small render cap: a reveal
65
+ whose offset the engine cannot restore pauses automatic paging until the next user scroll.
66
+ - The engine keeps the reading anchor in place when items are added before the window, when items
67
+ leave the window, and when the container width changes.
68
+ - When the reader is at the end of the timeline, the view follows new items. When the reader is not
69
+ at the end, the view stays in place. `followsAppend` can force a follow for a new last item. Use it
70
+ for an item that the reader created.
71
+ - A change of `layout.bottomInset` keeps a pinned tail in view.
72
+ - The engine reports the scroll state through `memory.onChange`. Give a stored value to
73
+ `memory.initial` to restore it. The engine restores the anchor item and its offset when the reader
74
+ was not at the end. Otherwise it scrolls to the end.
75
+ - `targets.initialId` opens the timeline at an item, scrolls to it, and highlights it. Add
76
+ `targets.initialTime` and `source.loadThrough` to load history until the item is cached.
77
+ - `navigateTo` scrolls to an item. It centers the item in the timeline's own scroll container. Ancestors
78
+ and the page do not scroll. When the item is cached, the engine scrolls to it. When you give
79
+ `time` and `source.loadThrough`, the engine loads history through that time first. When you give no
80
+ time, the engine walks older pages for a bounded number of pages. When an older page brings the
81
+ 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,
82
+ the outcome is `far-back`, or `not-found` when no older items remain.
83
+ When the engine loads history, it waits until the loaded item is in `source.items` and its row
84
+ registers. This is the same commit-driven wait as for a cached item. The outcome is `not-found`
85
+ only after an internal failsafe.
86
+ The engine waits for the target row to register before it scrolls. Call `registerItemElement` for every
87
+ rendered item. For a grouped row, call it under each item id that the row represents. If the reveal
88
+ does not put the item in the window, the outcome is `far-back`.
89
+ - `targets.focusId` keeps the window around an item. It does not scroll. When the item is cached, the
90
+ window opens around it. When the item is not cached, the window that is on screen stays. If no window
91
+ is on screen, the default window opens: the saved scroll anchor, else the latest items. A focus item
92
+ that arrives later does not move the window.
93
+ - `isReadTargetReached` is true when `targets.readId` is 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 until `targets.readId` changes.
94
+ - `targets.initialId` also scrolls only the timeline's own scroll container, and centers the item in it.
95
+ - Routine prefetch follows the `IntersectionObserver` entries of the two sentinels. The engine measures
96
+ the list only after a change that can make those entries old: a scroll that the engine made, a change
97
+ of the rendered items at a boundary, a resize of the container or of the item list, or a new
98
+ observer. Without `IntersectionObserver`, the engine measures on each scroll.
99
+ - The engine keeps one reading position: the row you read and its offset from the top of the scroll
100
+ container, or the end when you are pinned there. Every layout change puts that row back at its offset:
101
+ a page of older or newer rows, rows that leave the window at the cap, a change of the container width or
102
+ height, a row above the reading row that gets taller, and a replaced scroll container. A page request does
103
+ not hold a position of its own, so a request that fails or lands later cannot move the view. Only your own
104
+ scrolling changes the reading position and whether you are pinned to the end.
105
+ - Whether you follow the end (`isAtBottom`) is an intent, not a distance. Your own scrolling and the
106
+ commands (`scrollToBottom`, `navigateTo`, the opening position) set it. A layout change keeps it, also
107
+ when the browser moves the offset to the end because the viewport got taller. It ends when the window
108
+ does not render the latest items.
109
+ - One command owns the view at a time. `navigateTo` and `scrollToBottom` share one command token: a
110
+ later command ends an earlier one that still waits for a page, a history load, or the latest items.
111
+ - The engine owns scroll anchoring. It sets `overflow-anchor: none` on the scroll container. Do not
112
+ override it with an `!important` rule. Native anchoring would move the view a second time when
113
+ older rows are added.
114
+ - The engine shares one `ResizeObserver` registry and one measurement scheduler by default. Use
115
+ `platform` to share the ones that the rest of your page uses.
116
+ - The engine writes internal position corrections as instant jumps. This is true also when the
117
+ container has CSS `scroll-behavior: smooth`.
118
+ - The scroll container, the item list, and the sentinels can mount in a later render than the hook.
119
+ The engine positions the view and binds its observers when they attach.
120
+ - You can compose `scrollContainerRef` and the other refs with your own ref or with an inline callback
121
+ ref. A callback that is new on each render does not cause extra renders.
122
+ - A new scroll container (for example after a key change) gets the current position: the end when the
123
+ reader was at the end, else the reading anchor. This also holds when an older page lands in the same
124
+ render.
125
+ - A navigation is not moved back by a pending correction of an earlier page restore.
126
+ - Safari can change the scroll offset after paint. The engine corrects the offset after the next paint.
127
+ - Items outside the window are not in the DOM. Browser Find in page cannot find them.
128
+
129
+ ## API
130
+
131
+ ### `useScrollback(options)`
132
+
133
+ Returns the result object. The item type is generic: `useScrollback<Item extends ScrollbackItem>`.
134
+
135
+ #### Options
136
+
137
+ | Option | Type | Description |
138
+ | --- | --- | --- |
139
+ | `source.items` | `readonly Item[]` | The full cached history, oldest first. |
140
+ | `source.isLoading` | `boolean` | True while the first load runs. Default: `false`. |
141
+ | `source.older.hasMore` | `boolean` | True when the server has more older items. |
142
+ | `source.older.isLoading` | `boolean` | True while an older page loads. |
143
+ | `source.older.version` | `number` | A change counter. Any change marks a new page. It does not have to increase. |
144
+ | `source.older.load` | `() => Promise<boolean>` | Loads one older page. Resolves true when it added items. |
145
+ | `source.loadThrough` | `(target) => Promise<boolean>` | Loads history until `target` (`id` and `time`) is cached. Resolves true when found. |
146
+ | `targets.initialId` | `Item['id']` | Opens the timeline at this item. |
147
+ | `targets.initialTime` | `number` | The time of `initialId`. |
148
+ | `targets.focusId` | `Item['id']` | Keeps the window around this item when it is cached. No scrolling. |
149
+ | `targets.readId` | `Item['id']` | The item for `isReadTargetReached`. |
150
+ | `memory.initial` | `ScrollbackMemory` | The scroll state to restore. |
151
+ | `memory.onChange` | `(memory) => void` | Called when the scroll state changes. |
152
+ | `layout.bottomInset` | `number` | The height that an overlay covers at the end of the container. |
153
+ | `followsAppend` | `(item) => boolean` | Returns true for a new last item that the view must follow. Default: always false. |
154
+ | `limits.pageSize` | `number` | Reveal step and page size. A positive integer. Capped at half of `maxRenderedItems`. Default: 30. |
155
+ | `limits.initialPageSize` | `number` | Size of the first window. A positive integer. Capped at `maxRenderedItems`. Default: 60. |
156
+ | `limits.maxRenderedItems` | `number` | Render cap. A positive integer. Default: 150. |
157
+ | `thresholds.atBottom` | `number` | Distance in px from the end that counts as at the end. Default: 56. |
158
+ | `thresholds.prefetchMin` | `number` | Smallest prefetch distance in px. Default: 480. |
159
+ | `thresholds.prefetchMax` | `number` | Largest prefetch distance in px. Default: 1200. |
160
+ | `navigation.maxOlderPages` | `number` | Older pages that a navigation without `time` walks. An integer, 0 or more. Default: 5. |
161
+ | `navigation.highlightDuration` | `number` | Highlight time in ms. Default: 1400. |
162
+ | `platform.observeResize` | `(element, listener) => (() => void) \| null` | Watches an element size. Return `null` when unsupported. |
163
+ | `platform.scheduleMeasurement` | `(key, read) => () => void` | Schedules a keyed measurement. `read` returns the write function. Returns a cancel function. |
164
+ | `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. |
165
+
166
+ A navigation has `trigger` (`open` or `navigate`), `id`, and an optional `time`.
167
+
168
+ #### Result
169
+
170
+ | Field | Type | Description |
171
+ | --- | --- | --- |
172
+ | `items` | `readonly Item[]` | The rendered window, oldest first. |
173
+ | `isWaitingForInitialItem` | `boolean` | True while the engine waits for the initial target. |
174
+ | `isLoadingOlder` | `boolean` | True while an older page loads. |
175
+ | `hasMoreOlder` | `boolean` | True when more older items exist. |
176
+ | `hasMoreNewer` | `boolean` | True when newer items exist outside the window. |
177
+ | `isAtBottom` | `boolean` | True when the reader follows the end of the timeline. Only reader scrolling and commands change it. |
178
+ | `isReadTargetReached` | `boolean` | True when the read target is older than the rendered window, or its rendered row reached the viewport. |
179
+ | `isInitialTargetPending` | `boolean` | True while the initial target is not yet shown. |
180
+ | `highlightedId` | `Item['id'] \| undefined` | The item that a navigation highlights. |
181
+ | `scrollContainerRef` | `RefObject<HTMLDivElement \| null>` | Attach to the scroll container. |
182
+ | `itemListRef` | `RefObject<HTMLDivElement \| null>` | Attach to the element that holds the rows. |
183
+ | `olderSentinelRef` | `RefObject<HTMLDivElement \| null>` | Attach before the list. |
184
+ | `newerSentinelRef` | `RefObject<HTMLDivElement \| null>` | Attach after the list. |
185
+ | `onScroll` | `() => void` | Give to the `onScroll` prop of the scroll container. |
186
+ | `registerItemElement` | `(id, element) => void` | Register a row element. Call it with `null` on unmount. |
187
+ | `navigateTo` | `({ id, time? }) => void` | Scrolls to an item. It ends an earlier `navigateTo` or `scrollToBottom`. |
188
+ | `scrollToBottom` | `(options?) => void` | Scrolls to the end. It jumps instantly unless `options.behavior` is `'smooth'`. It ends an earlier `navigateTo` or `scrollToBottom`. |
189
+
190
+ The prefetch distance is 1.5 times the viewport height. The engine clamps it to the range from
191
+ `thresholds.prefetchMin` to `thresholds.prefetchMax`. All `thresholds` values are finite numbers, 0 or
192
+ more. `prefetchMin` must not be more than `prefetchMax`. Invalid values throw `RangeError`.
193
+
194
+ ## Errors
195
+
196
+ The package defines no error classes. A rejected `older.load` or `source.loadThrough` promise counts as
197
+ a load that found nothing. This is the same as resolving `false`. The engine does not rethrow. When an
198
+ initial target cannot be loaded, the outcome is `not-found` and the timeline opens at the latest items. A
199
+ navigation to an item that cannot be found ends with `not-found` or `far-back`.
200
+
201
+ A loader must resolve or reject. A loader that stays pending can keep navigation pending.
202
+
203
+ Invalid `limits`, `thresholds`, or `navigation` values throw `RangeError`.
204
+
205
+ ## TypeScript
206
+
207
+ The package includes declarations. Item ids can be a narrow string type:
208
+
209
+ ```ts
210
+ import { type ScrollbackItem, useScrollback } from '@bazariodev/scrollback';
211
+
212
+ type Row = { id: `m-${string}`; time: number; text: string };
213
+
214
+ // `items` and `older` come from your own data layer.
215
+ const result = useScrollback<Row>({ source: { items, older } });
216
+ result.navigateTo({ id: 'm-1' }); // `id` must match `Row['id']`.
217
+ ```
218
+
219
+ Exported types: `ScrollbackRef`, `ScrollbackItem`, `ItemIdOf`, `ScrollbackMemory`, `ScrollbackLimits`,
220
+ `ScrollbackThresholds`, `ScrollbackNavigationSettings`, `ScrollbackPlatform`, `ScrollbackNavigation`, `ScrollbackNavigationTrigger`,
221
+ `ScrollbackNavigationOutcome`, `ScrollToBottomOptions`, `UseScrollbackOptions`, `UseScrollbackResult`.
222
+
223
+ ## License
224
+
225
+ MIT
@@ -0,0 +1,61 @@
1
+ export const DEFAULT_LIMITS: Readonly<{
2
+ pageSize: 30;
3
+ initialPageSize: 60;
4
+ maxRenderedItems: 150;
5
+ }>;
6
+ export const DEFAULT_THRESHOLDS: Readonly<{
7
+ atBottom: 56;
8
+ prefetchMin: 480;
9
+ prefetchMax: 1200;
10
+ }>;
11
+ export const DEFAULT_NAVIGATION: Readonly<{
12
+ maxOlderPages: 5;
13
+ highlightDuration: 1400;
14
+ }>;
15
+ export const SCROLL: Readonly<{
16
+ PAGE_PREFETCH_VIEWPORT_MULTIPLIER: 1.5;
17
+ MEMORY_FLUSH_DELAY_MS: 80;
18
+ OFFSET_ROUNDING_TOLERANCE_PX: 0.5;
19
+ TOP_REAPPLY_TOLERANCE_PX: 1;
20
+ ITEM_WAIT_TIMEOUT_MS: 5000;
21
+ PAGE_COMMIT_TIMEOUT_MS: 5000;
22
+ }>;
23
+ export const PAGE_LOAD_DIRECTION: Readonly<{
24
+ NEWER: "newer";
25
+ OLDER: "older";
26
+ }>;
27
+ export const RESTORE_REASON: Readonly<{
28
+ OLDER_PAGE: "older-page";
29
+ NEWER_PAGE: "newer-page";
30
+ }>;
31
+ export const NAVIGATION_TRIGGER: Readonly<{
32
+ OPEN: "open";
33
+ NAVIGATE: "navigate";
34
+ }>;
35
+ export const NAVIGATION_OUTCOME: Readonly<{
36
+ SCROLLED: "scrolled";
37
+ NOT_FOUND: "not-found";
38
+ FAR_BACK: "far-back";
39
+ SUPERSEDED: "superseded";
40
+ }>;
41
+ export const OPEN_TARGET_STATE: Readonly<{
42
+ IDLE: "idle";
43
+ LOADING: "loading";
44
+ REACHED: "reached";
45
+ }>;
46
+ export const SCROLL_BEHAVIOR: Readonly<{
47
+ AUTO: "auto";
48
+ INSTANT: "instant";
49
+ SMOOTH: "smooth";
50
+ }>;
51
+ export const WINDOW_ERRORS: Readonly<{
52
+ ANCHOR_OUTSIDE: "Scroll window anchor is outside the item collection";
53
+ }>;
54
+ export const VALUE_TYPE: Readonly<{
55
+ FUNCTION: "function";
56
+ NUMBER: "number";
57
+ UNDEFINED: "undefined";
58
+ }>;
59
+ export const SCROLL_EVENT: Readonly<{
60
+ END: "scrollend";
61
+ }>;
@@ -0,0 +1,61 @@
1
+ export const DEFAULT_LIMITS: Readonly<{
2
+ pageSize: 30;
3
+ initialPageSize: 60;
4
+ maxRenderedItems: 150;
5
+ }>;
6
+ export const DEFAULT_THRESHOLDS: Readonly<{
7
+ atBottom: 56;
8
+ prefetchMin: 480;
9
+ prefetchMax: 1200;
10
+ }>;
11
+ export const DEFAULT_NAVIGATION: Readonly<{
12
+ maxOlderPages: 5;
13
+ highlightDuration: 1400;
14
+ }>;
15
+ export const SCROLL: Readonly<{
16
+ PAGE_PREFETCH_VIEWPORT_MULTIPLIER: 1.5;
17
+ MEMORY_FLUSH_DELAY_MS: 80;
18
+ OFFSET_ROUNDING_TOLERANCE_PX: 0.5;
19
+ TOP_REAPPLY_TOLERANCE_PX: 1;
20
+ ITEM_WAIT_TIMEOUT_MS: 5000;
21
+ PAGE_COMMIT_TIMEOUT_MS: 5000;
22
+ }>;
23
+ export const PAGE_LOAD_DIRECTION: Readonly<{
24
+ NEWER: "newer";
25
+ OLDER: "older";
26
+ }>;
27
+ export const RESTORE_REASON: Readonly<{
28
+ OLDER_PAGE: "older-page";
29
+ NEWER_PAGE: "newer-page";
30
+ }>;
31
+ export const NAVIGATION_TRIGGER: Readonly<{
32
+ OPEN: "open";
33
+ NAVIGATE: "navigate";
34
+ }>;
35
+ export const NAVIGATION_OUTCOME: Readonly<{
36
+ SCROLLED: "scrolled";
37
+ NOT_FOUND: "not-found";
38
+ FAR_BACK: "far-back";
39
+ SUPERSEDED: "superseded";
40
+ }>;
41
+ export const OPEN_TARGET_STATE: Readonly<{
42
+ IDLE: "idle";
43
+ LOADING: "loading";
44
+ REACHED: "reached";
45
+ }>;
46
+ export const SCROLL_BEHAVIOR: Readonly<{
47
+ AUTO: "auto";
48
+ INSTANT: "instant";
49
+ SMOOTH: "smooth";
50
+ }>;
51
+ export const WINDOW_ERRORS: Readonly<{
52
+ ANCHOR_OUTSIDE: "Scroll window anchor is outside the item collection";
53
+ }>;
54
+ export const VALUE_TYPE: Readonly<{
55
+ FUNCTION: "function";
56
+ NUMBER: "number";
57
+ UNDEFINED: "undefined";
58
+ }>;
59
+ export const SCROLL_EVENT: Readonly<{
60
+ END: "scrollend";
61
+ }>;