Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { JumpToLatest } from './jump-to-latest'
export { MothershipChatSkeleton } from './mothership-chat-skeleton'
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { JumpToLatest } from './jump-to-latest'
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/** @vitest-environment jsdom */

import { act } from 'react'
import { noop } from '@sim/utils/helpers'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { JumpToLatest } from '@/app/workspace/[workspaceId]/home/components/mothership-chat/components/jump-to-latest/jump-to-latest'

const FRAME_MS = 16

let atLatest = false
let root: Root
let container: HTMLDivElement
let scroller: HTMLDivElement
/** Stable across renders, like the chat's refs and its `useCallback` reader. */
const scrollElementRef: { current: HTMLElement | null } = { current: null }
const contentRef: { current: HTMLElement | null } = { current: null }
const isAtLatest = () => atLatest

function render(chatId: string | undefined) {
act(() =>
root.render(
<JumpToLatest
chatId={chatId}
scrollElementRef={scrollElementRef}
contentRef={contentRef}
enabled
isAtLatest={isAtLatest}
onJump={noop}
/>
)
)
}

/** The transcript scrolls (a landing step, a user scroll) and the next frame reads it. */
function scrollTo(nowAtLatest: boolean) {
atLatest = nowAtLatest
act(() => {
scroller.dispatchEvent(new Event('scroll'))
vi.advanceTimersByTime(FRAME_MS * 2)
})
}

const isShown = () => container.querySelector('button') !== null

describe('JumpToLatest', () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ['requestAnimationFrame', 'cancelAnimationFrame'] })
vi.stubGlobal(
'ResizeObserver',
class {
observe() {}
disconnect() {}
}
)
atLatest = false
scroller = document.createElement('div')
scrollElementRef.current = scroller
container = document.createElement('div')
document.body.append(scroller, container)
root = createRoot(container)
})

afterEach(() => {
act(() => root.unmount())
scroller.remove()
container.remove()
vi.useRealTimers()
})

it('stays hidden while a chat lands, and shows once the user leaves the latest message', () => {
render('chat-a')
scrollTo(false)
expect(isShown()).toBe(false)

scrollTo(true)
scrollTo(false)

expect(isShown()).toBe(true)
})

it('shows once the user scrolls a chat whose landing stopped short of the latest message', () => {
render('chat-a')
scrollTo(false)
expect(isShown()).toBe(false)

// At the very top an upward wheel moves nothing, so no scroll event follows it.
act(() => {
scroller.dispatchEvent(new WheelEvent('wheel', { deltaY: -120 }))
vi.advanceTimersByTime(FRAME_MS * 2)
})

expect(isShown()).toBe(true)
})

it('hides on a chat switch until the new chat has landed', () => {
render('chat-a')
scrollTo(true)
scrollTo(false)
expect(isShown()).toBe(true)

render('chat-b')
scrollTo(false)
expect(isShown()).toBe(false)

scrollTo(true)
scrollTo(false)
expect(isShown()).toBe(true)
})

