From a167c44cd1644f2f621355f1d4b32330afd4c989 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Tue, 20 Oct 2026 07:38:30 -0700 Subject: [PATCH 01/68] feat(app): animate the timeline like iOS while a session runs While the timeline follows its end, rows grow to their measured height on one spring instead of landing, and the end rides that growth onto the composer. A row leaving near the end fades where it was while the rows above close its gap. Space the composer frees while rows grow is held under the last row for the reply to rise into. Scroll offsets stay on the layout grid, a prompt sent from the composer flies into its bubble, and Working and the background hint fade in their lane without doubling up. --- .../e2e/regression/timeline-geometry.spec.ts | 23 +- .../app/src/session/timeline/interaction.ts | 23 +- .../src/session/timeline/message-timeline.tsx | 177 +++++-- .../src/session/timeline/row-growth.test.ts | 119 +++++ .../app/src/session/timeline/row-growth.ts | 156 +++++++ .../app/src/session/timeline/send-flight.ts | 163 +++++++ .../app/src/session/timeline/virtualizer.tsx | 439 ++++++++++++++++-- .../session-ui/src/components/basic-tool.css | 13 + .../src/components/message-part.css | 13 + 9 files changed, 1040 insertions(+), 86 deletions(-) create mode 100644 packages/app/src/session/timeline/row-growth.test.ts create mode 100644 packages/app/src/session/timeline/row-growth.ts create mode 100644 packages/app/src/session/timeline/send-flight.ts diff --git a/packages/app/e2e/regression/timeline-geometry.spec.ts b/packages/app/e2e/regression/timeline-geometry.spec.ts index a42dcc59358e..14a22f35a90b 100644 --- a/packages/app/e2e/regression/timeline-geometry.spec.ts +++ b/packages/app/e2e/regression/timeline-geometry.spec.ts @@ -65,9 +65,11 @@ test("remeasures a recent explored context group before the next paint", async ( // Samples every painted frame after the click until the open group's row holds its measured content, so a // stale row height shows up as overlap before the virtualizer catches up. + type Sample = { frame: number; allocated: number; overlap: number; expanded: string | null; measured: boolean } + const samples = await page.evaluate( ({ contextSelector, following }) => - new Promise<{ frame: number; overlap: number; expanded: string | null; measured: boolean }[]>((resolve) => { + new Promise((resolve) => { const context = document.querySelector(contextSelector) const text = document.querySelector(following) const scroller = context?.closest(".scroll-view__viewport") @@ -78,18 +80,17 @@ test("remeasures a recent explored context group before the next paint", async ( if (!scroller || !trigger || !contextRow || !virtualRow || !textRow) throw new Error("missing regression nodes") scroller.scrollTop = scroller.scrollHeight - const samples: { frame: number; overlap: number; expanded: string | null; measured: boolean }[] = [] + const samples: Sample[] = [] const capture = (frame: number) => { const content = context!.querySelector('[data-slot="collapsible-content"]') const allocated = virtualRow.getBoundingClientRect().height const inner = virtualRow.firstElementChild?.getBoundingClientRect().height ?? Infinity + const shown = Math.min(contextRow.getBoundingClientRect().bottom, virtualRow.getBoundingClientRect().bottom) samples.push({ frame, - overlap: Math.max( - 0, - Math.round((contextRow.getBoundingClientRect().bottom - textRow.getBoundingClientRect().top) * 10) / 10, - ), + allocated, + overlap: Math.max(0, Math.round((shown - textRow.getBoundingClientRect().top) * 10) / 10), expanded: trigger.getAttribute("aria-expanded"), measured: !!content && @@ -118,6 +119,8 @@ test("remeasures a recent explored context group before the next paint", async ( expect(samples[0]?.overlap).toBe(0) expect(samples.filter((sample) => sample.frame >= 1 && sample.overlap > 0.5)).toEqual([]) + // The row opens steadily onto its measured height, never shrinking back on the way. + expect(samples.filter((sample, index) => sample.allocated < (samples[index - 1]?.allocated ?? 0) - 0.5)).toEqual([]) expect(samples.at(-1)).toMatchObject({ expanded: "true", measured: true }) }) @@ -250,6 +253,9 @@ test("keeps a file diff anchored while it expands and collapses", async ({ page await expect.poll(bottom).toBeLessThanOrEqual(1) } + // Following the end, the row eases onto its new height; let it land before scrolling away. + await expect.poll(measured).toBeLessThanOrEqual(1) + // Scrolled away from the tail, the header keeps its viewport position. await expect .poll(() => scroller.evaluate((element) => element.scrollHeight - element.clientHeight)) @@ -551,7 +557,10 @@ for (const failed of [false, true]) { expect(frames.some((frame) => frame.working && frame.prompt === undefined)).toBe(false) const positions = frames.flatMap((frame) => (frame.prompt === undefined ? [] : [frame.prompt])) expect(positions.length).toBeGreaterThan(0) - expect(new Set(positions).size).toBe(1) + // The prompt grows in at the followed end and rises into place: it never moves back down or jumps, including + // when Working shows. + const steps = positions.slice(1).map((position, index) => position - positions[index]!) + expect(steps.filter((step) => step > 0.5 || step < -40)).toEqual([]) } finally { release.resolve() await observation.dispose() diff --git a/packages/app/src/session/timeline/interaction.ts b/packages/app/src/session/timeline/interaction.ts index 9bc18cfec3cb..c6907bcf0fbc 100644 --- a/packages/app/src/session/timeline/interaction.ts +++ b/packages/app/src/session/timeline/interaction.ts @@ -356,9 +356,14 @@ export function createSessionTimelineInteraction(session: SessionModel) { fill() }, ) - createResizeObserver( - () => state.refs.dock, - (_rect, _element, entry) => { + createEffect(() => { + const dock = state.refs.dock + + if (!dock) return + + // createResizeObserver deduplicates on rounded content-box dimensions, + // dropping the subpixel updates at the tail of the composer's spring. + const observer = new ResizeObserver(([entry]) => { // The activity pill floats above the region out of flow, so only the docks, queue and composer count here. const dpr = window.devicePixelRatio || 1 const next = Math.round((entry.borderBoxSize[0]?.blockSize ?? 0) * dpr) / dpr @@ -366,9 +371,10 @@ export function createSessionTimelineInteraction(session: SessionModel) { if (next === state.inset) return const delta = next - state.inset - // Measured before the new inset applies: a shrinking region also keeps a reader whose end it uncovers. + // Measured before the new inset applies: a shrinking region also keeps a reader whose end it uncovers. A + // following timeline keeps its own end, without landing rows that are still growing. const stick = scroller - ? pinned() || scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop < 10 + Math.max(0, -delta) + ? !pinned() && scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop < 10 + Math.max(0, -delta) : false setState("inset", next) @@ -377,8 +383,11 @@ export function createSessionTimelineInteraction(session: SessionModel) { if (scroller) scheduleScrollState(scroller) fill() - }, - ) + }) + + observer.observe(dock, { box: "border-box" }) + onCleanup(() => observer.disconnect()) + }) onCleanup(() => { if (historyContinuationFrame !== undefined) cancelAnimationFrame(historyContinuationFrame) diff --git a/packages/app/src/session/timeline/message-timeline.tsx b/packages/app/src/session/timeline/message-timeline.tsx index 1663dbc24dd9..3cbcbc16bcd5 100644 --- a/packages/app/src/session/timeline/message-timeline.tsx +++ b/packages/app/src/session/timeline/message-timeline.tsx @@ -1,7 +1,16 @@ -import { createEffect, createMemo, createSignal, on, onCleanup, Show, type Accessor, type JSX } from "solid-js" +import { + createComputed, + createEffect, + createMemo, + createSignal, + on, + onCleanup, + Show, + type Accessor, + type JSX, +} from "solid-js" import { createStore } from "solid-js/store" import { Predicate } from "effect" -import { createAnimatedPresence } from "@/runtime/animated-presence" import type { SessionUserActions } from "@opencode/session-ui/actions" import { Button } from "@opencode/ui/button" import { Icon } from "@opencode/ui/icon" @@ -119,8 +128,18 @@ export function MessageTimeline(props: MessageTimelineProps) { } } + // Motion state belongs to one session; another one starts from a fresh view. return ( - + + {(_id) => ( + + )} + ) } @@ -368,15 +387,6 @@ function MessageTimelineView( .findLast((ref) => blocking.has(ref.partID))?.partID }) - const [backgroundHintRef, setBackgroundHintRef] = createSignal() - - const backgroundHintPresence = createAnimatedPresence( - backgroundHintPartID, - () => backgroundHintRef() ?? null, - sessionID, - 1000, - ) - const showWorking = createMemo(() => { const id = sessionID() @@ -438,42 +448,53 @@ function MessageTimelineView( // Undelivered input waits below the work the model has seen, so live status moves into the row above it. const activityRow = createMemo(() => projection.rows().some((row) => Predicate.isTagged(row, "Activity"))) - - // The lane keeps its height while empty, so Working and the hint come and go without moving the rows around it. - const activity = () => ( -
-
- -
- -
-
- -
- -
-
+ // Set before the move renders, so the lane it moves to sees it. + let movedAt = -Infinity + createComputed(on(activityRow, () => (movedAt = performance.now()), { defer: true })) + + // Live status shows in one lane at a time. The lane it leaves fades it out where it was; the lane it moves to fades + // it in once that is done, so it never shows twice. The lane keeps its height while empty, so Working and the hint + // come and go without moving the rows around it. + function ActivityLane(lane: { here: () => boolean }) { + // Taking over from the other lane, status fades in once the copy there has faded out. + const delay = () => (performance.now() - movedAt < 100 ? 110 : undefined) + const working = createStatusFade(() => lane.here() && showWorking(), delay) + const hint = createStatusFade(() => lane.here() && !!backgroundHintPartID(), delay, 1000) + // Working keeps its width until a hint beside it leaves, so the hint never jumps sideways. + const holdWorking = createMemo((held) => working.present() || Boolean(held && hint.present())) + + return ( +
+
+ +
+ +
+
+ +
+ +
+
+
-
- ) + ) + } return ( {activity()}} + bottomSpacer={ !activityRow()} />} deferred={(row) => { if (!Predicate.isTagged(row, "AssistantPart") || row.group.type !== "part") return false const content = Timeline.resolveContent(messageByID().get(row.group.ref.messageID), row.group.ref.partID) @@ -485,7 +506,7 @@ function MessageTimelineView( when={Predicate.isTagged(row(), "Activity")} fallback={} > - {activity()} + true} /> )} header={ @@ -667,3 +688,69 @@ function MessageTimelineView( /> ) } + +// Status fades in and out from whatever opacity it has reached, so a flicker or a quick return never cuts it short. +// Present when it mounts, it starts at rest; `hold` keeps it at least that long once shown. +function createStatusFade(show: Accessor, delay: () => number | undefined, hold = 0) { + const [present, setPresent] = createSignal(show()) + let element: HTMLElement | undefined + let fade: Animation | undefined + let shownAt = performance.now() + let entering = false + + const run = (visible: boolean, wait = 0) => { + if (!element) return !visible && setPresent(false) + const from = entering ? "0" : getComputedStyle(element).opacity + entering = false + fade?.cancel() + + const current = element.animate([{ opacity: from }, { opacity: visible ? 1 : 0 }], { + duration: visible ? 150 : 110, + delay: wait, + easing: visible ? "cubic-bezier(.2,.8,.2,1)" : "cubic-bezier(.4,0,1,1)", + fill: "both", + }) + + fade = current + current.finished.then( + () => fade === current && !visible && setPresent(false), + () => undefined, + ) + } + + createEffect( + on( + show, + (visible) => { + if (visible) shownAt = performance.now() + + if (visible && !present()) { + entering = true + + return setPresent(true) + } + + const remaining = visible ? 0 : hold - (performance.now() - shownAt) + + if (remaining <= 0) return run(visible) + const timer = setTimeout(() => run(false), remaining) + onCleanup(() => clearTimeout(timer)) + }, + { defer: true }, + ), + ) + onCleanup(() => fade?.cancel()) + + return { + present, + ref(value: HTMLElement) { + element = value + const wait = delay() + + if (entering || (wait !== undefined && show())) { + entering = true + run(true, wait) + } + }, + } +} diff --git a/packages/app/src/session/timeline/row-growth.test.ts b/packages/app/src/session/timeline/row-growth.test.ts new file mode 100644 index 000000000000..50d95a5ec467 --- /dev/null +++ b/packages/app/src/session/timeline/row-growth.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, test } from "bun:test" +import { createRowGrowth } from "./row-growth" + +function setup() { + const wrapper = document.createElement("div") + const sizes: number[] = [] + const frames: { pending: number; held: number }[] = [] + + const growth = createRowGrowth({ + measure: () => {}, + resize: (key, size) => { + if (key !== "row") return false + sizes.push(size) + + return wrapper + }, + below: () => true, + settle: (state) => frames.push(state), + }) + + return { growth, sizes, wrapper, frames } +} + +async function settle(growth: ReturnType, frames: { held: number }[]) { + const deadline = performance.now() + 3000 + + while ((growth.target("row") !== undefined || frames.at(-1)?.held !== 0) && performance.now() < deadline) + await new Promise((resolve) => setTimeout(resolve, 16)) +} + +describe("row growth", () => { + test("eases a row on the layout grid, behind a soft edge that clears when it lands", async () => { + const { growth, sizes, wrapper, frames } = setup() + growth.grow("row", 0, 120.5) + expect(growth.target("row")).toBe(120.5) + + await new Promise((resolve) => setTimeout(resolve, 50)) + expect(wrapper.style.getPropertyValue("mask-image")).toContain("linear-gradient") + + await settle(growth, frames) + expect(growth.target("row")).toBeUndefined() + expect(sizes.at(-1)).toBe(120.5) + expect(sizes.every((size, index) => Number.isInteger(size * 64) && size >= (sizes[index - 1] ?? 0))).toBe(true) + expect(sizes.slice(0, -1).some((size) => !Number.isInteger(size))).toBe(true) + expect(wrapper.style.getPropertyValue("mask-image")).toBe("") + }) + + test("bends a running growth toward a new height instead of restarting it", async () => { + const { growth, sizes, frames } = setup() + growth.grow("row", 0, 100) + await new Promise((resolve) => setTimeout(resolve, 80)) + const reached = sizes.at(-1) ?? 0 + growth.grow("row", 0, 200) + + await new Promise((resolve) => setTimeout(resolve, 40)) + expect(sizes.at(-1)).toBeGreaterThanOrEqual(reached) + + await settle(growth, frames) + expect(sizes.at(-1)).toBe(200) + }) + + test("lands on a nearer target instead of passing it and coming back", async () => { + const { growth, sizes, frames } = setup() + growth.grow("row", 0, 200) + await new Promise((resolve) => setTimeout(resolve, 80)) + const near = (sizes.at(-1) ?? 0) + 2 + growth.grow("row", 0, near) + + await settle(growth, frames) + expect(sizes.at(-1)).toBe(near) + expect(sizes.every((size) => size <= near)).toBe(true) + }) + + test("reports once per frame how far the rows still have to grow", async () => { + const { growth, frames } = setup() + growth.grow("row", 0, 80) + + await settle(growth, frames) + expect(frames[0]!.pending).toBeGreaterThan(0) + expect(frames.at(-1)).toEqual({ pending: 0, held: 0 }) + expect(frames.every((frame, index) => frame.pending <= (frames[index - 1]?.pending ?? Infinity))).toBe(true) + }) + + test("closes a held gap on the same spring", async () => { + const { growth, frames } = setup() + growth.hold(40) + + await settle(growth, frames) + expect(frames[0]!.held).toBeGreaterThan(0) + expect(frames[0]!.held).toBeLessThanOrEqual(40) + expect(frames.at(-1)!.held).toBe(0) + expect(frames.every((frame, index) => frame.held <= (frames[index - 1]?.held ?? 40))).toBe(true) + }) + + test("fills a held gap with growth below it before closing the rest", async () => { + const { growth, sizes, frames } = setup() + growth.hold(40) + growth.grow("row", 0, 30) + + await settle(growth, frames) + expect(sizes.at(-1)).toBe(30) + expect(sizes.slice(0, -1).every((size, index) => frames[index]!.held === 40 - size)).toBe(true) + expect(frames.at(-1)!.held).toBe(0) + }) + + test("lands rows at once", () => { + const { growth, sizes, wrapper } = setup() + growth.grow("row", 10, 300) + growth.land("row", 280) + expect(sizes.at(-1)).toBe(280) + expect(growth.target("row")).toBeUndefined() + + growth.grow("row", 0, 90) + growth.finish() + expect(sizes.at(-1)).toBe(90) + expect(growth.target("row")).toBeUndefined() + expect(wrapper.style.getPropertyValue("mask-image")).toBe("") + }) +}) diff --git a/packages/app/src/session/timeline/row-growth.ts b/packages/app/src/session/timeline/row-growth.ts new file mode 100644 index 000000000000..a6ead53e3e60 --- /dev/null +++ b/packages/app/src/session/timeline/row-growth.ts @@ -0,0 +1,156 @@ +import { batch } from "solid-js" +import { frameLoop, Spring } from "@opencode/ui/motion" +import { motionTuning } from "@opencode/ui/motion-tuning" + +// Like the iOS transcript: while the timeline follows its end, a row's displayed height springs to its measured height. +export const growthSpring = motionTuning.spring("timeline.growth", { + label: "Row growth", + group: "Timeline", + presets: { + snappy: { duration: 0.32, bounce: 0 }, + smooth: { duration: 0.42, bounce: 0 }, + calm: { duration: 0.55, bounce: 0 }, + }, +}) + +const softEdge = 28 + +const grid = (value: number) => Math.round(value * 64) / 64 + +type Growth = { spring: Spring; start: number } + +/** + * Rows whose displayed height eases toward their measured height, and a gap left by a row near the end that closes on + * the same spring. Each frame `measure` reads layout before any writes, `resize` commits a displayed height and returns + * the row's clipping wrapper (false once the row has left the list), `below` tells whether a row is below the gap, and + * `settle` runs once after the sizes with how far the rows still have to grow and how much of the gap is still open. + */ +export function createRowGrowth(input: { + measure: () => void + resize: (key: string, size: number) => HTMLElement | false | undefined + below: (key: string) => boolean + settle: (state: { pending: number; held: number }) => void +}) { + const growths = new Map() + const fresh = new Set() + let held: Spring | undefined + let closing = false + let quiet = 0 + let stop: (() => void) | undefined + + const advance = (key: string, growth: Growth, dt: number) => { + const before = grid(growth.spring.value) + const value = growth.spring.step(dt) + const target = growth.spring.target + // A growth bent toward a nearer target keeps its speed and would pass it, then come back: it lands there instead. + const resting = growth.spring.resting || (target - before) * (target - value) <= 0 + const shown = resting ? growth.spring.target : grid(value) + const wrapper = input.resize(key, shown) + + if (wrapper === false || resting) growths.delete(key) + + if (wrapper) + paintEdge( + wrapper, + resting ? 0 : Math.min(softEdge, Math.abs(growth.spring.target - value), Math.abs(value - growth.start)), + ) + + if (held && wrapper !== false && input.below(key)) + held.value = Math.max(0, held.value - Math.max(0, shown - before)) + } + + const settle = () => { + let pending = 0 + growths.forEach((growth) => (pending += growth.spring.target - grid(growth.spring.value))) + input.settle({ pending, held: held ? Math.max(0, grid(held.value)) : 0 }) + } + + const step = (dt: number) => { + batch(() => growths.forEach((growth, key) => advance(key, growth, dt))) + // Wait briefly before closing what growth left of the gap so pauses between streamed chunks do not start and stop it. + quiet = growths.size ? 0 : quiet + dt + + if (held && (closing || quiet >= 0.12)) { + closing = true + held.step(dt) + } + + if (held?.resting) { + held = undefined + closing = false + } + + settle() + + if (growths.size > 0 || held) return true + stop = undefined + + return false + } + + const kick = () => { + const keys = [...fresh] + fresh.clear() + input.measure() + batch(() => + keys.forEach((key) => { + const growth = growths.get(key) + + if (growth) advance(key, growth, 1 / 60) + }), + ) + settle() + } + + return { + growing: () => growths.size > 0, + target: (key: string) => growths.get(key)?.spring.target, + grow(key: string, from: number, to: number) { + const running = growths.get(key) + const growth = running ?? { spring: Spring.fromDuration(from, growthSpring()), start: from } + growth.spring.set(to) + growths.set(key, growth) + stop ??= frameLoop.addMeasured(input.measure, step) + + if (running) return + + if (!fresh.size) queueMicrotask(kick) + fresh.add(key) + }, + hold(size: number) { + held ??= Spring.fromDuration(0, growthSpring()) + held.value += size + held.set(0) + stop ??= frameLoop.addMeasured(input.measure, step) + }, + land(key: string, size: number) { + growths.delete(key) + const wrapper = input.resize(key, size) + + if (wrapper) paintEdge(wrapper, 0) + }, + finish() { + fresh.clear() + stop?.() + stop = undefined + held = undefined + closing = false + batch(() => + growths.forEach((growth, key) => { + const wrapper = input.resize(key, growth.spring.target) + + if (wrapper) paintEdge(wrapper, 0) + }), + ) + growths.clear() + }, + } +} + +function paintEdge(wrapper: HTMLElement, fade: number) { + if (fade < 0.5) return wrapper.style.removeProperty("mask-image") + wrapper.style.setProperty( + "mask-image", + `linear-gradient(to bottom, #000 calc(100% - ${fade.toFixed(2)}px), transparent)`, + ) +} diff --git a/packages/app/src/session/timeline/send-flight.ts b/packages/app/src/session/timeline/send-flight.ts new file mode 100644 index 000000000000..954fde41a816 --- /dev/null +++ b/packages/app/src/session/timeline/send-flight.ts @@ -0,0 +1,163 @@ +import { frameLoop, prefersReducedMotion, Spring } from "@opencode/ui/motion" +import { growthSpring } from "./row-growth" + +type Rect = { x: number; y: number; w: number; h: number } + +type Flight = { text: HTMLElement; from: Rect; expire: ReturnType } + +// Like iOS: the sent text lifts out of the composer and becomes its bubble in the timeline. Both are copies drawn above +// the composer; the real composer clears and the real bubble stays hidden until the flight lands on it. +const waiting = new Map() + +let layer: HTMLDivElement | undefined + +/** Holds a copy of the composer's text where it is, before the composer clears, for the bubble that `id` becomes. */ +export function prepareSendFlight(id: string, editor: HTMLElement | undefined) { + if (!editor?.isConnected || prefersReducedMotion()) return + const range = document.createRange() + range.selectNodeContents(editor) + const box = range.getBoundingClientRect() + + if (box.width < 1 || box.height < 1) return + const style = getComputedStyle(editor) + const text = document.createElement("div") + text.setAttribute("aria-hidden", "true") + Object.assign(text.style, { + position: "fixed", + left: "0", + top: "0", + width: `${Math.ceil(box.width) + 1}px`, + transformOrigin: "0 0", + transform: `translate3d(${box.left}px, ${box.top}px, 0)`, + font: style.font, + letterSpacing: style.letterSpacing, + color: style.color, + whiteSpace: "pre-wrap", + overflowWrap: "anywhere", + }) + editor.childNodes.forEach((node) => text.append(node.cloneNode(true))) + text.querySelectorAll("[contenteditable]").forEach((node) => node.removeAttribute("contenteditable")) + + if (!layer?.isConnected) { + layer = document.createElement("div") + layer.setAttribute("aria-hidden", "true") + layer.dataset.sendFlight = "" + Object.assign(layer.style, { + position: "fixed", + inset: "0", + pointerEvents: "none", + zIndex: "1000", + contain: "strict", + }) + document.body.append(layer) + } + + layer.append(text) + waiting.get(id)?.text.remove() + waiting.set(id, { + text, + from: { x: box.left, y: box.top, w: box.width, h: box.height }, + expire: setTimeout(() => { + waiting.delete(id) + text + .animate([{ opacity: 1 }, { opacity: 0 }], { + duration: 110, + easing: "cubic-bezier(.4,0,1,1)", + fill: "forwards", + }) + .finished.finally(() => text.remove()) + }, 700), + }) +} + +/** Flies the waiting copy for `id` onto `bubble`. Returns false when nothing was waiting for it. */ +export function landSendFlight(id: string, bubble: HTMLElement) { + const flight = waiting.get(id) + + if (!flight) return false + waiting.delete(id) + clearTimeout(flight.expire) + + if (prefersReducedMotion()) { + flight.text.remove() + + return false + } + + const style = getComputedStyle(bubble) + const left = parseFloat(style.paddingLeft) || 0 + const right = parseFloat(style.paddingRight) || 0 + const top = parseFloat(style.paddingTop) || 0 + const bottom = parseFloat(style.paddingBottom) || 0 + + const start = { + x: flight.from.x - left, + y: flight.from.y - top, + w: flight.from.w + left + right, + h: flight.from.h + top + bottom, + } + + const host = document.createElement("div") + host.setAttribute("aria-hidden", "true") + host.dataset.component = "user-message" + host.dataset.flight = "" + Object.assign(host.style, { position: "fixed", left: "0", top: "0", transformOrigin: "0 0", opacity: "0" }) + // SAFETY: a deep clone has the same element type as its source. + const copy = bubble.cloneNode(true) as HTMLElement + Object.assign(copy.style, { width: "100%", height: "100%", margin: "0", boxSizing: "border-box" }) + host.append(copy) + flight.text.before(host) + bubble.style.opacity = "0" + + const spring = Spring.fromDuration(0, growthSpring()).set(1) + let last: DOMRect | undefined + let rect = bubble.getBoundingClientRect() + + const land = () => { + bubble.style.removeProperty("opacity") + host.remove() + flight.text.remove() + } + + frameLoop.addMeasured( + () => { + last = rect + rect = bubble.getBoundingClientRect() + }, + (dt) => { + if (!bubble.isConnected || rect.width < 1) { + land() + + return false + } + + const p = spring.step(dt) + const at = mix(start, { x: rect.left, y: rect.top, w: rect.width, h: rect.height }, p) + host.style.width = `${rect.width}px` + host.style.height = `${rect.height}px` + host.style.transform = `translate3d(${at.x}px, ${at.y}px, 0) scale(${at.w / rect.width}, ${at.h / rect.height})` + host.style.opacity = `${Math.min(1, p / 0.5)}` + + const words = mix( + flight.from, + { x: rect.left + left, y: rect.top + top, w: rect.width - left - right, h: flight.from.h }, + p, + ) + + flight.text.style.transform = `translate3d(${words.x}px, ${words.y}px, 0)` + flight.text.style.opacity = `${Math.max(0, 1 - p / 0.4)}` + + if (!spring.resting || !last || Math.abs(last.top - rect.top) > 0.5 || Math.abs(last.left - rect.left) > 0.5) + return true + land() + + return false + }, + ) + + return true +} + +function mix(a: Rect, b: Rect, p: number): Rect { + return { x: a.x + (b.x - a.x) * p, y: a.y + (b.y - a.y) * p, w: a.w + (b.w - a.w) * p, h: a.h + (b.h - a.h) * p } +} diff --git a/packages/app/src/session/timeline/virtualizer.tsx b/packages/app/src/session/timeline/virtualizer.tsx index 3eb0a56bc5c6..70392bebd843 100644 --- a/packages/app/src/session/timeline/virtualizer.tsx +++ b/packages/app/src/session/timeline/virtualizer.tsx @@ -28,11 +28,17 @@ import { createMediaQuery } from "@solid-primitives/media" import type { createTimelineProjection } from "./projection" import { observeElementOffsetReconnectAware } from "./observe-element-offset" import { filterVirtualIndexes } from "./virtual-items" -import { prefersReducedMotion } from "@opencode/ui/motion" import { holdLandingWidth } from "@/shell/panel-motion" +import { enter, prefersReducedMotion } from "@opencode/ui/motion" +import { landSendFlight } from "./send-flight" +import { createRowGrowth } from "./row-growth" const fallbackItemSize = 60 +const grid = (value: number) => Math.round(value * 64) / 64 + +const gridHeight = (element: Element) => grid(element.getBoundingClientRect().height) + // Reserved below the last row: a 36px lane for the live status row and its background hint, an 8px gap, then a 28px // activity pill and its 10px composer gap. Both come and go inside it, so neither moves the rows above. const tailSize = 82 @@ -139,15 +145,25 @@ export function createTimelineVirtualizer(input: Input) { const knownKeys = new Set(rowKeys()) const addedKeys = new Set() + // Rows added after the first one already shown, at the end or among the last rows. While following, they grow in + // instead of landing. + const arrivals = new Set() + + let listedKeys = rowKeys() const getItemKey = createMemo(() => { const keys = rowKeys() - keys - .filter((key) => !knownKeys.has(key)) - .forEach((key) => { - knownKeys.add(key) - addedKeys.add(key) - }) + const previous = listedKeys + listedKeys = keys + const head = keys.findIndex((key) => knownKeys.has(key)) + keys.forEach((key, index) => { + if (knownKeys.has(key)) return + knownKeys.add(key) + addedKeys.add(key) + + if (head < 0 || index > head) arrivals.add(key) + }) + closeRemoved(previous, keys) return (index: number) => keys[index] ?? `removed:${index}` }) @@ -191,12 +207,14 @@ export function createTimelineVirtualizer(input: Input) { }) const measuredElements = new WeakSet() + const observedElements = new WeakSet() let touchStart: number | undefined let touchTarget: EventTarget | null = null let touchNested = false let touchScrolling = false let touchAdjustment = 0 let pointerHeld = false + let userScrollAt = -Infinity let maxScroll = 0 let virtualContent: HTMLDivElement | undefined let rowLayer: HTMLDivElement | undefined @@ -218,7 +236,14 @@ export function createTimelineVirtualizer(input: Input) { let scrollTop = 0 let reportOffset: ((offset: number, scrolling: boolean) => void) | undefined let reportRect: ((rect: { width: number; height: number }) => void) | undefined + // The list root's last observed size; the composer region moving its edge does not resize it. + let rootRect: { width: number; height: number } | undefined let batchingColdSizes = false + let coldPending = coldBottomMount + // The whole-pixel offset last written, while a translate draws the fraction it dropped. + let wholeTop: number | undefined + // Sizes held back from rows still streaming, applied once their text completes. + const shrinks = new Map() const [headerHeight, setHeaderHeight] = createSignal(48) @@ -231,6 +256,8 @@ export function createTimelineVirtualizer(input: Input) { // inset spacer below the rows keeps consistent with the native scroll range. observeElementRect: (instance, callback) => { reportRect = (rect) => { + // Rows rewrap at a new width: their heights mean something else, so growth lands. + if (Math.abs(rect.width - (instance.scrollRect?.width ?? 0)) >= 1) landGrowth() const root = listRoot() batch(() => { // The container-responsive header can be 48px or 80px. @@ -242,6 +269,8 @@ export function createTimelineVirtualizer(input: Input) { } return observeElementRect(instance, (rect) => { + rootRect = rect + if (active()) reportRect?.(rect) }) }, @@ -281,7 +310,8 @@ export function createTimelineVirtualizer(input: Input) { }, initialOffset: () => (input.pinned() ? Number.MAX_SAFE_INTEGER : 0), initialMeasurementsCache: initialMeasurements, - estimateSize: () => fallbackItemSize, + // A row arriving at a followed end grows in from nothing, so it never paints first at the estimate. + estimateSize: (index) => (arrivals.has(getItemKey()(index)) && following() ? 0 : fallbackItemSize), // A newly observed element gets a real ResizeObserver box before paint. Reuse // its snapshot on attachment, but later explicit measurements must read layout // so deferred/rewrapped content cannot keep stale, clipped heights (TanStack/virtual#1183). @@ -295,7 +325,14 @@ export function createTimelineVirtualizer(input: Input) { measuredElements.add(element) const box = entry?.borderBoxSize[0] - if (box) return Math.round(box.blockSize) + if (box) { + const first = !observedElements.has(element) + observedElements.add(element) + + if (coldPending && first) settleColdBottom() + + return grid(box.blockSize) + } if (initial) { const size = instance.itemSizeCache.get(instance.options.getItemKey(instance.indexFromElement(element))) @@ -303,7 +340,7 @@ export function createTimelineVirtualizer(input: Input) { if (size !== undefined || coldPending) return size ?? fallbackItemSize } - return element.offsetHeight + return gridHeight(element) }, scrollToFn: (offset, options, instance) => { if (!active()) return @@ -312,6 +349,10 @@ export function createTimelineVirtualizer(input: Input) { setRendering("scrollAdjustment", 0) if (virtualContent) virtualContent.style.height = `${instance.getTotalSize()}px` + const root = listRoot() + + if (root && options.behavior !== "smooth") return writeScroll(root, offset + (options.adjustments ?? 0)) + clearRemainder() elementScroll(offset, options, instance) }, get getItemKey() { @@ -321,7 +362,9 @@ export function createTimelineVirtualizer(input: Input) { return input.pinned() ? "end" : "start" }, get followOnAppend() { - return input.pinned() + // Animated growth owns the followed offset. A second scroll-to-end here + // uses the previous DOM range while optimistic rows are still measuring. + return input.pinned() && !following() }, scrollEndThreshold: 80, get scrollMargin() { @@ -339,6 +382,277 @@ export function createTimelineVirtualizer(input: Input) { }) const resizeItem = virtualizer.resizeItem + + // Read at the start of each growth frame, before its writes: only a timeline resting on its end keeps it. + let endBefore = false + let viewport = 0 + // Space held under the last row so the end eases onto the composer instead of stopping there. + let lift = 0 + let ride: { from: number; gap: number; to: number } | undefined + let heldSpace = 0 + let insetSpacer: HTMLDivElement | undefined + const [shift, setShift] = createSignal({ rows: 0, size: 0 }) + // Whether the held gap is space the composer freed under the last row, rather than a row's place in the list. + let endGap = false + + // Each frame's displayed heights go in without TanStack's per-row scroll adjustment, then one write keeps the end + // in place for the whole frame, so the rows above glide. + const growth = createRowGrowth({ + measure: () => { + const root = listRoot() + endBefore = !!root && root.scrollHeight - root.clientHeight - root.scrollTop <= 1 + viewport = root?.clientHeight ?? 0 + }, + resize: (key, size) => { + const index = rowKeys().lastIndexOf(key) + + if (index < 0) return false + virtualizer.options.anchorTo = "start" + resizeItem(index, size) + virtualizer.options.anchorTo = input.pinned() ? "end" : "start" + + return virtualizer.elementsCache.get(key)?.parentElement ?? undefined + }, + below: (key) => rowKeys().lastIndexOf(key) >= shift().rows, + settle: (state) => { + rideEnd(state.pending) + + if (!state.held) endGap = false + + if (state.held !== shift().size) setShift((value) => ({ rows: state.held ? value.rows : 0, size: state.held })) + moveGhosts() + }, + }) + + // Growing past the composer, the end follows the rows' own progress onto it: the space below it closes as they + // finish growing, rather than the end travelling down and stopping dead at the composer's edge. + const rideEnd = (pending: number) => { + const root = listRoot() + const total = virtualizer.getTotalSize() + const target = total + pending + const room = (virtualizer.scrollRect?.height ?? 0) - virtualizer.options.scrollMargin + + if (pending < 1 || target <= room || !input.pinned()) { + ride = undefined + lift = 0 + } + + if (ride?.to !== target && lift + pending >= 1 && target > room && input.pinned()) + ride = { from: total, gap: Math.max(room - total, lift), to: target } + + if (ride) lift = ride.gap * (1 - Math.min(1, Math.max(0, (total - ride.from) / Math.max(1, ride.to - ride.from)))) + + holdSpace(grid(lift)) + + if (root && endBefore && input.pinned()) pinEnd(viewport) + } + + function pinEnd(viewport?: number) { + const root = listRoot() + + if (!root) return + writeScroll( + root, + topOffset() + virtualizer.getTotalSize() + bottomInset() + heldSpace - (viewport ?? root.clientHeight), + ) + } + + // Native scroll offsets snap to whole pixels. Each write takes the whole pixel below and draws the rest as a + // translate, so row edges stay on the 1/64 px grid instead of trembling with the rounding. + function writeScroll(root: HTMLDivElement, offset: number) { + const exact = Math.max(0, offset) + wholeTop = Math.floor(exact) + root.scrollTop = wholeTop + + if (wholeTop === exact) return virtualContent?.style.removeProperty("translate") + virtualContent?.style.setProperty("translate", `0 ${wholeTop - exact}px`) + } + + function clearRemainder() { + wholeTop = undefined + virtualContent?.style.removeProperty("translate") + } + + const holdSpace = (space: number) => { + if (space === heldSpace) return + heldSpace = space + + if (!space) return insetSpacer?.style.removeProperty("height") + insetSpacer?.style.setProperty("height", `calc(var(--session-timeline-inset) + ${space}px)`) + } + + // Lands every growing row and closes any gap or space held at the end at once. + const landGrowth = () => { + shrinks.forEach((size, key) => { + const index = rowKeys().lastIndexOf(key) + + if (index >= 0) resizeItem(index, size) + }) + shrinks.clear() + growth.finish() + ride = undefined + lift = 0 + holdSpace(0) + endGap = false + setShift({ rows: 0, size: 0 }) + } + + const commitSize = (index: number, key: string, size: number) => { + const measured = virtualizer.itemSizeCache.get(key) + const shown = measured ?? (arrivals.delete(key) ? 0 : undefined) + + // Streamed markdown can lose a line for a moment as it settles (a closing fence, say). While it streams, a followed + // row never shrinks below what it shows, and gives back what it lost once the text completes. A target that drops + // but stays above what is shown just bends the growth down to it. + if (shown !== undefined && size < shown && following() && streaming(rows()[index])) return shrinks.set(key, size) + shrinks.delete(key) + + if (shown === undefined || !grows(index, shown, size)) { + if (growth.target(key) !== undefined) return growth.land(key, size) + + return resizeItem(index, size) + } + + if (measured === undefined) { + resizeItem(index, 0) + virtualizer.itemSizeCache.set(key, 0) + const element = virtualizer.elementsCache.get(key) + + if (element && !textMessage(rows()[index])) enter(element, { duration: 200 }) + } + + growth.grow(key, shown, size) + } + + const grows = (index: number, shown: number, size: number) => { + const root = listRoot() + const item = virtualizer.measurementsCache[index] + const delta = Math.abs(size - shown) + + return ( + !!root && + !!item && + following() && + (delta >= 1 / 64 || growth.target(String(item.key)) !== undefined) && + delta <= root.clientHeight && + item.start + shown > root.scrollTop + ) + } + + function following() { + return input.pinned() && !coldPending && touchStart === undefined && !prefersReducedMotion() + } + + // A row near the end leaves while the timeline follows it: the offset clamps to the shorter end and the rows above + // would drop into its place in one frame. They start where they were and close the gap on the growth spring, while + // the row that left fades where it was. + function closeRemoved(previous: string[], keys: string[]) { + if (previous === keys) return + const remaining = new Set(keys) + const leaving = previous.filter((key) => !remaining.has(key)) + + if (!leaving.length) return + const first = previous.indexOf(leaving[0]!) + const removed = leaving.reduce((sum, key) => sum + (virtualizer.itemSizeCache.get(key) ?? 0), 0) + const root = listRoot() + const max = root ? root.scrollHeight - root.clientHeight : 0 + + const drop = + previous.length - first <= 4 && root && following() && max - root.scrollTop <= 1 ? Math.min(removed, max) : 0 + + if (drop >= 1) leaving.forEach((key) => fadeOutRow(key, previous[first - 1], drop)) + leaving.forEach((key) => { + knownKeys.delete(key) + addedKeys.delete(key) + arrivals.delete(key) + virtualizer.itemSizeCache.delete(key) + }) + + if (drop < 1) return + endGap = false + setShift((value) => ({ + rows: previous.slice(0, first).filter((key) => remaining.has(key)).length, + size: value.size + drop, + })) + growth.hold(drop) + queueMicrotask(() => { + if (input.pinned()) pinEnd() + }) + } + + const ghosts = new Map() + + function fadeOutRow(key: string, above: string | undefined, drop: number) { + const wrapper = virtualizer.elementsCache.get(key)?.parentElement + const anchor = above === undefined ? undefined : virtualizer.measurementsCache[rowKeys().lastIndexOf(above)] + + if (!wrapper?.isConnected || !virtualContent || !above || !anchor) return + // SAFETY: a deep clone has the same element type as its source. + const ghost = wrapper.cloneNode(true) as HTMLElement + const sources = [...wrapper.querySelectorAll("*")] + const copies = ghost.querySelectorAll("*") + wrapper.getAnimations({ subtree: true }).forEach((animation) => { + const target = animation.effect instanceof KeyframeEffect ? animation.effect.target : null + const copy = target ? copies[sources.indexOf(target)] : undefined + + if (!target || !copy) return + copy.style.animation = "none" + copy.style.opacity = getComputedStyle(target).opacity + }) + ghost.removeAttribute("data-timeline-key") + ghost.dataset.timelineLeaving = key + ghost.setAttribute("aria-hidden", "true") + ghost.inert = true + ghost.style.pointerEvents = "none" + ghost.style.top = `${parseFloat(wrapper.style.top) - drop}px` + virtualContent.append(ghost) + ghosts.set(ghost, { key: above, top: anchor.start - topOffset() - shift().size - drop }) + ghost + .animate([{ opacity: 1 }, { opacity: 0 }], { duration: 110, easing: "cubic-bezier(.4,0,1,1)", fill: "forwards" }) + .finished.finally(() => { + ghosts.delete(ghost) + ghost.remove() + }) + } + + const moveGhosts = () => + ghosts.forEach((anchor, ghost) => { + const index = rowKeys().lastIndexOf(anchor.key) + const item = virtualizer.measurementsCache[index] + const top = item && item.start - topOffset() - (index < shift().rows ? shift().size : 0) + + if (top === undefined || top === anchor.top) return + ghost.style.top = `${parseFloat(ghost.style.top) + top - anchor.top}px` + anchor.top = top + }) + + const textMessage = (row: TimelineRow.TimelineRow | undefined) => { + if (!Predicate.isTagged(row, "AssistantPart") || row.group.type !== "part") return + const message = input.projection.messageByID().get(row.group.ref.messageID) + + if (Timeline.resolveContent(message, row.group.ref.partID)?.type === "text") return message + } + + const streaming = (row: TimelineRow.TimelineRow | undefined) => { + const message = textMessage(row) + + return message?.type === "assistant" && message.time.completed === undefined + } + + createEffect(() => { + input.projection.messageByID() + shrinks.forEach((_, key) => { + if (streaming(rows()[rowKeys().lastIndexOf(key)])) return + shrinks.delete(key) + requestAnimationFrame(() => { + const element = virtualizer.elementsCache.get(key) + const index = rowKeys().lastIndexOf(key) + + if (element?.isConnected && index >= 0) virtualizer.resizeItem(index, gridHeight(element)) + }) + }) + }) + const pendingSizes = new Map() let resizeScheduled = false // Read the whole measurement delivery before committing reactive row sizes. @@ -349,8 +663,9 @@ export function createTimelineVirtualizer(input: Input) { if (!row) return const key = TimelineRow.key(row) + const known = growth.target(key) ?? virtualizer.itemSizeCache.get(key) - if ((virtualizer.itemSizeCache.get(key) ?? fallbackItemSize) === size) { + if ((known ?? (arrivals.has(key) ? undefined : fallbackItemSize)) === size) { pendingSizes.delete(index) return @@ -376,7 +691,7 @@ export function createTimelineVirtualizer(input: Input) { const row = rows()[index] if (!row || TimelineRow.key(row) !== value.key) return - resizeItem(index, value.size) + commitSize(index, value.key, value.size) // TanStack recalculates its range after each resize. Advance the // logical fold before deciding whether the next row needs anchoring. @@ -400,12 +715,22 @@ export function createTimelineVirtualizer(input: Input) { const root = listRoot() // Reopening a settled scroll-to-end operation can fight subsequent keyboard scrolling. - if (root && Math.abs(root.scrollHeight - root.clientHeight - root.scrollTop) > endEpsilon) + if (root && Math.abs(root.scrollHeight - root.clientHeight - root.scrollTop) > endEpsilon && !following()) virtualizer.scrollToEnd() }) } onCleanup(() => pendingSizes.clear()) + // Following stops, or the timeline is put away: growing rows land where the reader left them. + createEffect( + on( + () => input.pinned() && active(), + (following) => { + if (!following) landGrowth() + }, + { defer: true }, + ), + ) virtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item, delta, instance) => { // Prepended rows can resize more than once as deferred content mounts. Keep // compensating while they remain entirely above the visible content fold. @@ -471,7 +796,7 @@ export function createTimelineVirtualizer(input: Input) { // (and cannot unpin) or ends above the tool. Commit the real size first. const opened = virtualContent?.querySelector(`[data-index="${found.index}"]`) - if (opened) resizeItem(found.index, opened.offsetHeight) + if (opened) resizeItem(found.index, gridHeight(opened)) input.onUnpin() pinAnchor() @@ -509,6 +834,7 @@ export function createTimelineVirtualizer(input: Input) { } function prepareNavigation() { + landGrowth() releaseAnchor() if (touchStart === undefined) touchScrolling = false @@ -525,6 +851,7 @@ export function createTimelineVirtualizer(input: Input) { setRendering("scrollAdjustment", 0) if (virtualContent) virtualContent.style.height = `${virtualizer.getTotalSize()}px` + clearRemainder() elementScroll(Math.max(0, root.scrollTop + adjustment), {}, virtualizer) }) } @@ -582,6 +909,9 @@ export function createTimelineVirtualizer(input: Input) { const root = listRoot() if (!active() || !root?.isConnected) return + + // Already following its end (sending a prompt resumes it): rows growing in keep growing. + if (behavior !== "smooth" && following() && !rendering.anchor && !rendering.scrollAdjustment) return prepareNavigation() input.onPin() @@ -595,16 +925,31 @@ export function createTimelineVirtualizer(input: Input) { createEffect( on( bottomInset, - () => { + (inset, previous) => { const root = listRoot() - if (active() && root?.isConnected) reportRect?.({ width: root.offsetWidth, height: root.offsetHeight }) + if (!active() || !root?.isConnected) return + reportRect?.(rootRect ?? { width: root.offsetWidth, height: root.offsetHeight }) + + if (!input.pinned()) return + const freed = (previous ?? inset) - inset + + // The composer shrinks while rows grow in at the end (the queue closing as its prompt arrives): the end stays + // where it is rather than sinking with the composer only to be lifted by the reply. The space it frees is held + // under the last row for rows arriving below to rise into, and closes once nothing grows. + if (freed > 0 && following() && growth.growing() && (!shift().size || endGap)) { + setShift((value) => ({ rows: endGap ? value.rows : rows().length, size: value.size + freed })) + endGap = true + growth.hold(freed) + } + + // The composer region moved its edge: the followed end rides it in the same frame. + queueMicrotask(pinEnd) }, { defer: true }, ), ) - let coldPending = coldBottomMount let settleQueued = false let contentObserver: MutationObserver | undefined let viewportObserver: ResizeObserver | undefined @@ -617,7 +962,7 @@ export function createTimelineVirtualizer(input: Input) { // scrollToEnd computes its target from the DOM, not the new size cache. virtualContent.style.height = `${virtualizer.getTotalSize()}px` - if (Math.abs(root.scrollHeight - root.clientHeight - root.scrollTop) > endEpsilon) virtualizer.scrollToEnd() + pinEnd() // Report after core size adjustments finish so they cannot apply a delta // twice. This avoids waiting a frame for the native scroll event. @@ -629,7 +974,13 @@ export function createTimelineVirtualizer(input: Input) { return ( (rows().length > 0 && items.length === 0) || - items.some((item) => !virtualizer.elementsCache.get(item.key)?.isConnected) + items.some((item) => { + const element = virtualizer.elementsCache.get(item.key) + + // A synchronous attachment read can still see a tool's placeholder. + // Reveal only after its first browser layout delivery has been committed. + return !element?.isConnected || !observedElements.has(element) + }) ) } @@ -649,7 +1000,7 @@ export function createTimelineVirtualizer(input: Input) { // normal measureElement path skips reads while scrolling; this gate needs // current boxes before expanding the estimated range or revealing it. virtualizer.elementsCache.forEach((element) => { - if (element.isConnected) virtualizer.resizeItem(virtualizer.indexFromElement(element), element.offsetHeight) + if (element.isConnected) virtualizer.resizeItem(virtualizer.indexFromElement(element), gridHeight(element)) }) if (pendingSizes.size || pendingMeasurements()) return @@ -725,6 +1076,7 @@ export function createTimelineVirtualizer(input: Input) { // Upward input is the one intent geometry cannot recover: nudging up while still a pixel from // the end must stop following, even though the resulting position still looks like the end. const handleListWheel = (event: WheelEvent & { currentTarget: HTMLDivElement }) => { + userScrollAt = performance.now() releaseAnchor() input.onUserScroll(event.target) @@ -732,6 +1084,7 @@ export function createTimelineVirtualizer(input: Input) { } const handleListTouchStart = (event: TouchEvent) => { + userScrollAt = performance.now() clearTouchTarget() releaseAnchor() input.onUserScroll(event.target) @@ -816,6 +1169,7 @@ export function createTimelineVirtualizer(input: Input) { if (!isScrollKeyTarget(event.target, key)) return if (scrollKeyOwner(event.currentTarget, event.target, key) !== event.currentTarget) return + userScrollAt = performance.now() releaseAnchor() input.onUserScroll(event.currentTarget) @@ -832,6 +1186,13 @@ export function createTimelineVirtualizer(input: Input) { const previousMaxScroll = maxScroll scrollTop = root.scrollTop maxScroll = root.scrollHeight - root.clientHeight + + // Someone else moved the offset (the user, or the browser clamping it): the drawn remainder no longer applies. + if (wholeTop !== undefined && scrollTop !== wholeTop) clearRemainder() + + // Content the timeline moves under a resting pointer must not reveal the hover-only footers it passes; the pointer + // has to move again first. Scrolling the user drives keeps the native behavior. + if (!pointerHeld && performance.now() - userScrollAt > 250) root.dataset.hoverStale = "" const atEnd = maxScroll - scrollTop <= endEpsilon const arrived = scrollTop > previousTop + endEpsilon || maxScroll < previousMaxScroll @@ -850,6 +1211,14 @@ export function createTimelineVirtualizer(input: Input) { const initialRow = rowByKey().get(rowProps.rowKey)! const item = createMemo(() => virtualItemByKey().get(rowProps.rowKey) ?? initialItem) const row = createMemo(() => rowByKey().get(rowProps.rowKey) ?? rows()[item().index] ?? initialRow) + + const edges = createMemo(() => { + const top = + item().start - topOffset() - rendering.scrollAdjustment - (item().index < shift().rows ? shift().size : 0) + + return { top: grid(top), bottom: grid(top + item().size) } + }) + const [ready, setReady] = createSignal(initialItem.size <= fallbackItemSize || !props.deferred(initialRow)) let contentMeasureFrame: number | undefined @@ -866,10 +1235,10 @@ export function createTimelineVirtualizer(input: Input) { data-timeline-key={rowProps.rowKey} style={{ position: "absolute", - top: `${item().start - topOffset() - rendering.scrollAdjustment}px`, + top: `${edges().top}px`, left: "calc((100% - var(--panel-hold-width, 100%)) / 2)", width: "var(--panel-hold-width, 100%)", - height: `${item().size}px`, + height: `${edges().bottom - edges().top}px`, overflow: "clip", "overflow-clip-margin": Predicate.isTagged(row(), "TurnGap") ? undefined : "0.5px", }} @@ -877,12 +1246,21 @@ export function createTimelineVirtualizer(input: Input) {
{ element = value + const mounted = row() + + if (Predicate.isTagged(mounted, "UserMessage")) + queueMicrotask(() => { + const bubble = value.querySelector('[data-slot="user-message-text"]') + + if (bubble) landSendFlight(mounted.userMessageID, bubble) + }) if ( !Predicate.isTagged(row(), "UserMessage") || !addedKeys.has(rowProps.rowKey) || !input.pinned() || - coldPending + coldPending || + following() ) return // The optimistic row can paint before ResizeObserver corrects the tail estimates. @@ -890,9 +1268,9 @@ export function createTimelineVirtualizer(input: Input) { queueMicrotask(() => { if (!input.pinned() || !virtualContent?.isConnected) return virtualizer.elementsCache.forEach((item) => { - if (item.isConnected) virtualizer.resizeItem(virtualizer.indexFromElement(item), item.offsetHeight) + if (item.isConnected) virtualizer.resizeItem(virtualizer.indexFromElement(item), gridHeight(item)) }) - virtualizer.resizeItem(item().index, element.offsetHeight) + virtualizer.resizeItem(item().index, gridHeight(element)) virtualContent.style.height = `${virtualizer.getTotalSize()}px` virtualizer.scrollToEnd() }) @@ -961,6 +1339,7 @@ export function createTimelineVirtualizer(input: Input) { verticalScrollAdjustment={rendering.scrollAdjustment} onWheel={handleListWheel} onTouchStart={handleListTouchStart} + onPointerMove={(event) => delete event.currentTarget.dataset.hoverStale} onKeyDown={handleListKeyDown} onScroll={handleListScroll} onClick={input.onSelectionInteraction} @@ -1000,7 +1379,12 @@ export function createTimelineVirtualizer(input: Input) { {props.bottomSpacer}
-