From cf9efe770bd846ff4d9f3ef845a2562ffce7fc7e Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Wed, 2 Dec 2026 17:37:49 +1300 Subject: [PATCH] Snapshot page: images never larger than their own size (capture scale from -2x/@2x names), fitted to the screen by default, with Fit/100%/200% zoom (z, or click an image) shared by every view; the slider's divider follows a press anywhere on the image, with a grab handle, touch and arrow keys, and no range input (also in the PDF compare tool); comments in every view (diff: this build; slider: the side where the press starts, the divider by its handle while commenting; baseline and this build: the image shown), with the hint centred in the page header --- .../src/__tests__/comment-pins.test.tsx | 151 +++++++++ server/frontend/src/__tests__/zoom.test.ts | 27 ++ server/frontend/src/components/Comments.tsx | 13 +- .../frontend/src/components/SliderStage.tsx | 118 +++++++ server/frontend/src/lib/zoom.ts | 71 ++++ server/frontend/src/pages/SnapshotPage.tsx | 305 +++++++++++++----- server/frontend/src/styles.css | 110 ++++++- server/frontend/src/tools/ComparePdfs.tsx | 22 +- 8 files changed, 702 insertions(+), 115 deletions(-) create mode 100644 server/frontend/src/__tests__/comment-pins.test.tsx create mode 100644 server/frontend/src/__tests__/zoom.test.ts create mode 100644 server/frontend/src/components/SliderStage.tsx create mode 100644 server/frontend/src/lib/zoom.ts diff --git a/server/frontend/src/__tests__/comment-pins.test.tsx b/server/frontend/src/__tests__/comment-pins.test.tsx new file mode 100644 index 00000000..2935e054 --- /dev/null +++ b/server/frontend/src/__tests__/comment-pins.test.tsx @@ -0,0 +1,151 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render } from '@testing-library/react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { CommentButton, CommentHint, CommentsProvider, PageThreads } from '../components/Comments' +import { PageImages } from '../pages/SnapshotPage' +import type { PageRow } from '../api/types' + +// Both images are 800×1600 pixels, and jsdom lays every element out as a 400×800 box at the origin: a press at +// (100, 200) is a quarter of the way across and down, so the comment's pixels are (200, 400) on whichever image it goes on. +const page: PageRow = { + position: 0, + op: 'changed', + state: 'changed', + head_index: 0, + base_index: 0, + head_url: 'https://blobs.test/head.png', + base_url: 'https://blobs.test/base.png', + overlay_url: 'https://blobs.test/diff.png', + expired: false, + base_size: [800, 1600], + head_size: [800, 1600], + diff: null, + text_diff: [], +} + +beforeEach(() => { + vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({ + left: 0, top: 0, right: 400, bottom: 800, width: 400, height: 800, x: 0, y: 0, toJSON: () => ({}), + } as DOMRect) + // jsdom has no pointer capture. + Element.prototype.setPointerCapture = () => {} + Element.prototype.hasPointerCapture = () => false +}) +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +function view(mode: 'side' | 'diff' | 'slider' | 'base' | 'head') { + const client = new QueryClient({ defaultOptions: { queries: { enabled: false, retry: false } } }) + return render( + + {}} + canComment + canResolve + > + + + {}} name="dashboard/390-light" kind="image" /> + + + , + ) +} + +/** Turn comment mode on, press and release at (100, 200) on `layer`, and return where the draft pin landed. */ +function comment(container: HTMLElement, layer: Element) { + fireEvent.pointerDown(layer, { clientX: 100, clientY: 200, button: 0, pointerId: 1 }) + fireEvent.pointerUp(layer, { clientX: 100, clientY: 200, pointerId: 1 }) + const pin = container.querySelector('.pin[data-draft]') + expect(pin, 'a draft pin').toBeTruthy() + const point = pin!.closest('.pin-point') as HTMLElement + return { pin: pin!, left: point.style.left, top: point.style.top, text: container.querySelector('.composer')?.textContent ?? '' } +} + +const placing = (container: HTMLElement) => [...container.querySelectorAll('.pins[data-placing]')] + +describe('comment pins in each view mode', () => { + it('side by side: on the image pressed', () => { + const { container, getByRole } = view('side') + fireEvent.click(getByRole('button', { name: /comment/i })) + const layers = placing(container) + expect(layers).toHaveLength(2) + const at = comment(container, layers[0]) + expect(at.text).toContain('A point on the old image') + expect([at.left, at.top]).toEqual(['25%', '25%']) + }) + + it('diff: on this build, in its pixels', () => { + const { container, getByRole } = view('diff') + fireEvent.click(getByRole('button', { name: /comment/i })) + // The base side's layer is under the head side's, which takes the press. + const layers = placing(container) + const head = layers.find((l) => l.closest('[data-side]')?.getAttribute('data-side') === 'head')! + expect(head).toBe(layers[layers.length - 1]) + const at = comment(container, head) + expect(at.text).toContain('A point on the new image') + expect(at.pin.closest('[data-side]')?.getAttribute('data-side')).toBe('head') + expect([at.left, at.top]).toEqual(['25%', '25%']) + }) + + it("slider: each side's layer covers its side of the divider, and a press there doesn't move it", () => { + const { container, getByRole } = view('slider') + fireEvent.click(getByRole('button', { name: /comment/i })) + const layer = (side: string) => container.querySelector(`.pins-layer[data-side="${side}"]`) as HTMLElement + // Divider at 50%: the old image's pins left of it, the new image's from it on (a press on the line is new). + expect(layer('base').style.clipPath).toBe('inset(0 50% 0 0)') + expect(layer('head').style.clipPath).toBe('inset(0 0 0 50%)') + + const slider = getByRole('slider') + const at = comment(container, layer('base').querySelector('.pins')!) + expect(at.text).toContain('A point on the old image') + expect([at.left, at.top]).toEqual(['25%', '25%']) + expect(slider.getAttribute('aria-valuenow')).toBe('50') + + // The handle still drags the divider, and so do the arrow keys. + fireEvent.pointerDown(container.querySelector('.slider-handle')!, { clientX: 300, button: 0, pointerId: 2 }) + expect(slider.getAttribute('aria-valuenow')).toBe('75') + fireEvent.keyDown(slider, { key: 'ArrowLeft' }) + expect(slider.getAttribute('aria-valuenow')).toBe('73') + expect(layer('head').style.clipPath).toBe('inset(0 0 0 73%)') + }) + + it('slider without comment mode: a press anywhere moves the divider, and a drag follows', () => { + const { container, getByRole } = view('slider') + const slider = getByRole('slider') + fireEvent.pointerDown(container.querySelector('.slider-img')!, { clientX: 40, button: 0, pointerId: 1 }) + expect(slider.getAttribute('aria-valuenow')).toBe('10') + fireEvent.pointerMove(slider, { clientX: 200, pointerId: 1 }) + expect(slider.getAttribute('aria-valuenow')).toBe('50') + fireEvent.pointerUp(slider, { pointerId: 1 }) + fireEvent.pointerMove(slider, { clientX: 300, pointerId: 1 }) + expect(slider.getAttribute('aria-valuenow')).toBe('50') + expect(container.querySelector('input[type="range"]')).toBeNull() + }) + + it.each(['base', 'head'] as const)('%s view: on the image shown', (mode) => { + const { container, getByRole } = view(mode) + fireEvent.click(getByRole('button', { name: /comment/i })) + const layers = placing(container) + expect(layers).toHaveLength(1) + const at = comment(container, layers[0]) + expect(at.text).toContain(mode === 'base' ? 'A point on the old image' : 'A point on the new image') + expect([at.left, at.top]).toEqual(['25%', '25%']) + }) + + it('shows the hint while commenting', () => { + const { getByRole, queryByRole } = view('side') + expect(queryByRole('status')).toBeNull() + fireEvent.click(getByRole('button', { name: /comment/i })) + expect(getByRole('status').textContent).toBe('Click for a point, drag for an area. It goes on the image where you press.') + }) +}) diff --git a/server/frontend/src/__tests__/zoom.test.ts b/server/frontend/src/__tests__/zoom.test.ts new file mode 100644 index 00000000..4e42eda7 --- /dev/null +++ b/server/frontend/src/__tests__/zoom.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import { captureScale, nextZoom, shotWidth } from '../lib/zoom' + +describe('image zoom', () => { + it('reads the capture scale from the name', () => { + expect(captureScale('screenshots/app/account/390-light-2x')).toBe(2) + expect(captureScale('home@3x.png')).toBe(3) + expect(captureScale('dashboard/390-light')).toBe(1) + expect(captureScale('receipt.pdf')).toBe(1) + }) + + it('never shows an image larger than its own size', () => { + // A 390-wide phone screenshot at scale 2 has 780 pixels: its own size is 390. + expect(shotWidth([780, 1688], 2, '100')).toBe('390px') + expect(shotWidth([780, 1688], 2, '200')).toBe('780px') + // Fitted: at most its own width, fitted to the screen's height, but no narrower than 360 (or its own width). + expect(shotWidth([390, 844], 1, 'fit')).toBe('min(390px, max(calc(var(--fit-h) * 0.4621), 360px))') + expect(shotWidth([195, 420], 1, 'fit')).toBe('min(195px, max(calc(var(--fit-h) * 0.4643), 195px))') + }) + + it('zooms in on a click, and back out', () => { + expect(nextZoom('fit', 600, 1440)).toBe('100') + expect(nextZoom('fit', 390, 390)).toBe('200') + expect(nextZoom('100', 1440, 1440)).toBe('fit') + expect(nextZoom('200', 780, 390)).toBe('fit') + }) +}) diff --git a/server/frontend/src/components/Comments.tsx b/server/frontend/src/components/Comments.tsx index d4c53a3a..489d7670 100644 --- a/server/frontend/src/components/Comments.tsx +++ b/server/frontend/src/components/Comments.tsx @@ -307,7 +307,18 @@ export function CommentButton({ page }: { page: number | null }) { > {open ? 'Cancel' : 'Comment'} - {open && Click for a point, drag for an area} + + ) +} + +/** What a press on the image does while a comment is being placed on this page, shown in its header. `extra` says + * where it goes in views that show more than one image. */ +export function CommentHint({ page, extra }: { page: number | null; extra?: string }) { + const ctx = useCtx() + if (!ctx || ctx.draft === null || ctx.draft.page !== page) return null + return ( + + Click for a point, drag for an area.{extra ? ` ${extra}` : ''} ) } diff --git a/server/frontend/src/components/SliderStage.tsx b/server/frontend/src/components/SliderStage.tsx new file mode 100644 index 00000000..5d538f17 --- /dev/null +++ b/server/frontend/src/components/SliderStage.tsx @@ -0,0 +1,118 @@ +import { useRef, useState, type CSSProperties, type KeyboardEvent, type PointerEvent, type ReactNode } from 'react' +import { CaretLeftIcon, CaretRightIcon } from '@phosphor-icons/react' + +/** + * Two versions of an image on top of each other, compared by dragging. Swipe: the new version shows right of a + * divider, and pressing anywhere on the image moves the divider there and drags it. Fade: the same drag sets how much + * of the new version shows. While a comment is being placed (a layer with `data-placing`), a press there makes the + * comment instead, and the divider moves by its handle. Arrow keys move it in steps when it has focus (Shift for + * bigger steps, Home and End to the ends). + */ +export function SliderStage({ + base, + head, + fade = false, + label, + className, + style, + children, +}: { + /** The old version, which sets the stage's size. */ + base: ReactNode + /** The new version, laid over it. */ + head: ReactNode + fade?: boolean + /** What the control is for screen readers: "Divider between the baseline and this build". */ + label: string + className?: string + style?: CSSProperties + /** More layers over both (changed regions, comment pins), given the divider's position in percent. */ + children?: ReactNode | ((pos: number) => ReactNode) +}) { + const [pos, setPos] = useState(50) + const stage = useRef(null) + // Set by a press that drags the divider, not by one that places a comment. + const dragging = useRef(false) + const moveTo = (clientX: number) => { + const r = stage.current?.getBoundingClientRect() + if (!r || r.width === 0) return + setPos(clamp(((clientX - r.left) / r.width) * 100)) + } + const onPointerDown = (e: PointerEvent) => { + if (e.button !== 0) return + // While a comment is being placed, a press on the image makes the comment; the handle still drags the divider. + const target = e.target as Element + if (!target.closest('.slider-handle') && target.closest('[data-placing], button, a')) return + e.preventDefault() + dragging.current = true + // Focus for the arrow keys, without the keyboard focus ring a mouse press doesn't need. + e.currentTarget.focus({ preventScroll: true, focusVisible: false } as FocusOptions) + try { + // Keep the drag ours when the pointer leaves the image. + e.currentTarget.setPointerCapture(e.pointerId) + } catch { + // Not every pointer can be captured; the drag still works over the image. + } + moveTo(e.clientX) + } + const onPointerMove = (e: PointerEvent) => { + if (dragging.current) moveTo(e.clientX) + } + const stop = () => { + dragging.current = false + } + const onKeyDown = (e: KeyboardEvent) => { + const step = e.shiftKey ? 10 : 2 + const to = + e.key === 'ArrowLeft' || e.key === 'ArrowDown' + ? pos - step + : e.key === 'ArrowRight' || e.key === 'ArrowUp' + ? pos + step + : e.key === 'Home' + ? 0 + : e.key === 'End' + ? 100 + : null + if (to === null) return + e.preventDefault() + e.stopPropagation() + setPos(clamp(to)) + } + return ( + e.preventDefault()} + > + {base} + + {head} + + {typeof children === 'function' ? children(pos) : children} + + + + + + + + ) +} + +const clamp = (v: number) => Math.min(100, Math.max(0, v)) diff --git a/server/frontend/src/lib/zoom.ts b/server/frontend/src/lib/zoom.ts new file mode 100644 index 00000000..727b225e --- /dev/null +++ b/server/frontend/src/lib/zoom.ts @@ -0,0 +1,71 @@ +import { createContext, useContext, type MouseEvent } from 'react' + +/** How big a snapshot's images are shown: fitted to the screen (never larger than their own size), at their own size, + * or at twice it. One zoom for the whole page, so both sides and the diff stay the same size. */ +export const ZOOMS = ['fit', '100', '200'] as const +export type Zoom = (typeof ZOOMS)[number] +export const zoomLabel: Record = { fit: 'Fit', '100': '100%', '200': '200%' } + +export const ZoomContext = createContext<{ zoom: Zoom; setZoom: (z: Zoom) => void }>({ zoom: 'fit', setZoom: () => {} }) + +/** The device scale a screenshot was taken at, from its name (`dashboard/390-light-2x`, `home@3x.png`), else 1. A + * capture at scale 2 has two image pixels for each pixel of the screen it shows. */ +export function captureScale(name: string): number { + const m = /[-@_](\d(?:\.\d+)?)x$/i.exec(name.replace(/\.(png|jpe?g|webp)$/i, '')) + const scale = m ? Number(m[1]) : 1 + return scale >= 1 && scale <= 4 ? scale : 1 +} + +/** The narrowest a fitted image gets (or its own width, if less): a tall phone screenshot fitted to the screen's + * height would otherwise be too narrow to read. */ +const FIT_FLOOR = 360 + +/** + * The width to show an image of `size` image pixels at, as a CSS length. Never more than its own size: its pixels + * divided by its capture scale, so a 390-wide phone screenshot is shown 390 wide. `fit` also keeps it within the + * screen's height (`--fit-h`), down to FIT_FLOOR; `100` and `200` are one and two times its own size. + */ +export function shotWidth(size: [number, number], scale: number, zoom: Zoom): string { + const own = size[0] / scale + if (zoom === '100') return `${round(own)}px` + if (zoom === '200') return `${round(own * 2)}px` + const aspect = size[1] > 0 ? size[0] / size[1] : 1 + return `min(${round(own)}px, max(calc(var(--fit-h) * ${aspect.toFixed(4)}), ${round(Math.min(own, FIT_FLOOR))}px))` +} + +const round = (n: number) => Math.round(n * 100) / 100 + +/** The zoom a click on an image moves to: from Fit to 100% (or 200% when the image already shows at its own size), + * and back to Fit from either. */ +export function nextZoom(zoom: Zoom, shownWidth: number, ownWidth: number): Zoom { + if (zoom !== 'fit') return 'fit' + return shownWidth < ownWidth - 1 ? '100' : '200' +} + +/** + * Click-to-zoom on an image (`.shot` with `data-own-width`): changes the page's zoom, then scrolls so the point that + * was clicked stays under the pointer. Ignored while a comment pin is being placed, and on links and buttons. + */ +export function useZoomClick() { + const { zoom, setZoom } = useContext(ZoomContext) + return (e: MouseEvent) => { + const shot = e.currentTarget + const target = e.target as HTMLElement + if (shot.querySelector('[data-placing]') || target.closest('a, button, [data-pin]')) return + const own = Number(shot.dataset.ownWidth) + if (!own) return + const before = shot.getBoundingClientRect() + const fx = (e.clientX - before.left) / before.width + const fy = (e.clientY - before.top) / before.height + const { clientX, clientY } = e + setZoom(nextZoom(zoom, before.width, own)) + requestAnimationFrame(() => + requestAnimationFrame(() => { + const after = shot.getBoundingClientRect() + const scroller = shot.parentElement + if (scroller) scroller.scrollLeft += after.left + fx * after.width - clientX + window.scrollBy(0, after.top + fy * after.height - clientY) + }), + ) + } +} diff --git a/server/frontend/src/pages/SnapshotPage.tsx b/server/frontend/src/pages/SnapshotPage.tsx index 28f650ab..3891c101 100644 --- a/server/frontend/src/pages/SnapshotPage.tsx +++ b/server/frontend/src/pages/SnapshotPage.tsx @@ -12,7 +12,7 @@ import { import { useBuild, usePageAction, useReview, useSnapshot } from '../api/hooks' import type { AppliedIgnoreRule, BuildDetail, MovedLine, PageRow, SnapshotData, SnapshotRow, SnapshotState, TextLine } from '../api/types' import { errorMessage } from '../api/client' -import { CommentButton, CommentsProvider, PageThreads, Pins } from '../components/Comments' +import { CommentButton, CommentHint, CommentsProvider, PageThreads, Pins } from '../components/Comments' import { QueryState } from '../components/QueryState' import { PresignedImg, useExpiredRefetch } from '../components/PresignedImg' import { Button, Help, Kbd, Pill, ReviewPill, StatePill, type Tone } from '../components/ui' @@ -20,6 +20,8 @@ import { n, percent, plural } from '../lib/format' import { usePersistentState } from '../lib/theme' import { approvedElsewhereLabel, compareForReview, reviewable, useReviewOrder, type ReviewOrder } from './BuildPage' import { TextSnapshot, textHunks } from '../components/TextSnapshot' +import { SliderStage } from '../components/SliderStage' +import { ZOOMS, ZoomContext, captureScale, shotWidth, useZoomClick, zoomLabel, type Zoom } from '../lib/zoom' const route = getRouteApi('/_app/$org/$project/builds/$number/snapshots/$id') @@ -106,6 +108,9 @@ export function SnapshotPage() { if (linkedMode) setMode(linkedMode) }, [linkedMode, setMode]) const [highlight, setHighlight] = usePersistentState('vci-highlight', 'boxes', HIGHLIGHTS) + // Every image on the page shares one zoom; each snapshot opens fitted to the screen. + const [zoom, setZoom] = useState('fit') + const zoomValue = useMemo(() => ({ zoom, setZoom }), [zoom]) // `h` turns the highlight off and back on to the style it had. const lastHighlight = useRef(highlight === 'off' ? 'boxes' : highlight) useEffect(() => { @@ -211,6 +216,10 @@ export function SnapshotPage() { if (isText) return setMode(MODES[Number(e.key) - 1]) break + case 'z': + if (isText) return + setZoom((z) => ZOOMS[(ZOOMS.indexOf(z) + 1) % ZOOMS.length]) + break case 'h': if (isText) return setHighlight((h) => (h === 'off' ? lastHighlight.current : 'off')) @@ -264,6 +273,7 @@ export function SnapshotPage() { canResolve={q.data.can_review !== false} > +
@@ -340,6 +350,16 @@ export function SnapshotPage() {
)} + {!isText && ( +
+ {ZOOMS.map((z) => ( + + ))} +
+ )} +
{!isText && pages.length > 0 && } {!isText && ( @@ -500,6 +520,7 @@ export function SnapshotPage() {
)}
+ ) @@ -550,6 +571,7 @@ function ShortcutHelp({ onClose, canReview, isText }: { onClose: () => void; can [<>j k, 'Next and previous page'], [<>1 to 5, 'Side by side, diff, slider, baseline, this build'], [h, 'Turn the highlight of changed regions off or on'], + [z, 'Zoom: fit, 100%, 200% (or click an image)'], [<>[ ], 'Previous and next snapshot'], ] if (canReview) { @@ -683,6 +705,7 @@ function PageView({ index, page: p, mode, highlight, active, collapsedByDefault, )} )} + {snapshot.snapshot.kind !== 'text' && } {actionable && (
} -function PageImages({ +type Size = [number, number] + +/** The larger of two sizes, in each direction: the canvas a diff or a slider draws both versions on. */ +const canvasOf = (a?: Size | null, b?: Size | null): Size | undefined => + a && b ? [Math.max(a[0], b[0]), Math.max(a[1], b[1])] : (a ?? b ?? undefined) + +/** + * One image of a page at the page's zoom: never larger than its own size (its pixels over its capture scale), fitted + * to the screen by default, and scrolling sideways in its column when zoomed past it. Click it to zoom in or out. + * Until its size is known it shows at its own pixel size, at most the column's width. + */ +function Shot({ + size, + scale, + children, + zoomable = true, +}: { + size: Size | undefined + scale: number + children: ReactNode + zoomable?: boolean +}) { + const { zoom } = useContext(ZoomContext) + const zoomClick = useZoomClick() + const width = size ? shotWidth(size, scale, zoom) : undefined + return ( +
+ + {children} + +
+ ) +} + +/** The grid's columns for these images: each at most as wide as its image is shown, centred, so two phone screenshots + * sit side by side at about phone size instead of each filling half the page. */ +function columns(widths: (string | undefined)[]): CSSProperties | undefined { + if (widths.some((w) => !w)) return undefined + return { '--cols': widths.map((w) => `minmax(0, ${w})`).join(' ') } as CSSProperties +} + +/** + * One side's comment pins over a diff or slider canvas: a layer the size of that side's image within the canvas, so a + * pin is in that image's own pixels whichever view it's drawn in. `clip` hides the part past the slider's divider, and + * presses there go to the other side's layer. + */ +function SidePins({ page, side, size, canvas, clip }: { page: number; side: 'base' | 'head'; size?: Size | null; canvas?: Size; clip?: string }) { + if (!size || !canvas) return null + return ( + + + + ) +} + +export function PageImages({ page: p, mode, highlight, @@ -800,6 +897,18 @@ function PageImages({ kind: string }) { const old = useContext(OldSide) + const { zoom } = useContext(ZoomContext) + const scale = captureScale(name) + // Sizes come from the server, else from the images once they load. + const [loaded, setLoaded] = useState<{ base?: Size; head?: Size }>({}) + const note = (side: 'base' | 'head') => (e: SyntheticEvent) => { + const img = e.currentTarget + setLoaded((l) => (l[side] ? l : { ...l, [side]: [img.naturalWidth, img.naturalHeight] })) + } + const baseSize = p.base_size ?? loaded.base + const headSize = p.head_size ?? loaded.head + const width = (size?: Size) => (size ? shotWidth(size, scale, zoom) : undefined) + if (p.expired) { return (
@@ -813,76 +922,75 @@ function PageImages({ ) } const base = p.base_url ? ( - - + + - + ) : ( ) const head = p.head_url ? ( - - + + - + ) : ( ) + const one = (size: Size | undefined, frame: ReactNode) => ( +
+ {frame} +
+ ) - if (p.op === 'unchanged') { - return ( -
- {head} -
- ) - } + if (p.op === 'unchanged') return one(headSize, {head}) - // One version full size: the baseline as it was for this build, or this build's. An added page has no baseline and a - // removed one no new version, so they show the side they have. + // One version: the baseline as it was for this build, or this build's. An added page has no baseline and a removed + // one no new version, so they show the side they have. if ((mode === 'base' && p.base_url) || (mode === 'head' && !p.head_url && p.base_url)) { - return ( -
- {base} -
- ) + return one(baseSize, {base}) } if ((mode === 'head' && p.head_url) || (mode === 'base' && !p.base_url && p.head_url)) { - return ( -
- - {head} - -
+ return one( + headSize, + + {head} + , ) } const bothSides = !!(p.base_url && p.head_url) + const canvas = canvasOf(baseSize, headSize) if (mode === 'diff' && bothSides) { - return ( -
- - {p.overlay_url ? ( - - - - - ) : ( - - )} - -
+ return one( + canvas, + + {p.overlay_url ? ( + + + + {/* The diff is drawn in this build's coordinates: new comments go on this build's image. */} + + + + ) : ( + + )} + , ) } if (mode === 'slider' && bothSides) { - return + return ( + + ) } return ( -
+
{base} @@ -893,57 +1001,45 @@ function PageImages({ ) } -function Slider({ page: p, highlight, onExpired, name }: { page: PageRow; highlight: Highlight; onExpired: () => void; name: string }) { +function Slider({ + page: p, + highlight, + onExpired, + name, + scale, + base, + head, + onLoad, +}: { + page: PageRow + highlight: Highlight + onExpired: () => void + name: string + scale: number + base: Size | undefined + head: Size | undefined + onLoad: (side: 'base' | 'head') => (e: SyntheticEvent) => void +}) { const old = useContext(OldSide) - const [pos, setPos] = useState(50) + const { zoom } = useContext(ZoomContext) const [fade, setFade] = useState(false) // A resized page or screenshot: both images sit top-left on a canvas the size of the larger one, at one scale, so - // the line compares like with like; the area one of them doesn't cover shows as a checkerboard. Sizes come from the - // server, else from the images themselves once loaded. - const [loaded, setLoaded] = useState<{ base?: [number, number]; head?: [number, number] }>({}) - const base = p.base_size ?? loaded.base - const head = p.head_size ?? loaded.head - const canvas: [number, number] | null = - base && head ? [Math.max(base[0], head[0]), Math.max(base[1], head[1])] : null + // the line compares like with like; the area one of them doesn't cover shows as a checkerboard. + const canvas = base && head ? canvasOf(base, head) : undefined const resized = !!(base && head && (base[0] !== head[0] || base[1] !== head[1])) // Each image at its share of the canvas's width, pinned top-left; until the sizes are known, the base sets the height. - const place = (size: [number, number] | undefined): CSSProperties => + const place = (size: Size | undefined): CSSProperties => canvas && size ? { position: 'absolute', top: 0, left: 0, width: `${(size[0] / canvas[0]) * 100}%`, height: 'auto' } : { width: '100%' } - const note = (side: 'base' | 'head') => (e: SyntheticEvent) => { - const img = e.currentTarget - setLoaded((l) => (l[side] ? l : { ...l, [side]: [img.naturalWidth, img.naturalHeight] })) - } + const width = canvas ? shotWidth(canvas, scale, zoom) : undefined return ( -
- - - - - +
+
+
+ + {fade ? `${old}, fading to this build` : `${old} | This build`} - {!fade && } - - -
- base - setPos(Number(e.target.value))} - aria-label={fade ? 'Head opacity' : 'Divider position'} - /> - head
+
+ + } + head={ + + } + > + {(pos) => ( + <> + + {/* Each side's pins show, and take presses, on its own side of the divider: a comment goes on the image + where the press starts, and on the line counts as this build. In Fade, comments go on this build. */} + + + + )} +
- +
) } diff --git a/server/frontend/src/styles.css b/server/frontend/src/styles.css index f429cadb..082759f1 100644 --- a/server/frontend/src/styles.css +++ b/server/frontend/src/styles.css @@ -2547,16 +2547,20 @@ a.stat-cell:hover { flex-wrap: wrap; } +/* A page's images. Each column is at most as wide as its image is shown (`--cols`, set from the images' sizes and the + zoom), centred, so narrow phone screenshots sit side by side at about phone size. `--fit-h` is the height a fitted + image keeps within: the screen below the review bar. */ .frames { + --fit-h: max(360px, calc(100svh - var(--review-bar-h, 64px) - 160px)); display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-template-columns: var(--cols, repeat(2, minmax(0, 1fr))); + justify-content: center; gap: var(--space-4); align-items: start; } .frames-one { - grid-template-columns: minmax(0, 860px); - justify-content: center; + grid-template-columns: var(--cols, minmax(0, 860px)); } .frame { @@ -2594,9 +2598,19 @@ a.stat-cell:hover { color: var(--color-changed); } +/* Sideways scrolling for an image zoomed past its column; the page scrolls it up and down. */ +.shot-scroll { + max-width: 100%; + overflow-x: auto; + overflow-y: hidden; +} + .shot { position: relative; display: block; + /* Never wider than the image's own pixels until its size is known (then its width is set from the zoom). */ + width: fit-content; + max-width: 100%; background: var(--color-page); border: 1px solid var(--color-rule); border-radius: var(--radius-sm); @@ -2605,10 +2619,45 @@ a.stat-cell:hover { } .shot img { - width: 100%; + display: block; + max-width: 100%; height: auto; } +.shot[data-sized] img { + width: 100%; +} + +.shot-scroll:not([data-zoom='fit']) > .shot { + max-width: none; +} + +.shot[data-zoomable='fit'] { + cursor: zoom-in; +} + +.shot[data-zoomable='100'], +.shot[data-zoomable='200'] { + cursor: zoom-out; +} + +/* One side's comment pins over a diff or slider: the size of that side's image within the canvas. */ +.pins-layer { + position: absolute; + top: 0; + left: 0; + pointer-events: none; +} + +/* What a press on the image does while commenting, centred in the page's header. */ +.comment-hint { + flex: 1 1 16rem; + order: 2; + text-align: center; + font-size: var(--text-xs); + color: var(--color-accent-text); +} + .missing { display: grid; place-items: center; @@ -2685,13 +2734,30 @@ svg.regions-dim { font-size: var(--text-sm); } +/* Press anywhere on the image and drag: the divider follows. Vertical swipes still scroll the page on touch screens. */ .slider-stage { position: relative; user-select: none; + -webkit-user-select: none; + cursor: ew-resize; + touch-action: pan-y; +} + +.slider-stage:focus-visible { + outline: 2px solid var(--color-focus); + outline-offset: -2px; +} + +.slider-stage:has(.pins[data-placing]) { + cursor: crosshair; +} + +.slider-stage img { + pointer-events: none; } /* A resized page or screenshot: the canvas one image doesn't cover shows as a checkerboard. */ -.slider-stage[data-resized] { +.slider-stage.slider-resized { background-color: var(--color-sunken); background-image: linear-gradient(45deg, var(--color-rule) 25%, transparent 25%), @@ -2706,6 +2772,10 @@ svg.regions-dim { font-size: var(--text-xs); } +.slider-img { + width: 100%; +} + .slider-top { position: absolute; inset: 0; @@ -2721,17 +2791,29 @@ svg.regions-dim { pointer-events: none; } -.slider-controls { - display: flex; - align-items: center; - gap: var(--space-3); - font-size: var(--text-xs); +.slider-line[data-fade] { + background: transparent; } -.slider-controls input[type='range'] { - flex: 1; - accent-color: var(--color-accent); - min-width: 0; +/* The grab handle on the divider: it drags the divider even while a comment is being placed. Halfway down a short + image, and within the first screen of a tall one. */ +.slider-handle { + position: absolute; + top: min(50%, 40svh); + left: 50%; + translate: -50% -50%; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border-radius: 999px; + background: var(--color-accent); + color: var(--color-accent-ink); + box-shadow: var(--shadow-pop); + pointer-events: auto; + cursor: ew-resize; + touch-action: none; } .text-diff { diff --git a/server/frontend/src/tools/ComparePdfs.tsx b/server/frontend/src/tools/ComparePdfs.tsx index c53e4ded..5c5e7300 100644 --- a/server/frontend/src/tools/ComparePdfs.tsx +++ b/server/frontend/src/tools/ComparePdfs.tsx @@ -1,6 +1,7 @@ /** visualci.com's "Compare two PDFs" tool: two files in, the pages that changed out, all in the browser. Mounted on * /tools/compare-pdfs/ by docs-client.tsx; the page's text around it is content/pages/tools/compare-pdfs.md. */ -import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react' +import { useEffect, useRef, useState, type ReactNode } from 'react' +import { SliderStage } from '../components/SliderStage' import { FilePdfIcon } from '@phosphor-icons/react' import { Button, Pill } from '../components/ui' import { comparePdfs, release, renderPage, type ComparedPage, type Comparison } from './comparePdfs' @@ -85,23 +86,14 @@ function Shot({ src, alt }: { src?: string; alt: string }) { } function Slider({ base, head }: { base: string; head: string }) { - const [pos, setPos] = useState(50) - const top: CSSProperties = { clipPath: `inset(0 0 0 ${pos}%)` } return (
- - Old page - - - - - -
- old - setPos(Number(e.target.value))} aria-label="Divider position" /> - new -
+ } + head={New page} + />
)