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

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions scripts/screenshots/pages.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ export function pages() {
['app/snapshot/json', snapshot('web', 3, 'api/orders.json'), true, ALL],
['app/snapshot/html', snapshot('web', 3, 'emails/welcome.html'), true, ALL],
['app/snapshot/text', snapshot('web', 3, 'cli/help.txt'), true, ALL],
// The slider view, last of the snapshot pages: a ?mode= link is remembered, like the buttons.
['app/snapshot/slider', async (api) => `${await snapshot('web', 3, 'dashboard/1440-light')(api)}?mode=slider`, true, ALL],
['app/billing/team', '/acme/billing', true, ALL],
['app/billing/free', '/side-project/billing', true, ALL],
['app/account', '/account', true, ALL],
Expand Down
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))
3 changes: 3 additions & 0 deletions server/frontend/src/lib/snapshotModes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/** A snapshot page's views of a page's images, in the order of their keys (1 to 5). */
export const SNAPSHOT_MODES = ['side', 'diff', 'slider', 'base', 'head'] as const
export type SnapshotMode = (typeof SNAPSHOT_MODES)[number]
Loading
Loading