it('keeps showing when a pending chat adopts its id', () => {
render(undefined)
scrollTo(true)
scrollTo(false)
expect(isShown()).toBe(true)

render('chat-persisted')
expect(isShown()).toBe(true)

scrollTo(false)
expect(isShown()).toBe(true)
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
'use client'

import { type MouseEvent, type RefObject, useEffect, useRef, useState } from 'react'
import { Chip, Tooltip } from '@sim/emcn'
import { ArrowDown } from '@sim/emcn/icons'

const LABEL = 'Jump to latest'
/** Inputs that mean the user is scrolling the transcript themselves, which ends any landing. */
const USER_SCROLL_EVENTS = ['wheel', 'touchstart', 'keydown', 'pointerdown'] as const

interface JumpToLatestProps {
/** The chat shown. A different chat lands at its latest message before the button can show. */
chatId: string | undefined
scrollElementRef: RefObject<HTMLElement | null>
/** The transcript's sizer, whose growth moves the bottom away without a scroll. */
contentRef: RefObject<HTMLElement | null>
/** False while the transcript has no rows or its first landing at the bottom is held back. */
enabled: boolean
/** Whether the latest content is in view, read once per frame. */
isAtLatest: () => boolean
/**
* Scrolls to the latest message and resumes following. `fromKeyboard` asks the caller to
* move focus on, since the focused button unmounts.
*/
onJump: (fromKeyboard: boolean) => void
}

/**
* Floating control that returns a scrolled-away transcript to its latest message. Renders on a
* zero-height anchor between the transcript and the composer, outside the transcript's edge
* mask, so the fade never dims it and it never covers the composer.
*
* Owns its own visibility state so a scroll re-renders only this control. Each chat switch
* remounts it, so the switch's landing at the latest message never shows it on the way down.
*/
export function JumpToLatest({ chatId, ...controlProps }: JumpToLatestProps) {
const [landingChatId, setLandingChatId] = useState(chatId)
const [landing, setLanding] = useState(0)
if (landingChatId !== chatId) {
setLandingChatId(chatId)
// A pending chat adopting its id is the same conversation, which does not land again.
if (landingChatId !== undefined) setLanding(landing + 1)
}
return <JumpToLatestControl key={landing} {...controlProps} />
}

function JumpToLatestControl({
scrollElementRef,
contentRef,
enabled,
isAtLatest,
onJump,
}: Omit<JumpToLatestProps, 'chatId'>) {
/**
* Whether this chat has finished landing: its latest message has been in view, or the user has
* scrolled it themselves, so a landing that stops short still offers the jump.
*/
const landedRef = useRef(false)
const [away, setAway] = useState(false)

useEffect(() => {
const scrollElement = scrollElementRef.current
if (!enabled || !scrollElement) return

let frame = 0
/**
* One read per frame, after the frame's scroll writes and gesture listeners: a wheel or key
* that stops following reaches its own listener in an order this one does not control.
*/
const schedule = () => {
if (frame) return
frame = requestAnimationFrame(() => {
frame = 0
const atLatest = isAtLatest()
if (atLatest) landedRef.current = true
setAway(landedRef.current && !atLatest)
})
}

const endLanding = () => {
landedRef.current = true
schedule()
}
Comment thread
mzxchandra marked this conversation as resolved.
Resolved

schedule()
scrollElement.addEventListener('scroll', schedule, { passive: true })
for (const type of USER_SCROLL_EVENTS) {
scrollElement.addEventListener(type, endLanding, { passive: true })
}
const observer = new ResizeObserver(schedule)
observer.observe(scrollElement)
if (contentRef.current) observer.observe(contentRef.current)

return () => {
cancelAnimationFrame(frame)
scrollElement.removeEventListener('scroll', schedule)
for (const type of USER_SCROLL_EVENTS) scrollElement.removeEventListener(type, endLanding)
observer.disconnect()
setAway(false)
}
}, [enabled, scrollElementRef, contentRef, isAtLatest])

if (!enabled || !away) return null

/**
* Hides in the jump's own render: rows revealed by a long jump can hold the main thread for
* frames, and the per-frame check would only catch up after them.
*/
const handleClick = (event: MouseEvent<HTMLButtonElement>) => {
const fromKeyboard = event.currentTarget.matches(':focus-visible')
setAway(false)
onJump(fromKeyboard)
}

return (
<div className='relative h-0 shrink-0'>
<div className='-translate-x-1/2 fade-in-0 absolute bottom-6 left-1/2 animate-in duration-150 ease-out motion-reduce:animate-none'>
<Tooltip.Root>
<Tooltip.Trigger asChild>
<Chip
variant='border-shadow'
shape='round'
mobileIconOnly
aria-label={LABEL}
leftAdornment={<ArrowDown className='size-[14px] shrink-0 text-[var(--text-icon)]' />}
onClick={handleClick}
/>
</Tooltip.Trigger>
<Tooltip.Content side='top'>{LABEL}</Tooltip.Content>
</Tooltip.Root>
</div>
</div>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ import {
} from '@/app/workspace/[workspaceId]/home/components/message-content/components/special-tags'
import type { SearchIntegrationConnectionProps } from '@/app/workspace/[workspaceId]/home/components/message-content/components/special-tags/search-integration-connection'
import { watchLabel } from '@/app/workspace/[workspaceId]/home/components/message-content/components/watch-activity/watch-activity'
import {
JumpToLatest,
MothershipChatSkeleton,
} from '@/app/workspace/[workspaceId]/home/components/mothership-chat/components'
import {
prepareCopyableMarkdown,
toCopyableMarkdown,
Expand Down Expand Up @@ -87,7 +91,6 @@ import type {
import { useOptionalWorkspacePermissionsContext } from '@/app/workspace/[workspaceId]/providers/workspace-permissions-provider'
import { useAutoScroll } from '@/hooks/use-auto-scroll'
import type { ChatContext } from '@/stores/panel'
import { MothershipChatSkeleton } from './components/mothership-chat-skeleton'
import { shouldShowAssistantMessageActions } from './message-actions-visibility'

interface MothershipChatProps {
Expand Down Expand Up @@ -817,10 +820,12 @@ export function MothershipChat({
scrollElementRef,
virtualizer,
})
const { ref: autoScrollRef, release: releaseAutoScroll } = useAutoScroll(
isStreamActive || lastRowAnimating,
find.isOpen
)
const {
ref: autoScrollRef,
release: releaseAutoScroll,
follow: followAutoScroll,
isAtLatest,
} = useAutoScroll(isStreamActive || lastRowAnimating, find.isOpen)
const setScrollElement = useCallback(
(el: HTMLDivElement | null) => {
scrollElementRef.current = el
Expand Down Expand Up @@ -918,6 +923,15 @@ export function MothershipChat({
[messageIndexById, releaseAutoScroll, virtualizer]
)

/** A keyboard jump moves focus to the default composer, or the chat when a surface brings its own. */
const jumpToLatest = (fromKeyboard: boolean) => {
virtualizer.scrollToIndex(lastIndex, { align: 'end' })
followAutoScroll()
if (!fromKeyboard) return
if (userInputRef.current) userInputRef.current.focus()
else containerRef.current?.focus()
}

/** Quotes attach to the default composer; a surface that brings its own composer opts out. */
const { pendingQuote, clearPendingQuote, replyChipRef } = useQuoteSelection({
enabled: !composer && !isLoading,
Expand Down Expand Up @@ -1161,6 +1175,15 @@ export function MothershipChat({
)}
</div>

<JumpToLatest
chatId={chatId}
scrollElementRef={scrollElementRef}
contentRef={sizerRef}
enabled={hasMessages && !initialScrollBlocked}
isAtLatest={isAtLatest}
onJump={jumpToLatest}
/>

<ComposerScrollArea
className={cn(styles.footer, animateInput && 'animate-slide-in-bottom')}
onAnimationEnd={animateInput ? onInputAnimationEnd : undefined}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ export interface UserInputHandle {
/** Attaches an excerpt of an earlier chat message for the next message to reply to,
* then focuses the input. Attaching the same excerpt again is a no-op. */
attachQuote: (quote: ChatQuoteContext) => void
/** Focuses the input with the caret after any draft already typed. */
focus: () => void
}

function isChatQuote(context: ChatContext): context is ChatQuoteContext {
Expand Down Expand Up @@ -432,6 +434,7 @@ const UserInputImpl = forwardRef<UserInputHandle, UserInputProps>(function UserI
editorRef.current.focusAtEnd()
},
attachQuote: (quote: ChatQuoteContext) => editorRef.current.attachQuote(quote),
focus: () => editorRef.current.focusAtEnd(),
}),
[]
)
Expand Down
Loading
Loading