feat(editor): vertex handles, insert and remove, zone move, redraw

U2 Task 5. A selected polygon gets its vertex, « + » and « − » handles
(R-9, hidden « + » under two hit radii, R-18 zoom hint in the strip),
the handle cap at 40 (R-7), vertex drag and keys, the move mode on the
zone or the chosen vertex, « Redessiner » as a redraw mode kept in step
with its tracing (R-12 guard, R-13 drop), close radius in CSS px
(R-11). The numeric group leaves the properties panel (D1).

Removed or rewritten assertions (numeric group -> replacement):
- tab « shows its exact stored numbers » (Centre x field) -> the overlay
  selection circle's cx attribute, same exact value.
- tab « a numeric edit » x3 -> « an edit on the drawing »: Enter on the
  handle without a step commits nothing, a step + Enter commits once;
  a refused handle drag keeps the stored shape then a drag inside the
  frame repairs it (issues gone); Escape drops a pending series.
- tab C26 « Centre x 15 » -> overlay cx 15.
- tab C32 unmeasured « Centre x as text » -> no handle, no field.
- tab « adds and removes a vertex as part of the whole group » -> « + »
  then « − » on the drawing; « never offers to remove below three » ->
  « − » aria-disabled at 3.
- tab H8 « refused Remplacer drops the tracing » -> keeps it open with
  « Fermeture refusée » (board 33 A); « refused vertex add/remove stay
  non appliqué » -> a refused vertex drag restores the shape exactly.
- tab Désélectionner and D6b (typed Centre x committed, refused, undone)
  x6 and strip « a new commit replaces the message » -> the same with
  the Nom (FR) field (a blank name is the refused value).
- focus-request « Centre x 20 » -> overlay cx 20.
- escape « strip commands keep their Escape » -> a redraw: Escape on the
  strip or the box cancels it (R-12 row 4); kept for a new zone tracing.
- keep-alive « Remplacer tracing kept across Aller à » -> ended by a tab
  when empty, asked once a vertex is placed (R-12).
- e2e annotations: numeric cx edit + undo/redo -> handle keys + undo/
  redo; jitter/drag and Task 4 point reads -> overlay attributes (the
  stored place during the mode -> overlay-old-place); keyboard-only cy
  and vertex x typed -> handle and vertex keys.
- e2e deselect: Centre x typed/refused/committed -> Nom (FR).
- e2e geometry, shell-crossing: Centre x/cy reads -> overlay attributes.
- e2e journey: cx +3 and vertex x +4 typed -> 3 and 4 arrow steps + Enter;
  a far typed value + revert -> a far handle drag refused.
- e2e equine latency: typed cx rounds -> handle arrow + Enter rounds.
This commit is contained in:
bchanot committed 2026-11-17 20:24:49 +01:00
1 parent ba8e766fe8
commit 6211046537
44 files changed
+3790 -1050

No files matched your search

