From c293e53511e2297c2ddac308a9d55f885b65c950 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:08:03 -0600 Subject: [PATCH] fix(session-ui): drive the Pierre viewer render lifecycle with one state machine (#61938) --- .../component-tests/file-viewer.fixture.tsx | 23 + .../component-tests/file-viewer.spec.ts | 13 + packages/session-ui/src/components/file.tsx | 776 +++++++++--------- .../session-ui/src/pierre/file-runtime.ts | 87 -- .../src/pierre/render-machine.test.ts | 292 +++++++ .../session-ui/src/pierre/render-machine.ts | 381 +++++++++ 6 files changed, 1114 insertions(+), 458 deletions(-) create mode 100644 packages/session-ui/src/pierre/render-machine.test.ts create mode 100644 packages/session-ui/src/pierre/render-machine.ts diff --git a/packages/session-ui/component-tests/file-viewer.fixture.tsx b/packages/session-ui/component-tests/file-viewer.fixture.tsx index 62eaff18b00..828244a0649 100644 --- a/packages/session-ui/component-tests/file-viewer.fixture.tsx +++ b/packages/session-ui/component-tests/file-viewer.fixture.tsx @@ -47,6 +47,11 @@ export const controls = { keepHost: () => (first = document.querySelector("[data-testid='file-viewer-fixture'] diffs-container")), sameHost: () => first !== null && first === document.querySelector("[data-testid='file-viewer-fixture'] diffs-container"), + clearDiff: () => {}, + /** The inline min-height the viewer pins on its container while a draw replaces rows. */ + pinnedHeight: () => + document.querySelector("[data-testid='file-viewer-fixture'] div:has(> diffs-container)")?.style + .minHeight, } function host() { @@ -77,6 +82,24 @@ export function mountTextViewer(lines: number) { ) } +/** A plain diff of `lines` lines; `controls.clearDiff()` then makes both sides identical, which draws no rows. */ +export function mountChangingDiff(lines: number) { + const [after, setAfter] = createSignal(source(lines, 1)) + controls.clearDiff = () => setAfter(source(lines)) + render( + () => ( + + ), + host(), + ) +} + export function mountDiffViewer(lines: number) { const view = normalize({ file: "a.ts", before: source(lines), after: source(lines, 1), additions: 0, deletions: 0 }) render( diff --git a/packages/session-ui/component-tests/file-viewer.spec.ts b/packages/session-ui/component-tests/file-viewer.spec.ts index 466dbf00953..5836c50d4ce 100644 --- a/packages/session-ui/component-tests/file-viewer.spec.ts +++ b/packages/session-ui/component-tests/file-viewer.spec.ts @@ -119,6 +119,19 @@ story("does not end a drag that a fast second press replaced", async ({ mount, p await expect.poll(ends).toEqual([{ start: 10, end: 12 }]) }) +story("releases the pinned height when a diff becomes empty", async ({ mount, page }) => { + await mount("components-markdown--compact-result") + await page.evaluate(async (fixture) => (await import(fixture)).mountChangingDiff(40), fixture) + const root = page.getByTestId("file-viewer-fixture") + await expect(root.locator('[data-line-type="change-addition"]').first()).toBeVisible() + const pinned = () => page.evaluate(async (fixture) => (await import(fixture)).controls.pinnedHeight(), fixture) + await expect.poll(pinned).toBe("") + + await page.evaluate(async (fixture) => (await import(fixture)).controls.clearDiff(), fixture) + await expect(root.locator('[data-line-type="change-addition"]')).toHaveCount(0) + await expect.poll(pinned).toBe("") +}) + story("scrolls a virtualized diff to an off-screen selection", async ({ mount, page }) => { await mount("components-markdown--compact-result") await page.evaluate(async (fixture) => (await import(fixture)).mountDiffViewer(480), fixture) diff --git a/packages/session-ui/src/components/file.tsx b/packages/session-ui/src/components/file.tsx index 53f75253e43..fed6f0b6c85 100644 --- a/packages/session-ui/src/components/file.tsx +++ b/packages/session-ui/src/components/file.tsx @@ -1,6 +1,5 @@ import { sampledChecksum } from "@opencode/util/encode" import { - areFilesEqual, areOptionsEqual, DEFAULT_VIRTUAL_FILE_METRICS, type DiffLineAnnotation, @@ -36,15 +35,7 @@ import { createDefaultOptions, styleVariables } from "../pierre" import { markCommentedDiffLines, markCommentedFileLines } from "../pierre/commented-lines" import { fixDiffSelection, findDiffSide, type DiffSelectionSide } from "../pierre/diff-selection" import { createFileFind } from "../pierre/file-find" -import { - applyViewerScheme, - clearReadyWatcher, - createReadyWatcher, - getViewerHost, - getViewerRoot, - notifyShadowReady, - observeViewerScheme, -} from "../pierre/file-runtime" +import { applyViewerScheme, getViewerHost, getViewerRoot, observeViewerScheme } from "../pierre/file-runtime" import { findCodeSelectionSide, findDiffLineNumber, @@ -52,6 +43,21 @@ import { findFileLineNumber, readShadowLineSelection, } from "../pierre/file-selection" +import { + diffExpectsRows, + INITIAL_VIEWER_RENDER_STATE, + POOL_INIT_TIMEOUT_MS, + readPoolState, + ROWS_READY_TIMEOUT_MS, + selectMountedSpec, + selectRevision, + transitionViewerRender, + type ViewerInstanceSpec, + type ViewerRenderEffect, + type ViewerRenderEvent, + type ViewerRenderRequest, + type ViewerTarget, +} from "../pierre/render-machine" import { restoreShadowTextSelection } from "../pierre/selection-bridge" import { createFileSelectionState, @@ -168,7 +174,6 @@ type ViewerConfig = { mode: FileSelectionMode enableLineSelection: () => boolean selectedLines: () => SelectedLineRange | null | undefined - commentedLines: () => SelectedLineRange[] callbacks: SelectionCallbacks // mode-specific callbacks @@ -180,7 +185,6 @@ type ViewerConfig = { applySelection: (range: SelectedLineRange | null) => void /** Adjusts a range Pierre reports before the machine stores it. */ normalize?: (range: SelectedLineRange | null) => SelectedLineRange | null | undefined - markCommented: (root: ShadowRoot, ranges: SelectedLineRange[]) => void } type PointerMove = { @@ -207,9 +211,6 @@ function useFileViewer(config: ViewerConfig) { const hit: MouseHit = { line: undefined, numberColumn: false, side: undefined } const moveEvent: PointerMove = { type: "pointer.move", buttons: 0, line: undefined, side: undefined } - const ready = createReadyWatcher() - const [rendered, setRendered] = createSignal(0) - const getRoot = () => getViewerRoot(container) const getHost = () => getViewerHost(container) @@ -366,41 +367,6 @@ function useFileViewer(config: ViewerConfig) { onCleanup(observeViewerScheme(getHost)) }) - createEffect(() => { - rendered() - const ranges = config.commentedLines() - const root = getRoot() - - if (!root) return - - if (ranges.length === 0) { - config.markCommented(root, ranges) - - return - } - - let frame: number | undefined - - const mark = () => { - if (frame !== undefined) cancelAnimationFrame(frame) - frame = requestAnimationFrame(() => { - frame = undefined - config.markCommented(root, ranges) - }) - } - - const observer = new MutationObserver(mark) - - observer.observe(root, { childList: true, subtree: true }) - mark() - - onCleanup(() => { - observer.disconnect() - - if (frame !== undefined) cancelAnimationFrame(frame) - }) - }) - createEffect(() => { const range = config.selectedLines() ?? null untrack(() => dispatch({ type: "selection.controlled", range })) @@ -419,10 +385,7 @@ function useFileViewer(config: ViewerConfig) { makeEventListener(document, "selectionchange", handleSelectionChange) }) - onCleanup(() => { - clearReadyWatcher(ready) - dispatch({ type: "disposed" }) - }) + onCleanup(() => dispatch({ type: "disposed" })) return { get wrapper() { @@ -443,9 +406,6 @@ function useFileViewer(config: ViewerConfig) { set overlay(v: HTMLDivElement) { overlay = v }, - ready, - rendered, - setRendered, getRoot, getHost, find, @@ -467,11 +427,6 @@ type RenderTarget = { cleanUp: () => void } -type AnnotationTarget = { - setLineAnnotations: (annotations: A[]) => void - rerender: () => void -} - type VirtualStrategy = { get: () => Virtualizer | undefined cleanup: () => void @@ -495,75 +450,256 @@ function useSearchHandle(opts: { }) } -function useAnnotationRerender(opts: { - viewer: Viewer - current: () => AnnotationTarget | undefined - annotations: () => A[] -}) { - const applied = new WeakSet>() - createEffect(() => { - opts.viewer.rendered() - const active = opts.current() - - if (!active) return - const annotations = opts.annotations() - - // renderViewer always draws with empty annotations, so skip the extra rerender - // when this instance has nothing applied and nothing to apply. - if (annotations.length === 0 && !applied.has(active)) return - - if (annotations.length === 0) applied.delete(active) - else applied.add(active) - active.setLineAnnotations(annotations) - active.rerender() - requestAnimationFrame(() => opts.viewer.find.refresh({ reset: true })) - }) -} - -function notifyRendered(opts: { +type ViewerRenderConfig = { viewer: Viewer + /** Pierre options; a change redraws, and a draw always uses the latest ones. */ + options: () => O + /** Reads every other input a draw depends on; a change requests a new draw. */ + request: () => ViewerRenderRequest + create: (spec: ViewerInstanceSpec, options: O) => I + /** Applies options to a kept instance and returns whether its rows must render again. */ + update: (instance: I, options: O) => boolean + draw: (instance: I, spec: ViewerInstanceSpec, forceRender: boolean) => void isReady: (root: ShadowRoot) => boolean - settleFrames?: number - onReady: () => void -}) { - notifyShadowReady({ - state: opts.viewer.ready, - container: opts.viewer.container, - getRoot: opts.viewer.getRoot, - isReady: opts.isReady, - settleFrames: opts.settleFrames, - onReady: opts.onReady, - }) + annotations: () => unknown[] + applyAnnotations: (instance: I) => void + commentedLines: () => SelectedLineRange[] + markCommented: (root: ShadowRoot, ranges: SelectedLineRange[]) => void + /** Scrolls a range into a virtualized window; returns false while rows cannot be measured yet. */ + reveal?: (instance: I, spec: ViewerInstanceSpec, range: SelectedLineRange) => boolean + onRendered: () => void } -function renderViewer(opts: { - viewer: Viewer - current: I | undefined - reset?: boolean - create: () => I - update?: (value: I) => void - assign: (value: I) => void - draw: (value: I) => void - onReady: () => void -}) { - clearReadyWatcher(opts.viewer.ready) - const reset = opts.reset === true && opts.current !== undefined +type ViewerRender = { + instance: () => I | undefined + requestReveal: (range: SelectedLineRange | undefined) => void +} - if (reset) opts.current?.cleanUp() - const next = reset || !opts.current ? opts.create() : opts.current +function useViewerRender(config: ViewerRenderConfig): ViewerRender { + const viewer = config.viewer + let state = INITIAL_VIEWER_RENDER_STATE + let instance: I | undefined + let observer: MutationObserver | undefined + let poolTimer: ReturnType | undefined + let rowsTimer: ReturnType | undefined + let settleFrame: number | undefined + let findFrame: number | undefined + let releaseHeight: VoidFunction | undefined + const [revision, setRevision] = createSignal(selectRevision(state)) - if (reset || !opts.current) { - opts.viewer.container.innerHTML = "" - opts.assign(next) - } else { - opts.update?.(next) + const cancelAsync = () => { + observer?.disconnect() + observer = undefined + clearTimeout(poolTimer) + clearTimeout(rowsTimer) + poolTimer = undefined + rowsTimer = undefined + + if (settleFrame !== undefined) cancelAnimationFrame(settleFrame) + settleFrame = undefined } - opts.draw(next) + const watchRows = (attempt: number) => { + const done = () => { + observer?.disconnect() + observer = undefined + clearTimeout(rowsTimer) + rowsTimer = undefined + dispatch({ type: "rows.ready", attempt }) + } - applyViewerScheme(opts.viewer.getHost()) - opts.viewer.setRendered((value) => value + 1) - opts.onReady() + const watchRoot = (root: ShadowRoot) => { + observer?.disconnect() + observer = new MutationObserver(() => { + if (config.isReady(root)) done() + }) + observer.observe(root, { childList: true, subtree: true }) + } + + const root = viewer.getRoot() + + if (root && config.isReady(root)) return done() + + rowsTimer = setTimeout(() => { + rowsTimer = undefined + dispatch({ type: "rows.timed-out", attempt }) + }, ROWS_READY_TIMEOUT_MS) + + if (root) return watchRoot(root) + + observer = new MutationObserver(() => { + const next = viewer.getRoot() + + if (!next) return + + if (config.isReady(next)) return done() + watchRoot(next) + }) + observer.observe(viewer.container, { childList: true, subtree: true }) + } + + const run = (effect: ViewerRenderEffect) => { + if (effect.type === "cancel-async") return cancelAsync() + + if (effect.type === "await-pool") { + poolTimer = setTimeout(() => { + poolTimer = undefined + dispatch({ type: "pool.timed-out", attempt: effect.attempt }) + }, POOL_INIT_TIMEOUT_MS) + void effect.pool.initialize().then( + () => dispatch({ type: "pool.settled", attempt: effect.attempt, ok: true }), + () => dispatch({ type: "pool.settled", attempt: effect.attempt, ok: false }), + ) + + return + } + + if (effect.type === "preserve-height") { + releaseHeight ??= preserve(viewer) + + return + } + + if (effect.type === "release-height") { + releaseHeight?.() + releaseHeight = undefined + + return + } + + if (effect.type === "draw") { + if (effect.action === "reset") { + instance?.cleanUp() + instance = undefined + } + + const options = config.options() + const forceRender = instance ? config.update(instance, options) : false + + if (!instance) { + viewer.container.innerHTML = "" + instance = config.create(effect.spec, options) + } + + config.draw(instance, effect.spec, forceRender) + applyViewerScheme(viewer.getHost()) + + return + } + + if (effect.type === "sync-annotations") + return dispatch({ type: "annotations.synced", count: config.annotations().length }) + + if (effect.type === "apply-annotations") { + if (!instance) return + config.applyAnnotations(instance) + + if (findFrame !== undefined) cancelAnimationFrame(findFrame) + findFrame = requestAnimationFrame(() => { + findFrame = undefined + viewer.find.refresh({ reset: true }) + }) + + return + } + + if (effect.type === "watch-rows") return watchRows(effect.attempt) + + if (effect.type === "schedule-settle-frame") { + settleFrame = requestAnimationFrame(() => { + settleFrame = undefined + dispatch({ type: "settle.frame", attempt: effect.attempt }) + }) + + return + } + + if (effect.type === "reapply-selection") return viewer.reapplySelection() + + if (effect.type === "try-reveal") { + const spec = selectMountedSpec(state) + + if (!instance || !spec) return + + if (!config.reveal || config.reveal(instance, spec, effect.range)) dispatch({ type: "reveal.completed" }) + + return + } + + if (effect.type === "refresh-find") return viewer.find.refresh({ reset: true }) + + if (effect.type === "notify-rendered") return config.onRendered() + + instance?.cleanUp() + instance = undefined + + if (findFrame !== undefined) cancelAnimationFrame(findFrame) + } + + // Effects can dispatch again synchronously (rows already drawn, annotations synced after a draw). + const dispatch = (event: ViewerRenderEvent) => { + const step = transitionViewerRender(state, event) + const changed = selectRevision(step.state) !== selectRevision(state) + state = step.state + step.effects.forEach(run) + + if (changed && state.status !== "disposed") setRevision(selectRevision(state)) + } + + createEffect(() => { + config.options() + const request = config.request() + untrack(() => dispatch({ type: "render.requested", request })) + }) + + // Each draw syncs annotations itself, so only later changes dispatch here. + createEffect( + on(config.annotations, (annotations) => dispatch({ type: "annotations.synced", count: annotations.length }), { + defer: true, + }), + ) + + createEffect(() => { + revision() + const ranges = config.commentedLines() + const root = viewer.getRoot() + + if (!root) return + + if (ranges.length === 0) { + config.markCommented(root, ranges) + + return + } + + let frame: number | undefined + + const mark = () => { + if (frame !== undefined) cancelAnimationFrame(frame) + frame = requestAnimationFrame(() => { + frame = undefined + config.markCommented(root, ranges) + }) + } + + const watch = new MutationObserver(mark) + + watch.observe(root, { childList: true, subtree: true }) + mark() + + onCleanup(() => { + watch.disconnect() + + if (frame !== undefined) cancelAnimationFrame(frame) + }) + }) + + onCleanup(() => dispatch({ type: "disposed" })) + + return { + instance: () => instance, + requestReveal: (range) => dispatch({ type: "reveal.requested", range }), + } } function preserve(viewer: Viewer) { @@ -676,22 +812,6 @@ function createSharedVirtualStrategy(host: () => HTMLDivElement | undefined, ena } } -// Pierre draws nothing until its worker pool initializes, and a virtualizer that first sees an empty file at the top -// of its scroller anchors the file's bottom edge, then scrolls to the end once the rows arrive. -function createPoolReady() { - const [settled, setSettled] = createSignal(false) - - return (pool: ReturnType) => { - if (!pool || pool.isInitialized() || settled()) return true - void pool - .initialize() - .catch(() => undefined) - .then(() => setSettled(true)) - - return false - } -} - function parseLine(node: HTMLElement) { if (!node.dataset.line) return const value = parseInt(node.dataset.line, 10) @@ -805,9 +925,8 @@ function ViewerShell(props: { // --------------------------------------------------------------------------- function TextViewer(props: TextFileProps) { - let instance: PierreFile | VirtualizedFile | undefined - let instanceVirtualizer: Virtualizer | undefined let viewer!: Viewer + let render!: ViewerRender | VirtualizedFile> const [local, others] = splitProps(props, textKeys) @@ -821,11 +940,10 @@ function TextViewer(props: TextFileProps) { const virtual = createMemo(() => lineCount() > virtualizeLineThreshold) const virtuals = createLocalVirtualStrategy(() => viewer.wrapper, virtual) - const poolReady = createPoolReady() // Rows that are not drawn yet cannot show a range; the machine keeps it and the ready callback applies it again. const applySelection = (range: SelectedLineRange | null) => { - const current = instance + const current = render.instance() if (!current) return @@ -866,13 +984,11 @@ function TextViewer(props: TextFileProps) { mode: "text", enableLineSelection: () => props.enableLineSelection === true, selectedLines: () => local.selectedLines, - commentedLines: () => local.commentedLines ?? [], callbacks: local, lineForElement: parseLine, lineForNode: findFileLineNumber, sideForNode: findCodeSelectionSide, applySelection, - markCommented: markCommentedFileLines, }) const options = createMemo(() => ({ @@ -881,77 +997,61 @@ function TextViewer(props: TextFileProps) { ...viewer.lineCallbacks, })) - const notify = () => { - notifyRendered({ - viewer, - isReady: (root) => { - if (virtual()) return root.querySelector("[data-line]") != null - - return root.querySelectorAll("[data-line]").length >= lineCount() - }, - onReady: () => { - viewer.reapplySelection() - viewer.find.refresh({ reset: true }) - local.onRendered?.() - }, - }) - } - useSearchHandle({ search: () => local.search, find: viewer.find, }) - // -- render instance -- + // Cleanups run in reverse, so the instance is cleaned up before the virtualizer it uses. + onCleanup(() => virtuals.cleanup()) - createEffect(() => { - const opts = options() - const workerPool = getWorkerPool() - const virtualizer = virtuals.get() - - if (virtualizer && !poolReady(workerPool)) return - // An instance keeps the virtualizer it was built with; options and contents update in place. - const reset = instance !== undefined && instanceVirtualizer !== virtualizer - const forceRender = !reset && instance !== undefined && !areOptionsEqual(instance.options, opts) - - renderViewer({ - viewer, - current: instance, - reset, - create: () => - virtualizer - ? new VirtualizedFile(opts, virtualizer, codeMetrics, workerPool) - : new PierreFile(opts, workerPool), - update: (value) => value.setOptions(opts), - assign: (value) => { - instance = value - instanceVirtualizer = virtualizer - }, - draw: (value) => { - value.render({ - file: local.file, - forceRender, - lineAnnotations: [], - containerWrapper: viewer.container, - }) - }, - onReady: notify, - }) - }) - - useAnnotationRerender>({ + // An instance keeps the virtualizer and pool it was built with; options and contents update in place. + render = useViewerRender({ viewer, - current: () => instance, + options, + request: () => { + const workerPool = getWorkerPool() + + return { + spec: { + virtualizer: virtuals.get(), + workerPool, + hunkSeparators: undefined, + target: { kind: "text", file: local.file }, + }, + pool: readPoolState(workerPool), + settleFrames: 0, + preserveHeight: false, + expectsRows: true, + } + }, + create: (spec, opts) => + spec.virtualizer + ? new VirtualizedFile(opts, spec.virtualizer, codeMetrics, spec.workerPool) + : new PierreFile(opts, spec.workerPool), + update: (instance, opts) => { + const forceRender = !areOptionsEqual(instance.options, opts) + instance.setOptions(opts) + + return forceRender + }, + draw: (instance, spec, forceRender) => { + if (spec.target.kind !== "text") return + instance.render({ file: spec.target.file, forceRender, lineAnnotations: [], containerWrapper: viewer.container }) + }, + isReady: (root) => { + if (virtual()) return root.querySelector("[data-line]") != null + + return root.querySelectorAll("[data-line]").length >= lineCount() + }, annotations: () => local.annotations ?? [], - }) - - // -- cleanup -- - - onCleanup(() => { - instance?.cleanUp() - instance = undefined - instanceVirtualizer = undefined - virtuals.cleanup() + applyAnnotations: (instance) => { + instance.setLineAnnotations(local.annotations ?? []) + instance.rerender() + }, + commentedLines: () => local.commentedLines ?? [], + markCommented: markCommentedFileLines, + onRendered: () => local.onRendered?.(), }) return @@ -962,14 +1062,8 @@ function TextViewer(props: TextFileProps) { // --------------------------------------------------------------------------- function DiffViewer(props: DiffFileProps) { - let instance: FileDiff | undefined - let instanceVirtualizer: Virtualizer | undefined - let instanceWorkerPool: ReturnType - let instanceVirtualHunkSeparators: FileDiffOptions["hunkSeparators"] | undefined - let instanceFileDiff: FileDiffMetadata | undefined - let instanceBefore: FileContents | undefined - let instanceAfter: FileContents | undefined let viewer!: Viewer + let render!: ViewerRender> const [local, others] = splitProps(props, diffKeys) @@ -979,11 +1073,11 @@ function DiffViewer(props: DiffFileProps) { const fixSelection = (range: SelectedLineRange | null) => { const fixed = fixDiffSelection(viewer.getRoot(), range) - return fixed === null && instance instanceof VirtualizedFileDiff ? range : fixed + return fixed === null && render.instance() instanceof VirtualizedFileDiff ? range : fixed } const applySelection = (range: SelectedLineRange | null) => { - const active = instance + const active = render.instance() if (!active) return const fixed = fixSelection(range) @@ -995,7 +1089,6 @@ function DiffViewer(props: DiffFileProps) { mode: "diff", enableLineSelection: () => props.enableLineSelection === true, selectedLines: () => local.selectedLines, - commentedLines: () => local.commentedLines ?? [], callbacks: local, lineForElement: findDiffLineNumber, sideForElement: diffMouseSide, @@ -1003,7 +1096,6 @@ function DiffViewer(props: DiffFileProps) { sideForNode: diffSelectionSide, applySelection, normalize: fixSelection, - markCommented: markCommentedDiffLines, }) const virtuals = createSharedVirtualStrategy( @@ -1011,8 +1103,6 @@ function DiffViewer(props: DiffFileProps) { () => local.virtualize !== false, ) - const poolReady = createPoolReady() - const large = createMemo(() => { if (local.fileDiff) { const before = local.fileDiff.deletionLines.join("") @@ -1047,178 +1137,122 @@ function DiffViewer(props: DiffFileProps) { return { ...perf, disableLineNumbers: props.disableLineNumbers ?? true } }) - // A virtualized diff only renders rows near the viewport, so jumping to a selection must scroll it into range first. - let pendingReveal: SelectedLineRange | undefined - - const revealSelection = () => { - const active = instance - const range = pendingReveal - - if (!active || !range) return - - if (!(active instanceof VirtualizedFileDiff) || !instanceVirtualizer) { - pendingReveal = undefined - - return - } - - const position = active.getLinePosition(Math.min(range.start, range.end), range.side) - const root = instanceVirtualizer.getRoot() - - // Keep the request until the diff has a layout to measure; the next render retries it. - if (!position || !root) return - pendingReveal = undefined - const top = instanceVirtualizer.getOffsetInScrollContainer(viewer.container) + position.top - const scrollTop = instanceVirtualizer.getScrollTop() - const height = root instanceof Document ? window.innerHeight : root.clientHeight - - if (top >= scrollTop && top + position.height <= scrollTop + height) return - instanceVirtualizer.scrollTo({ top: top - height / 2 }) - } - - createEffect( - on( - () => local.selectedLines, - (range) => { - pendingReveal = range ?? undefined - revealSelection() - }, - ), - ) - - const notify = (done?: VoidFunction) => { - notifyRendered({ - viewer, - isReady: (root) => root.querySelector("[data-line]") != null, - settleFrames: 1, - onReady: () => { - done?.() - viewer.reapplySelection() - revealSelection() - viewer.find.refresh({ reset: true }) - local.onRendered?.() - }, - }) - } - useSearchHandle({ search: () => local.search, find: viewer.find, }) - // -- render instance -- + const cacheKey = (contents: string) => + large() ? sampledChecksum(contents) : sampledChecksum(contents, contents.length) - createEffect(() => { - const opts = options() - // Worker render options override per-viewer options, including the large-file fallback. - const workerPool = getWorkerPool(large() ? "none" : "word-line") - const virtualizer = virtuals.get() + const target = (): ViewerTarget => { + if (local.fileDiff) return { kind: "diff-patch", fileDiff: local.fileDiff } - if (virtualizer && !poolReady(workerPool)) return - const beforeContents = local.before?.contents ?? "" - const afterContents = local.after?.contents ?? "" - const done = preserve(viewer) + if (!local.before || !local.after) return { kind: "diff-empty" } - onCleanup(done) - - const cacheKey = (contents: string) => { - if (!large()) return sampledChecksum(contents, contents.length) - - return sampledChecksum(contents) + return { + kind: "diff-files", + before: { ...local.before, cacheKey: cacheKey(local.before.contents) }, + after: { ...local.after, cacheKey: cacheKey(local.after.contents) }, } + } - const before = local.before - ? { ...local.before, contents: beforeContents, cacheKey: cacheKey(beforeContents) } - : undefined + // Cleanups run in reverse, so the instance is cleaned up before it releases the shared virtualizer. + onCleanup(() => virtuals.cleanup()) - const after = local.after - ? { ...local.after, contents: afterContents, cacheKey: cacheKey(afterContents) } - : undefined + // Pierre beta virtualized instances retain their first diff target and resolve separator metrics at construction. + // Plain timeline diffs keep the instance as content streams; virtualized viewers reset only when that is unsafe. + render = useViewerRender({ + viewer, + options, + request: () => { + // Worker render options override per-viewer options, including the large-file fallback. + const workerPool = getWorkerPool(large() ? "none" : "word-line") + const virtualizer = virtuals.get() + const next = target() - const targetChanged = - local.fileDiff !== undefined - ? instanceFileDiff !== local.fileDiff - : instanceFileDiff !== undefined || - before === undefined || - after === undefined || - instanceBefore === undefined || - instanceAfter === undefined || - !areFilesEqual(instanceBefore, before) || - !areFilesEqual(instanceAfter, after) + return { + spec: { + virtualizer, + workerPool, + hunkSeparators: virtualizer ? options().hunkSeparators : undefined, + target: next, + }, + pool: readPoolState(workerPool), + settleFrames: 1, + preserveHeight: true, + expectsRows: diffExpectsRows(next, options().expandUnchanged), + } + }, + create: (spec, opts) => + spec.virtualizer + ? new VirtualizedFileDiff(opts, spec.virtualizer, virtualMetrics, spec.workerPool) + : new FileDiff(opts, spec.workerPool), + update: (instance, opts) => { + const forceRender = !areOptionsEqual(instance.options, opts) + instance.setOptions(opts) - // Pierre beta virtualized instances retain their first diff target and resolve separator metrics at construction. - // Plain timeline diffs can retain the instance as content streams; virtualized viewers reset only when that is unsafe. - const reset = - instance !== undefined && - (instanceVirtualizer !== virtualizer || - instanceWorkerPool !== workerPool || - (virtualizer !== undefined && (instanceVirtualHunkSeparators !== opts.hunkSeparators || targetChanged))) - - const forceRender = !reset && instance !== undefined && !areOptionsEqual(instance.options, opts) - - renderViewer({ - viewer, - current: instance, - reset, - create: () => - virtualizer - ? new VirtualizedFileDiff(opts, virtualizer, virtualMetrics, workerPool) - : new FileDiff(opts, workerPool), - update: (value) => value.setOptions(opts), - assign: (value) => { - instance = value - instanceVirtualizer = virtualizer - instanceWorkerPool = workerPool - instanceVirtualHunkSeparators = virtualizer ? opts.hunkSeparators : undefined - instanceFileDiff = local.fileDiff - instanceBefore = before - instanceAfter = after - }, - draw: (value) => { - if (local.fileDiff) { - value.render({ - fileDiff: local.fileDiff, - forceRender, - lineAnnotations: [], - containerWrapper: viewer.container, - }) - - return - } - - if (!before || !after) return - - value.render({ - oldFile: before, - newFile: after, + return forceRender + }, + draw: (instance, spec, forceRender) => { + if (spec.target.kind === "diff-patch") { + instance.render({ + fileDiff: spec.target.fileDiff, forceRender, lineAnnotations: [], containerWrapper: viewer.container, }) - }, - onReady: () => notify(done), - }) - }) - useAnnotationRerender>({ - viewer, - current: () => instance, + return + } + + if (spec.target.kind !== "diff-files") return + + instance.render({ + oldFile: spec.target.before, + newFile: spec.target.after, + forceRender, + lineAnnotations: [], + containerWrapper: viewer.container, + }) + }, + isReady: (root) => root.querySelector("[data-line]") != null, annotations: () => local.annotations ?? [], + applyAnnotations: (instance) => { + instance.setLineAnnotations(local.annotations ?? []) + instance.rerender() + }, + commentedLines: () => local.commentedLines ?? [], + markCommented: markCommentedDiffLines, + // A virtualized diff only renders rows near the viewport, so jumping to a selection must scroll it into range. + reveal: (instance, spec, range) => { + const virtualizer = spec.virtualizer + + if (!(instance instanceof VirtualizedFileDiff) || !virtualizer) return true + + const position = instance.getLinePosition(Math.min(range.start, range.end), range.side) + const root = virtualizer.getRoot() + + // Keep the request until the diff has a layout to measure; the next ready draw retries it. + if (!position || !root) return false + + const top = virtualizer.getOffsetInScrollContainer(viewer.container) + position.top + const scrollTop = virtualizer.getScrollTop() + const height = root instanceof Document ? window.innerHeight : root.clientHeight + + if (top < scrollTop || top + position.height > scrollTop + height) virtualizer.scrollTo({ top: top - height / 2 }) + + return true + }, + onRendered: () => local.onRendered?.(), }) - // -- cleanup -- - - onCleanup(() => { - instance?.cleanUp() - instance = undefined - instanceVirtualizer = undefined - instanceWorkerPool = undefined - instanceVirtualHunkSeparators = undefined - instanceFileDiff = undefined - instanceBefore = undefined - instanceAfter = undefined - virtuals.cleanup() - }) + createEffect( + on( + () => local.selectedLines, + (range) => render.requestReveal(range ?? undefined), + ), + ) return } diff --git a/packages/session-ui/src/pierre/file-runtime.ts b/packages/session-ui/src/pierre/file-runtime.ts index 85f36ff4480..175389a6932 100644 --- a/packages/session-ui/src/pierre/file-runtime.ts +++ b/packages/session-ui/src/pierre/file-runtime.ts @@ -1,17 +1,3 @@ -type ReadyWatcher = { - observer?: MutationObserver - token: number -} - -export function createReadyWatcher(): ReadyWatcher { - return { token: 0 } -} - -export function clearReadyWatcher(state: ReadyWatcher) { - state.observer?.disconnect() - state.observer = undefined -} - export function getViewerHost(container: HTMLElement | undefined) { if (!container) return const host = container.querySelector("diffs-container") @@ -54,76 +40,3 @@ export function observeViewerScheme(getHost: () => HTMLElement | undefined) { return () => monitor.disconnect() } - -export function notifyShadowReady(opts: { - state: ReadyWatcher - container: HTMLElement - getRoot: () => ShadowRoot | undefined - isReady: (root: ShadowRoot) => boolean - onReady: () => void - settleFrames?: number -}) { - clearReadyWatcher(opts.state) - opts.state.token += 1 - - const token = opts.state.token - const settle = Math.max(0, opts.settleFrames ?? 0) - - const runReady = () => { - const step = (left: number) => { - if (token !== opts.state.token) return - - if (left <= 0) { - opts.onReady() - - return - } - - requestAnimationFrame(() => step(left - 1)) - } - - requestAnimationFrame(() => step(settle)) - } - - const observeRoot = (root: ShadowRoot) => { - if (opts.isReady(root)) { - runReady() - - return - } - - if (typeof MutationObserver === "undefined") return - - clearReadyWatcher(opts.state) - opts.state.observer = new MutationObserver(() => { - if (token !== opts.state.token) return - - if (!opts.isReady(root)) return - - clearReadyWatcher(opts.state) - runReady() - }) - opts.state.observer.observe(root, { childList: true, subtree: true }) - } - - const root = opts.getRoot() - - if (!root) { - if (typeof MutationObserver === "undefined") return - - opts.state.observer = new MutationObserver(() => { - if (token !== opts.state.token) return - - const next = opts.getRoot() - - if (!next) return - - observeRoot(next) - }) - opts.state.observer.observe(opts.container, { childList: true, subtree: true }) - - return - } - - observeRoot(root) -} diff --git a/packages/session-ui/src/pierre/render-machine.test.ts b/packages/session-ui/src/pierre/render-machine.test.ts new file mode 100644 index 00000000000..8e936165587 --- /dev/null +++ b/packages/session-ui/src/pierre/render-machine.test.ts @@ -0,0 +1,292 @@ +import { describe, expect, test } from "bun:test" +import { Virtualizer } from "@pierre/diffs" +import type { WorkerPoolManager } from "@pierre/diffs/worker" +import { normalize } from "../components/session-diff" +import { + diffExpectsRows, + DISPOSED_VIEWER_RENDER_STATE, + INITIAL_VIEWER_RENDER_STATE, + needsInstanceReset, + NO_RENDER_EFFECTS, + selectMountedSpec, + transitionViewerRender, + type PoolReadiness, + type ViewerInstanceSpec, + type ViewerRenderEvent, + type ViewerRenderRequest, + type ViewerRenderTransition, + type ViewerTarget, +} from "./render-machine" + +// SAFETY: the machine only compares pools by identity; it never calls them. +const poolA = {} as WorkerPoolManager + +// SAFETY: as above. +const poolB = {} as WorkerPoolManager + +const virtualizer = new Virtualizer() + +const files = (before: string, after: string): ViewerTarget => ({ + kind: "diff-files", + before: { name: "a.ts", contents: before, cacheKey: before }, + after: { name: "a.ts", contents: after, cacheKey: after }, +}) + +const spec = (target: ViewerTarget, change: Partial = {}): ViewerInstanceSpec => ({ + virtualizer: undefined, + workerPool: undefined, + hunkSeparators: undefined, + target, + ...change, +}) + +const requested = ( + next: ViewerInstanceSpec, + change: Partial> = {}, +): ViewerRenderEvent => ({ + type: "render.requested", + request: { spec: next, pool: "none", settleFrames: 1, preserveHeight: true, expectsRows: true, ...change }, +}) + +function run(events: ViewerRenderEvent[], state = INITIAL_VIEWER_RENDER_STATE): ViewerRenderTransition { + return events.reduce((result, event) => transitionViewerRender(result.state, event), { + state, + effects: NO_RENDER_EFFECTS, + }) +} + +const frames = (attempt: number, count: number) => + Array.from({ length: count }, () => ({ type: "settle.frame", attempt }) as const) + +describe("viewer render", () => { + test("an in-place update records the drawn target, so a later virtualized draw compares against it", () => { + const first = spec(files("a1", "b1")) + const second = spec(files("a2", "b2")) + const updated = run([requested(first), requested(second)]) + + expect(updated.effects).toContainEqual({ type: "draw", action: "update", spec: second }) + expect(selectMountedSpec(updated.state)).toBe(second) + + const virtualized = run([requested({ ...second, virtualizer })], updated.state) + expect(virtualized.effects).toContainEqual({ type: "draw", action: "reset", spec: { ...second, virtualizer } }) + + const same = run([requested(spec(files("a2", "b2"), { virtualizer }))], virtualized.state) + expect(same.effects).toContainEqual(expect.objectContaining({ type: "draw", action: "update" })) + + const reverted = run([requested(spec(files("a1", "b1"), { virtualizer }))], same.state) + expect(reverted.effects).toContainEqual(expect.objectContaining({ type: "draw", action: "reset" })) + }) + + test("decides when an instance must be rebuilt", () => { + const text = (contents: string) => ({ kind: "text", file: { name: "a.ts", contents } }) as const + + const cases: [ViewerInstanceSpec, ViewerInstanceSpec, boolean][] = [ + [spec(text("a")), spec(text("b")), false], + [spec(text("a")), spec(text("a"), { virtualizer }), true], + [spec(text("a"), { workerPool: poolA }), spec(text("a"), { workerPool: poolB }), true], + [spec(files("a", "b")), spec(files("a", "c")), false], + [spec(files("a", "b"), { virtualizer }), spec(files("a", "c"), { virtualizer }), true], + [spec(files("a", "b"), { virtualizer }), spec(files("a", "b"), { virtualizer, hunkSeparators: "simple" }), true], + [spec(files("a", "b"), { virtualizer }), spec(files("a", "b"), { virtualizer }), false], + ] + + for (const [previous, next, reset] of cases) expect(needsInstanceReset(previous, next)).toBe(reset) + }) + + test("waits for each pool a virtualized draw needs, even after another pool settled", () => { + const ready = run([requested(spec(files("a", "b"), { virtualizer, workerPool: poolA }), { pool: "ready" })]) + expect(ready.state.status).toBe("awaiting-rows") + + const large = run( + [requested(spec(files("a", "c"), { virtualizer, workerPool: poolB }), { pool: "initializing" })], + ready.state, + ) + + expect(large.state).toMatchObject({ status: "awaiting-pool", attempt: 2 }) + expect(large.effects).toEqual([{ type: "cancel-async" }, { type: "await-pool", attempt: 2, pool: poolB }]) + + expect(transitionViewerRender(large.state, { type: "pool.settled", attempt: 1, ok: true }).state).toBe(large.state) + + const settled = transitionViewerRender(large.state, { type: "pool.settled", attempt: 2, ok: true }) + expect(settled.effects).toContainEqual( + expect.objectContaining({ type: "draw", action: "reset", spec: expect.objectContaining({ workerPool: poolB }) }), + ) + }) + + test("a failed or hung pool falls back to the main thread", () => { + const waiting = run([ + requested(spec(files("a", "b"), { virtualizer, workerPool: poolB }), { pool: "initializing" }), + ]) + + const failed = transitionViewerRender(waiting.state, { type: "pool.settled", attempt: 1, ok: false }) + expect(selectMountedSpec(failed.state)?.workerPool).toBeUndefined() + + const timedOut = transitionViewerRender(waiting.state, { type: "pool.timed-out", attempt: 1 }) + expect(selectMountedSpec(timedOut.state)?.workerPool).toBeUndefined() + expect(timedOut.state).toMatchObject({ timedOutPool: poolB }) + + // The timed-out pool does not block the next draw, until it reports ready. + const next = (pool: PoolReadiness) => + transitionViewerRender( + timedOut.state, + requested(spec(files("a", "c"), { virtualizer, workerPool: poolB }), { pool }), + ) + + expect(next("initializing").state.status).toBe("awaiting-rows") + expect(selectMountedSpec(next("initializing").state)?.workerPool).toBeUndefined() + expect(next("ready").state).toMatchObject({ timedOutPool: undefined }) + expect(selectMountedSpec(next("ready").state)?.workerPool).toBe(poolB) + + const broken = run([requested(spec(files("a", "b"), { virtualizer, workerPool: poolA }), { pool: "broken" })]) + expect(selectMountedSpec(broken.state)?.workerPool).toBeUndefined() + }) + + test("an empty diff settles without waiting for rows and releases the pinned height", () => { + const shown = run([requested(spec(files("a", "b"))), { type: "rows.ready", attempt: 1 }, ...frames(1, 2)]) + expect(shown.state).toMatchObject({ status: "ready", heightPinned: false }) + + const empty = run([requested(spec(files("a", "a")), { expectsRows: false })], shown.state) + expect(empty.effects).toEqual([ + { type: "preserve-height" }, + expect.objectContaining({ type: "draw", action: "update" }), + { type: "sync-annotations" }, + { type: "schedule-settle-frame", attempt: 2 }, + ]) + + const settled = run(frames(2, 2), empty.state) + expect(settled.state).toMatchObject({ status: "ready", outcome: "ready", heightPinned: false }) + expect(settled.effects).toEqual([ + { type: "release-height" }, + { type: "reapply-selection" }, + { type: "refresh-find" }, + { type: "notify-rendered" }, + ]) + }) + + test("knows which diffs draw no rows", () => { + const empty = normalize({ file: "a.ts", before: "same\n", after: "same\n", additions: 0, deletions: 0 }) + const changed = normalize({ file: "a.ts", before: "a\n", after: "b\n", additions: 1, deletions: 1 }) + + expect(diffExpectsRows({ kind: "diff-patch", fileDiff: empty.fileDiff }, false)).toBe(false) + expect(diffExpectsRows({ kind: "diff-patch", fileDiff: changed.fileDiff }, false)).toBe(true) + expect(diffExpectsRows(files("same", "same"), false)).toBe(false) + expect(diffExpectsRows(files("same", "same"), true)).toBe(true) + expect(diffExpectsRows({ kind: "diff-empty" }, true)).toBe(false) + }) + + test("rows that never appear time out, and late rows still finish the draw", () => { + const waiting = run([requested(spec(files("a", "b")))]) + const timedOut = transitionViewerRender(waiting.state, { type: "rows.timed-out", attempt: 1 }) + + expect(timedOut.state).toMatchObject({ status: "ready", outcome: "timeout", heightPinned: false }) + expect(timedOut.effects).toEqual([ + { type: "release-height" }, + { type: "reapply-selection" }, + { type: "refresh-find" }, + { type: "notify-rendered" }, + ]) + + const late = run([{ type: "rows.ready", attempt: 1 }, ...frames(1, 2)], timedOut.state) + expect(late.state).toMatchObject({ status: "ready", outcome: "ready" }) + expect(late.effects).toEqual([{ type: "reapply-selection" }, { type: "refresh-find" }, { type: "notify-rendered" }]) + + // The next draw stops the row watch the timeout left running. + expect(run([requested(spec(files("a", "c")))], timedOut.state).effects[0]).toEqual({ type: "cancel-async" }) + }) + + test("streamed draws keep the height pinned until the last one settles", () => { + const first = run([requested(spec(files("a", "b")))]) + expect(first.effects[0]).toEqual({ type: "preserve-height" }) + + const second = transitionViewerRender(first.state, requested(spec(files("a", "bc")))) + expect(second.effects).toEqual([ + { type: "cancel-async" }, + expect.objectContaining({ type: "draw", action: "update" }), + { type: "sync-annotations" }, + { type: "watch-rows", attempt: 2 }, + ]) + + expect(transitionViewerRender(second.state, { type: "rows.ready", attempt: 1 }).state).toBe(second.state) + + const done = run([{ type: "rows.ready", attempt: 2 }, ...frames(2, 1)], second.state) + expect(done.state).toMatchObject({ status: "settling", framesLeft: 1, heightPinned: true }) + + const ready = run(frames(2, 1), done.state) + expect(ready.effects.filter((effect) => effect.type === "release-height")).toHaveLength(1) + }) + + test("waits one frame per settle frame plus one, and ignores stale frames", () => { + const quick = run([requested(spec(files("a", "b")), { settleFrames: 0 }), { type: "rows.ready", attempt: 1 }]) + expect(transitionViewerRender(quick.state, { type: "settle.frame", attempt: 0 }).state).toBe(quick.state) + expect(run(frames(1, 1), quick.state).state.status).toBe("ready") + + const slow = run([requested(spec(files("a", "b"))), { type: "rows.ready", attempt: 1 }]) + expect(run(frames(1, 1), slow.state).state.status).toBe("settling") + expect(run(frames(1, 2), slow.state).state.status).toBe("ready") + }) + + test("annotations apply only when there are some or some were applied since the draw", () => { + expect(transitionViewerRender(INITIAL_VIEWER_RENDER_STATE, { type: "annotations.synced", count: 2 }).effects).toBe( + NO_RENDER_EFFECTS, + ) + + const drawn = run([requested(spec(files("a", "b")))]) + const none = transitionViewerRender(drawn.state, { type: "annotations.synced", count: 0 }) + expect(none.state).toBe(drawn.state) + expect(none.effects).toBe(NO_RENDER_EFFECTS) + + const added = run([{ type: "annotations.synced", count: 2 }], drawn.state) + expect(added.effects).toEqual([{ type: "apply-annotations" }]) + + const cleared = run([{ type: "annotations.synced", count: 0 }], added.state) + expect(cleared.effects).toEqual([{ type: "apply-annotations" }]) + + // A draw renders without annotations, so it syncs them again from scratch. + const redrawn = run([requested(spec(files("a", "c"))), { type: "annotations.synced", count: 0 }], added.state) + expect(redrawn.effects).toBe(NO_RENDER_EFFECTS) + }) + + test("a reveal waits for a mounted, ready draw and stops once it lands", () => { + const range = { start: 400, end: 400, side: "additions" } as const + const pending = transitionViewerRender(INITIAL_VIEWER_RENDER_STATE, { type: "reveal.requested", range }) + expect(pending.effects).toBe(NO_RENDER_EFFECTS) + + const ready = run( + [requested(spec(files("a", "b"))), { type: "rows.ready", attempt: 1 }, ...frames(1, 2)], + pending.state, + ) + + expect(ready.effects).toContainEqual({ type: "try-reveal", range }) + + const landed = run( + [ + { type: "reveal.completed" }, + requested(spec(files("a", "c"))), + { type: "rows.ready", attempt: 2 }, + ...frames(2, 2), + ], + ready.state, + ) + + expect(landed.effects).not.toContainEqual(expect.objectContaining({ type: "try-reveal" })) + }) + + test("disposing releases the height and instance and ignores later results", () => { + const waiting = run([requested(spec(files("a", "b")))]) + const disposed = transitionViewerRender(waiting.state, { type: "disposed" }) + + expect(disposed.state).toBe(DISPOSED_VIEWER_RENDER_STATE) + expect(disposed.effects).toEqual([ + { type: "cancel-async" }, + { type: "release-height" }, + { type: "cleanup-instance" }, + ]) + + for (const event of [ + { type: "rows.ready", attempt: 1 }, + { type: "pool.settled", attempt: 1, ok: true }, + requested(spec(files("a", "c"))), + ] as const) + expect(transitionViewerRender(disposed.state, event).effects).toBe(NO_RENDER_EFFECTS) + }) +}) diff --git a/packages/session-ui/src/pierre/render-machine.ts b/packages/session-ui/src/pierre/render-machine.ts new file mode 100644 index 00000000000..25bf6c48251 --- /dev/null +++ b/packages/session-ui/src/pierre/render-machine.ts @@ -0,0 +1,381 @@ +import { + areFilesEqual, + type FileContents, + type FileDiffMetadata, + type SelectedLineRange, + type Virtualizer, +} from "@pierre/diffs" +import type { WorkerPoolManager } from "@pierre/diffs/worker" + +/** A pool that never finishes initializing stops blocking a virtualized viewer after this long. */ +export const POOL_INIT_TIMEOUT_MS = 10_000 + +/** A draw whose rows never appear (an empty diff Pierre renders without rows) settles after this long. */ +export const ROWS_READY_TIMEOUT_MS = 2_000 + +export type PoolReadiness = "none" | "ready" | "initializing" | "broken" + +export type ViewerTarget = + | { readonly kind: "text"; readonly file: FileContents } + | { readonly kind: "diff-patch"; readonly fileDiff: FileDiffMetadata } + | { readonly kind: "diff-files"; readonly before: FileContents; readonly after: FileContents } + | { readonly kind: "diff-empty" } + +/** What a Pierre instance was built with. A virtualized instance keeps its first target and separators. */ +export type ViewerInstanceSpec = { + readonly virtualizer: Virtualizer | undefined + readonly workerPool: WorkerPoolManager | undefined + readonly hunkSeparators: unknown + readonly target: ViewerTarget +} + +export type ViewerRenderRequest = { + readonly spec: ViewerInstanceSpec + readonly pool: PoolReadiness + /** Extra frames to wait once rows exist, so a virtualizer can measure them. */ + readonly settleFrames: number + /** Pin the container's height while the draw replaces its rows, so the scroller does not jump. */ + readonly preserveHeight: boolean + /** Whether the draw produces rows at all; an empty diff settles without waiting for them. */ + readonly expectsRows: boolean +} + +export type MountedViewer = { + readonly spec: ViewerInstanceSpec + /** Whether the instance currently holds line annotations; each draw renders without them. */ + readonly annotated: boolean +} + +export type ViewerDrawAction = "create" | "reset" | "update" + +type Shared = { + /** Draw count. Events from an earlier draw or pool wait are stale. */ + readonly attempt: number + /** Changes on every draw; marks that live in Pierre's shadow DOM are applied again. */ + readonly revision: number + readonly heightPinned: boolean + /** A selection to scroll into a virtualized window once rows can be measured. */ + readonly reveal: SelectedLineRange | undefined + /** A pool that timed out once; later draws use the main thread until it reports ready. */ + readonly timedOutPool: WorkerPoolManager | undefined +} + +/** + * One Pierre viewer instance. A virtualized viewer waits for its worker pool before the first draw (`awaiting-pool`); + * each draw then waits for rows (`awaiting-rows`) and a few frames (`settling`) before the viewer reapplies the + * selection, releases the pinned height and reports `ready`. Each wait has a bound. + */ +export type ViewerRenderState = + | (Shared & { readonly status: "idle" }) + | (Shared & { + readonly status: "awaiting-pool" + readonly request: ViewerRenderRequest + readonly mounted: MountedViewer | undefined + }) + | (Shared & { readonly status: "awaiting-rows"; readonly mounted: MountedViewer; readonly settleFrames: number }) + | (Shared & { readonly status: "settling"; readonly mounted: MountedViewer; readonly framesLeft: number }) + | (Shared & { readonly status: "ready"; readonly mounted: MountedViewer; readonly outcome: "ready" | "timeout" }) + | { readonly status: "disposed" } + +export type ViewerRenderEvent = + | { readonly type: "render.requested"; readonly request: ViewerRenderRequest } + | { readonly type: "pool.settled"; readonly attempt: number; readonly ok: boolean } + | { readonly type: "pool.timed-out"; readonly attempt: number } + | { readonly type: "rows.ready"; readonly attempt: number } + | { readonly type: "rows.timed-out"; readonly attempt: number } + | { readonly type: "settle.frame"; readonly attempt: number } + | { readonly type: "annotations.synced"; readonly count: number } + | { readonly type: "reveal.requested"; readonly range: SelectedLineRange | undefined } + | { readonly type: "reveal.completed" } + | { readonly type: "disposed" } + +export type ViewerRenderEffect = + | { readonly type: "cancel-async" } + | { readonly type: "await-pool"; readonly attempt: number; readonly pool: WorkerPoolManager } + | { readonly type: "preserve-height" } + | { readonly type: "release-height" } + | { readonly type: "draw"; readonly action: ViewerDrawAction; readonly spec: ViewerInstanceSpec } + | { readonly type: "sync-annotations" } + | { readonly type: "apply-annotations" } + | { readonly type: "watch-rows"; readonly attempt: number } + | { readonly type: "schedule-settle-frame"; readonly attempt: number } + | { readonly type: "reapply-selection" } + | { readonly type: "try-reveal"; readonly range: SelectedLineRange } + | { readonly type: "refresh-find" } + | { readonly type: "notify-rendered" } + | { readonly type: "cleanup-instance" } + +export type ViewerRenderTransition = { + readonly state: ViewerRenderState + readonly effects: readonly ViewerRenderEffect[] +} + +type Active = Exclude + +export const NO_RENDER_EFFECTS: readonly ViewerRenderEffect[] = Object.freeze([]) + +export const INITIAL_VIEWER_RENDER_STATE: ViewerRenderState = Object.freeze({ + status: "idle", + attempt: 0, + revision: 0, + heightPinned: false, + reveal: undefined, + timedOutPool: undefined, +}) + +export const DISPOSED_VIEWER_RENDER_STATE: ViewerRenderState = Object.freeze({ status: "disposed" }) + +const CANCEL_ASYNC = { type: "cancel-async" } as const + +export function transitionViewerRender(state: ViewerRenderState, event: ViewerRenderEvent): ViewerRenderTransition { + if (state.status === "disposed") return { state, effects: NO_RENDER_EFFECTS } + + if (event.type === "disposed") + return { + state: DISPOSED_VIEWER_RENDER_STATE, + effects: [ + CANCEL_ASYNC, + ...(state.heightPinned ? [{ type: "release-height" as const }] : []), + { type: "cleanup-instance" }, + ], + } + + if (event.type === "render.requested") return request(state, event.request) + + if (event.type === "pool.settled" || event.type === "pool.timed-out") { + if (state.status !== "awaiting-pool" || event.attempt !== state.attempt) + return { state, effects: NO_RENDER_EFFECTS } + const pool = state.request.spec.workerPool + + // A failed or hung pool falls back to highlighting on the main thread. + if (event.type === "pool.timed-out") return draw({ ...state, timedOutPool: pool }, state.request, undefined) + + return draw(state, state.request, event.ok ? pool : undefined) + } + + if (event.type === "rows.ready") { + if (event.attempt !== state.attempt) return { state, effects: NO_RENDER_EFFECTS } + + if (state.status === "awaiting-rows") return settle(state, state.mounted, state.settleFrames) + + // Rows that arrive after the timeout still get the selection, reveal and search a ready draw gets. + if (state.status === "ready" && state.outcome === "timeout") return settle(state, state.mounted, 1) + + return { state, effects: NO_RENDER_EFFECTS } + } + + if (event.type === "settle.frame") { + if (state.status !== "settling" || event.attempt !== state.attempt) return { state, effects: NO_RENDER_EFFECTS } + + if (state.framesLeft > 1) + return { + state: { ...state, framesLeft: state.framesLeft - 1 }, + effects: [{ type: "schedule-settle-frame", attempt: state.attempt }], + } + + return finish(state, state.mounted, "ready") + } + + if (event.type === "rows.timed-out") { + if (state.status !== "awaiting-rows" || event.attempt !== state.attempt) + return { state, effects: NO_RENDER_EFFECTS } + + // Release the pinned height and report the draw; the row watch stays in case rows are only slow. + return finish(state, state.mounted, "timeout") + } + + if (event.type === "annotations.synced") { + const mounted = selectMounted(state) + + // Each draw renders without annotations, so there is nothing to clear when none were applied since. + if (!mounted || (event.count === 0 && !mounted.annotated)) return { state, effects: NO_RENDER_EFFECTS } + const annotated = event.count > 0 + + return { + state: mounted.annotated === annotated ? state : withMounted(state, { ...mounted, annotated }), + effects: [{ type: "apply-annotations" }], + } + } + + if (event.type === "reveal.requested") { + if (state.reveal === event.range) return { state, effects: NO_RENDER_EFFECTS } + + return { + state: { ...state, reveal: event.range }, + effects: event.range && selectMounted(state) ? [{ type: "try-reveal", range: event.range }] : NO_RENDER_EFFECTS, + } + } + + if (state.reveal === undefined) return { state, effects: NO_RENDER_EFFECTS } + + return { state: { ...state, reveal: undefined }, effects: NO_RENDER_EFFECTS } +} + +function request(state: Active, request: ViewerRenderRequest): ViewerRenderTransition { + const pool = request.spec.workerPool + const timedOutPool = request.pool === "ready" ? undefined : state.timedOutPool + const virtualized = request.spec.virtualizer !== undefined + + // A virtualizer that first sees an empty file anchors its bottom edge, then jumps once the pool draws rows. + if (virtualized && request.pool === "initializing" && pool && pool !== timedOutPool) { + const attempt = state.attempt + 1 + + return { + state: { + status: "awaiting-pool", + attempt, + revision: state.revision, + heightPinned: state.heightPinned, + reveal: state.reveal, + timedOutPool, + request, + mounted: selectMounted(state), + }, + effects: [...cancel(state), { type: "await-pool", attempt, pool }], + } + } + + const fallback = virtualized && (request.pool === "broken" || (pool !== undefined && pool === timedOutPool)) + + return draw({ ...state, timedOutPool }, request, fallback ? undefined : pool) +} + +function draw( + state: Active, + request: ViewerRenderRequest, + pool: WorkerPoolManager | undefined, +): ViewerRenderTransition { + const spec = pool === request.spec.workerPool ? request.spec : { ...request.spec, workerPool: pool } + const previous = selectMounted(state) + const action = !previous ? "create" : needsInstanceReset(previous.spec, spec) ? "reset" : "update" + const attempt = state.attempt + 1 + const mounted = { spec, annotated: false } + + const shared = { + attempt, + revision: state.revision + 1, + heightPinned: state.heightPinned || request.preserveHeight, + reveal: state.reveal, + timedOutPool: state.timedOutPool, + } + + const effects: ViewerRenderEffect[] = [ + ...cancel(state), + ...(request.preserveHeight && !state.heightPinned ? [{ type: "preserve-height" as const }] : []), + { type: "draw", action, spec }, + { type: "sync-annotations" }, + ] + + if (!request.expectsRows) { + const next = settle({ ...shared, status: "idle" }, mounted, request.settleFrames) + + return { state: next.state, effects: [...effects, ...next.effects] } + } + + return { + state: { ...shared, status: "awaiting-rows", mounted, settleFrames: request.settleFrames }, + effects: [...effects, { type: "watch-rows", attempt }], + } +} + +function settle(state: Active, mounted: MountedViewer, settleFrames: number): ViewerRenderTransition { + return { + state: { ...shared(state), status: "settling", mounted, framesLeft: Math.max(0, settleFrames) + 1 }, + effects: [{ type: "schedule-settle-frame", attempt: state.attempt }], + } +} + +function finish(state: Active, mounted: MountedViewer, outcome: "ready" | "timeout"): ViewerRenderTransition { + return { + state: { ...shared(state), heightPinned: false, status: "ready", mounted, outcome }, + effects: [ + ...(state.heightPinned ? [{ type: "release-height" as const }] : []), + { type: "reapply-selection" }, + ...(state.reveal ? [{ type: "try-reveal" as const, range: state.reveal }] : []), + { type: "refresh-find" }, + { type: "notify-rendered" }, + ], + } +} + +function cancel(state: Active) { + if (state.status === "idle" || (state.status === "ready" && state.outcome === "ready")) return NO_RENDER_EFFECTS + + return [CANCEL_ASYNC] +} + +function shared(state: Active) { + return { + attempt: state.attempt, + revision: state.revision, + heightPinned: state.heightPinned, + reveal: state.reveal, + timedOutPool: state.timedOutPool, + } +} + +function withMounted(state: Active, mounted: MountedViewer): ViewerRenderState { + if (state.status === "idle") return state + + return { ...state, mounted } +} + +function selectMounted(state: ViewerRenderState) { + return state.status === "idle" || state.status === "disposed" ? undefined : state.mounted +} + +export function readPoolState(pool: WorkerPoolManager | undefined): PoolReadiness { + if (!pool) return "none" + + if (pool.isInitialized()) return "ready" + + return pool.isWorkingPool() ? "initializing" : "broken" +} + +/** + * Whether an instance must be rebuilt rather than updated in place. Instances keep the virtualizer and pool they were + * built with; a virtualized diff also keeps its first target and hunk separators. + */ +export function needsInstanceReset(previous: ViewerInstanceSpec, next: ViewerInstanceSpec) { + if (previous.virtualizer !== next.virtualizer || previous.workerPool !== next.workerPool) return true + + if (next.virtualizer === undefined) return false + + return previous.hunkSeparators !== next.hunkSeparators || targetChanged(previous.target, next.target) +} + +function targetChanged(previous: ViewerTarget, next: ViewerTarget) { + if (previous.kind === "diff-patch" && next.kind === "diff-patch") return previous.fileDiff !== next.fileDiff + + if (previous.kind === "diff-files" && next.kind === "diff-files") + return !areFilesEqual(previous.before, next.before) || !areFilesEqual(previous.after, next.after) + + return previous.kind !== next.kind +} + +/** Whether Pierre draws any rows for this diff. */ +export function diffExpectsRows(target: ViewerTarget, expandUnchanged: boolean | undefined) { + if (target.kind === "diff-empty") return false + + if (target.kind === "diff-patch") + return ( + target.fileDiff.hunks.length > 0 || + (expandUnchanged === true && target.fileDiff.additionLines.length + target.fileDiff.deletionLines.length > 0) + ) + + if (target.kind === "diff-files") { + if (expandUnchanged === true) return target.before.contents.length + target.after.contents.length > 0 + + return target.before.contents !== target.after.contents + } + + return true +} + +export function selectRevision(state: ViewerRenderState) { + return state.status === "disposed" ? 0 : state.revision +} + +export function selectMountedSpec(state: ViewerRenderState) { + return selectMounted(state)?.spec +}