@barqjs/aria 0.0.0-stage → 0.2.0-next.1
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/LICENSE +21 -0
- package/README.md +304 -2
- package/package.json +437 -4
- package/src/autocomplete.tsx +581 -0
- package/src/breadcrumbs.tsx +297 -0
- package/src/button.tsx +468 -0
- package/src/calendar.tsx +2316 -0
- package/src/checkbox.tsx +732 -0
- package/src/collections.ts +1059 -0
- package/src/color.ts +2119 -0
- package/src/colorpicker.tsx +2023 -0
- package/src/colorswatchpicker.tsx +240 -0
- package/src/combobox.tsx +3003 -0
- package/src/command.tsx +1203 -0
- package/src/date.ts +674 -0
- package/src/datefield.tsx +2066 -0
- package/src/datepicker.tsx +907 -0
- package/src/dialog.tsx +1077 -0
- package/src/disclosure.tsx +711 -0
- package/src/dnd/clipboard.ts +125 -0
- package/src/dnd/collection.ts +1265 -0
- package/src/dnd/data.ts +409 -0
- package/src/dnd/drag-drop.ts +801 -0
- package/src/dnd/index.ts +133 -0
- package/src/dnd/manager.ts +639 -0
- package/src/dnd/strings.ts +1279 -0
- package/src/dnd/targets.ts +726 -0
- package/src/dnd/types.ts +212 -0
- package/src/dom.ts +703 -0
- package/src/drag-and-drop.tsx +669 -0
- package/src/drawer.ts +674 -0
- package/src/dropzone.tsx +208 -0
- package/src/file-trigger.tsx +103 -0
- package/src/focus.ts +1370 -0
- package/src/form.tsx +94 -0
- package/src/gridlist.tsx +1354 -0
- package/src/group.tsx +146 -0
- package/src/i18n.ts +823 -0
- package/src/index.ts +1672 -0
- package/src/interactions/description.ts +73 -0
- package/src/interactions/flags.ts +35 -0
- package/src/interactions/focus-events.ts +226 -0
- package/src/interactions/focusable.ts +86 -0
- package/src/interactions/hover.ts +213 -0
- package/src/interactions/interact-outside.ts +123 -0
- package/src/interactions/keyboard.ts +298 -0
- package/src/interactions/listeners.ts +78 -0
- package/src/interactions/long-press.ts +160 -0
- package/src/interactions/modality.ts +428 -0
- package/src/interactions/move.ts +257 -0
- package/src/interactions/open-link.ts +226 -0
- package/src/interactions/press.ts +915 -0
- package/src/interactions/prevent-focus.ts +102 -0
- package/src/interactions/scroll-wheel.ts +43 -0
- package/src/interactions/text-selection.ts +77 -0
- package/src/interactions.ts +81 -0
- package/src/label.ts +140 -0
- package/src/link.tsx +477 -0
- package/src/listbox.tsx +1247 -0
- package/src/live.ts +208 -0
- package/src/menu.tsx +2383 -0
- package/src/menubar.tsx +579 -0
- package/src/navigation-tree.tsx +357 -0
- package/src/navigation.ts +735 -0
- package/src/numberfield.tsx +942 -0
- package/src/otp.ts +430 -0
- package/src/overlay-arrow.tsx +157 -0
- package/src/overlays.ts +1549 -0
- package/src/platform.ts +75 -0
- package/src/presence.ts +164 -0
- package/src/preview-trigger.tsx +582 -0
- package/src/progress-bar-context.ts +15 -0
- package/src/questionnaire.tsx +1717 -0
- package/src/radio.tsx +641 -0
- package/src/register-dom.ts +12 -0
- package/src/scroller.ts +1165 -0
- package/src/select.tsx +1745 -0
- package/src/selection-indicator.tsx +74 -0
- package/src/selection.ts +1472 -0
- package/src/shared-element-transition.tsx +316 -0
- package/src/sheet.tsx +1461 -0
- package/src/slider.tsx +1137 -0
- package/src/splitter.ts +1152 -0
- package/src/static-collection.ts +211 -0
- package/src/switch.tsx +212 -0
- package/src/table.tsx +2218 -0
- package/src/tabs.tsx +1127 -0
- package/src/tag.tsx +637 -0
- package/src/textarea.tsx +186 -0
- package/src/textfield.tsx +483 -0
- package/src/toast-components.tsx +589 -0
- package/src/toast.ts +658 -0
- package/src/toggle-button-group.tsx +175 -0
- package/src/toggle-input.tsx +86 -0
- package/src/toggle.ts +384 -0
- package/src/togglegroup.ts +365 -0
- package/src/tokenfield.tsx +1673 -0
- package/src/toolbar.tsx +184 -0
- package/src/tooltip.tsx +674 -0
- package/src/tree.tsx +2075 -0
- package/src/utils.ts +787 -0
- package/src/validation.ts +504 -0
- package/src/virtualizer.tsx +837 -0
package/src/scroller.ts
ADDED
|
@@ -0,0 +1,1165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A viewport that stays at the end while new content arrives.
|
|
3
|
+
*
|
|
4
|
+
* This is the piece `@barqjs/ui`'s `<MessageScroller>` needed. Upstream's is a
|
|
5
|
+
* React primitive package, so the engine is written here and only the behaviour
|
|
6
|
+
* is upstream's.
|
|
7
|
+
*
|
|
8
|
+
* A transcript is the one scroller where the interesting end is the BOTTOM, and
|
|
9
|
+
* three things follow from that.
|
|
10
|
+
*
|
|
11
|
+
* **Sticking is a decision, and it survives new content.** Someone reading at
|
|
12
|
+
* the bottom wants the next message; someone who has scrolled up to read wants
|
|
13
|
+
* to be left alone. So the answer is not "scroll on every append" but "keep
|
|
14
|
+
* doing whatever the last scroll said", and a message arriving does not change
|
|
15
|
+
* what that was.
|
|
16
|
+
*
|
|
17
|
+
* **The end needs a tolerance.** Sub-pixel scroll offsets, a browser zoom and a
|
|
18
|
+
* fractional device pixel ratio all mean
|
|
19
|
+
* `scrollTop + clientHeight === scrollHeight` is almost never exactly true, and
|
|
20
|
+
* a scroller that tests for it is one that never counts as being at the end.
|
|
21
|
+
*
|
|
22
|
+
* **A programmatic scroll is not the person scrolling.** Calling `toEnd()`
|
|
23
|
+
* fires the same `scroll` event a finger does, and reading that event as
|
|
24
|
+
* intent is how a scroller decides the user just scrolled away from the
|
|
25
|
+
* bottom it moved them to.
|
|
26
|
+
*
|
|
27
|
+
* **A new turn goes to the top, not to the bottom.** A row marked as a scroll
|
|
28
|
+
* anchor is the start of an exchange: the question just sent. Following the
|
|
29
|
+
* end would show its last line and then push it away as the reply streams, so
|
|
30
|
+
* it is placed a peek below the top instead and HELD there while what is under
|
|
31
|
+
* it grows. There is usually not enough content below a new last row to scroll
|
|
32
|
+
* it that high, so an empty spacer after the rows makes the room and gives it
|
|
33
|
+
* back as the reply fills it. When none is left the reply has filled the
|
|
34
|
+
* viewport, and following the end takes over.
|
|
35
|
+
*
|
|
36
|
+
* **Only a gesture lets go of a held turn or a jump.** A scroll event cannot
|
|
37
|
+
* tell the person from the engine, and both of those positions are away from
|
|
38
|
+
* the end on purpose. A wheel, a touch move or a scrolling key is the person.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
import { createSignal, type Accessor } from "@barqjs/core";
|
|
42
|
+
|
|
43
|
+
import { access, type MaybeAccessor } from "./utils.ts";
|
|
44
|
+
|
|
45
|
+
const pixels = (value: string): number => {
|
|
46
|
+
const parsed = Number.parseFloat(value);
|
|
47
|
+
return Number.isFinite(parsed) ? parsed : 0;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/** How far from the end still counts as being at it, in px. */
|
|
51
|
+
const TOLERANCE = 8;
|
|
52
|
+
/** How much of the previous message stays in view above a newly anchored one, in px. */
|
|
53
|
+
const PEEK = 64;
|
|
54
|
+
/** Two positions closer than this are the same one: zoom and HiDPI round differently. */
|
|
55
|
+
const EPSILON = 0.5;
|
|
56
|
+
/** How long a smooth scroll is assumed to take, which no event reports. */
|
|
57
|
+
const SMOOTH = 400;
|
|
58
|
+
|
|
59
|
+
/** Where a transcript opens the first time it has anything in it. */
|
|
60
|
+
export type MessageScrollerDefaultScrollPosition = "start" | "end" | "last-anchor";
|
|
61
|
+
|
|
62
|
+
export type MessageScrollerScrollAlign = "start" | "center" | "end" | "nearest";
|
|
63
|
+
|
|
64
|
+
export interface MessageScrollerScrollOptions {
|
|
65
|
+
/** Which edge of the viewport the target lines up with. @default "start" */
|
|
66
|
+
align?: MessageScrollerScrollAlign;
|
|
67
|
+
/** @default "auto" */
|
|
68
|
+
behavior?: ScrollBehavior;
|
|
69
|
+
/** Space kept between the target and that edge, in px. @default the scroller's own */
|
|
70
|
+
scrollMargin?: number;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Which ways there is still somewhere to scroll. */
|
|
74
|
+
export interface MessageScrollerScrollable {
|
|
75
|
+
readonly start: boolean;
|
|
76
|
+
readonly end: boolean;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface MessageScrollerVisibilityState {
|
|
80
|
+
/**
|
|
81
|
+
* The anchored turn being read: the last one to have reached the reading
|
|
82
|
+
* line. It stays current after its first row scrolls out above.
|
|
83
|
+
*/
|
|
84
|
+
readonly currentAnchorId: string | null;
|
|
85
|
+
/** The message ids on screen, in document order. */
|
|
86
|
+
readonly visibleMessageIds: readonly string[];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const NOT_SCROLLABLE: MessageScrollerScrollable = { start: false, end: false };
|
|
90
|
+
const NOTHING_VISIBLE: MessageScrollerVisibilityState = {
|
|
91
|
+
currentAnchorId: null,
|
|
92
|
+
visibleMessageIds: [],
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* What the scroller is doing about new content.
|
|
97
|
+
*
|
|
98
|
+
* `following` keeps the end in view. `free` leaves the position alone. `anchored`
|
|
99
|
+
* holds one turn at the reading line while its reply streams in below it.
|
|
100
|
+
* `jumping` is where a `scrollToMessage` left it, which nothing but the person
|
|
101
|
+
* moves it away from.
|
|
102
|
+
*/
|
|
103
|
+
type Mode = "following" | "free" | "anchored" | "jumping";
|
|
104
|
+
|
|
105
|
+
export interface MessageScrollerOptions {
|
|
106
|
+
/** How close to the end still counts. @default 8 */
|
|
107
|
+
tolerance?: MaybeAccessor<number | undefined>;
|
|
108
|
+
/** Whether to follow new content at all. @default true */
|
|
109
|
+
follow?: MaybeAccessor<boolean | undefined>;
|
|
110
|
+
/** Where it opens once it first has content. @default wherever it is */
|
|
111
|
+
defaultScrollPosition?: MaybeAccessor<MessageScrollerDefaultScrollPosition | undefined>;
|
|
112
|
+
/** How much of the previous message shows above a newly anchored one, in px. @default 64 */
|
|
113
|
+
scrollPreviousItemPeek?: MaybeAccessor<number | undefined>;
|
|
114
|
+
/** Space kept at the aligned edge by `scrollToMessage` and by anchoring, in px. @default 0 */
|
|
115
|
+
scrollMargin?: MaybeAccessor<number | undefined>;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export interface MessageScroller {
|
|
119
|
+
/** Whether the viewport is at the end, within the tolerance. */
|
|
120
|
+
readonly isAtEnd: Accessor<boolean>;
|
|
121
|
+
/** Whether there is anything to scroll: false hides the button. */
|
|
122
|
+
readonly isScrollable: Accessor<boolean>;
|
|
123
|
+
/** True while a programmatic scroll is in flight. */
|
|
124
|
+
readonly isAutoscrolling: Accessor<boolean>;
|
|
125
|
+
/** Which ways there is still somewhere to go. */
|
|
126
|
+
readonly scrollable: Accessor<MessageScrollerScrollable>;
|
|
127
|
+
/** What is on screen. Empty until something calls {@link MessageScroller.watchVisibility}. */
|
|
128
|
+
readonly visibility: Accessor<MessageScrollerVisibilityState>;
|
|
129
|
+
/** True until the opening position has been applied, so the first paint can wait for it. */
|
|
130
|
+
readonly isPending: Accessor<boolean>;
|
|
131
|
+
/** The element to watch, or `null` to stop watching. */
|
|
132
|
+
readonly attach: (viewport: HTMLElement | null) => void;
|
|
133
|
+
/** The element whose children are the rows. @default the viewport's first child */
|
|
134
|
+
readonly attachContent: (content: HTMLElement | null) => void;
|
|
135
|
+
/** An empty last child of the content, which is grown to make room above an anchored turn. */
|
|
136
|
+
readonly attachSpacer: (spacer: HTMLElement | null) => void;
|
|
137
|
+
/** Name a row, so `scrollToMessage` and the visibility state can find it. */
|
|
138
|
+
readonly register: (
|
|
139
|
+
messageId: string,
|
|
140
|
+
element: HTMLElement | null,
|
|
141
|
+
removed?: HTMLElement | null,
|
|
142
|
+
) => void;
|
|
143
|
+
/** Whether rows added above keep the row being read where it is. @default true */
|
|
144
|
+
readonly preserveOnPrepend: (preserve: MaybeAccessor<boolean | undefined>) => void;
|
|
145
|
+
/** Start computing {@link MessageScroller.visibility}. Returns what stops it. */
|
|
146
|
+
readonly watchVisibility: () => () => void;
|
|
147
|
+
/** A wheel, a touch or a scrolling key: the person is moving it themselves. */
|
|
148
|
+
readonly intent: () => void;
|
|
149
|
+
/** Jump or glide to the bottom. */
|
|
150
|
+
readonly toEnd: (behavior?: ScrollBehavior) => boolean;
|
|
151
|
+
readonly toStart: (behavior?: ScrollBehavior) => boolean;
|
|
152
|
+
/** `toEnd` and `toStart` as upstream spells them. `false` before there is a viewport. */
|
|
153
|
+
readonly scrollToEnd: (options?: MessageScrollerScrollOptions) => boolean;
|
|
154
|
+
readonly scrollToStart: (options?: MessageScrollerScrollOptions) => boolean;
|
|
155
|
+
/**
|
|
156
|
+
* Bring a registered row into view. A row that has not mounted yet in an
|
|
157
|
+
* empty transcript is remembered and scrolled to when it does; otherwise an
|
|
158
|
+
* unknown id answers `false`.
|
|
159
|
+
*/
|
|
160
|
+
readonly scrollToMessage: (messageId: string, options?: MessageScrollerScrollOptions) => boolean;
|
|
161
|
+
/** Re-measure, which an append does through the observer already. */
|
|
162
|
+
readonly measure: () => void;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const isAnchor = (element: HTMLElement): boolean => element.dataset.scrollAnchor === "true";
|
|
166
|
+
|
|
167
|
+
export function messageScroller(options: MessageScrollerOptions = {}): MessageScroller {
|
|
168
|
+
// `ownedWrite`: `attach` is what a viewport's `ref` is given, so it measures,
|
|
169
|
+
// and writes these, while the component holding the viewport is being built.
|
|
170
|
+
const own = { ownedWrite: true } as const;
|
|
171
|
+
const [atEnd, setAtEnd] = createSignal(true, own);
|
|
172
|
+
const [scrollable, setScrollable] = createSignal(false, own);
|
|
173
|
+
const [autoscrolling, setAutoscrolling] = createSignal(false);
|
|
174
|
+
const [edges, setEdges] = createSignal<MessageScrollerScrollable>(NOT_SCROLLABLE, own);
|
|
175
|
+
const [seenNow, setSeenNow] = createSignal<MessageScrollerVisibilityState>(NOTHING_VISIBLE, own);
|
|
176
|
+
const opening = access(options.defaultScrollPosition);
|
|
177
|
+
const [pending, setPending] = createSignal(opening === "end" || opening === "last-anchor", own);
|
|
178
|
+
|
|
179
|
+
// The scroller's own copy of what the signals publish. A scroll event
|
|
180
|
+
// measures and then decides in the same tick, and a signal write is not
|
|
181
|
+
// published until the flush, so reading the signals back here would decide
|
|
182
|
+
// against the measurement the previous event left behind.
|
|
183
|
+
let isAtEnd = true;
|
|
184
|
+
let isAutoscrolling = false;
|
|
185
|
+
let published: MessageScrollerScrollable = NOT_SCROLLABLE;
|
|
186
|
+
|
|
187
|
+
let viewport: HTMLElement | null = null;
|
|
188
|
+
let content: HTMLElement | null = null;
|
|
189
|
+
let spacer: HTMLElement | null = null;
|
|
190
|
+
let spacerHeight = 0;
|
|
191
|
+
let observer: ResizeObserver | null = null;
|
|
192
|
+
let mutations: MutationObserver | null = null;
|
|
193
|
+
// What the last real scroll said, which an append must not change.
|
|
194
|
+
let mode: Mode = "following";
|
|
195
|
+
let settle: ReturnType<typeof setTimeout> | null = null;
|
|
196
|
+
let resized: number | null = null;
|
|
197
|
+
|
|
198
|
+
let itemCount = 0;
|
|
199
|
+
let firstItem: HTMLElement | null = null;
|
|
200
|
+
// Rows already accounted for, so an anchor is scrolled to once: when it
|
|
201
|
+
// arrives, not again every time something else in the list changes.
|
|
202
|
+
let known = new WeakSet<HTMLElement>();
|
|
203
|
+
let held: HTMLElement | null = null;
|
|
204
|
+
let reading: { element: HTMLElement; top: number } | null = null;
|
|
205
|
+
let queued: { messageId: string; options?: MessageScrollerScrollOptions } | null = null;
|
|
206
|
+
let opened = false;
|
|
207
|
+
let lastTop = 0;
|
|
208
|
+
let preserve: MaybeAccessor<boolean | undefined> = true;
|
|
209
|
+
|
|
210
|
+
const messages = new Map<string, HTMLElement>();
|
|
211
|
+
const onScreen = new Set<string>();
|
|
212
|
+
let watchers = 0;
|
|
213
|
+
let intersections: IntersectionObserver | null = null;
|
|
214
|
+
let visibilityFrame: number | null = null;
|
|
215
|
+
|
|
216
|
+
const tolerance = (): number => access(options.tolerance) ?? TOLERANCE;
|
|
217
|
+
const follows = (): boolean => access(options.follow) !== false;
|
|
218
|
+
const peek = (): number => access(options.scrollPreviousItemPeek) ?? PEEK;
|
|
219
|
+
const margin = (): number => access(options.scrollMargin) ?? 0;
|
|
220
|
+
|
|
221
|
+
const contentOf = (): HTMLElement | null => {
|
|
222
|
+
if (content !== null) return content;
|
|
223
|
+
const first = viewport?.firstElementChild;
|
|
224
|
+
return first instanceof HTMLElement ? first : null;
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
const itemsOf = (parent: HTMLElement): HTMLElement[] => {
|
|
228
|
+
const out: HTMLElement[] = [];
|
|
229
|
+
for (const child of parent.children) {
|
|
230
|
+
if (child instanceof HTMLElement && child !== spacer) out.push(child);
|
|
231
|
+
}
|
|
232
|
+
return out;
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
const padding = (element: HTMLElement | null): { start: number; end: number } => {
|
|
236
|
+
if (element === null) return { start: 0, end: 0 };
|
|
237
|
+
const style = getComputedStyle(element);
|
|
238
|
+
return {
|
|
239
|
+
start: pixels(style.paddingBlockStart || style.paddingTop),
|
|
240
|
+
end: pixels(style.paddingBlockEnd || style.paddingBottom),
|
|
241
|
+
};
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
/** Where a row sits in the scrolled content, and where it sits on screen. */
|
|
245
|
+
const topOf = (element: HTMLElement, box: HTMLElement): number =>
|
|
246
|
+
element.getBoundingClientRect().top - box.getBoundingClientRect().top + box.scrollTop;
|
|
247
|
+
const screenTopOf = (element: HTMLElement, box: HTMLElement): number =>
|
|
248
|
+
element.getBoundingClientRect().top - box.getBoundingClientRect().top;
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Where the rows end, which is not where the content does: the spacer below
|
|
252
|
+
* them is room made for an anchored turn, and a short transcript's column is
|
|
253
|
+
* stretched to fill the viewport.
|
|
254
|
+
*/
|
|
255
|
+
const rowsEnd = (parent: HTMLElement, box: HTMLElement): number => {
|
|
256
|
+
const inset = padding(parent);
|
|
257
|
+
const origin = box.getBoundingClientRect().top;
|
|
258
|
+
let bottom = inset.start + inset.end;
|
|
259
|
+
for (const item of itemsOf(parent)) {
|
|
260
|
+
bottom = Math.max(
|
|
261
|
+
bottom,
|
|
262
|
+
item.getBoundingClientRect().bottom - origin + box.scrollTop + inset.end,
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
return bottom;
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
const distance = (element: HTMLElement): number =>
|
|
269
|
+
element.scrollHeight - spacerHeight - element.clientHeight - element.scrollTop;
|
|
270
|
+
|
|
271
|
+
const measure = (): void => {
|
|
272
|
+
if (viewport === null) return;
|
|
273
|
+
const near = tolerance();
|
|
274
|
+
const room = viewport.scrollHeight - spacerHeight - viewport.clientHeight;
|
|
275
|
+
setScrollable(room > near);
|
|
276
|
+
const left = distance(viewport);
|
|
277
|
+
isAtEnd = left <= near;
|
|
278
|
+
setAtEnd(isAtEnd);
|
|
279
|
+
const start = viewport.scrollTop > near;
|
|
280
|
+
const end = left > near;
|
|
281
|
+
if (published.start !== start || published.end !== end) {
|
|
282
|
+
published = { start, end };
|
|
283
|
+
setEdges(published);
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
const resizeSpacer = (height: number): void => {
|
|
288
|
+
if (spacer === null) return;
|
|
289
|
+
const next = Math.max(0, Math.ceil(height));
|
|
290
|
+
if (next === spacerHeight) return;
|
|
291
|
+
spacerHeight = next;
|
|
292
|
+
spacer.hidden = next === 0;
|
|
293
|
+
spacer.style.height = `${String(next)}px`;
|
|
294
|
+
// The column's gap would otherwise sit between the last row and the
|
|
295
|
+
// spacer, and the anchored turn would land that much short.
|
|
296
|
+
const parent = spacer.parentElement;
|
|
297
|
+
const style = parent === null ? null : getComputedStyle(parent);
|
|
298
|
+
const gap = style === null ? 0 : pixels(style.rowGap === "normal" ? style.gap : style.rowGap);
|
|
299
|
+
spacer.style.marginTop = next > 0 && gap > 0 ? `${String(-gap)}px` : "";
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* The flag is for the ANIMATION and an instant jump has none. A smooth
|
|
304
|
+
* scroll passes through positions that are not the target, and each fires a
|
|
305
|
+
* `scroll` event that would otherwise read as the person scrolling away from
|
|
306
|
+
* where this call is taking them. A jump lands and whatever event follows
|
|
307
|
+
* finds it there.
|
|
308
|
+
*/
|
|
309
|
+
const glide = (behavior: ScrollBehavior): void => {
|
|
310
|
+
if (behavior !== "smooth") return;
|
|
311
|
+
isAutoscrolling = true;
|
|
312
|
+
setAutoscrolling(true);
|
|
313
|
+
if (settle !== null) clearTimeout(settle);
|
|
314
|
+
// There is no event for a smooth scroll finishing, so the flag is held
|
|
315
|
+
// long enough to cover it and then dropped.
|
|
316
|
+
settle = setTimeout(() => {
|
|
317
|
+
settle = null;
|
|
318
|
+
isAutoscrolling = false;
|
|
319
|
+
setAutoscrolling(false);
|
|
320
|
+
measure();
|
|
321
|
+
}, SMOOTH);
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
const computeVisibility = (): MessageScrollerVisibilityState => {
|
|
325
|
+
const parent = contentOf();
|
|
326
|
+
if (viewport === null || parent === null) return NOTHING_VISIBLE;
|
|
327
|
+
const box = viewport.getBoundingClientRect();
|
|
328
|
+
// An anchored turn lands a peek below the margin, with the previous one
|
|
329
|
+
// showing above it. A row only showing in that band has not been read down
|
|
330
|
+
// to yet, so it is neither visible nor current.
|
|
331
|
+
const line = box.top + margin() + peek();
|
|
332
|
+
const byLayout = intersections === null;
|
|
333
|
+
const visible: string[] = [];
|
|
334
|
+
let current: string | null = null;
|
|
335
|
+
|
|
336
|
+
for (const item of itemsOf(parent)) {
|
|
337
|
+
const messageId = item.dataset.messageId;
|
|
338
|
+
if (messageId === undefined || messageId === "") continue;
|
|
339
|
+
const anchor = isAnchor(item);
|
|
340
|
+
const rect = anchor || byLayout ? item.getBoundingClientRect() : null;
|
|
341
|
+
const shown =
|
|
342
|
+
byLayout && rect !== null
|
|
343
|
+
? rect.bottom > line && rect.top < box.bottom
|
|
344
|
+
: onScreen.has(messageId);
|
|
345
|
+
if (shown) visible.push(messageId);
|
|
346
|
+
if (anchor && rect !== null && rect.top <= line + EPSILON) current = messageId;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
if (visible.length === 0 && current === null) return NOTHING_VISIBLE;
|
|
350
|
+
return { currentAnchorId: current, visibleMessageIds: visible };
|
|
351
|
+
};
|
|
352
|
+
|
|
353
|
+
const scheduleVisibility = (): void => {
|
|
354
|
+
if (watchers === 0 || visibilityFrame !== null) return;
|
|
355
|
+
visibilityFrame = requestAnimationFrame(() => {
|
|
356
|
+
visibilityFrame = null;
|
|
357
|
+
if (watchers === 0) return;
|
|
358
|
+
const next = computeVisibility();
|
|
359
|
+
const before = seenNow();
|
|
360
|
+
const same =
|
|
361
|
+
before.currentAnchorId === next.currentAnchorId &&
|
|
362
|
+
before.visibleMessageIds.length === next.visibleMessageIds.length &&
|
|
363
|
+
before.visibleMessageIds.every((id, at) => id === next.visibleMessageIds[at]);
|
|
364
|
+
if (!same) setSeenNow(next);
|
|
365
|
+
});
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
/** The row to hold still when older ones arrive above: the first one on screen. */
|
|
369
|
+
const captureReading = (): void => {
|
|
370
|
+
const parent = contentOf();
|
|
371
|
+
if (viewport === null || parent === null || messages.size === 0) {
|
|
372
|
+
reading = null;
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
const box = viewport.getBoundingClientRect();
|
|
376
|
+
for (const item of itemsOf(parent)) {
|
|
377
|
+
const messageId = item.dataset.messageId;
|
|
378
|
+
if (messageId === undefined || messageId === "") continue;
|
|
379
|
+
const rect = item.getBoundingClientRect();
|
|
380
|
+
if (rect.bottom > box.top && rect.top < box.bottom) {
|
|
381
|
+
reading = { element: item, top: rect.top - box.top };
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
reading = null;
|
|
386
|
+
};
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Put the row being read back where it was.
|
|
390
|
+
*
|
|
391
|
+
* Measured against the viewport rather than the content, so it does nothing
|
|
392
|
+
* where the browser's own scroll anchoring already held the row and only
|
|
393
|
+
* corrects where it did not, without asking which engine this is.
|
|
394
|
+
*/
|
|
395
|
+
const restoreReading = (): void => {
|
|
396
|
+
if (viewport === null || reading === null || !reading.element.isConnected) return;
|
|
397
|
+
const moved = screenTopOf(reading.element, viewport) - reading.top;
|
|
398
|
+
if (Math.abs(moved) <= EPSILON) return;
|
|
399
|
+
viewport.scrollTop += moved;
|
|
400
|
+
lastTop = viewport.scrollTop;
|
|
401
|
+
reading.top = screenTopOf(reading.element, viewport);
|
|
402
|
+
measure();
|
|
403
|
+
scheduleVisibility();
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
function toEnd(behavior: ScrollBehavior = "smooth"): boolean {
|
|
407
|
+
if (viewport === null) return false;
|
|
408
|
+
resizeSpacer(0);
|
|
409
|
+
held = null;
|
|
410
|
+
mode = "following";
|
|
411
|
+
glide(behavior);
|
|
412
|
+
viewport.scrollTo({ top: viewport.scrollHeight, behavior });
|
|
413
|
+
lastTop = viewport.scrollTop;
|
|
414
|
+
measure();
|
|
415
|
+
scheduleVisibility();
|
|
416
|
+
return true;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function toStart(behavior: ScrollBehavior = "smooth"): boolean {
|
|
420
|
+
if (viewport === null) return false;
|
|
421
|
+
resizeSpacer(0);
|
|
422
|
+
held = null;
|
|
423
|
+
mode = "free";
|
|
424
|
+
viewport.scrollTo({ top: 0, behavior });
|
|
425
|
+
lastTop = viewport.scrollTop;
|
|
426
|
+
measure();
|
|
427
|
+
scheduleVisibility();
|
|
428
|
+
return true;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const targetFor = (
|
|
432
|
+
element: HTMLElement,
|
|
433
|
+
box: HTMLElement,
|
|
434
|
+
align: MessageScrollerScrollAlign,
|
|
435
|
+
space: number,
|
|
436
|
+
): number => {
|
|
437
|
+
const top = topOf(element, box);
|
|
438
|
+
const height = element.getBoundingClientRect().height;
|
|
439
|
+
const inset = padding(contentOf());
|
|
440
|
+
if (align === "center") {
|
|
441
|
+
const room = Math.max(0, box.clientHeight - inset.start - inset.end);
|
|
442
|
+
return top - inset.start - (room - height) / 2 - space;
|
|
443
|
+
}
|
|
444
|
+
if (align === "end") return top - box.clientHeight + height + inset.end + space;
|
|
445
|
+
if (align === "nearest") {
|
|
446
|
+
const bottom = top + height;
|
|
447
|
+
const first = box.scrollTop + inset.start;
|
|
448
|
+
const last = box.scrollTop + box.clientHeight - inset.end;
|
|
449
|
+
if (top >= first && bottom <= last) return box.scrollTop;
|
|
450
|
+
if (top < first) return top - inset.start - space;
|
|
451
|
+
return bottom - box.clientHeight + inset.end + space;
|
|
452
|
+
}
|
|
453
|
+
return top - inset.start - space;
|
|
454
|
+
};
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Bring a row to an edge, making room below the rows if there is not enough.
|
|
458
|
+
*
|
|
459
|
+
* `hold` is the anchoring case: the row is a new turn, it goes a peek below
|
|
460
|
+
* the top so the end of the previous one stays readable, and it is kept
|
|
461
|
+
* there while its reply grows underneath.
|
|
462
|
+
*/
|
|
463
|
+
const toElement = (
|
|
464
|
+
element: HTMLElement,
|
|
465
|
+
given: MessageScrollerScrollOptions = {},
|
|
466
|
+
hold = false,
|
|
467
|
+
): boolean => {
|
|
468
|
+
const parent = contentOf();
|
|
469
|
+
if (viewport === null || parent === null || !parent.contains(element)) return false;
|
|
470
|
+
const space = (given.scrollMargin ?? margin()) + (hold ? peek() : 0);
|
|
471
|
+
const top = targetFor(element, viewport, given.align ?? "start", space);
|
|
472
|
+
resizeSpacer(top + viewport.clientHeight - rowsEnd(parent, viewport));
|
|
473
|
+
// Seeded with the target, so a prepend that lands before this scroll has
|
|
474
|
+
// settled still holds the row that was jumped to.
|
|
475
|
+
reading = { element, top: screenTopOf(element, viewport) };
|
|
476
|
+
mode = hold ? "anchored" : "jumping";
|
|
477
|
+
held = hold ? element : null;
|
|
478
|
+
const behavior = given.behavior ?? "auto";
|
|
479
|
+
glide(behavior);
|
|
480
|
+
viewport.scrollTo({ top: Math.max(0, top), behavior });
|
|
481
|
+
lastTop = viewport.scrollTop;
|
|
482
|
+
measure();
|
|
483
|
+
scheduleVisibility();
|
|
484
|
+
return true;
|
|
485
|
+
};
|
|
486
|
+
|
|
487
|
+
const applied = (): void => {
|
|
488
|
+
opened = true;
|
|
489
|
+
setPending(false);
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
const flushQueued = (): boolean => {
|
|
493
|
+
if (queued === null) return false;
|
|
494
|
+
const element = messages.get(queued.messageId);
|
|
495
|
+
if (element === undefined || !toElement(element, queued.options)) return false;
|
|
496
|
+
queued = null;
|
|
497
|
+
applied();
|
|
498
|
+
return true;
|
|
499
|
+
};
|
|
500
|
+
|
|
501
|
+
const open = (): boolean => {
|
|
502
|
+
const position = access(options.defaultScrollPosition);
|
|
503
|
+
if (position === undefined || opened || itemCount === 0) return false;
|
|
504
|
+
let handled: boolean;
|
|
505
|
+
const parent = contentOf();
|
|
506
|
+
if (position === "start") {
|
|
507
|
+
handled = toStart("auto");
|
|
508
|
+
} else if (position === "end" || viewport === null || parent === null) {
|
|
509
|
+
handled = toEnd("auto");
|
|
510
|
+
} else {
|
|
511
|
+
const anchors = itemsOf(parent).filter(isAnchor);
|
|
512
|
+
const last = anchors.at(-1);
|
|
513
|
+
// A short last turn already fits below its first row, so opening at the
|
|
514
|
+
// end shows all of it without a blank gap underneath.
|
|
515
|
+
const fits =
|
|
516
|
+
last === undefined ||
|
|
517
|
+
rowsEnd(parent, viewport) - topOf(last, viewport) <= viewport.clientHeight;
|
|
518
|
+
handled = fits || last === undefined ? toEnd("auto") : toElement(last, {}, true);
|
|
519
|
+
}
|
|
520
|
+
if (handled) applied();
|
|
521
|
+
return handled;
|
|
522
|
+
};
|
|
523
|
+
|
|
524
|
+
/** The content grew, shrank or was re-laid out, with the same rows in it. */
|
|
525
|
+
const follow = (): void => {
|
|
526
|
+
measure();
|
|
527
|
+
if (mode === "following" && follows()) {
|
|
528
|
+
toEnd("auto");
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
// Hold the anchored turn as what is below it resizes, or the shrinking
|
|
532
|
+
// content lets the browser clamp the position and the turn drops.
|
|
533
|
+
if (mode === "anchored" && held !== null && held.isConnected) {
|
|
534
|
+
const before = spacerHeight;
|
|
535
|
+
toElement(held, {}, true);
|
|
536
|
+
// The reply has used up the room made for it, so it has filled the
|
|
537
|
+
// viewport and the reader is at the live edge: following takes over.
|
|
538
|
+
if (follows() && before > 0 && spacerHeight === 0) toEnd("auto");
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
scheduleVisibility();
|
|
542
|
+
};
|
|
543
|
+
|
|
544
|
+
/** A row was added, removed or replaced. The order of the cases is load-bearing. */
|
|
545
|
+
const reconcile = (): void => {
|
|
546
|
+
const parent = contentOf();
|
|
547
|
+
if (parent === null) return;
|
|
548
|
+
const items = itemsOf(parent);
|
|
549
|
+
const before = itemCount;
|
|
550
|
+
const wasFirst = firstItem;
|
|
551
|
+
itemCount = items.length;
|
|
552
|
+
firstItem = items[0] ?? null;
|
|
553
|
+
const fresh = items.filter((item) => !known.has(item));
|
|
554
|
+
for (const item of fresh) known.add(item);
|
|
555
|
+
|
|
556
|
+
if (flushQueued()) return;
|
|
557
|
+
|
|
558
|
+
if (before === 0) {
|
|
559
|
+
if (open()) return;
|
|
560
|
+
follow();
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
const shifted = wasFirst === null ? -1 : items.indexOf(wasFirst);
|
|
565
|
+
if (shifted > 0 && access(preserve) !== false) {
|
|
566
|
+
restoreReading();
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
const anchors = fresh.filter(isAnchor);
|
|
571
|
+
const anchor = anchors[0];
|
|
572
|
+
if (anchor !== undefined && items.length >= before) {
|
|
573
|
+
// Several turns arriving at once while the end is being followed keep
|
|
574
|
+
// following it, rather than yanking back to the first of the batch.
|
|
575
|
+
if (anchors.length > 1 && mode === "following" && follows()) {
|
|
576
|
+
toEnd("auto");
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
toElement(anchor, {}, true);
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
follow();
|
|
584
|
+
};
|
|
585
|
+
|
|
586
|
+
const onScroll = (): void => {
|
|
587
|
+
measure();
|
|
588
|
+
if (viewport === null) return;
|
|
589
|
+
const top = viewport.scrollTop;
|
|
590
|
+
// Content growing past the end also reads as "not at the end", but only
|
|
591
|
+
// the person moves the position UP. Growth must not release the follow: a
|
|
592
|
+
// scroll event can arrive after a chunk and before the follow catches up.
|
|
593
|
+
const up = top < lastTop - EPSILON;
|
|
594
|
+
lastTop = top;
|
|
595
|
+
// Only a scroll the PERSON made changes the decision. The one `toEnd`
|
|
596
|
+
// caused fires this too, and reading it as intent is how a scroller
|
|
597
|
+
// decides the user scrolled away from the bottom it just moved them to.
|
|
598
|
+
if (!isAutoscrolling) {
|
|
599
|
+
if (mode === "following" && !isAtEnd && up) mode = "free";
|
|
600
|
+
else if (mode === "free" && isAtEnd) mode = "following";
|
|
601
|
+
}
|
|
602
|
+
scheduleVisibility();
|
|
603
|
+
captureReading();
|
|
604
|
+
};
|
|
605
|
+
|
|
606
|
+
const watch = (): void => {
|
|
607
|
+
if (viewport === null) return;
|
|
608
|
+
observer?.disconnect();
|
|
609
|
+
mutations?.disconnect();
|
|
610
|
+
const parent = contentOf();
|
|
611
|
+
// Both, because the two ways a transcript grows are different events: a
|
|
612
|
+
// message added is a mutation, and an image finishing loading or a
|
|
613
|
+
// window narrowing is a resize.
|
|
614
|
+
if (typeof ResizeObserver !== "undefined") {
|
|
615
|
+
// On the next frame: following resizes the spacer, which is inside the
|
|
616
|
+
// observed content, and resizing an observed element while its
|
|
617
|
+
// notification is being delivered is reported as a loop.
|
|
618
|
+
observer = new ResizeObserver(() => {
|
|
619
|
+
if (resized !== null) cancelAnimationFrame(resized);
|
|
620
|
+
resized = requestAnimationFrame(() => {
|
|
621
|
+
resized = null;
|
|
622
|
+
follow();
|
|
623
|
+
});
|
|
624
|
+
});
|
|
625
|
+
observer.observe(viewport);
|
|
626
|
+
if (parent !== null) observer.observe(parent);
|
|
627
|
+
}
|
|
628
|
+
if (typeof MutationObserver !== "undefined") {
|
|
629
|
+
mutations = new MutationObserver((records) => {
|
|
630
|
+
const rows = contentOf();
|
|
631
|
+
if (records.some((record) => record.type === "childList" && record.target === rows)) {
|
|
632
|
+
reconcile();
|
|
633
|
+
captureReading();
|
|
634
|
+
} else {
|
|
635
|
+
follow();
|
|
636
|
+
}
|
|
637
|
+
});
|
|
638
|
+
mutations.observe(viewport, { childList: true, subtree: true, characterData: true });
|
|
639
|
+
}
|
|
640
|
+
};
|
|
641
|
+
|
|
642
|
+
const unwatchVisibility = (): void => {
|
|
643
|
+
if (visibilityFrame !== null) cancelAnimationFrame(visibilityFrame);
|
|
644
|
+
visibilityFrame = null;
|
|
645
|
+
intersections?.disconnect();
|
|
646
|
+
intersections = null;
|
|
647
|
+
onScreen.clear();
|
|
648
|
+
setSeenNow(NOTHING_VISIBLE);
|
|
649
|
+
};
|
|
650
|
+
|
|
651
|
+
const observeVisibility = (): void => {
|
|
652
|
+
if (viewport === null || watchers === 0) return;
|
|
653
|
+
if (typeof IntersectionObserver !== "undefined" && intersections === null) {
|
|
654
|
+
intersections = new IntersectionObserver(
|
|
655
|
+
(entries) => {
|
|
656
|
+
for (const entry of entries) {
|
|
657
|
+
const messageId =
|
|
658
|
+
entry.target instanceof HTMLElement ? entry.target.dataset.messageId : "";
|
|
659
|
+
if (messageId === undefined || messageId === "") continue;
|
|
660
|
+
if (entry.isIntersecting) onScreen.add(messageId);
|
|
661
|
+
else onScreen.delete(messageId);
|
|
662
|
+
}
|
|
663
|
+
scheduleVisibility();
|
|
664
|
+
},
|
|
665
|
+
{
|
|
666
|
+
root: viewport,
|
|
667
|
+
// The top edge moved down to the reading line, so the previous turn
|
|
668
|
+
// showing in the band above it is not reported as visible while it
|
|
669
|
+
// is not the current one either.
|
|
670
|
+
rootMargin: `${String(-(margin() + peek()))}px 0px 0px 0px`,
|
|
671
|
+
threshold: [0, 0.01, 0.5, 1],
|
|
672
|
+
},
|
|
673
|
+
);
|
|
674
|
+
for (const element of messages.values()) intersections.observe(element);
|
|
675
|
+
}
|
|
676
|
+
scheduleVisibility();
|
|
677
|
+
};
|
|
678
|
+
|
|
679
|
+
return {
|
|
680
|
+
isAtEnd: atEnd,
|
|
681
|
+
isScrollable: scrollable,
|
|
682
|
+
isAutoscrolling: autoscrolling,
|
|
683
|
+
scrollable: edges,
|
|
684
|
+
visibility: seenNow,
|
|
685
|
+
isPending: pending,
|
|
686
|
+
toEnd,
|
|
687
|
+
toStart,
|
|
688
|
+
measure,
|
|
689
|
+
scrollToEnd: (given) => toEnd(given?.behavior ?? "auto"),
|
|
690
|
+
scrollToStart: (given) => toStart(given?.behavior ?? "auto"),
|
|
691
|
+
scrollToMessage(messageId, given) {
|
|
692
|
+
const element = messages.get(messageId);
|
|
693
|
+
if (element === undefined) {
|
|
694
|
+
// Nothing has mounted yet, so the row may still be on its way: an
|
|
695
|
+
// asynchronously loaded transcript asks before it has rows.
|
|
696
|
+
if (itemCount > 0) return false;
|
|
697
|
+
queued = given === undefined ? { messageId } : { messageId, options: given };
|
|
698
|
+
applied();
|
|
699
|
+
return true;
|
|
700
|
+
}
|
|
701
|
+
// An explicit jump is the opening position, so the default does not
|
|
702
|
+
// replace it afterwards.
|
|
703
|
+
applied();
|
|
704
|
+
if (toElement(element, given)) {
|
|
705
|
+
queued = null;
|
|
706
|
+
return true;
|
|
707
|
+
}
|
|
708
|
+
queued = given === undefined ? { messageId } : { messageId, options: given };
|
|
709
|
+
return true;
|
|
710
|
+
},
|
|
711
|
+
intent() {
|
|
712
|
+
// A deliberate gesture lets go of a held turn and of a jump, so neither
|
|
713
|
+
// is put back while the person is reading somewhere else.
|
|
714
|
+
if (mode !== "anchored" && mode !== "jumping") return;
|
|
715
|
+
held = null;
|
|
716
|
+
mode = isAtEnd ? "following" : "free";
|
|
717
|
+
},
|
|
718
|
+
preserveOnPrepend(next) {
|
|
719
|
+
preserve = next;
|
|
720
|
+
},
|
|
721
|
+
register(messageId, element, removed) {
|
|
722
|
+
if (element !== null) {
|
|
723
|
+
messages.set(messageId, element);
|
|
724
|
+
intersections?.observe(element);
|
|
725
|
+
scheduleVisibility();
|
|
726
|
+
if (queued?.messageId === messageId && flushQueued()) captureReading();
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
if (removed !== null && removed !== undefined && messages.get(messageId) === removed) {
|
|
730
|
+
messages.delete(messageId);
|
|
731
|
+
onScreen.delete(messageId);
|
|
732
|
+
intersections?.unobserve(removed);
|
|
733
|
+
scheduleVisibility();
|
|
734
|
+
}
|
|
735
|
+
},
|
|
736
|
+
watchVisibility() {
|
|
737
|
+
watchers++;
|
|
738
|
+
if (watchers === 1) observeVisibility();
|
|
739
|
+
let stopped = false;
|
|
740
|
+
return () => {
|
|
741
|
+
if (stopped) return;
|
|
742
|
+
stopped = true;
|
|
743
|
+
watchers--;
|
|
744
|
+
if (watchers === 0) unwatchVisibility();
|
|
745
|
+
};
|
|
746
|
+
},
|
|
747
|
+
attachContent(element) {
|
|
748
|
+
content = element;
|
|
749
|
+
if (viewport !== null) watch();
|
|
750
|
+
},
|
|
751
|
+
attachSpacer(element) {
|
|
752
|
+
spacer = element;
|
|
753
|
+
spacerHeight = 0;
|
|
754
|
+
},
|
|
755
|
+
attach(element) {
|
|
756
|
+
observer?.disconnect();
|
|
757
|
+
mutations?.disconnect();
|
|
758
|
+
viewport?.removeEventListener("scroll", onScroll);
|
|
759
|
+
if (resized !== null) cancelAnimationFrame(resized);
|
|
760
|
+
resized = null;
|
|
761
|
+
observer = null;
|
|
762
|
+
mutations = null;
|
|
763
|
+
viewport = element;
|
|
764
|
+
if (element === null) {
|
|
765
|
+
unwatchVisibility();
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
element.addEventListener("scroll", onScroll, { passive: true });
|
|
770
|
+
watch();
|
|
771
|
+
lastTop = element.scrollTop;
|
|
772
|
+
|
|
773
|
+
const parent = contentOf();
|
|
774
|
+
const items = parent === null ? [] : itemsOf(parent);
|
|
775
|
+
itemCount = items.length;
|
|
776
|
+
firstItem = items[0] ?? null;
|
|
777
|
+
known = new WeakSet(items);
|
|
778
|
+
measure();
|
|
779
|
+
// An empty transcript has nowhere to open at, so there is nothing for
|
|
780
|
+
// the first paint to wait for.
|
|
781
|
+
if (!open() && itemCount === 0) setPending(false);
|
|
782
|
+
captureReading();
|
|
783
|
+
observeVisibility();
|
|
784
|
+
},
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// ---------------------------------------------------------------------------
|
|
789
|
+
// Scrollbars
|
|
790
|
+
// ---------------------------------------------------------------------------
|
|
791
|
+
|
|
792
|
+
/**
|
|
793
|
+
* A scrollbar drawn by the page, over a viewport that still scrolls natively.
|
|
794
|
+
*
|
|
795
|
+
* The native scroller keeps doing all the scrolling: wheel, trackpad, touch and
|
|
796
|
+
* keyboard never come through here. What this owns is the part a hidden native
|
|
797
|
+
* scrollbar takes away with it, which is the thumb: how long it is, where it
|
|
798
|
+
* sits, dragging it, and pressing the track to jump.
|
|
799
|
+
*
|
|
800
|
+
* **The thumb follows the viewport, never the other way round.** A drag writes
|
|
801
|
+
* a scroll position and the thumb is then measured from where the viewport
|
|
802
|
+
* ended up, so the two cannot disagree and a position the browser clamped is
|
|
803
|
+
* the one that is drawn.
|
|
804
|
+
*
|
|
805
|
+
* **A press on the track is the start of a drag.** It brings the middle of the
|
|
806
|
+
* thumb to the pointer and keeps following it, which is what every platform's
|
|
807
|
+
* own scrollbar does; a press on the thumb keeps hold of the point it grabbed.
|
|
808
|
+
*
|
|
809
|
+
* **When it shows is a policy with four answers**, which are Radix's: `hover`
|
|
810
|
+
* while the pointer is over the area, `scroll` while the content is moving,
|
|
811
|
+
* `auto` whenever there is overflow, `always` regardless.
|
|
812
|
+
*/
|
|
813
|
+
|
|
814
|
+
export type ScrollbarOrientation = "vertical" | "horizontal";
|
|
815
|
+
export type ScrollbarType = "auto" | "always" | "scroll" | "hover";
|
|
816
|
+
|
|
817
|
+
/** The lengths a thumb is worked out from, along the scrollbar's own axis. */
|
|
818
|
+
export interface ScrollbarSizes {
|
|
819
|
+
/** The whole scrollable content. */
|
|
820
|
+
readonly content: number;
|
|
821
|
+
/** The part of it on screen. */
|
|
822
|
+
readonly viewport: number;
|
|
823
|
+
readonly track: number;
|
|
824
|
+
readonly paddingStart: number;
|
|
825
|
+
readonly paddingEnd: number;
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/** Shorter than this and a thumb cannot be taken hold of. */
|
|
829
|
+
const MIN_THUMB = 18;
|
|
830
|
+
/** How long without a scroll event counts as the scrolling having stopped. */
|
|
831
|
+
const SCROLL_END = 100;
|
|
832
|
+
const HIDE_DELAY = 600;
|
|
833
|
+
|
|
834
|
+
const scale = (
|
|
835
|
+
value: number,
|
|
836
|
+
from: readonly [number, number],
|
|
837
|
+
to: readonly [number, number],
|
|
838
|
+
): number => {
|
|
839
|
+
if (from[0] === from[1] || to[0] === to[1]) return to[0];
|
|
840
|
+
const clamped = Math.min(Math.max(value, from[0]), from[1]);
|
|
841
|
+
return to[0] + ((to[1] - to[0]) / (from[1] - from[0])) * (clamped - from[0]);
|
|
842
|
+
};
|
|
843
|
+
|
|
844
|
+
const scrollRange = (
|
|
845
|
+
sizes: ScrollbarSizes,
|
|
846
|
+
direction: "ltr" | "rtl",
|
|
847
|
+
): readonly [number, number] => {
|
|
848
|
+
const most = Math.max(0, sizes.content - sizes.viewport);
|
|
849
|
+
// Right to left the position starts at zero and counts DOWN, which is what
|
|
850
|
+
// every engine has reported since they agreed on it.
|
|
851
|
+
return direction === "ltr" ? [0, most] : [-most, 0];
|
|
852
|
+
};
|
|
853
|
+
|
|
854
|
+
/** How long the thumb is, in px. */
|
|
855
|
+
export function thumbSize(sizes: ScrollbarSizes, minimum: number = MIN_THUMB): number {
|
|
856
|
+
const ratio = sizes.content > 0 ? Math.min(1, sizes.viewport / sizes.content) : 1;
|
|
857
|
+
const room = sizes.track - sizes.paddingStart - sizes.paddingEnd;
|
|
858
|
+
return Math.max(room * ratio, minimum);
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
/** How far along the track the thumb sits, in px from the track's padding. */
|
|
862
|
+
export function thumbOffset(
|
|
863
|
+
position: number,
|
|
864
|
+
sizes: ScrollbarSizes,
|
|
865
|
+
direction: "ltr" | "rtl" = "ltr",
|
|
866
|
+
minimum: number = MIN_THUMB,
|
|
867
|
+
): number {
|
|
868
|
+
const room = sizes.track - sizes.paddingStart - sizes.paddingEnd;
|
|
869
|
+
const travel = Math.max(0, room - thumbSize(sizes, minimum));
|
|
870
|
+
return scale(position, scrollRange(sizes, direction), [0, travel]);
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
/**
|
|
874
|
+
* The scroll position that puts the thumb under a pointer.
|
|
875
|
+
*
|
|
876
|
+
* `grab` is how far into the thumb the pointer holds it, so a drag keeps the
|
|
877
|
+
* point that was pressed rather than snapping the thumb's edge to the pointer.
|
|
878
|
+
*/
|
|
879
|
+
export function scrollPositionAt(
|
|
880
|
+
pointer: number,
|
|
881
|
+
grab: number,
|
|
882
|
+
sizes: ScrollbarSizes,
|
|
883
|
+
direction: "ltr" | "rtl" = "ltr",
|
|
884
|
+
minimum: number = MIN_THUMB,
|
|
885
|
+
): number {
|
|
886
|
+
const thumb = thumbSize(sizes, minimum);
|
|
887
|
+
const first = sizes.paddingStart + grab;
|
|
888
|
+
const last = sizes.track - sizes.paddingEnd - (thumb - grab);
|
|
889
|
+
const range = scrollRange(sizes, direction);
|
|
890
|
+
if (last <= first) return direction === "ltr" ? range[0] : range[1];
|
|
891
|
+
return scale(pointer, [first, last], range);
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
export interface ScrollbarOptions {
|
|
895
|
+
/** @default "vertical" */
|
|
896
|
+
orientation?: MaybeAccessor<ScrollbarOrientation | undefined>;
|
|
897
|
+
/** Which way a horizontal bar runs. @default "ltr" */
|
|
898
|
+
direction?: MaybeAccessor<"ltr" | "rtl" | undefined>;
|
|
899
|
+
/** When the bar shows. @default "hover" */
|
|
900
|
+
type?: MaybeAccessor<ScrollbarType | undefined>;
|
|
901
|
+
/** How long it stays after the pointer leaves or the scrolling stops, in ms. @default 600 */
|
|
902
|
+
hideDelay?: MaybeAccessor<number | undefined>;
|
|
903
|
+
/** The shortest the thumb gets, in px. @default 18 */
|
|
904
|
+
minThumbSize?: MaybeAccessor<number | undefined>;
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
export interface ScrollbarTrackProps {
|
|
908
|
+
readonly onPointerDown: (event: PointerEvent) => void;
|
|
909
|
+
readonly onPointerMove: (event: PointerEvent) => void;
|
|
910
|
+
readonly onPointerUp: (event: PointerEvent) => void;
|
|
911
|
+
readonly onPointerCancel: (event: PointerEvent) => void;
|
|
912
|
+
readonly onPointerEnter: (event: PointerEvent) => void;
|
|
913
|
+
readonly onPointerLeave: (event: PointerEvent) => void;
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
export interface Scrollbar {
|
|
917
|
+
/** Whether the content is longer than the viewport on this axis. */
|
|
918
|
+
readonly hasOverflow: Accessor<boolean>;
|
|
919
|
+
/** Whether the policy in `type` has it showing right now. */
|
|
920
|
+
readonly isVisible: Accessor<boolean>;
|
|
921
|
+
readonly isDragging: Accessor<boolean>;
|
|
922
|
+
/** The thumb's length, in px. */
|
|
923
|
+
readonly thumbSize: Accessor<number>;
|
|
924
|
+
/** The thumb's distance along the track, in px. */
|
|
925
|
+
readonly thumbOffset: Accessor<number>;
|
|
926
|
+
/** How far through the content the viewport is, from 0 to 100. */
|
|
927
|
+
readonly value: Accessor<number>;
|
|
928
|
+
/** The scroller and the track to draw for, or `null` for both to stop. */
|
|
929
|
+
readonly attach: (viewport: HTMLElement | null, track: HTMLElement | null) => void;
|
|
930
|
+
readonly measure: () => void;
|
|
931
|
+
/** The pointer came over the scroll area, or left it. */
|
|
932
|
+
readonly hoverStart: () => void;
|
|
933
|
+
readonly hoverEnd: () => void;
|
|
934
|
+
readonly trackProps: ScrollbarTrackProps;
|
|
935
|
+
readonly thumbProps: { readonly onPointerDown: (event: PointerEvent) => void };
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
export function scrollbar(options: ScrollbarOptions = {}): Scrollbar {
|
|
939
|
+
// `ownedWrite`: `attach` measures, and it is called from the component that
|
|
940
|
+
// renders the bar while that component is still settling.
|
|
941
|
+
const own = { ownedWrite: true } as const;
|
|
942
|
+
const [overflow, setOverflow] = createSignal(false, own);
|
|
943
|
+
const [size, setSize] = createSignal(0, own);
|
|
944
|
+
const [offset, setOffset] = createSignal(0, own);
|
|
945
|
+
const [value, setValue] = createSignal(0, own);
|
|
946
|
+
const [dragging, setDragging] = createSignal(false);
|
|
947
|
+
const [hovered, setHovered] = createSignal(false);
|
|
948
|
+
const [scrolling, setScrolling] = createSignal(false);
|
|
949
|
+
const [over, setOver] = createSignal(false);
|
|
950
|
+
|
|
951
|
+
let viewport: HTMLElement | null = null;
|
|
952
|
+
let track: HTMLElement | null = null;
|
|
953
|
+
let observer: ResizeObserver | null = null;
|
|
954
|
+
let mutations: MutationObserver | null = null;
|
|
955
|
+
let isDragging = false;
|
|
956
|
+
let isOver = false;
|
|
957
|
+
/** How far into the thumb the pointer took hold, or 0 for a press on the track. */
|
|
958
|
+
let grab = 0;
|
|
959
|
+
let trackStart = 0;
|
|
960
|
+
let hoverTimer: ReturnType<typeof setTimeout> | null = null;
|
|
961
|
+
let scrollTimer: ReturnType<typeof setTimeout> | null = null;
|
|
962
|
+
let restore: (() => void) | null = null;
|
|
963
|
+
|
|
964
|
+
const vertical = (): boolean => (access(options.orientation) ?? "vertical") === "vertical";
|
|
965
|
+
const direction = (): "ltr" | "rtl" =>
|
|
966
|
+
vertical() ? "ltr" : (access(options.direction) ?? "ltr");
|
|
967
|
+
const minimum = (): number => access(options.minThumbSize) ?? MIN_THUMB;
|
|
968
|
+
const hideDelay = (): number => access(options.hideDelay) ?? HIDE_DELAY;
|
|
969
|
+
|
|
970
|
+
const sizes = (): ScrollbarSizes | null => {
|
|
971
|
+
if (viewport === null || track === null) return null;
|
|
972
|
+
const style = getComputedStyle(track);
|
|
973
|
+
return vertical()
|
|
974
|
+
? {
|
|
975
|
+
content: viewport.scrollHeight,
|
|
976
|
+
viewport: viewport.offsetHeight,
|
|
977
|
+
track: track.clientHeight,
|
|
978
|
+
paddingStart: pixels(style.paddingTop),
|
|
979
|
+
paddingEnd: pixels(style.paddingBottom),
|
|
980
|
+
}
|
|
981
|
+
: {
|
|
982
|
+
content: viewport.scrollWidth,
|
|
983
|
+
viewport: viewport.offsetWidth,
|
|
984
|
+
track: track.clientWidth,
|
|
985
|
+
paddingStart: pixels(style.paddingLeft),
|
|
986
|
+
paddingEnd: pixels(style.paddingRight),
|
|
987
|
+
};
|
|
988
|
+
};
|
|
989
|
+
|
|
990
|
+
const position = (): number => {
|
|
991
|
+
if (viewport === null) return 0;
|
|
992
|
+
return vertical() ? viewport.scrollTop : viewport.scrollLeft;
|
|
993
|
+
};
|
|
994
|
+
|
|
995
|
+
const measure = (): void => {
|
|
996
|
+
const measured = sizes();
|
|
997
|
+
if (measured === null) return;
|
|
998
|
+
const most = measured.content - measured.viewport;
|
|
999
|
+
setOverflow(most > 0);
|
|
1000
|
+
setSize(thumbSize(measured, minimum()));
|
|
1001
|
+
setOffset(thumbOffset(position(), measured, direction(), minimum()));
|
|
1002
|
+
setValue(most > 0 ? Math.round((Math.min(Math.abs(position()), most) / most) * 100) : 0);
|
|
1003
|
+
};
|
|
1004
|
+
|
|
1005
|
+
const clear = (timer: ReturnType<typeof setTimeout> | null): null => {
|
|
1006
|
+
if (timer !== null) clearTimeout(timer);
|
|
1007
|
+
return null;
|
|
1008
|
+
};
|
|
1009
|
+
|
|
1010
|
+
/** Still for long enough, and then gone unless something is holding it. */
|
|
1011
|
+
const settle = (): void => {
|
|
1012
|
+
scrollTimer = clear(scrollTimer);
|
|
1013
|
+
scrollTimer = setTimeout(() => {
|
|
1014
|
+
scrollTimer = setTimeout(() => {
|
|
1015
|
+
scrollTimer = null;
|
|
1016
|
+
if (!isDragging && !isOver) setScrolling(false);
|
|
1017
|
+
}, hideDelay());
|
|
1018
|
+
}, SCROLL_END);
|
|
1019
|
+
};
|
|
1020
|
+
|
|
1021
|
+
const onScroll = (): void => {
|
|
1022
|
+
measure();
|
|
1023
|
+
setScrolling(true);
|
|
1024
|
+
settle();
|
|
1025
|
+
};
|
|
1026
|
+
|
|
1027
|
+
const watch = (): void => {
|
|
1028
|
+
if (observer === null || viewport === null) return;
|
|
1029
|
+
observer.disconnect();
|
|
1030
|
+
observer.observe(viewport);
|
|
1031
|
+
for (const child of viewport.children) {
|
|
1032
|
+
if (child !== track) observer.observe(child);
|
|
1033
|
+
}
|
|
1034
|
+
};
|
|
1035
|
+
|
|
1036
|
+
const moveTo = (event: PointerEvent): void => {
|
|
1037
|
+
const measured = sizes();
|
|
1038
|
+
if (measured === null || viewport === null) return;
|
|
1039
|
+
const pointer = (vertical() ? event.clientY : event.clientX) - trackStart;
|
|
1040
|
+
const held = grab > 0 ? grab : thumbSize(measured, minimum()) / 2;
|
|
1041
|
+
const next = scrollPositionAt(pointer, held, measured, direction(), minimum());
|
|
1042
|
+
if (vertical()) viewport.scrollTop = next;
|
|
1043
|
+
else viewport.scrollLeft = next;
|
|
1044
|
+
measure();
|
|
1045
|
+
};
|
|
1046
|
+
|
|
1047
|
+
const release = (event: PointerEvent): void => {
|
|
1048
|
+
if (!isDragging) return;
|
|
1049
|
+
isDragging = false;
|
|
1050
|
+
grab = 0;
|
|
1051
|
+
setDragging(false);
|
|
1052
|
+
if (track?.hasPointerCapture?.(event.pointerId) === true) {
|
|
1053
|
+
track.releasePointerCapture(event.pointerId);
|
|
1054
|
+
}
|
|
1055
|
+
restore?.();
|
|
1056
|
+
restore = null;
|
|
1057
|
+
settle();
|
|
1058
|
+
};
|
|
1059
|
+
|
|
1060
|
+
return {
|
|
1061
|
+
hasOverflow: overflow,
|
|
1062
|
+
isDragging: dragging,
|
|
1063
|
+
thumbSize: size,
|
|
1064
|
+
thumbOffset: offset,
|
|
1065
|
+
value,
|
|
1066
|
+
measure,
|
|
1067
|
+
isVisible: () => {
|
|
1068
|
+
const type = access(options.type) ?? "hover";
|
|
1069
|
+
if (type === "always") return true;
|
|
1070
|
+
if (!overflow()) return false;
|
|
1071
|
+
if (type === "auto") return true;
|
|
1072
|
+
if (type === "hover") return hovered() || dragging();
|
|
1073
|
+
return scrolling() || dragging() || over();
|
|
1074
|
+
},
|
|
1075
|
+
hoverStart() {
|
|
1076
|
+
hoverTimer = clear(hoverTimer);
|
|
1077
|
+
setHovered(true);
|
|
1078
|
+
},
|
|
1079
|
+
hoverEnd() {
|
|
1080
|
+
hoverTimer = clear(hoverTimer);
|
|
1081
|
+
hoverTimer = setTimeout(() => {
|
|
1082
|
+
hoverTimer = null;
|
|
1083
|
+
setHovered(false);
|
|
1084
|
+
}, hideDelay());
|
|
1085
|
+
},
|
|
1086
|
+
attach(element, rail) {
|
|
1087
|
+
observer?.disconnect();
|
|
1088
|
+
mutations?.disconnect();
|
|
1089
|
+
viewport?.removeEventListener("scroll", onScroll);
|
|
1090
|
+
observer = null;
|
|
1091
|
+
mutations = null;
|
|
1092
|
+
hoverTimer = clear(hoverTimer);
|
|
1093
|
+
scrollTimer = clear(scrollTimer);
|
|
1094
|
+
restore?.();
|
|
1095
|
+
restore = null;
|
|
1096
|
+
isDragging = false;
|
|
1097
|
+
viewport = element;
|
|
1098
|
+
track = rail;
|
|
1099
|
+
if (element === null || rail === null) return;
|
|
1100
|
+
|
|
1101
|
+
element.addEventListener("scroll", onScroll, { passive: true });
|
|
1102
|
+
// The content is whatever the viewport holds, so each child is watched
|
|
1103
|
+
// for its size and the list of them for who comes and goes.
|
|
1104
|
+
if (typeof ResizeObserver !== "undefined") {
|
|
1105
|
+
observer = new ResizeObserver(measure);
|
|
1106
|
+
watch();
|
|
1107
|
+
}
|
|
1108
|
+
if (typeof MutationObserver !== "undefined") {
|
|
1109
|
+
mutations = new MutationObserver(() => {
|
|
1110
|
+
watch();
|
|
1111
|
+
measure();
|
|
1112
|
+
});
|
|
1113
|
+
mutations.observe(element, { childList: true });
|
|
1114
|
+
}
|
|
1115
|
+
measure();
|
|
1116
|
+
},
|
|
1117
|
+
trackProps: {
|
|
1118
|
+
onPointerDown(event) {
|
|
1119
|
+
if (event.button !== 0 || viewport === null || track === null) return;
|
|
1120
|
+
track.setPointerCapture?.(event.pointerId);
|
|
1121
|
+
trackStart = vertical()
|
|
1122
|
+
? track.getBoundingClientRect().top
|
|
1123
|
+
: track.getBoundingClientRect().left;
|
|
1124
|
+
// A drag across text would select it, and a viewport with smooth
|
|
1125
|
+
// scrolling would chase the pointer instead of following it.
|
|
1126
|
+
const body = track.ownerDocument.body;
|
|
1127
|
+
const select = body.style.webkitUserSelect;
|
|
1128
|
+
const behavior = viewport.style.scrollBehavior;
|
|
1129
|
+
const scroller = viewport;
|
|
1130
|
+
body.style.webkitUserSelect = "none";
|
|
1131
|
+
scroller.style.scrollBehavior = "auto";
|
|
1132
|
+
restore = (): void => {
|
|
1133
|
+
body.style.webkitUserSelect = select;
|
|
1134
|
+
scroller.style.scrollBehavior = behavior;
|
|
1135
|
+
};
|
|
1136
|
+
isDragging = true;
|
|
1137
|
+
setDragging(true);
|
|
1138
|
+
event.preventDefault();
|
|
1139
|
+
moveTo(event);
|
|
1140
|
+
},
|
|
1141
|
+
onPointerMove(event) {
|
|
1142
|
+
if (isDragging) moveTo(event);
|
|
1143
|
+
},
|
|
1144
|
+
onPointerUp: release,
|
|
1145
|
+
onPointerCancel: release,
|
|
1146
|
+
onPointerEnter() {
|
|
1147
|
+
isOver = true;
|
|
1148
|
+
setOver(true);
|
|
1149
|
+
},
|
|
1150
|
+
onPointerLeave() {
|
|
1151
|
+
isOver = false;
|
|
1152
|
+
setOver(false);
|
|
1153
|
+
settle();
|
|
1154
|
+
},
|
|
1155
|
+
},
|
|
1156
|
+
thumbProps: {
|
|
1157
|
+
onPointerDown(event) {
|
|
1158
|
+
const thumb = event.currentTarget ?? event.target;
|
|
1159
|
+
if (!(thumb instanceof Element)) return;
|
|
1160
|
+
const rect = thumb.getBoundingClientRect();
|
|
1161
|
+
grab = vertical() ? event.clientY - rect.top : event.clientX - rect.left;
|
|
1162
|
+
},
|
|
1163
|
+
},
|
|
1164
|
+
};
|
|
1165
|
+
}
|