+57 -44
View File
@@ -6,8 +6,12 @@ import {
clickDrawing,
clientOf,
editorActor,
geometryField,
historyButton,
round2,
shownNumber,
shownPoints,
shownShape,
storedShape,
pressAtBox,
openEditor,
pickAnnotation,
@@ -25,7 +29,7 @@ import {
import { expectNoShift, keepNativeFrames } from '../support/layout'
// V1-2.6 A3 (contract C7, C8, C21): points, zones and links by clicks and by keyboard,
// move by drag, numeric edits, undo and redo, then the save that carries them.
// move by drag, edits on the handles (U2 Task 5), undo and redo, then the save.
const dict = fr
@@ -84,7 +88,7 @@ test.describe('editor annotations (A3)', () => {
await dropLateReplays(context)
})
test('point, zone and link by clicks; numeric edit; undo and redo; save', async ({
test('point, zone and link by clicks; handle edit; undo and redo; save', async ({
page,
requests,
}) => {
@@ -103,8 +107,8 @@ test.describe('editor annotations (A3)', () => {
await createFromPanel(page)
await expect(selectionTag(page)).toContainText('Point un')
await expect(properties(page)).toBeVisible()
const placed = await geometryField(page, dict, 'cx').inputValue()
expect(Math.abs(Number(placed) - 300)).toBeLessThan(1)
const placed = await shownNumber(page, 'cx')
expect(Math.abs(placed - 300)).toBeLessThan(1)
// A zone: three clicks, then « Fermer le tracé ».
await tool(page, 'zone').click()
@@ -137,19 +141,22 @@ test.describe('editor annotations (A3)', () => {
await expect(selectionTag(page)).toContainText('Accès un')
await expect(historyButton(page, dict, 'undo')).toBeEnabled()
// A numeric edit of the point, then undo and redo.
// A keyboard edit on the point's handle (two steps of 5 units), then undo and redo.
await tool(page, 'select').click()
await pickAnnotation(page, dict, /Point un/)
const cx = geometryField(page, dict, 'cx')
await cx.fill('420')
await cx.press('Enter')
await expect(cx).toHaveValue('420')
await page.getByRole('button', { name: 'Point Point un' }).focus()
await page.keyboard.press('ArrowRight')
await page.keyboard.press('ArrowRight')
await page.keyboard.press('Enter')
const moved = String(round2(round2(placed + 5) + 5))
await expect(shownShape(page)).toHaveAttribute('cx', moved)
await historyButton(page, dict, 'undo').click()
await expect(geometryField(page, dict, 'cx')).toHaveValue(placed)
await expect(shownShape(page)).toHaveAttribute('cx', String(placed))
await historyButton(page, dict, 'redo').click()
await expect(geometryField(page, dict, 'cx')).toHaveValue('420')
await expect(shownShape(page)).toHaveAttribute('cx', moved)
// Nothing left to redo: the button is aria-disabled and a press changes nothing.
await pressAtBox(page, historyButton(page, dict, 'redo'))
await expect(geometryField(page, dict, 'cx')).toHaveValue('420')
await expect(shownShape(page)).toHaveAttribute('cx', moved)
await saveDraft(page, dict, seed.revision + 1)
const saved = await serverDocument<{
@@ -176,9 +183,8 @@ test.describe('editor annotations (A3)', () => {
await fillCreation(page, { fr: 'Mobile', en: 'Movable' })
await createFromPanel(page)
await tool(page, 'select').click()
const cx = geometryField(page, dict, 'cx')
const cy = geometryField(page, dict, 'cy')
const [x0, y0] = [await cx.inputValue(), await cy.inputValue()]
const x0 = String(await shownNumber(page, 'cx'))
const y0 = String(await shownNumber(page, 'cy'))
expect(Math.abs(Number(x0) - 300)).toBeLessThan(1)
// Jitter under the 4 px threshold: pressed, moved by 3 px, released.
@@ -187,8 +193,8 @@ test.describe('editor annotations (A3)', () => {
await page.mouse.down()
await page.mouse.move(from.x + 2, from.y + 2)
await page.mouse.up()
await expect(cx).toHaveValue(x0)
await expect(cy).toHaveValue(y0)
await expect(shownShape(page)).toHaveAttribute('cx', x0)
await expect(shownShape(page)).toHaveAttribute('cy', y0)
// A real drag: the point follows to (400, 360) in drawing units.
const to = await clientOf(page, 400, 360)
@@ -199,14 +205,14 @@ test.describe('editor annotations (A3)', () => {
})
await page.mouse.move(to.x, to.y, { steps: 5 })
await page.mouse.up()
await expect(cx).not.toHaveValue(x0)
expect(Math.abs(Number(await cx.inputValue()) - 400)).toBeLessThan(2)
expect(Math.abs(Number(await cy.inputValue()) - 360)).toBeLessThan(2)
await expect(shownShape(page)).not.toHaveAttribute('cx', x0)
expect(Math.abs((await shownNumber(page, 'cx')) - 400)).toBeLessThan(2)
expect(Math.abs((await shownNumber(page, 'cy')) - 360)).toBeLessThan(2)
await page.keyboard.press('Control+z')
await expect(geometryField(page, dict, 'cx')).toHaveValue(x0)
await expect(shownShape(page)).toHaveAttribute('cx', x0)
})
test('keyboard only: creation by the add buttons, numeric position, numeric edit', async ({
test('keyboard only: creation by the add buttons, numeric position, edit by the handle keys', async ({
page,
requests,
}) => {
@@ -230,14 +236,20 @@ test.describe('editor annotations (A3)', () => {
await page.keyboard.press('Enter')
await expect(creation(page)).toHaveCount(0)
await expect(selectionTag(page)).toContainText('Clavier')
await expect(geometryField(page, dict, 'cx')).toHaveValue('250')
await expect(shownShape(page)).toHaveAttribute('cx', '250')
const cy = geometryField(page, dict, 'cy')
await cy.fill('510.5')
await cy.press('Enter')
await expect(cy).toHaveValue('510.5')
// The handle keys (U2 Task 5): two steps of 5 units down, one commit on Enter.
const cy0 = await shownNumber(page, 'cy')
await page.getByRole('button', { name: 'Point Clavier' }).focus()
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('Enter')
await expect(shownShape(page)).toHaveAttribute(
'cy',
String(round2(round2(cy0 + 5) + 5)),
)
// A polygon edit: the zone added by keyboard, a vertex typed.
// A polygon edit: the zone added by keyboard, its first vertex moved by its keys.
await page
.getByRole('button', { name: dict['editor.annotations.add.zone'] })
.focus()
@@ -248,13 +260,14 @@ test.describe('editor annotations (A3)', () => {
.focus()
await page.keyboard.press('Enter')
await expect(selectionTag(page)).toContainText('Zone clavier')
const vertexX = page.getByLabel(
dict['editor.annotations.geometry.vertex_x'].replace('{n}', '1'),
)
const before = Number(await vertexX.inputValue())
await vertexX.fill(String(before + 10))
await vertexX.press('Enter')
await expect(vertexX).toHaveValue(String(before + 10))
const [[before]] = await shownPoints(page)
await page.getByRole('button', { name: 'Sommet 1', exact: true }).focus()
await page.keyboard.press('ArrowRight')
await page.keyboard.press('ArrowRight')
await page.keyboard.press('Enter')
await expect
.poll(async () => (await shownPoints(page))[0][0])
.toBe(round2(round2(before + 5) + 5))
await saveDraft(page, dict, seed.revision + 1)
})
@@ -416,7 +429,6 @@ test.describe('editor annotations (A3)', () => {
await expectAccessible(page, 'a selected point: handle, slider, move')
// The handle follows the pointer; the drop is one commit.
const cx = geometryField(page, dict, 'cx')
await expectNoShift(
page,
async () => {
@@ -427,10 +439,9 @@ test.describe('editor annotations (A3)', () => {
},
swaps,
)
expect(Math.abs(Number(await cx.inputValue()) - 560)).toBeLessThan(2)
expect(Math.abs((await shownNumber(page, 'cx')) - 560)).toBeLessThan(2)
// A click on the track, no drag (WCAG 2.5.7): one commit at the release.
const r = geometryField(page, dict, 'r')
const track = (await slider.boundingBox())!
await expectNoShift(
page,
@@ -445,12 +456,12 @@ test.describe('editor annotations (A3)', () => {
},
swaps,
)
expect(Number(await r.inputValue())).toBeGreaterThan(40)
expect(await shownNumber(page, 'r')).toBeGreaterThan(40)
await page.keyboard.press('Control+z')
await expect(r).toHaveValue('40')
await expect(shownShape(page)).toHaveAttribute('r', '40')
// The move mode: three steps (5 units each on a 1 000 px wide frame), validated once.
const x0 = Number(await cx.inputValue())
const x0 = await shownNumber(page, 'cx')
await expectNoShift(
page,
() => button(page, 'editor.annotations.move.point').click(),
@@ -466,7 +477,8 @@ test.describe('editor annotations (A3)', () => {
},
swaps,
)
await expect(cx).toHaveValue(String(x0))
// Nothing committed yet: the stored place stays, drawn as the old place.
await expect(storedShape(page)).toHaveAttribute('cx', String(x0))
await expectNoShift(
page,
async () => {
@@ -475,7 +487,8 @@ test.describe('editor annotations (A3)', () => {
},
swaps,
)
await expect(cx).toHaveValue(String(x0 + 15))
await expect(shownShape(page)).toHaveAttribute('cx', String(x0 + 15))
await expect(storedShape(page)).toHaveCount(0)
await expect(button(page, 'editor.annotations.move.point')).toBeFocused()
})
+23 -13
View File
@@ -8,7 +8,6 @@ import {
clientOf,
creationPanel,
editorActor,
geometryField,
historyButton,
openEditor,
expectNoDialog,
@@ -39,6 +38,10 @@ import {
const dict = fr
const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
const properties = (page: Page) => page.getByTestId('annotation-properties')
const nameField = (page: Page) =>
properties(page).getByLabel(dict['editor.annotations.name_fr'], {
exact: true,
})
const overview = (page: Page) => page.getByTestId('annotation-overview')
const box = (page: Page) => page.getByTestId('annotation-canvas')
const liveRegion = (page: Page) =>
@@ -211,11 +214,11 @@ test.describe('deselect and D6b (editor, mouse and keyboard)', () => {
// A field focused: nothing happens, the field keeps the focus.
await select(page, POINT)
const cx = geometryField(page, dict, 'cx')
await cx.focus()
const name = nameField(page)
await name.focus()
await page.keyboard.press('Escape')
await expectKept(page, POINT)
await expect(cx).toBeFocused()
await expect(name).toBeFocused()
// The delete dialog: only it closes (LRN-111: wait until it is gone).
await properties(page)
@@ -389,12 +392,13 @@ test.describe('deselect and D6b (editor, mouse and keyboard)', () => {
}) => {
const { actor, saves } = await open(page)
requests.forbid(actor.account.email, actor.account.password)
const cx = geometryField(page, dict, 'cx')
// U2 Task 5: the coordinate fields left the panel; the name field carries the typing.
const name = nameField(page)
// Valid value, no blur, ONE click on the drawing.
await select(page, POINT)
await expect(cx).toHaveValue('700')
await cx.fill('720')
await expect(name).toHaveValue(POINT)
await name.fill('Pt Delta')
await clickAt(page, IN_CIRCLE)
await expectDeselected(page)
await expect(saveLine(page)).toHaveText(/1 modification non enregistrée/)
@@ -402,26 +406,27 @@ test.describe('deselect and D6b (editor, mouse and keyboard)', () => {
await historyButton(page, dict, 'undo').click()
await expect(saveLine(page)).not.toHaveText(UNSAVED_LINE)
await select(page, POINT)
await expect(cx).toHaveValue('700')
await expect(name).toHaveValue(POINT)
// « Désélectionner » with an unblurred refused value: closed at once, unchanged.
// A blank name is refused (both names are required).
const deselect = properties(page).getByRole('button', {
name: dict['editor.annotations.deselect'],
})
await cx.fill('abc')
await name.fill('')
await deselect.click()
await expectDeselected(page)
await expect(saveLine(page)).not.toHaveText(UNSAVED_LINE)
await select(page, POINT)
await expect(cx).toHaveValue('700')
await expect(name).toHaveValue(POINT)
// « Désélectionner » with an unblurred valid value: committed and closed.
await cx.fill('730')
await name.fill('Pt Epsilon')
await deselect.click()
await expectDeselected(page)
await expect(saveLine(page)).toHaveText(/1 modification non enregistrée/)
await select(page, POINT)
await expect(cx).toHaveValue('730')
await select(page, 'Pt Epsilon')
await expect(name).toHaveValue('Pt Epsilon')
expect(saves).toEqual([])
})
})
@@ -612,6 +617,11 @@ test.describe('deselect and D6b (touch, editor at 1 280 px)', () => {
// c. Within 36 px of the canvas bottom, above the add buttons.
await select(page, POINT)
await takeRecord(page)
// U2 Task 5: without the coordinate fields the properties panel is shorter than the
// overview, so with the page scrolled to its end the deselect's swap (aside content,
// until Task 6) grows the page and scrolls it before the tap's click lands. The tap
// is made from the top of the page; the hazard is reported for Task 6.
await page.evaluate(() => window.scrollTo(0, 0))
await box(page).scrollIntoViewIfNeeded()
const rect = (await box(page).boundingBox())!
const bottom = { x: rect.x + rect.width / 2, y: rect.y + rect.height - 36 }
+6 -9
View File
@@ -361,21 +361,18 @@ test.describe('equine working copy and commit latency', () => {
page,
'equine: add category (insert)',
)
// A geometry edit: the first annotation's centre, through the geometry group.
// A geometry edit: a point's centre, through its handle keys (U2 Task 5: the
// coordinate fields left the panel). Each round is one step and one commit (Enter).
await showDrawing(page, dict)
await page
.getByRole('list', { name: dict['editor.annotations.list'] })
.getByRole('button')
.first()
.getByRole('button', { name: /C7-T1/ })
.click()
const cx = page.getByLabel(dict['editor.annotations.geometry.cx'], {
exact: true,
})
const base = Number(await cx.inputValue())
await page.getByTestId('point-handle').focus()
await startProbe(page)
for (let round = 0; round <= SAMPLES; round++) {
await cx.fill(String(base + ((round % 2) + 1) * 0.5))
await cx.press('Enter')
await page.keyboard.press(round % 2 ? 'ArrowLeft' : 'ArrowRight')
await page.keyboard.press('Enter')
}
await page.waitForTimeout(200)
const moves = report(
+13 -10
View File
@@ -8,7 +8,8 @@ import {
clickDrawing,
clientOf,
editorActor,
geometryField,
shownNumber,
shownShape,
openEditor,
openSection,
pickAnnotation,
@@ -130,8 +131,8 @@ test.describe('editor geometry (adversarial)', () => {
.click()
await expect(creation(page)).toHaveCount(0)
await expect(selectionTag(page)).toContainText('Bord')
await expect(geometryField(page, dict, 'cx')).toHaveValue(shown.x)
await expect(geometryField(page, dict, 'cy')).toHaveValue(shown.y)
await expect(shownShape(page)).toHaveAttribute('cx', shown.x)
await expect(shownShape(page)).toHaveAttribute('cy', shown.y)
})
test('a click near the edge of a detail crop is corrected inside the crop', async ({
@@ -190,7 +191,6 @@ test.describe('editor geometry (adversarial)', () => {
(await verification.innerText()).replace(/\D/g, ''),
)
expect(errorsBefore).toBeGreaterThan(0)
const cx = geometryField(page, dict, 'cx')
const move = page.getByRole('button', {
name: dict['editor.annotations.move.point'],
})
@@ -201,6 +201,10 @@ test.describe('editor geometry (adversarial)', () => {
// A partial move (still out of the frame): refused by the core, the point restored.
// Nothing around the drawing moves (A14); the side panel's content may (Task 6).
const swaps = ['aside-content'] as const
// The list row scrolled the page to its end. Without the coordinate fields (U2 Task 5)
// the panel is short enough that the issue list leaving it (aside content, exempt until
// Task 6) would clamp that scroll: the check starts from the top.
await page.evaluate(() => window.scrollTo(0, 0))
await expectNoShift(page, () => move.click(), swaps)
await dragInMode(page, { x: 250, y: 250 }, { x: 260, y: 260 })
await expectNoShift(
@@ -215,7 +219,7 @@ test.describe('editor geometry (adversarial)', () => {
dict['editor.annotations.message.move_refused'].split(' :')[0],
)
await expect(page.getByTestId('overlay-refused-place')).toBeAttached()
await expect(cx).toHaveValue('110')
await expect(shownShape(page)).toHaveAttribute('cx', '110')
await expect(issues).toBeVisible()
// Far enough inside: kept, the issue gone, one error less.
@@ -229,7 +233,7 @@ test.describe('editor geometry (adversarial)', () => {
},
swaps,
)
expect(Math.abs(Number(await cx.inputValue()) - 150)).toBeLessThan(2)
expect(Math.abs((await shownNumber(page, 'cx')) - 150)).toBeLessThan(2)
const after = (await verification.innerText()).replace(/\D/g, '')
expect(Number(after || 0)).toBeLessThan(errorsBefore)
})
@@ -501,8 +505,7 @@ test.describe('editor touch path (real browser)', () => {
// touchstart, so a drag of the selected marker must not be left to the pan.
await pickAnnotation(page, dict, /Tactile/)
await expect.poll(touchAction).toBe('none')
const cx = geometryField(page, dict, 'cx')
await expect(cx).toHaveValue('500')
await expect(shownShape(page)).toHaveAttribute('cx', '500')
const from = await clientOf(page, 500, 400)
const to = await clientOf(page, 620, 400)
const cdp = await context.newCDPSession(page)
@@ -521,7 +524,7 @@ test.describe('editor touch path (real browser)', () => {
y: from.y,
})
await touch('touchEnd', null)
await expect(cx).not.toHaveValue('500')
expect(Math.abs(Number(await cx.inputValue()) - 620)).toBeLessThan(3)
await expect(shownShape(page)).not.toHaveAttribute('cx', '500')
expect(Math.abs((await shownNumber(page, 'cx')) - 620)).toBeLessThan(3)
})
})
+59 -24
View File
@@ -6,12 +6,16 @@ import { expect, expectAccessible, test } from '../support/browser'
import { dropLateReplays, routeToSandbox } from '../support/sandbox'
import {
clickDrawing,
clientOf,
closeFinding,
createFromPanel,
creationPanel,
editorActor,
fillCreation,
geometryField,
round2,
shownNumber,
shownPoints,
shownShape,
historyButton,
INKSCAPE_EXPORT,
openDraft,
@@ -185,28 +189,52 @@ async function createAnnotations(page: Page) {
const MODIFIED = { point: 3, vertex: 4 }
/** Applies (not only refuses) changes to a point, a zone and a link; read back at the save. */
/**
* `steps` arrow presses on the focused handle (one unit each on this 200-unit drawing,
* R-11), then Enter: one commit. Returns where `from` lands, rounded as the page does.
*/
async function stepRight(
page: Page,
handle: Locator,
from: number,
steps: number,
) {
await handle.focus()
let to = from
for (let step = 0; step < steps; step++) {
await page.keyboard.press('ArrowRight')
to = round2(to + 1)
}
await page.keyboard.press('Enter')
return to
}
/**
* Applies (not only refuses) changes to a point, a zone and a link; read back at the save.
* U2 Task 5: the point and the vertex move by their handle keys (no coordinate field).
*/
async function modifyAnnotations(page: Page) {
await pickAnnotation(page, dict, /Point essai/)
const cx = geometryField(page, dict, 'cx')
const before = Number(await cx.inputValue())
await commitText(cx, String(before + MODIFIED.point))
await expect(cx).toHaveValue(String(before + MODIFIED.point))
const before = await shownNumber(page, 'cx')
const handle = page.getByTestId('point-handle')
const point = await stepRight(page, handle, before, MODIFIED.point)
await expect(shownShape(page)).toHaveAttribute('cx', String(point))
await pickAnnotation(page, dict, /Zone dessinée/)
const vertex = page.getByLabel(
dict['editor.annotations.geometry.vertex_x'].replace('{n}', '1'),
)
const start = Number(await vertex.inputValue())
await commitText(vertex, String(start + MODIFIED.vertex))
await expect(vertex).toHaveValue(String(start + MODIFIED.vertex))
const [[start]] = await shownPoints(page)
const first = page.getByRole('button', { name: 'Sommet 1', exact: true })
const vertex = await stepRight(page, first, start, MODIFIED.vertex)
await expect.poll(async () => (await shownPoints(page))[0][0]).toBe(vertex)
await pickAnnotation(page, dict, /Accès essai/)
await commitText(page.locator('#annotation-name-fr'), 'Accès modifié')
await page.locator('#annotation-laterality').selectOption('bilateral')
await expect(page.locator('#annotation-name-fr')).toHaveValue('Accès modifié')
return { point: before + MODIFIED.point, vertex: start + MODIFIED.vertex }
return { point, vertex }
}
/** Guide 4.4: a click near the edge proposes a position; a far value is refused. */
/**
* Guide 4.4: a click near the edge proposes a position; a far place is refused (U2 Task
* 5: dragged by the handle, the coordinate fields left the panel).
*/
async function repairGeometry(page: Page) {
await toolButton(page, dict, 'point').click()
// On this 200 x 150 drawing the core keeps a shrunk marker at 1 unit from the edge: the
@@ -216,16 +244,20 @@ async function repairGeometry(page: Page) {
await fillCreation(page, dict, { fr: 'Point de bord', en: 'Edge point' })
await createFromPanel(page, dict)
await expect(selectionTag(page)).toContainText('Point de bord')
const cx = geometryField(page, dict, 'cx')
await cx.fill('9999')
await cx.press('Enter')
await expect(
page.getByText(dict['editor.annotations.geometry.unapplied']),
).toBeVisible()
await clickButton(page, dict['editor.annotations.geometry.revert'])
await expect(
page.getByText(dict['editor.annotations.geometry.unapplied']),
).toHaveCount(0)
// The point tool stays on after « Créer » (A7 lands with Task 7): the handle needs select.
await toolButton(page, dict, 'select').click()
const cx = String(await shownNumber(page, 'cx'))
const cy = await shownNumber(page, 'cy')
const from = await clientOf(page, Number(cx), cy)
const to = await clientOf(page, 260, cy)
await page.mouse.move(from.x, from.y)
await page.mouse.down()
await page.mouse.move(to.x, to.y, { steps: 6 })
await page.mouse.up()
await expect(page.getByTestId('gesture-message')).toContainText(
dict['editor.annotations.message.move_refused'].split(' :')[0],
)
await expect(shownShape(page)).toHaveAttribute('cx', cx)
}
/** Guide 4.5: an unsaved change, a reload (beforeunload accepted), the offer, a restore. */
@@ -284,6 +316,9 @@ test.describe('editor journey (owner trial steps)', () => {
await historyButton(page, dict, 'undo').click()
await historyButton(page, dict, 'redo').click()
const modified = await modifyAnnotations(page)
// The last list row scrolled the page: the shell's top bar would cover « Enregistrer »
// (axe target-size); the shorter panel of U2 Task 5 made that scroll reach it.
await page.evaluate(() => window.scrollTo(0, 0))
await expectAccessible(page, 'the editor with annotations')
await saveDraft(page, dict, 1)
const draftId = await sql(
@@ -9,7 +9,8 @@ import {
copyKeyOf,
editorActor,
expectNoDialog,
geometryField,
shownNumber,
shownShape,
historyButton,
openEditor,
openCitations,
@@ -362,8 +363,7 @@ test.describe('editor shell, width crossing (H)', () => {
)
await selectTab(page, dict, 'annotations')
await pickAnnotation(page, dict, 'Point libre')
const cx = geometryField(page, dict, 'cx')
const before = await cx.inputValue()
const before = String(await shownNumber(page, 'cx'))
const from = await clientOf(page, 120, 120)
const to = await clientOf(page, 200, 160)
await page.mouse.move(from.x, from.y)
@@ -372,7 +372,7 @@ test.describe('editor shell, width crossing (H)', () => {
await cross(page, NARROW)
await page.mouse.up()
await cross(page, WIDE)
await expect(geometryField(page, dict, 'cx')).toHaveValue(before)
await expect(shownShape(page)).toHaveAttribute('cx', before)
await expect(saveLine(page)).not.toHaveText(UNSAVED_LINE)
await expect(historyButton(page, dict, 'undo')).toHaveAttribute(
'aria-disabled',
+292
View File
@@ -0,0 +1,292 @@
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'
import { dropLateReplays, routeToSandbox } from '../support/sandbox'
import {
clientOf,
editorActor,
openEditor,
pickAnnotation,
seedDraft,
selectionTag,
shownPoints,
toolButton,
} from '../support/editor'
import { expectNoShift } from '../support/layout'
// V1-2.6 U2 Task 5: a zone edited on the drawing, « Vertèbres thoraciques » of the equine
// draft on its own drawing: vertex drag, « + », « − », zone drag, redraw accepted and
// refused, each undone, nothing around the drawing moving (A14); the topmost rule.
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).
const SWAPS = ['aside-content'] as const
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'),
shape: equineShape,
})
await openEditor(page, dict, actor, seed.sheetId)
await expect(toolButton(page, dict, 'point')).toBeEnabled()
return actor
}
const handle = (page: Page, name: string) =>
page.getByRole('button', { name, exact: true })
const line = (page: Page) => page.getByTestId('gesture-line')
const button = (page: Page, key: string) =>
page.getByRole('button', { name: dict[key], exact: true })
const undo = (page: Page) => page.keyboard.press('Control+z')
/** A press and release at the centre of a handle's hit shape. */
async function pressHandle(page: Page, name: string) {
const box = (await handle(page, name).locator('[data-handle]').boundingBox())!
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2)
}
/** A mouse drag between two drawing points, past the slop. */
async function dragDrawing(
page: Page,
from: { x: number; y: number },
to: { x: number; y: number },
) {
const start = await clientOf(page, from.x, from.y)
const end = await clientOf(page, to.x, to.y)
await page.mouse.move(start.x, start.y)
await page.mouse.down()
await page.mouse.move(end.x, end.y, { steps: 6 })
await page.mouse.up()
}
async function clickAt(page: Page, x: number, y: number) {
const at = await clientOf(page, x, y)
await page.mouse.click(at.x, at.y)
}
const count = async (page: Page) => (await shownPoints(page)).length
test.describe('editor zones on the drawing (U2 Task 5)', () => {
test.use({ locale: 'fr-FR', actionTimeout: 15_000 })
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('Thoraciques: vertex drag, « + », « − », zone drag, each undone', async ({
page,
requests,
}) => {
const actor = await openThoracic(page)
requests.forbid(actor.account.email, actor.account.password)
await pickAnnotation(page, dict, THORACIC)
await expect(selectionTag(page)).toContainText('Vertèbres thoraciques')
await expect(handle(page, 'Sommet 9')).toBeAttached()
// R-18: at fit zoom some segments are too short for their « + ».
await expect(page.getByTestId('edit-strip-notice')).toContainText(
dict['editor.annotations.strip.zoom_hint'],
)
// The list row scrolled the page: the shell's top bar would cover the header's buttons.
await page.evaluate(() => window.scrollTo(0, 0))
await expectAccessible(page, 'a selected zone: vertices and « + »')
const stored = await shownPoints(page)
// A vertex dragged: one commit, the vertex chosen, then undone.
await expectNoShift(
page,
async () => {
await dragDrawing(page, { x: 1103, y: 558.9 }, { x: 1103, y: 620 })
await expect(line(page)).toContainText(
dict['editor.annotations.message.vertex_moved'],
)
},
SWAPS,
)
const [, moved] = await shownPoints(page)
expect(Math.abs(moved[1] - 620)).toBeLessThan(3)
await undo(page)
await expect.poll(() => shownPoints(page)).toEqual(stored)
// « + » on the segment from vertex 2: a vertex added and chosen, then undone.
await expectNoShift(
page,
async () => {
await pressHandle(page, 'Ajouter un sommet après le sommet 2')
await expect(line(page)).toContainText(
dict['editor.annotations.message.vertex_added'],
)
},
SWAPS,
)
expect(await count(page)).toBe(10)
await expect(page.getByTestId('edit-strip-detail')).toContainText(
'sommet 3 choisi',
)
await undo(page)
await expect.poll(() => count(page)).toBe(9)
// « − » on the chosen vertex 3, then undone.
await pressHandle(page, 'Sommet 3')
await expectNoShift(
page,
async () => {
await pressHandle(page, 'Retirer le sommet 3')
await expect(line(page)).toContainText(
dict['editor.annotations.message.vertex_removed'],
)
},
SWAPS,
)
expect(await count(page)).toBe(8)
await undo(page)
await expect.poll(() => shownPoints(page)).toEqual(stored)
// The interior dragged by the mouse moves the zone as a block, then undone.
await expectNoShift(
page,
async () => {
await dragDrawing(page, { x: 914, y: 498 }, { x: 954, y: 538 })
await expect(line(page)).toContainText(
dict['editor.annotations.message.moved.zone'],
)
},
SWAPS,
)
const [first] = await shownPoints(page)
expect(Math.abs(first[0] - (stored[0][0] + 40))).toBeLessThan(3)
await undo(page)
await expect.poll(() => shownPoints(page)).toEqual(stored)
})
test('Thoraciques: redraw accepted, then refused, the old outline kept meanwhile', async ({
page,
requests,
}) => {
const actor = await openThoracic(page)
requests.forbid(actor.account.email, actor.account.password)
await pickAnnotation(page, dict, THORACIC)
const stored = await shownPoints(page)
// Accepted: four clicks, « Fermer le tracé », one commit, every property kept.
await expectNoShift(
page,
() => button(page, 'editor.annotations.redraw').click(),
SWAPS,
)
for (const [x, y] of [
[850, 440],
[1100, 470],
[1100, 560],
[850, 545],
])
await expectNoShift(page, () => clickAt(page, x, y), SWAPS)
await expect(page.getByTestId('overlay-old-place')).toBeAttached()
await expectNoShift(
page,
async () => {
await button(page, 'editor.annotations.trace_close').click()
await expect(line(page)).toContainText(
dict['editor.annotations.message.redrawn.zone'],
)
},
SWAPS,
)
await expect(selectionTag(page)).toContainText('Vertèbres thoraciques')
expect(await count(page)).toBe(4)
await undo(page)
await expect.poll(() => shownPoints(page)).toEqual(stored)
// Refused: a sliver; the tracing stays open with the core's message, then cancelled.
await button(page, 'editor.annotations.redraw').click()
for (const [x, y] of [
[900, 450],
[1100, 452],
[1300, 455],
])
await clickAt(page, x, y)
await expectNoShift(
page,
async () => {
await button(page, 'editor.annotations.trace_close').click()
await expect(page.getByTestId('edit-strip-title')).toHaveText(
dict['editor.annotations.strip.close_refused'],
)
},
SWAPS,
)
await expect(button(page, 'editor.annotations.trace_close')).toBeVisible()
await expectNoShift(
page,
() => button(page, 'editor.annotations.trace_cancel').click(),
SWAPS,
)
await expect.poll(() => shownPoints(page)).toEqual(stored)
})
test('a click inside Thoraciques on C7-T1 selects the point drawn on top', async ({
page,
requests,
}) => {
const actor = await openThoracic(page)
requests.forbid(actor.account.email, actor.account.password)
await clickAt(page, 865, 528)
await expect(selectionTag(page)).toContainText('C7-T1')
// Thoraciques selected: zoomed at C7-T1 so that its vertex handles leave room, a click
// inside both shapes still selects the point (the selection's interior comes after).
await pickAnnotation(page, dict, THORACIC)
const at = await clientOf(page, 870, 515)
await page.mouse.move(at.x, at.y)
await page.keyboard.down('Control')
for (let notch = 0; notch < 14; notch++) await page.mouse.wheel(0, -100)
await page.keyboard.up('Control')
// R-18: zoomed enough, every « + » shows and the zoom line is gone.
await expect(page.getByTestId('edit-strip-notice')).not.toContainText(
dict['editor.annotations.strip.zoom_hint'],
)
await clickAt(page, 870, 515)
await expect(selectionTag(page)).toContainText('C7-T1')
})
})
+30 -1
View File
@@ -676,10 +676,39 @@ export async function clickDrawing(page: Page, x: number, y: number) {
await page.mouse.click(at.x, at.y)
}
/** The geometry fields of the open creation panel or properties panel. */
/** The geometry fields of the open creation panel (until U2 Task 7) or repair dialog. */
export const geometryField = (page: Page, dict: Dict, key: string) =>
page.getByLabel(dict[`editor.annotations.geometry.${key}`], { exact: true })
/**
* The selected shape as the overlay draws it, its circle or polygon: read `cx`, `cy`, `r`
* or `points` (U2 Task 5: the coordinate fields left the properties panel). During a
* pending move it draws the preview; the stored place is `storedShape`.
*/
export const shownShape = (page: Page) =>
page.getByTestId('overlay-selection').locator('circle, polygon').first()
/** The stored shape while a preview moves it: the old place in grey dashes. */
export const storedShape = (page: Page) =>
page.getByTestId('overlay-old-place').locator('circle, polygon').first()
/** One number of the shown shape (`cx`, `cy`, `r`). */
export async function shownNumber(page: Page, name: string): Promise<number> {
return Number(await shownShape(page).getAttribute(name))
}
/** The vertices of the shown polygon, from its `points` attribute. */
export async function shownPoints(page: Page): Promise<number[][]> {
const points = (await shownShape(page).getAttribute('points')) ?? ''
return points
.trim()
.split(/\s+/)
.map((pair) => pair.split(',').map(Number))
}
/** The page's own rounding of a coordinate (0.01 grid). */
export const round2 = (value: number) => Math.round(value * 100) / 100
/** A point annotation of the fixtures (a circle in drawing units, reviewed). */
export function pointOf(
id: string,
@@ -13,6 +13,8 @@ import {
} from '@/editor/annotations/useCanvasBuild'
import { useCanvasGestures } from '@/editor/annotations/useCanvasGestures'
import type { MoveTarget } from '@/editor/annotations/useBlockDrag'
import type { Drop } from '@/editor/annotations/usePlacement'
import type { HandleAction } from '@/editor/annotations/usePressGesture'
import type { ToolId } from '@/editor/annotations/uiState'
import { useT } from '@/i18n/useT'
import AnnotationOverlay, { type OverlayProps } from './AnnotationOverlay'
@@ -27,7 +29,7 @@ type OverlayData = Omit<
/** The handle layer's content: the handle and its keys (the layer measures itself). */
export type HandleData = Pick<
HandleLayerProps,
'handle' | 'onKeyDown' | 'onBlur'
'handle' | 'onKeyDown' | 'onBlur' | 'zone' | 'zoneKeys' | 'onInsertsHidden'
>
export interface AnnotationCanvasProps {
@@ -43,9 +45,10 @@ export interface AnnotationCanvasProps {
/** The composed root as rebuilt (with its view); null on failure. */
onRoot: (root: RootAttributes | null) => void
onSelect: (id: string) => void
/** A click with a drawing tool, in drawing units. */
onPlace: (at: XY) => void
onDrop: (id: string, geometry: Geometry) => void
/** A click with a drawing tool, in drawing units, and its closing reach (R-11). */
onPlace: (at: XY, reach: number) => void
onDrop: Drop
onHandle: (action: HandleAction) => void
onDeselect: () => void
onTraceKey: (event: KeyboardEvent) => void
}
@@ -88,7 +91,11 @@ export default function AnnotationCanvas(props: AnnotationCanvasProps) {
svgRef: overlay,
dragged: gestures.drag,
},
handles: { ...props.handles, scale: gestures.framing.framing.scale },
handles: {
...props.handles,
scale: gestures.framing.framing.scale,
dragged: gestures.drag,
},
}}
/>
</div>
@@ -144,7 +151,7 @@ interface LayerProps {
root: RootAttributes | null
transform: string
overlay: Omit<OverlayProps, 'viewBox' | 'ratio'>
handles: HandleData & { scale: number }
handles: HandleData & { scale: number; dragged: Geometry | null }
}
/**
@@ -19,6 +19,8 @@ export interface OverlayProps {
pending: Geometry | null
tracing: Point[] | null
correction: Correction | null
/** A redraw runs: the stored outline stays as the old place until the close (06 C). */
redrawing: boolean
}
const STROKE = { fill: 'none', vectorEffect: 'non-scaling-stroke' } as const
@@ -130,7 +132,8 @@ export default function AnnotationOverlay(props: OverlayProps) {
const size = frame ? Math.max(frame.w, frame.h) / 200 : 1
const preview = usePreviewOf(props.selectedId)
const moved = props.dragged ?? preview
const shown = moved ?? selected
const old = moved !== null || props.redrawing
const shown = props.redrawing ? null : (moved ?? selected)
return (
<svg
ref={props.svgRef}
@@ -140,7 +143,7 @@ export default function AnnotationOverlay(props: OverlayProps) {
preserveAspectRatio={props.ratio}
className="pointer-events-none absolute inset-0 h-full w-full"
>
{moved && selected && isEditable(selected) && (
{old && selected && isEditable(selected) && (
<g data-testid="overlay-old-place">
<Outline geometry={selected} dashed colour="var(--color-ink-muted)" />
</g>
@@ -155,10 +158,10 @@ export default function AnnotationOverlay(props: OverlayProps) {
</g>
)}
{shown && isEditable(shown) && (
<>
<g data-testid="overlay-selection">
<Outline geometry={shown} dashed colour="var(--color-ink)" />
<Vertices geometry={shown} size={size} />
</>
</g>
)}
{pending && (
<Outline
@@ -1,5 +1,4 @@
import { useEffect, useReducer, useState, type Dispatch } from 'react'
import Button from '@/components/ui/Button'
import type {
AnatomicalSheetDocument,
Annotation,
@@ -12,7 +11,14 @@ import { parseFrame, type Frame } from '@/editor/annotations/frame'
import { newPointSize } from '@/editor/annotations/pointSize'
import { guardDrawing } from '@/editor/annotations/drawingGuard'
import { usePointEdit } from '@/editor/annotations/usePointEdit'
import { endMode, useAnnotationWork } from '@/editor/annotations/workStore'
import { useZoneEdit } from '@/editor/annotations/useZoneEdit'
import { useRedrawFollowsTracing } from '@/editor/annotations/redraw'
import {
useDroppedNotice,
useModeFollowsSelection,
} from '@/editor/annotations/modeEnds'
import { handledPoints } from '@/editor/annotations/zoneEdit'
import { useAnnotationWork } from '@/editor/annotations/workStore'
import { isEditable } from '@/editor/annotations/geometryEdit'
import { useSelectionEscape } from '@/editor/annotations/deselect'
import { usePlacement } from '@/editor/annotations/usePlacement'
@@ -20,7 +26,6 @@ import { stripLeadOf } from '@/editor/annotations/stripLead'
import {
useGestureMessage,
type GestureMessage as ShownMessage,
type GestureMessages,
} from '@/editor/annotations/useGestureMessage'
import {
initialUi,
@@ -49,6 +54,8 @@ import {
} from './PointCommands'
import CreationPanel from './CreationPanel'
import EditStrip, { type StripNotice } from './EditStrip'
import TracingCommands from './TracingCommands'
import ZoneCommands, { moveTitleKey, useChosenVertex } from './ZoneCommands'
import GestureMessage from './GestureMessage'
import KeyboardAdd from './KeyboardAdd'
import OverviewPanel from './OverviewPanel'
@@ -145,59 +152,41 @@ function useCommitContext(): CommitContext {
}
/**
* The tab's work: the commit context, the line under the drawing, the placement and the
* point editing (handle keys, slider, move mode) on the movable selected circle.
* The tab's work: the commit context, the line under the drawing, the placement, the
* editing of the movable selection (point handle keys, slider, move mode) and of a
* polygon's vertices, the redraw kept in step with its tracing.
*/
function useWork(scene: Scene) {
const context = useCommitContext()
const message = useGestureMessage()
const placement = usePlacement({ ...scene, context, message })
const target = circleTargetOf(scene.selected, scene.model, scene.ui.tool)
const edit = usePointEdit({
target,
frame: scene.frame,
onDrop: placement.onDrop,
const target = movableOf(scene.selected, scene.model, scene.ui.tool)
const onDrop = placement.onDrop
const edit = usePointEdit({ target, frame: scene.frame, onDrop })
const polygon = target?.geometry?.type === 'polygon' ? target : null
const zone = useZoneEdit({
...{ target: polygon, frame: scene.frame, onDrop, message },
t: context.t,
confirmMove: edit.confirmMove,
})
const [insertsHidden, setInsertsHidden] = useState(false)
useModeFollowsSelection(scene.ui.selectedId)
useRedrawFollowsTracing(scene.ui.tracing, scene.dispatch)
useDroppedNotice(message)
return { context, message, placement, edit, target }
return {
context,
message,
placement,
edit,
zone,
target,
insertsHidden,
setInsertsHidden,
}
}
type Work = ReturnType<typeof useWork>
/**
* The move mode belongs to the selection: another selection (a list row, a view change)
* ends it. A read-only flip keeps the body and its selection, so it suspends the mode
* instead (R-14).
*/
function useModeFollowsSelection(selectedId: string | null) {
const modeId = useAnnotationWork((s) => s.mode?.annotationId ?? null)
useEffect(() => {
if (modeId === null || modeId === selectedId) return
const { mode } = useAnnotationWork.getState()
endMode()
// Never silent (R-13): a started move that ends this way is said.
if (mode?.started) useAnnotationWork.setState({ dropped: mode.kind })
}, [modeId, selectedId])
}
/**
* R-13: a started mode a change made elsewhere dropped is said on the line, once the body
* is shown (a drop while read-only is said on the way back).
*/
function useDroppedNotice(message: GestureMessages) {
const t = useT()
const visible = usePlaceVisible()
const dropped = useAnnotationWork((s) => s.dropped)
const show = message.show
useEffect(() => {
if (dropped === null || !visible) return
useAnnotationWork.setState({ dropped: null })
const text = t(`editor.annotations.dropped.${dropped}`)
show(text, { undo: false, tone: 'info' })
}, [dropped, visible, show, t])
}
export default function EditableAnnotations(props: Props) {
const scene = useScene(props)
const work = useWork(scene)
@@ -206,7 +195,10 @@ export default function EditableAnnotations(props: Props) {
const { asideRef, byDrawing } = useSelectionEscape(
selected?.id ?? null,
() => scene.dispatch({ type: 'select', id: null }),
visible && selected !== undefined && ui.tracing === null,
// A redraw's Escape cancels it at once (R-12); a new tracing keeps its own keys.
visible &&
selected !== undefined &&
(ui.tracing === null || ui.tracing.target === 'replace'),
{ editable: true, creating: ui.pending !== null },
)
return (
@@ -222,8 +214,6 @@ export default function EditableAnnotations(props: Props) {
)
}
type Placement = ReturnType<typeof usePlacement>
/** A move that drops the drawing's work asks first (R-12): the action runs once allowed. */
const guarded = (action: () => void) => () => {
if (guardDrawing(action)) action()
@@ -265,7 +255,7 @@ function CanvasColumn({
function useHandle(target: Annotation | null, doc: AnatomicalSheetDocument) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
if (!target?.geometry) return null
if (target?.geometry?.type !== 'circle') return null
const name = annotationName(target, doc.views, locale)
const kind = t(`editor.annotations.kind.${target.kind}`)
const label = t('editor.annotations.handle.shape')
@@ -292,6 +282,8 @@ function CanvasStage({
const shown = usePlaceVisible()
const { doc, ui, dispatch, model, frame, selected } = scene
const handle = useHandle(shown ? work.target : null, doc)
const points = shown ? handledPoints(work.target?.geometry ?? null) : null
const zone = points && { annotationId: work.target!.id, points }
const view = doc.views.find((v) => v.id === scene.viewId)
const blocked = !model.measured || doc.categories.length === 0
if (!view) return null
@@ -307,6 +299,9 @@ function CanvasStage({
handle,
onKeyDown: work.edit.onHandleKey,
onBlur: work.edit.onHandleBlur,
zone,
zoneKeys: work.zone,
onInsertsHidden: work.setInsertsHidden,
}}
tools={{
tool: ui.tool,
@@ -318,6 +313,7 @@ function CanvasStage({
onSelect={(id) => dispatch({ type: 'select', id })}
onPlace={work.placement.onPlace}
onDrop={work.placement.onDrop}
onHandle={work.zone.onHandle}
onDeselect={onDeselect}
onTraceKey={work.placement.onTraceKey}
/>
@@ -379,7 +375,6 @@ function SidePanel({
readOnly={false}
geometryLocked={!model.measured}
dispatch={dispatch}
context={context}
navigate={scene.navigate}
// « Tout afficher » leaves the selection: a started move asks first (R-12).
onShowAll={guarded(() => dispatch({ type: 'select', id: null }))}
@@ -399,14 +394,13 @@ function moveTargetOf(
: null
}
/** The selected point or link circle, when it can be moved now (R-9: its handle). */
function circleTargetOf(
/** The selection when it can be moved now: a circle (its handle) or a polygon (R-9). */
function movableOf(
selected: Annotation | undefined,
model: ViewModel,
tool: ToolId,
): Annotation | null {
const movable = moveTargetOf(selected, model, tool) !== null
return movable && selected?.geometry?.type === 'circle' ? selected : null
return moveTargetOf(selected, model, tool) !== null ? selected! : null
}
function overlayOf(
@@ -423,6 +417,7 @@ function overlayOf(
pending: ui.pending?.geometry ?? null,
tracing: ui.tracing?.points ?? null,
correction: ui.pending?.correction ?? null,
redrawing: ui.tracing?.target === 'replace',
}
}
@@ -433,31 +428,47 @@ function overlayOf(
function SceneStrip({ scene, work }: { scene: Scene; work: Work }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const notice = useStripNotice(scene, work.message.message)
const moving = useAnnotationWork((s) => s.mode?.kind === 'move')
useMoveFocusReturn(moving)
const notice = useStripNotice(scene, work)
const mode = useAnnotationWork((s) =>
s.mode?.kind === 'move' ? s.mode : null,
)
useMoveFocusReturn(mode !== null)
const { ui, selected, doc } = scene
const lead = moving
const chosenVertex = useChosenVertex(selected?.id)
const lead = mode
? {
title: t('editor.annotations.move.point'),
title: t(moveTitleKey(mode, work.target?.kind)),
detail: t('editor.annotations.move.hint'),
icon: 'move' as const,
}
: stripLeadOf(ui, selected, doc, { t, locale })
: stripLeadOf(ui, selected, doc, { t, locale, chosenVertex })
const commandsKey = commandsKeyOf(
ui,
mode !== null,
work.target,
chosenVertex,
)
return (
<EditStrip
lead={lead}
notice={notice}
commands={<SceneCommands scene={scene} work={work} />}
commandsKey={commandsKeyOf(ui, moving, work.target?.kind === 'point')}
commandsKey={commandsKey}
/>
)
}
function commandsKeyOf(ui: UiState, moving: boolean, point: boolean) {
/** One box per set of commands: a wider set never moves an existing box (A14). */
function commandsKeyOf(
ui: UiState,
moving: boolean,
target: Annotation | null,
chosen: number | null,
) {
if (ui.tracing) return 'tracing'
if (moving) return 'move'
return point ? 'point' : `tool-${ui.tool}`
if (target?.geometry?.type === 'polygon') return `zone-${chosen !== null}`
return target?.kind === 'point' ? 'point' : `tool-${ui.tool}`
}
/** A tracing's commands, a movable point's, or the Point tool's size (A5). */
@@ -467,11 +478,18 @@ function SceneCommands({ scene, work }: { scene: Scene; work: Work }) {
return (
<TracingCommands
count={ui.tracing.points.length}
placement={work.placement}
onClose={work.placement.closeTracing}
onPop={work.placement.popVertex}
onCancel={() => dispatch({ type: 'trace_cancel' })}
/>
)
}
if (work.target?.geometry?.type === 'polygon') {
const edit = work.edit
return (
<ZoneCommands annotation={work.target} edit={edit} dispatch={dispatch} />
)
}
// A link circle keeps its handle but has no size and no move mode (R-10; no label).
if (work.target?.kind === 'point') {
const props = { doc, viewId, frame, edit: work.edit }
@@ -497,10 +515,12 @@ function SceneCommands({ scene, work }: { scene: Scene; work: Work }) {
*/
function useStripNotice(
scene: Scene,
message: ShownMessage | null,
work: Pick<Work, 'message' | 'insertsHidden'>,
): StripNotice | null {
const t = useT()
const issues = useGeometryIssues(scene.selected?.id ?? '')
const inMode = useAnnotationWork((s) => s.mode !== null)
const message: ShownMessage | null = work.message.message
const { ui, model, doc } = scene
if (ui.hint) return { tone: 'error', text: ui.hint }
if (message?.tone === 'error') {
@@ -509,6 +529,10 @@ function useStripNotice(
if (scene.selected && issues.length > 0) {
return { tone: 'error', text: issues[0]!, more: issues.length - 1 }
}
// R-18: a « + » hidden for its short segment; never in a mode (move, redraw).
if (work.insertsHidden && !inMode && !ui.tracing) {
return { tone: 'info', text: t('editor.annotations.strip.zoom_hint') }
}
if (!model.measured) return unmeasuredNotice(scene, t)
if (doc.categories.length === 0) {
return { tone: 'info', text: t('editor.annotations.no_category') }
@@ -534,54 +558,3 @@ function unmeasuredNotice(
},
}
}
const COMMAND = 'min-h-11 xl:min-h-9'
/** While a zone or link is traced: close (3 vertices at least), take one back, or drop it. */
function TracingCommands({
count,
placement,
onCancel,
}: {
count: number
placement: Placement
onCancel: () => void
}) {
const t = useT()
return (
<div
tabIndex={-1}
data-testid="tracing-commands"
className="flex items-center gap-2 outline-none"
>
<Button
type="button"
size="sm"
className={COMMAND}
disabled={count < 3}
onClick={placement.closeTracing}
>
{t('editor.annotations.trace_close')}
</Button>
<Button
type="button"
size="sm"
variant="secondary"
className={COMMAND}
disabled={count === 0}
onClick={placement.popVertex}
>
{t('editor.annotations.trace_pop')}
</Button>
<Button
type="button"
size="sm"
variant="ghost"
className={COMMAND}
onClick={onCancel}
>
{t('editor.annotations.trace_cancel')}
</Button>
</div>
)
}
@@ -1,4 +1,5 @@
import {
useEffect,
useLayoutEffect,
useRef,
useState,
@@ -13,6 +14,11 @@ import {
type HandleSizes,
} from '@/editor/annotations/handleSize'
import { useAnnotationWork } from '@/editor/annotations/workStore'
import ZoneHandles, {
shownInserts,
type ZoneHandle,
type ZoneKeys,
} from './ZoneHandles'
/** The selected point (or link circle) whose handle the layer draws. */
export interface PointHandle {
@@ -30,6 +36,13 @@ export interface HandleLayerProps {
handle: PointHandle | null
onKeyDown: (event: KeyboardEvent<SVGGElement>) => void
onBlur: (event: FocusEvent<SVGGElement>) => void
/** The selected polygon under the cap, and its handles' keys. */
zone: ZoneHandle | null
zoneKeys: ZoneKeys
/** The canvas-local drag preview: the handles follow it. */
dragged: Geometry | null
/** Whether a « + » is hidden for its short segment (R-18's hint). */
onInsertsHidden: (hidden: boolean) => void
}
/** The svg's own box in CSS px before the framing's transform. */
@@ -79,6 +92,8 @@ export default function HandleLayer(props: HandleLayerProps) {
const svg = useRef<SVGSVGElement | null>(null)
const unit = unitsPerPx(props.viewBox, useBoxSize(svg), props.scale)
const sizes = useHandleSizes()
const zone = useShownZone(props.zone, props.dragged)
useReportHidden(zone, { unit, sizes }, props.onInsertsHidden)
return (
<svg
ref={svg}
@@ -95,10 +110,40 @@ export default function HandleLayer(props: HandleLayerProps) {
unit={unit}
/>
)}
{zone && (
<ZoneHandles
zone={zone}
scale={{ unit, sizes }}
keys={props.zoneKeys}
/>
)}
</svg>
)
}
/** The polygon as shown now: the drag in flight, the pending preview, else the stored one. */
function useShownZone(
zone: ZoneHandle | null,
dragged: Geometry | null,
): ZoneHandle | null {
const id = zone?.annotationId ?? null
const preview = useAnnotationWork((s) =>
id !== null && s.preview?.annotationId === id ? s.preview.geometry : null,
)
const shown = dragged ?? preview
if (!zone || shown?.type !== 'polygon') return zone
return { ...zone, points: shown.points }
}
function useReportHidden(
zone: ZoneHandle | null,
scale: Parameters<typeof shownInserts>[1],
report: (hidden: boolean) => void,
) {
const hidden = zone ? shownInserts(zone.points, scale).includes(false) : false
useEffect(() => report(hidden), [hidden, report])
}
function PointHandleShape({
handle,
unit,
@@ -3,19 +3,15 @@ import { flushSync } from 'react-dom'
import type {
AnatomicalSheetDocument,
Annotation,
Geometry,
Marking,
} from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import DeleteDialog from '@/components/editor/DeleteDialog'
import Button from '@/components/ui/Button'
import {
updateGeometry,
type CommitContext,
} from '@/editor/annotations/annotationCommit'
import { useDeselect } from '@/editor/annotations/deselect'
import EditorGlyph from '@/components/editor/EditorGlyph'
import { isEditable } from '@/editor/annotations/geometryEdit'
import { beginRedraw } from '@/editor/annotations/redraw'
import type { UiAction } from '@/editor/annotations/uiState'
import { geometryErrorsById } from '@/editor/issues'
import { focusRow } from '@/editor/focusRequest'
@@ -26,9 +22,7 @@ import { useEditorStore } from '@/editor/state/editorStore'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import AnnotationFields from './AnnotationFields'
import type { ApplyResult } from './GeometryGroup'
import { annotationName } from './AnnotationList'
import GeometryGroup from './GeometryGroup'
import ReviewBadge from './ReviewBadge'
export interface PropertiesPanelProps {
@@ -39,7 +33,6 @@ export interface PropertiesPanelProps {
/** The view is not measured: geometry is shown as text only, the rest stays editable. */
geometryLocked: boolean
dispatch: Dispatch<UiAction>
context: CommitContext
navigate: EditorPlaceProps['navigate']
/** Clears the selection: the overview shows again. */
onShowAll: () => void
@@ -142,25 +135,22 @@ function DeselectButton({
)
}
/**
* The geometry's state: no coordinate field (A8, U2 Task 5: circles and polygons are
* edited on the drawing); a path or a missing geometry says so and offers the redraw.
*/
function GeometrySection(props: PropertiesPanelProps) {
const t = useT()
const { annotation, readOnly, geometryLocked } = props
const locked = readOnly || geometryLocked
const { geometry } = annotation
const editable = isEditable(geometry)
return (
<div className="space-y-2">
{geometryLocked && !readOnly && (
<UnmeasuredHint navigate={props.navigate} viewId={annotation.view_id} />
)}
{isEditable(geometry) ? (
<GeometryGroup
key={annotation.id}
idPrefix={`${props.idPrefix ?? ''}annotation`}
geometry={geometry}
locked={locked}
onApply={(next) => applyGeometry(annotation, next, props.context)}
/>
) : (
{!editable && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t(
geometry === null
@@ -169,7 +159,7 @@ function GeometrySection(props: PropertiesPanelProps) {
)}
</p>
)}
{!locked && !isEditable(geometry) && (
{!locked && !editable && (
<TraceReplacement id={annotation.id} dispatch={props.dispatch} />
)}
<GeometryIssues id={annotation.id} />
@@ -177,15 +167,6 @@ function GeometrySection(props: PropertiesPanelProps) {
)
}
function applyGeometry(
annotation: Annotation,
next: Geometry,
context: CommitContext,
): ApplyResult {
const result = updateGeometry(annotation, next, context)
return result.ok ? { ok: true } : { ok: false, messages: result.messages }
}
function TraceReplacement({
id,
dispatch,
@@ -199,9 +180,8 @@ function TraceReplacement({
type="button"
variant="secondary"
size="sm"
onClick={() =>
dispatch({ type: 'trace_start', target: 'replace', annotationId: id })
}
// The same redraw as « Redessiner »: the drawing guard asks before it is lost.
onClick={() => beginRedraw(id, dispatch)}
>
{t('editor.annotations.replace_polygon')}
</Button>
@@ -0,0 +1,57 @@
import Button from '@/components/ui/Button'
import { useT } from '@/i18n/useT'
const COMMAND = 'min-h-11 xl:min-h-9'
export interface TracingCommandsProps {
count: number
onClose: () => void
onPop: () => void
onCancel: () => void
}
/** While a zone or link is traced: close (3 vertices at least), take one back, or drop it. */
export default function TracingCommands({
count,
onClose,
onPop,
onCancel,
}: TracingCommandsProps) {
const t = useT()
return (
<div
tabIndex={-1}
data-testid="tracing-commands"
className="flex items-center gap-2 outline-none"
>
<Button
type="button"
size="sm"
className={COMMAND}
disabled={count < 3}
onClick={onClose}
>
{t('editor.annotations.trace_close')}
</Button>
<Button
type="button"
size="sm"
variant="secondary"
className={COMMAND}
disabled={count === 0}
onClick={onPop}
>
{t('editor.annotations.trace_pop')}
</Button>
<Button
type="button"
size="sm"
variant="ghost"
className={COMMAND}
onClick={onCancel}
>
{t('editor.annotations.trace_cancel')}
</Button>
</div>
)
}
@@ -0,0 +1,99 @@
import type { Dispatch } from 'react'
import type { Annotation } from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
import { beginRedraw } from '@/editor/annotations/redraw'
import type { UiAction } from '@/editor/annotations/uiState'
import type { PointEdit } from '@/editor/annotations/usePointEdit'
import {
useAnnotationWork,
type ModeWork,
} from '@/editor/annotations/workStore'
import { useT } from '@/i18n/useT'
import EditorGlyph from '../EditorGlyph'
import MoveModeBar from './MoveModeBar'
const COMMAND = 'min-h-11 gap-1.5 xl:min-h-9'
/** The move mode's title: « Déplacer le sommet », « … la zone » or « … le point ». */
export function moveTitleKey(
mode: ModeWork,
kind: Annotation['kind'] | undefined,
) {
if (mode.vertex !== null) return 'editor.annotations.move.vertex'
return kind === 'zone'
? 'editor.annotations.move.zone'
: 'editor.annotations.move.point'
}
/** The chosen vertex of `annotationId`, as the work store holds it. */
export function useChosenVertex(
annotationId: string | undefined,
): number | null {
return useAnnotationWork((s) =>
annotationId !== undefined && s.chosen?.annotationId === annotationId
? s.chosen.vertex
: null,
)
}
export interface ZoneCommandsProps {
/** The selected polygon, movable now. */
annotation: Annotation
edit: PointEdit
dispatch: Dispatch<UiAction>
}
/**
* The strip's commands for a selected polygon (board 05): « Déplacer la zone » (« Déplacer
* le sommet » while a vertex is chosen) and « Redessiner »; during the move mode, its bar
* (board 06 B). A link traced as a polygon gets « Redessiner » only (no move label).
*/
export default function ZoneCommands({
annotation,
edit,
dispatch,
}: ZoneCommandsProps) {
const t = useT()
const chosen = useChosenVertex(annotation.id)
const inMode = useAnnotationWork(
(s) => s.mode?.kind === 'move' && s.mode.annotationId === annotation.id,
)
if (inMode) {
return (
<MoveModeBar
onStep={edit.stepMove}
onConfirm={edit.confirmMove}
onCancel={edit.cancelMove}
/>
)
}
const moveKey = chosen === null ? 'move.zone' : 'move.vertex'
return (
<>
{annotation.kind === 'zone' && (
<Button
// R-12: the focus comes back here when the mode ends (useMoveFocusReturn).
data-move-entry=""
type="button"
size="sm"
variant="secondary"
className={COMMAND}
onClick={edit.startMove}
>
<EditorGlyph name="move" size={16} />
{t(`editor.annotations.${moveKey}`)}
</Button>
)}
<Button
type="button"
size="sm"
variant="secondary"
className={COMMAND}
onClick={() => beginRedraw(annotation.id, dispatch)}
>
<EditorGlyph name="zone" size={16} />
{t('editor.annotations.redraw')}
</Button>
</>
)
}
@@ -0,0 +1,325 @@
import { useLayoutEffect, useRef, type KeyboardEvent } from 'react'
import type { Point } from '@faunosteo/core-wasm/types'
import type { HandleSizes } from '@/editor/annotations/handleSize'
import { MIN_VERTICES, showsInsert } from '@/editor/annotations/polygonEdit'
import type { ZoneEdit } from '@/editor/annotations/useZoneEdit'
import { useAnnotationWork } from '@/editor/annotations/workStore'
import { useT } from '@/i18n/useT'
/** The selected polygon whose vertex, « + » and « − » handles the layer draws. */
export interface ZoneHandle {
annotationId: string
points: Point[]
}
export type ZoneKeys = Pick<
ZoneEdit,
| 'onVertexKey'
| 'onVertexFocus'
| 'onVertexBlur'
| 'onInsertKey'
| 'onRemoveKey'
>
interface Scale {
/** Drawing units per CSS px. */
unit: number
sizes: HandleSizes
}
const segmentPx = (a: Point, b: Point, unit: number) =>
Math.hypot(b[0] - a[0], b[1] - a[1]) / unit
/** R-9: the « + » of segment `i` (vertex i to the next) shows at the current zoom. */
export function shownInserts(points: readonly Point[], { unit, sizes }: Scale) {
return points.map((p, i) =>
showsInsert(segmentPx(p, points[(i + 1) % points.length], unit), sizes.hit),
)
}
const RING = 'invisible group-focus-visible:visible'
function FocusRing({ cx, cy, r }: { cx: number; cy: number; r: number }) {
return (
<circle
cx={cx}
cy={cy}
r={r}
fill="none"
stroke="var(--color-accent)"
strokeWidth={2}
vectorEffect="non-scaling-stroke"
className={RING}
/>
)
}
const LINE = { vectorEffect: 'non-scaling-stroke', strokeWidth: 2 } as const
function Insert({
at,
after,
label,
scale,
onKeyDown,
}: {
at: [number, number]
after: number
label: string
scale: Scale
onKeyDown: (event: KeyboardEvent) => void
}) {
const { unit, sizes } = scale
const [cx, cy] = at
const r = (sizes.insert / 2) * unit
const arm = r * 0.5
return (
<g
role="button"
tabIndex={0}
aria-label={label}
className="group outline-none"
onKeyDown={onKeyDown}
>
<circle
cx={cx}
cy={cy}
r={r}
fill="white"
stroke="var(--color-accent)"
{...LINE}
/>
<path
d={`M ${cx - arm} ${cy} H ${cx + arm} M ${cx} ${cy - arm} V ${cy + arm}`}
stroke="var(--color-accent)"
{...LINE}
/>
<circle
cx={cx}
cy={cy}
r={Math.max(sizes.hit * unit, r)}
data-handle={JSON.stringify({ kind: 'insert', after })}
fill="transparent"
className="pointer-events-auto cursor-copy"
/>
<FocusRing cx={cx} cy={cy} r={r + 3 * unit} />
</g>
)
}
function Vertex({
at,
index,
chosen,
label,
scale,
keys,
}: {
at: Point
index: number
chosen: boolean
label: string
scale: Scale
keys: ZoneKeys
}) {
const { unit, sizes } = scale
const [cx, cy] = at
// A chosen vertex is bigger, filled and ringed: never told by colour alone.
const r = (sizes.vertex / 2 + (chosen ? 2 : 0)) * unit
return (
<g
role="button"
tabIndex={0}
aria-label={label}
aria-pressed={chosen}
data-vertex={index}
// Its arrow series commits on blur; the drawing guard blurs it before leaving.
data-series=""
className="group outline-none"
onKeyDown={(event) => keys.onVertexKey(index, event)}
onFocus={() => keys.onVertexFocus(index)}
onBlur={keys.onVertexBlur}
>
{chosen && (
<circle
cx={cx}
cy={cy}
r={r + 3 * unit}
fill="none"
stroke="var(--color-accent)"
{...LINE}
/>
)}
<circle
cx={cx}
cy={cy}
r={r}
fill={chosen ? 'var(--color-accent)' : 'white'}
stroke="var(--color-ink)"
{...LINE}
/>
<circle
cx={cx}
cy={cy}
r={Math.max(sizes.hit * unit, r)}
data-handle={JSON.stringify({ kind: 'vertex', index })}
fill="transparent"
className="pointer-events-auto cursor-move"
/>
<FocusRing cx={cx} cy={cy} r={r + 6 * unit} />
</g>
)
}
/** The « − » bubble over the chosen vertex (board 05), greyed at three vertices (12 B). */
function Remove({
at,
index,
disabled,
label,
scale,
onKeyDown,
}: {
at: Point
index: number
disabled: boolean
label: string
scale: Scale
onKeyDown: (event: KeyboardEvent) => void
}) {
const { unit, sizes } = scale
const w = sizes.bubble.w * unit
const h = sizes.bubble.h * unit
const x = at[0] - w / 2
const y = at[1] - (sizes.vertex / 2 + 6) * unit - h
const fill = disabled
? 'var(--color-ink-muted)'
: 'var(--color-danger-strong)'
return (
<g
role="button"
tabIndex={0}
aria-label={label}
aria-disabled={disabled}
className="group outline-none"
onKeyDown={onKeyDown}
>
<rect
x={x}
y={y}
width={w}
height={h}
rx={6 * unit}
fill={fill}
data-handle={JSON.stringify({ kind: 'remove', index })}
className={`pointer-events-auto ${disabled ? 'cursor-not-allowed' : 'cursor-pointer'}`}
/>
<path
d={`M ${x + w * 0.3} ${y + h / 2} H ${x + w * 0.7}`}
stroke="white"
{...LINE}
/>
<rect
x={x - 3 * unit}
y={y - 3 * unit}
width={w + 6 * unit}
height={h + 6 * unit}
rx={8 * unit}
fill="none"
stroke="var(--color-accent)"
{...LINE}
className={RING}
/>
</g>
)
}
/** The chosen vertex of this polygon, as the store holds it now. */
function useChosen(annotationId: string, count: number): number | null {
return useAnnotationWork((s) => {
const chosen = s.chosen
if (chosen?.annotationId !== annotationId) return null
return chosen.vertex < count ? chosen.vertex : null
})
}
/**
* A keyboard choice (« + », Insert, Delete) moves the focus to the vertex now chosen, so
* the keys keep acting where the user looks; a pointer choice leaves the focus alone.
*/
function useFocusFollowsChoice(chosen: number | null) {
const group = useRef<SVGGElement | null>(null)
useLayoutEffect(() => {
const active = document.activeElement
if (chosen === null || !group.current?.contains(active)) return
if (active?.getAttribute('data-vertex') === String(chosen)) return
const target = group.current.querySelector(`[data-vertex="${chosen}"]`)
if (target instanceof SVGElement) target.focus()
}, [chosen])
return group
}
const midpoint = (a: Point, b: Point): [number, number] => [
(a[0] + b[0]) / 2,
(a[1] + b[1]) / 2,
]
/**
* The polygon's handles (docs/ANNOTATION-RENDERING.md « Editor overlay »): the « + » of the
* segments long enough on screen, every vertex, then the « − » bubble of the chosen one,
* in that order (Tab walks them so). No handle covers the interior.
*/
export default function ZoneHandles({
zone,
scale,
keys,
}: {
zone: ZoneHandle
scale: Scale
keys: ZoneKeys
}) {
const t = useT()
const { points } = zone
const chosen = useChosen(zone.annotationId, points.length)
const group = useFocusFollowsChoice(chosen)
const inserts = shownInserts(points, scale)
const named = (key: string, n: number) =>
t(`editor.annotations.handle.${key}`).replace('{n}', String(n + 1))
return (
<g ref={group} data-testid="zone-handles">
{points.map((p, i) =>
inserts[i] ? (
<Insert
key={`insert-${i}`}
at={midpoint(p, points[(i + 1) % points.length])}
after={i}
label={named('insert', i)}
scale={scale}
onKeyDown={(event) => keys.onInsertKey(i, event)}
/>
) : null,
)}
{points.map((p, i) => (
<Vertex
key={`vertex-${i}`}
at={p}
index={i}
chosen={chosen === i}
label={named('vertex', i)}
scale={scale}
keys={keys}
/>
))}
{chosen !== null && (
<Remove
at={points[chosen]}
index={chosen}
disabled={points.length <= MIN_VERTICES}
label={named('remove', chosen)}
scale={scale}
onKeyDown={(event) => keys.onRemoveKey(chosen, event)}
/>
)}
</g>
)
}
@@ -208,7 +208,6 @@ function ReadOnlyAnnotations({
readOnly
geometryLocked={!model.measured}
dispatch={() => undefined}
context={{ t: (key) => key, locale }}
navigate={navigate}
onShowAll={() => setSelectedId(null)}
/>
@@ -1,5 +1,6 @@
import type { Geometry } from '@faunosteo/core-wasm/types'
import { round2, type XY } from './frame'
import { moveVertex } from './polygonEdit'
/** A circle or polygon translated as a block by a drawing-unit delta, rounded to 0.01. */
export function translatedGeometry(
@@ -25,6 +26,21 @@ export function translatedGeometry(
return null
}
/** `geometry` moved by `delta`: as a block, or only its vertex `vertex` (a polygon's). */
export function movedBy(
geometry: Geometry,
delta: XY,
vertex: number | null,
): Geometry | null {
if (vertex === null) return translatedGeometry(geometry, delta)
if (geometry.type !== 'polygon') return null
const at = geometry.points[vertex]
if (!at) return null
const to = { x: at[0] + delta.x, y: at[1] + delta.y }
const points = moveVertex(geometry.points, vertex, to)
return points && { type: 'polygon', points }
}
interface Matrix {
a: number
b: number
@@ -50,3 +66,9 @@ export function clientToDrawing(
y: inverse.b * client.x + inverse.d * client.y + inverse.f,
}
}
/** Drawing units per client px, through the same matrix; null without one. */
export function drawingPerClientPx(svg: SVGSVGElement | null): number | null {
const inverse: Matrix | undefined = svg?.getScreenCTM?.()?.inverse()
return inverse ? Math.hypot(inverse.a, inverse.b) : null
}
+16 -2
View File
@@ -6,10 +6,24 @@ export interface HandleSizes {
insert: number
/** The radius around a handle's centre that a press reaches. */
hit: number
/** The « − » bubble over the chosen vertex. */
bubble: { w: number; h: number }
}
const FINE: HandleSizes = { vertex: 12, insert: 16, hit: 10 }
const COARSE: HandleSizes = { vertex: 18, insert: 24, hit: 22 }
// shortcut: the fine bubble size is read off board 05 (no number given by R-9). Upgrade:
// take the owner's value if the trial asks for another.
const FINE: HandleSizes = {
vertex: 12,
insert: 16,
hit: 10,
bubble: { w: 28, h: 22 },
}
const COARSE: HandleSizes = {
vertex: 18,
insert: 24,
hit: 22,
bubble: { w: 44, h: 36 },
}
function deviceSizes(): HandleSizes {
const coarse =
@@ -0,0 +1,38 @@
import { useEffect } from 'react'
import { usePlaceVisible } from '@/lib/placeVisibility'
import { useT } from '@/i18n/useT'
import type { GestureMessages } from './useGestureMessage'
import { endMode, useAnnotationWork } from './workStore'
/**
* The move mode belongs to the selection: another selection (a list row, a view change)
* ends it. A read-only flip keeps the body and its selection, so it suspends the mode
* instead (R-14).
*/
export function useModeFollowsSelection(selectedId: string | null) {
const modeId = useAnnotationWork((s) => s.mode?.annotationId ?? null)
useEffect(() => {
if (modeId === null || modeId === selectedId) return
const { mode } = useAnnotationWork.getState()
endMode()
// Never silent (R-13): a started move that ends this way is said.
if (mode?.started) useAnnotationWork.setState({ dropped: mode.kind })
}, [modeId, selectedId])
}
/**
* R-13: a started mode a change made elsewhere dropped is said on the line, once the body
* is shown (a drop while read-only is said on the way back).
*/
export function useDroppedNotice(message: GestureMessages) {
const t = useT()
const visible = usePlaceVisible()
const dropped = useAnnotationWork((s) => s.dropped)
const show = message.show
useEffect(() => {
if (dropped === null || !visible) return
useAnnotationWork.setState({ dropped: null })
const text = t(`editor.annotations.dropped.${dropped}`)
show(text, { undo: false, tone: 'info' })
}, [dropped, visible, show, t])
}
@@ -0,0 +1,64 @@
import type { Point } from '@faunosteo/core-wasm/types'
import { round2, type XY } from './frame'
/** T18 (R-7): above this many vertices, outline and message, no handle. */
export const HANDLE_CAP = 40
export const MIN_VERTICES = 3
const inRange = (points: readonly Point[], i: number) =>
Number.isInteger(i) && i >= 0 && i < points.length
/** « + » on the segment from vertex `after` to the next (wrapping): its midpoint, 0.01 grid. */
export function insertMidpoint(
points: readonly Point[],
after: number,
): Point[] | null {
if (!inRange(points, after)) return null
const [ax, ay] = points[after]
const [bx, by] = points[(after + 1) % points.length]
const middle: Point = [round2((ax + bx) / 2), round2((ay + by) / 2)]
return [...points.slice(0, after + 1), middle, ...points.slice(after + 1)]
}
/** « − »: null at 3 vertices (board 12 B reason shown by the caller). */
export function removeVertex(
points: readonly Point[],
index: number,
): Point[] | null {
if (!inRange(points, index) || points.length <= MIN_VERTICES) return null
return points.filter((_, i) => i !== index)
}
export function moveVertex(
points: readonly Point[],
index: number,
to: XY,
): Point[] | null {
if (
!inRange(points, index) ||
!Number.isFinite(to.x) ||
!Number.isFinite(to.y)
)
return null
return points.map(
(p, i): Point => (i === index ? [round2(to.x), round2(to.y)] : p),
)
}
/** A vertex released on itself or on a neighbour is no change (no commit). */
export function isNoOpMove(
points: readonly Point[],
index: number,
moved: readonly Point[],
): boolean {
const n = points.length
const [x, y] = moved[index]
return [index, (index + 1) % n, (index + n - 1) % n].some(
(j) => points[j][0] === x && points[j][1] === y,
)
}
/** R-9: a « + » shows only when its segment is at least two hit radii long on screen. */
export function showsInsert(segmentPx: number, hitRadiusPx: number): boolean {
return segmentPx >= 2 * hitRadiusPx
}
+6
View File
@@ -7,6 +7,12 @@ export const SLOP_PX: Readonly<Record<PointerKind, number>> = {
pen: 6,
touch: 10,
}
/** R-11: CSS px from the first vertex within which a click closes a tracing. */
export const CLOSE_PX: Readonly<Record<PointerKind, number>> = {
mouse: 12,
pen: 22,
touch: 22,
}
export const DOUBLE_MS = 400
export const DOUBLE_PX = 8
@@ -1,6 +1,6 @@
import type { Geometry } from '@faunosteo/core-wasm/types'
import { useEditorStore } from '../state/editorStore'
import { translatedGeometry } from './gesture'
import { movedBy } from './gesture'
import {
endMode,
setModePreview,
@@ -42,19 +42,22 @@ export function shownGeometry(
}
/**
* One step of the selection by `delta` drawing units: into the move mode when it is on,
* else as a keyboard series (`keys`), stamped with the current text.
* One step of the selection by `delta` drawing units: into the move mode when it is on
* (its vertex, or the shape), else as a keyboard series (`keys`) of the shape or of
* `vertex`, stamped with the current text.
*/
export function stepSelection(
annotationId: string,
stored: Geometry,
delta: { x: number; y: number },
vertex: number | null = null,
): void {
const moved = translatedGeometry(shownGeometry(annotationId, stored), delta)
const { mode } = useAnnotationWork.getState()
const inMode = mode?.kind === 'move'
const shown = shownGeometry(annotationId, stored)
const moved = movedBy(shown, delta, inMode ? mode.vertex : vertex)
if (!moved) return
if (useAnnotationWork.getState().mode?.kind === 'move') {
return setModePreview(moved, stored)
}
if (inMode) return setModePreview(moved, stored)
const base = useEditorStore.getState().documentText
const preview: Preview = {
annotationId,
+42
View File
@@ -0,0 +1,42 @@
import { useEffect, useRef, type Dispatch } from 'react'
import { useEditorStore } from '../state/editorStore'
import type { Tracing, UiAction } from './uiState'
import {
endMode,
markRedraw,
startRedraw,
useAnnotationWork,
} from './workStore'
/**
* « Redessiner » (or « Remplacer par un polygone »): the redraw mode, which the drawing
* guard reads (R-12), and the tracing target `replace` that draws the new polygon.
*/
export function beginRedraw(id: string, dispatch: Dispatch<UiAction>): void {
startRedraw(id, useEditorStore.getState().documentText)
dispatch({ type: 'trace_start', target: 'replace', annotationId: id })
}
/**
* The redraw lives in two places, the tab's tracing and the work store's mode; whichever
* ends first ends the other: a tracing gone (closed, « Annuler le tracé », Escape, a
* tool, a view, a selection) ends the mode; a mode gone (« Abandonner », an undo, a
* document change made elsewhere) ends the tracing. The mode is started once the
* tracing holds a vertex, and no longer when it is back to none.
*/
export function useRedrawFollowsTracing(
tracing: Tracing | null,
dispatch: Dispatch<UiAction>,
): void {
const redraw = useAnnotationWork((s) => s.mode?.kind === 'redraw')
const count = tracing?.target === 'replace' ? tracing.points.length : null
// Only the body whose tracing it was ends the mode: another body kept alive has none.
const traced = useRef(false)
useEffect(() => {
const was = traced.current
traced.current = count !== null
if (redraw && count === null && was) endMode()
else if (!redraw && count !== null) dispatch({ type: 'trace_cancel' })
else if (count !== null) markRedraw(count > 0)
}, [redraw, count, dispatch])
}
+34 -14
View File
@@ -9,6 +9,7 @@ import type { GlyphName } from '@/components/editor/EditorGlyph'
import type { Locale } from '@/i18n/types'
import { pluralKey } from '../plural'
import type { PendingElement } from './creation'
import { HANDLE_CAP } from './polygonEdit'
import type { ToolId, Tracing, UiState } from './uiState'
/** The strip's left part: what is selected or in progress, then its type and detail. */
@@ -24,6 +25,8 @@ export interface LeadContext {
locale: Locale
/** The sheet cannot be edited now: the detail says so (board 33 E). */
readOnly?: boolean
/** The chosen vertex of the selected polygon, said after its count. */
chosenVertex?: number | null
}
const ICON: Record<Annotation['kind'], GlyphName> = {
@@ -45,6 +48,23 @@ function counted(
.replace('{kind}', () => kind)
}
/**
* « Zone · 9 sommets », « … · sommet 7 choisi », or above the cap (T18) « Zone · 41
* sommets, trop pour les poignées ».
*/
function polygonDetail(count: number, kind: string, ctx: LeadContext): string {
if (count > HANDLE_CAP && !ctx.readOnly) {
return counted(ctx, 'editor.annotations.strip.too_many', count, kind)
}
const shape = counted(ctx, 'editor.annotations.strip.vertices', count, kind)
const chosen = ctx.chosenVertex
if (chosen === null || chosen === undefined || ctx.readOnly) return shape
return ctx
.t('editor.annotations.strip.vertex_chosen')
.replace('{detail}', () => shape)
.replace('{n}', String(chosen + 1))
}
/** « Point », « Zone · 9 sommets »; « … · fiche en lecture seule » when read-only. */
export function selectionLead(
annotation: Annotation,
@@ -55,12 +75,7 @@ export function selectionLead(
const geometry = annotation.geometry
const shape =
geometry?.type === 'polygon'
? counted(
ctx,
'editor.annotations.strip.vertices',
geometry.points.length,
kind,
)
? polygonDetail(geometry.points.length, kind, ctx)
: kind
return {
title: annotationName(annotation, views, ctx.locale),
@@ -74,17 +89,22 @@ export function selectionLead(
}
}
/** A tracing: « Ajouter une zone » or « Redessiner · {nom} », then the vertices placed. */
/**
* A tracing: « Ajouter une zone » or « Redessiner · {nom} », then the vertices placed;
* « Fermeture refusée » while the core's refusal of its close shows (board 33 A).
*/
function tracingLead(
tracing: Tracing,
replaced: string,
ctx: LeadContext,
ctx: LeadContext & { refused: boolean },
): StripLead {
const title =
tracing.target === 'replace'
? ctx
.t('editor.annotations.strip.redraw')
.replace('{name}', () => replaced)
const redraw = ctx
.t('editor.annotations.strip.redraw')
.replace('{name}', () => replaced)
const title = ctx.refused
? ctx.t('editor.annotations.strip.close_refused')
: tracing.target === 'replace'
? redraw
: ctx.t(`editor.annotations.add.${tracing.target}`)
return {
title,
@@ -149,7 +169,7 @@ export function stripLeadOf(
(a) => a.id === ui.tracing?.annotationId,
)
const name = replaced ? annotationName(replaced, doc.views, ctx.locale) : ''
return tracingLead(ui.tracing, name, ctx)
return tracingLead(ui.tracing, name, { ...ctx, refused: ui.hint !== null })
}
if (selected) return selectionLead(selected, doc.views, ctx)
const lead = TOOL_LEAD[ui.tool]
+11 -1
View File
@@ -60,6 +60,10 @@ const TOOL_OF: Record<Tracing['target'], ToolId> = {
replace: 'zone',
}
/** A redraw lends the zone tool to its tracing: whatever ends it gives the select tool back. */
const toolAfterTracing = (state: UiState): ToolId =>
state.tracing?.target === 'replace' ? 'select' : state.tool
export function uiReducer(state: UiState, action: UiAction): UiState {
switch (action.type) {
case 'view':
@@ -69,6 +73,7 @@ export function uiReducer(state: UiState, action: UiAction): UiState {
case 'select':
return {
...state,
tool: toolAfterTracing(state),
selectedId: action.id,
pending: null,
tracing: null,
@@ -124,7 +129,12 @@ export function uiReducer(state: UiState, action: UiAction): UiState {
}
: state
case 'trace_cancel':
return { ...state, tracing: null, hint: null }
return {
...state,
tool: toolAfterTracing(state),
tracing: null,
hint: null,
}
case 'hint':
return { ...state, hint: action.hint }
case 'filter':
+45 -13
View File
@@ -2,9 +2,12 @@ import { useEffect, useRef, useState, type RefObject } from 'react'
import type { Annotation, Geometry } from '@faunosteo/core-wasm/types'
import { useEditorStore } from '../state/editorStore'
import type { XY } from './frame'
import { clientToDrawing, translatedGeometry } from './gesture'
import { clientToDrawing, movedBy } from './gesture'
import { isNoOpMove } from './polygonEdit'
import { shownGeometry } from './previewCommit'
import { setModePreview } from './workStore'
import type { GeometryChange } from './usePlacement'
import { chooseVertex } from './zoneEdit'
import { setModePreview, useAnnotationWork } from './workStore'
import type { EditableGeometry } from './geometryEdit'
export interface MoveTarget {
@@ -18,7 +21,7 @@ export interface BlockDragInput {
/** The selected annotation, when it can be moved (editable, measured, circle or polygon). */
target: MoveTarget | null
/** One `update` on the drop; the verdict and the message are the caller's. */
onDrop: (id: string, geometry: Geometry) => void
onDrop: (id: string, geometry: Geometry, change?: GeometryChange) => boolean
}
interface Drag {
@@ -29,6 +32,8 @@ interface Drag {
base: Geometry
/** A drag of the move mode (board 06 B): it moves the mode's preview, never commits. */
mode: boolean
/** The vertex dragged alone (a vertex handle, or the mode's chosen vertex). */
vertex: number | null
}
function translatedAt(
@@ -38,10 +43,27 @@ function translatedAt(
): Geometry | null {
const now = clientToDrawing(overlay.current, client)
if (!now) return null
return translatedGeometry(drag.base, {
x: now.x - drag.origin.x,
y: now.y - drag.origin.y,
})
const delta = { x: now.x - drag.origin.x, y: now.y - drag.origin.y }
return movedBy(drag.base, delta, drag.vertex)
}
/** A vertex released on itself or on a neighbour moves nothing: no commit. */
function isNoOp(drag: Drag, dropped: Geometry): boolean {
const { base, vertex } = drag
if (vertex === null || base.type !== 'polygon') return false
return (
dropped.type === 'polygon' &&
isNoOpMove(base.points, vertex, dropped.points)
)
}
/** A drop outside the mode commits once: the shape moved, or its vertex. */
function commitDrop(input: BlockDragInput, drag: Drag, dropped: Geometry) {
if (drag.mode || isNoOp(drag, dropped)) return
const { id } = drag.target
if (drag.vertex === null) return void input.onDrop(id, dropped, 'move')
// The dragged vertex stays chosen on the new text (board 05 B).
if (input.onDrop(id, dropped, 'vertex')) chooseVertex(id, drag.vertex)
}
/** Losing the target (read-only, another selection) or a document change drops the drag. */
@@ -77,14 +99,24 @@ function dragActions(
drag.current = null
setPreview(null)
}
const start = (pressedAt: XY, client: XY, mode = false) => {
/** `vertex`: a vertex handle's drag; the move mode drags its own vertex, if any. */
const start = (
pressedAt: XY,
client: XY,
mode: boolean,
vertex: number | null,
) => {
const origin = clientToDrawing(input.overlay.current, pressedAt)
const { target } = input
if (!target || !origin) return
const base = mode
? shownGeometry(target.id, target.geometry)
: target.geometry
drag.current = { target, origin, base, mode }
const own = mode
? (useAnnotationWork.getState().mode?.vertex ?? null)
: vertex
if (!mode && vertex !== null) chooseVertex(target.id, vertex)
drag.current = { target, origin, base, mode, vertex: own }
show(translatedAt(input.overlay, drag.current, client))
}
const follow = (client: XY) => {
@@ -98,15 +130,15 @@ function dragActions(
if (gesture?.mode) show(dropped)
drag.current = null
setPreview(null)
if (gesture && !gesture.mode && dropped)
input.onDrop(gesture.target.id, dropped)
if (gesture && dropped) commitDrop(input, gesture, dropped)
}
return { start, follow, drop, cancel }
}
/**
* The selection moved as a block (`drag_shape`, `drag_point`): the overlay previews the
* translated outline, kept local to the canvas for speed; the drop commits once. A drag
* 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;
* the drop commits once. A drag
* of the move mode (`drag_mode`) moves the mode's preview instead, and commits nothing.
*/
export function useBlockDrag(input: BlockDragInput) {
+68 -41
View File
@@ -10,12 +10,10 @@ import { updateGeometry, type CommitContext } from './annotationCommit'
import { pendingForClick, type NewKind } from './creation'
import { round2, type Frame, type XY } from './frame'
import { newPointSize } from './pointSize'
import { endMode, useAnnotationWork } from './workStore'
import type { ToolId, Tracing, UiAction, UiState } from './uiState'
import type { GestureMessages } from './useGestureMessage'
/** A click on the first vertex closes the tracing when within this share of F's span. */
const CLOSE_SHARE = 0.015
const TOOL_TARGET: Record<Exclude<ToolId, 'select'>, NewKind> = {
point: 'point',
zone: 'zone',
@@ -35,47 +33,56 @@ export interface PlacementInput {
const asPoint = (at: XY): Point => [round2(at.x), round2(at.y)]
function nearFirstVertex(tracing: Tracing, at: XY, frame: Frame): boolean {
/** R-11: `reach` is the closing radius of the pointer, in drawing units. */
function nearFirstVertex(tracing: Tracing, at: XY, reach: number): boolean {
const first = tracing.points[0]
if (!first || tracing.points.length < 3) return false
const reach = CLOSE_SHARE * Math.max(frame.w, frame.h)
return Math.hypot(first[0] - at.x, first[1] - at.y) <= reach
}
/**
* What closing a tracing does: a new zone or link becomes the pending element; a polygon
* replacing a geometry is committed at once under `accept`, and a refusal drops the
* tracing with the core's message (the annotation is unchanged).
* A redraw's close commits the polygon at once. The mode leaves first, so the commit is
* never said as an abandoned redraw (R-13); a refusal brings it back and keeps the
* tracing open with the core's message (board 33 A).
*/
export function closingActions(
tracing: Tracing | null,
doc: AnatomicalSheetDocument,
context: CommitContext,
): UiAction[] {
if (!tracing || tracing.points.length < 3) return []
const polygon = { type: 'polygon' as const, points: tracing.points }
if (tracing.target !== 'replace') {
const pending = { kind: tracing.target, geometry: polygon }
return [{ type: 'pending_new', pending }]
}
function closeRedraw(input: PlacementInput, tracing: Tracing): void {
const { doc, context, dispatch } = input
const annotation = doc.annotations.find((a) => a.id === tracing.annotationId)
if (!annotation) return [{ type: 'trace_cancel' }]
if (!annotation) return dispatch({ type: 'trace_cancel' })
const held = useAnnotationWork.getState().mode
endMode()
const polygon = { type: 'polygon' as const, points: tracing.points }
const result = updateGeometry(annotation, polygon, context)
if (result.ok) return [{ type: 'select', id: annotation.id }]
return [
{ type: 'trace_cancel' },
{ type: 'hint', hint: result.messages.join(' ') },
]
if (!result.ok) {
useAnnotationWork.setState({ mode: held })
return dispatch({ type: 'hint', hint: result.messages.join(' ') })
}
dispatch({ type: 'select', id: annotation.id })
const text = context.t(
`editor.annotations.message.redrawn.${annotation.kind}`,
)
input.message.show(text, { undo: true, tone: 'info' })
}
/** Tracing with the zone and link tools: vertices, closing, Enter, Backspace and Escape. */
function tracingActions(input: PlacementInput) {
const { ui, dispatch, frame } = input
const closeTracing = () =>
closingActions(ui.tracing, input.doc, input.context).forEach(dispatch)
const trace = (tool: Exclude<ToolId, 'select' | 'point'>, at: XY) => {
if (!frame) return
if (ui.tracing && nearFirstVertex(ui.tracing, at, frame)) {
const { ui, dispatch } = input
const closeTracing = () => {
const tracing = ui.tracing
if (!tracing || tracing.points.length < 3) return
if (tracing.target === 'replace') return closeRedraw(input, tracing)
const pending = {
kind: tracing.target,
geometry: { type: 'polygon' as const, points: tracing.points },
}
dispatch({ type: 'pending_new', pending })
}
const trace = (
tool: Exclude<ToolId, 'select' | 'point'>,
at: XY,
reach: number,
) => {
if (ui.tracing && nearFirstVertex(ui.tracing, at, reach)) {
return closeTracing()
}
if (!ui.tracing)
@@ -97,14 +104,25 @@ function tracingActions(input: PlacementInput) {
return { closeTracing, trace, onTraceKey }
}
/** A move (drag, move mode, arrow keys) or a size change of the selection. */
export type GeometryChange = 'move' | 'size'
/**
* A move (drag, move mode, arrow keys) or a size change of the selection, a vertex
* moved, added or removed.
*/
export type GeometryChange = 'move' | 'size' | 'vertex' | 'insert' | 'remove'
const KEPT: Record<Exclude<GeometryChange, 'move'>, string> = {
size: 'resized',
vertex: 'vertex_moved',
insert: 'vertex_added',
remove: 'vertex_removed',
}
/** The message keys of a kept and of a refused change. */
function changeKeys(change: GeometryChange, kind: Annotation['kind']) {
return change === 'size'
? { kept: 'resized', refused: 'size_refused' }
: { kept: `moved.${kind}`, refused: 'move_refused' }
const kept = change === 'move' ? `moved.${kind}` : KEPT[change]
if (change === 'size') return { kept, refused: 'size_refused' }
const moved = change === 'move' || change === 'vertex'
return { kept, refused: moved ? 'move_refused' : 'edit_refused' }
}
/**
@@ -112,24 +130,32 @@ function changeKeys(change: GeometryChange, kind: Annotation['kind']) {
* with the refused place drawn (the shape stays where it was).
*/
function dropAction({ doc, context, message, dispatch }: PlacementInput) {
return (id: string, geometry: Geometry, change: GeometryChange = 'move') => {
return (
id: string,
geometry: Geometry,
change: GeometryChange = 'move',
): boolean => {
const annotation = doc.annotations.find((a) => a.id === id)
if (!annotation) return
if (!annotation) return false
const keys = changeKeys(change, annotation.kind)
const result = updateGeometry(annotation, geometry, context)
if (result.ok) {
// A kept move ends any refusal the strip still shows.
dispatch({ type: 'hint', hint: null })
const text = context.t(`editor.annotations.message.${keys.kept}`)
return message.show(text, { undo: true, tone: 'info' })
message.show(text, { undo: true, tone: 'info' })
return true
}
const text = context
.t(`editor.annotations.message.${keys.refused}`)
.replace('{text}', () => result.messages.join(' '))
message.show(text, { undo: false, tone: 'error', place: geometry })
return false
}
}
export type Drop = ReturnType<typeof dropAction>
/**
* What a click, a key or a drop does with the current tool. Every geometry it proposes is
* arithmetic over F; the core decides at « Créer » or at the commit of an existing one.
@@ -139,9 +165,10 @@ export function usePlacement(input: PlacementInput) {
const t = useT()
const tracing = tracingActions(input)
const { ui, dispatch, frame } = input
const onPlace = (at: XY) => {
/** `reach`: the pointer's closing radius in drawing units (R-11). */
const onPlace = (at: XY, reach: number) => {
if (ui.tool === 'zone' || ui.tool === 'link')
return tracing.trace(ui.tool, at)
return tracing.trace(ui.tool, at, reach)
if (ui.tool !== 'point' || !frame) return
const { doc, viewId } = input
const size = newPointSize(doc.annotations, viewId, frame, ui.size)
@@ -1,9 +1,10 @@
import type { KeyboardEvent } from 'react'
import type { Annotation, Geometry } from '@faunosteo/core-wasm/types'
import type { Annotation } from '@faunosteo/core-wasm/types'
import { useEditorStore } from '../state/editorStore'
import { moveStep, type Frame } from './frame'
import type { GeometryChange } from './usePlacement'
import type { Drop } from './usePlacement'
import { takeMove, takePreview, stepSelection } from './previewCommit'
import { chooseVertex, freshChosen } from './zoneEdit'
import {
endMode,
startMove,
@@ -11,10 +12,8 @@ import {
type Preview,
} from './workStore'
type Drop = (id: string, geometry: Geometry, change?: GeometryChange) => void
export interface PointEditInput {
/** The selection when it can be moved now (a circle: a point or a link). */
/** The selection when it can be moved now: a circle (point, link) or a polygon. */
target: Annotation | null
frame: Frame | null
onDrop: Drop
@@ -67,8 +66,13 @@ function commits({ onDrop, target }: PointEditInput) {
}
}
const move = () => {
const vertex = useAnnotationWork.getState().mode?.vertex ?? null
const preview = takeMove()
if (preview) onDrop(preview.annotationId, preview.geometry)
if (!preview) return
const { annotationId: id, geometry } = preview
if (vertex === null) return void onDrop(id, geometry)
// The moved vertex stays chosen on the new text.
if (onDrop(id, geometry, 'vertex')) chooseVertex(id, vertex)
}
return { keys, size, move }
}
@@ -102,9 +106,12 @@ export function usePointEdit(input: PointEditInput) {
// BDR-050: leaving the handle commits its series; a move mode waits for « Valider ».
onHandleBlur: () => commit.keys(),
commitSize: commit.size,
// « Déplacer le sommet » while a vertex is chosen, else the whole shape.
startMove: () => {
if (!input.target) return
startMove(input.target.id, useEditorStore.getState().documentText)
const id = input.target?.id
if (!id) return
const base = useEditorStore.getState().documentText
startMove(id, base, freshChosen(id))
},
stepMove: (direction: Direction) => step(input, direction, false),
confirmMove: commit.move,
@@ -1,7 +1,9 @@
import { useEffect, useRef, type PointerEvent, type RefObject } from 'react'
import type { XY } from './frame'
import { clientToDrawing } from './gesture'
import { clientToDrawing, drawingPerClientPx } from './gesture'
import { HANDLE_CAP } from './polygonEdit'
import {
CLOSE_PX,
clickAction,
dragAction,
isDoubleClick,
@@ -28,8 +30,10 @@ export interface PressInput extends BlockDragInput {
selectedId: string | null
viewport: RefObject<HTMLDivElement | null>
onSelect: (id: string) => void
/** A click with a drawing tool, in drawing units. */
onPlace: (at: XY) => void
/** A click with a drawing tool, in drawing units, with its closing reach (R-11). */
onPlace: (at: XY, reach: number) => void
/** A click on a vertex handle, a « + » or the « − » bubble. */
onHandle: (action: HandleAction) => void
/** A tap on the empty drawing with the select tool. */
onDeselect: () => void
}
@@ -91,16 +95,23 @@ function doubled(
return id === null ? action : { type: 'open', id }
}
/**
* What a click does with the select tool. `open` (the properties dialog) and the vertex
* handles (`choose_vertex`, `insert`, `remove`) have nothing to act on yet.
*/
export type HandleAction = Extract<
ClickAction,
{ type: 'choose_vertex' | 'insert' | 'remove' }
>
const isHandleAction = (action: ClickAction): action is HandleAction =>
action.type === 'choose_vertex' ||
action.type === 'insert' ||
action.type === 'remove'
/** What a click does with the select tool. `open` (the properties dialog) has nothing yet. */
function runClick(action: ClickAction, input: PressInput): void {
if (action.type === 'select') input.onSelect(action.id)
else if (action.type === 'deselect') input.onDeselect()
else if (action.type === 'unchoose') {
useAnnotationWork.setState({ chosen: null })
}
} else if (isHandleAction(action)) input.onHandle(action)
}
interface Machine {
@@ -123,8 +134,11 @@ interface Feed {
/** A click with a drawing tool places at the pointer-up, in drawing units. */
function place(input: PressInput, event: PointerEvent): void {
const drawn = clientToDrawing(input.overlay.current, clientOf(event))
if (drawn) input.onPlace(drawn)
const svg = input.overlay.current
const drawn = clientToDrawing(svg, clientOf(event))
const perPx = drawingPerClientPx(svg)
if (!drawn || perPx === null) return
input.onPlace(drawn, CLOSE_PX[pointerKindOf(event.pointerType)] * perPx)
}
/** A click with the select tool: its action, or `open` as the second of a double click. */
@@ -144,7 +158,12 @@ function onClick(f: Feed, target: PressTarget, event: PointerEvent): void {
if (!inMoveMode()) selectClick(f, target, event)
}
const BLOCK_DRAGS = new Set(['drag_shape', 'drag_point', 'drag_mode'])
const BLOCK_DRAGS = new Set([
'drag_shape',
'drag_point',
'drag_mode',
'drag_vertex',
])
function applyEffect(f: Feed, effect: PressEffect, event: PointerEvent | null) {
if (effect?.type === 'drag_cancel') f.drag.cancel()
@@ -152,13 +171,22 @@ function applyEffect(f: Feed, effect: PressEffect, event: PointerEvent | null) {
if (effect.type === 'click') onClick(f, effect.target, event)
if (effect.type === 'drag_end') f.drag.drop(clientOf(event))
if (effect.type === 'drag_start' && BLOCK_DRAGS.has(effect.action.type)) {
const mode = effect.action.type === 'drag_mode'
f.drag.start(f.machine.current.pressedAt, clientOf(event), mode)
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)
}
}
/** R-7: above the handle cap a polygon keeps the move mode and the redraw only. */
function movable(input: PressInput): boolean {
const geometry = input.target?.geometry
if (!geometry) return false
return geometry.type !== 'polygon' || geometry.points.length <= HANDLE_CAP
}
const contextOf = (input: PressInput) => ({
movable: input.target !== null,
movable: movable(input),
moveMode: inMoveMode(),
})
@@ -0,0 +1,149 @@
import type { KeyboardEvent } from 'react'
import type { Annotation, Point } from '@faunosteo/core-wasm/types'
import { moveStep, type Frame } from './frame'
import { insertMidpoint, removeVertex } from './polygonEdit'
import { stepSelection, takePreview } from './previewCommit'
import type { Drop } from './usePlacement'
import type { GestureMessages } from './useGestureMessage'
import type { HandleAction } from './usePressGesture'
import { chooseVertex, freshChosen } from './zoneEdit'
import { useAnnotationWork } from './workStore'
export interface ZoneEditInput {
/** The selected polygon when its vertices can be edited now (editable, measured). */
target: Annotation | null
frame: Frame | null
onDrop: Drop
message: Pick<GestureMessages, 'show'>
t: (key: string) => string
/** The move mode's own Enter: « Valider la position ». */
confirmMove: () => void
}
const STEP: Record<string, [number, number]> = {
ArrowLeft: [-1, 0],
ArrowUp: [0, -1],
ArrowDown: [0, 1],
ArrowRight: [1, 0],
}
const pointsOf = (target: Annotation | null): Point[] | null =>
target?.geometry?.type === 'polygon' ? target.geometry.points : null
/** « + »: the midpoint commits once, and the new vertex is chosen on the new text. */
function insertAfter(input: ZoneEditInput, after: number): void {
const { target, onDrop } = input
const next = insertMidpoint(pointsOf(target) ?? [], after)
if (!target || !next) return
const polygon = { type: 'polygon' as const, points: next }
if (onDrop(target.id, polygon, 'insert')) chooseVertex(target.id, after + 1)
}
/**
* « − »: only the vertex chosen on the current text (Review Focus 2: an undo drops it, so a
* stale bubble or key removes nothing). At three vertices the reason is said instead.
*/
function removeChosen(input: ZoneEditInput, index: number): boolean {
const { target, onDrop } = input
const points = pointsOf(target)
if (!target || !points || freshChosen(target.id) !== index) return false
const next = removeVertex(points, index)
if (!next) {
const text = input.t('editor.annotations.message.vertex_min')
input.message.show(text, { undo: false, tone: 'error' })
return false
}
return onDrop(target.id, { type: 'polygon', points: next }, 'remove')
}
/** The keyboard series of a vertex commits once, the vertex still chosen after. */
function commitKeys(input: ZoneEditInput): void {
const { target, onDrop } = input
const preview = takePreview('keys')
if (!target || !preview || preview.annotationId !== target.id) return
const same =
JSON.stringify(preview.geometry) === JSON.stringify(target.geometry)
if (same) return
const vertex = freshChosen(target.id)
const kept = onDrop(target.id, preview.geometry, 'vertex')
if (kept && vertex !== null) chooseVertex(target.id, vertex)
}
function stepVertex(input: ZoneEditInput, index: number, event: KeyboardEvent) {
const { target, frame } = input
const [x, y] = STEP[event.key]
if (!target?.geometry || !frame) return
const size = moveStep(frame, event.shiftKey)
stepSelection(target.id, target.geometry, { x: x * size, y: y * size }, index)
}
const inMoveMode = () => useAnnotationWork.getState().mode?.kind === 'move'
/** Delete removes the chosen vertex; the next one is chosen so the focus stays on a vertex. */
function deleteChosen(input: ZoneEditInput): void {
const id = input.target?.id
const chosen = id ? freshChosen(id) : null
if (id === undefined || chosen === null || !removeChosen(input, chosen))
return
const left = pointsOf(input.target)!.length - 2
chooseVertex(id, Math.min(chosen, left))
}
/** A vertex handle's keys (board 32): arrows step it, Enter commits, Insert adds, Delete. */
function vertexKey(input: ZoneEditInput, index: number, event: KeyboardEvent) {
const id = input.target?.id
if (STEP[event.key]) {
event.preventDefault()
return stepVertex(input, index, event)
}
if (event.key === 'Enter') {
event.preventDefault()
return inMoveMode() ? input.confirmMove() : commitKeys(input)
}
const chosen = id ? freshChosen(id) : null
if (event.key === 'Insert' && chosen !== null) insertAfter(input, chosen)
if (event.key === 'Delete') deleteChosen(input)
}
/** Enter or Space on a « + » or on the « − » bubble is its click. */
const isPress = (event: KeyboardEvent) =>
event.key === 'Enter' || event.key === ' '
/**
* Zone editing (R-7 to R-13): a click on a vertex chooses it, « + » inserts at a segment's
* midpoint, « − » removes the chosen vertex, and the vertex handles' keys. Every change
* commits once through `onDrop`, the core deciding.
*/
export function useZoneEdit(input: ZoneEditInput) {
const onHandle = (action: HandleAction) => {
const id = input.target?.id
if (!id) return
if (action.type === 'choose_vertex') chooseVertex(id, action.index)
if (action.type === 'insert') insertAfter(input, action.after)
if (action.type === 'remove') removeChosen(input, action.index)
}
return {
onHandle,
onVertexKey: (index: number, event: KeyboardEvent) =>
vertexKey(input, index, event),
// Focus chooses (board 32: Insert and Delete act on the chosen vertex).
onVertexFocus: (index: number) => {
const id = input.target?.id
if (id && freshChosen(id) !== index) chooseVertex(id, index)
},
// BDR-050: leaving the vertex commits its series; a move mode waits for « Valider ».
onVertexBlur: () => commitKeys(input),
onInsertKey: (after: number, event: KeyboardEvent) => {
if (!isPress(event)) return
event.preventDefault()
insertAfter(input, after)
},
onRemoveKey: (index: number, event: KeyboardEvent) => {
if (!isPress(event)) return
event.preventDefault()
removeChosen(input, index)
},
}
}
export type ZoneEdit = ReturnType<typeof useZoneEdit>
+24 -3
View File
@@ -31,6 +31,8 @@ export interface ModeWork {
annotationId: string
started: boolean
base: string
/** The chosen vertex a move mode moves alone (« Déplacer le sommet »); null: the shape. */
vertex: number | null
}
export type GuardWork = 'creation' | 'move' | 'redraw' | null
/** A navigation held by the drawing guard (R-12): what it asks about, and the move itself. */
@@ -68,15 +70,34 @@ export function endMode(): void {
useAnnotationWork.setState({ mode: null, preview: null })
}
/** « Déplacer … »: the mode on `annotationId`, nothing moved yet. */
export function startMove(annotationId: string, base: string): void {
/** « Déplacer … »: the mode on `annotationId` (or its vertex `vertex`), nothing moved yet. */
export function startMove(
annotationId: string,
base: string,
vertex: number | null = null,
): void {
useAnnotationWork.setState({
mode: { kind: 'move', annotationId, started: false, base },
mode: { kind: 'move', annotationId, started: false, base, vertex },
preview: null,
})
}
/** « Redessiner »: the redraw of `annotationId`, no vertex placed yet (R-12). */
export function startRedraw(annotationId: string, base: string): void {
useAnnotationWork.setState({
mode: { kind: 'redraw', annotationId, started: false, base, vertex: null },
preview: null,
chosen: null,
})
}
/** The redraw is started once its tracing holds a vertex, and no longer at none. */
export function markRedraw(started: boolean): void {
const { mode } = useAnnotationWork.getState()
if (mode?.kind !== 'redraw' || mode.started === started) return
useAnnotationWork.setState({ mode: { ...mode, started } })
}
const sameGeometry = (a: Geometry, b: Geometry) =>
JSON.stringify(a) === JSON.stringify(b)
@@ -0,0 +1,24 @@
import type { Geometry, Point } from '@faunosteo/core-wasm/types'
import { useEditorStore } from '../state/editorStore'
import { HANDLE_CAP } from './polygonEdit'
import { useAnnotationWork } from './workStore'
/** A polygon's vertices when it gets handles (R-7: at most HANDLE_CAP), else null. */
export function handledPoints(geometry: Geometry | null): Point[] | null {
if (geometry?.type !== 'polygon') return null
return geometry.points.length > HANDLE_CAP ? null : geometry.points
}
/** The vertex `vertex` of `annotationId` is chosen, stamped with the current text (R-13). */
export function chooseVertex(annotationId: string, vertex: number): void {
const base = useEditorStore.getState().documentText
useAnnotationWork.setState({ chosen: { annotationId, vertex, base } })
}
/** The chosen vertex of `annotationId`, only when it was chosen on the current text. */
export function freshChosen(annotationId: string): number | null {
const { chosen } = useAnnotationWork.getState()
if (chosen?.annotationId !== annotationId) return null
const current = useEditorStore.getState().documentText
return chosen.base === current ? chosen.vertex : null
}
+480 -264
View File
File diff suppressed because it is too large. Load diff
+550 -288
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,120 @@
/** U2 Task 5: the polygon arithmetic of the vertex handles (R-7, R-9). */
import { describe, expect, it } from 'vitest'
import type { Point } from '@faunosteo/core-wasm/types'
import {
HANDLE_CAP,
MIN_VERTICES,
insertMidpoint,
isNoOpMove,
moveVertex,
removeVertex,
showsInsert,
} from '@/editor/annotations/polygonEdit'
const square: Point[] = [
[0, 0],
[10, 0],
[10, 10],
[0, 10],
]
describe('the limits', () => {
it('caps the handles at 40 vertices and keeps 3 at least', () => {
expect(HANDLE_CAP).toBe(40)
expect(MIN_VERTICES).toBe(3)
})
})
describe('insertMidpoint', () => {
it.each([
[0, [5, 0], 1],
[2, [5, 10], 3],
// The last segment wraps to the first vertex.
[3, [0, 5], 4],
] as const)('after %i adds %j at %i', (after, middle, at) => {
const next = insertMidpoint(square, after)!
expect(next).toHaveLength(5)
expect(next[at]).toEqual(middle)
})
it('rounds the midpoint to the 0.01 grid', () => {
const odd: Point[] = [
[0, 0],
[0.015, 0.025],
[5, 5],
]
expect(insertMidpoint(odd, 0)![1]).toEqual([0.01, 0.01])
})
it.each([-1, 4, 1.5, Number.NaN])('gives null for index %s', (index) => {
expect(insertMidpoint(square, index)).toBeNull()
})
})
describe('removeVertex', () => {
it('removes the vertex at the index', () => {
expect(removeVertex(square, 1)).toEqual([
[0, 0],
[10, 10],
[0, 10],
])
})
it('gives null at 3 vertices and out of range', () => {
expect(removeVertex(square.slice(0, 3), 0)).toBeNull()
expect(removeVertex(square, 4)).toBeNull()
expect(removeVertex(square, -1)).toBeNull()
})
})
describe('moveVertex', () => {
it('moves one vertex, rounded to 0.01', () => {
const next = moveVertex(square, 2, { x: 12.345, y: 9.999 })!
expect(next[2]).toEqual([12.35, 10])
expect(next[0]).toBe(square[0])
})
it.each([
{ x: Number.NaN, y: 1 },
{ x: 1, y: Number.POSITIVE_INFINITY },
])('gives null for a non-finite place %j', (to) => {
expect(moveVertex(square, 0, to)).toBeNull()
})
it('gives null out of range', () => {
expect(moveVertex(square, 9, { x: 1, y: 1 })).toBeNull()
})
})
describe('isNoOpMove', () => {
const movedTo = (index: number, x: number, y: number) =>
moveVertex(square, index, { x, y })!
it.each([
['itself', 1, 10, 0],
['the next vertex', 1, 10, 10],
['the previous vertex', 1, 0, 0],
// Wrapping both ways.
['the previous one across the start', 0, 0, 10],
['the next one across the end', 3, 0, 0],
] as const)('a release on %s is no change', (_, index, x, y) => {
expect(isNoOpMove(square, index, movedTo(index, x, y))).toBe(true)
})
it('a release elsewhere is a change, even on a vertex that is not a neighbour', () => {
expect(isNoOpMove(square, 0, movedTo(0, 3, 3))).toBe(false)
expect(isNoOpMove(square, 0, movedTo(0, 10, 10))).toBe(false)
})
})
describe('showsInsert (R-9)', () => {
it.each([
[20, 10, true],
[19.99, 10, false],
[44, 22, true],
[43.9, 22, false],
[0, 10, false],
])('a %s px segment with a %s px hit radius: %s', (segment, hit, shown) => {
expect(showsInsert(segment, hit)).toBe(shown)
})
})
@@ -50,7 +50,13 @@ describe('dropStale (R-13)', () => {
it('a new session (another sheet, the editor closed) resets the work', () => {
useAnnotationWork.setState({
mode: { kind: 'move', annotationId: 'a', started: true, base: 'one' },
mode: {
kind: 'move',
annotationId: 'a',
started: true,
base: 'one',
vertex: null,
},
})
useEditorStore.setState({ session: useEditorStore.getState().session + 1 })
expect(useAnnotationWork.getState().mode).toBeNull()
@@ -14,8 +14,10 @@ import DrawingGuardDialog from '@/components/editor/annotations/DrawingGuardDial
import { guardDrawing } from '@/editor/annotations/drawingGuard'
import {
resetWork,
markRedraw,
setModePreview,
startMove,
startRedraw,
} from '@/editor/annotations/workStore'
import { useLeaveGuardStore } from '@/state/leaveGuardStore'
@@ -160,3 +162,44 @@ describe('SignOutButton and a started move on the drawing (R-12)', () => {
expect(signOut).not.toHaveBeenCalled()
})
})
describe('SignOutButton and a started redraw (R-12)', () => {
beforeEach(() => {
useLeaveGuardStore.getState().setAsk(guardDrawing)
startRedraw('a', 'doc')
markRedraw(true)
})
afterEach(() => {
useLeaveGuardStore.getState().setAsk(null)
resetWork()
})
it('asks « Abandonner le nouveau tracé ? »; « Abandonner » signs out', async () => {
render(
<MemoryRouter>
<SignOutButton />
<DrawingGuardDialog />
</MemoryRouter>,
)
await click()
expect(
screen.getByRole('dialog', { name: 'Abandonner le nouveau tracé ?' }),
).toBeInTheDocument()
expect(signOut).not.toHaveBeenCalled()
await userEvent.click(screen.getByRole('button', { name: 'Abandonner' }))
await waitFor(() => expect(signOut).toHaveBeenCalledTimes(1))
})
it('an unstarted redraw signs out at once and ends', async () => {
markRedraw(false)
render(
<MemoryRouter>
<SignOutButton />
<DrawingGuardDialog />
</MemoryRouter>,
)
await click()
await waitFor(() => expect(signOut).toHaveBeenCalledTimes(1))
expect(screen.queryByRole('dialog')).toBeNull()
})
})
@@ -61,8 +61,28 @@ const props = {
const named = (id: string, cx: number, cy: number, r: number) =>
point(id, cx, cy, r)
const annotations = () => store.getState().previewState!.document.annotations
const nameOf = (id: string) =>
annotations().find((a: Annotation) => a.id === id)?.name?.fr
const geometryOf = (id: string) =>
annotations().find((a: Annotation) => a.id === id)?.geometry
/** The selection as the overlay draws it (U2 Task 5: no coordinate field in the panel). */
const shownCircle = () =>
screen.getByTestId('overlay-selection').querySelector('circle')!
/** A mouse drag of `el` from `from` to `to`, past the 4 px slop. */
function mouseDrag(el: Element, from: [number, number], to: [number, number]) {
const at = ([x, y]: [number, number], buttons = 1) => ({
clientX: x,
clientY: y,
pointerId: 1,
isPrimary: true,
button: 0,
buttons,
pointerType: 'mouse',
})
fireEvent.pointerDown(el, at(from))
fireEvent.pointerMove(el, at(to))
fireEvent.pointerUp(el, at(to, 0))
}
/** Screen = drawing: the overlay's inverse CTM is the identity in the page under test. */
function stubCtm(): void {
@@ -105,14 +125,12 @@ async function selectFromList(name: RegExp | string = /N/) {
}
describe('selection and the list', () => {
it('lists the view annotations, selects one and shows its exact stored numbers', async () => {
it('lists the view annotations, selects one and draws its exact stored numbers', async () => {
await mount({
text: insert(drawnText(), named('anno-a', 743.0451049804688, 50, 5)),
})
const panel = await selectFromList()
expect(within(panel).getByLabelText('Centre x')).toHaveValue(
'743.0451049804688',
)
await selectFromList()
expect(shownCircle()).toHaveAttribute('cx', '743.0451049804688')
expect(screen.getByTestId('edit-strip-detail')).toHaveTextContent('Point')
})
@@ -126,52 +144,37 @@ describe('selection and the list', () => {
})
})
describe('a numeric edit', () => {
it('commits only when the typed number differs from the stored one', async () => {
describe('an edit on the drawing (U2 Task 5: the numeric group left the panel)', () => {
it('commits only when the shape changes', async () => {
await mount()
const panel = await selectFromList()
const user = userEvent.setup()
await selectFromList()
const version = store.getState().handleVersion
const cx = within(panel).getByLabelText('Centre x')
await user.click(cx)
await user.keyboard('{Enter}')
const handle = screen.getByTestId('point-handle')
fireEvent.keyDown(handle, { key: 'Enter' })
expect(store.getState().handleVersion).toBe(version)
await user.clear(cx)
await user.type(cx, '60{Enter}')
fireEvent.keyDown(handle, { key: 'ArrowRight' })
fireEvent.keyDown(handle, { key: 'Enter' })
expect(geometryOf('anno-a')).toEqual({
type: 'circle',
cx: 60,
cx: 50.5,
cy: 50,
r: 5,
})
expect(store.getState().handleVersion).toBe(version + 1)
})
it('keeps a refused value as « non appliqué » with the document unchanged, then applies a coherent set', async () => {
it('a refused place keeps the stored shape, then a place inside the frame repairs it', async () => {
await mount({ text: insert(drawnText(), named('anno-a', 150, 150, 5)) })
const panel = await selectFromList()
const user = userEvent.setup()
const before = store.getState().documentText
expect(
within(panel).getByTestId('annotation-geometry-issues'),
).toBeInTheDocument()
const cx = within(panel).getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '50{Enter}')
mouseDrag(pointHandle(), [150, 150], [50, 150])
expect(store.getState().documentText).toBe(before)
expect(within(panel).getByText('non appliqué')).toBeInTheDocument()
expect(
within(panel).getByText(/Valeurs non appliquées/),
).toBeInTheDocument()
expect(
within(panel).getByRole('button', {
name: 'Revenir aux valeurs enregistrées',
}),
).toBeInTheDocument()
expect(within(panel).getByLabelText('Centre x')).toHaveValue('50')
const cy = within(panel).getByLabelText('Centre y')
await user.clear(cy)
await user.type(cy, '50{Enter}')
expect(screen.getByTestId('overlay-refused-place')).toBeInTheDocument()
expect(shownCircle()).toHaveAttribute('cx', '150')
mouseDrag(pointHandle(), [150, 150], [50, 50])
expect(geometryOf('anno-a')).toEqual({
type: 'circle',
cx: 50,
@@ -181,19 +184,17 @@ describe('a numeric edit', () => {
expect(screen.queryByTestId('annotation-geometry-issues')).toBeNull()
})
it('reverts the group to the saved values', async () => {
await mount({ text: insert(drawnText(), named('anno-a', 150, 150, 5)) })
const panel = await selectFromList()
const user = userEvent.setup()
const cx = within(panel).getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '50{Enter}')
await user.click(
within(panel).getByRole('button', {
name: 'Revenir aux valeurs enregistrées',
}),
)
expect(within(panel).getByLabelText('Centre x')).toHaveValue('150')
it('Escape drops a pending series: the stored shape shows again', async () => {
await mount({ text: insert(drawnText(), named('anno-a', 50, 50, 5)) })
await selectFromList()
const before = store.getState().documentText
const handle = screen.getByTestId('point-handle')
fireEvent.keyDown(handle, { key: 'ArrowRight' })
expect(shownCircle()).toHaveAttribute('cx', '50.5')
// This mount has no workspace wrapper: Escape is pressed with nothing focused.
fireEvent.keyDown(document.body, { key: 'Escape' })
expect(shownCircle()).toHaveAttribute('cx', '50')
expect(store.getState().documentText).toBe(before)
})
})
@@ -307,8 +308,8 @@ describe('the point tool and the corrected position (C26)', () => {
})
expect(panel).not.toBeInTheDocument()
expect(screen.queryByTestId('overlay-click-cross')).toBeNull()
const props = await screen.findByTestId('annotation-properties')
expect(within(props).getByLabelText('Centre x')).toHaveValue('15')
await screen.findByTestId('annotation-properties')
expect(shownCircle()).toHaveAttribute('cx', '15')
})
it('keeps the pending point at the click when the correction is cancelled', async () => {
@@ -495,12 +496,9 @@ describe('an unmeasured view (C32)', () => {
screen.getAllByText(/Ce dessin n'est pas mesurable/).length,
).toBeGreaterThan(0)
const panel = await selectFromList()
expect(
within(panel).queryByRole('textbox', { name: 'Centre x' }),
).toBeNull()
expect(
within(panel).getByText('Centre x', { exact: false }),
).toBeInTheDocument()
// Nothing edits the geometry of an unmeasured view: no handle, no field.
expect(screen.queryByTestId('point-handle')).toBeNull()
expect(within(panel).queryByRole('textbox', { name: /^Centre/ })).toBeNull()
expect(
within(panel).getByText(/Ce dessin n'est pas mesurable/),
).toBeInTheDocument()
@@ -657,14 +655,13 @@ describe('polygons and paths', () => {
const zoneText = (geometry: object) =>
insert(drawnText(), { kind: 'annotation', value: zoneAnnotation(geometry) })
it('adds and removes a vertex as part of the whole group', async () => {
const handleHit = (name: string) =>
screen.getByRole('button', { name }).querySelector('[data-handle]')!
it('« + » adds a vertex on the drawing and « − » removes it', async () => {
await mount({ text: zoneText({ type: 'polygon', points: triangle }) })
const panel = await selectFromList()
const user = userEvent.setup()
await user.click(within(panel).getByLabelText('x du sommet 1'))
await user.click(
within(panel).getByRole('button', { name: 'Ajouter un sommet' }),
)
await selectFromList()
pressAt(handleHit('Ajouter un sommet après le sommet 1'), 50, 20)
expect(geometryOf('zone-a')).toMatchObject({
points: [
[20, 20],
@@ -673,18 +670,17 @@ describe('polygons and paths', () => {
[50, 80],
],
})
await user.click(within(panel).getByRole('button', { name: 'Retirer' }))
expect(geometryOf('zone-a')).toMatchObject({
points: triangle.slice(0, 3).map((p, i) => (i === 0 ? [50, 20] : p)),
})
pressAt(handleHit('Retirer le sommet 2'), 50, 10)
expect(geometryOf('zone-a')).toMatchObject({ points: triangle })
})
it('never offers to remove a vertex below three', async () => {
it('never removes a vertex below three: « − » is greyed', async () => {
await mount({ text: zoneText({ type: 'polygon', points: triangle }) })
const panel = await selectFromList()
await selectFromList()
pressAt(handleHit('Sommet 1'), 20, 20)
expect(
within(panel).getByRole('button', { name: 'Retirer' }),
).toBeDisabled()
screen.getByRole('button', { name: 'Retirer le sommet 1' }),
).toHaveAttribute('aria-disabled', 'true')
})
it('moves a selected polygon as a block', async () => {
@@ -857,7 +853,7 @@ describe('refusals through the tab (H8)', () => {
const zoneText = (geometry: object) =>
insert(drawnText(), { kind: 'annotation', value: zoneAnnotation(geometry) })
it('a refused « Remplacer par un polygone » drops the tracing, shows the core message', async () => {
it('a refused « Remplacer par un polygone » keeps the tracing open, with the core message', async () => {
const path = { type: 'path', d: 'M 20 20 L 80 20 L 50 80 Z' }
await mount({ text: zoneText(path) })
const panel = await selectFromList()
@@ -874,35 +870,31 @@ describe('refusals through the tab (H8)', () => {
].forEach(([x, y]) => pressAt(canvas, x, y))
fireEvent.keyDown(canvas, { key: 'Enter' })
expect(await screen.findByRole('alert')).toBeInTheDocument()
// Board 33 A: the tracing stays open with its commands (it was dropped before Task 5).
expect(
screen.queryByRole('button', { name: 'Annuler le tracé' }),
).toBeNull()
screen.getByRole('button', { name: 'Annuler le tracé' }),
).toBeInTheDocument()
expect(screen.getByTestId('edit-strip-title')).toHaveTextContent(
'Fermeture refusée',
)
expect(geometryOf('zone-a')).toEqual(path)
})
it('a refused vertex add and a refused remove stay « non appliqué », document unchanged', async () => {
it('a refused vertex move restores the shape exactly, document unchanged', async () => {
await mount({
text: zoneText({ type: 'polygon', points: [...triangle, [20, 60]] }),
})
const panel = await selectFromList()
const user = userEvent.setup()
await selectFromList()
const before = store.getState().documentText
const x = within(panel).getByLabelText('x du sommet 1')
await user.clear(x)
await user.type(x, '500{Enter}')
await user.click(
within(panel).getByRole('button', { name: 'Ajouter un sommet' }),
const vertex = screen
.getByRole('button', { name: 'Sommet 1' })
.querySelector('[data-handle]')!
mouseDrag(vertex, [20, 20], [500, 20])
expect(store.getState().documentText).toBe(before)
expect(screen.getByTestId('overlay-refused-place')).toBeInTheDocument()
expect(screen.getByTestId('gesture-line')).toHaveTextContent(
'Déplacement refusé',
)
expect(store.getState().documentText).toBe(before)
expect(within(panel).getAllByLabelText(/^x du sommet/)).toHaveLength(5)
expect(
within(panel).getByText(/Valeurs non appliquées/),
).toBeInTheDocument()
await user.click(within(panel).getByRole('button', { name: 'Retirer' }))
expect(store.getState().documentText).toBe(before)
expect(
within(panel).getByText(/Valeurs non appliquées/),
).toBeInTheDocument()
})
})
@@ -1038,12 +1030,12 @@ describe('« Désélectionner » (R1, A6)', () => {
await mountSpy()
const panel = await selectFromList()
const user = userEvent.setup()
await user.clear(within(panel).getByLabelText('Centre x'))
await user.type(within(panel).getByLabelText('Centre x'), '60{Enter}')
expect(geometryOf('anno-a')).toMatchObject({ cx: 60 })
await user.clear(within(panel).getByLabelText('Nom (FR)'))
await user.type(within(panel).getByLabelText('Nom (FR)'), 'Nuque{Enter}')
expect(nameOf('anno-a')).toBe('Nuque')
await user.click(button(panel))
act(() => void store.getState().undoStep())
expect(geometryOf('anno-a')).toMatchObject({ cx: 50 })
expect(nameOf('anno-a')).toBe('N')
})
it('read-only: no « Supprimer », it deselects and focuses the ro- row', async () => {
@@ -1065,23 +1057,22 @@ describe('« Désélectionner » (R1, A6)', () => {
await mountSpy()
const panel = await selectFromList()
const user = userEvent.setup()
const cx = within(panel).getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '60')
const name = within(panel).getByLabelText('Nom (FR)')
await user.clear(name)
await user.type(name, 'Nuque')
const depth = store.getState().undo.length
await user.click(button(panel))
expect(geometryOf('anno-a')).toMatchObject({ cx: 60 })
expect(nameOf('anno-a')).toBe('Nuque')
expect(store.getState().undo.length).toBe(depth + 1)
})
it('a refused typed value: the panel closes, the document is unchanged', async () => {
await mountSpy({ text: insert(drawnText(), named('anno-a', 150, 150, 5)) })
await mountSpy()
const panel = await selectFromList()
const user = userEvent.setup()
const before = store.getState().documentText
const cx = within(panel).getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '1000000')
// A blank name is refused (both names are required).
await user.clear(within(panel).getByLabelText('Nom (FR)'))
await user.click(button(panel))
expect(screen.queryByTestId('annotation-properties')).toBeNull()
expect(store.getState().documentText).toBe(before)
@@ -1585,40 +1576,39 @@ describe('a tap on the drawing (D6b)', () => {
it('undo after a tap deselect undoes the earlier edit, redo restores it', async () => {
await selected()
const user = userEvent.setup()
const cx = screen.getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '60{Enter}')
const name = screen.getByLabelText('Nom (FR)')
await user.clear(name)
await user.type(name, 'Nuque{Enter}')
tap(rect())
act(() => void store.getState().undoStep())
expect(geometryOf('anno-a')).toMatchObject({ cx: 50 })
expect(nameOf('anno-a')).toBe('N')
act(() => void store.getState().redoStep())
expect(geometryOf('anno-a')).toMatchObject({ cx: 60 })
expect(nameOf('anno-a')).toBe('Nuque')
})
it('commits a typed valid value once and deselects when the press blurs the field', async () => {
await selected()
const user = userEvent.setup()
const cx = screen.getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '60')
const name = screen.getByLabelText('Nom (FR)')
await user.clear(name)
await user.type(name, 'Nuque')
const depth = store.getState().undo.length
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
// What mousedown does: the focus moves to the box, the field commits, the drawing rebuilds.
act(() => box().focus())
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.click(rect())
expect(geometryOf('anno-a')).toMatchObject({ cx: 60 })
expect(nameOf('anno-a')).toBe('Nuque')
expect(store.getState().undo.length).toBe(depth + 1)
expect(isDeselected()).toBe(true)
})
it('a refused typed value: the panel closes, the document is unchanged', async () => {
await selected({ text: insert(drawnText(), named('anno-a', 150, 150, 5)) })
await selected()
const user = userEvent.setup()
const before = store.getState().documentText
const cx = screen.getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '1000000')
// A blank name is refused (both names are required).
await user.clear(screen.getByLabelText('Nom (FR)'))
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
act(() => box().focus())
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
@@ -1815,10 +1805,10 @@ describe('the strip', () => {
await selectFromList()
drag(marker('anno-a'), [60, 40])
expect(line()).toHaveTextContent('Point déplacé')
const cx = screen.getByLabelText('Centre x')
const name = screen.getByLabelText('Nom (FR)')
const user = userEvent.setup()
await user.clear(cx)
await user.type(cx, '30{Enter}')
await user.clear(name)
await user.type(name, 'Nuque{Enter}')
expect(line()).not.toHaveTextContent('Point déplacé')
drag(marker('anno-a'), [40, 40])
expect(line()).toHaveTextContent('Point déplacé')
+21 -3
View File
@@ -14,7 +14,7 @@ import type { Annotation } from '@faunosteo/core-wasm/types'
import ModalDialog from '@/components/ui/ModalDialog'
import { useLocaleStore } from '@/state/localeStore'
import { drawnText, edit, insert, point } from '../helpers/editorFixtures'
import { resetStore, serverHas, store } from '../helpers/editorHarness'
import { pressAt, resetStore, serverHas, store } from '../helpers/editorHarness'
import { openFinding } from '../helpers/findingDialog'
import { mountDraft, setWidth } from '../helpers/editorRoute'
@@ -240,14 +240,32 @@ describe('Escape leaves alone', () => {
expect(store.getState().documentText).toBe(before)
})
it('a tracing: the strip tracing commands keep their Escape, the canvas box cancels the tracing only', async () => {
it('a new zone tracing: the strip tracing commands keep their Escape (Task 7 asks)', async () => {
const user = await mount(ZONE())
await user.click(screen.getByRole('button', { name: 'Zone' }))
pressAt(canvasBox(), 20, 20)
const bar = await screen.findByTestId('tracing-commands')
bar.focus()
escape(bar)
expect(screen.queryByTestId('tracing-commands')).not.toBeNull()
})
// U2 Task 5 (R-12, board 32 row 4): « Remplacer par un polygone » is a redraw, which
// Escape cancels at once from anywhere in the workspace, the strip's commands included
// (before Task 5 only the canvas box did). The selection stays.
it('a redraw: Escape on the strip commands or on the canvas box cancels the tracing only', async () => {
const user = await mount(ZONE())
await select(user, 'zone-a')
await user.click(inPanel('Remplacer par un polygone'))
const bar = await screen.findByTestId('tracing-commands')
bar.focus()
escape(bar)
expect(screen.queryByTestId('tracing-commands')).not.toBeNull()
await waitFor(() =>
expect(screen.queryByTestId('tracing-commands')).toBeNull(),
)
expect(panel()).toBeDefined()
await user.click(inPanel('Remplacer par un polygone'))
await screen.findByTestId('tracing-commands')
canvasBox().focus()
escape(canvasBox())
await waitFor(() =>
@@ -135,7 +135,11 @@ describe('focus requests', () => {
)
// anno-b and anno-a share a name: the circle's centre tells which one is selected.
const properties = await screen.findByTestId('annotation-properties')
expect(within(properties).getByLabelText('Centre x')).toHaveValue('20')
expect(properties).toBeInTheDocument()
// U2 Task 5: no coordinate field in the panel; the overlay draws the selection.
expect(
screen.getByTestId('overlay-selection').querySelector('circle'),
).toHaveAttribute('cx', '20')
await waitFor(() =>
expect(document.activeElement).toHaveAttribute('data-properties-heading'),
)
+25 -11
View File
@@ -17,6 +17,7 @@ import { usePlaceVisible } from '@/lib/placeVisibility'
import { FocusConsumedContext } from '@/editor/focusRequest'
import { targetOfKey } from '@/editor/navigation'
import { useLocaleStore } from '@/state/localeStore'
import { useAnnotationWork } from '@/editor/annotations/workStore'
import { cleanSvg } from '@/editor/core/cleaning'
import {
ASSET,
@@ -512,7 +513,9 @@ describe('« Aller à » while a creation or a tracing is in progress', () => {
expect(liveText()).toContain('tracé est en cours')
})
it('a « Remplacer par un polygone » tracing is kept and focused (it cannot coexist with a pending creation)', async () => {
// U2 Task 5 (R-12): « Remplacer par un polygone » is a redraw mode. With nothing placed a
// tab ends it at once; with a vertex placed the tab asks first and « Continuer » keeps it.
it('a « Remplacer par un polygone » redraw: ended by a tab when empty, asked once a vertex is placed', async () => {
const zone = point('zone-a', 0, 0, 1)
const zoneValue = {
...zone.value,
@@ -524,22 +527,33 @@ describe('« Aller à » while a creation or a tracing is in progress', () => {
value: zoneValue,
} as typeof zone)
const user = await mount(text)
await gotoBare(user, async () => {
const drawing = inPlace('annotations.drawing')
const list = drawing.getByRole('list', { name: 'Annotations de la vue' })
await user.click(within(list).getAllByRole('button')[0])
const drawing = inPlace('annotations.drawing')
const replace = async () => {
await user.click(
await drawing.findByRole('button', {
name: 'Remplacer par un polygone',
}),
)
expect(drawing.getByTestId('tracing-commands')).toBeVisible()
})
const bar = within(place('annotations.drawing')).getByTestId(
'tracing-commands',
)
await waitFor(() => expect(document.activeElement).toBe(bar))
expect(liveText()).toContain('tracé est en cours')
}
const list = drawing.getByRole('list', { name: 'Annotations de la vue' })
await user.click(within(list).getAllByRole('button')[0])
await replace()
await user.click(tab(/Vérification/))
expect(tab(/Vérification/)).toHaveAttribute('aria-selected', 'true')
expect(useAnnotationWork.getState().mode).toBeNull()
await user.click(tab('Annotations'))
await replace()
pressAt(screen.getByTestId('annotation-canvas'), 20, 20)
await user.click(tab(/Vérification/))
expect(
await screen.findByRole('dialog', {
name: 'Abandonner le nouveau tracé ?',
}),
).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Continuer' }))
expect(tab('Annotations')).toHaveAttribute('aria-selected', 'true')
expect(drawing.getByTestId('tracing-commands')).toBeVisible()
})
it('a pending creation is kept and focused', async () => {
@@ -0,0 +1,676 @@
/** U2 Task 5: vertices, « + », « − », zone move, redraw, paths and the handle cap. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
act,
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 { answerDrawing, guardDrawing } from '@/editor/annotations/drawingGuard'
import { useAnnotationWork, resetWork } from '@/editor/annotations/workStore'
import { useUndoShortcuts } from '@/editor/useUndoShortcuts'
import { useLocaleStore } from '@/state/localeStore'
import { drawnText, insert, point } from '../helpers/editorFixtures'
import { openReady, pressAt, resetStore, store } 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(),
}
function UndoKeys() {
useUndoShortcuts(true)
return null
}
const annotations = () => store.getState().previewState!.document.annotations
const annotationOf = (id: string) =>
annotations().find((a: Annotation) => a.id === id)!
const pointsOf = (id: string) => {
const geometry = annotationOf(id).geometry
return geometry?.type === 'polygon' ? geometry.points : null
}
const depth = () => store.getState().undo.length
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 zone = (id: string, geometry: object): Annotation =>
({
...(point(id, 0, 0, 1).value as Annotation),
kind: 'zone',
geometry,
}) as Annotation
const withZone = (text: string, id: string, geometry: object) =>
insert(text, { kind: 'annotation', value: zone(id, geometry) })
const squareText = (points: Point[] = SQUARE) =>
withZone(drawnText(), 'z', { type: 'polygon', points })
const tab = (readOnly = false) => (
<div data-editor-workspace>
<AnnotationsTab {...props} readOnly={readOnly} />
</div>
)
async function mount(text: string) {
await openReady({ text })
const view = render(tab())
await waitFor(() =>
expect(
screen.getByTestId('annotation-canvas-drawing').querySelector('svg'),
).not.toBeNull(),
)
return view
}
async function select(index = 0) {
const list = await screen.findByRole('list', {
name: 'Annotations de la vue',
})
await userEvent.setup().click(within(list).getAllByRole('button')[index])
return screen.findByTestId('annotation-properties')
}
const mouse = {
pointerId: 1,
isPrimary: true,
button: 0,
buttons: 1,
pointerType: 'mouse',
}
/** The hit shape of a handle: the press machine reads its `data-handle`. */
const hitOf = (name: string) =>
screen.getByRole('button', { name }).querySelector('[data-handle]')!
const vertex = (n: number) =>
screen.getByRole('button', { name: `Sommet ${n}` })
const plus = (n: number) =>
screen.getByRole('button', { name: `Ajouter un sommet après le sommet ${n}` })
const minus = (n: number) =>
screen.getByRole('button', { name: `Retirer le sommet ${n}` })
const clickHandle = (name: string, at: [number, number] = [0, 0]) =>
pressAt(hitOf(name), at[0], at[1])
const marker = (id: string) =>
screen
.getByTestId('annotation-canvas-drawing')
.querySelector(`[data-anno-id="${id}"]`)!
const detail = () => screen.getByTestId('edit-strip-detail')
const message = () => screen.getByTestId('gesture-line')
const chosen = () => useAnnotationWork.getState().chosen
function drag(el: Element, from: [number, number], to: [number, number]) {
const [x0, y0] = from
const [x1, y1] = to
fireEvent.pointerDown(el, { ...mouse, clientX: x0, clientY: y0 })
fireEvent.pointerMove(el, { ...mouse, clientX: x1, clientY: y1 })
fireEvent.pointerUp(el, { ...mouse, buttons: 0, clientX: x1, clientY: y1 })
}
describe('a vertex (R-9)', () => {
it('a click chooses it, stamped; the strip says it; the interior unchooses it', async () => {
await mount(squareText())
await select()
expect(detail()).toHaveTextContent('Zone · 4 sommets')
clickHandle('Sommet 2', [80, 20])
expect(chosen()).toEqual({
annotationId: 'z',
vertex: 1,
base: store.getState().documentText,
})
expect(detail()).toHaveTextContent('Zone · 4 sommets · sommet 2 choisi')
expect(minus(2)).toBeInTheDocument()
pressAt(marker('z'), 50, 50)
expect(chosen()).toBeNull()
expect(
screen.queryByRole('button', { name: /^Retirer le sommet/ }),
).toBeNull()
})
it('a drag commits once; a release on a neighbour commits nothing', async () => {
await mount(squareText())
await select()
const before = depth()
drag(hitOf('Sommet 2'), [80, 20], [90, 10])
expect(pointsOf('z')![1]).toEqual([90, 10])
expect(depth()).toBe(before + 1)
expect(message()).toHaveTextContent('Sommet déplacé')
drag(hitOf('Sommet 2'), [90, 10], [80, 80])
expect(pointsOf('z')![1]).toEqual([90, 10])
expect(depth()).toBe(before + 1)
})
it('« + » inserts at the midpoint and chooses the new vertex', async () => {
await mount(squareText())
await select()
const before = depth()
clickHandle('Ajouter un sommet après le sommet 1', [50, 20])
expect(pointsOf('z')).toEqual([[20, 20], [50, 20], ...SQUARE.slice(1)])
expect(depth()).toBe(before + 1)
expect(chosen()).toMatchObject({ vertex: 1 })
expect(chosen()!.base).toBe(store.getState().documentText)
expect(detail()).toHaveTextContent('sommet 2 choisi')
expect(message()).toHaveTextContent('Sommet ajouté')
})
it('undo after « + » drops the chosen vertex: « − » removes nothing stale (Review Focus 2)', async () => {
await mount(squareText())
render(<UndoKeys />)
await select()
clickHandle('Ajouter un sommet après le sommet 1', [50, 20])
const bubble = hitOf('Retirer le sommet 2')
fireEvent.keyDown(document.body, { key: 'z', ctrlKey: true })
expect(pointsOf('z')).toEqual(SQUARE)
expect(chosen()).toBeNull()
expect(
screen.queryByRole('button', { name: /^Retirer le sommet/ }),
).toBeNull()
const after = depth()
pressAt(bubble, 50, 20)
fireEvent.keyDown(vertex(2), { key: 'Delete' })
expect(pointsOf('z')).toEqual(SQUARE)
expect(depth()).toBe(after)
})
it('« − » removes the chosen vertex', async () => {
await mount(squareText())
await select()
clickHandle('Sommet 3', [80, 80])
clickHandle('Retirer le sommet 3', [80, 70])
expect(pointsOf('z')).toEqual([SQUARE[0], SQUARE[1], SQUARE[3]])
expect(chosen()).toBeNull()
expect(message()).toHaveTextContent('Sommet retiré')
})
it('« − » is disabled at 3 with its reason; nothing is removed', async () => {
const triangle = SQUARE.slice(0, 3)
await mount(squareText(triangle))
await select()
const before = depth()
clickHandle('Sommet 1', [20, 20])
expect(minus(1)).toHaveAttribute('aria-disabled', 'true')
clickHandle('Retirer le sommet 1', [20, 10])
expect(pointsOf('z')).toEqual(triangle)
expect(depth()).toBe(before)
expect(message()).toHaveTextContent('Une zone garde au moins 3 sommets')
})
it('keys: focus chooses, arrows preview, Enter commits; Insert adds, Delete removes', async () => {
await mount(squareText())
await select()
const before = depth()
vertex(1).focus()
expect(chosen()).toMatchObject({ vertex: 0 })
fireEvent.keyDown(vertex(1), { key: 'ArrowRight' })
expect(pointsOf('z')![0]).toEqual([20, 20])
fireEvent.keyDown(vertex(1), { key: 'Enter' })
expect(pointsOf('z')![0]).toEqual([20.5, 20])
expect(depth()).toBe(before + 1)
fireEvent.keyDown(vertex(1), { key: 'Insert' })
expect(pointsOf('z')).toHaveLength(5)
expect(pointsOf('z')![1]).toEqual([50.25, 20])
expect(chosen()).toMatchObject({ vertex: 1 })
fireEvent.keyDown(vertex(2), { key: 'Delete' })
expect(pointsOf('z')).toHaveLength(4)
expect(depth()).toBe(before + 3)
})
it('Enter on a « + » inserts; Tab walks the handles, « + » included', async () => {
await mount(squareText())
await select()
const order = screen
.getAllByRole('button')
.filter((b) => b.closest('[data-testid="handle-layer"]'))
.map((b) => b.getAttribute('aria-label'))
expect(order).toContain('Ajouter un sommet après le sommet 4')
expect(order).toContain('Sommet 4')
fireEvent.keyDown(plus(4), { key: 'Enter' })
expect(pointsOf('z')).toHaveLength(5)
expect(pointsOf('z')![4]).toEqual([20, 50])
})
})
describe('a double click on a handle (R-8, carried Task 2 gap)', () => {
const twice = (el: Element, x: number, y: number) => {
pressAt(el, x, y)
pressAt(el, x, y)
}
it('on « + »: one insert, never a second', async () => {
await mount(squareText())
await select()
const before = depth()
twice(hitOf('Ajouter un sommet après le sommet 1'), 50, 20)
expect(pointsOf('z')).toHaveLength(5)
expect(depth()).toBe(before + 1)
})
it('on a vertex: chosen once, the second click runs no handle action', async () => {
await mount(squareText())
await select()
const spy = vi.spyOn(useAnnotationWork, 'setState')
twice(hitOf('Sommet 2'), 80, 20)
const choices = spy.mock.calls.filter(
([patch]) => typeof patch === 'object' && 'chosen' in patch,
)
spy.mockRestore()
expect(choices).toHaveLength(1)
expect(chosen()).toMatchObject({ vertex: 1 })
})
it('on « − »: one removal, never a second', async () => {
await mount(squareText([...SQUARE, [10, 50]]))
await select()
clickHandle('Sommet 2', [80, 20])
const before = depth()
const bubble = hitOf('Retirer le sommet 2')
pressAt(bubble, 80, 10)
pressAt(bubble, 80, 10)
expect(pointsOf('z')).toHaveLength(4)
expect(depth()).toBe(before + 1)
})
})
describe('moving the zone (A11, R-12)', () => {
it('the interior dragged by mouse moves the zone once', async () => {
await mount(squareText())
await select()
const before = depth()
drag(marker('z'), [50, 50], [60, 55])
expect(pointsOf('z')![0]).toEqual([30, 25])
expect(depth()).toBe(before + 1)
expect(message()).toHaveTextContent('Zone déplacée')
})
it('« Déplacer la zone » moves it whole; « Valider la position » commits once', async () => {
await mount(squareText())
await select()
const before = depth()
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Déplacer la zone' }))
expect(screen.getByTestId('edit-strip-title')).toHaveTextContent(
'Déplacer la zone',
)
const bar = screen.getByTestId('move-mode-bar')
fireEvent.click(
within(bar).getByRole('button', { name: 'Déplacer vers la droite' }),
)
expect(pointsOf('z')).toEqual(SQUARE)
fireEvent.click(
within(bar).getByRole('button', { name: 'Valider la position' }),
)
expect(pointsOf('z')).toEqual(SQUARE.map(([x, y]) => [x + 0.5, y]))
expect(depth()).toBe(before + 1)
})
it('« Déplacer le sommet » moves the chosen vertex only', async () => {
await mount(squareText())
await select()
clickHandle('Sommet 3', [80, 80])
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Déplacer le sommet' }))
expect(screen.getByTestId('edit-strip-title')).toHaveTextContent(
'Déplacer le sommet',
)
const bar = screen.getByTestId('move-mode-bar')
fireEvent.click(
within(bar).getByRole('button', { name: 'Déplacer vers le bas' }),
)
fireEvent.click(
within(bar).getByRole('button', { name: 'Valider la position' }),
)
expect(pointsOf('z')).toEqual([SQUARE[0], SQUARE[1], [80, 80.5], SQUARE[3]])
})
})
describe('the handle cap (R-7, T18)', () => {
const many = (n: number): Point[] =>
Array.from({ length: n }, (_, i) => {
const angle = (2 * Math.PI * i) / n
return [
Math.round((50 + 30 * Math.cos(angle)) * 100) / 100,
Math.round((50 + 30 * Math.sin(angle)) * 100) / 100,
]
})
it('41 vertices: the outline, the cap message, no handle; move and redraw remain', async () => {
await mount(squareText(many(41)))
await select()
expect(screen.queryByRole('button', { name: /^Sommet / })).toBeNull()
expect(
screen.queryByRole('button', { name: /^Ajouter un sommet après/ }),
).toBeNull()
expect(screen.getByTestId('overlay-selection')).toBeInTheDocument()
expect(detail()).toHaveTextContent(
'Zone · 41 sommets, trop pour les poignées',
)
expect(
screen.getByRole('button', { name: 'Déplacer la zone' }),
).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Redessiner' }),
).toBeInTheDocument()
})
it('40 vertices still have their handles', async () => {
await mount(squareText(many(40)))
await select()
expect(screen.getAllByRole('button', { name: /^Sommet / })).toHaveLength(40)
})
})
describe('paths (UX_TESTS « Paths »)', () => {
const PATH = { type: 'path', d: 'M 20 20 L 80 20 L 50 80 Z' }
const pathAndZone = () =>
withZone(withZone(drawnText(), 'p', PATH), 'z', {
type: 'polygon',
points: [
[55, 55],
[90, 55],
[90, 90],
[55, 90],
],
})
it('show no handle and offer « Remplacer par un polygone »', async () => {
await mount(pathAndZone())
const panel = await select(0)
expect(screen.queryByRole('button', { name: /^Sommet / })).toBeNull()
expect(
within(panel).getByRole('button', { name: 'Remplacer par un polygone' }),
).toBeInTheDocument()
})
it('keep their `d` byte-identical after gestures on a neighbour', async () => {
await mount(pathAndZone())
const before = JSON.stringify(annotationOf('p').geometry)
await select(1)
clickHandle('Ajouter un sommet après le sommet 1', [72.5, 55])
clickHandle('Sommet 2', [72.5, 55])
clickHandle('Retirer le sommet 2', [72.5, 45])
drag(hitOf('Sommet 1'), [55, 55], [60, 60])
drag(marker('z'), [80, 80], [85, 85])
expect(depth()).toBe(4)
expect(JSON.stringify(annotationOf('p').geometry)).toBe(before)
})
})
describe('redraw (R-12, board 06 C)', () => {
const canvas = () => screen.getByTestId('annotation-canvas')
const TRACE: [number, number][] = [
[30, 30],
[70, 30],
[70, 70],
[30, 70],
]
async function redrawing() {
await mount(squareText())
await select()
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Redessiner' }))
}
it('keeps the old outline during the trace, no handle; a close commits once and keeps every property', async () => {
await redrawing()
const kept = { ...annotationOf('z'), geometry: null }
expect(useAnnotationWork.getState().mode).toMatchObject({
kind: 'redraw',
started: false,
})
expect(screen.getByTestId('edit-strip-title')).toHaveTextContent(
'Redessiner · N',
)
expect(screen.queryByRole('button', { name: /^Sommet / })).toBeNull()
const before = depth()
TRACE.forEach(([x, y]) => pressAt(canvas(), x, y))
expect(screen.getByTestId('overlay-old-place')).toBeInTheDocument()
expect(useAnnotationWork.getState().mode?.started).toBe(true)
expect(pointsOf('z')).toEqual(SQUARE)
fireEvent.click(screen.getByRole('button', { name: 'Fermer le tracé' }))
expect(pointsOf('z')).toEqual(TRACE)
expect({ ...annotationOf('z'), geometry: null }).toEqual(kept)
expect(depth()).toBe(before + 1)
expect(useAnnotationWork.getState().mode).toBeNull()
expect(message()).toHaveTextContent('Zone redessinée')
expect(
screen.queryByText('Nouveau tracé abandonné : la fiche a changé.'),
).toBeNull()
})
it('a click within 12 px of the first vertex closes it (R-11)', async () => {
await redrawing()
TRACE.slice(0, 3).forEach(([x, y]) => pressAt(canvas(), x, y))
pressAt(canvas(), 38, 30)
expect(pointsOf('z')).toEqual(TRACE.slice(0, 3))
})
it('a refusal (too small to touch) keeps the trace open with the core message', async () => {
await redrawing()
const sliver: [number, number][] = [
[20, 50],
[80, 50],
[80, 50.5],
]
sliver.forEach(([x, y]) => pressAt(canvas(), x, y))
fireEvent.click(screen.getByRole('button', { name: 'Fermer le tracé' }))
expect(pointsOf('z')).toEqual(SQUARE)
expect(
screen.getByRole('button', { name: 'Fermer le tracé' }),
).toBeInTheDocument()
expect(screen.getByTestId('edit-strip-notice')).toHaveTextContent(
/too small/,
)
expect(screen.getByTestId('edit-strip-title')).toHaveTextContent(
'Fermeture refusée',
)
expect(useAnnotationWork.getState().mode).toMatchObject({
kind: 'redraw',
started: true,
})
})
it('Escape and « Annuler le tracé » cancel at once and keep the old shape', async () => {
await redrawing()
pressAt(canvas(), 30, 30)
fireEvent.keyDown(document.body, { key: 'Escape' })
expect(useAnnotationWork.getState().mode).toBeNull()
expect(screen.queryByRole('button', { name: 'Fermer le tracé' })).toBeNull()
expect(useAnnotationWork.getState().question).toBeNull()
expect(pointsOf('z')).toEqual(SQUARE)
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Redessiner' }))
pressAt(canvas(), 30, 30)
fireEvent.click(screen.getByRole('button', { name: 'Annuler le tracé' }))
expect(useAnnotationWork.getState().mode).toBeNull()
expect(pointsOf('z')).toEqual(SQUARE)
})
it('removing the last vertex back to none makes it unstarted again', async () => {
await redrawing()
pressAt(canvas(), 30, 30)
expect(useAnnotationWork.getState().mode?.started).toBe(true)
fireEvent.click(
screen.getByRole('button', { name: 'Retirer le dernier sommet' }),
)
expect(useAnnotationWork.getState().mode?.started).toBe(false)
})
it('the guard: Back before the first vertex ends it at once; after one, it asks', async () => {
await redrawing()
const back = vi.fn()
let allowed = false
act(() => void (allowed = guardDrawing(back)))
expect(allowed).toBe(true)
expect(useAnnotationWork.getState().mode).toBeNull()
expect(screen.queryByRole('button', { name: 'Fermer le tracé' })).toBeNull()
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Redessiner' }))
pressAt(canvas(), 30, 30)
act(() => void (allowed = guardDrawing(back)))
expect(allowed).toBe(false)
expect(useAnnotationWork.getState().question?.work).toBe('redraw')
expect(
screen.getByRole('button', { name: 'Fermer le tracé' }),
).toBeInTheDocument()
})
it('a tool asks first once a vertex is placed; « Abandonner » ends the trace', async () => {
await redrawing()
pressAt(canvas(), 30, 30)
fireEvent.click(screen.getByRole('button', { name: 'Point' }))
expect(useAnnotationWork.getState().question?.work).toBe('redraw')
act(() => answerDrawing(true))
expect(useAnnotationWork.getState().mode).toBeNull()
expect(screen.queryByRole('button', { name: 'Fermer le tracé' })).toBeNull()
expect(pointsOf('z')).toEqual(SQUARE)
})
it('a document change made elsewhere drops a started redraw and says so (R-13)', async () => {
await redrawing()
pressAt(canvas(), 30, 30)
act(
() =>
void store.getState().commit({
op: 'update',
key: { kind: 'annotation', id: 'z' },
element: {
kind: 'annotation',
value: zone('z', { type: 'polygon', points: TRACE }),
},
}),
)
expect(useAnnotationWork.getState().mode).toBeNull()
expect(
await screen.findByText('Nouveau tracé abandonné : la fiche a changé.'),
).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Fermer le tracé' })).toBeNull()
})
it('« Remplacer par un polygone » on a path is the same redraw', async () => {
await mount(
withZone(drawnText(), 'p', {
type: 'path',
d: 'M 20 20 L 80 20 L 50 80 Z',
}),
)
const panel = await select()
await userEvent.setup().click(
within(panel).getByRole('button', {
name: 'Remplacer par un polygone',
}),
)
expect(useAnnotationWork.getState().mode).toMatchObject({ kind: 'redraw' })
})
})
describe('the zoom hint for short segments (R-18, D2)', () => {
const SHORT: Point[] = [
[20, 20],
[35, 20],
[80, 20],
[80, 80],
[20, 80],
]
const zoomHint = 'Zoomez pour ajouter un sommet sur les segments courts.'
beforeEach(() => {
// One CSS px per drawing unit at fit: the 100-unit frame in a 100 px box.
for (const side of ['clientWidth', 'clientHeight'])
Object.defineProperty(window.SVGSVGElement.prototype, side, {
configurable: true,
get: () => 100,
})
})
afterEach(() => {
for (const side of ['clientWidth', 'clientHeight'])
delete (
window.SVGSVGElement.prototype as unknown as Record<string, unknown>
)[side]
})
it('a hidden « + » shows the line; zooming until every « + » shows removes it', async () => {
await mount(squareText(SHORT))
await select()
expect(
screen.queryByRole('button', {
name: 'Ajouter un sommet après le sommet 1',
}),
).toBeNull()
expect(plus(2)).toBeInTheDocument()
expect(screen.getByTestId('edit-strip-notice')).toHaveTextContent(zoomHint)
const zoomIn = screen.getByRole('button', { name: 'Zoom avant' })
fireEvent.click(zoomIn)
fireEvent.click(zoomIn)
await waitFor(() => expect(plus(1)).toBeInTheDocument())
expect(screen.getByTestId('edit-strip-notice')).not.toHaveTextContent(
zoomHint,
)
})
it('a refusal takes its place while shown', async () => {
await mount(squareText(SHORT))
await select()
drag(hitOf('Sommet 3'), [80, 20], [500, 20])
const notice = screen.getByTestId('edit-strip-notice')
expect(notice).toHaveTextContent('Déplacement refusé')
expect(notice).not.toHaveTextContent(zoomHint)
})
it('is absent in a redraw', async () => {
await mount(squareText(SHORT))
await select()
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Redessiner' }))
expect(screen.getByTestId('edit-strip-notice')).not.toHaveTextContent(
zoomHint,
)
})
})
@@ -32,8 +32,10 @@ import DrawingGuardDialog from '@/components/editor/annotations/DrawingGuardDial
import { guardDrawing } from '@/editor/annotations/drawingGuard'
import {
resetWork,
markRedraw,
setModePreview,
startMove,
startRedraw,
useAnnotationWork,
} from '@/editor/annotations/workStore'
@@ -341,6 +343,21 @@ describe('AppLayout and a started move on the drawing (R-12)', () => {
expect(screen.queryByText('account page')).toBeNull()
})
it('a started redraw asks « Abandonner le nouveau tracé ? » before a link', async () => {
const user = userEvent.setup()
mountDraft()
startRedraw('a', 'doc')
markRedraw(true)
await user.click(account())
expect(
screen.getByRole('dialog', { name: 'Abandonner le nouveau tracé ?' }),
).toBeInTheDocument()
expect(screen.queryByText('account page')).toBeNull()
await user.click(screen.getByRole('button', { name: 'Abandonner' }))
expect(await screen.findByText('account page')).toBeInTheDocument()
expect(useAnnotationWork.getState().mode).toBeNull()
})
it('a move with nothing started leaves at once and ends', async () => {
const user = userEvent.setup()
mountDraft()