feat(editor): two-finger pan, touch hint, loupe, touch-sized handles

useFraming gains twoPointerPan (the editor's pinch also pans by the
midpoint and scales from the spread since the pinch began; the
catalogue passes nothing). A futile one-finger drag shows the R-1
hint unless two fingers already worked in this editor visit (work
store flag). A finger drag of a handle shows the loupe (technique A:
the drawing copied once, data-anno-id stripped, outline on top).
editor-touch.spec covers 1 024, 1 180 and 1 280 px with CDP touch.
measure-drag.ts is the hand-run smoothness measure (MEASURE_DRAG=1).
equineShape moved from editor-zones.spec to support/editor.ts, no
assertion changed.
This commit is contained in:
bchanot committed 2026-11-18 10:54:46 +01:00
1 parent 3a7715486b
commit 85231a2680
18 files changed
+1338 -53

No files matched your search

@@ -0,0 +1,34 @@
import { test } from '../support/browser'
import { measureDrag } from '../support/measure-drag'
import { dropLateReplays, routeToSandbox } from '../support/sandbox'
// U2 Task 8: the hand-run smoothness measure (support/measure-drag.ts). Skipped unless
// MEASURE_DRAG=1: a timing figure, never a suite assertion.
test.describe('drag smoothness measure (hand-run)', () => {
test.use({
locale: 'fr-FR',
hasTouch: true,
viewport: { width: 1180, height: 800 },
})
test.beforeEach(async ({ context }, info) => {
test.skip(process.env.MEASURE_DRAG !== '1', 'run by hand: MEASURE_DRAG=1')
test.skip(info.project.name !== 'chromium-desktop', 'one run, at 1 180 px')
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('vertex drag on the equine main view, touch with the loupe and mouse', async ({
page,
context,
}, info) => {
test.setTimeout(180_000)
for (const figures of await measureDrag(page, context)) {
const line = JSON.stringify(figures)
console.log(`MEASURE ${line}`)
info.annotations.push({ type: 'measure', description: line })
}
})
})
+420
View File
@@ -0,0 +1,420 @@
import { fr } from '@/i18n/fr'
import type { CDPSession, Page, TestInfo } from '@playwright/test'
import { expect, test } from '../support/browser'
import { dropLateReplays, routeToSandbox } from '../support/sandbox'
import {
clientOf,
creationPanel,
editorActor,
historyButton,
openEditor,
pickAnnotation,
pointOf,
seedDraft,
selectionTag,
shapeWith,
shownNumber,
shownPoints,
toolButton,
} from '../support/editor'
import { expectNoShift } from '../support/layout'
// V1-2.6 U2 Task 8: the editor by finger (A13, board 13) at 1 024, 1 180 and 1 280 px, with
// CDP touch points: a finger drags what it holds (a vertex, the point) under the loupe and
// nothing else (the two-finger hint, R-1, shown once, nothing moving), two fingers zoom and
// pan, a second finger cancels a vertex drag (Review Focus 1), the move mode, a tap on the
// selection (A1), the tracing closed within 22 px (R-11), the page scroll over the drawing
// without a selection, and every handle reached within 44 px (R-9).
const dict = fr
const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
const WIDTHS = [1024, 1180, 1280]
const HINT = dict['editor.annotations.message.two_fingers']
const POINT = 'Pt Alpha'
const ZONE = 'Zone Beta'
const SQUARE = [
[300, 200],
[600, 200],
[600, 500],
[300, 500],
]
// Away from every annotation and handle (drawing units of the 1000 × 800 fixture).
const EMPTY = { x: 150, y: 150 }
const INSIDE = { x: 450, y: 330 }
const zone = {
...pointOf('zone-b', 'main', { cx: 0, cy: 0, r: 1 }, ZONE),
kind: 'zone',
geometry: { type: 'polygon', points: SQUARE },
}
type XY = { x: number; y: number }
const touch = (
cdp: CDPSession,
type: 'touchStart' | 'touchMove' | 'touchEnd',
points: XY[],
) =>
cdp.send('Input.dispatchTouchEvent', {
type,
touchPoints: points.map((p, id) => ({ x: p.x, y: p.y, id })),
})
const between = (from: XY, to: XY, step: number, steps: number) => ({
x: from.x + ((to.x - from.x) * step) / steps,
y: from.y + ((to.y - from.y) * step) / steps,
})
/** Fingers moved together from `from` to `to` in `steps` moves (no touchEnd). */
async function move(cdp: CDPSession, from: XY[], to: XY[], steps = 6) {
for (let step = 1; step <= steps; step++)
await touch(
cdp,
'touchMove',
from.map((f, i) => between(f, to[i], step, steps)),
)
}
async function tap(cdp: CDPSession, at: XY) {
await touch(cdp, 'touchStart', [at])
await touch(cdp, 'touchEnd', [])
}
/** One finger pressed at `from`, dragged to `to`, released. */
async function drag(cdp: CDPSession, from: XY, to: XY) {
await touch(cdp, 'touchStart', [from])
await move(cdp, [from], [to])
await touch(cdp, 'touchEnd', [])
}
/** Two fingers 60 px apart around `at`, spread to 240 px: the drawing zooms in. */
async function pinchOut(cdp: CDPSession, at: XY) {
const start = [
{ x: at.x - 30, y: at.y },
{ x: at.x + 30, y: at.y },
]
const end = [
{ x: at.x - 120, y: at.y },
{ x: at.x + 120, y: at.y },
]
await touch(cdp, 'touchStart', start)
await move(cdp, start, end)
await touch(cdp, 'touchEnd', [])
}
const canvas = (page: Page) => page.getByTestId('annotation-canvas')
const loupe = (page: Page) => page.getByTestId('loupe')
const message = (page: Page) => page.getByTestId('gesture-message')
const button = (page: Page, key: string) =>
page.getByRole('button', { name: dict[key], exact: true })
/** The framing of the drawing layer: `translate(x, y) scale(s)`. */
async function framing(page: Page) {
const transform = await page
.getByTestId('annotation-canvas-drawing')
.evaluate((el) => (el.parentElement as HTMLElement).style.transform)
const [x, y, scale] = (transform.match(/-?[\d.]+/g) ?? []).map(Number)
return { x, y, scale }
}
async function open(page: Page) {
const actor = await editorActor('fr')
const seed = await seedDraft(actor, {
shape: shapeWith(
pointOf('pt-a', 'main', { cx: 750, cy: 600, r: 30 }, POINT),
zone,
),
})
const saves: string[] = []
page.on('request', (request) => {
if (request.url().includes('save_sheet_draft')) saves.push(request.url())
})
await openEditor(page, dict, actor, seed.sheetId)
await expect(toolButton(page, dict, 'point')).toBeEnabled()
return { actor, saves }
}
/** Selects from the overview, then brings the whole drawing into view. */
async function select(page: Page, name: string) {
await pickAnnotation(page, dict, name)
await expect(selectionTag(page)).toContainText(name)
await canvas(page).scrollIntoViewIfNeeded()
}
/** R-9 on a finger: every hit circle at least 44 px, the « − » bubble 44 × 36 px. */
async function expectFingerSizedHandles(page: Page) {
const shapes = await page
.locator('[data-testid="handle-layer"] [data-handle]')
.evaluateAll((elements) =>
elements.map((el) => {
const box = el.getBoundingClientRect()
return { tag: el.tagName, w: box.width, h: box.height }
}),
)
expect(shapes.length).toBeGreaterThan(0)
for (const shape of shapes) {
if (shape.tag === 'circle') {
expect(Math.min(shape.w, shape.h), 'hit circle').toBeGreaterThanOrEqual(
43.5,
)
} else {
expect(shape.w, '« − » width').toBeGreaterThanOrEqual(43.5)
expect(shape.h, '« − » height').toBeGreaterThanOrEqual(35.5)
}
}
return shapes
}
/** The loupe while a finger moves: shown, round, inside the canvas box. */
async function expectLoupeInBox(page: Page) {
await expect(loupe(page)).toBeVisible()
const disc = (await loupe(page).boundingBox())!
const box = (await canvas(page).boundingBox())!
expect(disc.width).toBeCloseTo(120, 0)
expect(disc.x).toBeGreaterThanOrEqual(box.x - 1)
expect(disc.y).toBeGreaterThanOrEqual(box.y - 1)
expect(disc.x + disc.width).toBeLessThanOrEqual(box.x + box.width + 1)
expect(disc.y + disc.height).toBeLessThanOrEqual(box.y + box.height + 1)
await expect(loupe(page).locator('[data-anno-id]')).toHaveCount(0)
}
/** One finger from `from` to `to`, the loupe checked halfway. */
async function dragWithLoupe(page: Page, cdp: CDPSession, from: XY, to: XY) {
await touch(cdp, 'touchStart', [from])
await move(cdp, [from], [between(from, to, 1, 2)], 3)
await expectLoupeInBox(page)
await move(cdp, [between(from, to, 1, 2)], [to], 3)
await touch(cdp, 'touchEnd', [])
await expect(loupe(page)).toHaveCount(0)
}
for (const width of WIDTHS) {
test.describe(`the editor by finger at ${width} px (U2 Task 8)`, () => {
test.use({
locale: 'fr-FR',
actionTimeout: 15_000,
hasTouch: true,
viewport: { width, height: 800 },
})
test.beforeEach(async ({ context }, info) => {
test.skip(isPhone(info), 'editing needs 1 024 px') // floor-guard: allow C16 editing needs >= 1024 px; phone read-only covered in editor-access
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('a finger drags a vertex and the point under the loupe; handles answer within 44 px', async ({
page,
context,
requests,
}) => {
const { actor } = await open(page)
requests.forbid(actor.account.email, actor.account.password)
const cdp = await context.newCDPSession(page)
await select(page, ZONE)
await expectFingerSizedHandles(page)
const from = await clientOf(page, 600, 200)
await dragWithLoupe(page, cdp, from, { x: from.x + 40, y: from.y + 30 })
await expect(message(page)).toContainText(
dict['editor.annotations.message.vertex_moved'],
)
const [, moved] = await shownPoints(page)
expect(moved).not.toEqual(SQUARE[1])
// The chosen vertex shows its « − » bubble: finger-sized too.
await expect(
page.getByRole('button', { name: /^Retirer le sommet/ }),
).toHaveCount(1)
await expectFingerSizedHandles(page)
await select(page, POINT)
const centre = await clientOf(page, 750, 600)
await dragWithLoupe(page, cdp, centre, {
x: centre.x - 40,
y: centre.y - 20,
})
await expect(message(page)).toContainText(
dict['editor.annotations.message.moved.point'],
)
expect(await shownNumber(page, 'cx')).toBeLessThan(750)
// Zoomed in, the handles keep their CSS px size.
await pinchOut(cdp, await clientOf(page, EMPTY.x, EMPTY.y))
expect((await framing(page)).scale).toBeGreaterThan(1)
await select(page, ZONE)
await expectFingerSizedHandles(page)
})
test('a finger off the handles moves nothing and shows the hint once; no hint over a scroll', async ({
page,
context,
requests,
}) => {
const { actor, saves } = await open(page)
requests.forbid(actor.account.email, actor.account.password)
const cdp = await context.newCDPSession(page)
// No selection at the fit: a finger scrolls the page over the drawing.
await page.evaluate(() => window.scrollTo(0, 0))
const room = await page.evaluate(
() => document.documentElement.scrollHeight - window.innerHeight,
)
expect(room, 'the page can scroll').toBeGreaterThan(40)
const box = (await canvas(page).boundingBox())!
const low = {
x: box.x + box.width / 2,
y: Math.min(box.y + box.height, 790) - 20,
}
await drag(cdp, low, { x: low.x, y: low.y - 200 })
await expect
.poll(() => page.evaluate(() => window.scrollY))
.toBeGreaterThan(0)
await expect(message(page)).toHaveCount(0)
await select(page, ZONE)
const empty = await clientOf(page, EMPTY.x, EMPTY.y)
await expectNoShift(page, async () => {
await drag(cdp, empty, { x: empty.x + 60, y: empty.y + 40 })
await expect(message(page)).toHaveText(HINT)
})
expect(await shownPoints(page)).toEqual(SQUARE)
expect((await framing(page)).scale).toBe(1)
// The hint leaves after 4 s; the line is free again.
await expect(message(page)).toHaveCount(0, { timeout: 6_000 })
// Two fingers worked: never again in this visit.
await pinchOut(cdp, await clientOf(page, INSIDE.x, INSIDE.y))
expect((await framing(page)).scale).toBeGreaterThan(1)
const again = await clientOf(page, 320, 220)
await drag(cdp, again, { x: again.x + 50, y: again.y })
await page.waitForTimeout(300)
await expect(message(page)).toHaveCount(0)
expect(saves).toEqual([])
})
test('two fingers zoom and pan; a second finger cancels a vertex drag and pinches (Review Focus 1)', async ({
page,
context,
requests,
}) => {
const { actor, saves } = await open(page)
requests.forbid(actor.account.email, actor.account.password)
const cdp = await context.newCDPSession(page)
await select(page, ZONE)
const undo = historyButton(page, dict, 'undo')
await expect(undo).toBeDisabled()
// Finger 1 drags vertex 2 under the loupe, then finger 2 lands.
const vertex = await clientOf(page, 600, 200)
const held = { x: vertex.x + 30, y: vertex.y + 30 }
await touch(cdp, 'touchStart', [vertex])
await move(cdp, [vertex], [held], 3)
await expect(loupe(page)).toBeVisible()
expect(await shownPoints(page)).not.toEqual(SQUARE)
const other = await clientOf(page, EMPTY.x, EMPTY.y)
await touch(cdp, 'touchStart', [held, other])
await expect(loupe(page)).toHaveCount(0)
expect(await shownPoints(page)).toEqual(SQUARE)
// The pinch goes on: the drawing zooms, the shape stays where it was.
const spread = { x: other.x - 80, y: other.y - 40 }
await move(
cdp,
[held, other],
[{ x: held.x + 40, y: held.y + 20 }, spread],
)
await touch(cdp, 'touchEnd', [])
expect((await framing(page)).scale).toBeGreaterThan(1)
expect(await shownPoints(page)).toEqual(SQUARE)
await expect(page.getByRole('dialog')).toHaveCount(0)
await expect(selectionTag(page)).toContainText(ZONE)
await expect(undo).toBeDisabled()
// Two fingers zoom further, then pan together without scaling.
await pinchOut(cdp, await clientOf(page, INSIDE.x, INSIDE.y))
const zoomed = await framing(page)
const centre = await clientOf(page, INSIDE.x, INSIDE.y)
const pair = [
{ x: centre.x - 60, y: centre.y },
{ x: centre.x + 60, y: centre.y },
]
await touch(cdp, 'touchStart', pair)
await move(
cdp,
pair,
pair.map((p) => ({ x: p.x + 50, y: p.y + 30 })),
)
await touch(cdp, 'touchEnd', [])
const panned = await framing(page)
expect(panned.scale).toBeCloseTo(zoomed.scale, 2)
expect(Math.abs(panned.x - zoomed.x - 50)).toBeLessThan(1.5)
expect(Math.abs(panned.y - zoomed.y - 30)).toBeLessThan(1.5)
expect(await shownPoints(page)).toEqual(SQUARE)
await expect(undo).toBeDisabled()
expect(saves).toEqual([])
})
test('the move mode by a finger; a tap opens the selection or unchooses; a trace closes within 22 px', async ({
page,
context,
requests,
}) => {
const { actor } = await open(page)
requests.forbid(actor.account.email, actor.account.password)
const cdp = await context.newCDPSession(page)
await select(page, ZONE)
// « Déplacer la zone »: a finger anywhere moves it, « Valider la position » commits.
await button(page, 'editor.annotations.move.zone').click()
await canvas(page).scrollIntoViewIfNeeded()
const empty = await clientOf(page, EMPTY.x, EMPTY.y)
await drag(cdp, empty, { x: empty.x + 40, y: empty.y + 40 })
const previewed = await shownPoints(page)
expect(previewed).not.toEqual(SQUARE)
await button(page, 'editor.annotations.move.confirm').click()
await expect.poll(() => shownPoints(page)).toEqual(previewed)
const dx = previewed[0][0] - SQUARE[0][0]
const dy = previewed[0][1] - SQUARE[0][1]
expect(dx).toBeGreaterThan(0)
expect(previewed[2][0]).toBeCloseTo(SQUARE[2][0] + dx, 6)
expect(previewed[2][1]).toBeCloseTo(SQUARE[2][1] + dy, 6)
// A tap on the selected zone opens its properties; the dialog stays.
await canvas(page).scrollIntoViewIfNeeded()
const inside = await clientOf(page, INSIDE.x + dx, INSIDE.y + dy)
await tap(cdp, inside)
const dialog = page.getByRole('dialog')
await expect(dialog).toBeVisible()
await page.waitForTimeout(450)
await expect(dialog).toBeVisible()
await page.keyboard.press('Escape')
await expect(dialog).toHaveCount(0)
// A tap on a vertex chooses it; a tap inside then unchooses, no dialog.
await canvas(page).scrollIntoViewIfNeeded()
const corner = previewed[0]
await tap(cdp, await clientOf(page, corner[0], corner[1]))
const bubble = page.getByRole('button', { name: /^Retirer le sommet/ })
await expect(bubble).toHaveCount(1)
await tap(cdp, await clientOf(page, INSIDE.x + dx, INSIDE.y + dy))
await expect(bubble).toHaveCount(0)
await expect(dialog).toHaveCount(0)
// A new zone traced by finger closes on a tap 18 px from its first vertex (R-11).
await button(page, 'editor.annotations.deselect').click()
await toolButton(page, dict, 'zone').click()
await canvas(page).scrollIntoViewIfNeeded()
const first = await clientOf(page, 150, 600)
// Quick taps, each within the absorber's 400 ms of the last: each one places.
for (const [x, y] of [
[150, 600],
[300, 600],
[300, 700],
]) {
await tap(cdp, await clientOf(page, x, y))
}
await expect(creationPanel(page)).toHaveCount(0)
await tap(cdp, { x: first.x + 18, y: first.y })
await expect(creationPanel(page)).toBeVisible()
})
})
}
+3 -36
View File
@@ -1,5 +1,3 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { fr } from '@/i18n/fr'
import type { Page, TestInfo } from '@playwright/test'
import { expect, expectAccessible, test } from '../support/browser'
@@ -7,6 +5,8 @@ import { dropLateReplays, routeToSandbox } from '../support/sandbox'
import {
clientOf,
editorActor,
equineDrawing,
equineShape,
openEditor,
pickAnnotation,
seedDraft,
@@ -23,47 +23,14 @@ import { expectNoShift } from '../support/layout'
const dict = fr
const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
const DRAFT = join(
__dirname,
'../../../../supabase/seed/anatomical-sheets/equine/draft',
)
const THORACIC = /Vertèbres thoraciques/
// The side panel's content may change (U2 Task 6 moves it into a dialog).
interface Draft {
vertebral_config: unknown
references: unknown
categories: unknown
finding_zones: unknown
views: { id: string; svg_asset_id: string | null }[]
annotations: { view_id: string; kind: string }[]
}
/** The equine draft's main view, its annotations and structures, on the seeded drawing. */
function equineShape(document: Record<string, unknown>) {
const draft = JSON.parse(
readFileSync(join(DRAFT, 'document.json'), 'utf8'),
) as Draft
const [seeded] = document.views as Draft['views']
const main = draft.views.find((view) => view.id === 'main')!
Object.assign(document, {
vertebral_config: draft.vertebral_config,
references: draft.references,
categories: draft.categories,
finding_zones: draft.finding_zones,
views: [{ ...main, svg_asset_id: seeded.svg_asset_id }],
// The detail view is left out, so is the link that opens it.
annotations: draft.annotations.filter(
(a) => a.view_id === 'main' && a.kind !== 'detail_trigger',
),
})
}
async function openThoracic(page: Page) {
await page.setViewportSize({ width: 1280, height: 800 })
const actor = await editorActor('fr')
const seed = await seedDraft(actor, {
drawing: readFileSync(join(DRAFT, 'assets/horse.svg'), 'utf8'),
drawing: equineDrawing(),
shape: equineShape,
})
await openEditor(page, dict, actor, seed.sheetId)
+39
View File
@@ -899,3 +899,42 @@ export const INKSCAPE_EXPORT = readFileSync(
'../../../../crates/core/tests/fixtures/svg/exports/inkscape-1.4.3-inkscape-svg.svg',
),
)
/** The curated equine draft (document and drawing): a drawing and a document of real size. */
const EQUINE_DRAFT = join(
__dirname,
'../../../../supabase/seed/anatomical-sheets/equine/draft',
)
interface Draft {
vertebral_config: unknown
references: unknown
categories: unknown
finding_zones: unknown
views: { id: string; svg_asset_id: string | null }[]
annotations: { view_id: string; kind: string }[]
}
/** The equine draft's main view, its annotations and structures, on the seeded drawing. */
export function equineShape(document: Record<string, unknown>) {
const draft = JSON.parse(
readFileSync(join(EQUINE_DRAFT, 'document.json'), 'utf8'),
) as Draft
const [seeded] = document.views as Draft['views']
const main = draft.views.find((view) => view.id === 'main')!
Object.assign(document, {
vertebral_config: draft.vertebral_config,
references: draft.references,
categories: draft.categories,
finding_zones: draft.finding_zones,
views: [{ ...main, svg_asset_id: seeded.svg_asset_id }],
// The detail view is left out, so is the link that opens it.
annotations: draft.annotations.filter(
(a) => a.view_id === 'main' && a.kind !== 'detail_trigger',
),
})
}
/** The equine main view's drawing, as a person would attach it. */
export const equineDrawing = () =>
readFileSync(join(EQUINE_DRAFT, 'assets/horse.svg'), 'utf8')
+184
View File
@@ -0,0 +1,184 @@
/**
* The smoothness measure of U2 Task 8 (plan Task 8 Step 1), run by hand, never by a suite: a
* timing assertion would flake on the shared sandbox. Chromium touch at 1 180 px, CPU × 4, a
* 2 s drag of a vertex of « Vertèbres thoraciques » on the equine main view (the curated
* draft's drawing and document, seeded per run as a new draft of its own: no existing sheet
* or working copy is opened). It prints the median and the p95, in ms, from each
* pointermove to the end of the next frame (after its style, layout and paint), loupe
* included; the same drag with a mouse (no loupe) is the control.
*
* Run: MEASURE_DRAG=1 pnpm db:sandbox e2e-shell editor-measure-drag.spec.ts
*/
import type { BrowserContext, Page } from '@playwright/test'
import { fr } from '@/i18n/fr'
import { expect } from './browser'
import {
editorActor,
equineDrawing,
equineShape,
openEditor,
pickAnnotation,
seedDraft,
toolButton,
} from './editor'
const DURATION_MS = 2_000
const STEP_MS = 16
const RADIUS_PX = 40
const CPU_RATE = 4
export interface DragFigures {
kind: 'touch' | 'mouse'
samples: number
/** Samples whose frame showed the loupe. */
withLoupe: number
/** From the event's own time stamp (input queueing included) to the frame's end. */
fromEvent: { median: number; p95: number }
/** From the first listener of the event to the frame's end: the frame's own work. */
fromHandler: { median: number; p95: number }
}
interface Sample {
fromEvent: number
fromHandler: number
/** The loupe was on screen at the frame's end. */
loupe: boolean
}
/** A capture listener on the document: it runs before the application's own. */
function startRecording(page: Page, kind: string) {
return page.evaluate((pointerType) => {
const scope = window as unknown as { __drag: Sample[] }
scope.__drag = []
const record = (event: PointerEvent) => {
if (event.pointerType !== pointerType || event.buttons === 0) return
const start = performance.now()
requestAnimationFrame(() => {
// The message runs after this frame's rendering: style, layout and paint.
const channel = new MessageChannel()
channel.port1.onmessage = () => {
const end = performance.now()
scope.__drag.push({
fromEvent: end - event.timeStamp,
fromHandler: end - start,
loupe: document.querySelector('[data-testid="loupe"]') !== null,
})
}
channel.port2.postMessage(0)
})
}
document.addEventListener('pointermove', record, true)
}, kind)
}
const percentile = (sorted: number[], p: number) =>
sorted[Math.min(sorted.length - 1, Math.floor((sorted.length - 1) * p))]
function summary(values: number[]) {
const sorted = [...values].sort((a, b) => a - b)
const round = (v: number) => Math.round(v * 10) / 10
return {
median: round(percentile(sorted, 0.5)),
p95: round(percentile(sorted, 0.95)),
}
}
async function figures(page: Page, kind: DragFigures['kind']) {
const samples = await page.evaluate(
() => (window as unknown as { __drag: Sample[] }).__drag,
)
return {
kind,
samples: samples.length,
withLoupe: samples.filter((s) => s.loupe).length,
fromEvent: summary(samples.map((s) => s.fromEvent)),
fromHandler: summary(samples.map((s) => s.fromHandler)),
}
}
/** The point of the circle the drag follows, `elapsed` ms after its start. */
function pathAt(from: { x: number; y: number }, elapsed: number) {
const angle = (2 * Math.PI * elapsed) / DURATION_MS
return {
x: from.x + RADIUS_PX * Math.sin(angle),
y: from.y - RADIUS_PX * (1 - Math.cos(angle)),
}
}
type Mover = (at: { x: number; y: number }) => Promise<unknown>
/** Moves along the path for DURATION_MS, one move per STEP_MS at most. */
async function follow(from: { x: number; y: number }, moveTo: Mover) {
const start = Date.now()
for (let elapsed = 0; elapsed < DURATION_MS; elapsed = Date.now() - start) {
await moveTo(pathAt(from, elapsed))
await new Promise((done) => setTimeout(done, STEP_MS))
}
}
async function vertexCentre(page: Page) {
const box = (await page
.getByRole('button', { name: 'Sommet 1', exact: true })
.locator('[data-handle]')
.boundingBox())!
return { x: box.x + box.width / 2, y: box.y + box.height / 2 }
}
async function touchDrag(page: Page, context: BrowserContext) {
const cdp = await context.newCDPSession(page)
const from = await vertexCentre(page)
const send = (type: string, points: { x: number; y: number }[]) =>
cdp.send('Input.dispatchTouchEvent', {
type: type as 'touchStart',
touchPoints: points.map((p) => ({ ...p, id: 0 })),
})
await send('touchStart', [from])
await follow(from, (at) => send('touchMove', [at]))
await send('touchEnd', [])
}
async function mouseDrag(page: Page) {
const from = await vertexCentre(page)
await page.mouse.move(from.x, from.y)
await page.mouse.down()
await follow(from, (at) => page.mouse.move(at.x, at.y))
await page.mouse.up()
}
/** One measured drag of the same vertex, by `kind`, CPU × 4 while it runs. */
async function measure(
page: Page,
context: BrowserContext,
kind: DragFigures['kind'],
): Promise<DragFigures> {
const cdp = await context.newCDPSession(page)
await page.getByTestId('annotation-canvas').scrollIntoViewIfNeeded()
await startRecording(page, kind)
await cdp.send('Emulation.setCPUThrottlingRate', { rate: CPU_RATE })
try {
if (kind === 'touch') await touchDrag(page, context)
else await mouseDrag(page)
} finally {
await cdp.send('Emulation.setCPUThrottlingRate', { rate: 1 })
}
return figures(page, kind)
}
/** Seeds its own equine-sized draft, opens it, selects the zone, measures touch then mouse. */
export async function measureDrag(
page: Page,
context: BrowserContext,
): Promise<DragFigures[]> {
const actor = await editorActor('fr')
const seed = await seedDraft(actor, {
drawing: equineDrawing(),
shape: equineShape,
})
await openEditor(page, fr, actor, seed.sheetId)
await expect(toolButton(page, fr, 'point')).toBeEnabled()
await pickAnnotation(page, fr, /Vertèbres thoraciques/)
const touch = await measure(page, context, 'touch')
// The drop committed the vertex; the mouse drags the same vertex from there.
const mouse = await measure(page, context, 'mouse')
return [touch, mouse]
}
+70 -10
View File
@@ -30,6 +30,17 @@ export interface FramingOptions {
* caller tells a drag from a click), replacing the 4 px threshold and `canPan`.
*/
panning?: () => boolean
/**
* The editor's pinch: two fingers also pan by their midpoint's movement, and the scale
* follows the fingers' spread since the pinch began (a clamp at the fit never ratchets).
*/
twoPointerPan?: boolean
}
/** Where a pinch began: its spread and the scale then. */
interface PinchStart {
spread: number
scale: number
}
function boxOf(
@@ -48,6 +59,42 @@ function distance(a: Point, b: Point): number {
return Math.hypot(a.x - b.x, a.y - b.y)
}
const midpoint = (a: Point, b: Point, box: { left: number; top: number }) => ({
x: (a.x + b.x) / 2 - box.left,
y: (a.y + b.y) / 2 - box.top,
})
/** The pinch's base, taken whenever exactly two pointers are down. */
function pinchStart(
pointers: Map<number, Point>,
scale: number,
): PinchStart | null {
if (pointers.size !== 2) return null
const [a, b] = [...pointers.values()]
return { spread: Math.max(distance(a, b), 1), scale }
}
/**
* One finger of a two-finger pan moved from `before` to `now`: the drawing scales around
* the old midpoint to the spread's scale, then follows the midpoint (half the move).
*/
function pinchPan(
framing: Framing,
start: PinchStart,
fingers: { before: Point; now: Point; other: Point },
box: Box & { left: number; top: number },
): Framing {
const { before, now, other } = fingers
const target = (start.scale * distance(now, other)) / start.spread
const zoomed = zoomBy(
framing,
target / framing.scale,
box,
midpoint(before, other, box),
)
return panBy(zoomed, (now.x - before.x) / 2, (now.y - before.y) / 2, box)
}
/** One-pointer pan: the caller's gate when it gives one, else past the threshold and allowed. */
function pansNow(
gate: (() => boolean) | undefined,
@@ -81,6 +128,9 @@ export function useFraming(
canPan.current = options.canPan
const panning = useRef(options.panning)
panning.current = options.panning
const twoPointerPan = useRef(options.twoPointerPan ?? false)
twoPointerPan.current = options.twoPointerPan ?? false
const pinch = useRef<PinchStart | null>(null)
useEffect(() => setFraming(FIT), [resetKey])
useEffect(() => {
@@ -128,8 +178,25 @@ export function useFraming(
dragged.current = false
panAllowed.current = canPan.current?.(event) ?? true
}
pinch.current = pinchStart(pointers.current, scale.current)
}, [])
const pinchMove = useCallback(
(fingers: { before: Point; now: Point; other: Point }) => {
const box = boxOf(viewport.current)
const start = pinch.current
if (twoPointerPan.current && start) {
setFraming((f) => pinchPan(f, start, fingers, box))
return
}
const { now, other } = fingers
const factor =
distance(now, other) / Math.max(distance(fingers.before, other), 1)
zoom(factor, midpoint(now, other, box))
},
[viewport, zoom],
)
const onPointerMove = useCallback(
(event: PointerEvent) => {
const before = pointers.current.get(event.pointerId)
@@ -142,15 +209,7 @@ export function useFraming(
moved.current += distance(before, now)
if (moved.current > DRAG_THRESHOLD) dragged.current = true
if (others.length === 1) {
const other = others[0][1]
const box = boxOf(viewport.current)
const at = {
x: (now.x + other.x) / 2 - box.left,
y: (now.y + other.y) / 2 - box.top,
}
const factor =
distance(now, other) / Math.max(distance(before, other), 1)
zoom(factor, at)
pinchMove({ before, now, other: others[0][1] })
} else if (
others.length === 0 &&
pansNow(panning.current, dragged, panAllowed)
@@ -159,11 +218,12 @@ export function useFraming(
pan(now.x - before.x, now.y - before.y)
}
},
[viewport, zoom, pan],
[pinchMove, pan],
)
const onPointerUp = useCallback((event: PointerEvent) => {
pointers.current.delete(event.pointerId)
pinch.current = pinchStart(pointers.current, scale.current)
}, [])
const onKeyDown = useCallback(
@@ -27,6 +27,7 @@ import type { ToolId } from '@/editor/annotations/uiState'
import { useT } from '@/i18n/useT'
import AnnotationOverlay, { type OverlayProps } from './AnnotationOverlay'
import HandleLayer, { type HandleLayerProps } from './HandleLayer'
import Loupe from './Loupe'
import ToolColumn, { type ToolColumnProps } from './ToolColumn'
type OverlayData = Omit<
@@ -64,6 +65,8 @@ export interface AnnotationCanvasProps {
onDrop: Drop
onHandle: (action: HandleAction) => void
onDeselect: () => void
/** A one-finger drag off the handles moved nothing (R-1). */
onFutileDrag: () => void
onTraceKey: (event: KeyboardEvent) => void
}
@@ -99,6 +102,7 @@ export default function AnnotationCanvas(props: AnnotationCanvasProps) {
build={build}
viewport={viewport}
boxProps={withPreview(gestures.boxProps, preview)}
finger={gestures.finger}
layer={{
transform: transformOf(gestures.framing.framing),
overlay: {
@@ -160,14 +164,18 @@ function CanvasBox({
viewName,
tool,
creating,
selectedId,
build,
viewport,
boxProps,
finger,
layer,
}: AnnotationCanvasProps & {
build: Build
viewport: RefObject<HTMLDivElement | null>
boxProps: BoxProps
/** A finger's drag in flight: the loupe above it (board 13). */
finger: XY | null
layer: Omit<LayerProps, 'host' | 'root'>
}) {
const root = build.root?.viewId === viewId ? build.root : null
@@ -186,6 +194,17 @@ function CanvasBox({
>
<DrawingLayer host={build.host} root={root} {...layer} />
</div>
{finger && root && (
<Loupe
finger={finger}
viewport={viewport}
host={build.host}
transform={layer.transform}
root={root}
selectedId={selectedId}
dragged={layer.overlay.dragged}
/>
)}
<CanvasFailure failure={build.failure} retry={build.retry} />
</div>
)
@@ -29,7 +29,7 @@ export interface OverlayProps {
const STROKE = { fill: 'none', vectorEffect: 'non-scaling-stroke' } as const
function Outline({
export function Outline({
geometry,
dashed,
colour,
@@ -55,7 +55,13 @@ function Outline({
return null
}
function Vertices({ geometry, size }: { geometry: Geometry; size: number }) {
export function Vertices({
geometry,
size,
}: {
geometry: Geometry
size: number
}) {
if (geometry.type !== 'polygon') return null
return (
<>
@@ -184,7 +190,7 @@ function TracingPath({ points, size }: { points: Point[]; size: number }) {
}
/** The selection's pending preview (move mode, slider, keys), read without the tab. */
function usePreviewOf(selectedId: string | null): Geometry | null {
export function usePreviewOf(selectedId: string | null): Geometry | null {
return useAnnotationWork((s) =>
selectedId !== null && s.preview?.annotationId === selectedId
? s.preview.geometry
@@ -34,7 +34,10 @@ import {
type OpenDialog,
} from '@/editor/annotations/dialogOpening'
import { creationStart, usePlacement } from '@/editor/annotations/usePlacement'
import { useGestureMessage } from '@/editor/annotations/useGestureMessage'
import {
useGestureMessage,
type GestureMessages,
} from '@/editor/annotations/useGestureMessage'
import {
initialUi,
uiReducer,
@@ -177,6 +180,12 @@ function useScene(props: Props): Scene {
}
}
/** R-1: a finger dragged off the handles, unless two fingers already worked in this visit. */
function hintTwoFingers(message: GestureMessages, t: CommitContext['t']) {
if (useAnnotationWork.getState().twoFingers) return
message.hint(t('editor.annotations.message.two_fingers'))
}
function useCommitContext(): CommitContext {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
@@ -353,6 +362,7 @@ function CanvasStage({
onDrop={work.placement.onDrop}
onHandle={work.zone.onHandle}
onDeselect={() => free && onDeselect()}
onFutileDrag={() => hintTwoFingers(work.message, work.context.t)}
onTraceKey={work.placement.onTraceKey}
/>
)
@@ -0,0 +1,156 @@
import { useLayoutEffect, useRef, useState, type RefObject } from 'react'
import type { Geometry } from '@faunosteo/core-wasm/types'
import { parseFrame, type XY } from '@/editor/annotations/frame'
import type { RootAttributes } from '@/editor/annotations/useCanvasBuild'
import { Outline, usePreviewOf, Vertices } from './AnnotationOverlay'
/** Board 13: a 120 px disc, its centre 90 px above the finger, twice the size on screen. */
const SIZE = 120
const LIFT = 90
const ZOOM = 2
export interface LoupeProps {
/** The finger's client point. */
finger: XY
/** The canvas box: the disc stays inside it. */
viewport: RefObject<HTMLDivElement | null>
/** The core's drawing, copied once when the loupe opens. */
host: RefObject<HTMLDivElement | null>
/** The framing's transform of the drawing layer. */
transform: string
root: RootAttributes
selectedId: string | null
/** The canvas-local drag preview; a move-mode drag previews through the work store. */
dragged: Geometry | null
}
interface Box {
left: number
top: number
width: number
height: number
}
const clamp = (value: number, max: number) =>
Math.min(Math.max(value, 0), Math.max(max, 0))
/** The box read once: a finger's drag never scrolls the page (`touch-action: none`). */
function useBoxAtOpen(viewport: RefObject<HTMLDivElement | null>) {
const [box, setBox] = useState<Box | null>(null)
useLayoutEffect(() => {
const rect = viewport.current?.getBoundingClientRect()
if (rect) setBox(rect)
}, [viewport])
return box
}
/**
* The drawing copied once into `into`: a picture, so every `data-anno-id` is removed and
* no press or locator ever reads the copy as a marker.
*/
function usePicture(
host: RefObject<HTMLDivElement | null>,
into: RefObject<HTMLDivElement | null>,
) {
useLayoutEffect(() => {
const drawing = host.current?.querySelector('svg')
if (!drawing || !into.current) return
const copy = drawing.cloneNode(true) as SVGSVGElement
for (const marked of [copy, ...copy.querySelectorAll('[data-anno-id]')]) {
marked.removeAttribute('data-anno-id')
}
into.current.replaceChildren(copy)
}, [host, into])
}
/** The disc's place in the box and the content's offset that centres it on the finger. */
function placeOf(finger: XY, box: Box) {
const x = finger.x - box.left
const y = finger.y - box.top
const half = SIZE / 2
return {
disc: {
x: clamp(x - half, box.width - SIZE),
y: clamp(y - LIFT - half, box.height - SIZE),
},
content: { x: half - ZOOM * x, y: half - ZOOM * y },
}
}
// `svg-canvas`: the copy's markers keep the canvas's look (the selection's mark).
const DISC =
'svg-canvas pointer-events-none absolute top-0 left-0 z-10 overflow-hidden ' +
'rounded-full border-2 border-[var(--color-ink)] bg-white shadow-lg'
const translate = (at: XY | undefined) =>
`translate(${at?.x ?? 0}px, ${at?.y ?? 0}px)`
/**
* The loupe of a finger's drag (board 13, docs/ANNOTATION-RENDERING.md « Editor overlay »):
* what the finger hides, at twice the size, with the preview outline on top. It never
* takes the pointer and is hidden from assistive technologies.
*/
export default function Loupe(props: LoupeProps) {
const picture = useRef<HTMLDivElement | null>(null)
const box = useBoxAtOpen(props.viewport)
usePicture(props.host, picture)
const preview = usePreviewOf(props.selectedId)
const outline = props.dragged ?? preview
const place = box ? placeOf(props.finger, box) : null
return (
<div
data-testid="loupe"
aria-hidden="true"
inert
className={DISC}
style={{
width: SIZE,
height: SIZE,
transform: translate(place?.disc),
visibility: place ? 'visible' : 'hidden',
}}
>
<div
className="origin-top-left"
style={{
width: box?.width,
height: box?.height,
transform: `${translate(place?.content)} scale(${ZOOM})`,
}}
>
<div
className="relative h-full w-full origin-top-left"
style={{ transform: props.transform }}
>
<div
ref={picture}
className="h-full w-full [&>svg]:block [&>svg]:h-full [&>svg]:w-full"
/>
<LoupeOutline root={props.root} outline={outline} />
</div>
</div>
</div>
)
}
function LoupeOutline({
root,
outline,
}: {
root: RootAttributes
outline: Geometry | null
}) {
const frame = parseFrame(root.viewBox)
if (!outline || !root.viewBox) return null
const size = frame ? Math.max(frame.w, frame.h) / 200 : 1
return (
<svg
viewBox={root.viewBox}
preserveAspectRatio={root.ratio}
className="absolute inset-0 h-full w-full"
>
<Outline geometry={outline} dashed={false} colour="var(--color-accent)" />
<Vertices geometry={outline} size={size} />
</svg>
)
}
@@ -135,6 +135,49 @@ function dragActions(
return { start, follow, drop, cancel }
}
type Actions = ReturnType<typeof dragActions>
/**
* The client point of a finger's drag, for the loupe (board 13): set when the drag really
* starts, followed, cleared by the drop and by every cancel. A mouse or pen sets nothing.
*/
function useFinger(drag: RefObject<Drag | null>, actions: Actions) {
const [finger, setFinger] = useState<XY | null>(null)
const touch = useRef(false)
// A mouse drag never set a finger: no state update (and no render) at its end.
const end = () => {
if (!touch.current) return
touch.current = false
setFinger(null)
}
return {
finger,
start: (
pressedAt: XY,
client: XY,
mode: boolean,
vertex: number | null,
byFinger: boolean,
) => {
actions.start(pressedAt, client, mode, vertex)
touch.current = byFinger && drag.current !== null
if (touch.current) setFinger(client)
},
follow: (client: XY) => {
actions.follow(client)
if (touch.current && drag.current) setFinger(client)
},
drop: (client: XY) => {
end()
actions.drop(client)
},
cancel: () => {
end()
actions.cancel()
},
}
}
/**
* The selection moved as a block (`drag_shape`, `drag_point`) or one of its vertices
* (`drag_vertex`): the overlay previews the outline, kept local to the canvas for speed;
@@ -144,7 +187,7 @@ function dragActions(
export function useBlockDrag(input: BlockDragInput) {
const drag = useRef<Drag | null>(null)
const [preview, setPreview] = useState<Geometry | null>(null)
const actions = dragActions(input, drag, setPreview)
const actions = useFinger(drag, dragActions(input, drag, setPreview))
useDropOnChange(input.target, actions.cancel)
return { preview, ...actions }
}
@@ -1,7 +1,15 @@
import type { CSSProperties, KeyboardEvent, PointerEvent } from 'react'
import {
useEffect,
useRef,
type CSSProperties,
type KeyboardEvent,
type PointerEvent,
} from 'react'
import type { Framing as Frame } from '@/catalogue/framing'
import { useFraming } from '@/catalogue/useFraming'
import type { ToolId } from './uiState'
import { usePressGesture, type PressInput } from './usePressGesture'
import { markTwoFingers } from './workStore'
export interface GestureInput extends PressInput {
viewId: string
@@ -50,6 +58,24 @@ function touchStyle(
return { touchAction: none ? 'none' : 'pan-x pan-y' }
}
const sameFrame = (a: Frame, b: Frame) =>
a.scale === b.scale && a.x === b.x && a.y === b.y
/**
* R-1: a framing that changed while two pointers or more were down is a two-finger pan or
* zoom that worked; the editor visit then never shows the two-finger hint again.
*/
function useTwoFingersWorked(framing: Frame, multi: () => boolean): void {
const last = useRef(framing)
const isMulti = useRef(multi)
isMulti.current = multi
useEffect(() => {
const changed = !sameFrame(last.current, framing)
last.current = framing
if (changed && isMulti.current()) markTwoFingers()
}, [framing])
}
/**
* Everything the canvas box listens to: zoom and pan, the press machine (click, drag,
* tap), and the keys. Keys only count when the box itself is the target: Enter on
@@ -62,7 +88,9 @@ export function useCanvasGestures(input: GestureInput) {
// The press machine decides: the drawing pans only while the press is a pan, so one
// press is either a pan or a click, never both (R-8).
panning: () => input.tool === 'select' && press.panning(),
twoPointerPan: true,
})
useTwoFingersWorked(framing.framing, press.multi)
const onKeyDown = (event: KeyboardEvent) => {
if (event.target !== event.currentTarget) return
framing.handlers.onKeyDown(event)
@@ -71,6 +99,7 @@ export function useCanvasGestures(input: GestureInput) {
return {
framing,
drag: press.preview,
finger: press.finger,
boxProps: {
...composedPointer(framing, press),
onKeyDown,
@@ -40,6 +40,8 @@ export interface PressInput extends BlockDragInput {
onHandle: (action: HandleAction) => void
/** A tap on the empty drawing with the select tool. */
onDeselect: () => void
/** A one-finger drag that moved nothing ended (R-1: the two-finger hint). */
onFutileDrag: () => void
}
const clientOf = (event: { clientX: number; clientY: number }): XY => ({
@@ -206,7 +208,9 @@ function applyEffect(f: Feed, effect: PressEffect, event: PointerEvent | null) {
const { action } = effect
const vertex = action.type === 'drag_vertex' ? action.index : null
const mode = action.type === 'drag_mode'
f.drag.start(f.machine.current.pressedAt, clientOf(event), mode, vertex)
const finger = pointerKindOf(event.pointerType) === 'touch'
const { pressedAt } = f.machine.current
f.drag.start(pressedAt, clientOf(event), mode, vertex, finger)
}
}
@@ -222,13 +226,19 @@ const contextOf = (input: PressInput) => ({
moveMode: inMoveMode(),
})
/** A drag that ends having moved nothing (`none` with `futile`): a finger off the handles. */
const isFutile = (press: Press) =>
press.phase === 'drag' && press.action.type === 'none' && press.action.futile
/** One event through the machine and its effect; at idle the press is over. */
function feed(f: Feed, event: PressEvent, pointer: PointerEvent | null) {
const m = f.machine.current
const context = contextOf(f.input)
const step = stepPress(m.press, event, context)
const futile = step.effect?.type === 'drag_end' && isFutile(m.press)
m.press = step.press
applyEffect(f, step.effect, pointer)
if (futile) f.input.onFutileDrag()
if (m.press.phase !== 'idle') return
m.pointers.clear()
m.stop?.()
@@ -358,6 +368,9 @@ export function usePressGesture(input: PressInput) {
const cancel = () => feed(latest.current, { type: 'cancel' }, null)
return {
preview: drag.preview,
finger: drag.finger,
/** Two pointers or more are down: a pan or zoom of the fingers, never a click. */
multi: () => machine.current.press.phase === 'multi',
panning: () => {
const press = machine.current.press
return press.phase === 'drag' && press.action.type === 'pan'
@@ -74,6 +74,8 @@ interface Work {
*/
dropped: ModeWork['kind'] | 'creation' | null
question: DrawingQuestion | null
/** A two-finger pan or zoom worked in this editor visit: the hint never shows again (R-1). */
twoFingers: boolean
}
const NO_WORK: Work = {
creation: null,
@@ -84,6 +86,7 @@ const NO_WORK: Work = {
chosen: null,
dropped: null,
question: null,
twoFingers: false,
}
export const useAnnotationWork = create<Work>(() => NO_WORK)
@@ -172,6 +175,12 @@ export function dropStale(text: string): void {
})
}
export function markTwoFingers(): void {
if (!useAnnotationWork.getState().twoFingers) {
useAnnotationWork.setState({ twoFingers: true })
}
}
/** Another sheet opened, or the editor closed: nothing of the previous one survives. */
export function resetWork(): void {
useAnnotationWork.setState(NO_WORK)
+2
View File
@@ -1852,6 +1852,8 @@ export const en: Dict = {
'editor.annotations.move.vertex': 'Move vertex',
'editor.annotations.redraw': 'Redraw',
'editor.annotations.message.vertex_moved': 'Vertex moved',
'editor.annotations.message.two_fingers':
'Use two fingers to move or zoom the drawing',
'editor.annotations.message.vertex_added': 'Vertex added',
'editor.annotations.message.vertex_removed': 'Vertex removed',
'editor.annotations.message.vertex_min': 'A zone keeps at least 3 vertices',
+2
View File
@@ -1921,6 +1921,8 @@ export const fr: Dict = {
'editor.annotations.move.vertex': 'Déplacer le sommet',
'editor.annotations.redraw': 'Redessiner',
'editor.annotations.message.vertex_moved': 'Sommet déplacé',
'editor.annotations.message.two_fingers':
'Deux doigts pour déplacer ou zoomer le dessin',
'editor.annotations.message.vertex_added': 'Sommet ajouté',
'editor.annotations.message.vertex_removed': 'Sommet retiré',
'editor.annotations.message.vertex_min': 'Une zone garde au moins 3 sommets',
@@ -0,0 +1,70 @@
/** U2 Task 8: the two-finger pan of the editor (`twoPointerPan`); the catalogue keeps its pinch. */
import { describe, expect, it } from 'vitest'
import { act, renderHook } from '@testing-library/react'
import type { PointerEvent } from 'react'
import { useFraming, type FramingOptions } from '@/catalogue/useFraming'
const BOX = { left: 0, top: 0, width: 400, height: 300 }
function viewport() {
const element = document.createElement('div')
element.getBoundingClientRect = () =>
({ ...BOX, right: BOX.width, bottom: BOX.height, x: 0, y: 0 }) as DOMRect
return { current: element }
}
const pointer = (pointerId: number, x: number, y: number) =>
({
pointerId,
clientX: x,
clientY: y,
currentTarget: { setPointerCapture: () => {} },
}) as unknown as PointerEvent
function mount(options?: FramingOptions) {
return renderHook(() => useFraming(viewport(), 'view', options)).result
}
type Hook = ReturnType<typeof mount>
/** Two fingers at (100, 100) and (200, 100), the trailing one moved first, both by `dx`. */
function moveTogether(result: Hook, dx: number) {
const { handlers } = result.current
act(() => {
handlers.onPointerDown(pointer(1, 100, 100))
handlers.onPointerDown(pointer(2, 200, 100))
})
act(() => result.current.handlers.onPointerMove(pointer(1, 100 + dx, 100)))
act(() => result.current.handlers.onPointerMove(pointer(2, 200 + dx, 100)))
}
describe('useFraming with twoPointerPan (U2 Task 8)', () => {
it('two pointers moving together translate by their movement without scaling', () => {
const result = mount({ twoPointerPan: true })
act(() => result.current.zoomIn())
const before = result.current.framing
expect(before.scale).toBe(1.5)
moveTogether(result, 20)
const after = result.current.framing
expect(after.scale).toBeCloseTo(1.5, 9)
expect(after.x - before.x).toBeCloseTo(20, 9)
expect(after.y).toBeCloseTo(before.y, 9)
})
it('at the fit, a pan that first narrows the fingers zooms nothing (no clamp ratchet)', () => {
const result = mount({ twoPointerPan: true })
moveTogether(result, 20)
expect(result.current.framing).toEqual({ scale: 1, x: 0, y: 0 })
})
it('still zooms when the fingers spread', () => {
const result = mount({ twoPointerPan: true })
const { handlers } = result.current
act(() => {
handlers.onPointerDown(pointer(1, 150, 150))
handlers.onPointerDown(pointer(2, 250, 150))
})
act(() => result.current.handlers.onPointerMove(pointer(2, 300, 150)))
expect(result.current.framing.scale).toBeCloseTo(1.5, 9)
})
})
+222
View File
@@ -0,0 +1,222 @@
/** U2 Task 8: the two-finger hint (R-1) and the loupe of a finger's drag. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
cleanup,
fireEvent,
render,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Annotation, Point } from '@faunosteo/core-wasm/types'
import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab'
import { resetWork } from '@/editor/annotations/workStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import { drawnText, insert, point } from '../helpers/editorFixtures'
import { openReady, resetStore } from '../helpers/editorHarness'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
getSheetVersion: vi.fn(),
downloadSheetDrawing: vi.fn(),
saveSheetDraft: vi.fn(),
getOfficialSheetAdmin: vi.fn(),
submitSheetReview: vi.fn(),
}))
const props = {
readOnly: false,
navigate: vi.fn(),
reloadSheet: vi.fn(),
section: 'drawing' as const,
visited: ['drawing'] as const,
onOpenSection: vi.fn(),
onBack: vi.fn(),
}
const HINT = fr['editor.annotations.message.two_fingers']
function stubCtm(): void {
const identity = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }
Object.defineProperty(window.SVGElement.prototype, 'getScreenCTM', {
configurable: true,
value: () => ({ ...identity, inverse: () => identity }),
})
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
stubCtm()
})
afterEach(() => {
cleanup()
resetStore()
resetWork()
})
const SQUARE: Point[] = [
[20, 20],
[80, 20],
[80, 80],
[20, 80],
]
const squareText = () =>
insert(drawnText(), {
kind: 'annotation',
value: {
...(point('z', 0, 0, 1).value as Annotation),
kind: 'zone',
geometry: { type: 'polygon', points: SQUARE },
} as Annotation,
})
const tab = () => (
<div data-editor-workspace>
<AnnotationsTab {...props} />
</div>
)
async function show() {
render(tab())
await waitFor(() =>
expect(
screen.getByTestId('annotation-canvas-drawing').querySelector('svg'),
).not.toBeNull(),
)
}
async function mount() {
await openReady({ text: squareText() })
await show()
}
async function select() {
const list = await screen.findByRole('list', {
name: 'Annotations de la vue',
})
await userEvent.setup().click(within(list).getAllByRole('button')[0])
await screen.findByRole('button', { name: 'Propriétés' })
}
const canvas = () => screen.getByTestId('annotation-canvas')
const line = () => screen.getByTestId('gesture-line')
const loupe = () => screen.queryByTestId('loupe')
const hitOf = (name: string) =>
screen.getByRole('button', { name }).querySelector('[data-handle]')!
const finger = (
pointerId: number,
x: number,
y: number,
pointerType = 'touch',
) => ({
pointerId,
isPrimary: pointerId === 1,
button: 0,
buttons: 1,
pointerType,
clientX: x,
clientY: y,
})
/** One pointer pressed at `from`, moved to `to` (past every slop), released there. */
function drag(el: Element, from: Point, to: Point, pointerType = 'touch') {
fireEvent.pointerDown(el, finger(1, from[0], from[1], pointerType))
fireEvent.pointerMove(el, finger(1, to[0], to[1], pointerType))
fireEvent.pointerUp(el, {
...finger(1, to[0], to[1], pointerType),
buttons: 0,
})
}
/** Two fingers on the box, the second one spread: the drawing zooms. */
function pinch() {
fireEvent.pointerDown(canvas(), finger(1, 10, 10))
fireEvent.pointerDown(canvas(), finger(2, 60, 10))
fireEvent.pointerMove(canvas(), finger(2, 110, 10))
fireEvent.pointerUp(canvas(), { ...finger(2, 110, 10), buttons: 0 })
fireEvent.pointerUp(canvas(), { ...finger(1, 10, 10), buttons: 0 })
}
describe('the two-finger hint (R-1)', () => {
it('a finger dragged off the handles moves nothing and shows the hint', async () => {
await mount()
await select()
drag(canvas(), [5, 5], [45, 5])
expect(line()).toHaveTextContent(HINT)
})
it('a mouse drag pans: no hint', async () => {
await mount()
await select()
drag(canvas(), [5, 5], [45, 5], 'mouse')
expect(line()).not.toHaveTextContent(HINT)
})
it('never replaces a message that shows', async () => {
await mount()
await select()
drag(hitOf('Sommet 2'), [80, 20], [90, 10], 'mouse')
expect(line()).toHaveTextContent('Sommet déplacé')
drag(canvas(), [5, 5], [45, 5])
expect(line()).toHaveTextContent('Sommet déplacé')
expect(line()).not.toHaveTextContent(HINT)
})
it('never shows again once two fingers worked, even after a remount', async () => {
await mount()
await select()
pinch()
drag(canvas(), [5, 5], [45, 5])
expect(line()).not.toHaveTextContent(HINT)
cleanup()
await show()
await select()
drag(canvas(), [5, 5], [45, 5])
expect(line()).not.toHaveTextContent(HINT)
})
})
describe('the loupe of a finger drag', () => {
it('shows a picture of the drawing above the finger, then goes on the drop', async () => {
await mount()
await select()
const vertex = hitOf('Sommet 2')
fireEvent.pointerDown(vertex, finger(1, 80, 20))
fireEvent.pointerMove(vertex, finger(1, 95, 35))
const shown = loupe()!
expect(shown).not.toBeNull()
expect(shown).toHaveAttribute('aria-hidden', 'true')
expect(shown.hasAttribute('inert')).toBe(true)
expect(shown.querySelector('svg')).not.toBeNull()
expect(shown.querySelector('[data-anno-id]')).toBeNull()
expect(shown.querySelector('polygon')).not.toBeNull()
fireEvent.pointerUp(vertex, { ...finger(1, 95, 35), buttons: 0 })
expect(loupe()).toBeNull()
})
it('goes when the drag is cancelled by a second finger', async () => {
await mount()
await select()
const vertex = hitOf('Sommet 2')
fireEvent.pointerDown(vertex, finger(1, 80, 20))
fireEvent.pointerMove(vertex, finger(1, 95, 35))
expect(loupe()).not.toBeNull()
fireEvent.pointerDown(canvas(), finger(2, 10, 10))
expect(loupe()).toBeNull()
})
it('a mouse drag shows none', async () => {
await mount()
await select()
const vertex = hitOf('Sommet 2')
fireEvent.pointerDown(vertex, finger(1, 80, 20, 'mouse'))
fireEvent.pointerMove(vertex, finger(1, 95, 35, 'mouse'))
expect(loupe()).toBeNull()
fireEvent.pointerUp(vertex, { ...finger(1, 95, 35, 'mouse'), buttons: 0 })
})
})