diff --git a/.gitignore b/.gitignore index e6177998a11..4df76f12115 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/scripts/check_emdash.sh b/scripts/check_emdash.sh index bf8d5fb8d3a..7d910347269 100755 --- a/scripts/check_emdash.sh +++ b/scripts/check_emdash.sh @@ -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() { diff --git a/site/.oxlintrc.jsonc b/site/.oxlintrc.jsonc index 96c8bbd1975..92baf268d16 100644 --- a/site/.oxlintrc.jsonc +++ b/site/.oxlintrc.jsonc @@ -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": [ { diff --git a/site/biome.jsonc b/site/biome.jsonc index 1721a0853c5..1afdd26c8be 100644 --- a/site/biome.jsonc +++ b/site/biome.jsonc @@ -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" } diff --git a/site/package.json b/site/package.json index d27310e4a90..c7b1b1f4e54 100644 --- a/site/package.json +++ b/site/package.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", diff --git a/site/pnpm-lock.yaml b/site/pnpm-lock.yaml index 826754753a8..0e590ca0274 100644 --- a/site/pnpm-lock.yaml +++ b/site/pnpm-lock.yaml @@ -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 diff --git a/site/src/pages/AgentsPage/AgentChatPage.tsx b/site/src/pages/AgentsPage/AgentChatPage.tsx index ffc45979d55..7ae0bcdb030 100644 --- a/site/src/pages/AgentsPage/AgentChatPage.tsx +++ b/site/src/pages/AgentsPage/AgentChatPage.tsx @@ -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, diff --git a/site/src/pages/AgentsPage/AgentChatPageView.stories.tsx b/site/src/pages/AgentsPage/AgentChatPageView.stories.tsx index 93f959cc815..434aa0eba32 100644 --- a/site/src/pages/AgentsPage/AgentChatPageView.stories.tsx +++ b/site/src/pages/AgentsPage/AgentChatPageView.stories.tsx @@ -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, diff --git a/site/src/pages/AgentsPage/components/ChatConversation/ConversationTimeline.stories.tsx b/site/src/pages/AgentsPage/components/ChatConversation/ConversationTimeline.stories.tsx index 16bb3eab10c..8c5a944bcbc 100644 --- a/site/src/pages/AgentsPage/components/ChatConversation/ConversationTimeline.stories.tsx +++ b/site/src/pages/AgentsPage/components/ChatConversation/ConversationTimeline.stories.tsx @@ -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"; diff --git a/site/src/pages/AgentsPage/components/ChatConversation/ConversationTimeline.tsx b/site/src/pages/AgentsPage/components/ChatConversation/ConversationTimeline.tsx index ad1eacd000d..e5f2e85da8d 100644 --- a/site/src/pages/AgentsPage/components/ChatConversation/ConversationTimeline.tsx +++ b/site/src/pages/AgentsPage/components/ChatConversation/ConversationTimeline.tsx @@ -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"; diff --git a/site/src/pages/AgentsPage/components/ChatConversation/LiveStreamTail.tsx b/site/src/pages/AgentsPage/components/ChatConversation/LiveStreamTail.tsx index 9d8c8c0affe..bfd3bb088b0 100644 --- a/site/src/pages/AgentsPage/components/ChatConversation/LiveStreamTail.tsx +++ b/site/src/pages/AgentsPage/components/ChatConversation/LiveStreamTail.tsx @@ -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"; diff --git a/site/src/pages/AgentsPage/components/ChatConversation/TerminalStatusRow.stories.tsx b/site/src/pages/AgentsPage/components/ChatConversation/TerminalStatusRow.stories.tsx index 810b7760d20..09da43fa16b 100644 --- a/site/src/pages/AgentsPage/components/ChatConversation/TerminalStatusRow.stories.tsx +++ b/site/src/pages/AgentsPage/components/ChatConversation/TerminalStatusRow.stories.tsx @@ -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"; diff --git a/site/src/pages/AgentsPage/components/ChatMessageScroller.tsx b/site/src/pages/AgentsPage/components/ChatMessageScroller.tsx index 5498cb92e2f..924d04b632f 100644 --- a/site/src/pages/AgentsPage/components/ChatMessageScroller.tsx +++ b/site/src/pages/AgentsPage/components/ChatMessageScroller.tsx @@ -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 = { diff --git a/site/src/pages/AgentsPage/components/ChatPageContent.stories.tsx b/site/src/pages/AgentsPage/components/ChatPageContent.stories.tsx index 112a6c7e2b5..77450e615b7 100644 --- a/site/src/pages/AgentsPage/components/ChatPageContent.stories.tsx +++ b/site/src/pages/AgentsPage/components/ChatPageContent.stories.tsx @@ -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"; diff --git a/site/src/vendor/LICENSE b/site/src/vendor/LICENSE new file mode 100644 index 00000000000..fad4d887a68 --- /dev/null +++ b/site/src/vendor/LICENSE @@ -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. diff --git a/site/src/vendor/message-scroller/components.tsx b/site/src/vendor/message-scroller/components.tsx new file mode 100644 index 00000000000..af0e2ffe9b5 --- /dev/null +++ b/site/src/vendor/message-scroller/components.tsx @@ -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(null) +const MessageScrollerItemContext = + React.createContext(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 ( + + + {children} + + + ) +} + +function MessageScroller({ children, ...props }: MessageScrollerProps) { + const { setRootElement } = useMessageScrollerContext() + + return ( +
+ {children} +
+ ) +} + +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) { + syncAfterScroll() + onScroll?.(event) + } + + function handleWheel(event: React.WheelEvent) { + userScrollIntent() + onWheel?.(event) + } + + function handleTouchMove(event: React.TouchEvent) { + userScrollIntent() + onTouchMove?.(event) + } + + function handleKeyDown(event: React.KeyboardEvent) { + 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 ( +
+ {children} +
+ ) +} + +function MessageScrollerContent({ + "aria-relevant": ariaRelevant, + children, + ref, + role, + spacerClassName, + ...props +}: MessageScrollerContentProps) { + const { + handleContentChange, + handleResize, + setContentElement, + setSpacerElement, + } = useMessageScrollerContext() + const contentRef = React.useRef(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 ( +
+ {children} + + ) +} + +function MessageScrollerItem({ + messageId, + ref, + scrollAnchor = false, + ...props +}: MessageScrollerItemProps) { + const registerMessage = useMessageScrollerItemContext() + const elementRef = React.useRef(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 ( +
+ ) +} + +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) => { + 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 ?? Scroll to {direction}, + 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, +} diff --git a/site/src/vendor/message-scroller/geometry.ts b/site/src/vendor/message-scroller/geometry.ts new file mode 100644 index 00000000000..4348d9ab9bb --- /dev/null +++ b/site/src/vendor/message-scroller/geometry.ts @@ -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 +}): 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, +} diff --git a/site/src/vendor/message-scroller/index.ts b/site/src/vendor/message-scroller/index.ts new file mode 100644 index 00000000000..d6344c2df44 --- /dev/null +++ b/site/src/vendor/message-scroller/index.ts @@ -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" diff --git a/site/src/vendor/message-scroller/stores.ts b/site/src/vendor/message-scroller/stores.ts new file mode 100644 index 00000000000..563f444427e --- /dev/null +++ b/site/src/vendor/message-scroller/stores.ts @@ -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( + 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( + initialSnapshot: T, + isEqual: (a: T, b: T) => boolean +): MessageScrollerStore { + 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, +} diff --git a/site/src/vendor/message-scroller/types.ts b/site/src/vendor/message-scroller/types.ts new file mode 100644 index 00000000000..170307548b1 --- /dev/null +++ b/site/src/vendor/message-scroller/types.ts @@ -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 = { + 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 + 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 + syncAfterScroll: () => void + unobserveVisibility: () => void + userScrollIntent: () => void + viewportRef: React.RefObject + 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, +} diff --git a/site/src/vendor/message-scroller/use-message-scroller-commands.ts b/site/src/vendor/message-scroller/use-message-scroller-commands.ts new file mode 100644 index 00000000000..47212d522ad --- /dev/null +++ b/site/src/vendor/message-scroller/use-message-scroller-commands.ts @@ -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 } diff --git a/site/src/vendor/message-scroller/use-message-scroller-controller.ts b/site/src/vendor/message-scroller/use-message-scroller-controller.ts new file mode 100644 index 00000000000..827c47668fe --- /dev/null +++ b/site/src/vendor/message-scroller/use-message-scroller-controller.ts @@ -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, + 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( + (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( + () => ({ + 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 } diff --git a/site/src/vendor/message-scroller/use-message-scroller-refs.ts b/site/src/vendor/message-scroller/use-message-scroller-refs.ts new file mode 100644 index 00000000000..e2cf28fe16f --- /dev/null +++ b/site/src/vendor/message-scroller/use-message-scroller-refs.ts @@ -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 + autoscrollingRef: React.RefObject + autoscrollingTimeoutRef: React.RefObject + streamingTurnRef: React.RefObject + contentRef: React.RefObject + defaultScrollPositionAppliedRef: React.RefObject + firstItemRef: React.RefObject + itemCountRef: React.RefObject + lastScrollTopRef: React.RefObject + messageElementsRef: React.RefObject> + modeRef: React.RefObject + pendingScrollFrameRef: React.RefObject + pendingScrollToMessageRef: React.RefObject<{ + messageId: string + options?: MessageScrollerScrollOptions + } | null> + prependRestoreRef: React.RefObject<{ + element: HTMLElement + viewportTop: number + } | null> + preserveScrollOnPrependRef: React.RefObject + rootRef: React.RefObject + scrollEdgeThresholdRef: React.RefObject + scrollMarginRef: React.RefObject + scrollPreviousItemPeekRef: React.RefObject + spacerGapRef: React.RefObject + spacerHeightRef: React.RefObject + spacerRef: React.RefObject + stateFrameRef: React.RefObject + stateStore: MessageScrollerStore + viewportRef: React.RefObject + visibilityFrameRef: React.RefObject + visibilityObserverRef: React.RefObject + visibilityStore: MessageScrollerVisibilityStore + visibleMessageIdsRef: React.RefObject> + handledScrollAnchorsRef: React.RefObject> +} + +// 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(null) + const defaultScrollPositionAppliedRef = React.useRef(false) + const scrollEdgeThresholdRef = React.useRef(scrollEdgeThreshold) + const itemCountRef = React.useRef(0) + const firstItemRef = React.useRef(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( + autoScroll ? "following-bottom" : "free-scrolling" + ) + const messageElementsRef = React.useRef(new Map()) + 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(null) + const scrollPreviousItemPeekRef = React.useRef(scrollPreviousItemPeek) + const preserveScrollOnPrependRef = React.useRef(true) + const rootRef = React.useRef(null) + const scrollMarginRef = React.useRef(scrollMargin) + const pendingScrollFrameRef = React.useRef(null) + const spacerGapRef = React.useRef(0) + const spacerHeightRef = React.useRef(0) + const spacerRef = React.useRef(null) + const stateFrameRef = React.useRef(null) + const stateStoreRef = + React.useRef | null>(null) + const autoscrollingTimeoutRef = React.useRef(null) + const viewportRef = React.useRef(null) + const visibilityFrameRef = React.useRef(null) + const visibilityObserverRef = React.useRef(null) + const visibilityStoreRef = + React.useRef(null) + const visibleMessageIdsRef = React.useRef(new Set()) + const handledScrollAnchorsRef = React.useRef(new WeakSet()) + + 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 } diff --git a/site/src/vendor/message-scroller/utils.ts b/site/src/vendor/message-scroller/utils.ts new file mode 100644 index 00000000000..ce5797ea4b5 --- /dev/null +++ b/site/src/vendor/message-scroller/utils.ts @@ -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(value: T) { + const ref = React.useRef(value) + + ref.current = value + + return ref +} + +export { useLatest } diff --git a/site/src/vendor/use-render/index.ts b/site/src/vendor/use-render/index.ts new file mode 100644 index 00000000000..69517949095 --- /dev/null +++ b/site/src/vendor/use-render/index.ts @@ -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 + +type RenderFunction = ( + props: Record, + state: TState +) => React.ReactElement | null + +type RenderProp = + | React.ReactElement + | RenderFunction + +type StateAttributesMapping = Partial<{ + [K in keyof TState]: ( + value: TState[K] + ) => Record | null | undefined +}> + +type UseRenderComponentProps< + TElement extends React.ElementType, + TState extends RenderState = RenderState, +> = React.ComponentPropsWithRef & { + render?: RenderProp +} + +type UseRenderOptions< + TElement extends React.ElementType, + TState extends RenderState, +> = { + defaultTagName: TElement + props?: React.ComponentPropsWithRef + render?: RenderProp + state?: TState + stateAttributesMapping?: StateAttributesMapping +} + +function useRender< + TElement extends React.ElementType, + TState extends RenderState = RenderState, +>({ + defaultTagName, + props, + render, + state = {} as TState, + stateAttributesMapping, +}: UseRenderOptions) { + const elementProps = mergeProps( + 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 + const propsWithRenderProps = mergeProps(elementProps, renderProps) + const propsWithRef = { + ...propsWithRenderProps, + ref: composeRefs( + elementProps.ref as React.Ref | undefined, + renderProps.ref as React.Ref | undefined + ), + } + + return React.cloneElement( + render, + propsWithRef as React.Attributes & Record + ) +} + +function mergeProps( + ...sources: Array< + React.ComponentPropsWithRef | Record | undefined + > +) { + const result: Record = {} + + for (const source of sources) { + if (!source) { + continue + } + + const sourceProps = source as Record + + 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 | undefined, + value as React.Ref | 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 +} + +function getStateAttributes( + state: TState, + mapping?: StateAttributesMapping +) { + const props: Record = {} + + for (const key of Object.keys(state) as Array) { + 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( + ...refs: Array | undefined> +): React.RefCallback | 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 }