chore: vendor the @shadcn/react message-scroller source (#29473)
The agent chat transcript scrolls through `@shadcn/react`'s MessageScroller, and its scroll defects have to be fixed in the package. The package ships only minified dist, so the fix would be an unreviewable patch against minified code, and 0.3.1 still has the identical defect, so an upgrade buys nothing. This vendors the readable upstream source (`@shadcn/react@0.3.0`, commit `b1c580c63`, MIT) under `site/src/vendor/` and drops the npm dependency. It is a pure move with no behavior change; the fix itself follows in #29354. Each file header pins the upstream tree, and any deviation from upstream must be marked `LOCAL CHANGE`.
This commit is contained in:
1 parent
60cc826f2b
commit
06d421fbcf
25 files changed
+2741
-41
No files matched your search
@@ -11,6 +11,8 @@ gotests_stats.json
|
||||
gotests.json
|
||||
node_modules/
|
||||
vendor/
|
||||
!site/src/vendor/
|
||||
!site/src/vendor/**
|
||||
yarn-error.log
|
||||
|
||||
# Vale (prose linter) pulls package contents into docs/.style/styles/ on
|
||||
|
||||
@@ -31,6 +31,8 @@ exclude_pathspecs=(
|
||||
# (migration 000324). It lives in an applied migration, so it cannot be
|
||||
# edited in place.
|
||||
":(exclude)coderd/notifications/testdata/rendered-templates/**/*.golden"
|
||||
# Vendored third-party source keeps upstream comments verbatim.
|
||||
":(exclude)site/src/vendor/**"
|
||||
)
|
||||
|
||||
scan_all_files() {
|
||||
|
||||
@@ -263,11 +263,15 @@
|
||||
]
|
||||
},
|
||||
// typesGenerated.ts is generated, so ignore it entirely rather than
|
||||
// tracking per-rule exceptions for it.
|
||||
// tracking per-rule exceptions for it. src/vendor/ is third-party source
|
||||
// vendored verbatim (minus marked local changes) and must not drift from
|
||||
// upstream to satisfy in-repo lint rules; Biome excludes it for the same
|
||||
// reason (see biome.jsonc).
|
||||
"ignorePatterns": [
|
||||
"e2e/**/*Generated.ts",
|
||||
"scripts/*.mjs",
|
||||
"**/typesGenerated.ts"
|
||||
"**/typesGenerated.ts",
|
||||
"src/vendor/**"
|
||||
],
|
||||
"overrides": [
|
||||
{
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"extends": "//",
|
||||
"files": {
|
||||
"includes": ["!e2e/**/*Generated.ts", "!scripts/*.mjs"]
|
||||
"includes": ["!e2e/**/*Generated.ts", "!scripts/*.mjs", "!src/vendor"]
|
||||
},
|
||||
"$schema": "./node_modules/@biomejs/biome/configuration_schema.json"
|
||||
}
|
||||
@@ -56,7 +56,6 @@
|
||||
"@novnc/novnc": "^1.5.0",
|
||||
"@pierre/diffs": "1.4.0",
|
||||
"@pierre/trees": "1.0.0-beta.6",
|
||||
"@shadcn/react": "0.3.0",
|
||||
"@tanstack/react-query-devtools": "5.82.0",
|
||||
"@xterm/addon-canvas": "0.7.0",
|
||||
"@xterm/addon-fit": "0.11.0",
|
||||
|
||||
Generated
-19
@@ -67,9 +67,6 @@ importers:
|
||||
'@pierre/trees':
|
||||
specifier: 1.0.0-beta.6
|
||||
version: 1.0.0-beta.6(@pierre/theme@2.0.0)(@shikijs/themes@4.4.3)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(shiki@4.4.3)
|
||||
'@shadcn/react':
|
||||
specifier: 0.3.0
|
||||
version: 0.3.0(@types/react@19.2.18)(react@19.2.8)
|
||||
'@tanstack/react-query-devtools':
|
||||
specifier: 5.82.0
|
||||
version: 5.82.0(@tanstack/react-query@5.82.0(react@19.2.8))(react@19.2.8)
|
||||
@@ -2681,17 +2678,6 @@ packages:
|
||||
rollup:
|
||||
optional: true
|
||||
|
||||
'@shadcn/react@0.3.0':
|
||||
resolution: {integrity: sha512-iKN0NuYe850VDHlxEfvppFrpa7CMV3zArTHusXlaSmeFeQhohGbIqclv6WwPTs/44I8EkXQpcuRt6sXEVKkWqQ==, tarball: https://registry.npmjs.org/@shadcn/react/-/react-0.3.0.tgz}
|
||||
peerDependencies:
|
||||
'@types/react': '>=19'
|
||||
react: '>=19'
|
||||
peerDependenciesMeta:
|
||||
'@types/react':
|
||||
optional: true
|
||||
react:
|
||||
optional: true
|
||||
|
||||
'@shikijs/core@4.4.3':
|
||||
resolution: {integrity: sha512-QCR4q2ZO/ILJEuwiBMel4wdcTDb1JGwfjKTxPDF6x8ixOaluPrVqIn06C99AcRPhmYlBR56d/Fb+GN58GzExpg==, tarball: https://registry.npmjs.org/@shikijs/core/-/core-4.4.3.tgz}
|
||||
engines: {node: '>=20'}
|
||||
@@ -8770,11 +8756,6 @@ snapshots:
|
||||
estree-walker: 2.0.2
|
||||
picomatch: 4.0.7
|
||||
|
||||
'@shadcn/react@0.3.0(@types/react@19.2.18)(react@19.2.8)':
|
||||
optionalDependencies:
|
||||
'@types/react': 19.2.18
|
||||
react: 19.2.8
|
||||
|
||||
'@shikijs/core@4.4.3':
|
||||
dependencies:
|
||||
'@shikijs/primitive': 4.4.3
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
import {
|
||||
MessageScroller,
|
||||
useMessageScroller,
|
||||
} from "@shadcn/react/message-scroller";
|
||||
import { type FC, useEffect, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
useInfiniteQuery,
|
||||
useMutation,
|
||||
@@ -49,6 +44,7 @@ import {
|
||||
} from "#/modules/dashboard/useDashboard";
|
||||
import { pageTitle } from "#/utils/page";
|
||||
import { rewriteLocalhostURL } from "#/utils/portForward";
|
||||
import { MessageScroller, useMessageScroller } from "#/vendor/message-scroller";
|
||||
import { AgentChatPageErrorView } from "./AgentChatPageErrorView";
|
||||
import {
|
||||
AgentChatPageLoadingView,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { MessageScroller } from "@shadcn/react/message-scroller";
|
||||
import type { Decorator, Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { type ComponentProps, type FC, useState } from "react";
|
||||
import { Outlet } from "react-router";
|
||||
@@ -44,6 +43,7 @@ import {
|
||||
withProxyProvider,
|
||||
withWebSocket,
|
||||
} from "#/testHelpers/storybook";
|
||||
import { MessageScroller } from "#/vendor/message-scroller";
|
||||
import {
|
||||
AgentChatPageLoadingView,
|
||||
AgentChatPageNotFoundView,
|
||||
|
||||
+1
-1
@@ -1,4 +1,3 @@
|
||||
import { MessageScroller } from "@shadcn/react/message-scroller";
|
||||
import type { Decorator, Meta, StoryObj } from "@storybook/react-vite";
|
||||
import {
|
||||
expect,
|
||||
@@ -12,6 +11,7 @@ import {
|
||||
} from "storybook/test";
|
||||
import type * as TypesGen from "#/api/typesGenerated";
|
||||
import { MockChatFileMetadata } from "#/testHelpers/chatEntities";
|
||||
import { MessageScroller } from "#/vendor/message-scroller";
|
||||
import { getChatFileURL } from "../../utils/chatAttachments";
|
||||
import { ChatMessageScroller } from "../ChatMessageScroller";
|
||||
import { ConversationTimeline } from "./ConversationTimeline";
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import {
|
||||
MessageScroller,
|
||||
useMessageScroller,
|
||||
} from "@shadcn/react/message-scroller";
|
||||
import { cn } from "cn";
|
||||
import {
|
||||
ChevronLeftIcon,
|
||||
@@ -20,6 +16,7 @@ import {
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "#/components/Tooltip/Tooltip";
|
||||
import { MessageScroller, useMessageScroller } from "#/vendor/message-scroller";
|
||||
|
||||
import { ConversationItem } from "../ChatElements/Conversation";
|
||||
import { Message, MessageContent } from "../ChatElements/Message";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { MessageScroller } from "@shadcn/react/message-scroller";
|
||||
import { MessageScroller } from "#/vendor/message-scroller";
|
||||
import { ChatStatusCallout } from "./ChatStatusCallout";
|
||||
import type { LiveStatusModel } from "./liveStatusModel";
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { MessageScroller } from "@shadcn/react/message-scroller";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { MessageScroller } from "#/vendor/message-scroller";
|
||||
import { ChatMessageScroller } from "../ChatMessageScroller";
|
||||
import { TerminalStatusRow } from "./LiveStreamTail";
|
||||
import { buildLiveStatus, pinFixtureClock } from "./storyFixtures";
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import {
|
||||
MessageScroller,
|
||||
useMessageScrollerScrollable,
|
||||
} from "@shadcn/react/message-scroller";
|
||||
import { cn } from "cn";
|
||||
import { ArrowDownIcon, RotateCcwIcon } from "lucide-react";
|
||||
import { type FC, type ReactNode, useEffect } from "react";
|
||||
import { Button } from "#/components/Button/Button";
|
||||
import { Spinner } from "#/components/Spinner/Spinner";
|
||||
import {
|
||||
MessageScroller,
|
||||
useMessageScrollerScrollable,
|
||||
} from "#/vendor/message-scroller";
|
||||
import { chatWidthClass, useChatFullWidth } from "../hooks/useChatFullWidth";
|
||||
|
||||
type EarlierMessagesProps = {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { MessageScroller } from "@shadcn/react/message-scroller";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import type { FC } from "react";
|
||||
import { expect, fn, userEvent, within } from "storybook/test";
|
||||
@@ -25,6 +24,7 @@ import {
|
||||
withAuthProvider,
|
||||
withDashboardProvider,
|
||||
} from "#/testHelpers/storybook";
|
||||
import { MessageScroller } from "#/vendor/message-scroller";
|
||||
import { ChatWorkspaceContext } from "../context/ChatWorkspaceContext";
|
||||
import { createChatStore } from "./ChatConversation/chatStore";
|
||||
import { FIXTURE_NOW } from "./ChatConversation/storyFixtures";
|
||||
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 shadcn
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+433
@@ -0,0 +1,433 @@
|
||||
// Vendored from @shadcn/react 0.3.0 (MIT; see LICENSE in site/src/vendor).
|
||||
// Upstream: https://github.com/shadcn-ui/ui/tree/b1c580c/packages/react/src/message-scroller
|
||||
// Local deviations must be marked LOCAL CHANGE.
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
import { composeRefs, mergeProps, useRender } from "../use-render"
|
||||
import { USER_SCROLL_KEYS } from "./types"
|
||||
import type {
|
||||
MessageScrollerButtonProps,
|
||||
MessageScrollerContentProps,
|
||||
MessageScrollerContextValue,
|
||||
MessageScrollerItemProps,
|
||||
MessageScrollerProps,
|
||||
MessageScrollerProviderProps,
|
||||
MessageScrollerRegisterMessage,
|
||||
MessageScrollerViewportProps,
|
||||
} from "./types"
|
||||
import { useMessageScrollerController } from "./use-message-scroller-controller"
|
||||
import { useLatest } from "./utils"
|
||||
|
||||
const MessageScrollerContext =
|
||||
React.createContext<MessageScrollerContextValue | null>(null)
|
||||
const MessageScrollerItemContext =
|
||||
React.createContext<MessageScrollerRegisterMessage | null>(null)
|
||||
|
||||
function useMessageScrollerContext() {
|
||||
const context = React.useContext(MessageScrollerContext)
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useMessageScroller must be used within a MessageScroller.")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function useMessageScrollerItemContext() {
|
||||
const context = React.useContext(MessageScrollerItemContext)
|
||||
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
"MessageScrollerItem must be used within a MessageScroller."
|
||||
)
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function useMessageScroller() {
|
||||
const { scrollToEnd, scrollToMessage, scrollToStart } =
|
||||
useMessageScrollerContext()
|
||||
|
||||
return React.useMemo(
|
||||
() => ({
|
||||
scrollToEnd,
|
||||
scrollToMessage,
|
||||
scrollToStart,
|
||||
}),
|
||||
[scrollToEnd, scrollToMessage, scrollToStart]
|
||||
)
|
||||
}
|
||||
|
||||
function useMessageScrollerScrollable() {
|
||||
const { stateStore } = useMessageScrollerContext()
|
||||
|
||||
return React.useSyncExternalStore(
|
||||
stateStore.subscribe,
|
||||
stateStore.getSnapshot,
|
||||
stateStore.getSnapshot
|
||||
)
|
||||
}
|
||||
|
||||
function useMessageScrollerVisibility() {
|
||||
const { observeVisibility, unobserveVisibility, visibilityStore } =
|
||||
useMessageScrollerContext()
|
||||
const subscribe = React.useCallback(
|
||||
(listener: () => void) =>
|
||||
visibilityStore.subscribe(
|
||||
listener,
|
||||
observeVisibility,
|
||||
unobserveVisibility
|
||||
),
|
||||
[observeVisibility, unobserveVisibility, visibilityStore]
|
||||
)
|
||||
|
||||
return React.useSyncExternalStore(
|
||||
subscribe,
|
||||
visibilityStore.getSnapshot,
|
||||
visibilityStore.getSnapshot
|
||||
)
|
||||
}
|
||||
|
||||
function MessageScrollerProvider({
|
||||
autoScroll = false,
|
||||
children,
|
||||
defaultScrollPosition = "end",
|
||||
scrollEdgeThreshold,
|
||||
scrollPreviousItemPeek,
|
||||
scrollMargin,
|
||||
}: MessageScrollerProviderProps) {
|
||||
const { context, registerMessage } = useMessageScrollerController({
|
||||
autoScroll,
|
||||
defaultScrollPosition,
|
||||
scrollEdgeThreshold,
|
||||
scrollPreviousItemPeek,
|
||||
scrollMargin,
|
||||
})
|
||||
|
||||
return (
|
||||
<MessageScrollerContext.Provider value={context}>
|
||||
<MessageScrollerItemContext.Provider value={registerMessage}>
|
||||
{children}
|
||||
</MessageScrollerItemContext.Provider>
|
||||
</MessageScrollerContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function MessageScroller({ children, ...props }: MessageScrollerProps) {
|
||||
const { setRootElement } = useMessageScrollerContext()
|
||||
|
||||
return (
|
||||
<div ref={setRootElement} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function MessageScrollerViewport({
|
||||
"aria-label": ariaLabel,
|
||||
children,
|
||||
onKeyDown,
|
||||
onScroll,
|
||||
onTouchMove,
|
||||
onWheel,
|
||||
preserveScrollOnPrepend = true,
|
||||
ref,
|
||||
role,
|
||||
tabIndex,
|
||||
...props
|
||||
}: MessageScrollerViewportProps) {
|
||||
const {
|
||||
handleResize,
|
||||
preserveScrollOnPrependRef,
|
||||
setViewportElement,
|
||||
syncAfterScroll,
|
||||
userScrollIntent,
|
||||
viewportRef,
|
||||
} = useMessageScrollerContext()
|
||||
|
||||
preserveScrollOnPrependRef.current = preserveScrollOnPrepend
|
||||
|
||||
const setViewportRef = React.useCallback(
|
||||
(element: HTMLDivElement | null) => {
|
||||
setViewportElement(element)
|
||||
composeRefs(ref)?.(element)
|
||||
},
|
||||
[ref, setViewportElement]
|
||||
)
|
||||
|
||||
function handleScroll(event: React.UIEvent<HTMLDivElement>) {
|
||||
syncAfterScroll()
|
||||
onScroll?.(event)
|
||||
}
|
||||
|
||||
function handleWheel(event: React.WheelEvent<HTMLDivElement>) {
|
||||
userScrollIntent()
|
||||
onWheel?.(event)
|
||||
}
|
||||
|
||||
function handleTouchMove(event: React.TouchEvent<HTMLDivElement>) {
|
||||
userScrollIntent()
|
||||
onTouchMove?.(event)
|
||||
}
|
||||
|
||||
function handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
|
||||
if (USER_SCROLL_KEYS.has(event.key)) {
|
||||
userScrollIntent()
|
||||
}
|
||||
|
||||
onKeyDown?.(event)
|
||||
}
|
||||
|
||||
React.useEffect(() => {
|
||||
const viewport = viewportRef.current
|
||||
|
||||
if (!viewport || typeof ResizeObserver === "undefined") {
|
||||
return
|
||||
}
|
||||
|
||||
// Coalesce into rAF: handleResize mutates the spacer inside the observed
|
||||
// content, and resizing an observed element during delivery fires
|
||||
// "ResizeObserver loop completed with undelivered notifications".
|
||||
let frame = 0
|
||||
|
||||
const observer = new ResizeObserver(() => {
|
||||
window.cancelAnimationFrame(frame)
|
||||
frame = window.requestAnimationFrame(handleResize)
|
||||
})
|
||||
|
||||
observer.observe(viewport)
|
||||
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frame)
|
||||
observer.disconnect()
|
||||
}
|
||||
}, [handleResize, viewportRef])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setViewportRef}
|
||||
role={role ?? "region"}
|
||||
aria-label={ariaLabel ?? "Messages"}
|
||||
tabIndex={tabIndex ?? 0}
|
||||
onKeyDown={handleKeyDown}
|
||||
onScroll={handleScroll}
|
||||
onTouchMove={handleTouchMove}
|
||||
onWheel={handleWheel}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function MessageScrollerContent({
|
||||
"aria-relevant": ariaRelevant,
|
||||
children,
|
||||
ref,
|
||||
role,
|
||||
spacerClassName,
|
||||
...props
|
||||
}: MessageScrollerContentProps) {
|
||||
const {
|
||||
handleContentChange,
|
||||
handleResize,
|
||||
setContentElement,
|
||||
setSpacerElement,
|
||||
} = useMessageScrollerContext()
|
||||
const contentRef = React.useRef<HTMLDivElement | null>(null)
|
||||
|
||||
const setContentRef = React.useCallback(
|
||||
(element: HTMLDivElement | null) => {
|
||||
contentRef.current = element
|
||||
setContentElement(element)
|
||||
composeRefs(ref)?.(element)
|
||||
},
|
||||
[ref, setContentElement]
|
||||
)
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
const content = contentRef.current
|
||||
|
||||
if (!content) {
|
||||
return
|
||||
}
|
||||
|
||||
handleContentChange()
|
||||
|
||||
if (typeof MutationObserver === "undefined") {
|
||||
return
|
||||
}
|
||||
|
||||
const observer = new MutationObserver(() => {
|
||||
handleContentChange()
|
||||
})
|
||||
|
||||
observer.observe(content, { childList: true })
|
||||
|
||||
return () => observer.disconnect()
|
||||
}, [handleContentChange])
|
||||
|
||||
React.useEffect(() => {
|
||||
const content = contentRef.current
|
||||
|
||||
if (!content || typeof ResizeObserver === "undefined") {
|
||||
return
|
||||
}
|
||||
|
||||
// Coalesce into rAF: handleResize mutates the spacer inside this observed
|
||||
// element, and resizing an observed element during delivery fires
|
||||
// "ResizeObserver loop completed with undelivered notifications".
|
||||
let frame = 0
|
||||
|
||||
const observer = new ResizeObserver(() => {
|
||||
window.cancelAnimationFrame(frame)
|
||||
frame = window.requestAnimationFrame(handleResize)
|
||||
})
|
||||
|
||||
observer.observe(content)
|
||||
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frame)
|
||||
observer.disconnect()
|
||||
}
|
||||
}, [handleResize])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setContentRef}
|
||||
role={role ?? "log"}
|
||||
aria-relevant={ariaRelevant ?? "additions"}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<div
|
||||
ref={setSpacerElement}
|
||||
aria-hidden="true"
|
||||
data-message-scroller-spacer=""
|
||||
hidden
|
||||
className={spacerClassName}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function MessageScrollerItem({
|
||||
messageId,
|
||||
ref,
|
||||
scrollAnchor = false,
|
||||
...props
|
||||
}: MessageScrollerItemProps) {
|
||||
const registerMessage = useMessageScrollerItemContext()
|
||||
const elementRef = React.useRef<HTMLDivElement | null>(null)
|
||||
|
||||
const setItemRef = React.useCallback(
|
||||
(element: HTMLDivElement | null) => {
|
||||
const previousElement = elementRef.current
|
||||
|
||||
elementRef.current = element
|
||||
|
||||
if (messageId) {
|
||||
registerMessage(messageId, element, previousElement)
|
||||
}
|
||||
|
||||
composeRefs(ref)?.(element)
|
||||
},
|
||||
[messageId, ref, registerMessage]
|
||||
)
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setItemRef}
|
||||
data-message-id={messageId}
|
||||
data-scroll-anchor={scrollAnchor ? "true" : "false"}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function MessageScrollerButton({
|
||||
behavior = "smooth",
|
||||
children,
|
||||
direction = "end",
|
||||
onClick,
|
||||
render,
|
||||
tabIndex,
|
||||
type = "button",
|
||||
...props
|
||||
}: MessageScrollerButtonProps) {
|
||||
const { scrollToEnd, scrollToStart, stateStore } = useMessageScrollerContext()
|
||||
const onClickRef = useLatest(onClick)
|
||||
const subscribe = React.useCallback(
|
||||
(listener: () => void) => stateStore.subscribe(listener),
|
||||
[stateStore]
|
||||
)
|
||||
const getSnapshot = React.useCallback(() => {
|
||||
const state = stateStore.getSnapshot()
|
||||
|
||||
return direction === "start" ? state.start : state.end
|
||||
}, [direction, stateStore])
|
||||
const isActive = React.useSyncExternalStore(
|
||||
subscribe,
|
||||
getSnapshot,
|
||||
getSnapshot
|
||||
)
|
||||
|
||||
const handleClick = React.useCallback(
|
||||
(event: React.MouseEvent<HTMLButtonElement>) => {
|
||||
if (!isActive) {
|
||||
return
|
||||
}
|
||||
|
||||
onClickRef.current?.(event)
|
||||
|
||||
if (!event.defaultPrevented) {
|
||||
event.currentTarget.blur()
|
||||
|
||||
if (direction === "start") {
|
||||
scrollToStart({ behavior })
|
||||
} else {
|
||||
scrollToEnd({ behavior })
|
||||
}
|
||||
}
|
||||
},
|
||||
[behavior, direction, isActive, onClickRef, scrollToEnd, scrollToStart]
|
||||
)
|
||||
|
||||
return useRender({
|
||||
defaultTagName: "button",
|
||||
props: mergeProps<"button">(
|
||||
{
|
||||
type,
|
||||
inert: !isActive,
|
||||
tabIndex: isActive ? tabIndex : -1,
|
||||
children: children ?? <span>Scroll to {direction}</span>,
|
||||
onClick: handleClick,
|
||||
},
|
||||
props
|
||||
),
|
||||
render,
|
||||
state: {
|
||||
active: isActive,
|
||||
direction,
|
||||
},
|
||||
stateAttributesMapping: {
|
||||
active: (value) => ({
|
||||
"data-active": value ? "true" : "false",
|
||||
}),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export {
|
||||
MessageScroller,
|
||||
MessageScrollerButton,
|
||||
MessageScrollerContent,
|
||||
MessageScrollerItem,
|
||||
MessageScrollerProvider,
|
||||
MessageScrollerViewport,
|
||||
useMessageScroller,
|
||||
useMessageScrollerScrollable,
|
||||
useMessageScrollerVisibility,
|
||||
}
|
||||
+391
@@ -0,0 +1,391 @@
|
||||
// Vendored from @shadcn/react 0.3.0 (MIT; see LICENSE in site/src/vendor).
|
||||
// Upstream: https://github.com/shadcn-ui/ui/tree/b1c580c/packages/react/src/message-scroller
|
||||
// Local deviations must be marked LOCAL CHANGE.
|
||||
|
||||
import {
|
||||
EMPTY_MESSAGE_SCROLLER_SCROLLABLE,
|
||||
EMPTY_MESSAGE_SCROLLER_VISIBILITY_STATE,
|
||||
SCROLL_POSITION_EPSILON,
|
||||
} from "./types"
|
||||
import type {
|
||||
MessageScrollerScrollable,
|
||||
MessageScrollerScrollAlign,
|
||||
MessageScrollerVisibilityState,
|
||||
} from "./types"
|
||||
|
||||
function getMessageScrollerScrollable({
|
||||
content,
|
||||
scrollEdgeThreshold,
|
||||
spacer,
|
||||
viewport,
|
||||
}: {
|
||||
content: HTMLElement | null
|
||||
scrollEdgeThreshold: number
|
||||
spacer: HTMLElement | null
|
||||
viewport: HTMLElement | null
|
||||
}): MessageScrollerScrollable {
|
||||
if (!viewport || !content) {
|
||||
return EMPTY_MESSAGE_SCROLLER_SCROLLABLE
|
||||
}
|
||||
|
||||
const contentBottom = getContentBottom({ content, spacer, viewport })
|
||||
|
||||
return {
|
||||
start: viewport.scrollTop > scrollEdgeThreshold,
|
||||
end:
|
||||
contentBottom - viewport.scrollTop - viewport.clientHeight >
|
||||
scrollEdgeThreshold,
|
||||
}
|
||||
}
|
||||
|
||||
function getMessageScrollerVisibilityState({
|
||||
content,
|
||||
scrollMargin,
|
||||
scrollPreviousItemPeek,
|
||||
spacer,
|
||||
viewport,
|
||||
visibleMessageIds,
|
||||
}: {
|
||||
content: HTMLElement | null
|
||||
scrollMargin: number
|
||||
scrollPreviousItemPeek: number
|
||||
spacer: HTMLElement | null
|
||||
viewport: HTMLElement | null
|
||||
visibleMessageIds: Set<string>
|
||||
}): MessageScrollerVisibilityState {
|
||||
if (!content || !viewport) {
|
||||
return EMPTY_MESSAGE_SCROLLER_VISIBILITY_STATE
|
||||
}
|
||||
|
||||
const viewportRect = viewport.getBoundingClientRect()
|
||||
// The reading line sits scrollPreviousItemPeek below scrollMargin: anchored
|
||||
// turns land there with the previous turn peeking above. A row only peeking in
|
||||
// that band has not been read down to yet, so it counts as neither visible nor
|
||||
// current.
|
||||
const lineTop = viewportRect.top + scrollMargin + scrollPreviousItemPeek
|
||||
const trackByLayout = typeof IntersectionObserver === "undefined"
|
||||
|
||||
const visible: string[] = []
|
||||
let currentAnchorId: string | null = null
|
||||
|
||||
// Walk rows in document order so visible ids come out top-to-bottom.
|
||||
for (const item of getMessageScrollerItems(content, spacer)) {
|
||||
const messageId = item.dataset.messageId
|
||||
|
||||
if (!messageId) {
|
||||
continue
|
||||
}
|
||||
|
||||
const isAnchor = item.dataset.scrollAnchor === "true"
|
||||
// Anchors need a rect to place the current line; non-anchors lean on the
|
||||
// observer set (or a rect in the no-observer fallback).
|
||||
const rect = isAnchor || trackByLayout ? item.getBoundingClientRect() : null
|
||||
|
||||
const isVisible =
|
||||
trackByLayout && rect
|
||||
? rect.bottom > lineTop && rect.top < viewportRect.bottom
|
||||
: visibleMessageIds.has(messageId)
|
||||
|
||||
if (isVisible) {
|
||||
visible.push(messageId)
|
||||
}
|
||||
|
||||
// Current is the last anchor to have reached the reading line: the turn you
|
||||
// scrolled to (placed at the line) wins over newer turns lower down, the
|
||||
// previous turn peeking above the line has been passed, and it stays current
|
||||
// even after its header scrolls above the viewport.
|
||||
if (isAnchor && rect && rect.top <= lineTop + SCROLL_POSITION_EPSILON) {
|
||||
currentAnchorId = messageId
|
||||
}
|
||||
}
|
||||
|
||||
if (visible.length === 0 && currentAnchorId === null) {
|
||||
return EMPTY_MESSAGE_SCROLLER_VISIBILITY_STATE
|
||||
}
|
||||
|
||||
return {
|
||||
currentAnchorId,
|
||||
visibleMessageIds: visible,
|
||||
}
|
||||
}
|
||||
|
||||
function getMessageScrollerItems(
|
||||
content: HTMLElement,
|
||||
spacer: HTMLElement | null
|
||||
) {
|
||||
return Array.from(content.children).filter(
|
||||
(child): child is HTMLElement =>
|
||||
child instanceof HTMLElement && child !== spacer
|
||||
)
|
||||
}
|
||||
|
||||
function getNewScrollAnchor(items: HTMLElement[], previousItemCount: number) {
|
||||
for (let index = previousItemCount; index < items.length; index++) {
|
||||
const item = items[index]
|
||||
|
||||
if (item?.dataset.scrollAnchor === "true") {
|
||||
return item
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function getUnanchoredScrollAnchor(
|
||||
items: HTMLElement[],
|
||||
handledAnchors: { has(element: HTMLElement): boolean }
|
||||
) {
|
||||
for (const item of items) {
|
||||
if (item.dataset.scrollAnchor === "true" && !handledAnchors.has(item)) {
|
||||
return item
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function hasMultipleNewScrollAnchors(
|
||||
items: HTMLElement[],
|
||||
previousItemCount: number
|
||||
) {
|
||||
let count = 0
|
||||
|
||||
for (let index = previousItemCount; index < items.length; index++) {
|
||||
const item = items[index]
|
||||
|
||||
if (item?.dataset.scrollAnchor !== "true") {
|
||||
continue
|
||||
}
|
||||
|
||||
count += 1
|
||||
|
||||
if (count > 1) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
function getLastScrollAnchor(items: HTMLElement[]) {
|
||||
for (let index = items.length - 1; index >= 0; index--) {
|
||||
const item = items[index]
|
||||
|
||||
if (item?.dataset.scrollAnchor === "true") {
|
||||
return item
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function getFirstVisibleMessageItem({
|
||||
content,
|
||||
spacer,
|
||||
viewport,
|
||||
}: {
|
||||
content: HTMLElement
|
||||
spacer: HTMLElement | null
|
||||
viewport: HTMLElement
|
||||
}) {
|
||||
const viewportRect = viewport.getBoundingClientRect()
|
||||
|
||||
for (const item of getMessageScrollerItems(content, spacer)) {
|
||||
if (!item.dataset.messageId) {
|
||||
continue
|
||||
}
|
||||
|
||||
const rect = item.getBoundingClientRect()
|
||||
|
||||
if (rect.bottom > viewportRect.top && rect.top < viewportRect.bottom) {
|
||||
return item
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function getElementScrollTop({
|
||||
align,
|
||||
element,
|
||||
scrollMargin,
|
||||
spacer,
|
||||
viewport,
|
||||
}: {
|
||||
align: MessageScrollerScrollAlign
|
||||
element: HTMLElement
|
||||
scrollMargin: number
|
||||
spacer: HTMLElement | null
|
||||
viewport: HTMLElement
|
||||
}) {
|
||||
const elementTop = getElementTop(element, viewport)
|
||||
const elementHeight = element.getBoundingClientRect().height
|
||||
const contentPadding = getContentBlockPadding(spacer)
|
||||
|
||||
if (align === "center") {
|
||||
const insetHeight = Math.max(
|
||||
0,
|
||||
viewport.clientHeight - contentPadding.start - contentPadding.end
|
||||
)
|
||||
|
||||
return (
|
||||
elementTop -
|
||||
contentPadding.start -
|
||||
(insetHeight - elementHeight) / 2 -
|
||||
scrollMargin
|
||||
)
|
||||
}
|
||||
|
||||
if (align === "end") {
|
||||
return (
|
||||
elementTop -
|
||||
viewport.clientHeight +
|
||||
elementHeight +
|
||||
contentPadding.end +
|
||||
scrollMargin
|
||||
)
|
||||
}
|
||||
|
||||
if (align === "nearest") {
|
||||
const elementBottom = elementTop + elementHeight
|
||||
const viewportTop = viewport.scrollTop + contentPadding.start
|
||||
const viewportBottom =
|
||||
viewport.scrollTop + viewport.clientHeight - contentPadding.end
|
||||
|
||||
if (elementTop >= viewportTop && elementBottom <= viewportBottom) {
|
||||
return viewport.scrollTop
|
||||
}
|
||||
|
||||
if (elementTop < viewportTop) {
|
||||
return elementTop - contentPadding.start - scrollMargin
|
||||
}
|
||||
|
||||
return (
|
||||
elementBottom - viewport.clientHeight + contentPadding.end + scrollMargin
|
||||
)
|
||||
}
|
||||
|
||||
return elementTop - contentPadding.start - scrollMargin
|
||||
}
|
||||
|
||||
function getElementTop(element: HTMLElement, viewport: HTMLElement) {
|
||||
const elementRect = element.getBoundingClientRect()
|
||||
const viewportRect = viewport.getBoundingClientRect()
|
||||
|
||||
return elementRect.top - viewportRect.top + viewport.scrollTop
|
||||
}
|
||||
|
||||
function getElementViewportTop(element: HTMLElement, viewport: HTMLElement) {
|
||||
return (
|
||||
element.getBoundingClientRect().top - viewport.getBoundingClientRect().top
|
||||
)
|
||||
}
|
||||
|
||||
function getTailSpacerHeight({
|
||||
content,
|
||||
scrollTop,
|
||||
spacer,
|
||||
viewport,
|
||||
}: {
|
||||
content: HTMLElement
|
||||
scrollTop: number
|
||||
spacer: HTMLElement | null
|
||||
viewport: HTMLElement
|
||||
}) {
|
||||
const contentBottom = getContentBottom({ content, spacer, viewport })
|
||||
|
||||
return scrollTop + viewport.clientHeight - contentBottom
|
||||
}
|
||||
|
||||
function getContentBottom({
|
||||
content,
|
||||
spacer,
|
||||
viewport,
|
||||
}: {
|
||||
content: HTMLElement
|
||||
spacer: HTMLElement | null
|
||||
viewport: HTMLElement
|
||||
}) {
|
||||
const items = getMessageScrollerItems(content, spacer)
|
||||
const padding = getBlockPadding(content)
|
||||
const viewportRect = viewport.getBoundingClientRect()
|
||||
const scrollTop = viewport.scrollTop
|
||||
let contentBottom = padding.start + padding.end
|
||||
|
||||
for (const item of items) {
|
||||
const rect = item.getBoundingClientRect()
|
||||
|
||||
contentBottom = Math.max(
|
||||
contentBottom,
|
||||
rect.bottom - viewportRect.top + scrollTop + padding.end
|
||||
)
|
||||
}
|
||||
|
||||
return contentBottom
|
||||
}
|
||||
|
||||
function getMaxScrollTop(viewport: HTMLElement) {
|
||||
return Math.max(0, viewport.scrollHeight - viewport.clientHeight)
|
||||
}
|
||||
|
||||
function getBlockPadding(element: HTMLElement) {
|
||||
const style = window.getComputedStyle(element)
|
||||
|
||||
return {
|
||||
end: readCssPixel(style.paddingBlockEnd || style.paddingBottom),
|
||||
start: readCssPixel(style.paddingBlockStart || style.paddingTop),
|
||||
}
|
||||
}
|
||||
|
||||
function getContentBlockPadding(spacer: HTMLElement | null) {
|
||||
const content = spacer?.parentElement
|
||||
|
||||
if (!content) {
|
||||
return {
|
||||
end: 0,
|
||||
start: 0,
|
||||
}
|
||||
}
|
||||
|
||||
return getBlockPadding(content)
|
||||
}
|
||||
|
||||
function getFlexGap(element: HTMLElement | null) {
|
||||
if (!element) {
|
||||
return 0
|
||||
}
|
||||
|
||||
const style = window.getComputedStyle(element)
|
||||
const gap = style.rowGap === "normal" ? style.gap : style.rowGap
|
||||
|
||||
return readCssPixel(gap)
|
||||
}
|
||||
|
||||
function readCssPixel(value: string | undefined) {
|
||||
if (!value) {
|
||||
return 0
|
||||
}
|
||||
|
||||
const number = Number.parseFloat(value)
|
||||
|
||||
return Number.isFinite(number) ? number : 0
|
||||
}
|
||||
|
||||
export {
|
||||
getContentBlockPadding,
|
||||
getContentBottom,
|
||||
getElementScrollTop,
|
||||
getElementTop,
|
||||
getElementViewportTop,
|
||||
getFirstVisibleMessageItem,
|
||||
getFlexGap,
|
||||
getLastScrollAnchor,
|
||||
getMaxScrollTop,
|
||||
getMessageScrollerItems,
|
||||
getMessageScrollerScrollable,
|
||||
getMessageScrollerVisibilityState,
|
||||
getNewScrollAnchor,
|
||||
getTailSpacerHeight,
|
||||
getUnanchoredScrollAnchor,
|
||||
hasMultipleNewScrollAnchors,
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
// Vendored from @shadcn/react 0.3.0 (MIT; see LICENSE in site/src/vendor).
|
||||
// Upstream: https://github.com/shadcn-ui/ui/tree/b1c580c/packages/react/src/message-scroller
|
||||
// Local deviations must be marked LOCAL CHANGE.
|
||||
|
||||
import {
|
||||
MessageScrollerButton as Button,
|
||||
MessageScrollerContent as Content,
|
||||
MessageScrollerItem as Item,
|
||||
MessageScrollerProvider as Provider,
|
||||
MessageScroller as Root,
|
||||
MessageScrollerViewport as Viewport,
|
||||
} from "./components"
|
||||
|
||||
export const MessageScroller = {
|
||||
Provider,
|
||||
Root,
|
||||
Viewport,
|
||||
Content,
|
||||
Item,
|
||||
Button,
|
||||
}
|
||||
|
||||
export {
|
||||
useMessageScroller,
|
||||
useMessageScrollerScrollable,
|
||||
useMessageScrollerVisibility,
|
||||
} from "./components"
|
||||
|
||||
export type {
|
||||
MessageScrollerDefaultScrollPosition,
|
||||
MessageScrollerScrollAlign,
|
||||
MessageScrollerScrollOptions,
|
||||
MessageScrollerScrollable,
|
||||
MessageScrollerVisibilityState,
|
||||
} from "./types"
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
// Vendored from @shadcn/react 0.3.0 (MIT; see LICENSE in site/src/vendor).
|
||||
// Upstream: https://github.com/shadcn-ui/ui/tree/b1c580c/packages/react/src/message-scroller
|
||||
// Local deviations must be marked LOCAL CHANGE.
|
||||
|
||||
import { EMPTY_MESSAGE_SCROLLER_VISIBILITY_STATE } from "./types"
|
||||
import type {
|
||||
MessageScrollerScrollable,
|
||||
MessageScrollerStore,
|
||||
MessageScrollerVisibilityState,
|
||||
MessageScrollerVisibilityStore,
|
||||
} from "./types"
|
||||
|
||||
// Generic useSyncExternalStore backing: a stable snapshot (referentially equal
|
||||
// while isEqual holds, so subscribers only re-render on real transitions) plus
|
||||
// optional reference-counting via the subscribe-time lifecycle callbacks.
|
||||
function createExternalStore<T>(
|
||||
initialSnapshot: T,
|
||||
isEqual: (a: T, b: T) => boolean
|
||||
) {
|
||||
let snapshot = initialSnapshot
|
||||
const listeners = new Set<() => void>()
|
||||
|
||||
return {
|
||||
getSnapshot: () => snapshot,
|
||||
hasListeners: () => listeners.size > 0,
|
||||
setSnapshot: (nextSnapshot: T) => {
|
||||
if (isEqual(snapshot, nextSnapshot)) {
|
||||
return
|
||||
}
|
||||
|
||||
snapshot = nextSnapshot
|
||||
listeners.forEach((listener) => listener())
|
||||
},
|
||||
subscribe: (
|
||||
listener: () => void,
|
||||
onFirstSubscribe?: () => void,
|
||||
onLastUnsubscribe?: () => void
|
||||
) => {
|
||||
const wasEmpty = listeners.size === 0
|
||||
|
||||
listeners.add(listener)
|
||||
|
||||
if (wasEmpty) {
|
||||
onFirstSubscribe?.()
|
||||
}
|
||||
|
||||
return () => {
|
||||
listeners.delete(listener)
|
||||
|
||||
if (listeners.size === 0) {
|
||||
onLastUnsubscribe?.()
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function createMessageScrollerStore<T>(
|
||||
initialSnapshot: T,
|
||||
isEqual: (a: T, b: T) => boolean
|
||||
): MessageScrollerStore<T> {
|
||||
return createExternalStore(initialSnapshot, isEqual)
|
||||
}
|
||||
|
||||
function createMessageScrollerVisibilityStore(): MessageScrollerVisibilityStore {
|
||||
return createExternalStore(
|
||||
EMPTY_MESSAGE_SCROLLER_VISIBILITY_STATE,
|
||||
areVisibilityStatesEqual
|
||||
)
|
||||
}
|
||||
|
||||
function areScrollStatesEqual(
|
||||
current: MessageScrollerScrollable,
|
||||
next: MessageScrollerScrollable
|
||||
) {
|
||||
return current.start === next.start && current.end === next.end
|
||||
}
|
||||
|
||||
function areVisibilityStatesEqual(
|
||||
current: MessageScrollerVisibilityState,
|
||||
next: MessageScrollerVisibilityState
|
||||
) {
|
||||
if (current.currentAnchorId !== next.currentAnchorId) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (current.visibleMessageIds.length !== next.visibleMessageIds.length) {
|
||||
return false
|
||||
}
|
||||
|
||||
return current.visibleMessageIds.every(
|
||||
(messageId, index) => messageId === next.visibleMessageIds[index]
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
areScrollStatesEqual,
|
||||
areVisibilityStatesEqual,
|
||||
createMessageScrollerStore,
|
||||
createMessageScrollerVisibilityStore,
|
||||
}
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
// Vendored from @shadcn/react 0.3.0 (MIT; see LICENSE in site/src/vendor).
|
||||
// Upstream: https://github.com/shadcn-ui/ui/tree/b1c580c/packages/react/src/message-scroller
|
||||
// Local deviations must be marked LOCAL CHANGE.
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
import type { UseRenderComponentProps } from "../use-render"
|
||||
|
||||
// Default scrollEdgeThreshold. Sub-pixel tolerance so edge detection does not
|
||||
// flicker across engines that round scrollTop differently.
|
||||
const DEFAULT_SCROLL_EDGE_THRESHOLD = 8
|
||||
|
||||
// Default scrollPreviousItemPeek. Pixels of the previous item kept visible above
|
||||
// a newly anchored row.
|
||||
const DEFAULT_SCROLL_PREVIOUS_ITEM_PEEK = 64
|
||||
|
||||
// Default scrollMargin for scrollToMessage and programmatic targets.
|
||||
const DEFAULT_SCROLL_MARGIN = 0
|
||||
|
||||
// Two fractional scrollTop values within this range are treated as equal, to
|
||||
// absorb zoom and HiDPI rounding drift.
|
||||
const SCROLL_POSITION_EPSILON = 0.5
|
||||
|
||||
// How long (ms) data-autoscrolling stays set during a programmatic smooth scroll
|
||||
// before clearing.
|
||||
const AUTOSCROLLING_CLEAR_DELAY = 180
|
||||
|
||||
// Viewport keys that count as deliberate scroll intent and release follow-bottom.
|
||||
const USER_SCROLL_KEYS = new Set([
|
||||
"ArrowDown",
|
||||
"ArrowUp",
|
||||
"End",
|
||||
"Home",
|
||||
"PageDown",
|
||||
"PageUp",
|
||||
" ", // Space key.
|
||||
])
|
||||
|
||||
// Internal scroll mode. Derived from intent and commands; decides how the
|
||||
// viewport reacts to content and resize.
|
||||
type MessageScrollerMode =
|
||||
| "following-bottom" // autoScroll on, pinned to the latest message.
|
||||
| "free-scrolling" // reader scrolled away; position left alone (prepends still preserved).
|
||||
| "anchored-to-message" // holding a turn at the reading line while it streams.
|
||||
| "settling-jump" // a programmatic jump is animating; intent detection suppressed until it settles.
|
||||
|
||||
// Where a saved transcript opens on the first non-empty render.
|
||||
type MessageScrollerDefaultScrollPosition = "start" | "end" | "last-anchor"
|
||||
|
||||
// Which transcript edge MessageScrollerButton scrolls toward.
|
||||
type MessageScrollerButtonDirection = "start" | "end"
|
||||
|
||||
// Viewport alignment for scrollToMessage and programmatic jumps.
|
||||
type MessageScrollerScrollAlign = "start" | "center" | "end" | "nearest"
|
||||
|
||||
// Options for scrollToMessage, scrollToEnd, and scrollToStart.
|
||||
type MessageScrollerScrollOptions = {
|
||||
// Viewport edge or center to align the target to.
|
||||
align?: MessageScrollerScrollAlign
|
||||
// Native scroll behavior.
|
||||
behavior?: ScrollBehavior
|
||||
// Margin on the aligned edge, in pixels. Defaults to the provider scrollMargin.
|
||||
scrollMargin?: number
|
||||
}
|
||||
|
||||
// Scroll snapshot from useMessageScrollerScrollable: which edges the viewport can
|
||||
// still scroll toward.
|
||||
type MessageScrollerScrollable = {
|
||||
// The viewport can scroll toward the start (content is hidden above).
|
||||
start: boolean
|
||||
// The viewport can scroll toward the end (content is hidden below).
|
||||
end: boolean
|
||||
}
|
||||
|
||||
// Visibility snapshot from useMessageScrollerVisibility.
|
||||
type MessageScrollerVisibilityState = {
|
||||
// The anchored turn the reader is in, or null. Stays set after the anchor
|
||||
// scrolls above the viewport.
|
||||
currentAnchorId: string | null
|
||||
// messageId values intersecting the viewport, in document order.
|
||||
visibleMessageIds: string[]
|
||||
}
|
||||
|
||||
// Headless provider for a chat transcript scroller. Owns scroll behavior and
|
||||
// state; renders no DOM.
|
||||
type MessageScrollerProviderProps = {
|
||||
children?: React.ReactNode
|
||||
// Follow new content at the bottom while the viewport is already at the end.
|
||||
autoScroll?: boolean
|
||||
// Opening position on the first non-empty render, applied once.
|
||||
defaultScrollPosition?: MessageScrollerDefaultScrollPosition
|
||||
// Distance from an edge that still counts as at-top/at-bottom. Defaults to 8.
|
||||
scrollEdgeThreshold?: number
|
||||
// Extra top margin for a newly anchored row, added to scrollMargin. Defaults to 64.
|
||||
scrollPreviousItemPeek?: number
|
||||
// Default margin on the aligned edge for commands and visibility. Defaults to 0.
|
||||
scrollMargin?: number
|
||||
}
|
||||
|
||||
// Frame container for a chat transcript scroller. Must render inside a
|
||||
// MessageScrollerProvider.
|
||||
type MessageScrollerProps = React.ComponentProps<"div">
|
||||
|
||||
// Scrollable viewport. Owns native scroll events and prepend preservation.
|
||||
type MessageScrollerViewportProps = React.ComponentProps<"div"> & {
|
||||
// Keep the first visible messageId row stable on prepend. Defaults to true.
|
||||
preserveScrollOnPrepend?: boolean
|
||||
}
|
||||
|
||||
// Transcript row container. Every direct child should be a MessageScrollerItem.
|
||||
type MessageScrollerContentProps = React.ComponentProps<"div"> & {
|
||||
// Class name for the internal tail spacer used when anchoring turns near the top.
|
||||
spacerClassName?: string
|
||||
}
|
||||
|
||||
// One transcript row: a message, marker, typing row, separator, or load-more row.
|
||||
type MessageScrollerItemProps = React.ComponentProps<"div"> & {
|
||||
// Stable row id for scrollToMessage, visibility, and prepend preservation.
|
||||
messageId?: string
|
||||
// Marks a turn boundary that newly appended anchors and last-anchor restore use.
|
||||
scrollAnchor?: boolean
|
||||
}
|
||||
|
||||
// State passed to MessageScrollerButton's render prop.
|
||||
type MessageScrollerButtonRenderState = {
|
||||
// Whether overflow exists toward this button's direction.
|
||||
active: boolean
|
||||
direction: MessageScrollerButtonDirection
|
||||
}
|
||||
|
||||
// Scroll control for the start or end of the transcript.
|
||||
type MessageScrollerButtonProps = UseRenderComponentProps<
|
||||
"button",
|
||||
MessageScrollerButtonRenderState
|
||||
> & {
|
||||
// Native scroll behavior when clicked. Defaults to "smooth".
|
||||
behavior?: ScrollBehavior
|
||||
// Transcript edge to scroll toward. Defaults to "end".
|
||||
direction?: MessageScrollerButtonDirection
|
||||
}
|
||||
|
||||
// Minimal external store backing useMessageScrollerScrollable, consumed via
|
||||
// useSyncExternalStore.
|
||||
type MessageScrollerStore<T> = {
|
||||
getSnapshot: () => T
|
||||
setSnapshot: (nextSnapshot: T) => void
|
||||
subscribe: (listener: () => void) => () => void
|
||||
}
|
||||
|
||||
// External store backing useMessageScrollerVisibility. Adds reference-counting so
|
||||
// tracking stays lazy.
|
||||
type MessageScrollerVisibilityStore = {
|
||||
getSnapshot: () => MessageScrollerVisibilityState
|
||||
hasListeners: () => boolean
|
||||
setSnapshot: (nextSnapshot: MessageScrollerVisibilityState) => void
|
||||
subscribe: (
|
||||
listener: () => void,
|
||||
onFirstSubscribe: () => void,
|
||||
onLastUnsubscribe: () => void
|
||||
) => () => void
|
||||
}
|
||||
|
||||
// Registers (or, with removedElement, unregisters) a MessageScrollerItem node by
|
||||
// messageId.
|
||||
type MessageScrollerRegisterMessage = (
|
||||
messageId: string,
|
||||
element: HTMLElement | null,
|
||||
removedElement?: HTMLElement | null
|
||||
) => void
|
||||
|
||||
// Internal context wiring the parts together. Not part of the public API.
|
||||
type MessageScrollerContextValue = {
|
||||
handleContentChange: () => void
|
||||
handleResize: () => void
|
||||
observeVisibility: () => void
|
||||
preserveScrollOnPrependRef: React.RefObject<boolean>
|
||||
scrollToEnd: (options?: MessageScrollerScrollOptions) => boolean
|
||||
scrollToMessage: (
|
||||
messageId: string,
|
||||
options?: MessageScrollerScrollOptions
|
||||
) => boolean
|
||||
scrollToStart: (options?: MessageScrollerScrollOptions) => boolean
|
||||
setContentElement: (element: HTMLDivElement | null) => void
|
||||
setRootElement: (element: HTMLDivElement | null) => void
|
||||
setSpacerElement: (element: HTMLDivElement | null) => void
|
||||
setViewportElement: (element: HTMLDivElement | null) => void
|
||||
stateStore: MessageScrollerStore<MessageScrollerScrollable>
|
||||
syncAfterScroll: () => void
|
||||
unobserveVisibility: () => void
|
||||
userScrollIntent: () => void
|
||||
viewportRef: React.RefObject<HTMLDivElement | null>
|
||||
visibilityStore: MessageScrollerVisibilityStore
|
||||
}
|
||||
|
||||
// Initial MessageScrollerScrollable before measurement. Stable reference for the
|
||||
// server and first-render snapshot.
|
||||
const EMPTY_MESSAGE_SCROLLER_SCROLLABLE: MessageScrollerScrollable = {
|
||||
start: false,
|
||||
end: false,
|
||||
}
|
||||
|
||||
// Shared empty array so empty visibility snapshots stay referentially stable.
|
||||
const EMPTY_VISIBLE_MESSAGE_IDS: string[] = []
|
||||
|
||||
// Initial MessageScrollerVisibilityState. Nothing tracked, no current anchor.
|
||||
const EMPTY_MESSAGE_SCROLLER_VISIBILITY_STATE: MessageScrollerVisibilityState =
|
||||
{
|
||||
currentAnchorId: null,
|
||||
visibleMessageIds: EMPTY_VISIBLE_MESSAGE_IDS,
|
||||
}
|
||||
|
||||
export {
|
||||
AUTOSCROLLING_CLEAR_DELAY,
|
||||
DEFAULT_SCROLL_EDGE_THRESHOLD,
|
||||
DEFAULT_SCROLL_MARGIN,
|
||||
DEFAULT_SCROLL_PREVIOUS_ITEM_PEEK,
|
||||
EMPTY_MESSAGE_SCROLLER_SCROLLABLE,
|
||||
EMPTY_MESSAGE_SCROLLER_VISIBILITY_STATE,
|
||||
EMPTY_VISIBLE_MESSAGE_IDS,
|
||||
SCROLL_POSITION_EPSILON,
|
||||
USER_SCROLL_KEYS,
|
||||
}
|
||||
|
||||
export type {
|
||||
MessageScrollerButtonDirection,
|
||||
MessageScrollerButtonProps,
|
||||
MessageScrollerButtonRenderState,
|
||||
MessageScrollerContentProps,
|
||||
MessageScrollerContextValue,
|
||||
MessageScrollerDefaultScrollPosition,
|
||||
MessageScrollerItemProps,
|
||||
MessageScrollerMode,
|
||||
MessageScrollerProps,
|
||||
MessageScrollerProviderProps,
|
||||
MessageScrollerRegisterMessage,
|
||||
MessageScrollerScrollAlign,
|
||||
MessageScrollerScrollOptions,
|
||||
MessageScrollerScrollable,
|
||||
MessageScrollerStore,
|
||||
MessageScrollerViewportProps,
|
||||
MessageScrollerVisibilityState,
|
||||
MessageScrollerVisibilityStore,
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
// Vendored from @shadcn/react 0.3.0 (MIT; see LICENSE in site/src/vendor).
|
||||
// Upstream: https://github.com/shadcn-ui/ui/tree/b1c580c/packages/react/src/message-scroller
|
||||
// Local deviations must be marked LOCAL CHANGE.
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
import {
|
||||
getElementScrollTop,
|
||||
getElementViewportTop,
|
||||
getMaxScrollTop,
|
||||
getTailSpacerHeight,
|
||||
} from "./geometry"
|
||||
import { AUTOSCROLLING_CLEAR_DELAY, SCROLL_POSITION_EPSILON } from "./types"
|
||||
import type { MessageScrollerScrollOptions } from "./types"
|
||||
import type { MessageScrollerRefs } from "./use-message-scroller-refs"
|
||||
|
||||
// Imperative scroll primitives, split from the controller so the move mechanics
|
||||
// live apart from the policy that decides when to run them. Each command resolves
|
||||
// a target scrollTop and returns false when the viewport is not mounted yet.
|
||||
function useMessageScrollerCommands({
|
||||
refs,
|
||||
commitScrollState,
|
||||
scheduleStateCommit,
|
||||
scheduleVisibilitySync,
|
||||
}: {
|
||||
refs: MessageScrollerRefs
|
||||
commitScrollState: () => void
|
||||
scheduleStateCommit: () => void
|
||||
scheduleVisibilitySync: () => void
|
||||
}) {
|
||||
const {
|
||||
streamingTurnRef,
|
||||
autoScrollRef,
|
||||
autoscrollingRef,
|
||||
autoscrollingTimeoutRef,
|
||||
contentRef,
|
||||
defaultScrollPositionAppliedRef,
|
||||
itemCountRef,
|
||||
messageElementsRef,
|
||||
modeRef,
|
||||
pendingScrollToMessageRef,
|
||||
prependRestoreRef,
|
||||
scrollMarginRef,
|
||||
scrollPreviousItemPeekRef,
|
||||
spacerGapRef,
|
||||
spacerHeightRef,
|
||||
spacerRef,
|
||||
viewportRef,
|
||||
} = refs
|
||||
|
||||
const setAutoScrolling = React.useCallback(
|
||||
(autoscrolling: boolean) => {
|
||||
if (autoscrollingTimeoutRef.current !== null) {
|
||||
window.clearTimeout(autoscrollingTimeoutRef.current)
|
||||
autoscrollingTimeoutRef.current = null
|
||||
}
|
||||
|
||||
if (autoscrollingRef.current !== autoscrolling) {
|
||||
autoscrollingRef.current = autoscrolling
|
||||
commitScrollState()
|
||||
}
|
||||
|
||||
if (autoscrolling) {
|
||||
autoscrollingTimeoutRef.current = window.setTimeout(() => {
|
||||
autoscrollingTimeoutRef.current = null
|
||||
autoscrollingRef.current = false
|
||||
commitScrollState()
|
||||
}, AUTOSCROLLING_CLEAR_DELAY)
|
||||
}
|
||||
},
|
||||
[commitScrollState]
|
||||
)
|
||||
|
||||
const setTailSpacerHeight = React.useCallback((height: number) => {
|
||||
const spacer = spacerRef.current
|
||||
|
||||
if (!spacer) {
|
||||
return
|
||||
}
|
||||
|
||||
const nextHeight = Math.max(0, Math.ceil(height))
|
||||
|
||||
if (spacerHeightRef.current === nextHeight) {
|
||||
return
|
||||
}
|
||||
|
||||
spacerHeightRef.current = nextHeight
|
||||
spacer.hidden = nextHeight === 0
|
||||
spacer.style.height = `${nextHeight}px`
|
||||
spacer.style.marginTop = nextHeight > 0 ? `${-spacerGapRef.current}px` : ""
|
||||
}, [])
|
||||
|
||||
const scrollToPosition = React.useCallback(
|
||||
(
|
||||
scrollTop: number,
|
||||
{
|
||||
behavior = "auto",
|
||||
autoscrolling = false,
|
||||
}: {
|
||||
behavior?: ScrollBehavior
|
||||
autoscrolling?: boolean
|
||||
} = {}
|
||||
) => {
|
||||
const viewport = viewportRef.current
|
||||
|
||||
if (!viewport) {
|
||||
return
|
||||
}
|
||||
|
||||
const nextScrollTop = Math.max(0, scrollTop)
|
||||
|
||||
if (
|
||||
Math.abs(viewport.scrollTop - nextScrollTop) <= SCROLL_POSITION_EPSILON
|
||||
) {
|
||||
viewport.scrollTop = nextScrollTop
|
||||
commitScrollState()
|
||||
return
|
||||
}
|
||||
|
||||
if (autoscrolling) {
|
||||
setAutoScrolling(true)
|
||||
}
|
||||
|
||||
viewport.scrollTo({
|
||||
top: nextScrollTop,
|
||||
behavior,
|
||||
})
|
||||
scheduleStateCommit()
|
||||
},
|
||||
[commitScrollState, scheduleStateCommit, setAutoScrolling]
|
||||
)
|
||||
|
||||
const scrollToStart = React.useCallback(
|
||||
({ behavior = "auto" }: MessageScrollerScrollOptions = {}) => {
|
||||
if (!viewportRef.current) {
|
||||
return false
|
||||
}
|
||||
|
||||
setTailSpacerHeight(0)
|
||||
streamingTurnRef.current = null
|
||||
modeRef.current = "free-scrolling"
|
||||
scrollToPosition(0, { behavior })
|
||||
scheduleVisibilitySync()
|
||||
|
||||
return true
|
||||
},
|
||||
[scheduleVisibilitySync, scrollToPosition, setTailSpacerHeight]
|
||||
)
|
||||
|
||||
const scrollToEnd = React.useCallback(
|
||||
({ behavior = "auto" }: MessageScrollerScrollOptions = {}) => {
|
||||
const viewport = viewportRef.current
|
||||
|
||||
if (!viewport) {
|
||||
return false
|
||||
}
|
||||
|
||||
setTailSpacerHeight(0)
|
||||
streamingTurnRef.current = null
|
||||
modeRef.current = autoScrollRef.current
|
||||
? "following-bottom"
|
||||
: "free-scrolling"
|
||||
scrollToPosition(getMaxScrollTop(viewport), {
|
||||
autoscrolling: true,
|
||||
behavior,
|
||||
})
|
||||
scheduleVisibilitySync()
|
||||
|
||||
return true
|
||||
},
|
||||
[scheduleVisibilitySync, scrollToPosition, setTailSpacerHeight]
|
||||
)
|
||||
|
||||
const scrollToElement = React.useCallback(
|
||||
(
|
||||
element: HTMLElement,
|
||||
{
|
||||
align = "start",
|
||||
behavior = "auto",
|
||||
scrollMargin = scrollMarginRef.current,
|
||||
}: MessageScrollerScrollOptions = {},
|
||||
{
|
||||
keepPreviousPeek = false,
|
||||
}: {
|
||||
keepPreviousPeek?: boolean
|
||||
} = {}
|
||||
) => {
|
||||
const content = contentRef.current
|
||||
const viewport = viewportRef.current
|
||||
|
||||
if (!content || !viewport || !content.contains(element)) {
|
||||
return false
|
||||
}
|
||||
|
||||
const scrollTop = getElementScrollTop({
|
||||
align,
|
||||
element,
|
||||
scrollMargin: keepPreviousPeek
|
||||
? scrollMargin + scrollPreviousItemPeekRef.current
|
||||
: scrollMargin,
|
||||
spacer: spacerRef.current,
|
||||
viewport,
|
||||
})
|
||||
|
||||
const nextSpacerHeight = getTailSpacerHeight({
|
||||
content,
|
||||
scrollTop,
|
||||
spacer: spacerRef.current,
|
||||
viewport,
|
||||
})
|
||||
|
||||
setTailSpacerHeight(nextSpacerHeight)
|
||||
// Seed the prepend anchor with the jump target so a prepend that lands
|
||||
// before this scroll settles still preserves the jumped-to row; once it
|
||||
// settles, syncAfterScroll's capturePrependAnchor re-captures it from the
|
||||
// first visible row.
|
||||
prependRestoreRef.current = {
|
||||
element,
|
||||
viewportTop: getElementViewportTop(element, viewport),
|
||||
}
|
||||
|
||||
modeRef.current = keepPreviousPeek
|
||||
? "anchored-to-message"
|
||||
: "settling-jump"
|
||||
streamingTurnRef.current = keepPreviousPeek ? element : null
|
||||
|
||||
scrollToPosition(scrollTop, { behavior })
|
||||
scheduleVisibilitySync()
|
||||
|
||||
return true
|
||||
},
|
||||
[scheduleVisibilitySync, scrollToPosition, setTailSpacerHeight]
|
||||
)
|
||||
|
||||
const reanchorToAnchoredMessage = React.useCallback(() => {
|
||||
const element = streamingTurnRef.current
|
||||
|
||||
if (
|
||||
!element ||
|
||||
!element.isConnected ||
|
||||
modeRef.current !== "anchored-to-message"
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Re-run the placement so the tail spacer is recomputed for the new content
|
||||
// height and the turn is held at the reading line.
|
||||
return scrollToElement(
|
||||
element,
|
||||
{ align: "start" },
|
||||
{ keepPreviousPeek: true }
|
||||
)
|
||||
}, [scrollToElement])
|
||||
|
||||
// The target row may not be mounted yet (e.g. an async-loaded transcript).
|
||||
// When it is missing the request is queued in pendingScrollToMessageRef and
|
||||
// flushed later — on registerMessage for that id, or on the next content
|
||||
// change. An explicit jump also marks the mount default as applied, so
|
||||
// defaultScrollPosition does not override it.
|
||||
const scrollToMessage = React.useCallback(
|
||||
(messageId: string, options?: MessageScrollerScrollOptions) => {
|
||||
const element = messageElementsRef.current.get(messageId)
|
||||
|
||||
if (!element) {
|
||||
if (itemCountRef.current === 0) {
|
||||
pendingScrollToMessageRef.current = {
|
||||
messageId,
|
||||
options,
|
||||
}
|
||||
defaultScrollPositionAppliedRef.current = true
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
defaultScrollPositionAppliedRef.current = true
|
||||
|
||||
if (scrollToElement(element, options)) {
|
||||
pendingScrollToMessageRef.current = null
|
||||
return true
|
||||
}
|
||||
|
||||
pendingScrollToMessageRef.current = {
|
||||
messageId,
|
||||
options,
|
||||
}
|
||||
|
||||
return true
|
||||
},
|
||||
[scrollToElement]
|
||||
)
|
||||
|
||||
const flushPendingScrollToMessage = React.useCallback(() => {
|
||||
const pending = pendingScrollToMessageRef.current
|
||||
|
||||
if (!pending) {
|
||||
return false
|
||||
}
|
||||
|
||||
const element = messageElementsRef.current.get(pending.messageId)
|
||||
|
||||
if (!element) {
|
||||
return false
|
||||
}
|
||||
|
||||
const handled = scrollToElement(element, pending.options)
|
||||
|
||||
if (!handled) {
|
||||
return false
|
||||
}
|
||||
|
||||
pendingScrollToMessageRef.current = null
|
||||
defaultScrollPositionAppliedRef.current = true
|
||||
|
||||
return true
|
||||
}, [scrollToElement])
|
||||
|
||||
return {
|
||||
flushPendingScrollToMessage,
|
||||
reanchorToAnchoredMessage,
|
||||
scrollToElement,
|
||||
scrollToEnd,
|
||||
scrollToMessage,
|
||||
scrollToStart,
|
||||
}
|
||||
}
|
||||
|
||||
export { useMessageScrollerCommands }
|
||||
@@ -0,0 +1,762 @@
|
||||
// Vendored from @shadcn/react 0.3.0 (MIT; see LICENSE in site/src/vendor).
|
||||
// Upstream: https://github.com/shadcn-ui/ui/tree/b1c580c/packages/react/src/message-scroller
|
||||
// Local deviations must be marked LOCAL CHANGE.
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
import {
|
||||
getContentBottom,
|
||||
getElementTop,
|
||||
getElementViewportTop,
|
||||
getFirstVisibleMessageItem,
|
||||
getFlexGap,
|
||||
getLastScrollAnchor,
|
||||
getMessageScrollerItems,
|
||||
getMessageScrollerScrollable,
|
||||
getMessageScrollerVisibilityState,
|
||||
getNewScrollAnchor,
|
||||
getUnanchoredScrollAnchor,
|
||||
hasMultipleNewScrollAnchors,
|
||||
} from "./geometry"
|
||||
import {
|
||||
DEFAULT_SCROLL_EDGE_THRESHOLD,
|
||||
DEFAULT_SCROLL_MARGIN,
|
||||
DEFAULT_SCROLL_PREVIOUS_ITEM_PEEK,
|
||||
EMPTY_MESSAGE_SCROLLER_VISIBILITY_STATE,
|
||||
SCROLL_POSITION_EPSILON,
|
||||
} from "./types"
|
||||
import type {
|
||||
MessageScrollerContextValue,
|
||||
MessageScrollerProviderProps,
|
||||
MessageScrollerRegisterMessage,
|
||||
MessageScrollerScrollable,
|
||||
} from "./types"
|
||||
import { useMessageScrollerCommands } from "./use-message-scroller-commands"
|
||||
import { useMessageScrollerRefs } from "./use-message-scroller-refs"
|
||||
|
||||
// Builds a ref callback that stores the node and runs onMount once it attaches.
|
||||
function useElementRef(
|
||||
elementRef: React.RefObject<HTMLDivElement | null>,
|
||||
onMount: () => void
|
||||
) {
|
||||
return React.useCallback(
|
||||
(element: HTMLDivElement | null) => {
|
||||
elementRef.current = element
|
||||
|
||||
if (element) {
|
||||
onMount()
|
||||
}
|
||||
},
|
||||
[elementRef, onMount]
|
||||
)
|
||||
}
|
||||
|
||||
// Orchestrator hook. Decides when to scroll and delegates the moves to
|
||||
// useMessageScrollerCommands; state and visibility commits are coalesced on a
|
||||
// requestAnimationFrame and torn down on cleanup for StrictMode safety.
|
||||
function useMessageScrollerController({
|
||||
autoScroll = false,
|
||||
defaultScrollPosition = "end",
|
||||
scrollEdgeThreshold = DEFAULT_SCROLL_EDGE_THRESHOLD,
|
||||
scrollPreviousItemPeek = DEFAULT_SCROLL_PREVIOUS_ITEM_PEEK,
|
||||
scrollMargin = DEFAULT_SCROLL_MARGIN,
|
||||
}: MessageScrollerProviderProps) {
|
||||
const refs = useMessageScrollerRefs({
|
||||
autoScroll,
|
||||
scrollEdgeThreshold,
|
||||
scrollMargin,
|
||||
scrollPreviousItemPeek,
|
||||
})
|
||||
|
||||
const {
|
||||
streamingTurnRef,
|
||||
autoScrollRef,
|
||||
autoscrollingRef,
|
||||
autoscrollingTimeoutRef,
|
||||
contentRef,
|
||||
defaultScrollPositionAppliedRef,
|
||||
firstItemRef,
|
||||
itemCountRef,
|
||||
lastScrollTopRef,
|
||||
messageElementsRef,
|
||||
modeRef,
|
||||
pendingScrollFrameRef,
|
||||
pendingScrollToMessageRef,
|
||||
prependRestoreRef,
|
||||
preserveScrollOnPrependRef,
|
||||
rootRef,
|
||||
scrollEdgeThresholdRef,
|
||||
scrollMarginRef,
|
||||
scrollPreviousItemPeekRef,
|
||||
spacerGapRef,
|
||||
spacerHeightRef,
|
||||
spacerRef,
|
||||
stateFrameRef,
|
||||
stateStore,
|
||||
viewportRef,
|
||||
visibilityFrameRef,
|
||||
visibilityObserverRef,
|
||||
visibilityStore,
|
||||
visibleMessageIdsRef,
|
||||
handledScrollAnchorsRef,
|
||||
} = refs
|
||||
|
||||
const previousDefaultScrollPositionRef = React.useRef(defaultScrollPosition)
|
||||
|
||||
if (previousDefaultScrollPositionRef.current !== defaultScrollPosition) {
|
||||
previousDefaultScrollPositionRef.current = defaultScrollPosition
|
||||
defaultScrollPositionAppliedRef.current = false
|
||||
}
|
||||
|
||||
const writeStateAttributes = React.useCallback(
|
||||
(state: MessageScrollerScrollable) => {
|
||||
const root = rootRef.current
|
||||
const viewport = viewportRef.current
|
||||
const scrollable = [state.start && "start", state.end && "end"]
|
||||
.filter(Boolean)
|
||||
.join(" ")
|
||||
const autoScrolling = autoscrollingRef.current
|
||||
|
||||
for (const element of [root, viewport]) {
|
||||
if (!element) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (scrollable) {
|
||||
element.setAttribute("data-scrollable", scrollable)
|
||||
} else {
|
||||
element.removeAttribute("data-scrollable")
|
||||
}
|
||||
|
||||
element.toggleAttribute("data-autoscrolling", autoScrolling)
|
||||
}
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
// Owns the one follow-bottom transition: arm at the bottom, release on any
|
||||
// scroll away (including a scrollbar drag), suppressed during a programmatic
|
||||
// scroll so the auto-scroll animation cannot release itself. Arming also
|
||||
// skips the anchored-to-message hold: the tail spacer makes a freshly
|
||||
// anchored turn read as "at the end", and re-arming there would let the
|
||||
// first streamed chunk yank the reader off the anchor. The hold hands back
|
||||
// to following in handleResize, once the reply consumes the tail spacer.
|
||||
const reconcileFollowMode = React.useCallback(
|
||||
(scrollable: MessageScrollerScrollable) => {
|
||||
const scrollTop = viewportRef.current?.scrollTop ?? 0
|
||||
// Content growing past the live edge also reads as "not at the end", but
|
||||
// only a scrollbar drag moves scrollTop up. Growth must not release
|
||||
// follow-output: the resize handler is coalesced onto a frame, so a state
|
||||
// commit can observe the grown content before follow catches up.
|
||||
const scrolledUp =
|
||||
scrollTop < lastScrollTopRef.current - SCROLL_POSITION_EPSILON
|
||||
|
||||
lastScrollTopRef.current = scrollTop
|
||||
|
||||
if (
|
||||
autoScrollRef.current &&
|
||||
!scrollable.end &&
|
||||
modeRef.current !== "settling-jump" &&
|
||||
modeRef.current !== "anchored-to-message"
|
||||
) {
|
||||
modeRef.current = "following-bottom"
|
||||
} else if (
|
||||
modeRef.current === "following-bottom" &&
|
||||
scrollable.end &&
|
||||
scrolledUp &&
|
||||
!autoscrollingRef.current
|
||||
) {
|
||||
modeRef.current = "free-scrolling"
|
||||
}
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
const commitScrollState = React.useCallback(() => {
|
||||
const nextState = getMessageScrollerScrollable({
|
||||
content: contentRef.current,
|
||||
scrollEdgeThreshold: scrollEdgeThresholdRef.current,
|
||||
spacer: spacerRef.current,
|
||||
viewport: viewportRef.current,
|
||||
})
|
||||
|
||||
reconcileFollowMode(nextState)
|
||||
|
||||
// While follow-output is engaged the scroller is already closing any gap a
|
||||
// streamed chunk just opened, so publishing it as scrollable toward the
|
||||
// end would strobe the scroll button once per chunk. Reconcile runs on the
|
||||
// raw geometry first, so a commit that releases follow still publishes the
|
||||
// gap it released over.
|
||||
const publishedState =
|
||||
modeRef.current === "following-bottom"
|
||||
? { ...nextState, end: false }
|
||||
: nextState
|
||||
|
||||
writeStateAttributes(publishedState)
|
||||
stateStore.setSnapshot(publishedState)
|
||||
}, [reconcileFollowMode, stateStore, writeStateAttributes])
|
||||
|
||||
const scheduleStateCommit = React.useCallback(() => {
|
||||
if (stateFrameRef.current !== null) {
|
||||
return
|
||||
}
|
||||
|
||||
stateFrameRef.current = window.requestAnimationFrame(() => {
|
||||
stateFrameRef.current = null
|
||||
commitScrollState()
|
||||
})
|
||||
}, [commitScrollState])
|
||||
|
||||
const scheduleVisibilitySync = React.useCallback(() => {
|
||||
if (!visibilityStore.hasListeners()) {
|
||||
return
|
||||
}
|
||||
|
||||
if (visibilityFrameRef.current !== null) {
|
||||
return
|
||||
}
|
||||
|
||||
visibilityFrameRef.current = window.requestAnimationFrame(() => {
|
||||
visibilityFrameRef.current = null
|
||||
|
||||
// A frame can outlive the last unsubscribe. Recomputing here would
|
||||
// overwrite the EMPTY snapshot that teardown just wrote, leaving a stale
|
||||
// value for the next subscriber to read.
|
||||
if (!visibilityStore.hasListeners()) {
|
||||
return
|
||||
}
|
||||
|
||||
visibilityStore.setSnapshot(
|
||||
getMessageScrollerVisibilityState({
|
||||
content: contentRef.current,
|
||||
scrollMargin: scrollMarginRef.current,
|
||||
scrollPreviousItemPeek: scrollPreviousItemPeekRef.current,
|
||||
spacer: spacerRef.current,
|
||||
viewport: viewportRef.current,
|
||||
visibleMessageIds: visibleMessageIdsRef.current,
|
||||
})
|
||||
)
|
||||
})
|
||||
}, [visibilityStore])
|
||||
|
||||
const {
|
||||
flushPendingScrollToMessage,
|
||||
reanchorToAnchoredMessage,
|
||||
scrollToElement,
|
||||
scrollToEnd,
|
||||
scrollToMessage,
|
||||
scrollToStart,
|
||||
} = useMessageScrollerCommands({
|
||||
refs,
|
||||
commitScrollState,
|
||||
scheduleStateCommit,
|
||||
scheduleVisibilitySync,
|
||||
})
|
||||
|
||||
const restorePrependedAnchor = React.useCallback(() => {
|
||||
const anchor = prependRestoreRef.current
|
||||
const viewport = viewportRef.current
|
||||
|
||||
if (!anchor || !viewport || !anchor.element.isConnected) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Compare the anchor relative to the viewport, not to the content. Native
|
||||
// scroll anchoring leaves the viewport-relative position unchanged, so this
|
||||
// is a no-op where the browser already handled the prepend and only corrects
|
||||
// the scroll where it did not (e.g. Safari) — without trusting a capability
|
||||
// flag, which some engines report incorrectly.
|
||||
const nextViewportTop = getElementViewportTop(anchor.element, viewport)
|
||||
const delta = nextViewportTop - anchor.viewportTop
|
||||
|
||||
if (Math.abs(delta) <= SCROLL_POSITION_EPSILON) {
|
||||
return false
|
||||
}
|
||||
|
||||
viewport.scrollTop += delta
|
||||
anchor.viewportTop = getElementViewportTop(anchor.element, viewport)
|
||||
scheduleStateCommit()
|
||||
scheduleVisibilitySync()
|
||||
|
||||
return true
|
||||
}, [scheduleStateCommit, scheduleVisibilitySync])
|
||||
|
||||
const capturePrependAnchor = React.useCallback(() => {
|
||||
const content = contentRef.current
|
||||
const viewport = viewportRef.current
|
||||
|
||||
if (!content || !viewport) {
|
||||
prependRestoreRef.current = null
|
||||
return
|
||||
}
|
||||
|
||||
const anchor = getFirstVisibleMessageItem({
|
||||
content,
|
||||
spacer: spacerRef.current,
|
||||
viewport,
|
||||
})
|
||||
|
||||
prependRestoreRef.current = anchor
|
||||
? {
|
||||
element: anchor,
|
||||
viewportTop: getElementViewportTop(anchor, viewport),
|
||||
}
|
||||
: null
|
||||
}, [])
|
||||
|
||||
const schedulePendingScrollToMessageFlush = React.useCallback(() => {
|
||||
if (pendingScrollFrameRef.current !== null) {
|
||||
return
|
||||
}
|
||||
|
||||
pendingScrollFrameRef.current = window.requestAnimationFrame(() => {
|
||||
pendingScrollFrameRef.current = null
|
||||
|
||||
if (flushPendingScrollToMessage()) {
|
||||
capturePrependAnchor()
|
||||
}
|
||||
})
|
||||
}, [capturePrependAnchor, flushPendingScrollToMessage])
|
||||
|
||||
const applyDefaultScrollPosition = React.useCallback(() => {
|
||||
if (
|
||||
!defaultScrollPosition ||
|
||||
defaultScrollPositionAppliedRef.current ||
|
||||
itemCountRef.current === 0
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
let handled = false
|
||||
|
||||
if (defaultScrollPosition === "last-anchor") {
|
||||
const content = contentRef.current
|
||||
const viewport = viewportRef.current
|
||||
const anchor =
|
||||
content && viewport
|
||||
? getLastScrollAnchor(
|
||||
getMessageScrollerItems(content, spacerRef.current)
|
||||
)
|
||||
: null
|
||||
|
||||
if (!content || !viewport || !anchor) {
|
||||
handled = scrollToEnd({ behavior: "auto" })
|
||||
} else {
|
||||
const anchorTop = getElementTop(anchor, viewport)
|
||||
const contentBottom = getContentBottom({
|
||||
content,
|
||||
spacer: spacerRef.current,
|
||||
viewport,
|
||||
})
|
||||
// A short last turn already fits below the anchor, so opening at the end
|
||||
// shows the whole turn without leaving a blank gap beneath it.
|
||||
const lastTurnFits = contentBottom - anchorTop <= viewport.clientHeight
|
||||
|
||||
handled = lastTurnFits
|
||||
? scrollToEnd({ behavior: "auto" })
|
||||
: scrollToElement(
|
||||
anchor,
|
||||
{ align: "start" },
|
||||
{ keepPreviousPeek: true }
|
||||
)
|
||||
}
|
||||
} else {
|
||||
handled =
|
||||
defaultScrollPosition === "end"
|
||||
? scrollToEnd({ behavior: "auto" })
|
||||
: scrollToStart({ behavior: "auto" })
|
||||
}
|
||||
|
||||
if (!handled) {
|
||||
return false
|
||||
}
|
||||
|
||||
defaultScrollPositionAppliedRef.current = true
|
||||
|
||||
return true
|
||||
}, [defaultScrollPosition, scrollToElement, scrollToEnd, scrollToStart])
|
||||
|
||||
const handleContentChange = React.useCallback(() => {
|
||||
const content = contentRef.current
|
||||
|
||||
if (!content) {
|
||||
return
|
||||
}
|
||||
|
||||
const items = getMessageScrollerItems(content, spacerRef.current)
|
||||
const previousItemCount = itemCountRef.current
|
||||
const previousFirstItem = firstItemRef.current
|
||||
|
||||
itemCountRef.current = items.length
|
||||
firstItemRef.current = items[0] ?? null
|
||||
|
||||
// Reconcile the scroll position with the new content. Every path re-captures
|
||||
// the prepend anchor afterward, so each branch just returns.
|
||||
//
|
||||
// Branch order is load-bearing: first-content, prepended, appended, updated.
|
||||
const reconcileScrollPosition = () => {
|
||||
if (flushPendingScrollToMessage()) {
|
||||
return
|
||||
}
|
||||
|
||||
if (previousItemCount === 0) {
|
||||
if (applyDefaultScrollPosition()) {
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
items.length > 0 &&
|
||||
autoScrollRef.current &&
|
||||
scrollToEnd({ behavior: "auto" })
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
commitScrollState()
|
||||
scheduleVisibilitySync()
|
||||
return
|
||||
}
|
||||
|
||||
const previousFirstItemIndex = previousFirstItem
|
||||
? items.indexOf(previousFirstItem)
|
||||
: -1
|
||||
const didPrepend =
|
||||
preserveScrollOnPrependRef.current && previousFirstItemIndex > 0
|
||||
|
||||
if (didPrepend) {
|
||||
// Prepended rows are not new appends. Restore the prior scroll position.
|
||||
// The restore is a no-op where native scroll anchoring already did it.
|
||||
restorePrependedAnchor()
|
||||
return
|
||||
}
|
||||
|
||||
if (items.length > previousItemCount) {
|
||||
const anchor = getNewScrollAnchor(items, previousItemCount)
|
||||
|
||||
if (anchor) {
|
||||
// While the reader is following the live end, a batch of several
|
||||
// anchored turns arriving at once should keep following the end — not
|
||||
// yank back to anchor the first turn of the batch. A single new anchor
|
||||
// still moves to the top as usual.
|
||||
if (
|
||||
autoScrollRef.current &&
|
||||
modeRef.current === "following-bottom" &&
|
||||
hasMultipleNewScrollAnchors(items, previousItemCount)
|
||||
) {
|
||||
scrollToEnd({ behavior: "auto" })
|
||||
return
|
||||
}
|
||||
|
||||
scrollToElement(
|
||||
anchor,
|
||||
{ align: "start" },
|
||||
{ keepPreviousPeek: true }
|
||||
)
|
||||
handledScrollAnchorsRef.current.add(anchor)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if (items.length === previousItemCount) {
|
||||
const anchor = getUnanchoredScrollAnchor(
|
||||
items,
|
||||
handledScrollAnchorsRef.current
|
||||
)
|
||||
|
||||
if (anchor) {
|
||||
scrollToElement(
|
||||
anchor,
|
||||
{ align: "start" },
|
||||
{ keepPreviousPeek: true }
|
||||
)
|
||||
handledScrollAnchorsRef.current.add(anchor)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Appends with no new anchor (and content-only updates) fall through here:
|
||||
// keep following the end if we still are, otherwise just recommit state.
|
||||
if (modeRef.current === "following-bottom" && autoScrollRef.current) {
|
||||
scrollToEnd({ behavior: "auto" })
|
||||
} else {
|
||||
commitScrollState()
|
||||
scheduleVisibilitySync()
|
||||
}
|
||||
}
|
||||
|
||||
reconcileScrollPosition()
|
||||
capturePrependAnchor()
|
||||
}, [
|
||||
applyDefaultScrollPosition,
|
||||
capturePrependAnchor,
|
||||
commitScrollState,
|
||||
flushPendingScrollToMessage,
|
||||
restorePrependedAnchor,
|
||||
scheduleVisibilitySync,
|
||||
scrollToElement,
|
||||
scrollToEnd,
|
||||
])
|
||||
|
||||
const handleResize = React.useCallback(() => {
|
||||
if (modeRef.current === "following-bottom" && autoScrollRef.current) {
|
||||
scrollToEnd({ behavior: "auto" })
|
||||
return
|
||||
}
|
||||
|
||||
// Hold the anchored turn in place as content below it resizes (a reply
|
||||
// streaming in, or a transient marker collapsing) — otherwise the shrinking
|
||||
// content lets the browser clamp scrollTop and the turn drops.
|
||||
const previousSpacerHeight = spacerHeightRef.current
|
||||
|
||||
if (reanchorToAnchoredMessage()) {
|
||||
// The reply streaming below the anchor consumes the tail spacer as it
|
||||
// grows. Once the last of it is gone the reply has filled the viewport
|
||||
// and the reader is genuinely at the live edge, so autoScroll hands off
|
||||
// from the anchor hold to following the bottom. Requiring the >0 → 0
|
||||
// transition keeps a turn taller than the viewport (placed with no
|
||||
// spacer) held instead of yanked to the end.
|
||||
if (
|
||||
autoScrollRef.current &&
|
||||
previousSpacerHeight > 0 &&
|
||||
spacerHeightRef.current === 0
|
||||
) {
|
||||
scrollToEnd({ behavior: "auto" })
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
scheduleStateCommit()
|
||||
scheduleVisibilitySync()
|
||||
}, [
|
||||
reanchorToAnchoredMessage,
|
||||
scheduleStateCommit,
|
||||
scheduleVisibilitySync,
|
||||
scrollToEnd,
|
||||
])
|
||||
|
||||
const observeVisibility = React.useCallback(() => {
|
||||
const viewport = viewportRef.current
|
||||
|
||||
if (!viewport || !visibilityStore.hasListeners()) {
|
||||
return
|
||||
}
|
||||
|
||||
if (typeof IntersectionObserver === "undefined") {
|
||||
scheduleVisibilitySync()
|
||||
return
|
||||
}
|
||||
|
||||
if (!visibilityObserverRef.current) {
|
||||
visibilityObserverRef.current = new IntersectionObserver(
|
||||
(entries) => {
|
||||
for (const entry of entries) {
|
||||
const messageId = (entry.target as HTMLElement).dataset.messageId
|
||||
|
||||
if (!messageId) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (entry.isIntersecting) {
|
||||
visibleMessageIdsRef.current.add(messageId)
|
||||
} else {
|
||||
visibleMessageIdsRef.current.delete(messageId)
|
||||
}
|
||||
}
|
||||
|
||||
scheduleVisibilitySync()
|
||||
},
|
||||
{
|
||||
root: viewport,
|
||||
// Shrink the root's top edge to the anchoring line so a previous turn
|
||||
// peeking in the scrollMargin + peek band is not reported as visible,
|
||||
// keeping visibleMessageIds consistent with currentAnchorId. Captured
|
||||
// at observe time; a prop change rebuilds the observer on resubscribe.
|
||||
rootMargin: `${-(
|
||||
scrollMarginRef.current + scrollPreviousItemPeekRef.current
|
||||
)}px 0px 0px 0px`,
|
||||
threshold: [0, 0.01, 0.5, 1],
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
messageElementsRef.current.forEach((element) => {
|
||||
visibilityObserverRef.current?.observe(element)
|
||||
})
|
||||
scheduleVisibilitySync()
|
||||
}, [scheduleVisibilitySync, visibilityStore])
|
||||
|
||||
const unobserveVisibility = React.useCallback(() => {
|
||||
if (visibilityFrameRef.current !== null) {
|
||||
window.cancelAnimationFrame(visibilityFrameRef.current)
|
||||
visibilityFrameRef.current = null
|
||||
}
|
||||
|
||||
visibilityObserverRef.current?.disconnect()
|
||||
visibilityObserverRef.current = null
|
||||
visibleMessageIdsRef.current.clear()
|
||||
visibilityStore.setSnapshot(EMPTY_MESSAGE_SCROLLER_VISIBILITY_STATE)
|
||||
}, [visibilityStore])
|
||||
|
||||
const registerMessage = React.useCallback<MessageScrollerRegisterMessage>(
|
||||
(messageId, element, removedElement) => {
|
||||
if (element) {
|
||||
messageElementsRef.current.set(messageId, element)
|
||||
visibilityObserverRef.current?.observe(element)
|
||||
scheduleVisibilitySync()
|
||||
|
||||
if (pendingScrollToMessageRef.current?.messageId === messageId) {
|
||||
schedulePendingScrollToMessageFlush()
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
removedElement &&
|
||||
messageElementsRef.current.get(messageId) === removedElement
|
||||
) {
|
||||
messageElementsRef.current.delete(messageId)
|
||||
visibleMessageIdsRef.current.delete(messageId)
|
||||
visibilityObserverRef.current?.unobserve(removedElement)
|
||||
scheduleVisibilitySync()
|
||||
}
|
||||
},
|
||||
[schedulePendingScrollToMessageFlush, scheduleVisibilitySync]
|
||||
)
|
||||
|
||||
const userScrollIntent = React.useCallback(() => {
|
||||
if (
|
||||
modeRef.current === "following-bottom" ||
|
||||
modeRef.current === "anchored-to-message" ||
|
||||
modeRef.current === "settling-jump"
|
||||
) {
|
||||
// A deliberate gesture releases auto-follow, turn-anchoring, and an in-flight
|
||||
// programmatic jump so re-pinning (and re-arming) never fights the reader.
|
||||
streamingTurnRef.current = null
|
||||
modeRef.current = "free-scrolling"
|
||||
}
|
||||
}, [])
|
||||
|
||||
const mirrorStateAttributes = React.useCallback(
|
||||
() => writeStateAttributes(stateStore.getSnapshot()),
|
||||
[stateStore, writeStateAttributes]
|
||||
)
|
||||
|
||||
const setRootElement = useElementRef(rootRef, mirrorStateAttributes)
|
||||
const setViewportElement = useElementRef(viewportRef, mirrorStateAttributes)
|
||||
|
||||
const setContentElement = React.useCallback(
|
||||
(element: HTMLDivElement | null) => {
|
||||
contentRef.current = element
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
const setSpacerElement = React.useCallback(
|
||||
(element: HTMLDivElement | null) => {
|
||||
spacerRef.current = element
|
||||
spacerGapRef.current = getFlexGap(element?.parentElement ?? null)
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
const syncAfterScroll = React.useCallback(() => {
|
||||
commitScrollState()
|
||||
scheduleVisibilitySync()
|
||||
capturePrependAnchor()
|
||||
}, [capturePrependAnchor, commitScrollState, scheduleVisibilitySync])
|
||||
|
||||
const context = React.useMemo<MessageScrollerContextValue>(
|
||||
() => ({
|
||||
handleContentChange,
|
||||
handleResize,
|
||||
observeVisibility,
|
||||
preserveScrollOnPrependRef,
|
||||
scrollToEnd,
|
||||
scrollToMessage,
|
||||
scrollToStart,
|
||||
setContentElement,
|
||||
setRootElement,
|
||||
setSpacerElement,
|
||||
setViewportElement,
|
||||
stateStore,
|
||||
syncAfterScroll,
|
||||
unobserveVisibility,
|
||||
userScrollIntent,
|
||||
viewportRef,
|
||||
visibilityStore,
|
||||
}),
|
||||
[
|
||||
handleContentChange,
|
||||
handleResize,
|
||||
observeVisibility,
|
||||
scrollToEnd,
|
||||
scrollToMessage,
|
||||
scrollToStart,
|
||||
setContentElement,
|
||||
setRootElement,
|
||||
setSpacerElement,
|
||||
setViewportElement,
|
||||
stateStore,
|
||||
syncAfterScroll,
|
||||
unobserveVisibility,
|
||||
userScrollIntent,
|
||||
visibilityStore,
|
||||
]
|
||||
)
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
applyDefaultScrollPosition()
|
||||
}, [applyDefaultScrollPosition])
|
||||
|
||||
React.useEffect(() => {
|
||||
return () => {
|
||||
// Reset every ref after cancelling. StrictMode replays effects on the same
|
||||
// refs (unmount then remount), so a frame id left non-null here makes the
|
||||
// scheduler on remount think a frame is still pending and never reschedule.
|
||||
if (stateFrameRef.current !== null) {
|
||||
window.cancelAnimationFrame(stateFrameRef.current)
|
||||
stateFrameRef.current = null
|
||||
}
|
||||
|
||||
if (visibilityFrameRef.current !== null) {
|
||||
window.cancelAnimationFrame(visibilityFrameRef.current)
|
||||
visibilityFrameRef.current = null
|
||||
}
|
||||
|
||||
if (autoscrollingTimeoutRef.current !== null) {
|
||||
window.clearTimeout(autoscrollingTimeoutRef.current)
|
||||
autoscrollingTimeoutRef.current = null
|
||||
}
|
||||
|
||||
if (pendingScrollFrameRef.current !== null) {
|
||||
window.cancelAnimationFrame(pendingScrollFrameRef.current)
|
||||
pendingScrollFrameRef.current = null
|
||||
}
|
||||
|
||||
visibilityObserverRef.current?.disconnect()
|
||||
visibilityObserverRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
if (
|
||||
autoScroll &&
|
||||
modeRef.current === "following-bottom" &&
|
||||
itemCountRef.current > 0
|
||||
) {
|
||||
scrollToEnd({ behavior: "auto" })
|
||||
return
|
||||
}
|
||||
|
||||
commitScrollState()
|
||||
}, [autoScroll, commitScrollState, scrollToEnd])
|
||||
|
||||
return {
|
||||
context,
|
||||
registerMessage,
|
||||
}
|
||||
}
|
||||
|
||||
export { useMessageScrollerController }
|
||||
@@ -0,0 +1,176 @@
|
||||
// Vendored from @shadcn/react 0.3.0 (MIT; see LICENSE in site/src/vendor).
|
||||
// Upstream: https://github.com/shadcn-ui/ui/tree/b1c580c/packages/react/src/message-scroller
|
||||
// Local deviations must be marked LOCAL CHANGE.
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
import {
|
||||
areScrollStatesEqual,
|
||||
createMessageScrollerStore,
|
||||
createMessageScrollerVisibilityStore,
|
||||
} from "./stores"
|
||||
import { EMPTY_MESSAGE_SCROLLER_SCROLLABLE } from "./types"
|
||||
import type {
|
||||
MessageScrollerMode,
|
||||
MessageScrollerScrollable,
|
||||
MessageScrollerScrollOptions,
|
||||
MessageScrollerStore,
|
||||
MessageScrollerVisibilityStore,
|
||||
} from "./types"
|
||||
|
||||
// Shared mutable ref bag for one MessageScroller, closed over by both the
|
||||
// controller and the commands so writes are visible across them without prop
|
||||
// threading. stateStore and visibilityStore fan out via useSyncExternalStore.
|
||||
type MessageScrollerRefs = {
|
||||
autoScrollRef: React.RefObject<boolean>
|
||||
autoscrollingRef: React.RefObject<boolean>
|
||||
autoscrollingTimeoutRef: React.RefObject<number | null>
|
||||
streamingTurnRef: React.RefObject<HTMLElement | null>
|
||||
contentRef: React.RefObject<HTMLDivElement | null>
|
||||
defaultScrollPositionAppliedRef: React.RefObject<boolean>
|
||||
firstItemRef: React.RefObject<HTMLElement | null>
|
||||
itemCountRef: React.RefObject<number>
|
||||
lastScrollTopRef: React.RefObject<number>
|
||||
messageElementsRef: React.RefObject<Map<string, HTMLElement>>
|
||||
modeRef: React.RefObject<MessageScrollerMode>
|
||||
pendingScrollFrameRef: React.RefObject<number | null>
|
||||
pendingScrollToMessageRef: React.RefObject<{
|
||||
messageId: string
|
||||
options?: MessageScrollerScrollOptions
|
||||
} | null>
|
||||
prependRestoreRef: React.RefObject<{
|
||||
element: HTMLElement
|
||||
viewportTop: number
|
||||
} | null>
|
||||
preserveScrollOnPrependRef: React.RefObject<boolean>
|
||||
rootRef: React.RefObject<HTMLDivElement | null>
|
||||
scrollEdgeThresholdRef: React.RefObject<number>
|
||||
scrollMarginRef: React.RefObject<number>
|
||||
scrollPreviousItemPeekRef: React.RefObject<number>
|
||||
spacerGapRef: React.RefObject<number>
|
||||
spacerHeightRef: React.RefObject<number>
|
||||
spacerRef: React.RefObject<HTMLDivElement | null>
|
||||
stateFrameRef: React.RefObject<number | null>
|
||||
stateStore: MessageScrollerStore<MessageScrollerScrollable>
|
||||
viewportRef: React.RefObject<HTMLDivElement | null>
|
||||
visibilityFrameRef: React.RefObject<number | null>
|
||||
visibilityObserverRef: React.RefObject<IntersectionObserver | null>
|
||||
visibilityStore: MessageScrollerVisibilityStore
|
||||
visibleMessageIdsRef: React.RefObject<Set<string>>
|
||||
handledScrollAnchorsRef: React.RefObject<WeakSet<HTMLElement>>
|
||||
}
|
||||
|
||||
// Builds the per-instance ref bag: the two external stores constructed once, and
|
||||
// the latest prop values mirrored onto refs each render so callbacks stay stable.
|
||||
function useMessageScrollerRefs({
|
||||
autoScroll,
|
||||
scrollEdgeThreshold,
|
||||
scrollMargin,
|
||||
scrollPreviousItemPeek,
|
||||
}: {
|
||||
autoScroll: boolean
|
||||
scrollEdgeThreshold: number
|
||||
scrollMargin: number
|
||||
scrollPreviousItemPeek: number
|
||||
}): MessageScrollerRefs {
|
||||
const autoScrollRef = React.useRef(autoScroll)
|
||||
const autoscrollingRef = React.useRef(false)
|
||||
const contentRef = React.useRef<HTMLDivElement | null>(null)
|
||||
const defaultScrollPositionAppliedRef = React.useRef(false)
|
||||
const scrollEdgeThresholdRef = React.useRef(scrollEdgeThreshold)
|
||||
const itemCountRef = React.useRef(0)
|
||||
const firstItemRef = React.useRef<HTMLElement | null>(null)
|
||||
// The scrollTop seen by the previous state commit, so follow-release can tell
|
||||
// a reader scrolling up from content growing past the live edge.
|
||||
const lastScrollTopRef = React.useRef(0)
|
||||
const modeRef = React.useRef<MessageScrollerMode>(
|
||||
autoScroll ? "following-bottom" : "free-scrolling"
|
||||
)
|
||||
const messageElementsRef = React.useRef(new Map<string, HTMLElement>())
|
||||
const pendingScrollToMessageRef = React.useRef<{
|
||||
messageId: string
|
||||
options?: MessageScrollerScrollOptions
|
||||
} | null>(null)
|
||||
// The row to hold steady on the next prepend: the first visible row, or a jump
|
||||
// target seeded by scrollToElement. restorePrependedAnchor reads only this.
|
||||
const prependRestoreRef = React.useRef<{
|
||||
element: HTMLElement
|
||||
viewportTop: number
|
||||
} | null>(null)
|
||||
// The turn held at the reading line so a reply streaming in below it can re-pin
|
||||
// it instead of letting scrollTop clamp it loose.
|
||||
const streamingTurnRef = React.useRef<HTMLElement | null>(null)
|
||||
const scrollPreviousItemPeekRef = React.useRef(scrollPreviousItemPeek)
|
||||
const preserveScrollOnPrependRef = React.useRef(true)
|
||||
const rootRef = React.useRef<HTMLDivElement | null>(null)
|
||||
const scrollMarginRef = React.useRef(scrollMargin)
|
||||
const pendingScrollFrameRef = React.useRef<number | null>(null)
|
||||
const spacerGapRef = React.useRef(0)
|
||||
const spacerHeightRef = React.useRef(0)
|
||||
const spacerRef = React.useRef<HTMLDivElement | null>(null)
|
||||
const stateFrameRef = React.useRef<number | null>(null)
|
||||
const stateStoreRef =
|
||||
React.useRef<MessageScrollerStore<MessageScrollerScrollable> | null>(null)
|
||||
const autoscrollingTimeoutRef = React.useRef<number | null>(null)
|
||||
const viewportRef = React.useRef<HTMLDivElement | null>(null)
|
||||
const visibilityFrameRef = React.useRef<number | null>(null)
|
||||
const visibilityObserverRef = React.useRef<IntersectionObserver | null>(null)
|
||||
const visibilityStoreRef =
|
||||
React.useRef<MessageScrollerVisibilityStore | null>(null)
|
||||
const visibleMessageIdsRef = React.useRef(new Set<string>())
|
||||
const handledScrollAnchorsRef = React.useRef(new WeakSet<HTMLElement>())
|
||||
|
||||
if (stateStoreRef.current === null) {
|
||||
stateStoreRef.current = createMessageScrollerStore(
|
||||
EMPTY_MESSAGE_SCROLLER_SCROLLABLE,
|
||||
areScrollStatesEqual
|
||||
)
|
||||
}
|
||||
|
||||
if (visibilityStoreRef.current === null) {
|
||||
visibilityStoreRef.current = createMessageScrollerVisibilityStore()
|
||||
}
|
||||
|
||||
// Track the latest prop values on every render so callbacks read fresh values
|
||||
// without being recreated (the useLatest pattern).
|
||||
autoScrollRef.current = autoScroll
|
||||
scrollEdgeThresholdRef.current = scrollEdgeThreshold
|
||||
scrollMarginRef.current = scrollMargin
|
||||
scrollPreviousItemPeekRef.current = scrollPreviousItemPeek
|
||||
|
||||
return {
|
||||
autoScrollRef,
|
||||
autoscrollingRef,
|
||||
autoscrollingTimeoutRef,
|
||||
streamingTurnRef,
|
||||
contentRef,
|
||||
defaultScrollPositionAppliedRef,
|
||||
firstItemRef,
|
||||
itemCountRef,
|
||||
lastScrollTopRef,
|
||||
messageElementsRef,
|
||||
modeRef,
|
||||
pendingScrollFrameRef,
|
||||
pendingScrollToMessageRef,
|
||||
prependRestoreRef,
|
||||
preserveScrollOnPrependRef,
|
||||
rootRef,
|
||||
scrollEdgeThresholdRef,
|
||||
scrollMarginRef,
|
||||
scrollPreviousItemPeekRef,
|
||||
spacerGapRef,
|
||||
spacerHeightRef,
|
||||
spacerRef,
|
||||
stateFrameRef,
|
||||
stateStore: stateStoreRef.current,
|
||||
viewportRef,
|
||||
visibilityFrameRef,
|
||||
visibilityObserverRef,
|
||||
visibilityStore: visibilityStoreRef.current,
|
||||
visibleMessageIdsRef,
|
||||
handledScrollAnchorsRef,
|
||||
}
|
||||
}
|
||||
|
||||
export { useMessageScrollerRefs }
|
||||
export type { MessageScrollerRefs }
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
// Vendored from @shadcn/react 0.3.0 (MIT; see LICENSE in site/src/vendor).
|
||||
// Upstream: https://github.com/shadcn-ui/ui/tree/b1c580c/packages/react/src/message-scroller
|
||||
// Local deviations must be marked LOCAL CHANGE.
|
||||
|
||||
import * as React from "react"
|
||||
|
||||
function useLatest<T>(value: T) {
|
||||
const ref = React.useRef(value)
|
||||
|
||||
ref.current = value
|
||||
|
||||
return ref
|
||||
}
|
||||
|
||||
export { useLatest }
|
||||
Vendored
+212
@@ -0,0 +1,212 @@
|
||||
// Vendored from @shadcn/react 0.3.0 (MIT; see LICENSE in site/src/vendor).
|
||||
// Upstream: https://github.com/shadcn-ui/ui/tree/b1c580c/packages/react/src/use-render
|
||||
// Local deviations must be marked LOCAL CHANGE.
|
||||
|
||||
// A poor man's version of base-ui useRender.
|
||||
// see https://base-ui.com/react/utils/use-render.
|
||||
// TODO: Replace if base-ui useRender is published as a package.
|
||||
import * as React from "react"
|
||||
|
||||
type RenderState = Record<string, unknown>
|
||||
|
||||
type RenderFunction<TState extends RenderState> = (
|
||||
props: Record<string, unknown>,
|
||||
state: TState
|
||||
) => React.ReactElement | null
|
||||
|
||||
type RenderProp<TState extends RenderState> =
|
||||
| React.ReactElement
|
||||
| RenderFunction<TState>
|
||||
|
||||
type StateAttributesMapping<TState extends RenderState> = Partial<{
|
||||
[K in keyof TState]: (
|
||||
value: TState[K]
|
||||
) => Record<string, string | undefined> | null | undefined
|
||||
}>
|
||||
|
||||
type UseRenderComponentProps<
|
||||
TElement extends React.ElementType,
|
||||
TState extends RenderState = RenderState,
|
||||
> = React.ComponentPropsWithRef<TElement> & {
|
||||
render?: RenderProp<TState>
|
||||
}
|
||||
|
||||
type UseRenderOptions<
|
||||
TElement extends React.ElementType,
|
||||
TState extends RenderState,
|
||||
> = {
|
||||
defaultTagName: TElement
|
||||
props?: React.ComponentPropsWithRef<TElement>
|
||||
render?: RenderProp<TState>
|
||||
state?: TState
|
||||
stateAttributesMapping?: StateAttributesMapping<TState>
|
||||
}
|
||||
|
||||
function useRender<
|
||||
TElement extends React.ElementType,
|
||||
TState extends RenderState = RenderState,
|
||||
>({
|
||||
defaultTagName,
|
||||
props,
|
||||
render,
|
||||
state = {} as TState,
|
||||
stateAttributesMapping,
|
||||
}: UseRenderOptions<TElement, TState>) {
|
||||
const elementProps = mergeProps<TElement>(
|
||||
getStateAttributes(state, stateAttributesMapping),
|
||||
props
|
||||
)
|
||||
|
||||
if (!render) {
|
||||
return React.createElement(defaultTagName, elementProps)
|
||||
}
|
||||
|
||||
if (typeof render === "function") {
|
||||
return render(elementProps, state)
|
||||
}
|
||||
|
||||
if (!React.isValidElement(render)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const renderProps = render.props as Record<string, unknown>
|
||||
const propsWithRenderProps = mergeProps<TElement>(elementProps, renderProps)
|
||||
const propsWithRef = {
|
||||
...propsWithRenderProps,
|
||||
ref: composeRefs(
|
||||
elementProps.ref as React.Ref<unknown> | undefined,
|
||||
renderProps.ref as React.Ref<unknown> | undefined
|
||||
),
|
||||
}
|
||||
|
||||
return React.cloneElement(
|
||||
render,
|
||||
propsWithRef as React.Attributes & Record<string, unknown>
|
||||
)
|
||||
}
|
||||
|
||||
function mergeProps<TElement extends React.ElementType>(
|
||||
...sources: Array<
|
||||
React.ComponentPropsWithRef<TElement> | Record<string, unknown> | undefined
|
||||
>
|
||||
) {
|
||||
const result: Record<string, unknown> = {}
|
||||
|
||||
for (const source of sources) {
|
||||
if (!source) {
|
||||
continue
|
||||
}
|
||||
|
||||
const sourceProps = source as Record<string, unknown>
|
||||
|
||||
for (const key of Object.keys(sourceProps)) {
|
||||
const value = sourceProps[key]
|
||||
|
||||
if (value === undefined) {
|
||||
continue
|
||||
}
|
||||
|
||||
const current = result[key]
|
||||
|
||||
if (key === "className") {
|
||||
result[key] = [current, value].filter(Boolean).join(" ")
|
||||
} else if (key === "style") {
|
||||
result[key] = {
|
||||
...(current as React.CSSProperties | undefined),
|
||||
...(value as React.CSSProperties | undefined),
|
||||
}
|
||||
} else if (key === "ref") {
|
||||
result[key] = composeRefs(
|
||||
current as React.Ref<unknown> | undefined,
|
||||
value as React.Ref<unknown> | undefined
|
||||
)
|
||||
} else if (
|
||||
isEventHandler(key) &&
|
||||
typeof current === "function" &&
|
||||
typeof value === "function"
|
||||
) {
|
||||
result[key] = composeEventHandlers(
|
||||
value as EventHandler,
|
||||
current as EventHandler
|
||||
)
|
||||
} else {
|
||||
result[key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result as React.ComponentPropsWithRef<TElement>
|
||||
}
|
||||
|
||||
function getStateAttributes<TState extends RenderState>(
|
||||
state: TState,
|
||||
mapping?: StateAttributesMapping<TState>
|
||||
) {
|
||||
const props: Record<string, unknown> = {}
|
||||
|
||||
for (const key of Object.keys(state) as Array<keyof TState>) {
|
||||
const value = state[key]
|
||||
const attributes = mapping?.[key]?.(value)
|
||||
|
||||
if (attributes) {
|
||||
Object.assign(props, attributes)
|
||||
continue
|
||||
}
|
||||
|
||||
if (key === "slot") {
|
||||
props["data-slot"] = value
|
||||
continue
|
||||
}
|
||||
|
||||
const attribute = `data-${String(key).replace(
|
||||
/[A-Z]/g,
|
||||
(letter) => `-${letter.toLowerCase()}`
|
||||
)}`
|
||||
|
||||
if (typeof value === "boolean") {
|
||||
props[attribute] = value ? "" : undefined
|
||||
} else if (value !== null && value !== undefined) {
|
||||
props[attribute] = String(value)
|
||||
}
|
||||
}
|
||||
|
||||
return props
|
||||
}
|
||||
|
||||
type EventHandler = (event: React.SyntheticEvent) => void
|
||||
|
||||
function composeEventHandlers(theirs: EventHandler, ours: EventHandler) {
|
||||
return function handleEvent(event: React.SyntheticEvent) {
|
||||
theirs(event)
|
||||
|
||||
if (!event.defaultPrevented) {
|
||||
ours(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isEventHandler(key: string) {
|
||||
return /^on[A-Z]/.test(key)
|
||||
}
|
||||
|
||||
function composeRefs<T>(
|
||||
...refs: Array<React.Ref<T> | undefined>
|
||||
): React.RefCallback<T> | undefined {
|
||||
const validRefs = refs.filter(Boolean)
|
||||
|
||||
if (validRefs.length === 0) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return (value) => {
|
||||
for (const ref of validRefs) {
|
||||
if (typeof ref === "function") {
|
||||
ref(value)
|
||||
} else if (ref) {
|
||||
ref.current = value
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { composeRefs, mergeProps, useRender, type UseRenderComponentProps }
|
||||
Reference in new issue
Block a user