@majapisoftwares/ui 6.7.0 → 6.8.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.
@@ -0,0 +1,240 @@
1
+ import * as React from "react"
2
+
3
+ import type { UseRenderComponentProps } from "./use-render"
4
+
5
+ // Default scrollEdgeThreshold. Sub-pixel tolerance so edge detection does not
6
+ // flicker across engines that round scrollTop differently.
7
+ const DEFAULT_SCROLL_EDGE_THRESHOLD = 8
8
+
9
+ // Default scrollPreviousItemPeek. Pixels of the previous item kept visible above
10
+ // a newly anchored row.
11
+ const DEFAULT_SCROLL_PREVIOUS_ITEM_PEEK = 64
12
+
13
+ // Default scrollMargin for scrollToMessage and programmatic targets.
14
+ const DEFAULT_SCROLL_MARGIN = 0
15
+
16
+ // Two fractional scrollTop values within this range are treated as equal, to
17
+ // absorb zoom and HiDPI rounding drift.
18
+ const SCROLL_POSITION_EPSILON = 0.5
19
+
20
+ // How long (ms) data-autoscrolling stays set during a programmatic smooth scroll
21
+ // before clearing.
22
+ const AUTOSCROLLING_CLEAR_DELAY = 180
23
+
24
+ // Viewport keys that count as deliberate scroll intent and release follow-bottom.
25
+ const USER_SCROLL_KEYS = new Set([
26
+ "ArrowDown",
27
+ "ArrowUp",
28
+ "End",
29
+ "Home",
30
+ "PageDown",
31
+ "PageUp",
32
+ " ", // Space key.
33
+ ])
34
+
35
+ // Internal scroll mode. Derived from intent and commands; decides how the
36
+ // viewport reacts to content and resize.
37
+ type MessageScrollerMode =
38
+ | "following-bottom" // autoScroll on, pinned to the latest message.
39
+ | "free-scrolling" // reader scrolled away; position left alone (prepends still preserved).
40
+ | "anchored-to-message" // holding a turn at the reading line while it streams.
41
+ | "settling-jump" // a programmatic jump is animating; intent detection suppressed until it settles.
42
+
43
+ // Where a saved transcript opens on the first non-empty render.
44
+ type MessageScrollerDefaultScrollPosition = "start" | "end" | "last-anchor"
45
+
46
+ // Which transcript edge MessageScrollerButton scrolls toward.
47
+ type MessageScrollerButtonDirection = "start" | "end"
48
+
49
+ // Viewport alignment for scrollToMessage and programmatic jumps.
50
+ type MessageScrollerScrollAlign = "start" | "center" | "end" | "nearest"
51
+
52
+ // Options for scrollToMessage, scrollToEnd, and scrollToStart.
53
+ type MessageScrollerScrollOptions = {
54
+ // Viewport edge or center to align the target to.
55
+ align?: MessageScrollerScrollAlign
56
+ // Native scroll behavior.
57
+ behavior?: ScrollBehavior
58
+ // Margin on the aligned edge, in pixels. Defaults to the provider scrollMargin.
59
+ scrollMargin?: number
60
+ }
61
+
62
+ // Scroll snapshot from useMessageScrollerScrollable: which edges the viewport can
63
+ // still scroll toward.
64
+ type MessageScrollerScrollable = {
65
+ // The viewport can scroll toward the start (content is hidden above).
66
+ start: boolean
67
+ // The viewport can scroll toward the end (content is hidden below).
68
+ end: boolean
69
+ }
70
+
71
+ // Visibility snapshot from useMessageScrollerVisibility.
72
+ type MessageScrollerVisibilityState = {
73
+ // The anchored turn the reader is in, or null. Stays set after the anchor
74
+ // scrolls above the viewport.
75
+ currentAnchorId: string | null
76
+ // messageId values intersecting the viewport, in document order.
77
+ visibleMessageIds: string[]
78
+ }
79
+
80
+ // Headless provider for a chat transcript scroller. Owns scroll behavior and
81
+ // state; renders no DOM.
82
+ type MessageScrollerProviderProps = {
83
+ children?: React.ReactNode
84
+ // Follow new content at the bottom while the viewport is already at the end.
85
+ autoScroll?: boolean
86
+ // Opening position on the first non-empty render, applied once.
87
+ defaultScrollPosition?: MessageScrollerDefaultScrollPosition
88
+ // Distance from an edge that still counts as at-top/at-bottom. Defaults to 8.
89
+ scrollEdgeThreshold?: number
90
+ // Extra top margin for a newly anchored row, added to scrollMargin. Defaults to 64.
91
+ scrollPreviousItemPeek?: number
92
+ // Default margin on the aligned edge for commands and visibility. Defaults to 0.
93
+ scrollMargin?: number
94
+ }
95
+
96
+ // Frame container for a chat transcript scroller. Must render inside a
97
+ // MessageScrollerProvider.
98
+ type MessageScrollerProps = React.ComponentProps<"div">
99
+
100
+ // Scrollable viewport. Owns native scroll events and prepend preservation.
101
+ type MessageScrollerViewportProps = React.ComponentProps<"div"> & {
102
+ // Keep the first visible messageId row stable on prepend. Defaults to true.
103
+ preserveScrollOnPrepend?: boolean
104
+ }
105
+
106
+ // Transcript row container. Every direct child should be a MessageScrollerItem.
107
+ type MessageScrollerContentProps = React.ComponentProps<"div"> & {
108
+ // Class name for the internal tail spacer used when anchoring turns near the top.
109
+ spacerClassName?: string
110
+ }
111
+
112
+ // One transcript row: a message, marker, typing row, separator, or load-more row.
113
+ type MessageScrollerItemProps = React.ComponentProps<"div"> & {
114
+ // Stable row id for scrollToMessage, visibility, and prepend preservation.
115
+ messageId?: string
116
+ // Marks a turn boundary that newly appended anchors and last-anchor restore use.
117
+ scrollAnchor?: boolean
118
+ }
119
+
120
+ // State passed to MessageScrollerButton's render prop.
121
+ type MessageScrollerButtonRenderState = {
122
+ // Whether overflow exists toward this button's direction.
123
+ active: boolean
124
+ direction: MessageScrollerButtonDirection
125
+ }
126
+
127
+ // Scroll control for the start or end of the transcript.
128
+ type MessageScrollerButtonProps = UseRenderComponentProps<
129
+ "button",
130
+ MessageScrollerButtonRenderState
131
+ > & {
132
+ // Native scroll behavior when clicked. Defaults to "smooth".
133
+ behavior?: ScrollBehavior
134
+ // Transcript edge to scroll toward. Defaults to "end".
135
+ direction?: MessageScrollerButtonDirection
136
+ }
137
+
138
+ // Minimal external store backing useMessageScrollerScrollable, consumed via
139
+ // useSyncExternalStore.
140
+ type MessageScrollerStore<T> = {
141
+ getSnapshot: () => T
142
+ setSnapshot: (nextSnapshot: T) => void
143
+ subscribe: (listener: () => void) => () => void
144
+ }
145
+
146
+ // External store backing useMessageScrollerVisibility. Adds reference-counting so
147
+ // tracking stays lazy.
148
+ type MessageScrollerVisibilityStore = {
149
+ getSnapshot: () => MessageScrollerVisibilityState
150
+ hasListeners: () => boolean
151
+ setSnapshot: (nextSnapshot: MessageScrollerVisibilityState) => void
152
+ subscribe: (
153
+ listener: () => void,
154
+ onFirstSubscribe: () => void,
155
+ onLastUnsubscribe: () => void
156
+ ) => () => void
157
+ }
158
+
159
+ // Registers (or, with removedElement, unregisters) a MessageScrollerItem node by
160
+ // messageId.
161
+ type MessageScrollerRegisterMessage = (
162
+ messageId: string,
163
+ element: HTMLElement | null,
164
+ removedElement?: HTMLElement | null
165
+ ) => void
166
+
167
+ // Internal context wiring the parts together. Not part of the public API.
168
+ type MessageScrollerContextValue = {
169
+ handleContentChange: () => void
170
+ handleResize: () => void
171
+ observeVisibility: () => void
172
+ preserveScrollOnPrependRef: React.RefObject<boolean>
173
+ scrollToEnd: (options?: MessageScrollerScrollOptions) => boolean
174
+ scrollToMessage: (
175
+ messageId: string,
176
+ options?: MessageScrollerScrollOptions
177
+ ) => boolean
178
+ scrollToStart: (options?: MessageScrollerScrollOptions) => boolean
179
+ setContentElement: (element: HTMLDivElement | null) => void
180
+ setRootElement: (element: HTMLDivElement | null) => void
181
+ setSpacerElement: (element: HTMLDivElement | null) => void
182
+ setViewportElement: (element: HTMLDivElement | null) => void
183
+ pendingDefaultScrollStore: MessageScrollerStore<boolean>
184
+ stateStore: MessageScrollerStore<MessageScrollerScrollable>
185
+ syncAfterScroll: () => void
186
+ unobserveVisibility: () => void
187
+ userScrollIntent: () => void
188
+ viewportRef: React.RefObject<HTMLDivElement | null>
189
+ visibilityStore: MessageScrollerVisibilityStore
190
+ }
191
+
192
+ // Initial MessageScrollerScrollable before measurement. Stable reference for the
193
+ // server and first-render snapshot.
194
+ const EMPTY_MESSAGE_SCROLLER_SCROLLABLE: MessageScrollerScrollable = {
195
+ start: false,
196
+ end: false,
197
+ }
198
+
199
+ // Shared empty array so empty visibility snapshots stay referentially stable.
200
+ const EMPTY_VISIBLE_MESSAGE_IDS: string[] = []
201
+
202
+ // Initial MessageScrollerVisibilityState. Nothing tracked, no current anchor.
203
+ const EMPTY_MESSAGE_SCROLLER_VISIBILITY_STATE: MessageScrollerVisibilityState =
204
+ {
205
+ currentAnchorId: null,
206
+ visibleMessageIds: EMPTY_VISIBLE_MESSAGE_IDS,
207
+ }
208
+
209
+ export {
210
+ AUTOSCROLLING_CLEAR_DELAY,
211
+ DEFAULT_SCROLL_EDGE_THRESHOLD,
212
+ DEFAULT_SCROLL_MARGIN,
213
+ DEFAULT_SCROLL_PREVIOUS_ITEM_PEEK,
214
+ EMPTY_MESSAGE_SCROLLER_SCROLLABLE,
215
+ EMPTY_MESSAGE_SCROLLER_VISIBILITY_STATE,
216
+ EMPTY_VISIBLE_MESSAGE_IDS,
217
+ SCROLL_POSITION_EPSILON,
218
+ USER_SCROLL_KEYS,
219
+ }
220
+
221
+ export type {
222
+ MessageScrollerButtonDirection,
223
+ MessageScrollerButtonProps,
224
+ MessageScrollerButtonRenderState,
225
+ MessageScrollerContentProps,
226
+ MessageScrollerContextValue,
227
+ MessageScrollerDefaultScrollPosition,
228
+ MessageScrollerItemProps,
229
+ MessageScrollerMode,
230
+ MessageScrollerProps,
231
+ MessageScrollerProviderProps,
232
+ MessageScrollerRegisterMessage,
233
+ MessageScrollerScrollAlign,
234
+ MessageScrollerScrollOptions,
235
+ MessageScrollerScrollable,
236
+ MessageScrollerStore,
237
+ MessageScrollerViewportProps,
238
+ MessageScrollerVisibilityState,
239
+ MessageScrollerVisibilityStore,
240
+ }
@@ -0,0 +1,337 @@
1
+ import * as React from "react"
2
+
3
+ import {
4
+ getElementScrollTop,
5
+ getElementViewportTop,
6
+ getMaxScrollTop,
7
+ getTailSpacerHeight,
8
+ } from "./geometry"
9
+ import { AUTOSCROLLING_CLEAR_DELAY, SCROLL_POSITION_EPSILON } from "./types"
10
+ import type { MessageScrollerScrollOptions } from "./types"
11
+ import {
12
+ markDefaultScrollPositionApplied,
13
+ type MessageScrollerRefs,
14
+ } from "./use-message-scroller-refs"
15
+
16
+ // Imperative scroll primitives, split from the controller so the move mechanics
17
+ // live apart from the policy that decides when to run them. Each command resolves
18
+ // a target scrollTop and returns false when the viewport is not mounted yet.
19
+ function useMessageScrollerCommands({
20
+ refs,
21
+ commitScrollState,
22
+ scheduleStateCommit,
23
+ scheduleVisibilitySync,
24
+ }: {
25
+ refs: MessageScrollerRefs
26
+ commitScrollState: () => void
27
+ scheduleStateCommit: () => void
28
+ scheduleVisibilitySync: () => void
29
+ }) {
30
+ const {
31
+ streamingTurnRef,
32
+ autoScrollRef,
33
+ autoscrollingRef,
34
+ autoscrollingTimeoutRef,
35
+ contentRef,
36
+ itemCountRef,
37
+ messageElementsRef,
38
+ modeRef,
39
+ pendingScrollToMessageRef,
40
+ prependRestoreRef,
41
+ scrollMarginRef,
42
+ scrollPreviousItemPeekRef,
43
+ spacerGapRef,
44
+ spacerHeightRef,
45
+ spacerRef,
46
+ viewportRef,
47
+ } = refs
48
+
49
+ const setAutoScrolling = React.useCallback(
50
+ (autoscrolling: boolean) => {
51
+ if (autoscrollingTimeoutRef.current !== null) {
52
+ window.clearTimeout(autoscrollingTimeoutRef.current)
53
+ autoscrollingTimeoutRef.current = null
54
+ }
55
+
56
+ if (autoscrollingRef.current !== autoscrolling) {
57
+ autoscrollingRef.current = autoscrolling
58
+ commitScrollState()
59
+ }
60
+
61
+ if (autoscrolling) {
62
+ autoscrollingTimeoutRef.current = window.setTimeout(() => {
63
+ autoscrollingTimeoutRef.current = null
64
+ autoscrollingRef.current = false
65
+ commitScrollState()
66
+ }, AUTOSCROLLING_CLEAR_DELAY)
67
+ }
68
+ },
69
+ [commitScrollState]
70
+ )
71
+
72
+ // Low-level spacer primitive. Unlike the scroll commands, this does not move
73
+ // the viewport: it only writes the tail spacer's reserved height (hiding it
74
+ // at zero). It lives on the commands surface rather than staying private to
75
+ // the controller because the controller both reserves room for an anchored
76
+ // turn (via reanchorToAnchoredMessage) and consumes it while draining a
77
+ // released spacer (in drainReleasedSpacer), and both need the same write. It
78
+ // is intentionally not a user-facing scroll command - treat it as an internal
79
+ // handle the orchestrator threads through to keep spacer writes in one place.
80
+ const setTailSpacerHeight = React.useCallback((height: number) => {
81
+ const spacer = spacerRef.current
82
+
83
+ if (!spacer) {
84
+ return
85
+ }
86
+
87
+ const nextHeight = Math.max(0, Math.ceil(height))
88
+
89
+ if (spacerHeightRef.current === nextHeight) {
90
+ return
91
+ }
92
+
93
+ spacerHeightRef.current = nextHeight
94
+ spacer.hidden = nextHeight === 0
95
+ spacer.style.height = `${nextHeight}px`
96
+ spacer.style.marginTop = nextHeight > 0 ? `${-spacerGapRef.current}px` : ""
97
+ }, [])
98
+
99
+ const scrollToPosition = React.useCallback(
100
+ (
101
+ scrollTop: number,
102
+ {
103
+ behavior = "auto",
104
+ autoscrolling = false,
105
+ }: {
106
+ behavior?: ScrollBehavior
107
+ autoscrolling?: boolean
108
+ } = {}
109
+ ) => {
110
+ const viewport = viewportRef.current
111
+
112
+ if (!viewport) {
113
+ return
114
+ }
115
+
116
+ const nextScrollTop = Math.max(0, scrollTop)
117
+
118
+ if (
119
+ Math.abs(viewport.scrollTop - nextScrollTop) <= SCROLL_POSITION_EPSILON
120
+ ) {
121
+ viewport.scrollTop = nextScrollTop
122
+ commitScrollState()
123
+ return
124
+ }
125
+
126
+ if (autoscrolling) {
127
+ setAutoScrolling(true)
128
+ }
129
+
130
+ viewport.scrollTo({
131
+ top: nextScrollTop,
132
+ behavior,
133
+ })
134
+ scheduleStateCommit()
135
+ },
136
+ [commitScrollState, scheduleStateCommit, setAutoScrolling]
137
+ )
138
+
139
+ const scrollToStart = React.useCallback(
140
+ ({ behavior = "auto" }: MessageScrollerScrollOptions = {}) => {
141
+ if (!viewportRef.current) {
142
+ return false
143
+ }
144
+
145
+ setTailSpacerHeight(0)
146
+ streamingTurnRef.current = null
147
+ modeRef.current = "free-scrolling"
148
+ scrollToPosition(0, { behavior })
149
+ scheduleVisibilitySync()
150
+
151
+ return true
152
+ },
153
+ [scheduleVisibilitySync, scrollToPosition, setTailSpacerHeight]
154
+ )
155
+
156
+ const scrollToEnd = React.useCallback(
157
+ ({ behavior = "auto" }: MessageScrollerScrollOptions = {}) => {
158
+ const viewport = viewportRef.current
159
+
160
+ if (!viewport) {
161
+ return false
162
+ }
163
+
164
+ setTailSpacerHeight(0)
165
+ streamingTurnRef.current = null
166
+ modeRef.current = autoScrollRef.current
167
+ ? "following-bottom"
168
+ : "free-scrolling"
169
+ scrollToPosition(getMaxScrollTop(viewport), {
170
+ autoscrolling: true,
171
+ behavior,
172
+ })
173
+ scheduleVisibilitySync()
174
+
175
+ return true
176
+ },
177
+ [scheduleVisibilitySync, scrollToPosition, setTailSpacerHeight]
178
+ )
179
+
180
+ const scrollToElement = React.useCallback(
181
+ (
182
+ element: HTMLElement,
183
+ {
184
+ align = "start",
185
+ behavior = "auto",
186
+ scrollMargin = scrollMarginRef.current,
187
+ }: MessageScrollerScrollOptions = {},
188
+ {
189
+ keepPreviousPeek = false,
190
+ }: {
191
+ keepPreviousPeek?: boolean
192
+ } = {}
193
+ ) => {
194
+ const content = contentRef.current
195
+ const viewport = viewportRef.current
196
+
197
+ if (!content || !viewport || !content.contains(element)) {
198
+ return false
199
+ }
200
+
201
+ const scrollTop = getElementScrollTop({
202
+ align,
203
+ element,
204
+ scrollMargin: keepPreviousPeek
205
+ ? scrollMargin + scrollPreviousItemPeekRef.current
206
+ : scrollMargin,
207
+ spacer: spacerRef.current,
208
+ viewport,
209
+ })
210
+
211
+ const nextSpacerHeight = getTailSpacerHeight({
212
+ content,
213
+ scrollTop,
214
+ spacer: spacerRef.current,
215
+ viewport,
216
+ })
217
+
218
+ setTailSpacerHeight(nextSpacerHeight)
219
+ // Seed the prepend anchor with the jump target so a prepend that lands
220
+ // before this scroll settles still preserves the jumped-to row; once it
221
+ // settles, syncAfterScroll's capturePrependAnchor re-captures it from the
222
+ // first visible row.
223
+ prependRestoreRef.current = {
224
+ element,
225
+ viewportTop: getElementViewportTop(element, viewport),
226
+ }
227
+
228
+ modeRef.current = keepPreviousPeek
229
+ ? "anchored-to-message"
230
+ : "settling-jump"
231
+ streamingTurnRef.current = keepPreviousPeek ? element : null
232
+
233
+ scrollToPosition(scrollTop, { behavior })
234
+ scheduleVisibilitySync()
235
+
236
+ return true
237
+ },
238
+ [scheduleVisibilitySync, scrollToPosition, setTailSpacerHeight]
239
+ )
240
+
241
+ const reanchorToAnchoredMessage = React.useCallback(() => {
242
+ const element = streamingTurnRef.current
243
+
244
+ if (
245
+ !element ||
246
+ !element.isConnected ||
247
+ modeRef.current !== "anchored-to-message"
248
+ ) {
249
+ return false
250
+ }
251
+
252
+ // Re-run the placement so the tail spacer is recomputed for the new content
253
+ // height and the turn is held at the reading line.
254
+ return scrollToElement(
255
+ element,
256
+ { align: "start" },
257
+ { keepPreviousPeek: true }
258
+ )
259
+ }, [scrollToElement])
260
+
261
+ // The target row may not be mounted yet (e.g. an async-loaded transcript).
262
+ // When it is missing the request is queued in pendingScrollToMessageRef and
263
+ // flushed later — on registerMessage for that id, or on the next content
264
+ // change. An explicit jump also marks the mount default as applied, so
265
+ // defaultScrollPosition does not override it.
266
+ const scrollToMessage = React.useCallback(
267
+ (messageId: string, options?: MessageScrollerScrollOptions) => {
268
+ const element = messageElementsRef.current.get(messageId)
269
+
270
+ if (!element) {
271
+ if (itemCountRef.current === 0) {
272
+ pendingScrollToMessageRef.current = {
273
+ messageId,
274
+ options,
275
+ }
276
+ markDefaultScrollPositionApplied(refs)
277
+
278
+ return true
279
+ }
280
+
281
+ return false
282
+ }
283
+
284
+ markDefaultScrollPositionApplied(refs)
285
+
286
+ if (scrollToElement(element, options)) {
287
+ pendingScrollToMessageRef.current = null
288
+ return true
289
+ }
290
+
291
+ pendingScrollToMessageRef.current = {
292
+ messageId,
293
+ options,
294
+ }
295
+
296
+ return true
297
+ },
298
+ [scrollToElement]
299
+ )
300
+
301
+ const flushPendingScrollToMessage = React.useCallback(() => {
302
+ const pending = pendingScrollToMessageRef.current
303
+
304
+ if (!pending) {
305
+ return false
306
+ }
307
+
308
+ const element = messageElementsRef.current.get(pending.messageId)
309
+
310
+ if (!element) {
311
+ return false
312
+ }
313
+
314
+ const handled = scrollToElement(element, pending.options)
315
+
316
+ if (!handled) {
317
+ return false
318
+ }
319
+
320
+ pendingScrollToMessageRef.current = null
321
+ markDefaultScrollPositionApplied(refs)
322
+
323
+ return true
324
+ }, [scrollToElement])
325
+
326
+ return {
327
+ flushPendingScrollToMessage,
328
+ reanchorToAnchoredMessage,
329
+ scrollToElement,
330
+ scrollToEnd,
331
+ scrollToMessage,
332
+ scrollToStart,
333
+ setTailSpacerHeight,
334
+ }
335
+ }
336
+
337
+ export { useMessageScrollerCommands }