Skip to content

Commit cf9efe7

Browse files
committed
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
1 parent cac0a7c commit cf9efe7

8 files changed

Lines changed: 702 additions & 115 deletions

File tree

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2+
import { cleanup, fireEvent, render } from '@testing-library/react'
3+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
4+
import { CommentButton, CommentHint, CommentsProvider, PageThreads } from '../components/Comments'
5+
import { PageImages } from '../pages/SnapshotPage'
6+
import type { PageRow } from '../api/types'
7+
8+
// Both images are 800×1600 pixels, and jsdom lays every element out as a 400×800 box at the origin: a press at
9+
// (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.
10+
const page: PageRow = {
11+
position: 0,
12+
op: 'changed',
13+
state: 'changed',
14+
head_index: 0,
15+
base_index: 0,
16+
head_url: 'https://blobs.test/head.png',
17+
base_url: 'https://blobs.test/base.png',
18+
overlay_url: 'https://blobs.test/diff.png',
19+
expired: false,
20+
base_size: [800, 1600],
21+
head_size: [800, 1600],
22+
diff: null,
23+
text_diff: [],
24+
}
25+
26+
beforeEach(() => {
27+
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({
28+
left: 0, top: 0, right: 400, bottom: 800, width: 400, height: 800, x: 0, y: 0, toJSON: () => ({}),
29+
} as DOMRect)
30+
// jsdom has no pointer capture.
31+
Element.prototype.setPointerCapture = () => {}
32+
Element.prototype.hasPointerCapture = () => false
33+
})
34+
afterEach(() => {
35+
cleanup()
36+
vi.restoreAllMocks()
37+
})
38+
39+
function view(mode: 'side' | 'diff' | 'slider' | 'base' | 'head') {
40+
const client = new QueryClient({ defaultOptions: { queries: { enabled: false, retry: false } } })
41+
return render(
42+
<QueryClientProvider client={client}>
43+
<CommentsProvider
44+
org="acme"
45+
project="web"
46+
build={3}
47+
snapshotId="s1"
48+
threads={[]}
49+
compared={{ kind: 'baseline' }}
50+
previousBuild={null}
51+
showPrevious={() => {}}
52+
canComment
53+
canResolve
54+
>
55+
<CommentButton page={0} />
56+
<CommentHint page={0} extra="It goes on the image where you press." />
57+
<PageImages page={page} mode={mode} highlight="off" onExpired={() => {}} name="dashboard/390-light" kind="image" />
58+
<PageThreads page={0} />
59+
</CommentsProvider>
60+
</QueryClientProvider>,
61+
)
62+
}
63+
64+
/** Turn comment mode on, press and release at (100, 200) on `layer`, and return where the draft pin landed. */
65+
function comment(container: HTMLElement, layer: Element) {
66+
fireEvent.pointerDown(layer, { clientX: 100, clientY: 200, button: 0, pointerId: 1 })
67+
fireEvent.pointerUp(layer, { clientX: 100, clientY: 200, pointerId: 1 })
68+
const pin = container.querySelector('.pin[data-draft]')
69+
expect(pin, 'a draft pin').toBeTruthy()
70+
const point = pin!.closest('.pin-point') as HTMLElement
71+
return { pin: pin!, left: point.style.left, top: point.style.top, text: container.querySelector('.composer')?.textContent ?? '' }
72+
}
73+
74+
const placing = (container: HTMLElement) => [...container.querySelectorAll('.pins[data-placing]')]
75+
76+
describe('comment pins in each view mode', () => {
77+
it('side by side: on the image pressed', () => {
78+
const { container, getByRole } = view('side')
79+
fireEvent.click(getByRole('button', { name: /comment/i }))
80+
const layers = placing(container)
81+
expect(layers).toHaveLength(2)
82+
const at = comment(container, layers[0])
83+
expect(at.text).toContain('A point on the old image')
84+
expect([at.left, at.top]).toEqual(['25%', '25%'])
85+
})
86+
87+
it('diff: on this build, in its pixels', () => {
88+
const { container, getByRole } = view('diff')
89+
fireEvent.click(getByRole('button', { name: /comment/i }))
90+
// The base side's layer is under the head side's, which takes the press.
91+
const layers = placing(container)
92+
const head = layers.find((l) => l.closest('[data-side]')?.getAttribute('data-side') === 'head')!
93+
expect(head).toBe(layers[layers.length - 1])
94+
const at = comment(container, head)
95+
expect(at.text).toContain('A point on the new image')
96+
expect(at.pin.closest('[data-side]')?.getAttribute('data-side')).toBe('head')
97+
expect([at.left, at.top]).toEqual(['25%', '25%'])
98+
})
99+
100+
it("slider: each side's layer covers its side of the divider, and a press there doesn't move it", () => {
101+
const { container, getByRole } = view('slider')
102+
fireEvent.click(getByRole('button', { name: /comment/i }))
103+
const layer = (side: string) => container.querySelector(`.pins-layer[data-side="${side}"]`) as HTMLElement
104+
// 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).
105+
expect(layer('base').style.clipPath).toBe('inset(0 50% 0 0)')
106+
expect(layer('head').style.clipPath).toBe('inset(0 0 0 50%)')
107+
108+
const slider = getByRole('slider')
109+
const at = comment(container, layer('base').querySelector('.pins')!)
110+
expect(at.text).toContain('A point on the old image')
111+
expect([at.left, at.top]).toEqual(['25%', '25%'])
112+
expect(slider.getAttribute('aria-valuenow')).toBe('50')
113+
114+
// The handle still drags the divider, and so do the arrow keys.
115+
fireEvent.pointerDown(container.querySelector('.slider-handle')!, { clientX: 300, button: 0, pointerId: 2 })
116+
expect(slider.getAttribute('aria-valuenow')).toBe('75')
117+
fireEvent.keyDown(slider, { key: 'ArrowLeft' })
118+
expect(slider.getAttribute('aria-valuenow')).toBe('73')
119+
expect(layer('head').style.clipPath).toBe('inset(0 0 0 73%)')
120+
})
121+
122+
it('slider without comment mode: a press anywhere moves the divider, and a drag follows', () => {
123+
const { container, getByRole } = view('slider')
124+
const slider = getByRole('slider')
125+
fireEvent.pointerDown(container.querySelector('.slider-img')!, { clientX: 40, button: 0, pointerId: 1 })
126+
expect(slider.getAttribute('aria-valuenow')).toBe('10')
127+
fireEvent.pointerMove(slider, { clientX: 200, pointerId: 1 })
128+
expect(slider.getAttribute('aria-valuenow')).toBe('50')
129+
fireEvent.pointerUp(slider, { pointerId: 1 })
130+
fireEvent.pointerMove(slider, { clientX: 300, pointerId: 1 })
131+
expect(slider.getAttribute('aria-valuenow')).toBe('50')
132+
expect(container.querySelector('input[type="range"]')).toBeNull()
133+
})
134+
135+
it.each(['base', 'head'] as const)('%s view: on the image shown', (mode) => {
136+
const { container, getByRole } = view(mode)
137+
fireEvent.click(getByRole('button', { name: /comment/i }))
138+
const layers = placing(container)
139+
expect(layers).toHaveLength(1)
140+
const at = comment(container, layers[0])
141+
expect(at.text).toContain(mode === 'base' ? 'A point on the old image' : 'A point on the new image')
142+
expect([at.left, at.top]).toEqual(['25%', '25%'])
143+
})
144+
145+
it('shows the hint while commenting', () => {
146+
const { getByRole, queryByRole } = view('side')
147+
expect(queryByRole('status')).toBeNull()
148+
fireEvent.click(getByRole('button', { name: /comment/i }))
149+
expect(getByRole('status').textContent).toBe('Click for a point, drag for an area. It goes on the image where you press.')
150+
})
151+
})
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { captureScale, nextZoom, shotWidth } from '../lib/zoom'
3+
4+
describe('image zoom', () => {
5+
it('reads the capture scale from the name', () => {
6+
expect(captureScale('screenshots/app/account/390-light-2x')).toBe(2)
7+
expect(captureScale('home@3x.png')).toBe(3)
8+
expect(captureScale('dashboard/390-light')).toBe(1)
9+
expect(captureScale('receipt.pdf')).toBe(1)
10+
})
11+
12+
it('never shows an image larger than its own size', () => {
13+
// A 390-wide phone screenshot at scale 2 has 780 pixels: its own size is 390.
14+
expect(shotWidth([780, 1688], 2, '100')).toBe('390px')
15+
expect(shotWidth([780, 1688], 2, '200')).toBe('780px')
16+
// Fitted: at most its own width, fitted to the screen's height, but no narrower than 360 (or its own width).
17+
expect(shotWidth([390, 844], 1, 'fit')).toBe('min(390px, max(calc(var(--fit-h) * 0.4621), 360px))')
18+
expect(shotWidth([195, 420], 1, 'fit')).toBe('min(195px, max(calc(var(--fit-h) * 0.4643), 195px))')
19+
})
20+
21+
it('zooms in on a click, and back out', () => {
22+
expect(nextZoom('fit', 600, 1440)).toBe('100')
23+
expect(nextZoom('fit', 390, 390)).toBe('200')
24+
expect(nextZoom('100', 1440, 1440)).toBe('fit')
25+
expect(nextZoom('200', 780, 390)).toBe('fit')
26+
})
27+
})

