diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..4fe0116 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,53 @@ +# Notes for coding agents + +Read [CONTRIBUTING.md](CONTRIBUTING.md) first - its pull request expectations +apply to agents exactly as they do to people. What follows is what an agent +tends to skip. + +## Pull requests show what they change + +Any pull request that changes something a person can see gets screenshots, and +anything that moves - a scroll, an animation, a transition - gets a short video +or GIF. Reviewing a picture takes seconds; reviewing the same change from the +diff alone is slow and misses things. If a change has no visible effect, say so +in the description instead of leaving the reviewer to wonder. + +- Capture the real app, not a mock-up: build, launch Electron with + `--remote-debugging-port`, and drive it with the helpers in `scripts/cdp.mjs`. + Point `GITWARREN_DATA_DIR` at a scratch directory and pass a scratch + `--user-data-dir`, so neither the real database nor an already-running + GitWarren is touched. +- Show light and dark when colours are involved, and before and after when the + change is to something that already existed. +- Images are not committed to the branch under review. Push them as a commit of + their own to a `pr-assets/` branch, with the files at its root, and + embed them from that commit's SHA: + `https://raw.githubusercontent.com/klarluft/gitwarren-app//.png`. + Pinning the SHA keeps the images in the description stable even if the + branch moves. +- Say what each picture is showing in a line above it. A screenshot without a + caption makes the reviewer guess which part of it changed. + +## Every UI change works on a phone too + +GitWarren is used from phones - the web build is served over the tailnet - so a +change is not done until it has been checked at a phone's size, and the pull +request shows it there as well as on the desktop. + +- Check at a phone viewport, 390×844, with touch emulated - not a narrowed + desktop window. Over CDP that is `Emulation.setDeviceMetricsOverride` + (`mobile: true`), `Emulation.setTouchEmulationEnabled`, and + `Emulation.setEmulatedMedia` with `hover: none` and `pointer: coarse`, so the + `(hover: none)` styles the app relies on actually apply. Drive it with + `Input.dispatchTouchEvent`, not mouse events. +- Attach mobile screenshots beside the desktop ones, and a GIF for any gesture. +- Everything that can be done on the desktop must be doable on a phone. Smaller + elements are fine, and so is rearranging the layout for a narrow screen - + dropping a label to its icon, wrapping a row, moving something behind a + screen of its own. Losing a capability is not. Hover in particular does not + exist on a phone: anything a hover reveals needs a touch way to reach it. +- Touch targets can be smaller than they look, but not smaller than a thumb: + extend the hit area with an invisible pseudo-element rather than making the + control bigger. +- Nothing on the page may scroll sideways at 390px except code, inside its own + container. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2fa3ebe..513b0b6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -176,6 +176,14 @@ differently. pull requests. - **Describe the behaviour, not just the code.** What was wrong, what is right now, and how you checked. +- **Show anything that can be seen.** A change to the UI comes with screenshots + (light and dark where the theme matters, before and after where something + moved, and at a phone's size as well as the desktop's), and a change to how + something moves or animates comes with a short video or GIF. Whatever can be + done on the desktop has to be doable on a phone too, even if the layout + changes to get it there. A reviewer can judge a picture in seconds; reconstructing the + same thing from a diff of class names takes far longer and is easier to get + wrong. - **Match the surrounding style.** The codebase has a consistent voice in both its code and its comments — comments explain *why*, not *what*. ESLint covers the mechanical part; the rest is a matter of reading the neighbours. diff --git a/src/renderer/src/features/comments/use-comments.ts b/src/renderer/src/features/comments/use-comments.ts index 6d53194..9bef61c 100644 --- a/src/renderer/src/features/comments/use-comments.ts +++ b/src/renderer/src/features/comments/use-comments.ts @@ -15,7 +15,7 @@ * that moved on while the window was in the background. */ import { useSWRConfig } from 'swr' -import { useCallback } from 'react' +import { useCallback, useMemo } from 'react' import { CACHE_PREFIXES } from '@/lib/api' import { useApi } from '@/lib/host-scope' import { useReviewThreads } from '@/features/reviews/use-reviews' @@ -65,44 +65,51 @@ export function useCommentMutations(): CommentMutations { [mutate] ) - return { - createThread: useCallback( + const createThread: CommentMutations['createThread'] = useCallback( async (input) => { const thread = await api.comments.createThread(input) await revalidate() return thread }, [api, revalidate] - ), - reply: useCallback( + ) + const reply: CommentMutations['reply'] = useCallback( async (input) => { const comment = await api.comments.reply(input) await revalidate() return comment }, [api, revalidate] - ), - edit: useCallback( + ) + const edit: CommentMutations['edit'] = useCallback( async (id, body) => { const comment = await api.comments.update({ id, body }) await revalidate() return comment }, [api, revalidate] - ), - remove: useCallback( + ) + const remove: CommentMutations['remove'] = useCallback( async (id) => { await api.comments.remove({ id }) await revalidate() }, [api, revalidate] - ), - setResolved: useCallback( + ) + const setResolved: CommentMutations['setResolved'] = useCallback( async (threadId, resolved) => { await api.comments.setResolved({ threadId, resolved }) await revalidate() }, [api, revalidate] ) - } + + // One object for as long as the callbacks in it are the same ones. The files + // tab hands it to every file card, and a fresh object on each render would + // re-render all of them - every line of a four-hundred-file diff - whenever + // the reader scrolled onto a new file. + return useMemo( + () => ({ createThread, reply, edit, remove, setResolved }), + [createThread, reply, edit, remove, setResolved] + ) } diff --git a/src/renderer/src/features/reviews/__tests__/review-progress.test.ts b/src/renderer/src/features/reviews/__tests__/review-progress.test.ts new file mode 100644 index 0000000..51748cf --- /dev/null +++ b/src/renderer/src/features/reviews/__tests__/review-progress.test.ts @@ -0,0 +1,81 @@ +/** + * The progress strip counts files, not lines. + * + * Worth pinning down because it is the whole reason the strip exists: a lock + * file regenerated alongside four real changes must be one slot of five, and + * must not swallow the bar. + */ +import assert from 'node:assert/strict' +import { test } from 'node:test' + +import { fileAt, markRuns, readingPosition, type CardBox } from '../review-progress-model.js' + +const PATHS = ['a.ts', 'b.ts', 'package-lock.json', 'c.ts', 'd.ts'] + +test('neighbouring files in the same state are drawn as one run', () => { + const runs = markRuns(PATHS, new Set(['a.ts', 'b.ts', 'package-lock.json', 'd.ts']), new Set()) + assert.deepEqual(runs, [ + { mark: 'reviewed', start: 0, length: 3 }, + { mark: 'reviewed', start: 4, length: 1 } + ]) +}) + +test('a file changed since it was reviewed is a run of its own kind', () => { + const runs = markRuns(PATHS, new Set(['a.ts']), new Set(['b.ts', 'package-lock.json'])) + assert.deepEqual(runs, [ + { mark: 'reviewed', start: 0, length: 1 }, + { mark: 'changed', start: 1, length: 2 } + ]) +}) + +test('nothing reviewed is nothing drawn', () => { + assert.deepEqual(markRuns(PATHS, new Set(), new Set()), []) +}) + +/** Five cards stacked down the page; the lock file is a hundred times taller. */ +const HEIGHTS = [200, 200, 20_000, 200, 200] +function boxes(scrolled: number): (index: number) => CardBox { + return (index) => { + let top = -scrolled + for (let before = 0; before < index; before += 1) top += HEIGHTS[before] ?? 0 + return { top, height: HEIGHTS[index] ?? 0 } + } +} + +test('at the top of the diff the reader is at the start', () => { + assert.equal(readingPosition(5, 0, boxes(0), false), 0) +}) + +test('halfway through a short file is half a slot', () => { + assert.equal(readingPosition(5, 0, boxes(100), false), 0.5) +}) + +test('the lock file is one slot however long it scrolls', () => { + // Two short files read and halfway down a file a hundred times their size. + assert.equal(readingPosition(5, 0, boxes(400 + 10_000), false), 2.5) + // Past it, the reader is on file four - not four-fifths of the way through + // the lines of the branch. + assert.equal(readingPosition(5, 0, boxes(400 + 20_000), false), 3) +}) + +test('a scroller at its end has shown every file', () => { + assert.equal(readingPosition(5, 0, boxes(400), true), 5) +}) + +test('above the first card - the toolbar - is the start', () => { + assert.equal(readingPosition(5, 0, boxes(-50), false), 0) +}) + +test('a card missing from the DOM counts as still below the line', () => { + const box = boxes(250) + assert.equal(readingPosition(5, 0, (index) => (index >= 2 ? null : box(index)), false), 1.25) +}) + +test('a point on the strip lands on the slot under it', () => { + assert.equal(fileAt(5, 0, 500), 0) + assert.equal(fileAt(5, 250, 500), 2) + assert.equal(fileAt(5, 499, 500), 4) + // The far edge itself, and past it, is still the last file. + assert.equal(fileAt(5, 500, 500), 4) + assert.equal(fileAt(5, -10, 500), 0) +}) diff --git a/src/renderer/src/features/reviews/changed-files-tree.tsx b/src/renderer/src/features/reviews/changed-files-tree.tsx index 137ea8f..d4f76e2 100644 --- a/src/renderer/src/features/reviews/changed-files-tree.tsx +++ b/src/renderer/src/features/reviews/changed-files-tree.tsx @@ -18,7 +18,7 @@ * same ranking, the same name-first result row - means the gesture that finds a * file is one gesture in this app rather than one per tab. */ -import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from 'react' +import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from 'react' import { Check, ChevronDown, ChevronRight, History } from 'lucide-react' import { cn } from '@/lib/utils' import { plural } from '@/lib/format' @@ -200,7 +200,7 @@ export function ChangedFilesTree({ key={match.path} file={byPath.get(match.path) as FileDiff} indices={match.indices} - {...rowProps} + {...rowState(match.path, rowProps)} /> ))} {matches.total > matches.shown.length && ( @@ -228,7 +228,8 @@ function TreeRows({ const [open, setOpen] = useState(true) // Indent by nesting depth, but stop growing it before the column runs out of // room; a path fifteen directories deep should still show its file name. - const indent = { paddingLeft: `${Math.min(depth, 6) * 0.75 + 0.25}rem` } + const paddingLeft = `${Math.min(depth, 6) * 0.75 + 0.25}rem` + const indent = { paddingLeft } if (node.kind === 'directory') { return ( @@ -264,36 +265,60 @@ function TreeRows({ } // Always present: the tree was built from these very paths. - return + return ( + + ) +} + +/** + * What one row needs to know, boiled down to values that compare equal when + * nothing about that row changed - which is what lets `FileRow` skip the + * re-render. Scrolling onto a new file moves the highlight between two rows, + * and on a branch of four hundred files the other three hundred and ninety-eight + * have no reason to be drawn again. + */ +function rowState(path: string, props: Omit) { + return { + isActive: path === props.activePath, + isReviewed: props.reviewedPaths.has(path), + hasChangedSince: props.changedSincePaths.has(path), + unresolved: props.unresolvedByFile.get(path) ?? 0, + onSelect: props.onSelect + } } -function FileRow({ +const FileRow = memo(function FileRow({ file, indices, - indent, - activePath, - onSelect, - unresolvedByFile, - reviewedPaths, - changedSincePaths + paddingLeft, + isActive, + isReviewed, + hasChangedSince, + unresolved, + onSelect }: { file: FileDiff /** Set on a filter row: which characters of the path the query hit. */ indices?: number[] /** Set on a tree row, where the depth is what the indent is measuring. */ - indent?: { paddingLeft: string } -} & Omit) { + paddingLeft?: string + isActive: boolean + isReviewed: boolean + hasChangedSince: boolean + unresolved: number + onSelect: (path: string) => void +}) { const path = file.path - const unresolved = unresolvedByFile.get(path) ?? 0 - const isActive = path === activePath - const isReviewed = reviewedPaths.has(path) - const hasChangedSince = changedSincePaths.has(path) return ( ) -} +}) diff --git a/src/renderer/src/features/reviews/diff-find-bar.tsx b/src/renderer/src/features/reviews/diff-find-bar.tsx index 14fa19d..f98cafc 100644 --- a/src/renderer/src/features/reviews/diff-find-bar.tsx +++ b/src/renderer/src/features/reviews/diff-find-bar.tsx @@ -150,20 +150,33 @@ export function useDiffFind(files: readonly FileDiff[]): DiffFind { // eslint-disable-next-line react-hooks/exhaustive-deps }, [activeKey]) - const searchFor = useCallback( - (path: string): DiffSearch | undefined => - term === '' + /** + * The same object for every file the current hit is not in, and one more for + * the file it is. A card is only re-rendered when what it is handed changes, + * so a fresh object per file per render would redraw the whole diff on every + * step through the hits rather than the two files the step moved between. + */ + const passive = useMemo( + () => (term === '' ? undefined : { query: term, active: null }), + [term] + ) + const pointed = useMemo( + () => + term === '' || active === null ? undefined : { query: term, - active: - active !== null && active.filePath === path - ? { side: active.side, line: active.line, occurrence: active.occurrence } - : null + active: { side: active.side, line: active.line, occurrence: active.occurrence } }, [term, active] ) + const searchFor = useCallback( + (path: string): DiffSearch | undefined => + active !== null && active.filePath === path ? pointed : passive, + [active, pointed, passive] + ) + return { open, query, diff --git a/src/renderer/src/features/reviews/diff-snippet.tsx b/src/renderer/src/features/reviews/diff-snippet.tsx index 58cf038..f3b7023 100644 --- a/src/renderer/src/features/reviews/diff-snippet.tsx +++ b/src/renderer/src/features/reviews/diff-snippet.tsx @@ -126,7 +126,9 @@ export function DiffSnippet({
{clipped && (
- … + + … +
)} @@ -138,13 +140,19 @@ export function DiffSnippet({
- + {number ?? ''}
)} - {showsDiff && !previewing && ( -
+ {showsDiff && !previewing && !built && ( +
+ )} + + {showsDiff && !previewing && built && ( +
{/* `@container` makes this element an inline-size container, which is what lets a comment inside it be sized to the *visible* width rather than to the width of the scrolled code. */} @@ -748,7 +837,7 @@ export function FileDiffCard({ )} ) -} +}) /** * Copy the path to the clipboard. @@ -957,8 +1046,8 @@ function ExpanderBand({ const stepped = hidden === null || hidden > EXPAND_STEP return ( -
-
+
+
{/* Down unfolds from the top of the run, next to the code above it; up unfolds from the bottom, next to the code below. */} {hasAbove && stepped && ( @@ -1098,8 +1187,8 @@ function HunkRows({ return ( <> {showHeader && ( -
- +
+ {!oneGutter && } @@ -1227,6 +1326,7 @@ export function LineRow({ line, ...context }: { line: DiffLine } & RowContext) { commentable state={state} context={context} + pin={oneGutter ? 'left-0' : 'left-12'} />
@@ -1249,7 +1349,7 @@ export function LineRow({ line, ...context }: { line: DiffLine } & RowContext) { )} ) -} +}) /** * One row of the side-by-side diff: the base version on the left, the head @@ -1267,7 +1367,11 @@ export function LineRow({ line, ...context }: { line: DiffLine } & RowContext) { * in the left column, beneath the text it is about, rather than across the * whole width where it would cover the version it is not about. */ -function SplitLineRow({ row, ...context }: { row: SplitRow } & RowContext) { +/** Memoised like `LineRow`, with a comparison that sees through the pairing. */ +const SplitLineRow = memo(function SplitLineRow({ + row, + ...context +}: { row: SplitRow } & RowContext) { const left = row.left === null ? null : rowPosition(row.left) const right = row.right === null ? null : rowPosition(row.right) // The left half of a context row is the same line as the right half, so it @@ -1309,7 +1413,23 @@ function SplitLineRow({ row, ...context }: { row: SplitRow } & RowContext) { )} ) -} +}, +/** + * `splitRows` pairs the lines afresh on every render, so the row object is + * always new; what it pairs is not. Compared by its two sides, then the rest + * of the context field by field - the same thing `memo` does for `LineRow`. + */ +(previous, next) => { + for (const key of Object.keys(next) as (keyof typeof next)[]) { + if (key === 'row') continue + if (!Object.is(previous[key], next[key])) return false + } + return ( + Object.keys(previous).length === Object.keys(next).length && + previous.row.left === next.row.left && + previous.row.right === next.row.right + ) +}) function SplitHalf({ line, @@ -1342,7 +1462,7 @@ function SplitHalf({ data-diff-side={number === null ? undefined : side} data-diff-line={number === null ? undefined : number} className={cn( - 'group grid min-w-0 grid-cols-[3rem_minmax(0,1fr)]', + 'group grid min-w-0 grid-cols-[3rem_minmax(0,1fr)] bg-(--row-tint)', isLeft && 'border-r border-border', rowTone(line.type, state), state.inThread && 'shadow-[inset_3px_0_0_0_var(--color-primary)]' @@ -1368,7 +1488,8 @@ function CommentCell({ display, commentable, state, - context + context, + pin }: { side: DiffSide number: number | null @@ -1377,13 +1498,19 @@ function CommentCell({ commentable: boolean state: LineState context: RowContext + /** + * Where the cell sticks when the code beside it scrolls sideways - the unified + * row's columns. Absent side by side, which always wraps and never scrolls, + * and where a sticky offset would push the left half's numbers right. + */ + pin?: 'left-0' | 'left-12' }) { const { comments, onSelectStart, onSelectOver, filePath } = context const { composing, selected } = state return (
{ @@ -1710,7 +1837,7 @@ function LineText({ export function Gutter({ value }: { value: number | null }) { return ( - + {value ?? ''} ) diff --git a/src/renderer/src/features/reviews/review-files-tab.tsx b/src/renderer/src/features/reviews/review-files-tab.tsx index 6521241..4dfe490 100644 --- a/src/renderer/src/features/reviews/review-files-tab.tsx +++ b/src/renderer/src/features/reviews/review-files-tab.tsx @@ -11,6 +11,7 @@ * answer is cached under its own SWR key so switching back is instant. */ import { + memo, useCallback, useEffect, useMemo, @@ -53,7 +54,8 @@ import { plural } from '@/lib/format' import { useApi, useHost, useHostScope } from '@/lib/host-scope' import { useNarrow } from '@/lib/narrow' import { useStoredFlag, useStoredPreference } from '@/lib/preferences' -import { revealElement } from '@/lib/reveal' +import { revealElement, scrollToElement } from '@/lib/reveal' +import { scrollParent } from '@/lib/scroll-parent' import { cn } from '@/lib/utils' import { useRegisterCommands, type Command } from '@/features/commands/command-registry' import { navigate, replace, type DiffFocus } from '@/lib/router' @@ -70,8 +72,13 @@ import { DiffStat, FileDiffCard, type AnchoredThread, + type DiffComments, + type DiffFileSource, type DiffLayout } from './diff-view' +import type { DiffSearch } from './diff-search' +import { ReviewProgress } from './review-progress' +import { TOP_EDGE_SLACK } from './review-progress-model' import { DEFAULT_DIFF_CHANGES, useEditors, @@ -87,18 +94,6 @@ import type { DiffChanges, FileDiff as FileDiffData } from '@shared/git' import { isSelfReview } from '@shared/schemas' import type { CommentThread, Review } from '@shared/schemas' -/** - * How far below the top of the scroller a file card may still sit and count as - * the one being read. - * - * Larger than it looks like it needs to be, deliberately. `scrollIntoView` does - * not land exactly on zero - measured, it settles several pixels short - and the - * cards are separated by a gap of their own. A threshold tighter than that error - * makes a stepped-to file read as "not reached yet", so the next press aims at - * the same file again and stepping appears to stick. It only has to stay far - * below the height of any card to be unambiguous, and it does. - */ -const TOP_EDGE_SLACK = 24 /** * The three views of a review's changes, in the order `u` steps through them. @@ -130,23 +125,6 @@ function nextChangesAfter(current: DiffChanges): DiffChanges { return CHANGES_CYCLE[(index + 1) % CHANGES_CYCLE.length] ?? 'all' } -/** - * The element a card actually scrolls inside. - * - * The app scrolls in a `
` that sits below the title bar, not in the - * window, so a card resting at the top of the page still reports a viewport - * offset of the title bar's height. Comparing against the scroller's own top - * edge instead is what makes "which file is at the top" independent of whatever - * chrome the shell puts above it. - */ -function scrollParent(element: HTMLElement): HTMLElement { - for (let node = element.parentElement; node !== null; node = node.parentElement) { - const overflow = getComputedStyle(node).overflowY - if (overflow === 'auto' || overflow === 'scroll') return node - } - return document.documentElement -} - /** * How far below its scroller a card comes to rest when it is scrolled to - * where the reading area starts, rather than where the scroller does. @@ -169,15 +147,6 @@ function readingTop(card: HTMLElement): number { return scrollParent(card).getBoundingClientRect().top + readingInset(card) } -/** - * The gap the tab leaves between the blocks stacked down it - `gap-3`. - * - * Written out here because the sticky offset is arithmetic done in JS: a header - * parking directly against the underside of the find bar reads as one welded - * bar, and the gap it rests below is the same one it would have had in the flow. - */ -const STICKY_GAP = '0.75rem' - /** * The height of an element as it changes, for whoever has to leave room for it. * @@ -406,7 +375,7 @@ function useFocusScroll(focus: DiffFocus | undefined, ready: boolean): DiffFocus const target = line ?? document.getElementById(fileDomId(focus.filePath)) if (target) { - target.scrollIntoView({ block: line ? 'center' : 'start', behavior: 'smooth' }) + scrollToElement(target, { block: line ? 'center' : 'start', behavior: 'smooth' }) if (line) { setMarked(focus) // Long enough to catch the eye after a smooth scroll, short enough @@ -478,16 +447,19 @@ function useFilesLayout(): { const selectFile = useCallback( (path: string) => { - if (narrow) { + // Only while the list is the screen. The progress strip picks files too, + // and from the diff itself: there the list is already shut, setting it + // shut again re-renders nothing, the effect above never runs, and the + // jump would silently not happen. + if (narrow && listScreen) { pending.current = path setListScreen(false) return } - document - .getElementById(fileDomId(path)) - ?.scrollIntoView({ block: 'start', behavior: 'smooth' }) + const element = document.getElementById(fileDomId(path)) + if (element !== null) scrollToElement(element, { block: 'start', behavior: 'smooth' }) }, - [narrow] + [narrow, listScreen] ) return { @@ -562,7 +534,7 @@ export function ReviewFilesTab({ review, focus }: { review: Review; focus?: Diff const files = useMemo(() => data?.files ?? [], [data?.files]) const paths = useMemo(() => files.map((file) => file.path), [files]) const find = useDiffFind(files) - const [bindFindBar, findBarHeight] = useMeasuredHeight() + const [bindPinned, pinnedHeight] = useMeasuredHeight() /** * Take the find bar's query to the whole repository. @@ -583,11 +555,15 @@ export function ReviewFilesTab({ review, focus }: { review: Review; focus?: Diff * Where a sticky thing in this tab parks, and how far below the top of the * scroller a scrolled-to card comes to rest. * - * Both shift down by the find bar when it is open, because it is sticky too - * and sits above everything else: a file header pinned to the top of the - * scroller would spend the whole search hidden behind it. + * Both shift down by whatever is pinned above the diff - the progress strip, + * and the find bar when it is open - because those sit above everything + * else: a file header pinned to the top of the scroller would spend the whole + * review hidden behind them. */ - const stickyTop = find.open ? `calc(${findBarHeight}px + ${STICKY_GAP})` : '0px' + // The pinned block carries the gap below it as padding of its own, painted + // over, so code scrolling up never shows through between the strip and the + // header of the file being read. Its measured height already includes it. + const stickyTop = `${pinnedHeight}px` const stickyStyle = { '--diff-sticky-top': stickyTop, '--diff-scroll-top': `calc(${stickyTop} + 0.5rem)` @@ -678,6 +654,22 @@ export function ReviewFilesTab({ review, focus }: { review: Review; focus?: Diff [digestByPath, setReviewed, paths, scrollToSettled] ) + /** + * `markReviewed` for the cards, under one identity for the life of the tab. + * + * The real one is rebuilt with every mark - it closes over the marks - and + * handing that to four hundred memoised cards would re-render all of them + * each time one file is ticked off. This forwards to whichever is current. + */ + const latestMarkReviewed = useRef(markReviewed) + useEffect(() => { + latestMarkReviewed.current = markReviewed + }, [markReviewed]) + const onMarkReviewed = useCallback( + (path: string, next: boolean) => latestMarkReviewed.current(path, next), + [] + ) + /** What the tree shows next to a file: comments still waiting on someone. */ const unresolvedByFile = useMemo(() => { const counts = new Map() @@ -739,6 +731,27 @@ export function ReviewFilesTab({ review, focus }: { review: Review; focus?: Diff const marked = useFocusScroll(focus, !isLoading && data !== undefined) + /** What every card's comments share; each card adds its own threads. */ + const sharedComments = useMemo( + () => ({ reviewId: review.id, mutations, changes }), + [review.id, mutations, changes] + ) + + const editorLabel = + editors?.editors.find((editor) => editor.id === (editorId ?? editors.defaultId))?.label ?? null + + /** One object for every card, rebuilt only when one of its parts changes. */ + const source = useMemo( + () => ({ + reviewId: review.id, + changes, + editorId, + editorLabel, + onOpenInEditor: openInEditor + }), + [review.id, changes, editorId, editorLabel, openInEditor] + ) + /** * Which file the reader is on, measured from the layout: the last card whose * top edge has passed the top of the scroller, with everything after it still @@ -999,17 +1012,6 @@ export function ReviewFilesTab({ review, focus }: { review: Review; focus?: Diff {plural(data.files.length, 'file')} changed

- {/* Only once there is progress to report; "0 of 12 reviewed" is a - statement of the obvious taking up room next to the file count. */} - {reviewedPaths.size > 0 && ( -

- - {reviewedPaths.size} of {data.files.length} reviewed -

- )}
{/* On a phone the three buttons keep their icons and lose their words, @@ -1122,8 +1124,26 @@ export function ReviewFilesTab({ review, focus }: { review: Review; focus?: Diff
- {find.open && ( - + {/* Pinned above the diff as one block, measured as one, so the card + headers below know how far down to park. The strip is only worth its + room once there is more than one file to be part of the way through. */} + {(find.open || data.files.length > 1) && ( + // `pb-3 -mb-3` is the tab's own gap, moved inside the block so it is + // opaque; the flow below is spaced exactly as before. +
+ {find.open && } + {data.files.length > 1 && ( + + )} +
)} {changes !== 'committed' && data.workingTree?.isDirty && ( @@ -1286,48 +1306,24 @@ export function ReviewFilesTab({ review, focus }: { review: Review; focus?: Diff )} > {data.files.map((file) => ( -
- markReviewed(file.path, next) - }} - comments={{ - reviewId: review.id, - threads: threadsByFile.get(file.path) ?? [], - mutations, - changes - }} - source={{ - reviewId: review.id, - changes, - editorId, - editorLabel: - editors?.editors.find( - (editor) => editor.id === (editorId ?? editors.defaultId) - )?.label ?? null, - onOpenInEditor: openInEditor - }} - /> -
+ file={file} + changes={changes} + // Only the card that owns the line hears about it, so one + // arriving link cannot light up the same number in every file. + focus={focus?.filePath === file.path ? focus : undefined} + search={find.searchFor(file.path)} + layout={layout} + wrap={wrap} + marked={marked?.filePath === file.path ? marked : undefined} + isReviewed={reviewedPaths.has(file.path)} + hasChangedSince={changedSincePaths.has(file.path)} + onMarkReviewed={onMarkReviewed} + threads={threadsByFile.get(file.path) ?? NO_THREADS} + comments={sharedComments} + source={source} + /> ))}
@@ -1342,6 +1338,84 @@ export function ReviewFilesTab({ review, focus }: { review: Review; focus?: Diff ) } +const NO_THREADS: AnchoredThread[] = [] + +/** + * One file in the diff, and the reason the tab can be scrolled at all on a big + * branch. + * + * The tab re-renders whenever the reader scrolls onto a new file - the file + * list's highlight moves - and before this every one of those re-rendered every + * card and every line in it. Memoised, and handed only values that keep their + * identity, a card now re-renders when something about *that file* changed: + * its mark, its threads, a search hit in it. + */ +const FileDiffItem = memo(function FileDiffItem({ + file, + changes, + focus, + search, + layout, + wrap, + marked, + isReviewed, + hasChangedSince, + onMarkReviewed, + threads, + comments, + source +}: { + file: FileDiffData + changes: DiffChanges + focus: DiffFocus | undefined + search: DiffSearch | undefined + layout: DiffLayout + wrap: boolean + marked: DiffFocus | undefined + isReviewed: boolean + hasChangedSince: boolean + onMarkReviewed: (path: string, next: boolean) => void + threads: AnchoredThread[] + comments: Omit + source: DiffFileSource +}) { + const path = file.path + const reviewed = useMemo( + () => ({ + isReviewed, + hasChangedSince, + onChange: (next: boolean) => onMarkReviewed(path, next) + }), + [isReviewed, hasChangedSince, onMarkReviewed, path] + ) + const fileComments = useMemo(() => ({ ...comments, threads }), [comments, threads]) + const markedLine = useMemo(() => focusedLine(marked), [marked]) + + return ( +
+ +
+ ) +}) + /** * Which of the three views of the changes is on screen. * diff --git a/src/renderer/src/features/reviews/review-progress-model.ts b/src/renderer/src/features/reviews/review-progress-model.ts new file mode 100644 index 0000000..1770e0c --- /dev/null +++ b/src/renderer/src/features/reviews/review-progress-model.ts @@ -0,0 +1,122 @@ +/** + * The arithmetic behind the review progress strip, kept apart from the DOM so + * it can be tested on its own. + * + * Everything here counts in *files*, never in lines. A branch that touches four + * source files and regenerates a lock file is five files of work, not one lock + * file with some code attached: reading past the lock file is one step of five, + * however many thousand lines it scrolls. + */ + +/** + * How far below the top of the scroller a file card may still sit and count as + * the one being read. + * + * Shared by stepping with `[` and `]` and by the progress strip, so the strip + * never names a different file from the one the next key press leaves. + * + * Larger than it looks like it needs to be, deliberately. `scrollIntoView` does + * not land exactly on zero - measured, it settles several pixels short - and the + * cards are separated by a gap of their own. A threshold tighter than that error + * makes a stepped-to file read as "not reached yet", so the next press aims at + * the same file again and stepping appears to stick. It only has to stay far + * below the height of any card to be unambiguous, and it does. + */ +export const TOP_EDGE_SLACK = 24 + +export type FileMark = 'reviewed' | 'changed' | 'unread' + +/** A stretch of neighbouring files in the same state, in file units. */ +export interface MarkRun { + mark: Exclude + start: number + length: number +} + +/** + * The reviewed and changed-since files as runs. + * + * Drawn as one element per run rather than one per file, so a thousand-file + * branch that has been read straight through is a single bar and not a + * thousand slivers. Unread files are the track itself and need no element. + */ +export function markRuns( + paths: readonly string[], + reviewed: ReadonlySet, + changed: ReadonlySet +): MarkRun[] { + const runs: MarkRun[] = [] + for (const [index, path] of paths.entries()) { + const mark: FileMark = reviewed.has(path) + ? 'reviewed' + : changed.has(path) + ? 'changed' + : 'unread' + if (mark === 'unread') continue + const last = runs.at(-1) + if (last !== undefined && last.mark === mark && last.start + last.length === index) { + last.length += 1 + } else { + runs.push({ mark, start: index, length: 1 }) + } + } + return runs +} + +/** Where a file's card sits, measured in the same coordinates as the line. */ +export interface CardBox { + top: number + height: number +} + +/** + * How far down the list of files the reader is, from 0 to `count`. + * + * The whole part is the file whose card is under the reading line - where a + * card stepped to comes to rest, give or take `TOP_EDGE_SLACK` - and the fraction is + * how much of that card has gone past it. So the marker moves through a short + * file quickly and a long one slowly, but every file is the same width on the + * strip, and finishing a file always moves it on by exactly one slot. + * + * Cards are in document order, so the one under the line is found by binary + * search: a handful of layout reads per scroll frame, however long the diff. + * `boxOf` returns null for a card that is not in the DOM; it is treated as + * still below the line. + */ +export function readingPosition( + count: number, + line: number, + boxOf: (index: number) => CardBox | null, + atEnd: boolean +): number { + if (count === 0) return 0 + // A scroller that cannot go any further has shown the reader everything, + // including a last file too short ever to reach the top. + if (atEnd) return count + + let low = 0 + let high = count - 1 + let found = -1 + let foundBox: CardBox | null = null + while (low <= high) { + const middle = (low + high) >> 1 + const box = boxOf(middle) + if (box !== null && box.top <= line) { + found = middle + foundBox = box + low = middle + 1 + } else { + high = middle - 1 + } + } + + if (found === -1 || foundBox === null) return 0 + const through = foundBox.height <= 0 ? 1 : (line - foundBox.top) / foundBox.height + return found + Math.min(1, Math.max(0, through)) +} + +/** Which file a point along the strip is over, given its width. */ +export function fileAt(count: number, offset: number, width: number): number { + if (count === 0 || width <= 0) return 0 + return Math.min(count - 1, Math.max(0, Math.floor((offset / width) * count))) +} diff --git a/src/renderer/src/features/reviews/review-progress.tsx b/src/renderer/src/features/reviews/review-progress.tsx new file mode 100644 index 0000000..2bef83d --- /dev/null +++ b/src/renderer/src/features/reviews/review-progress.tsx @@ -0,0 +1,458 @@ +/** + * How far through the review the reader is: where they have scrolled to, and + * how much of it they have ticked off. + * + * One slot per file, every slot the same width. The scrollbar already says how + * far down the *lines* you are, and on a branch that regenerated a lock file it + * says you are nowhere: the lock file is most of the page. This says you are on + * file three of five, which is the question a reviewer is actually asking. + * + * Three things on one track: + * - green slots for files marked reviewed, amber for files that changed after + * they were marked - the same colours the file list uses for both; + * - a lighter wash up to the marker, for what has been scrolled past; + * - the marker itself, which moves through a file as it is read. + * + * The strip is its own component with its own scroll listener on purpose. The + * reading position changes every frame while the page moves, and that state + * living in the files tab would re-render the tab - and ask four hundred file + * cards whether they had changed - sixty times a second. + */ +import { + memo, + useEffect, + useMemo, + useRef, + useState, + type MouseEvent, + type RefObject +} from 'react' +import { Check, CheckCheck, History, PartyPopper } from 'lucide-react' +import { FileStatusIcon } from './diff-view' +import { fileDomId } from './dom-ids' +import { FilePath } from './file-path' +import { fileAt, markRuns, readingPosition, TOP_EDGE_SLACK } from './review-progress-model' +import { scrollParent } from '@/lib/scroll-parent' +import { cn } from '@/lib/utils' +import type { FileDiff } from '@shared/git' + +/** + * Up to how many files the slots are drawn with a gap between them. Past this + * a gap is wider than the slot it separates, and the strip reads as a comb. + */ +const SEPARATE_SLOTS_UP_TO = 80 + +/** How long a newly ticked slot glows for; matches `review-tick` in index.css. */ +const TICK_GLOW_MS = 900 + +export interface ReviewProgressProps { + files: readonly FileDiff[] + reviewedPaths: ReadonlySet + changedSincePaths: ReadonlySet + /** Take the reader to a file - the same thing picking it in the file list does. */ + onSelect: (path: string) => void +} + +const percent = (part: number, whole: number): string => + `${whole === 0 ? 0 : (part / whole) * 100}%` + +/** + * The reading position, in files, kept up to date while the page scrolls. + * + * Read on the next frame after a scroll rather than on the scroll itself, so a + * fast flick that fires a dozen events between paints costs one measurement. + * Also re-read when the column of cards changes size: ticking a file off folds + * it, which moves everything below without the scroller moving at all. + */ +function useReadingPosition( + paths: readonly string[], + strip: RefObject +): number { + const [position, setPosition] = useState(0) + + useEffect(() => { + const anchor = strip.current + if (anchor === null || paths.length === 0) return + + const scroller = scrollParent(anchor) + const isDocument = scroller === document.documentElement + let frame = 0 + + const measure = (): void => { + frame = 0 + // The line a card comes to rest on when it is stepped or jumped to - the + // top of the scroller plus the cards' `scroll-mt`, which clears the + // pinned strip - so the file a jump lands on is the file this names. + const firstPath = paths[0] + const firstCard = + firstPath === undefined ? null : document.getElementById(fileDomId(firstPath)) + const margin = + firstCard === null ? 0 : parseFloat(getComputedStyle(firstCard).scrollMarginTop) || 0 + // The diff is hidden behind the file list on a phone. Every card then + // measures zero and the page reads as finished, so the strip would claim + // the last file; it keeps where the reader actually was instead. + if (firstCard !== null && firstCard.offsetParent === null) return + const top = isDocument ? 0 : scroller.getBoundingClientRect().top + const line = top + margin + TOP_EDGE_SLACK + const atEnd = scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 2 + const next = readingPosition( + paths.length, + line, + (index) => { + const path = paths[index] + const card = path === undefined ? null : document.getElementById(fileDomId(path)) + if (card === null) return null + const box = card.getBoundingClientRect() + return { top: box.top, height: box.height } + }, + atEnd + ) + // Rounded to a few thousandths of a file, so a scroll that moves nothing + // anyone could see does not re-render the strip either. + setPosition(Math.round(next * 1000) / 1000) + } + const schedule = (): void => { + if (frame === 0) frame = requestAnimationFrame(measure) + } + + measure() + const target: HTMLElement | Window = isDocument ? window : scroller + target.addEventListener('scroll', schedule, { passive: true }) + const resize = new ResizeObserver(schedule) + resize.observe(scroller) + const firstPath = paths[0] + const column = + firstPath === undefined ? null : document.getElementById(fileDomId(firstPath))?.parentElement + if (column) resize.observe(column) + + return () => { + cancelAnimationFrame(frame) + target.removeEventListener('scroll', schedule) + resize.disconnect() + } + }, [paths, strip]) + + return position +} + +/** + * Files ticked off in the last moment, so their slots can light up. + * + * Only additions, and only ones made while the strip is on screen - a review + * opened with sixty files already marked does not greet the reader with sixty + * flashes. + */ +function useJustReviewed(reviewedPaths: ReadonlySet): ReadonlySet { + const previous = useRef(reviewedPaths) + const [glowing, setGlowing] = useState>(() => new Set()) + // One timer per glow, cleared only when the strip goes away. Clearing it on + // the next change instead - the obvious effect cleanup - left a file ticked + // a moment before another glowing for good, because its timer never ran. + const timers = useRef(new Set()) + + useEffect(() => { + const pending = timers.current + return () => { + for (const timer of pending) window.clearTimeout(timer) + } + }, []) + + useEffect(() => { + const before = previous.current + previous.current = reviewedPaths + const added = [...reviewedPaths].filter((path) => !before.has(path)) + if (added.length === 0 || added.length > 3) return + + setGlowing((current) => new Set([...current, ...added])) + const timer = window.setTimeout(() => { + timers.current.delete(timer) + setGlowing((current) => { + const next = new Set(current) + for (const path of added) next.delete(path) + return next + }) + }, TICK_GLOW_MS) + timers.current.add(timer) + }, [reviewedPaths]) + + return glowing +} + +export const ReviewProgress = memo(function ReviewProgress({ + files, + reviewedPaths, + changedSincePaths, + onSelect +}: ReviewProgressProps) { + const paths = useMemo(() => files.map((file) => file.path), [files]) + const count = paths.length + const strip = useRef(null) + const track = useRef(null) + const position = useReadingPosition(paths, strip) + const glowing = useJustReviewed(reviewedPaths) + const [hovered, setHovered] = useState(null) + + const runs = useMemo( + () => markRuns(paths, reviewedPaths, changedSincePaths), + [paths, reviewedPaths, changedSincePaths] + ) + + // Counted against the files on screen, not against the stored marks: a mark + // for a file that has since left the diff is nothing left to do. + const reviewed = reviewedPaths.size + const done = count > 0 && reviewed === count + const current = Math.min(count, Math.floor(position) + 1) + // Never "0%" once something is ticked, and never "100%" until everything is: + // three files into four hundred is a start, and the number should say so. + const share = + reviewed === 0 || count === 0 + ? 0 + : done + ? 100 + : Math.min(99, Math.max(1, Math.round((reviewed / count) * 100))) + + /** + * A finger on the track, being dragged along it. + * + * A touch screen has no hover, so the hover card - which file a slot is, + * before going there - would be the one thing the strip could do on a desktop + * and not on a phone. Pressing on the track and sliding along it shows the + * same card under the finger, and lifting goes to the file it names: the + * scrubber gesture a video player taught everyone. A tap is the same gesture + * with no slide, so it still jumps straight to the slot it lands on. + */ + const [scrubbing, setScrubbing] = useState(false) + // The click a finger's release produces after a scrub, which has already + // jumped. Without this a tap would go to its file twice. + const swallowClick = useRef(false) + + function pointAt(event: MouseEvent): number { + const box = event.currentTarget.getBoundingClientRect() + return fileAt(count, event.clientX - box.left, box.width) + } + + const hoveredFile = hovered === null ? undefined : files[hovered] + + return ( +
+ {/* The track. A pointer target as a shortcut - the file list and `[`/`]` + are the ways in that do not need one - so it is a progress bar to + assistive technology, and the jump is a bonus for a mouse or a + finger. */} +
{ + if (event.pointerType === 'mouse') return + event.currentTarget.setPointerCapture(event.pointerId) + setScrubbing(true) + setHovered(pointAt(event)) + }} + onPointerMove={(event) => { + if (event.pointerType === 'mouse' || scrubbing) setHovered(pointAt(event)) + }} + onPointerUp={(event) => { + if (!scrubbing) return + setScrubbing(false) + setHovered(null) + swallowClick.current = true + const path = paths[pointAt(event)] + if (path !== undefined) onSelect(path) + }} + onPointerCancel={() => { + setScrubbing(false) + setHovered(null) + }} + onPointerLeave={(event) => { + if (event.pointerType === 'mouse') setHovered(null) + }} + onClick={(event) => { + if (swallowClick.current) { + swallowClick.current = false + return + } + const path = paths[pointAt(event)] + if (path !== undefined) onSelect(path) + }} + > +
+ {/* Scrolled past. Under the marks, so a reviewed file reads as + reviewed whichever side of the marker it is on. */} +
+ + {runs.map((run) => ( +
+ ))} + + {[...glowing].map((path) => { + const index = paths.indexOf(path) + // A tick taken back while it is still glowing stops glowing with it. + if (index === -1 || !reviewedPaths.has(path)) return null + return ( +
+ ) + })} + + {/* The gaps between slots, drawn over everything as one repeating + background rather than one element per file. */} + {count > 1 && count <= SEPARATE_SLOTS_UP_TO && ( +
+ )} + + {hovered !== null && ( +
+ )} +
+ + {/* Where the reader is. Taller than the track so it can be found on a + bar that is entirely green. */} +
+ + {hoveredFile !== undefined && hovered !== null && ( + + )} +
+ +

+ {/* Shorter on a phone rather than gone: where you are matters there + just as much, and "3/5" is a third of the width of the words. */} + + File {current} + of + / + {count} + + {done ? ( + + + All {count} reviewed + + ) : ( + 0 && 'text-foreground')} + title="Files you have marked as reviewed. A mark clears itself when its file changes." + > + 0 && 'text-success')} /> + {/* Keyed on the count so it rises in afresh each time it goes up. */} + + {reviewed}/{count} + + · {share}% + + )} +

+
+ ) +}) + +/** + * Which file a point on the track is, before the click that goes there. + * + * Kept to its slot's side of the track near either end, so a file at the edge + * of the strip does not push its own label off the window. + */ +function HoverCard({ + file, + index, + count, + isReviewed, + hasChangedSince, + underFinger +}: { + file: FileDiff + index: number + count: number + isReviewed: boolean + hasChangedSince: boolean + /** Dropped further below the track, clear of the thumb that is on it. */ + underFinger: boolean +}) { + const centre = (index + 0.5) / count + const align = centre < 0.2 ? 'start' : centre > 0.8 ? 'end' : 'middle' + + return ( +
+ {isReviewed ? ( + + ) : hasChangedSince ? ( + + ) : ( + + )} + + + + + {index + 1}/{count} + +
+ ) +} diff --git a/src/renderer/src/index.css b/src/renderer/src/index.css index f34345c..adaae90 100644 --- a/src/renderer/src/index.css +++ b/src/renderer/src/index.css @@ -170,9 +170,10 @@ } /* - * The one keyframe the app defines. Everything else that animates does so - * through Base UI's `data-[starting-style]`, which needs a primitive to hang - * off; the back-to-top button is a plain conditional render and has none. + * Keyframes. Most things that animate do so through Base UI's + * `data-[starting-style]`, which needs a primitive to hang off; these are for + * plain conditional renders that have none - the back-to-top button, and the + * review progress strip's counter. */ @keyframes rise-in { from { @@ -181,6 +182,55 @@ } } +/* A slot on the review progress strip, just ticked off: a flare that fades. */ +@keyframes review-tick { + from { + filter: brightness(1.6); + box-shadow: 0 0 0.5rem 0.125rem var(--color-success); + } + to { + filter: none; + box-shadow: none; + opacity: 0; + } +} + +/* The whole strip, once, when the last file in the review is ticked off. */ +@keyframes review-done { + 0% { + box-shadow: 0 0 0 0 var(--color-success); + } + 40% { + filter: brightness(1.35); + box-shadow: 0 0 0.75rem 0.125rem var(--color-success); + } + 100% { + box-shadow: 0 0 0 0 transparent; + } +} + +/* + * A line-number cell that stays put while the code beside it scrolls sideways. + * + * Without it a long line - or the find jumping to a hit far along one - takes + * the numbers out of view, and with them the comment button, which is the + * one place a comment can be started from. The row's tint is a translucent + * colour over the card, so a pinned cell cannot just be transparent: the code + * scrolling under it would show through. It paints the same tint over an + * opaque card instead, read from `--row-tint` on the row, and carries the + * row's left-edge mark (`--row-mark`) because it now covers where that was. + */ +@utility diff-gutter { + position: sticky; + z-index: 1; + background: + linear-gradient(var(--row-tint, transparent), var(--row-tint, transparent)), + var(--color-card); + &:first-child { + box-shadow: inset 3px 0 0 0 var(--row-mark, transparent); + } +} + /* The draggable strip behind the macOS traffic lights. */ .titlebar-drag { -webkit-app-region: drag; diff --git a/src/renderer/src/lib/near-viewport.ts b/src/renderer/src/lib/near-viewport.ts new file mode 100644 index 0000000..acf99ef --- /dev/null +++ b/src/renderer/src/lib/near-viewport.ts @@ -0,0 +1,78 @@ +/** + * Find out, once, when an element first comes near the visible part of its + * scroller. + * + * This is what lets a four-hundred-file diff open in the time a ten-file one + * does: a card draws its header straight away and its body only when the reader + * is about to reach it. "Near" is a screenful and a half either side, so the + * body is built while it is still out of sight and scrolling never lands on a + * blank one. + * + * One observer per scroller rather than one per element. A diff that needs this + * at all has hundreds of cards, and the browser answers for all of them in a + * single pass when they share an observer. + * + * The root has to be the scroller and not the window. An observer rooted at the + * window still sees through the scroller's clipping, so anything scrolled out + * of `
` would never count as near however wide the margin was drawn. + */ +import { scrollParent } from './scroll-parent' + +/** How far beyond the visible part of the scroller counts as near. */ +const LOOKAHEAD = '150% 0px' + +interface Watch { + observer: IntersectionObserver + callbacks: Map void> +} + +const watches = new Map() + +function watchFor(root: HTMLElement): Watch { + const existing = watches.get(root) + if (existing) return existing + + const callbacks = new Map void>() + const observer = new IntersectionObserver( + (entries) => { + for (const entry of entries) { + if (!entry.isIntersecting) continue + const callback = callbacks.get(entry.target) + if (callback === undefined) continue + forget(root, entry.target) + callback() + } + }, + { + // The document's own scroller is the implicit root; naming it explicitly + // makes the margin apply to an element rather than to the viewport. + root: root === document.documentElement ? null : root, + rootMargin: LOOKAHEAD + } + ) + + const watch = { observer, callbacks } + watches.set(root, watch) + return watch +} + +function forget(root: HTMLElement, element: Element): void { + const watch = watches.get(root) + if (watch === undefined) return + watch.observer.unobserve(element) + watch.callbacks.delete(element) + // A scroller that leaves the page takes its observer with it. + if (watch.callbacks.size === 0) { + watch.observer.disconnect() + watches.delete(root) + } +} + +/** Call `onNear` the first time `element` is near view. Returns a cancel. */ +export function whenNearViewport(element: HTMLElement, onNear: () => void): () => void { + const root = scrollParent(element) + const watch = watchFor(root) + watch.callbacks.set(element, onNear) + watch.observer.observe(element) + return () => forget(root, element) +} diff --git a/src/renderer/src/lib/reveal.ts b/src/renderer/src/lib/reveal.ts index 2ee6ef3..2a03ef4 100644 --- a/src/renderer/src/lib/reveal.ts +++ b/src/renderer/src/lib/reveal.ts @@ -11,9 +11,41 @@ * the diff, and there is nothing useful to say about it mid-jump. */ +import { scrollParent } from './scroll-parent' + /** Half a second at 60Hz: long enough for a tab switch, short enough to drop. */ const MAX_FRAMES = 30 +/** + * How many screens away a target may be and still be scrolled to smoothly. + * See `scrollToElement`. + */ +const SMOOTH_WITHIN_SCREENS = 3 + +/** + * `scrollIntoView`, except that a smooth scroll to something far away is made + * instant. + * + * Two reasons, and the second is the one that matters. An animation across a + * hundred screens of diff is a blur that tells the reader nothing about where + * they went. And a long diff builds each file's rows as it comes near the + * screen - see `lib/near-viewport.ts` - so a smooth scroll from the top to the + * last file builds every file in between, which on a four-hundred-file branch + * is the whole two million elements the lazy build exists to avoid. + */ +export function scrollToElement(element: HTMLElement, options: ScrollIntoViewOptions): void { + if (options.behavior === 'smooth') { + const scroller = scrollParent(element) + const top = scroller === document.documentElement ? 0 : scroller.getBoundingClientRect().top + const distance = Math.abs(element.getBoundingClientRect().top - top) + if (distance > scroller.clientHeight * SMOOTH_WITHIN_SCREENS) { + element.scrollIntoView({ ...options, behavior: 'instant' }) + return + } + } + element.scrollIntoView(options) +} + export function revealElement( id: string, options: ScrollIntoViewOptions = { block: 'start', behavior: 'smooth' } @@ -24,7 +56,7 @@ export function revealElement( const attempt = (): void => { const element = document.getElementById(id) if (element) { - element.scrollIntoView(options) + scrollToElement(element, options) return } frames += 1 diff --git a/src/renderer/src/lib/scroll-parent.ts b/src/renderer/src/lib/scroll-parent.ts new file mode 100644 index 0000000..95e4bff --- /dev/null +++ b/src/renderer/src/lib/scroll-parent.ts @@ -0,0 +1,17 @@ +/** + * The element something actually scrolls inside. + * + * The app scrolls in a `
` that sits below the title bar, not in the + * window, so a card resting at the top of the page still reports a viewport + * offset of the title bar's height. Comparing against the scroller's own top + * edge instead is what makes "which file is at the top" independent of whatever + * chrome the shell puts above it - and an observer rooted anywhere else would + * have the scroller clip away everything it was asked to look ahead for. + */ +export function scrollParent(element: HTMLElement): HTMLElement { + for (let node = element.parentElement; node !== null; node = node.parentElement) { + const overflow = getComputedStyle(node).overflowY + if (overflow === 'auto' || overflow === 'scroll') return node + } + return document.documentElement +} diff --git a/tsconfig.node.json b/tsconfig.node.json index fb37a3a..cb7e412 100644 --- a/tsconfig.node.json +++ b/tsconfig.node.json @@ -60,6 +60,8 @@ "src/renderer/src/features/reviews/__tests__/remark-change-marks.test.ts", "src/renderer/src/features/reviews/folder-name.ts", "src/renderer/src/features/reviews/__tests__/folder-name.test.ts", + "src/renderer/src/features/reviews/review-progress-model.ts", + "src/renderer/src/features/reviews/__tests__/review-progress.test.ts", "src/web/loopback-fragment.ts", "src/web/__tests__/loopback-fragment.test.ts", "src/web/wire.ts",