Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 151 additions & 0 deletions server/frontend/src/__tests__/comment-pins.test.tsx
Original file line number Diff line number Diff line change
@@ -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(
<QueryClientProvider client={client}>
<CommentsProvider
org="acme"
project="web"
build={3}
snapshotId="s1"
threads={[]}
compared={{ kind: 'baseline' }}
previousBuild={null}
showPrevious={() => {}}
canComment
canResolve
>
<CommentButton page={0} />
<CommentHint page={0} extra="It goes on the image where you press." />
<PageImages page={page} mode={mode} highlight="off" onExpired={() => {}} name="dashboard/390-light" kind="image" />
<PageThreads page={0} />
</CommentsProvider>
</QueryClientProvider>,
)
}

/** 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.')
})
})
27 changes: 27 additions & 0 deletions server/frontend/src/__tests__/zoom.test.ts
Original file line number Diff line number Diff line change
@@ -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')
})
})
13 changes: 12 additions & 1 deletion server/frontend/src/components/Comments.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,18 @@ export function CommentButton({ page }: { page: number | null }) {
>
<ChatCircleIcon size={14} /> {open ? 'Cancel' : 'Comment'}
</Button>
{open && <span className="hint hide-sm">Click for a point, drag for an area</span>}
</span>
)
}

/** 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 (
<span className="comment-hint" role="status">
Click for a point, drag for an area.{extra ? ` ${extra}` : ''}
</span>
)
}
Expand Down
118 changes: 118 additions & 0 deletions server/frontend/src/components/SliderStage.tsx
Original file line number Diff line number Diff line change
@@ -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<HTMLSpanElement>(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<HTMLSpanElement>) => {
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<HTMLSpanElement>) => {
if (dragging.current) moveTo(e.clientX)
}
const stop = () => {
dragging.current = false
}
const onKeyDown = (e: KeyboardEvent<HTMLSpanElement>) => {
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 (
<span
ref={stage}
className={['shot', 'slider-stage', className].filter(Boolean).join(' ')}
style={style}
data-fade={fade || undefined}
role="slider"
tabIndex={0}
aria-label={label}
aria-orientation="horizontal"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={Math.round(pos)}
aria-valuetext={fade ? `${Math.round(pos)}% of the new version` : `Divider at ${Math.round(pos)}%`}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={stop}
onPointerCancel={stop}
onLostPointerCapture={stop}
onKeyDown={onKeyDown}
onDragStart={(e) => e.preventDefault()}
>
{base}
<span className="slider-top" style={fade ? { opacity: pos / 100 } : { clipPath: `inset(0 0 0 ${pos}%)` }}>
{head}
</span>
{typeof children === 'function' ? children(pos) : children}
<span className="slider-line" style={{ left: `${pos}%` }} data-fade={fade || undefined} aria-hidden>
<span className="slider-handle">
<CaretLeftIcon size={12} weight="bold" />
<CaretRightIcon size={12} weight="bold" />
</span>
</span>
</span>
)
}

const clamp = (v: number) => Math.min(100, Math.max(0, v))
71 changes: 71 additions & 0 deletions server/frontend/src/lib/zoom.ts
Original file line number Diff line number Diff line change
@@ -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<Zoom, string> = { 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<HTMLElement>) => {
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)
}),
)
}
}
Loading
Loading