‎server/frontend/src/components/Comments.tsx‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -307,7 +307,18 @@ export function CommentButton({ page }: { page: number | null }) {
307307
>
308308
<ChatCircleIcon size={14} /> {open ? 'Cancel' : 'Comment'}
309309
</Button>
310-
{open && <span className="hint hide-sm">Click for a point, drag for an area</span>}
310+
</span>
311+
)
312+
}
313+
314+
/** What a press on the image does while a comment is being placed on this page, shown in its header. `extra` says
315+
* where it goes in views that show more than one image. */
316+
export function CommentHint({ page, extra }: { page: number | null; extra?: string }) {
317+
const ctx = useCtx()
318+
if (!ctx || ctx.draft === null || ctx.draft.page !== page) return null
319+
return (
320+
<span className="comment-hint" role="status">
321+
Click for a point, drag for an area.{extra ? ` ${extra}` : ''}
311322
</span>
312323
)
313324
}
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import { useRef, useState, type CSSProperties, type KeyboardEvent, type PointerEvent, type ReactNode } from 'react'
2+
import { CaretLeftIcon, CaretRightIcon } from '@phosphor-icons/react'
3+
4+
/**
5+
* Two versions of an image on top of each other, compared by dragging. Swipe: the new version shows right of a
6+
* divider, and pressing anywhere on the image moves the divider there and drags it. Fade: the same drag sets how much
7+
* of the new version shows. While a comment is being placed (a layer with `data-placing`), a press there makes the
8+
* comment instead, and the divider moves by its handle. Arrow keys move it in steps when it has focus (Shift for
9+
* bigger steps, Home and End to the ends).
10+
*/
11+
export function SliderStage({
12+
base,
13+
head,
14+
fade = false,
15+
label,
16+
className,
17+
style,
18+
children,
19+
}: {
20+
/** The old version, which sets the stage's size. */
21+
base: ReactNode
22+
/** The new version, laid over it. */
23+
head: ReactNode
24+
fade?: boolean
25+
/** What the control is for screen readers: "Divider between the baseline and this build". */
26+
label: string
27+
className?: string
28+
style?: CSSProperties
29+
/** More layers over both (changed regions, comment pins), given the divider's position in percent. */
30+
children?: ReactNode | ((pos: number) => ReactNode)
31+
}) {
32+
const [pos, setPos] = useState(50)
33+
const stage = useRef<HTMLSpanElement>(null)
34+
// Set by a press that drags the divider, not by one that places a comment.
35+
const dragging = useRef(false)
36+
const moveTo = (clientX: number) => {
37+
const r = stage.current?.getBoundingClientRect()
38+
if (!r || r.width === 0) return
39+
setPos(clamp(((clientX - r.left) / r.width) * 100))
40+
}
41+
const onPointerDown = (e: PointerEvent<HTMLSpanElement>) => {
42+
if (e.button !== 0) return
43+
// While a comment is being placed, a press on the image makes the comment; the handle still drags the divider.
44+
const target = e.target as Element
45+
if (!target.closest('.slider-handle') && target.closest('[data-placing], button, a')) return
46+
e.preventDefault()
47+
dragging.current = true
48+
// Focus for the arrow keys, without the keyboard focus ring a mouse press doesn't need.
49+
e.currentTarget.focus({ preventScroll: true, focusVisible: false } as FocusOptions)
50+
try {
51+
// Keep the drag ours when the pointer leaves the image.
52+
e.currentTarget.setPointerCapture(e.pointerId)
53+
} catch {
54+
// Not every pointer can be captured; the drag still works over the image.
55+
}
56+
moveTo(e.clientX)
57+
}
58+
const onPointerMove = (e: PointerEvent<HTMLSpanElement>) => {
59+
if (dragging.current) moveTo(e.clientX)
60+
}
61+
const stop = () => {
62+
dragging.current = false
63+
}
64+
const onKeyDown = (e: KeyboardEvent<HTMLSpanElement>) => {
65+
const step = e.shiftKey ? 10 : 2
66+
const to =
67+
e.key === 'ArrowLeft' || e.key === 'ArrowDown'
68+
? pos - step
69+
: e.key === 'ArrowRight' || e.key === 'ArrowUp'
70+
? pos + step
71+
: e.key === 'Home'
72+
? 0
73+
: e.key === 'End'
74+
? 100
75+
: null
76+
if (to === null) return
77+
e.preventDefault()
78+
e.stopPropagation()
79+
setPos(clamp(to))
80+
}
81+
return (
82+
<span
83+
ref={stage}
84+
className={['shot', 'slider-stage', className].filter(Boolean).join(' ')}
85+
style={style}
86+
data-fade={fade || undefined}
87+
role="slider"
88+
tabIndex={0}
89+
aria-label={label}
90+
aria-orientation="horizontal"
91+
aria-valuemin={0}
92+
aria-valuemax={100}
93+
aria-valuenow={Math.round(pos)}
94+
aria-valuetext={fade ? `${Math.round(pos)}% of the new version` : `Divider at ${Math.round(pos)}%`}
95+
onPointerDown={onPointerDown}
96+
onPointerMove={onPointerMove}
97+
onPointerUp={stop}
98+
onPointerCancel={stop}
99+
onLostPointerCapture={stop}
100+
onKeyDown={onKeyDown}
101+
onDragStart={(e) => e.preventDefault()}
102+
>
103+
{base}
104+
<span className="slider-top" style={fade ? { opacity: pos / 100 } : { clipPath: `inset(0 0 0 ${pos}%)` }}>
105+
{head}
106+
</span>
107+
{typeof children === 'function' ? children(pos) : children}
108+
<span className="slider-line" style={{ left: `${pos}%` }} data-fade={fade || undefined} aria-hidden>
109+
<span className="slider-handle">
110+
<CaretLeftIcon size={12} weight="bold" />
111+
<CaretRightIcon size={12} weight="bold" />
112+
</span>
113+
</span>
114+
</span>
115+
)
116+
}
117+
118+
const clamp = (v: number) => Math.min(100, Math.max(0, v))

‎server/frontend/src/lib/zoom.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import { createContext, useContext, type MouseEvent } from 'react'
2+
3+
/** How big a snapshot's images are shown: fitted to the screen (never larger than their own size), at their own size,
4+
* or at twice it. One zoom for the whole page, so both sides and the diff stay the same size. */
5+
export const ZOOMS = ['fit', '100', '200'] as const
6+
export type Zoom = (typeof ZOOMS)[number]
7+
export const zoomLabel: Record<Zoom, string> = { fit: 'Fit', '100': '100%', '200': '200%' }
8+
9+
export const ZoomContext = createContext<{ zoom: Zoom; setZoom: (z: Zoom) => void }>({ zoom: 'fit', setZoom: () => {} })
10+
11+
/** The device scale a screenshot was taken at, from its name (`dashboard/390-light-2x`, `home@3x.png`), else 1. A
12+
* capture at scale 2 has two image pixels for each pixel of the screen it shows. */
13+
export function captureScale(name: string): number {
14+
const m = /[-@_](\d(?:\.\d+)?)x$/i.exec(name.replace(/\.(png|jpe?g|webp)$/i, ''))
15+
const scale = m ? Number(m[1]) : 1
16+
return scale >= 1 && scale <= 4 ? scale : 1
17+
}
18+
19+
/** The narrowest a fitted image gets (or its own width, if less): a tall phone screenshot fitted to the screen's
20+
* height would otherwise be too narrow to read. */
21+
const FIT_FLOOR = 360
22+
23+
/**
24+
* The width to show an image of `size` image pixels at, as a CSS length. Never more than its own size: its pixels
25+
* divided by its capture scale, so a 390-wide phone screenshot is shown 390 wide. `fit` also keeps it within the
26+
* screen's height (`--fit-h`), down to FIT_FLOOR; `100` and `200` are one and two times its own size.
27+
*/
28+
export function shotWidth(size: [number, number], scale: number, zoom: Zoom): string {
29+
const own = size[0] / scale
30+
if (zoom === '100') return `${round(own)}px`
31+
if (zoom === '200') return `${round(own * 2)}px`
32+
const aspect = size[1] > 0 ? size[0] / size[1] : 1
33+
return `min(${round(own)}px, max(calc(var(--fit-h) * ${aspect.toFixed(4)}), ${round(Math.min(own, FIT_FLOOR))}px))`
34+
}
35+
36+
const round = (n: number) => Math.round(n * 100) / 100
37+
38+
/** The zoom a click on an image moves to: from Fit to 100% (or 200% when the image already shows at its own size),
39+
* and back to Fit from either. */
40+
export function nextZoom(zoom: Zoom, shownWidth: number, ownWidth: number): Zoom {
41+
if (zoom !== 'fit') return 'fit'
42+
return shownWidth < ownWidth - 1 ? '100' : '200'
43+
}
44+
45+
/**
46+
* Click-to-zoom on an image (`.shot` with `data-own-width`): changes the page's zoom, then scrolls so the point that
47+
* was clicked stays under the pointer. Ignored while a comment pin is being placed, and on links and buttons.
48+
*/
49+
export function useZoomClick() {
50+
const { zoom, setZoom } = useContext(ZoomContext)
51+
return (e: MouseEvent<HTMLElement>) => {
52+
const shot = e.currentTarget
53+
const target = e.target as HTMLElement
54+
if (shot.querySelector('[data-placing]') || target.closest('a, button, [data-pin]')) return
55+
const own = Number(shot.dataset.ownWidth)
56+
if (!own) return
57+
const before = shot.getBoundingClientRect()
58+
const fx = (e.clientX - before.left) / before.width
59+
const fy = (e.clientY - before.top) / before.height
60+
const { clientX, clientY } = e
61+
setZoom(nextZoom(zoom, before.width, own))
62+
requestAnimationFrame(() =>
63+
requestAnimationFrame(() => {
64+
const after = shot.getBoundingClientRect()
65+
const scroller = shot.parentElement
66+
if (scroller) scroller.scrollLeft += after.left + fx * after.width - clientX
67+
window.scrollBy(0, after.top + fy * after.height - clientY)
68+
}),
69+
)
70+
}
71+
}

0 commit comments

Comments
 (0)