feat(editor): creation on the drawing then the creation dialog

U2 Task 7 (A2, A4, A5, A7, A12, A15; R-3, R-4, R-12, R-13, R-14).
The work store's `creation` owns the new shape, its form, its view and
F: a click with the point tool, a closed tracing or a keyboard
« Ajouter … » opens « Nouveau point / zone / accès », a modal without
a history layer over the right column, mounted beside EditOnly so a
read-only flip keeps it (« Créer », « Replacer », « Reprendre » off).
A new zone or link is a creation from its first vertex. The ghost
takes the form's category colour; the point tool previews under a
mouse; the canvas carries data-creating (other markers dimmed,
unselectable). « Replacer le point » / « Reprendre le tracé » hide the
dialog and keep the form; the strip offers « Revenir aux propriétés »,
« Retirer le dernier sommet », « Abandonner ». « Créer »: one insert,
tool back to « Sélectionner », the new element selected, « Point
créé · Défaire », focus on its row. ✕, Échap, « Abandonner » and Back
always ask « Abandonner la création ? » (DiscardConfirm inside the
dialog; DrawingGuardDialog elsewhere); answerDrawing drops the
creation. Undo, its shortcuts and the line's « Défaire » are inactive
during a creation. missingFields replaces formProblem (MissingSummary
shared with the edit form); the C26 notice has no numbers.
CreationPanel, formProblem, withGeometry and the keys required.fields,
required.names and create_cancel are gone; GeometryGroup is imported
by RepairDialog only.

Removed or rewritten assertions:
- tab « holds a point at the frame centre »: « Centre x » = 50 ->
  the ghost circle cx = 50; plus tool back to Sélectionner, « Point
  créé », one undo step.
- tab « refuses a creation without laterality »: the general line
  « Choisissez la catégorie et la latéralité » -> only « Choisissez
  une latéralité. » and « À compléter : Latéralité. », focus on it.
- tab « applies the geometry group to a pending zone »: removed (A8,
  no coordinate field) -> « places a triangle at the centre: the ghost
  shows it, Créer inserts it »; vertex edits after Créer are the e2e
  keyboard test.
- tab C26 « proposes C »: « x = 15, y = 15 » in the notice -> the R-4
  text, the notice inside the dialog; cancel test « Centre x » = 0 ->
  ghost cx = 0.
- tab « offers the correction when the core refuses a pending point »
  (typed cx 98): removed, no typed coordinate is possible; the verdict
  path stays covered by the C26 click tests and correctionFor units.
- tab H5 « a typed radius shows the core issue »: removed (A8); the
  size refusal is the slider's (Task 4 tests).
- tab H6 « a second click moves the pending point »: -> « Replacer le
  point », then the click moves the ghost, the form kept.
- tab H7 « Centre x/y » = 30/50 -> ghost cx/cy.
- tab tracing Enter: « x du sommet 3 » -> ghost points; « drops the
  tracing on Escape » -> Escape asks first (board 32 row 3), Continuer
  keeps, Abandonner drops; new « Annuler le tracé acts at once ».
- keep-alive « a pending creation is kept and focused » and « a
  tracing … is kept and focused »: the tab now asks first (R-12) ->
  « Continuer » keeps the tracing / the form, « Abandonner » goes.
- sections « its panel takes the focus » -> its dialog's
  [data-creation-focus] takes it.
- no-loss « pending creation with its name » (hidden with the body) ->
  the dialog stays across the crossing, read-only, Créer off (R-14).
- point-edit A5 « Rayon » = 7 / 9 -> ghost r = 7 / 9.
- e2e editor-annotations keyboard test « numeric position » (cx field
  250) -> UX_TESTS Keyboard: zone added, vertex added and removed,
  moved by the move mode, validated, saved. The « Fermer le tracé »
  step runs under expectNoShift again (shortcut removed).
- e2e editor-geometry C26: the proposed x, y read from the notice
  text -> from the overlay's correction circle; the R-4 text checked
  in the dialog.
- e2e editor-deselect « Escape cancels the tracing only » -> Escape
  asks, « Abandonner » cancels it, the selection kept.
- e2e editor-shell-crossing « keeps its tool and its pending
  creation » (field hidden) -> the dialog stays read-only, Créer off,
  then editable on widening.
This commit is contained in:
bchanot committed 2026-11-17 23:32:42 +01:00
1 parent 2d58da7d01
commit 4d2c64f57f
50 files changed
+3050 -1181

No files matched your search

+2 -2
View File
@@ -749,8 +749,8 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet
- [ ] `shortcut:` the « − » bubble for a mouse is 28 × 22 px, read off board 05 (R-9 gives only the touch size), `apps/app/src/editor/annotations/handleSize.ts`. Upgrade: the owner's value at the trial (U2 Task 5).
- [ ] No `scroll-padding-top` under the sticky top bar (pre-existing, WCAG 2.4.11): a keyboard focus on the header's « Défaire », « Refaire » or « Enregistrer » while scrolled can stay hidden under it; axe target-size flags them once a list click scrolled the page (U2 Task 5 review M-3).
- [x] At the page's end, a side panel that shortens (the issue list leaving it) clamps the scroll and moves the canvas by its height (11 px in `editor-geometry.spec.ts`, which starts from the top for that reason). Gone with Task 6: the column keeps the overview, the issue is in the strip and the dialog. `editor-geometry.spec.ts` now runs the accepted repair (the issue leaving) from the page's end under `expectNoShift`, buttons pressed in place, scroll position unchanged (U2 Task 5 fix round 1, closed by Task 6 fix round 1).
- [ ] `shortcut:` the creation panel still shows the general lines `editor.annotations.required.fields` / `.names`, which R-3 removes (`apps/app/src/components/editor/annotations/CreationPanel.tsx`, `formProblem` in `creation.ts`). Upgrade: Task 7's creation dialog uses `missingFields` and the `editor.annotations.missing.*` keys, then the two keys and `formProblem` go (U2 Task 6 review Minor 6).
- [ ] `shortcut:` the close of a zone tracing (« Fermer le tracé ») is checked out of `expectNoShift` in `editor-annotations.spec.ts` « the drawing never moves »: the creation panel still replaces the overview in the side column until Task 7. Upgrade: wrap it again once the creation is a dialog (U2 Task 6, `aside-content` exemption removed).
- [x] (U2 Task 7: `CreationPanel`, `formProblem` and the two keys removed; the creation dialog uses `missingFields`) `shortcut:` the creation panel still shows the general lines `editor.annotations.required.fields` / `.names`, which R-3 removes (`apps/app/src/components/editor/annotations/CreationPanel.tsx`, `formProblem` in `creation.ts`). Upgrade: Task 7's creation dialog uses `missingFields` and the `editor.annotations.missing.*` keys, then the two keys and `formProblem` go (U2 Task 6 review Minor 6).
- [x] (U2 Task 7: the close runs under `expectNoShift` again) `shortcut:` the close of a zone tracing (« Fermer le tracé ») is checked out of `expectNoShift` in `editor-annotations.spec.ts` « the drawing never moves »: the creation panel still replaces the overview in the side column until Task 7. Upgrade: wrap it again once the creation is a dialog (U2 Task 6, `aside-content` exemption removed).
- [ ] Test anomaly A (owner 2026-11-09, separate from U1/U2): fictitious fingerprints `'a'.repeat(64)` from worker stand-ins (`packages/supabase/tests/sandbox/sheet-fixtures.ts:115` openRound, `sheets-concurrency.sandbox.ts:168`, `sheets-perf.sandbox.ts:169`); 7 published/deprecated sandbox versions fail `check_published`. Fix: real fingerprint through the core (as e2e `fingerprintOf`, `apps/app/e2e/support/catalogue.ts:88`); never weaken the publish gate or the reader check. Needs its own go. Census 2026-11-17 (R4 Task 3, read-only): 4 of 164 catalogue entries fail, the four current « Cheval sandbox » versions (2 at v1, 2 at v2), all `fingerprint_mismatch`; R4 cards show them with the integrity line.
- [ ] Test anomaly B (owner 2026-11-09, separate from U1/U2): `packages/supabase/tests/sandbox/sheets-admin.sandbox.ts:181-195` creates the historical working copy and never archives it; slot taken → `admin.spec.ts:717` fails x4. Fix test independence and cleanup; the existing copy `8c315a12-20d4-4432-9db3-7cb88b27a5b4` stays untouched until the owner authorises. Linked: RR-13, the admin.spec confirmation line above.
- [x] Test anomaly C (owner 2026-11-09, separate from U1/U2): CLOSED 2026-11-17 with R4's owner validation. Integrity failure invisible in catalogue cards; implemented as lot R4; failure shown, never hidden or bypassed. Built 2026-11-17 (R4 Task 1-3 and final fix wave, `V1-2-6_U1_CORRECTIONS.md` §5 row C: built by R4, closes on the owner's validation); checked off with R4's owner validation.
+92 -48
View File
@@ -35,7 +35,10 @@ import { expectNoShift, keepNativeFrames } from '../support/layout'
const dict = fr
const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
/** The creation dialog's form (U2 Task 7). */
const creation = (page: Page) => page.getByTestId('annotation-creation')
const creationDialog = (page: Page, kind: string) =>
page.getByRole('dialog', { name: dict[`editor.annotations.new.${kind}`] })
/** The selection's commands in the strip (U2 Task 6: the properties are a dialog). */
const properties = (page: Page) =>
page.locator('[data-testid="edit-strip"]:has([data-properties-button])')
@@ -53,7 +56,7 @@ interface Names {
en: string
}
/** Fills the creation panel; the category keeps its first choice. */
/** Fills the creation dialog; the category keeps its first choice (A4). */
async function fillCreation(page: Page, names: Names, opens?: string) {
const panel = creation(page)
await panel.getByLabel(dict['editor.annotations.name_fr']).fill(names.fr)
@@ -71,6 +74,8 @@ async function createFromPanel(page: Page) {
.getByRole('button', { name: dict['editor.annotations.create'] })
.click()
await expect(creation(page)).toHaveCount(0)
// A7: back to « Sélectionner », the new element selected.
await expect(tool(page, 'select')).toHaveAttribute('aria-pressed', 'true')
}
async function openAnnotations(page: Page) {
@@ -97,12 +102,34 @@ test.describe('editor annotations (A3)', () => {
}) => {
const { actor, seed } = await openAnnotations(page)
requests.forbid(actor.account.email, actor.account.password)
const line = page.getByTestId('gesture-line')
// A point: the tool, a click in the drawing, the fields the core requires.
// An entry of the editor's own below this one, for the Back further down.
await selectTab(page, dict, 'general')
await selectTab(page, dict, 'annotations')
// A point: the tool, a click in the drawing, the dialog « Nouveau point » (A2).
await tool(page, 'point').click()
await clickDrawing(page, 300, 300)
await expect(creation(page)).toBeVisible()
await expectAccessible(page, 'the point creation panel')
await expect(creationDialog(page, 'point')).toBeVisible()
await expect(page.getByTestId('overlay-ghost')).toBeAttached()
await expect(page.getByTestId('annotation-canvas')).toHaveAttribute(
'data-creating',
'',
)
await expectAccessible(page, 'the point creation dialog')
// A Back while the dialog is open: refused (a modal, no history layer), the question
// inside the dialog (A12); the tab stays.
await page.goBack()
const ask = creationDialog(page, 'point').getByRole('group', {
name: dict['editor.annotations.guard.creation'],
})
await expect(ask).toBeVisible()
await expect(page.locator('dialog[open]')).toHaveCount(1)
await ask
.getByRole('button', { name: dict['editor.annotations.guard.continue'] })
.click()
await expect(ask).toHaveCount(0)
await expect(creationDialog(page, 'point')).toBeVisible()
await fillCreation(page, { fr: 'Point un', en: 'Point one' })
await creation(page)
.getByLabel(dict['editor.annotations.zone'])
@@ -110,6 +137,9 @@ test.describe('editor annotations (A3)', () => {
await createFromPanel(page)
await expect(selectionTag(page)).toContainText('Point un')
await expect(properties(page)).toBeVisible()
await expect(line).toContainText(
dict['editor.annotations.message.created.point'],
)
const placed = await shownNumber(page, 'cx')
expect(Math.abs(placed - 300)).toBeLessThan(1)
@@ -121,12 +151,18 @@ test.describe('editor annotations (A3)', () => {
[700, 400],
])
await clickDrawing(page, x, y)
await expectAccessible(page, 'a zone tracing in progress')
await page
.getByRole('button', { name: dict['editor.annotations.trace_close'] })
.click()
await expect(creationDialog(page, 'zone')).toBeVisible()
await expectAccessible(page, 'the zone creation dialog')
await fillCreation(page, { fr: 'Zone une', en: 'Zone one' })
await createFromPanel(page)
await expect(selectionTag(page)).toContainText('Zone une')
await expect(line).toContainText(
dict['editor.annotations.message.created.zone'],
)
// A link to the detail view: the same tracing, the opened view chosen.
await tool(page, 'link').click()
@@ -144,6 +180,15 @@ test.describe('editor annotations (A3)', () => {
await expect(selectionTag(page)).toContainText('Accès un')
await expect(historyButton(page, dict, 'undo')).toBeEnabled()
// Each creation is one step: « Défaire » removes the link, « Refaire » brings it back.
const rows = list(page).getByRole('button')
await expect(rows.filter({ hasText: 'Accès un' })).toHaveCount(1)
await historyButton(page, dict, 'undo').click()
await expect(rows.filter({ hasText: 'Accès un' })).toHaveCount(0)
await expect(rows.filter({ hasText: 'Zone une' })).toHaveCount(1)
await historyButton(page, dict, 'redo').click()
await expect(rows.filter({ hasText: 'Accès un' })).toHaveCount(1)
// 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/)
@@ -221,64 +266,63 @@ test.describe('editor annotations (A3)', () => {
await expect(shownShape(page)).toHaveAttribute('cx', x0)
})
test('keyboard only: creation by the add buttons, numeric position, edit by the handle keys', async ({
// UX_TESTS « Keyboard »: create a zone, add and remove a vertex, move the zone, validate.
test('keyboard only: a zone by « Ajouter une zone », a vertex added and removed, moved, validated', async ({
page,
requests,
}) => {
const { actor, seed } = await openAnnotations(page)
requests.forbid(actor.account.email, actor.account.password)
const add = page.getByRole('button', {
name: dict['editor.annotations.add.point'],
})
await add.focus()
await page.keyboard.press('Enter')
await expect(creation(page)).toBeVisible()
await fillCreation(page, { fr: 'Clavier', en: 'Keyboard' })
const cx = creation(page).getByLabel(dict['editor.annotations.geometry.cx'])
await cx.fill('250')
await cx.press('Enter')
await expect(cx).toHaveValue('250')
await creation(page)
.getByRole('button', { name: dict['editor.annotations.create'] })
.focus()
await page.keyboard.press('Enter')
await expect(creation(page)).toHaveCount(0)
await expect(selectionTag(page)).toContainText('Clavier')
await expect(shownShape(page)).toHaveAttribute('cx', '250')
// 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', exact: true })
.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, its first vertex moved by its keys.
await page
.getByRole('button', { name: dict['editor.annotations.add.zone'] })
.focus()
await page.keyboard.press('Enter')
await expect(creationDialog(page, 'zone')).toBeVisible()
await fillCreation(page, { fr: 'Zone clavier', en: 'Keyboard zone' })
await creation(page)
.getByRole('button', { name: dict['editor.annotations.create'] })
.focus()
await page.keyboard.press('Enter')
await expect(creation(page)).toHaveCount(0)
await expect(selectionTag(page)).toContainText('Zone clavier')
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')
// Board 32: « Créer » réussi, the focus on the new row.
await expect(
list(page).getByRole('button', { name: /Zone clavier/ }),
).toBeFocused()
const [first] = await shownPoints(page)
expect(await shownPoints(page)).toHaveLength(3)
// « + » after vertex 1 by Enter: four vertices; Delete on the chosen one: three again.
await page
.getByRole('button', { name: 'Ajouter un sommet après le sommet 1' })
.focus()
await page.keyboard.press('Enter')
await expect.poll(async () => (await shownPoints(page)).length).toBe(4)
await page.getByRole('button', { name: 'Sommet 2', exact: true }).focus()
await page.keyboard.press('Delete')
await expect.poll(async () => (await shownPoints(page)).length).toBe(3)
// Escape unchooses the vertex (board 32 row 5): the strip offers the zone's move.
await page.keyboard.press('Escape')
// The move mode by its keys: two steps right, then « Valider la position ».
await page
.getByRole('button', { name: dict['editor.annotations.move.zone'] })
.focus()
await page.keyboard.press('Enter')
const right = page.getByRole('button', {
name: dict['editor.annotations.move.right'],
})
await right.focus()
await page.keyboard.press('Enter')
await page.keyboard.press('Enter')
await page
.getByRole('button', { name: dict['editor.annotations.move.confirm'] })
.focus()
await page.keyboard.press('Enter')
await expect
.poll(async () => (await shownPoints(page))[0][0])
.toBe(round2(round2(before + 5) + 5))
.toBe(round2(round2(first[0] + 5) + 5))
await saveDraft(page, dict, seed.revision + 1)
})
@@ -394,11 +438,11 @@ test.describe('editor annotations (A3)', () => {
button(page, 'editor.annotations.trace_pop').click(),
)
await expectNoShift(page, () => clickDrawing(page, 700, 400))
// shortcut: the creation panel still replaces the overview in the side column until
// Task 7 (the creation dialog), so the close is checked out of the no-shift probe.
// Upgrade path: wrap it in expectNoShift again once the creation is a dialog.
await button(page, 'editor.annotations.trace_close').click()
await expect(creation(page)).toBeVisible()
// The close opens « Nouvelle zone » over the column: nothing under it moves.
await expectNoShift(page, async () => {
await button(page, 'editor.annotations.trace_close').click()
await expect(creationDialog(page, 'zone')).toBeVisible()
})
})
}
+8 -1
View File
@@ -263,7 +263,8 @@ test.describe('deselect and D6b (editor, mouse and keyboard)', () => {
await page.keyboard.press('Escape')
await expectDeselected(page)
// A tracing: Escape cancels the tracing only.
// A tracing (a creation, U2 Task 7): Escape asks first (board 32 row 3, A12), then
// « Abandonner » cancels the tracing only.
await select(page, POINT)
await toolButton(page, dict, 'zone').click()
await clickAt(page, { x: 300, y: 500 })
@@ -272,6 +273,12 @@ test.describe('deselect and D6b (editor, mouse and keyboard)', () => {
await expect(bar).toBeVisible()
await box(page).focus()
await page.keyboard.press('Escape')
const guardQuestion = page.getByRole('dialog', {
name: dict['editor.annotations.guard.creation'],
})
await guardQuestion
.getByRole('button', { name: dict['editor.annotations.guard.discard'] })
.click()
await expect(bar).toHaveCount(0)
await expectKept(page, POINT)
expect(saves).toEqual([])
+13 -5
View File
@@ -48,12 +48,16 @@ const viewChip = (page: Page, name: string) =>
.getByRole('group', { name: dict['editor.annotations.views'] })
.getByRole('button', { name })
/** The x and y a correction notice proposes, read from its sentence. */
/**
* The x and y the correction proposes, read from the drawing (R-4: the notice in the
* creation dialog says it without numbers).
*/
async function proposed(page: Page): Promise<{ x: string; y: string }> {
const text = (await notice(page).innerText()).replace(/\s+/g, ' ')
const found = /x = (-?\d+(?:\.\d+)?), y = (-?\d+(?:\.\d+)?)/.exec(text)
if (!found) throw new Error('no proposed position in the notice')
return { x: found[1], y: found[2] }
const circle = page.getByTestId('overlay-correction').locator('circle')
const x = await circle.getAttribute('cx')
const y = await circle.getAttribute('cy')
if (x === null || y === null) throw new Error('no proposed position drawn')
return { x, y }
}
/** A mouse drag on the drawing in the move mode, between two points in drawing units. */
@@ -109,6 +113,10 @@ test.describe('editor geometry (adversarial)', () => {
.getByRole('button', { name: dict['editor.annotations.create'] })
.click()
await expect(notice(page)).toBeVisible()
// R-4: the notice is in the creation dialog, its text without numbers.
await expect(
page.getByRole('dialog', { name: dict['editor.annotations.new.point'] }),
).toContainText(dict['editor.annotations.correction'])
await expect(page.getByTestId('overlay-click-cross')).toBeAttached()
const shown = await proposed(page)
await expect(selectionTag(page)).toHaveCount(0) // an insertion selects it
@@ -252,7 +252,9 @@ test.describe('editor shell, width crossing (H)', () => {
await expectNoDialog(page)
})
test('the annotation edit body keeps its tool and its pending creation', async ({
// U2 Task 7 (R-14): the creation dialog is mounted outside the edit-only body. A
// crossing keeps it open, read-only, with its form; widening gives the form back.
test('the creation dialog stays across a crossing: its form kept, « Créer » off, then on', async ({
page,
}) => {
await open(page)
@@ -266,15 +268,26 @@ test.describe('editor shell, width crossing (H)', () => {
await page
.getByRole('button', { name: dict['editor.annotations.add.point'] })
.click()
const name = page.getByLabel(dict['editor.annotations.name_fr'])
const dialog = page.getByRole('dialog', {
name: dict['editor.annotations.new.point'],
})
const name = dialog.getByLabel(dict['editor.annotations.name_fr'])
const create = dialog.getByRole('button', {
name: dict['editor.annotations.create'],
})
await name.fill('Futur point')
await cross(page, NARROW)
await expect(name).toBeHidden()
await page.setViewportSize(NARROW)
await expect(zone).toHaveCount(0)
await expect(active(page)).toHaveAttribute('id', 'editor-tab-annotations')
await cross(page, WIDE)
await expect(dialog).toBeVisible()
await expect(name).toHaveValue('Futur point')
await expect(zone).toHaveAttribute('aria-pressed', 'true')
await expect(name).not.toBeEditable()
await expect(create).toBeDisabled()
await expect(page.getByTestId('overlay-ghost')).toBeAttached()
await page.setViewportSize(WIDE)
await expect(name).toHaveValue('Futur point')
await expect(name).toBeEditable()
await expect(create).toBeEnabled()
await expect(page.getByTestId('overlay-ghost')).toBeVisible()
await expect(saveLine(page)).not.toHaveText(UNSAVED_LINE)
})
+3 -2
View File
@@ -676,7 +676,7 @@ 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 (until U2 Task 7) or repair dialog. */
/** The geometry fields of the open repair dialog (D1: the only place they remain). */
export const geometryField = (page: Page, dict: Dict, key: string) =>
page.getByLabel(dict[`editor.annotations.geometry.${key}`], { exact: true })
@@ -738,6 +738,7 @@ export function shapeWith(...annotations: unknown[]) {
}
}
/** The creation dialog's form (U2 Task 7: the side panel became a dialog over the column). */
export const creationPanel = (page: Page) =>
page.getByTestId('annotation-creation')
@@ -791,7 +792,7 @@ export const toolButton = (page: Page, dict: Dict, id: string) =>
exact: true,
})
/** Fills the creation panel; the category keeps its first choice. */
/** Fills the creation dialog; the category keeps its first choice (A4). */
export async function fillCreation(
page: Page,
dict: Dict,
@@ -7,7 +7,10 @@ import {
import { useEditorReadOnly } from '@/editor/editingContext'
import { commitFocusedField } from '@/editor/focusRequest'
import { canRedo, canUndo, useEditorStore } from '@/editor/state/editorStore'
import { cancelPending } from '@/editor/annotations/workStore'
import {
cancelPending,
useAnnotationWork,
} from '@/editor/annotations/workStore'
import { useT } from '@/i18n/useT'
import EditorGlyph from './EditorGlyph'
@@ -67,6 +70,8 @@ function usePress(
left.current = asField(event.relatedTarget) ?? left.current
}
const onClick = () => {
// A12: undo and redo are inactive during a creation (R-13).
if (useAnnotationWork.getState().creation) return
const field = left.current
forget()
if (field?.isConnected && field.getAttribute('aria-invalid') === 'true') {
@@ -101,6 +106,7 @@ function HistoryButton({
const t = useT()
const readOnly = useEditorReadOnly()
const steppable = useEditorStore(direction === 'undo' ? canUndo : canRedo)
const creating = useAnnotationWork((s) => s.creation !== null)
const name = t(`editor.history.${direction}_title`)
const press = usePress(direction, readOnly, left)
return (
@@ -108,7 +114,7 @@ function HistoryButton({
type="button"
aria-label={name}
title={`${name} (${t(`editor.history.${direction}_shortcut`)})`}
aria-disabled={readOnly || !steppable}
aria-disabled={readOnly || !steppable || creating}
aria-keyshortcuts={SHORTCUT[direction]}
{...press}
className={BUTTON}
@@ -1,4 +1,11 @@
import { useEffect, useRef, type KeyboardEvent, type RefObject } from 'react'
import {
useEffect,
useRef,
useState,
type KeyboardEvent,
type PointerEvent,
type RefObject,
} from 'react'
import type { Geometry } from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
@@ -6,6 +13,7 @@ import { coreFailureMessage } from '@/core/failure'
import { useCoreStopped } from '@/core/runtime'
import { transformOf } from '@/catalogue/framing'
import type { XY } from '@/editor/annotations/frame'
import { clientToDrawing } from '@/editor/annotations/gesture'
import {
useCanvasBuild,
type RootAttributes,
@@ -23,7 +31,7 @@ import ToolColumn, { type ToolColumnProps } from './ToolColumn'
type OverlayData = Omit<
OverlayProps,
'svgRef' | 'viewBox' | 'ratio' | 'dragged'
'svgRef' | 'viewBox' | 'ratio' | 'dragged' | 'hover'
>
/** The handle layer's content: the handle and its keys (the layer measures itself). */
@@ -37,6 +45,10 @@ export interface AnnotationCanvasProps {
viewName: string
tool: ToolId
selectedId: string | null
/** The point tool's next size (A5), shown under a mouse pointer; null: no preview. */
previewRadius: number | null
/** A creation is in progress: the other markers are dimmed and unselectable (A12). */
creating: boolean
/** The selected annotation when it can be moved now. */
moveTarget: MoveTarget | null
overlay: OverlayData
@@ -71,6 +83,7 @@ export default function AnnotationCanvas(props: AnnotationCanvasProps) {
overlay,
viewport,
})
const preview = usePointPreview(props.previewRadius, overlay)
useSelectionMark(build.host, props.selectedId, build.root)
useReportRoot(build.root, props.onRoot)
return (
@@ -85,13 +98,14 @@ export default function AnnotationCanvas(props: AnnotationCanvasProps) {
{...props}
build={build}
viewport={viewport}
boxProps={gestures.boxProps}
boxProps={withPreview(gestures.boxProps, preview)}
layer={{
transform: transformOf(gestures.framing.framing),
overlay: {
...props.overlay,
svgRef: overlay,
dragged: gestures.drag,
hover: preview.hover,
},
handles: {
...props.handles,
@@ -105,11 +119,47 @@ export default function AnnotationCanvas(props: AnnotationCanvasProps) {
}
type Build = ReturnType<typeof useCanvasBuild>
type BoxProps = ReturnType<typeof useCanvasGestures>['boxProps']
type Preview = ReturnType<typeof usePointPreview>
/**
* Board 02 A: with the point tool, the next point follows a mouse pointer over the drawing
* at the strip's size. Touch and pen have no hover: nothing is shown for them.
*/
function usePointPreview(
radius: number | null,
overlay: RefObject<SVGSVGElement | null>,
) {
const [at, setAt] = useState<XY | null>(null)
const onMove = (event: PointerEvent) => {
if (radius === null || event.pointerType !== 'mouse') {
if (at !== null) setAt(null)
return
}
const client = { x: event.clientX, y: event.clientY }
setAt(clientToDrawing(overlay.current, client))
}
const hover = radius !== null && at ? { ...at, r: radius } : null
return { hover, onMove, onLeave: () => setAt(null) }
}
/** The box's own pointer handlers, then the preview's. */
function withPreview(box: BoxProps, preview: Preview) {
return {
...box,
onPointerMove: (event: PointerEvent) => {
box.onPointerMove(event)
preview.onMove(event)
},
onPointerLeave: preview.onLeave,
}
}
function CanvasBox({
viewId,
viewName,
tool,
creating,
build,
viewport,
boxProps,
@@ -117,7 +167,7 @@ function CanvasBox({
}: AnnotationCanvasProps & {
build: Build
viewport: RefObject<HTMLDivElement | null>
boxProps: ReturnType<typeof useCanvasGestures>['boxProps']
boxProps: BoxProps
layer: Omit<LayerProps, 'host' | 'root'>
}) {
const root = build.root?.viewId === viewId ? build.root : null
@@ -130,6 +180,7 @@ function CanvasBox({
role="group"
aria-label={viewName}
data-testid="annotation-canvas"
data-creating={creating ? '' : undefined}
className={`svg-canvas aspect-[4/3] w-full select-none ${cursor} ${FOCUS_RING}`}
{...boxProps}
>
@@ -18,29 +18,14 @@ import { useEditCommand } from '@/editor/useEditCommand'
import type { Guards } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
import CreationFields from './CreationFields'
import MissingSummary, { focusFirstMissing } from './MissingSummary'
/** What the form edits: the creation's fields plus « Couleur » (A9), as plain strings. */
type Draft = CreationForm & { color: string }
/** The edit form's ids: never the creation panel's, kept mounted in the hidden edit body. */
/** The edit form's ids: never the creation dialog's (`creation-`). */
const ID_PREFIX = 'annotation-edit-'
const FIELD_ID: Record<MissingField, string> = {
name_fr: 'fr',
name_en: 'en',
category: 'category',
laterality: 'laterality',
opens: 'opens',
}
const FIELD_LABEL: Record<MissingField, string> = {
name_fr: 'editor.annotations.name_fr',
name_en: 'editor.annotations.name_en',
category: 'editor.annotations.category',
laterality: 'editor.annotations.laterality',
opens: 'editor.annotations.opens',
}
function draftOf(annotation: Annotation): Draft {
const link = annotation.kind === 'detail_trigger'
return {
@@ -158,7 +143,7 @@ function useSave(props: AnnotationEditFormProps, form: FormDraft) {
const absent = missingFields(props.annotation.kind, form.draft)
setMissing(absent)
if (absent.length > 0) {
document.getElementById(`${ID_PREFIX}${FIELD_ID[absent[0]!]}`)?.focus()
focusFirstMissing(ID_PREFIX, absent)
return
}
if (!form.dirty) return props.onDone(false)
@@ -174,21 +159,6 @@ function useSave(props: AnnotationEditFormProps, form: FormDraft) {
type FormDraft = ReturnType<typeof useFormDraft<Draft>>
/** « À compléter : Latéralité. »: the missing fields by their labels, in form order. */
function MissingSummary({ missing }: { missing: readonly MissingField[] }) {
const t = useT()
if (missing.length === 0) return null
const fields = missing.map((field) => t(FIELD_LABEL[field])).join(', ')
return (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{t('editor.annotations.missing.summary').replace(
'{fields}',
() => fields,
)}
</p>
)
}
/**
* « Modifier » (board 31 C): the creation's fields with « Couleur » on a local draft, one
* `update` on « Enregistrer » (none when unchanged), nothing on « Annuler » or a close.
@@ -16,7 +16,11 @@ export interface OverlayProps {
dragged: Geometry | null
/** The place the core just refused (red dashes while its message shows). */
refused: Geometry | null
/** The new shape waiting for its properties (the ghost), in its category's colour (A4). */
pending: Geometry | null
pendingColour: string
/** The point tool's preview under a mouse pointer (none on touch). */
hover: { x: number; y: number; r: number } | null
tracing: Point[] | null
correction: Correction | null
/** A redraw runs: the stored outline stays as the old place until the close (06 C). */
@@ -94,6 +98,74 @@ function HollowCross({
)
}
/** The shape `geometry` with its own style: a ghost's fill and halo, the preview's dashes. */
function Shape({
geometry,
style,
}: {
geometry: Geometry
style: Record<string, string | number | undefined>
}) {
if (geometry.type === 'circle') {
return (
<circle cx={geometry.cx} cy={geometry.cy} r={geometry.r} {...style} />
)
}
if (geometry.type === 'polygon') {
return <polygon points={geometry.points.join(' ')} {...style} />
}
return null
}
/**
* The new shape before « Créer »: its category's colour, a white halo, accent dashes over
* it (docs/ANNOTATION-RENDERING.md « Editor overlay »).
*/
function Ghost({ geometry, colour }: { geometry: Geometry; colour: string }) {
const line = { vectorEffect: 'non-scaling-stroke', fill: 'none' }
return (
<g data-testid="overlay-ghost" data-colour={colour}>
<Shape
geometry={geometry}
style={{ fill: colour, fillOpacity: 0.45, stroke: 'none' }}
/>
<Shape
geometry={geometry}
style={{ ...line, stroke: 'white', strokeWidth: 6 }}
/>
<Shape
geometry={geometry}
style={{
...line,
stroke: 'var(--color-accent)',
strokeWidth: 2,
strokeDasharray: '6 4',
}}
/>
</g>
)
}
/** Board 02 A: the next point's size, dashed, with a cross at the pointer. */
function HoverPreview({
hover,
}: {
hover: { x: number; y: number; r: number }
}) {
const { x, y, r } = hover
const arm = r / 4
const style = { ...STROKE, stroke: 'var(--color-accent)', strokeWidth: 1.5 }
return (
<g data-testid="overlay-point-preview">
<circle cx={x} cy={y} r={r} {...style} strokeDasharray="6 4" />
<path
d={`M ${x - arm} ${y} H ${x + arm} M ${x} ${y - arm} V ${y + arm}`}
{...style}
/>
</g>
)
}
function TracingPath({ points, size }: { points: Point[]; size: number }) {
if (points.length === 0) return null
const shape: Geometry = { type: 'polygon', points }
@@ -163,24 +235,19 @@ export default function AnnotationOverlay(props: OverlayProps) {
<Vertices geometry={shown} size={size} />
</g>
)}
{pending && (
<Outline
geometry={pending}
dashed={false}
colour="var(--color-accent)"
/>
)}
{pending && <Ghost geometry={pending} colour={props.pendingColour} />}
{correction && (
<>
<g data-testid="overlay-correction">
<Outline
geometry={{ type: 'circle', ...correction.circle }}
dashed
colour="var(--color-accent)"
/>
<HollowCross at={correction.click} size={size * 1.5} />
</>
</g>
)}
{tracing && <TracingPath points={tracing} size={size} />}
{props.hover && <HoverPreview hover={props.hover} />}
</svg>
)
}
@@ -1,26 +1,21 @@
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import type { Correction } from '@/editor/annotations/correction'
import { useT } from '@/i18n/useT'
/**
* The corrected position is never taken silently: the page says where the point would
* sit, the overlay shows it with the click marked apart, and only « Utiliser cette
* position » inserts it.
* The corrected position is never taken silently: the notice says a corrected position
* is proposed (no numbers, A8, R-4), the overlay shows it with the click marked apart,
* and only « Utiliser cette position » inserts it.
*/
export default function CorrectionNotice({
correction,
onConfirm,
onCancel,
}: {
correction: Correction
onConfirm: () => void
onCancel: () => void
}) {
const t = useT()
const message = t('editor.annotations.correction')
.replace('{x}', String(correction.circle.cx))
.replace('{y}', String(correction.circle.cy))
return (
<Notice tone="info">
<div className="space-y-2" data-testid="correction-notice">
@@ -0,0 +1,65 @@
import Button from '@/components/ui/Button'
import { askCreation } from '@/editor/annotations/creationAsk'
import { backToProperties, popVertex } from '@/editor/annotations/creationWork'
import type { Creation } from '@/editor/annotations/workStore'
import { useT } from '@/i18n/useT'
import EditorGlyph from '../EditorGlyph'
const COMMAND = 'min-h-11 gap-1.5 xl:min-h-9'
/** The vertices a resumed tracing holds now; null for a point. */
const tracedCount = (work: Creation) =>
!work.closed && work.pending.geometry.type === 'polygon'
? work.pending.geometry.points.length
: null
/**
* Board 04 C: the dialog hidden by « Replacer le point » or « Reprendre le tracé ». « Revenir
* aux propriétés » shows it again (a tracing closes first, three vertices at least);
* « Abandonner » asks first, the shape always exists (A12).
*/
export default function CreationCommands({ creation }: { creation: Creation }) {
const t = useT()
const count = tracedCount(creation)
return (
<div
tabIndex={-1}
data-testid="creation-commands"
data-creation-focus=""
className="flex items-center gap-2 outline-none"
>
<Button
data-back-to-properties=""
type="button"
size="sm"
className={COMMAND}
disabled={count !== null && count < 3}
onClick={() => backToProperties()}
>
<EditorGlyph name="properties" size={16} />
{t('editor.annotations.back_to_properties')}
</Button>
{count !== null && (
<Button
type="button"
size="sm"
variant="secondary"
className={COMMAND}
disabled={count === 0}
onClick={popVertex}
>
{t('editor.annotations.trace_pop')}
</Button>
)}
<Button
type="button"
size="sm"
variant="ghost"
className={COMMAND}
onClick={askCreation}
>
{t('editor.annotations.creation.discard')}
</Button>
</div>
)
}
@@ -0,0 +1,281 @@
import { useRef, useState, type RefObject } from 'react'
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import DiscardConfirm from '@/components/editor/findings/DiscardConfirm'
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import { creationOpener } from '@/editor/annotations/creationAsk'
import {
confirmAttempt,
createAttempt,
type Attempt,
} from '@/editor/annotations/creationAttempt'
import {
dropCreation,
finishCreation,
patchForm,
replacePoint,
resumeTrace,
setCorrection,
} from '@/editor/annotations/creationWork'
import { answerDrawing, guardDrawing } from '@/editor/annotations/drawingGuard'
import type { MissingField } from '@/editor/annotations/missingFields'
import {
useAnnotationWork,
type Creation,
} from '@/editor/annotations/workStore'
import { visibleElement } from '@/editor/focusRequest'
import { CANVAS_BOX } from '@/editor/useEditorNavigation'
import { usePlaceVisible } from '@/lib/placeVisibility'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import { pluralKey } from '@/editor/plural'
import EditorGlyph from '../EditorGlyph'
import CorrectionNotice from './CorrectionNotice'
import CreationFields from './CreationFields'
import MissingSummary, { focusFirstMissing } from './MissingSummary'
const ID_PREFIX = 'creation-'
export interface CreationDialogProps {
doc: AnatomicalSheetDocument
readOnly: boolean
/** The column the dialog sits over (A2); null: centred. */
anchor: RefObject<HTMLElement | null>
}
/** What « Créer » left on screen: the fields R-3 names, or the core's refusal. */
interface Outcome {
missing: MissingField[]
messages: string[]
}
const NONE: Outcome = { missing: [], messages: [] }
/**
* « Créer » and « Utiliser cette position »: one `insertAnnotation` under `accept` (one
* undo); a point lets the core's verdict offer C (C26); a success ends the creation.
*/
function useCreate(work: Creation, created: { current: boolean }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const [outcome, setOutcome] = useState<Outcome>(NONE)
const settle = (attempt: Attempt) => {
if (attempt.status === 'invalid') {
setOutcome({ missing: attempt.missing, messages: [] })
return focusFirstMissing(ID_PREFIX, attempt.missing)
}
setOutcome({
missing: [],
messages: attempt.status === 'refused' ? attempt.messages : [],
})
if (attempt.status === 'correction') setCorrection(attempt.correction)
if (attempt.status !== 'created') return
created.current = true
if (attempt.id) finishCreation(attempt.id, work.pending.kind)
else dropCreation()
}
const input = { ...work, context: { t, locale } }
return {
outcome,
create: () => settle(createAttempt(input, work.form)),
confirm: () => {
const { correction } = work.pending
if (correction) settle(confirmAttempt(input, work.form, correction))
},
}
}
/** « Point placé · Replacer le point », « Zone tracée, 5 sommets · Reprendre le tracé ». */
function ShapeLine({ work, readOnly }: { work: Creation; readOnly: boolean }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const { kind, geometry } = work.pending
const count = geometry.type === 'polygon' ? geometry.points.length : 0
const text =
kind === 'point'
? t('editor.annotations.creation.placed')
: t(
pluralKey(
locale,
`editor.annotations.creation.traced.${kind}`,
count,
),
).replace('{count}', String(count))
const point = kind === 'point'
return (
<div
data-creation-focus=""
tabIndex={-1}
className="flex flex-wrap items-center gap-x-2 gap-y-1 rounded-lg bg-[var(--color-surface-strong)] px-3 py-2 text-sm outline-none"
>
<EditorGlyph
name={point ? 'point' : kind === 'zone' ? 'zone' : 'link'}
size={16}
/>
<span>{text}</span>
<button
type="button"
disabled={readOnly}
onClick={point ? replacePoint : resumeTrace}
className="min-h-11 font-medium text-[var(--color-accent-strong)] underline underline-offset-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] disabled:cursor-not-allowed disabled:opacity-40 xl:min-h-0"
>
{t(`editor.annotations.creation.${point ? 'replace' : 'resume'}`)}
</button>
</div>
)
}
/** Board 02: « Abandonner » asks first (A12), « Créer » inserts; the question in its place. */
function CreationActions({
readOnly,
onDiscard,
}: {
readOnly: boolean
onDiscard: () => void
}) {
const t = useT()
const asking = useAnnotationWork((s) => s.question?.work === 'creation')
if (asking) {
return (
<DiscardConfirm
words={{
title: t('editor.annotations.guard.creation'),
keep: t('editor.annotations.guard.continue'),
discard: t('editor.annotations.guard.discard'),
}}
onKeepTyping={() => answerDrawing(false)}
onDiscard={() => answerDrawing(true)}
/>
)
}
return (
<div className="flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={onDiscard}>
{t('editor.annotations.creation.discard')}
</Button>
<Button type="submit" disabled={readOnly}>
{t('editor.annotations.create')}
</Button>
</div>
)
}
/** The guard is always armed (A12): ✕, Échap and « Abandonner » ask, even with nothing typed. */
const askDiscard = () => guardDrawing(() => undefined)
function CreationBody({
work,
doc,
readOnly,
created,
}: {
work: Creation
doc: AnatomicalSheetDocument
readOnly: boolean
created: { current: boolean }
}) {
const creating = useCreate(work, created)
const { outcome } = creating
return (
<form
data-testid="annotation-creation"
className="space-y-3"
noValidate
onSubmit={(event) => {
event.preventDefault()
if (!readOnly) creating.create()
}}
>
{readOnly && <ReadOnlyNotice />}
<ShapeLine work={work} readOnly={readOnly} />
<CreationFields
kind={work.pending.kind}
viewId={work.viewId}
doc={doc}
form={work.form}
onChange={patchForm}
idPrefix={ID_PREFIX}
missing={outcome.missing}
readOnly={readOnly}
/>
{work.pending.correction && (
<CorrectionNotice
onConfirm={() => !readOnly && creating.confirm()}
onCancel={() => setCorrection(null)}
/>
)}
<MissingSummary missing={outcome.missing} />
{outcome.messages.length > 0 && (
<div
role="alert"
className="space-y-1 text-sm text-[var(--color-danger-strong)]"
>
{outcome.messages.map((text) => (
<p key={text}>{text}</p>
))}
</div>
)}
<CreationActions readOnly={readOnly} onDiscard={askDiscard} />
</form>
)
}
/**
* Where the focus goes once the dialog closes (board 32): nowhere after « Créer » (the new
* row takes it), the strip's « Revenir aux propriétés » while the shape is replaced or
* retraced, else what started the creation.
*/
function useCreationReturn(work: Creation | null) {
const last = useRef<Creation | null>(null)
const created = useRef(false)
// A new creation starts with no « Créer » behind it.
if (work && last.current === null) created.current = false
last.current = work ?? last.current
const returnFocus = () => {
const ended = last.current
if (useAnnotationWork.getState().creation) {
return (
visibleElement('[data-back-to-properties]') ??
visibleElement(CANVAS_BOX)
)
}
last.current = null
if (created.current || !ended) return null
return creationOpener(ended)
}
return { created, returnFocus }
}
/**
* « Nouveau point », « Nouvelle zone », « Nouvel accès » (board 02, 04): a modal without a
* history layer over the right column, mounted outside the edit-only body so a read-only
* flip keeps it with its form and ghost, « Créer » disabled (R-14). The shape and the
* form are the work store's: they outlive « Replacer le point » and « Reprendre le tracé ».
*/
export default function CreationDialog(props: CreationDialogProps) {
const t = useT()
const visible = usePlaceVisible()
const work = useAnnotationWork((s) => s.creation)
const back = useCreationReturn(work)
const shown = visible && work !== null && work.dialog
const title = work ? t(`editor.annotations.new.${work.pending.kind}`) : ''
return (
<Dialog
open={shown}
anchor={props.anchor}
veilCloses={false}
title={title}
returnFocus={back.returnFocus}
onClose={() => (askDiscard() ? undefined : 'kept')}
>
{work && (
<CreationBody
work={work}
doc={props.doc}
readOnly={props.readOnly}
created={back.created}
/>
)}
</Dialog>
)
}
@@ -1,170 +0,0 @@
import { useState, type Dispatch } from 'react'
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
import type { CommitContext } from '@/editor/annotations/annotationCommit'
import {
emptyForm,
withGeometry,
type CreationForm,
type PendingElement,
} from '@/editor/annotations/creation'
import {
confirmAttempt,
createAttempt,
type Attempt,
type CreationInput,
} from '@/editor/annotations/creationAttempt'
import type { Frame } from '@/editor/annotations/frame'
import type { UiAction } from '@/editor/annotations/uiState'
import { useT } from '@/i18n/useT'
import CorrectionNotice from './CorrectionNotice'
import CreationFields from './CreationFields'
import GeometryGroup from './GeometryGroup'
export interface CreationPanelProps {
pending: PendingElement
viewId: string
doc: AnatomicalSheetDocument
/** F of the current view; null while it is not measured. */
frame: Frame | null
dispatch: Dispatch<UiAction>
context: CommitContext
}
/** What an attempt leaves on screen: the core's words, or the form's own. */
function messagesOf(attempt: Attempt, words: (problem: string) => string) {
if (attempt.status === 'refused') return attempt.messages
return attempt.status === 'invalid' ? [words(attempt.problem)] : []
}
/**
* The typed fields and the outcome of « Créer » / « Utiliser cette position ». The form
* survives a change of the pending geometry (a second click): the panel is not remounted.
*/
function useCreation(props: CreationPanelProps) {
const t = useT()
const [form, setForm] = useState<CreationForm>(() => emptyForm(props.doc))
const [messages, setMessages] = useState<string[]>([])
const settle = (attempt: Attempt) => {
const { dispatch, pending } = props
// shortcut: the general lines `editor.annotations.required.{fields,names}` (R-3 removes
// them) stay until Task 7. Upgrade: the creation dialog names each field through
// `missingFields` and the `editor.annotations.missing.*` keys, as the edit form does.
setMessages(
messagesOf(attempt, (p) => t(`editor.annotations.required.${p}`)),
)
if (attempt.status === 'created') {
dispatch({ type: 'select', id: attempt.id ?? null })
}
if (attempt.status === 'correction') {
const next = { ...pending, correction: attempt.correction }
dispatch({ type: 'pending_update', pending: next })
}
}
const input: CreationInput = props
return {
form,
messages,
patch: (change: Partial<CreationForm>) => setForm({ ...form, ...change }),
create: () => settle(createAttempt(input, form)),
confirm: () => {
const { correction } = props.pending
if (correction) settle(confirmAttempt(input, form, correction))
},
}
}
/**
* « Nouveau point / Nouvelle zone / Nouvel accès »: the fields the core requires are
* collected first, then « Créer » inserts once through `accept` (no default labels).
* The geometry stays here, outside the document, until then.
*/
export default function CreationPanel(props: CreationPanelProps) {
const t = useT()
const creation = useCreation(props)
const { pending, dispatch } = props
const title = t(`editor.annotations.new.${pending.kind}`)
return (
<section
aria-label={title}
data-testid="annotation-creation"
className="space-y-3 rounded-xl border border-[var(--color-border)] p-4"
>
<h3
tabIndex={-1}
data-creation-heading
className="outline-none text-base font-semibold"
>
{title}
</h3>
<CreationFields
kind={pending.kind}
viewId={props.viewId}
form={creation.form}
doc={props.doc}
onChange={creation.patch}
/>
<GeometryGroup
idPrefix="creation"
geometry={pending.geometry}
locked={false}
onApply={(geometry) => {
const next = withGeometry(pending, geometry)
dispatch({ type: 'pending_update', pending: next })
return { ok: true }
}}
/>
{pending.correction && (
<CorrectionNotice
correction={pending.correction}
onConfirm={creation.confirm}
onCancel={() =>
dispatch({
type: 'pending_update',
pending: { ...pending, correction: null },
})
}
/>
)}
<Messages messages={creation.messages} />
<CreationActions
onCreate={creation.create}
onCancel={() => dispatch({ type: 'pending_drop' })}
/>
</section>
)
}
function CreationActions({
onCreate,
onCancel,
}: {
onCreate: () => void
onCancel: () => void
}) {
const t = useT()
return (
<div className="flex gap-2">
<Button type="button" onClick={onCreate}>
{t('editor.annotations.create')}
</Button>
<Button type="button" variant="secondary" onClick={onCancel}>
{t('editor.annotations.create_cancel')}
</Button>
</div>
)
}
function Messages({ messages }: { messages: string[] }) {
if (messages.length === 0) return null
return (
<div
role="alert"
className="space-y-1 text-sm text-[var(--color-danger-strong)]"
>
{messages.map((message) => (
<p key={message}>{message}</p>
))}
</div>
)
}
@@ -7,11 +7,14 @@ import ConfirmDialog from '../ConfirmDialog'
/**
* The drawing guard's question (R-12), mounted with the workspace so it shows whatever
* tab is in view: « Continuer » keeps the work, « Abandonner » drops it and makes the move
* that was held.
* that was held. The creation dialog, when shown, asks it in its own footer instead.
*/
export default function DrawingGuardDialog() {
const t = useT()
const question = useAnnotationWork((s) => s.question)
// Over a shown creation dialog the question is that dialog's own (R-12, board 31 D).
const question = useAnnotationWork((s) =>
s.question?.work === 'creation' && s.creation?.dialog ? null : s.question,
)
// The title stays while the dialog closes.
const title = useRef('')
if (question) title.current = t(`editor.annotations.guard.${question.work}`)
@@ -7,6 +7,15 @@ import type {
import type { CommitContext } from '@/editor/annotations/annotationCommit'
import { useAnnotationRequest } from '@/editor/annotations/focusTarget'
import { keyboardPending, type NewKind } from '@/editor/annotations/creation'
import {
creationTracing,
placePending,
} from '@/editor/annotations/creationWork'
import { useCreationFollow } from '@/editor/annotations/useCreationFollow'
import {
useAnnotationWork,
type Creation,
} from '@/editor/annotations/workStore'
import { parseFrame, type Frame } from '@/editor/annotations/frame'
import { newPointSize } from '@/editor/annotations/pointSize'
import { guardDrawing } from '@/editor/annotations/drawingGuard'
@@ -24,12 +33,13 @@ import {
useLayerFollow,
type OpenDialog,
} from '@/editor/annotations/dialogOpening'
import { usePlacement } from '@/editor/annotations/usePlacement'
import { creationStart, usePlacement } from '@/editor/annotations/usePlacement'
import { useGestureMessage } from '@/editor/annotations/useGestureMessage'
import {
initialUi,
uiReducer,
type ToolId,
type Tracing,
type UiAction,
type UiState,
} from '@/editor/annotations/uiState'
@@ -46,7 +56,6 @@ import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import AnnotationCanvas from './AnnotationCanvas'
import { annotationName } from './AnnotationList'
import CreationPanel from './CreationPanel'
import GestureMessage from './GestureMessage'
import KeyboardAdd from './KeyboardAdd'
import OverviewPanel from './OverviewPanel'
@@ -73,6 +82,10 @@ export interface Scene {
/** F of the current view, only while the core measures it and the build is its own. */
frame: Frame | null
selected: Annotation | undefined
/** The creation in progress on this view (A12), the work store's. */
creation: Creation | null
/** The tracing shown: a redraw's, or the open tracing of a new zone or link. */
tracing: Tracing | null
setRoot: (root: RootAttributes | null) => void
navigate: EditorPlaceProps['navigate']
onOpenSection: Props['onOpenSection']
@@ -81,9 +94,9 @@ export interface Scene {
/**
* The shown view no longer exists (an undo, a deletion in the views section): the full
* reset to the main view drops the pending creation, the tracing and the selection, so
* nothing pending is inserted on another view. It fires only for a view absent from the
* document, since `view` always returns a new state.
* reset to the main view drops the tracing and the selection (a creation on that view is
* dropped by `useCreationFollow`), so nothing pending is inserted on another view. It
* fires only for a view absent from the document, since `view` always returns a new state.
*/
function useViewFallback(
doc: AnatomicalSheetDocument,
@@ -100,11 +113,16 @@ function useViewFallback(
}
/** « Aller à » an annotation: the request, with what it needs of the drawing's state. */
/** A fresh tracing reads as a tracing; a placed, closed or resumed shape as a creation. */
function busyOf(creation: Creation | null, ui: UiState) {
if (creation)
return creation.closed || creation.resumed ? 'creation' : 'tracing'
return ui.tracing ? 'tracing' : null
}
function useSceneRequest(
{ doc, focus, layerId }: Props,
ui: UiState,
viewId: string,
dispatch: Dispatch<UiAction>,
{ ui, viewId, dispatch, creation }: SceneCore,
) {
useViewFallback(doc, ui.viewId, dispatch)
const show = (view: string, id: string) => {
@@ -114,7 +132,7 @@ function useSceneRequest(
useAnnotationRequest(focus, doc, {
viewId,
selectedId: ui.selectedId,
busy: ui.pending ? 'creation' : ui.tracing ? 'tracing' : null,
busy: busyOf(creation, ui),
show,
})
useLayerFollow(layerId, doc, {
@@ -125,6 +143,13 @@ function useSceneRequest(
})
}
interface SceneCore {
ui: UiState
viewId: string
dispatch: Dispatch<UiAction>
creation: Creation | null
}
function useScene(props: Props): Scene {
const { doc, navigate, onOpenSection, onOpen } = props
const [ui, dispatch] = useReducer(uiReducer, initialUi)
@@ -132,13 +157,17 @@ function useScene(props: Props): Scene {
const viewId = ui.viewId ?? mainViewId(doc)
const model = useViewModel(doc, viewId)
const own = model.measured && root?.viewId === viewId
useSceneRequest(props, ui, viewId, dispatch)
const work = useAnnotationWork((s) => s.creation)
const creation = work?.viewId === viewId ? work : null
useSceneRequest(props, { ui, viewId, dispatch, creation })
return {
doc,
ui,
dispatch,
viewId,
model,
creation,
tracing: ui.tracing ?? creationTracing(creation, viewId),
frame: own ? parseFrame(root.viewBox) : null,
selected: model.annotations.find((a) => a.id === ui.selectedId),
setRoot,
@@ -163,6 +192,7 @@ function useWork(scene: Scene) {
const context = useCommitContext()
const message = useGestureMessage()
const placement = usePlacement({ ...scene, context, message })
useCreationFollow({ ...scene, message, t: context.t })
const target = movableOf(scene.selected, scene.model, scene.ui.tool)
const onDrop = placement.onDrop
const edit = usePointEdit({ target, frame: scene.frame, onDrop })
@@ -198,11 +228,11 @@ export default function EditableAnnotations(props: Props) {
const { asideRef, byDrawing } = useSelectionEscape(
selected?.id ?? null,
() => scene.dispatch({ type: 'select', id: null }),
// A redraw's Escape cancels it at once (R-12); a new tracing keeps its own keys.
// A redraw's Escape cancels it at once (R-12); a creation asks (board 32 row 3).
visible &&
selected !== undefined &&
(selected !== undefined || scene.creation !== null) &&
(ui.tracing === null || ui.tracing.target === 'replace'),
{ editable: true, creating: ui.pending !== null },
{ editable: true, creating: scene.creation !== null },
)
return (
<div className="space-y-3">
@@ -210,7 +240,7 @@ export default function EditableAnnotations(props: Props) {
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]">
<CanvasColumn scene={scene} work={work} onDeselect={byDrawing} />
<aside ref={asideRef} data-annotation-aside="edit">
<SidePanel scene={scene} context={work.context} />
<SidePanel scene={scene} />
</aside>
</div>
</div>
@@ -283,8 +313,10 @@ function CanvasStage({
const locale = useLocaleStore((s) => s.locale)
// Hidden (the editor is read-only): no drag in flight survives, none is committed.
const shown = usePlaceVisible()
const { doc, ui, dispatch, model, frame, selected } = scene
const { doc, ui, dispatch, model, selected, creation } = scene
const handle = useHandle(shown ? work.target : null, doc)
// A12: during a creation nothing else is selected or opened from the drawing.
const free = creation === null
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)
@@ -296,8 +328,10 @@ function CanvasStage({
viewName={view.name[locale]}
tool={ui.tool}
selectedId={ui.selectedId}
previewRadius={previewRadiusOf(scene)}
creating={!free}
moveTarget={shown ? moveTargetOf(selected, model, ui.tool) : null}
overlay={overlayOf(ui, selected, frame, work.message.message?.place)}
overlay={overlayOf(scene, work.message.message?.place)}
handles={{
handle,
onKeyDown: work.edit.onHandleKey,
@@ -313,48 +347,35 @@ function CanvasStage({
linkDisabled: model.children.length === 0,
}}
onRoot={scene.setRoot}
onSelect={(id) => dispatch({ type: 'select', id })}
onOpen={(id) => scene.onOpen(id, 'drawing')}
onSelect={(id) => free && dispatch({ type: 'select', id })}
onOpen={(id) => free && scene.onOpen(id, 'drawing')}
onPlace={work.placement.onPlace}
onDrop={work.placement.onDrop}
onHandle={work.zone.onHandle}
onDeselect={onDeselect}
onDeselect={() => free && onDeselect()}
onTraceKey={work.placement.onTraceKey}
/>
)
}
function addAtCentre(
kind: NewKind,
{ frame, doc, viewId, ui, dispatch }: Scene,
) {
/** « Ajouter … » (keyboard): the shape at the centre at the A5 size, then its dialog. */
function addAtCentre(kind: NewKind, scene: Scene) {
const { frame, doc, viewId, ui } = scene
if (!frame) return
const size = newPointSize(doc.annotations, viewId, frame, ui.size)
dispatch({ type: 'pending_new', pending: keyboardPending(kind, frame, size) })
const start = creationStart(scene, 'keyboard')
placePending(start, keyboardPending(kind, frame, size))
}
/** The creation panel while an element is pending, else the overview (A3). */
function SidePanel({
scene,
context,
}: {
scene: Scene
context: CommitContext
}) {
const { doc, ui, dispatch, frame } = scene
if (ui.pending) {
return (
<CreationPanel
key={ui.serial}
pending={ui.pending}
viewId={scene.viewId}
doc={doc}
frame={frame}
dispatch={dispatch}
context={context}
/>
)
}
/** Board 02 A: the next point's size under a mouse pointer, while the point tool places. */
function previewRadiusOf({ ui, frame, doc, viewId, creation }: Scene) {
if (ui.tool !== 'point' || !frame || creation?.dialog) return null
return newPointSize(doc.annotations, viewId, frame, ui.size)
}
/** The overview, during a selection (A3) and a creation alike: the right column never swaps. */
function SidePanel({ scene }: { scene: Scene }) {
const { doc, ui, dispatch } = scene
return (
<OverviewPanel
doc={doc}
@@ -397,20 +418,27 @@ function movableOf(
return moveTargetOf(selected, model, tool) !== null ? selected! : null
}
/** The ghost's fill: the category the form holds (A4), else the accent. */
function ghostColour(doc: AnatomicalSheetDocument, creation: Creation | null) {
const id = creation?.form.categoryId
const category = doc.categories.find((c) => c.id === id)
return category?.color ?? 'var(--color-accent)'
}
function overlayOf(
ui: UiState,
selected: Annotation | undefined,
frame: Frame | null,
{ ui, selected, frame, creation, tracing, doc }: Scene,
refused: Geometry | null | undefined,
) {
const placed = creation?.closed ? creation.pending : null
return {
frame,
selectedId: selected?.id ?? null,
refused: refused ?? null,
selected: selected?.geometry ?? null,
pending: ui.pending?.geometry ?? null,
tracing: ui.tracing?.points ?? null,
correction: ui.pending?.correction ?? null,
pending: placed?.geometry ?? null,
pendingColour: ghostColour(doc, creation),
tracing: tracing?.points ?? null,
correction: placed?.correction ?? null,
redrawing: ui.tracing?.target === 'replace',
}
}
@@ -2,7 +2,10 @@ import type { ReactNode } from 'react'
import { useEditorReadOnly } from '@/editor/editingContext'
import type { GestureMessages } from '@/editor/annotations/useGestureMessage'
import { canUndo, useEditorStore } from '@/editor/state/editorStore'
import { cancelPending } from '@/editor/annotations/workStore'
import {
cancelPending,
useAnnotationWork,
} from '@/editor/annotations/workStore'
import { useT } from '@/i18n/useT'
const PILL =
@@ -45,6 +48,8 @@ export default function GestureMessage({
function Message({ messages }: { messages: GestureMessages }) {
const t = useT()
const readOnly = useEditorReadOnly()
// A12: « Défaire » is hidden during a creation; the message itself stays.
const creating = useAnnotationWork((s) => s.creation !== null)
const { message, hold } = messages
if (!message) return null
const error = message.tone === 'error'
@@ -65,7 +70,7 @@ function Message({ messages }: { messages: GestureMessages }) {
<span className="truncate" title={message.text}>
{message.text}
</span>
{message.undo && !error && (
{message.undo && !error && !creating && (
<>
<span aria-hidden="true">·</span>
<button
@@ -5,8 +5,8 @@ import { useT } from '@/i18n/useT'
const KINDS: readonly NewKind[] = ['point', 'zone', 'detail_trigger']
/**
* The keyboard creation path (C7): each button holds a pending element at the centre of
* the frame and opens the creation panel; every coordinate is then typed in the fields.
* The keyboard creation path (C7): each button places a shape at the centre of the frame
* at the A5 size and opens the creation dialog; once created, its handles correct it.
*/
export default function KeyboardAdd({
disabled,
@@ -28,6 +28,7 @@ export default function KeyboardAdd({
type="button"
variant="secondary"
size="sm"
data-add-kind={kind}
disabled={disabled || (kind === 'detail_trigger' && linkDisabled)}
onClick={() => onAdd(kind)}
>
@@ -0,0 +1,50 @@
import type { MissingField } from '@/editor/annotations/missingFields'
import { useT } from '@/i18n/useT'
/** Each missing field's input id, after the form's id prefix. */
const FIELD_ID: Record<MissingField, string> = {
name_fr: 'fr',
name_en: 'en',
category: 'category',
laterality: 'laterality',
opens: 'opens',
}
const FIELD_LABEL: Record<MissingField, string> = {
name_fr: 'editor.annotations.name_fr',
name_en: 'editor.annotations.name_en',
category: 'editor.annotations.category',
laterality: 'editor.annotations.laterality',
opens: 'editor.annotations.opens',
}
/** R-3: the focus goes to the first missing field of the form whose ids start with `prefix`. */
export function focusFirstMissing(
prefix: string,
missing: readonly MissingField[],
): void {
const first = missing[0]
if (first) document.getElementById(`${prefix}${FIELD_ID[first]}`)?.focus()
}
/**
* « À compléter : Latéralité. »: the missing fields by their labels, in form order. The
* creation dialog and the edit form share it (R-3).
*/
export default function MissingSummary({
missing,
}: {
missing: readonly MissingField[]
}) {
const t = useT()
if (missing.length === 0) return null
const fields = missing.map((field) => t(FIELD_LABEL[field])).join(', ')
return (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{t('editor.annotations.missing.summary').replace(
'{fields}',
() => fields,
)}
</p>
)
}
@@ -2,9 +2,9 @@ import type { Annotation } from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
import { useDeselect } from '@/editor/annotations/deselect'
import { isEditable } from '@/editor/annotations/geometryEdit'
import { dropCreation } from '@/editor/annotations/creationWork'
import { beginRedraw } from '@/editor/annotations/redraw'
import { stripLeadOf } from '@/editor/annotations/stripLead'
import type { UiState } from '@/editor/annotations/uiState'
import { useGeometryIssues } from '@/editor/annotations/useGeometryIssues'
import type { GestureMessage as ShownMessage } from '@/editor/annotations/useGestureMessage'
import { useAnnotationWork } from '@/editor/annotations/workStore'
@@ -12,6 +12,7 @@ import { targetOfKey } from '@/editor/navigation'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import type { Scene, Work } from './EditableAnnotations'
import CreationCommands from './CreationCommands'
import EditStrip, { type StripNotice } from './EditStrip'
import {
SelectionPointCommands,
@@ -48,9 +49,14 @@ export default function SceneStrip({
detail: t('editor.annotations.move.hint'),
icon: 'move' as const,
}
: stripLeadOf(ui, selected, doc, { t, locale, chosenVertex })
: stripLeadOf(
{ tool: ui.tool, tracing: scene.tracing, creation: scene.creation },
selected,
doc,
{ t, locale, chosenVertex },
)
const commandsKey = commandsKeyOf(
ui,
scene,
mode !== null,
work.target,
chosenVertex,
@@ -69,12 +75,15 @@ export default function SceneStrip({
/** One box per set of commands: a wider set never moves an existing box (A14). */
function commandsKeyOf(
ui: UiState,
{ ui, tracing, creation }: Scene,
moving: boolean,
target: Annotation | null,
chosen: number | null,
) {
if (ui.tracing) return 'tracing'
if (creation?.dialog) return 'creation-dialog'
if (creation?.resumed)
return `creation-${creation.closed ? 'point' : 'trace'}`
if (tracing) return 'tracing'
if (moving) return 'move'
if (target?.geometry?.type === 'polygon') return `zone-${chosen !== null}`
if (target?.kind === 'point') return 'point'
@@ -124,17 +133,25 @@ function SceneCommands({
work: Work
moving: boolean
}) {
const { ui, doc, viewId, frame, dispatch, selected } = scene
const { ui, doc, viewId, frame, dispatch, selected, creation, tracing } =
scene
const { byButton } = useDeselect(selected?.id ?? null, () =>
dispatch({ type: 'select', id: null }),
)
if (ui.tracing) {
// The dialog shown: its own actions; hidden after it was shown: board 04 C.
if (creation?.dialog) return null
if (creation?.resumed) return <CreationCommands creation={creation} />
if (tracing) {
// « Annuler le tracé » is an explicit cancel: it acts at once (board 04 A).
const redraw = tracing.target === 'replace'
return (
<TracingCommands
count={ui.tracing.points.length}
count={tracing.points.length}
onClose={work.placement.closeTracing}
onPop={work.placement.popVertex}
onCancel={() => dispatch({ type: 'trace_cancel' })}
onCancel={() =>
redraw ? dispatch({ type: 'trace_cancel' }) : dropCreation()
}
/>
)
}
@@ -152,7 +169,7 @@ function SceneCommands({
</>
)
}
if (ui.tool !== 'point' || ui.pending || !frame) return null
if (ui.tool !== 'point' || creation || !frame) return null
return (
<ToolSize
doc={doc}
@@ -187,7 +204,7 @@ function useStripNotice(
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) {
if (work.insertsHidden && !inMode && !scene.tracing) {
return { tone: 'info', text: t('editor.annotations.strip.zoom_hint') }
}
if (!model.measured) return unmeasuredNotice(scene, t)
@@ -26,10 +26,13 @@ function ToolButton({
label,
pressed,
disabled,
tool,
onClick,
}: {
glyph: GlyphName
label: string
/** The tool it chooses: a creation's « Abandonner » gives it the focus back (board 32). */
tool?: ToolId
pressed?: boolean
disabled?: boolean
onClick: () => void
@@ -40,6 +43,7 @@ function ToolButton({
aria-label={label}
title={label}
aria-pressed={pressed}
data-tool={tool}
disabled={disabled}
onClick={onClick}
className={`${BUTTON} ${
@@ -59,6 +63,7 @@ export default function ToolColumn(props: ToolColumnProps) {
const tool = (id: ToolId, disabled: boolean) => (
<ToolButton
glyph={id}
tool={id}
label={t(`editor.annotations.tool.${id}`)}
pressed={props.tool === id}
disabled={disabled}
@@ -58,26 +58,32 @@ function focusWhenOnTop(target: HTMLElement): () => void {
return () => watcher.disconnect()
}
/** The question and its answers, when a form asks other words (the creation, R-12). */
export interface DiscardWords {
title: string
keep: string
discard: string
}
export default function DiscardConfirm({
onKeepTyping,
onDiscard,
words,
}: {
onKeepTyping: () => void
onDiscard: () => void
words?: DiscardWords
}) {
const t = useT()
const title = words?.title ?? t('editor.findings.discard_ask')
const keep = useRef<HTMLButtonElement>(null)
useEffect(() => {
const button = keep.current
return button ? focusWhenOnTop(button) : undefined
}, [])
return (
<div
role="group"
aria-label={t('editor.findings.discard_ask')}
className={BOX}
>
<p className="text-sm font-medium">{t('editor.findings.discard_ask')}</p>
<div role="group" aria-label={title} className={BOX}>
<p className="text-sm font-medium">{title}</p>
<div className="flex flex-wrap justify-end gap-2">
<Button
ref={keep}
@@ -85,10 +91,10 @@ export default function DiscardConfirm({
variant="secondary"
onClick={onKeepTyping}
>
{t('editor.findings.keep_typing')}
{words?.keep ?? t('editor.findings.keep_typing')}
</Button>
<Button type="button" variant="danger" onClick={onDiscard}>
{t('editor.findings.discard')}
{words?.discard ?? t('editor.findings.discard')}
</Button>
</div>
</div>
@@ -7,6 +7,7 @@ import CatalogueCanvas from '@/components/catalogue/CatalogueCanvas'
import AnnotationDialog from '@/components/editor/annotations/AnnotationDialog'
import { annotationName } from '@/components/editor/annotations/AnnotationList'
import AnnotationReadBody from '@/components/editor/annotations/AnnotationReadBody'
import CreationDialog from '@/components/editor/annotations/CreationDialog'
import EditableAnnotations from '@/components/editor/annotations/EditableAnnotations'
import EditStrip from '@/components/editor/annotations/EditStrip'
import OverviewPanel from '@/components/editor/annotations/OverviewPanel'
@@ -68,8 +69,9 @@ function SectionPlace({
}
/**
* The drawing workspace: edit or read-only body of the same view, and the properties
* dialog over both, outside the edit-only part so a read-only flip keeps it (R-14).
* The drawing workspace: edit or read-only body of the same view, and the properties and
* creation dialogs over both, outside the edit-only part so a read-only flip keeps them
* (R-14).
*/
function DrawingPlace(props: AnnotationsTabProps) {
const t = useT()
@@ -107,6 +109,9 @@ function DrawingPlace(props: AnnotationsTabProps) {
returnFocus={dialog.returnFocus}
/>
)}
{doc && (
<CreationDialog doc={doc} readOnly={readOnly} anchor={dialog.anchor} />
)}
</section>
)
}
@@ -120,8 +125,8 @@ function SectionBody(props: AnnotationsTabProps & { id: SectionId }) {
}
/**
* Annotations: the drawing workspace (canvas with its tools, the overview or the creation
* panel, the properties dialog), or one of its full-width sections. Read-only, the same
* Annotations: the drawing workspace (canvas with its tools, the overview, the properties
* and creation dialogs), or one of its full-width sections. Read-only, the same
* view is browsable (canvas, list, properties as text) with no tool and no action.
* Each section shown so far stays mounted, hidden while another is shown.
*/
+1 -31
View File
@@ -31,22 +31,7 @@ export interface PendingElement {
wantedRadius?: number
}
/** The pending element with a geometry the user typed: C and the proposal lapse with it. */
export function withGeometry(
pending: PendingElement,
geometry: EditableGeometry,
): PendingElement {
const kept =
geometry.type === 'circle' && geometry.r === pending.proposedRadius
return {
...pending,
geometry,
correction: null,
proposedRadius: kept ? pending.proposedRadius : undefined,
}
}
/** What the creation panel collects (no default labels: names and laterality are typed). */
/** What the creation dialog collects (no default labels: names and laterality are typed). */
export interface CreationForm {
fr: string
en: string
@@ -107,23 +92,8 @@ export function keyboardPending(
return { kind, geometry: { type: 'polygon', points: centreTriangle(frame) } }
}
export type FormProblem = 'names' | 'fields'
const blank = (value: string) => value.trim() === ''
/** Input shape only: what the core requires to exist, collected before the insert. */
export function formProblem(
kind: NewKind,
form: CreationForm,
): FormProblem | null {
if (form.categoryId === '' || form.laterality === '') return 'fields'
if (kind === 'detail_trigger') {
if (form.opensViewId === '') return 'fields'
return blank(form.fr) !== blank(form.en) ? 'names' : null
}
return blank(form.fr) || blank(form.en) ? 'names' : null
}
const orNull = (value: string): string | null => (blank(value) ? null : value)
/** The annotation the form and the pending geometry describe, under a given id. */
@@ -0,0 +1,34 @@
import { landAfterModalsClosed } from '@/components/ui/afterModalsClosed'
import { visibleElement } from '../focusRequest'
import { guardDrawing } from './drawingGuard'
import type { NewKind } from './creation'
import { useAnnotationWork, type Creation } from './workStore'
const TOOL_OF: Record<NewKind, string> = {
point: 'point',
zone: 'zone',
detail_trigger: 'link',
}
/**
* Where the focus goes once a creation is abandoned (board 32): the tool's button, or the
* keyboard « Ajouter … » button that started it.
*/
export function creationOpener(work: Creation): HTMLElement | null {
const { kind } = work.pending
if (work.origin === 'keyboard') {
return visibleElement(`[data-add-kind="${kind}"]`)
}
return visibleElement(`[data-tool="${TOOL_OF[kind]}"]`)
}
/**
* Escape or « Abandonner » outside the dialog (a tracing, a point being replaced): the
* guard is always armed (A12), « Abandonner la création ? » asks; its « Abandonner »
* drops the creation and the focus goes back to what started it.
*/
export function askCreation(): void {
const work = useAnnotationWork.getState().creation
if (!work) return
guardDrawing(() => landAfterModalsClosed(() => creationOpener(work)?.focus()))
}
@@ -12,12 +12,12 @@ import {
} from './correction'
import {
annotationOf,
formProblem,
type CreationForm,
type PendingElement,
} from './creation'
import { defaultRadius, type Frame } from './frame'
import type { EditableGeometry } from './geometryEdit'
import { missingFields, type MissingField } from './missingFields'
/** What « Créer » or the confirmation of C works from. */
export interface CreationInput {
@@ -28,7 +28,10 @@ export interface CreationInput {
context: CommitContext
}
export type Attempt = PointAttempt | { status: 'invalid'; problem: string }
/** `invalid`: the fields R-3 names as missing, nothing tried. */
export type Attempt =
| PointAttempt
| { status: 'invalid'; missing: MissingField[] }
/** The insert of the pending element under a given geometry, through `accept`. */
function inserterOf(input: CreationInput, form: CreationForm) {
@@ -46,8 +49,8 @@ export function createAttempt(
form: CreationForm,
): Attempt {
const { pending, frame } = input
const problem = formProblem(pending.kind, form)
if (problem) return { status: 'invalid', problem }
const missing = missingFields(pending.kind, form)
if (missing.length > 0) return { status: 'invalid', missing }
const insert = inserterOf(input, form)
const { geometry } = pending
if (pending.kind === 'point' && geometry.type === 'circle' && frame) {
@@ -0,0 +1,149 @@
import type { Point } from '@faunosteo/core-wasm/types'
import type { CreationForm, NewKind, PendingElement } from './creation'
import type { Correction } from './correction'
import type { Frame } from './frame'
import type { Tracing } from './uiState'
import { useAnnotationWork, type Creation } from './workStore'
/** Where a creation starts: its view, F, how it began, and the form it starts with. */
export interface CreationStart {
viewId: string
frame: Frame | null
origin: Creation['origin']
form: CreationForm
}
const creation = () => useAnnotationWork.getState().creation
function patch(change: Partial<Creation>): void {
const current = creation()
if (current)
useAnnotationWork.setState({ creation: { ...current, ...change } })
}
/**
* A placed point or a keyboard shape: the dialog opens (A2). A creation of the same kind
* keeps its form (« Replacer le point »: the next click moves the ghost).
*/
export function placePending(
start: CreationStart,
pending: PendingElement,
): void {
const kept = creation()
const same = kept !== null && kept.pending.kind === pending.kind
useAnnotationWork.setState({
creation: {
...start,
form: same ? kept.form : start.form,
resumed: same ? kept.resumed : false,
pending,
closed: true,
dialog: true,
},
})
}
const polygonOf = (kind: NewKind, points: Point[]): PendingElement => ({
kind,
geometry: { type: 'polygon', points },
})
/** The open tracing's vertices; none when no tracing of a new shape is open. */
const tracedPoints = (work: Creation | null): Point[] | null =>
work && !work.closed && work.pending.geometry.type === 'polygon'
? work.pending.geometry.points
: null
/** A vertex of a new zone or link: the first one starts the creation (A12). */
export function traceVertex(
start: CreationStart,
kind: NewKind,
point: Point,
): void {
const points = tracedPoints(creation())
if (points) return patch({ pending: polygonOf(kind, [...points, point]) })
useAnnotationWork.setState({
creation: {
...start,
pending: polygonOf(kind, [point]),
closed: false,
dialog: false,
resumed: false,
},
})
}
/** Backspace or « Retirer le dernier sommet »; a fresh tracing left empty is no creation. */
export function popVertex(): void {
const work = creation()
const points = tracedPoints(work)
if (!work || !points) return
const left = points.slice(0, -1)
if (left.length === 0 && !work.resumed) return dropCreation()
patch({ pending: polygonOf(work.pending.kind, left) })
}
/** The tracing closes (three vertices at least): « Nouvelle zone » opens. */
export function closeTrace(): boolean {
const points = tracedPoints(creation())
if (!points || points.length < 3) return false
patch({ closed: true, dialog: true })
return true
}
/** « Reprendre le tracé »: the dialog hides, the vertices and the form are kept. */
export function resumeTrace(): void {
patch({ closed: false, dialog: false, resumed: true })
}
/** « Replacer le point »: the dialog hides; the next click moves the ghost. */
export function replacePoint(): void {
patch({ dialog: false, resumed: true })
}
/** « Revenir aux propriétés »: a resumed tracing closes again, a point shows its dialog. */
export function backToProperties(): boolean {
const work = creation()
if (!work) return false
if (work.closed) {
patch({ dialog: true })
return true
}
return closeTrace()
}
export function patchForm(change: Partial<CreationForm>): void {
const work = creation()
if (work) patch({ form: { ...work.form, ...change } })
}
/** Candidate C offered by the core's verdict (C26), or withdrawn. */
export function setCorrection(correction: Correction | null): void {
const work = creation()
if (work) patch({ pending: { ...work.pending, correction } })
}
/** « Abandonner », or a guard's « Abandonner »: nothing of the creation is left. */
export function dropCreation(): void {
useAnnotationWork.setState({ creation: null })
}
/** « Créer » succeeded: the creation ends, the drawing selects `id` (A7). */
export function finishCreation(id: string, kind: NewKind): void {
useAnnotationWork.setState({ creation: null, created: { id, kind } })
}
/** The open tracing of a new shape on `viewId`, as the drawing reads a tracing. */
export function creationTracing(
work: Creation | null,
viewId: string,
): Tracing | null {
const points = tracedPoints(work)
if (!work || !points || work.viewId !== viewId) return null
return {
target: work.pending.kind,
annotationId: null,
points,
refused: false,
}
}
+4 -2
View File
@@ -9,6 +9,7 @@ import {
} from '@/editor/focusRequest'
import { CANVAS_BOX } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
import { askCreation } from './creationAsk'
import { commitFocusedSeries } from './drawingGuard'
import { escapeAction, type EscapeAction } from './escape'
import { endMode, useAnnotationWork } from './workStore'
@@ -121,8 +122,9 @@ function runEscape(action: EscapeAction, deselect: () => boolean): boolean {
else if (action === 'drop_mode') endMode()
else if (action === 'unchoose') useAnnotationWork.setState({ chosen: null })
else if (action === 'deselect') return deselect()
// `ask_creation`: the creation dialog asks (U2 Task 7); nothing here yet.
return action !== null && action !== 'ask_creation'
// The dialog hidden (a tracing, a point being replaced): « Abandonner la création ? ».
else if (action === 'ask_creation') askCreation()
return action !== null
}
/** Where Escape applies: the editable body runs the work order; the read-only twin deselects. */
@@ -28,21 +28,30 @@ function endModeOnly(): void {
* (false).
*/
export function guardDrawing(proceed: () => void): boolean {
const work = guardWork(useAnnotationWork.getState())
const state = useAnnotationWork.getState()
const work = guardWork(state)
if (work === null) {
commitFocusedSeries()
endModeOnly()
return true
}
useAnnotationWork.setState({ question: { work, proceed } })
// A question already open keeps its own move (a Back over it is not replayed).
if (state.question === null) {
useAnnotationWork.setState({ question: { work, proceed } })
}
return false
}
/** « Continuer » keeps the work as it is; « Abandonner » drops it and makes the move. */
/**
* « Continuer » keeps the work as it is; « Abandonner » drops the work the question
* named (the mode, or the whole creation) and makes the move.
*/
export function answerDrawing(discard: boolean): void {
const { question } = useAnnotationWork.getState()
useAnnotationWork.setState({ question: null })
if (!discard || !question) return
endMode()
if (question.work === 'creation')
useAnnotationWork.setState({ creation: null })
else endMode()
question.proceed()
}
@@ -35,13 +35,13 @@ export interface DrawingState {
}
const BUSY_TARGET = {
creation: '[data-creation-heading]',
creation: '[data-creation-focus]',
tracing: '[data-testid="tracing-commands"]',
} as const
const focusFirst = (selector: string) => visibleElement(selector)?.focus()
/** A creation or tracing in progress keeps the request: focus its panel, say why. */
/** A creation or tracing in progress keeps the request: focus its dialog or the strip, say why. */
function keepBusy(
busy: NonNullable<DrawingState['busy']>,
announce: (text: string) => void,
+33 -3
View File
@@ -10,7 +10,8 @@ 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'
import type { ToolId, Tracing } from './uiState'
import type { Creation } from './workStore'
/** The strip's left part: what is selected or in progress, then its type and detail. */
export interface StripLead {
@@ -130,6 +131,27 @@ function pendingLead(pending: PendingElement, ctx: LeadContext): StripLead {
}
}
/**
* A creation whose dialog is shown or was (board 04 C): placed or closed, waiting for its
* properties; a point being replaced says where to click; a resumed tracing says the
* input is kept. A fresh tracing reads as a tracing.
*/
function creationLead(work: Creation, ctx: LeadContext): StripLead | null {
const { pending } = work
const title = ctx.t(`editor.annotations.new.${pending.kind}`)
const icon = ICON[pending.kind]
if (work.closed && !work.dialog && pending.geometry.type === 'circle') {
return {
title,
detail: ctx.t('editor.annotations.strip.place_point'),
icon,
}
}
if (work.closed) return pendingLead(pending, ctx)
if (!work.resumed) return null
return { title, detail: ctx.t('editor.annotations.strip.resumed'), icon }
}
const TOOL_LEAD: Record<
ToolId,
{ title: string; detail: string; icon: GlyphName }
@@ -156,14 +178,22 @@ const TOOL_LEAD: Record<
},
}
/** What the strip reads of the drawing: the tool, the tracing shown, the creation. */
export interface LeadState {
tool: ToolId
tracing: Tracing | null
creation?: Creation | null
}
/** What the strip leads with: a creation, then a tracing, then the selection, then the tool. */
export function stripLeadOf(
ui: UiState,
ui: LeadState,
selected: Annotation | undefined,
doc: AnatomicalSheetDocument,
ctx: LeadContext,
): StripLead {
if (ui.pending) return pendingLead(ui.pending, ctx)
const creation = ui.creation ? creationLead(ui.creation, ctx) : null
if (creation) return creation
if (ui.tracing) {
const replaced = doc.annotations.find(
(a) => a.id === ui.tracing?.annotationId,
+5 -29
View File
@@ -1,9 +1,12 @@
import type { Point } from '@faunosteo/core-wasm/types'
import type { NewKind, PendingElement } from './creation'
import type { NewKind } from './creation'
export type ToolId = 'select' | 'point' | 'zone' | 'link'
/** A tracing in progress: a new zone or link, or a polygon replacing a geometry. */
/**
* A tracing in progress: a new zone or link, or a polygon replacing a geometry. Only a
* redraw's tracing is the reducer's; a new shape's lives in the creation (work store).
*/
export interface Tracing {
target: NewKind | 'replace'
/** The annotation whose geometry the tracing replaces (target `replace`). */
@@ -17,9 +20,6 @@ export interface UiState {
viewId: string | null
tool: ToolId
selectedId: string | null
pending: PendingElement | null
/** Bumped by every new pending element: keys the creation form's own state. */
serial: number
tracing: Tracing | null
hint: string | null
/** The overview's « Filtrer par nom » term: it outlives a selection, not a view. */
@@ -32,9 +32,6 @@ export type UiAction =
| { type: 'view'; viewId: string }
| { type: 'tool'; tool: ToolId }
| { type: 'select'; id: string | null }
| { type: 'pending_new'; pending: PendingElement }
| { type: 'pending_update'; pending: PendingElement }
| { type: 'pending_drop' }
| { type: 'trace_start'; target: Tracing['target']; annotationId?: string }
| { type: 'trace_add'; point: Point }
| { type: 'trace_pop' }
@@ -48,8 +45,6 @@ export const initialUi: UiState = {
viewId: null,
tool: 'select',
selectedId: null,
pending: null,
serial: 0,
tracing: null,
hint: null,
filter: '',
@@ -88,32 +83,13 @@ export function uiReducer(state: UiState, action: UiAction): UiState {
...state,
tool: toolAfterTracing(state),
selectedId: action.id,
pending: null,
tracing: null,
hint: null,
}
case 'pending_new':
return {
...state,
pending: action.pending,
// A second click with the same kind keeps the typed fields (same panel).
serial:
state.pending?.kind === action.pending.kind
? state.serial
: state.serial + 1,
selectedId: null,
tracing: null,
hint: null,
}
case 'pending_update':
return state.pending ? { ...state, pending: action.pending } : state
case 'pending_drop':
return { ...state, pending: null, hint: null }
case 'trace_start':
return {
...state,
tool: TOOL_OF[action.target],
pending: null,
hint: null,
tracing: {
target: action.target,
@@ -0,0 +1,75 @@
import { useEffect, useRef, type Dispatch } from 'react'
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import { landAfterModalsClosed } from '@/components/ui/afterModalsClosed'
import type { NewKind } from './creation'
import { dropCreation } from './creationWork'
import { focusRowOrDrawing } from './deselect'
import type { ToolId, UiAction, UiState } from './uiState'
import type { GestureMessages } from './useGestureMessage'
import { useAnnotationWork, type Creation } from './workStore'
const TOOL_OF: Record<NewKind, ToolId> = {
point: 'point',
zone: 'zone',
detail_trigger: 'link',
}
export interface CreationFollow {
doc: AnatomicalSheetDocument
ui: UiState
dispatch: Dispatch<UiAction>
creation: Creation | null
message: Pick<GestureMessages, 'show'>
t: (key: string) => string
}
/**
* The drawing kept in step with the creation: nothing selected once its shape is placed, its tool
* on while the dialog is hidden (« Replacer le point » places with the point tool, a
* resumed tracing traces), and dropped when its view no longer exists.
*/
function useDrawingFollows({ doc, ui, dispatch, creation }: CreationFollow) {
const wanted =
creation && !creation.dialog ? TOOL_OF[creation.pending.kind] : null
// A placed or closed shape takes the stage; a fresh tracing keeps the selection under
// it, as before, so abandoning it gives the selection back.
const selected = creation?.closed === true && ui.selectedId !== null
const gone =
creation !== null && !doc.views.some((v) => v.id === creation.viewId)
useEffect(() => {
if (wanted && wanted !== ui.tool) dispatch({ type: 'tool', tool: wanted })
}, [wanted, ui.tool, dispatch])
useEffect(() => {
if (selected) dispatch({ type: 'select', id: null })
}, [selected, dispatch])
useEffect(() => {
if (gone) dropCreation()
}, [gone])
}
/**
* « Créer » succeeded (A7): the tool goes back to « Sélectionner », the new annotation is
* selected, the line under the drawing says « Point créé · Défaire » and the focus goes to
* its row once the dialog has closed (board 32).
*/
function useCreatedFollows({ dispatch, message, t }: CreationFollow) {
const created = useAnnotationWork((s) => s.created)
const latest = useRef({ message, t })
latest.current = { message, t }
useEffect(() => {
if (!created) return
useAnnotationWork.setState({ created: null })
dispatch({ type: 'tool', tool: 'select' })
dispatch({ type: 'select', id: created.id })
const text = latest.current.t(
`editor.annotations.message.created.${created.kind}`,
)
latest.current.message.show(text, { undo: true, tone: 'info' })
landAfterModalsClosed(() => void focusRowOrDrawing(created.id))
}, [created, dispatch])
}
export function useCreationFollow(input: CreationFollow): void {
useDrawingFollows(input)
useCreatedFollows(input)
}
+41 -22
View File
@@ -7,7 +7,15 @@ import type {
} from '@faunosteo/core-wasm/types'
import { useT } from '@/i18n/useT'
import { updateGeometry, type CommitContext } from './annotationCommit'
import { pendingForClick, type NewKind } from './creation'
import { emptyForm, pendingForClick, type NewKind } from './creation'
import {
closeTrace,
placePending,
popVertex,
traceVertex,
type CreationStart,
} from './creationWork'
import { askCreation } from './creationAsk'
import { round2, type Frame, type XY } from './frame'
import { newPointSize } from './pointSize'
import { endMode, useAnnotationWork } from './workStore'
@@ -22,6 +30,8 @@ const TOOL_TARGET: Record<Exclude<ToolId, 'select'>, NewKind> = {
export interface PlacementInput {
ui: UiState
/** The tracing shown: a redraw's (the reducer's) or a new shape's (the creation's). */
tracing: Tracing | null
dispatch: Dispatch<UiAction>
frame: Frame | null
doc: AnatomicalSheetDocument
@@ -64,44 +74,52 @@ function closeRedraw(input: PlacementInput, tracing: Tracing): void {
input.message.show(text, { undo: true, tone: 'info' })
}
/** Tracing with the zone and link tools: vertices, closing, Enter, Backspace and Escape. */
/** Where a creation on this view starts: F, the origin, a fresh form (A4). */
export const creationStart = (
{ viewId, frame, doc }: Pick<PlacementInput, 'viewId' | 'frame' | 'doc'>,
origin: CreationStart['origin'],
): CreationStart => ({ viewId, frame, origin, form: emptyForm(doc) })
const isRedraw = (tracing: Tracing | null) => tracing?.target === 'replace'
/**
* Tracing with the zone and link tools: vertices, closing, Enter, Backspace and Escape. A
* redraw's tracing is the reducer's; a new shape's is the creation's (A12): its Escape
* asks « Abandonner la création ? » (board 32 row 3).
*/
function tracingActions(input: PlacementInput) {
const { ui, dispatch } = input
const { tracing, 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 })
if (isRedraw(tracing)) return closeRedraw(input, tracing)
closeTrace()
}
const trace = (
tool: Exclude<ToolId, 'select' | 'point'>,
at: XY,
reach: number,
) => {
if (ui.tracing && nearFirstVertex(ui.tracing, at, reach)) {
return closeTracing()
}
if (!ui.tracing)
dispatch({ type: 'trace_start', target: TOOL_TARGET[tool] })
dispatch({ type: 'trace_add', point: asPoint(at) })
if (tracing && nearFirstVertex(tracing, at, reach)) return closeTracing()
if (isRedraw(tracing))
return dispatch({ type: 'trace_add', point: asPoint(at) })
traceVertex(creationStart(input, 'tool'), TOOL_TARGET[tool], asPoint(at))
}
const pop = () =>
isRedraw(tracing) ? dispatch({ type: 'trace_pop' }) : popVertex()
const onTraceKey = (event: KeyboardEvent) => {
if (!ui.tracing) return
if (!tracing) return
if (event.key === 'Enter') closeTracing()
if (event.key === 'Backspace') {
event.preventDefault()
dispatch({ type: 'trace_pop' })
pop()
}
if (event.key === 'Escape') {
event.preventDefault()
dispatch({ type: 'trace_cancel' })
if (isRedraw(tracing)) dispatch({ type: 'trace_cancel' })
else askCreation()
}
}
return { closeTracing, trace, onTraceKey }
return { closeTracing, trace, onTraceKey, pop }
}
/**
@@ -174,7 +192,8 @@ export function usePlacement(input: PlacementInput) {
const size = newPointSize(doc.annotations, viewId, frame, ui.size)
const outcome = pendingForClick(frame, at, size)
if (outcome.kind === 'pending') {
return dispatch({ type: 'pending_new', pending: outcome.pending })
dispatch({ type: 'hint', hint: null })
return placePending(creationStart(input, 'tool'), outcome.pending)
}
dispatch({ type: 'hint', hint: t('editor.annotations.outside') })
}
@@ -183,6 +202,6 @@ export function usePlacement(input: PlacementInput) {
onDrop: dropAction(input),
onTraceKey: tracing.onTraceKey,
closeTracing: tracing.closeTracing,
popVertex: () => dispatch({ type: 'trace_pop' }),
popVertex: tracing.pop,
}
}
+20 -1
View File
@@ -1,6 +1,7 @@
import { create } from 'zustand'
import type { Geometry } from '@faunosteo/core-wasm/types'
import type { CreationForm, PendingElement } from './creation'
import type { CreationForm, NewKind, PendingElement } from './creation'
import type { Frame } from './frame'
/** A geometry shown but not committed, stamped with the document text it was computed on. */
export interface Preview {
@@ -14,13 +15,29 @@ export interface Chosen {
vertex: number
base: string
}
/**
* A creation in progress (A12): the only owner of the new shape and of its form, read by
* the drawing and by the creation dialog, which lives outside the edit-only body (R-14).
*/
export interface Creation {
viewId: string
/** F of the view when the shape was placed: the point's verdict works from it. */
frame: Frame | null
/** A tool on the drawing, or a keyboard « Ajouter … » (where the focus goes back). */
origin: 'tool' | 'keyboard'
/** A new zone or link being traced lives here from its first vertex (`closed` false). */
pending: PendingElement
closed: boolean
form: CreationForm
/** The dialog is shown; false while the shape is replaced or the trace resumed. */
dialog: boolean
/** The dialog was shown once: « Replacer le point » or « Reprendre le tracé » ran. */
resumed: boolean
}
/** The annotation « Créer » just inserted: the drawing selects it and says so (A7). */
export interface Created {
id: string
kind: NewKind
}
/**
* A move mode or a redraw, stamped with the document text it started on; `started` once
@@ -42,6 +59,7 @@ export interface DrawingQuestion {
}
interface Work {
creation: Creation | null
created: Created | null
mode: ModeWork | null
preview: Preview | null
chosen: Chosen | null
@@ -51,6 +69,7 @@ interface Work {
}
const NO_WORK: Work = {
creation: null,
created: null,
mode: null,
preview: null,
chosen: null,
@@ -10,6 +10,7 @@ import {
landAfterModalsClosed,
} from '@/components/ui/afterModalsClosed'
import { guardDrawing } from '../annotations/drawingGuard'
import { useAnnotationWork } from '../annotations/workStore'
import { focusActiveTab } from '../focusRequest'
import { LAYERS_TOP_DOWN } from '../leftDraft'
import { citationsOfView, sameView, type EditorView } from '../navigation'
@@ -251,6 +252,9 @@ function refusal(
const { nav, view } = ctx
if (document.querySelector('dialog[open]:not([data-layer])')) {
nav.guards.askAll(false)
// The creation dialog is such a modal: its « Abandonner la création ? » shows inside.
if (useAnnotationWork.getState().creation?.dialog)
guardDrawing(() => undefined)
return 'modal'
}
const leaving = leavingLayers(view, entry?.view ?? ctx.defaultView)
+3 -1
View File
@@ -1,5 +1,5 @@
import { useEffect } from 'react'
import { cancelPending } from './annotations/workStore'
import { cancelPending, useAnnotationWork } from './annotations/workStore'
import { isTextField } from './focusRequest'
import { useEditorStore } from './state/editorStore'
@@ -17,6 +17,8 @@ export function useUndoShortcuts(writable: boolean): void {
// A text field keeps its own undo; a slider or a checkbox does not (R-13).
if (isTextField(event.target)) return
if (document.querySelector(MODAL_OPEN)) return
// A12: undo is inactive during a creation, its dialog shown or not (R-13).
if (useAnnotationWork.getState().creation) return
if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== 'z')
return
event.preventDefault()
+476 -268
View File
File diff suppressed because it is too large. Load diff
+546 -292
View File
File diff suppressed because it is too large. Load diff
+33 -8
View File
@@ -1,14 +1,24 @@
@import 'tailwindcss';
@import './tokens.css';
html, body, #root { height: 100%; }
html,
body,
#root {
height: 100%;
}
/* A modal dialog is open (components/ui/ModalDialog): the page behind it does not scroll. */
html:has(dialog:modal) { overflow: hidden; }
html:has(dialog:modal) {
overflow: hidden;
}
/* The editor keeps its scrollbar width whatever opens or closes (R-2, A14): nothing moves. */
html:has([data-editor-workspace]) { scrollbar-gutter: stable; }
html:has([data-editor-workspace]) {
scrollbar-gutter: stable;
}
/* Nor does the browser's scroll anchoring move it: a side panel growing under a tap at the
page's end scrolled the drawing under the finger (U2 Task 5 fix round, A14). */
body:has([data-editor-workspace]) { overflow-anchor: none; }
body:has([data-editor-workspace]) {
overflow-anchor: none;
}
body {
background: var(--color-bg);
color: var(--color-ink);
@@ -16,9 +26,24 @@ body {
-webkit-font-smoothing: antialiased;
}
.svg-canvas [data-state='current'] { fill: var(--color-accent) !important; fill-opacity: 0.85 !important; }
.svg-canvas [data-anno-id] { cursor: pointer; }
.svg-canvas [data-anno-id]:hover { filter: brightness(1.05); }
.svg-canvas [data-state='current'] {
fill: var(--color-accent) !important;
fill-opacity: 0.85 !important;
}
.svg-canvas [data-anno-id] {
cursor: pointer;
}
.svg-canvas [data-anno-id]:hover {
filter: brightness(1.05);
}
/* A creation in progress (A12): the other markers are dimmed and read as unselectable. */
.svg-canvas[data-creating] [data-anno-id] {
opacity: 0.35;
cursor: crosshair;
}
.svg-canvas[data-creating] [data-anno-id]:hover {
filter: none;
}
.zone-tooltip {
position: absolute;
@@ -30,7 +55,7 @@ body {
white-space: nowrap;
background: var(--color-ink);
color: var(--color-bg);
box-shadow: 0 2px 8px rgba(0,0,0,.18);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
transition: opacity 120ms ease;
z-index: 50;
}
@@ -1,4 +1,5 @@
/** U2 Task 6: the Annotations tab with a real navigation, so its properties dialog opens. */
import DrawingGuardDialog from '@/components/editor/annotations/DrawingGuardDialog'
import AnnotationsTab, {
type AnnotationsTabProps,
} from '@/components/editor/tabs/AnnotationsTab'
@@ -20,6 +21,8 @@ export function LayeredTab(
return (
<AnnounceContext value={nav.announce}>
<AnnotationsTab {...props} annotationLayer={annotationLayerOf(nav)} />
{/* The workspace's drawing question (R-12), as EditorWorkspace mounts it. */}
<DrawingGuardDialog />
<p data-testid="live-region">{nav.live}</p>
</AnnounceContext>
)
@@ -18,8 +18,11 @@ import {
setModePreview,
startMove,
startRedraw,
useAnnotationWork,
} from '@/editor/annotations/workStore'
import { useLeaveGuardStore } from '@/state/leaveGuardStore'
import { emptyForm } from '@/editor/annotations/creation'
import { traceVertex } from '@/editor/annotations/creationWork'
const user = fakeUser()
const OTHER = 'bbbbbbbb-0000-0000-0000-000000000002'
@@ -203,3 +206,44 @@ describe('SignOutButton and a started redraw (R-12)', () => {
expect(screen.queryByRole('dialog')).toBeNull()
})
})
describe('SignOutButton during a creation (R-12, A12)', () => {
beforeEach(() => {
useLeaveGuardStore.getState().setAsk(guardDrawing)
// A tracing with one vertex: no dialog, a shape exists.
traceVertex(
{
viewId: 'v',
frame: null,
origin: 'tool',
form: emptyForm({ categories: [] } as never),
},
'zone',
[1, 1],
)
})
afterEach(() => {
useLeaveGuardStore.getState().setAsk(null)
resetWork()
})
it('asks « Abandonner la création ? »; « Continuer » keeps it, « Abandonner » signs out', async () => {
render(
<MemoryRouter>
<SignOutButton />
<DrawingGuardDialog />
</MemoryRouter>,
)
await click()
expect(
screen.getByRole('dialog', { name: 'Abandonner la création ?' }),
).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Continuer' }))
expect(signOut).not.toHaveBeenCalled()
expect(useAnnotationWork.getState().creation).not.toBeNull()
await click()
await userEvent.click(screen.getByRole('button', { name: 'Abandonner' }))
await waitFor(() => expect(signOut).toHaveBeenCalledTimes(1))
expect(useAnnotationWork.getState().creation).toBeNull()
})
})
@@ -207,6 +207,7 @@ describe('an edit on the drawing (U2 Task 5: the numeric group left the panel)',
})
})
/** The creation dialog's form (U2 Task 7: no side panel, no coordinate field, A8). */
async function fillCreation(user: ReturnType<typeof userEvent.setup>) {
const panel = await screen.findByTestId('annotation-creation')
await user.type(within(panel).getByLabelText('Nom (FR)'), 'Nuque')
@@ -218,6 +219,10 @@ async function fillCreation(user: ReturnType<typeof userEvent.setup>) {
return panel
}
/** The ghost of the new shape: its filled shape, drawn by the overlay. */
const ghostShape = () =>
screen.getByTestId('overlay-ghost').querySelector('circle, polygon')!
describe('the keyboard creation path', () => {
it('holds a point at the frame centre, asks the required fields, then inserts once', async () => {
await mount({ text: drawnText() })
@@ -228,8 +233,11 @@ describe('the keyboard creation path', () => {
).toBeEnabled(),
)
await user.click(screen.getByRole('button', { name: 'Ajouter un point' }))
expect(
await screen.findByRole('dialog', { name: 'Nouveau point' }),
).toBeInTheDocument()
const panel = await fillCreation(user)
expect(within(panel).getByLabelText('Centre x')).toHaveValue('50')
expect(ghostShape()).toHaveAttribute('cx', '50')
expect(within(panel).getByLabelText('Latéralité')).toHaveValue('unpaired')
expect(annotations()).toHaveLength(0)
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
@@ -240,10 +248,16 @@ describe('the keyboard creation path', () => {
laterality: 'unpaired',
geometry: { type: 'circle', cx: 50, cy: 50 },
})
// A7: the new point selected (the strip offers its properties).
// A7: back to « Sélectionner », the new point selected, « Point créé · Défaire ».
expect(
await screen.findByRole('button', { name: 'Propriétés' }),
).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Sélectionner et déplacer' }),
).toHaveAttribute('aria-pressed', 'true')
expect(screen.getByTestId('gesture-line')).toHaveTextContent('Point créé')
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(store.getState().undo).toHaveLength(1)
})
it('refuses a creation without laterality and creates nothing', async () => {
@@ -259,13 +273,22 @@ describe('the keyboard creation path', () => {
await user.type(within(panel).getByLabelText('Nom (FR)'), 'A')
await user.type(within(panel).getByLabelText('Nom (EN)'), 'B')
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
expect(within(panel).getByRole('alert')).toHaveTextContent(
'Choisissez la catégorie et la latéralité',
)
// R-3, board 33 B: only the missing field is named, under it and in the summary.
const alerts = within(panel).getAllByRole('alert')
expect(alerts.map((a) => a.textContent)).toEqual([
'Choisissez une latéralité.',
'À compléter : Latéralité.',
])
expect(
within(panel).getByText('Choisissez une latéralité.'),
).toBeInTheDocument()
expect(within(panel).queryByText(/Choisissez une catégorie/)).toBeNull()
expect(within(panel).queryByText(/Saisissez/)).toBeNull()
expect(within(panel).getByLabelText('Latéralité')).toHaveFocus()
expect(annotations()).toHaveLength(0)
})
it('applies the geometry group to a pending zone, the core deciding at « Créer »', async () => {
it('places a triangle at the centre: the ghost shows it, « Créer » inserts it (A8: no field)', async () => {
await mount({ text: drawnText() })
const user = userEvent.setup()
await waitFor(() =>
@@ -275,14 +298,14 @@ describe('the keyboard creation path', () => {
)
await user.click(screen.getByRole('button', { name: 'Ajouter une zone' }))
const panel = await fillCreation(user)
const x = within(panel).getByLabelText('x du sommet 1')
await user.clear(x)
await user.type(x, '500{Enter}')
expect(within(panel).getByLabelText('x du sommet 1')).toHaveValue('500')
expect(within(panel).queryByLabelText('x du sommet 1')).toBeNull()
expect(
within(panel).getByText('Zone tracée, 3 sommets'),
).toBeInTheDocument()
expect(ghostShape().tagName).toBe('polygon')
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
expect(annotations()).toHaveLength(0)
expect(within(panel).getByRole('alert')).toBeInTheDocument()
expect(within(panel).getByLabelText('x du sommet 1')).toHaveValue('500')
expect(annotations()[0]).toMatchObject({ kind: 'zone' })
expect(annotations()[0].geometry).toMatchObject({ type: 'polygon' })
})
})
@@ -301,8 +324,12 @@ describe('the point tool and the corrected position (C26)', () => {
)
const user = await clickCorner()
const notice = await screen.findByTestId('correction-notice')
// R-4: the notice is in the dialog, without numbers.
expect(
screen.getByRole('dialog', { name: 'Nouveau point' }),
).toContainElement(notice)
expect(notice).toHaveTextContent(
'Position corrigée proposée : x = 15, y = 15.',
"Le point ne tient pas à l'endroit choisi : la position corrigée est proposée sur le dessin.",
)
expect(screen.getByTestId('overlay-click-cross')).toBeInTheDocument()
const panel = await fillCreation(user)
@@ -316,7 +343,7 @@ describe('the point tool and the corrected position (C26)', () => {
cy: 15,
r: 15,
})
expect(panel).not.toBeInTheDocument()
await waitFor(() => expect(panel).not.toBeInTheDocument())
expect(screen.queryByTestId('overlay-click-cross')).toBeNull()
await screen.findByRole('button', { name: 'Propriétés' })
expect(shownCircle()).toHaveAttribute('cx', '15')
@@ -332,28 +359,8 @@ describe('the point tool and the corrected position (C26)', () => {
await user.click(within(notice).getByRole('button', { name: 'Annuler' }))
expect(screen.queryByTestId('correction-notice')).toBeNull()
expect(screen.queryByTestId('overlay-click-cross')).toBeNull()
const panel = screen.getByTestId('annotation-creation')
expect(within(panel).getByLabelText('Centre x')).toHaveValue('0')
expect(annotations()).toHaveLength(0)
})
it('offers the correction when the core refuses a pending point', async () => {
await mount({ text: drawnText() })
const user = userEvent.setup()
await waitFor(() =>
expect(
screen.getByRole('button', { name: 'Ajouter un point' }),
).toBeEnabled(),
)
await user.click(screen.getByRole('button', { name: 'Ajouter un point' }))
const panel = await fillCreation(user)
const cx = within(panel).getByLabelText('Centre x')
await user.clear(cx)
await user.type(cx, '98{Enter}')
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
expect(await screen.findByTestId('correction-notice')).toHaveTextContent(
'x = 85',
)
expect(screen.getByTestId('annotation-creation')).toBeInTheDocument()
expect(ghostShape()).toHaveAttribute('cx', '0')
expect(annotations()).toHaveLength(0)
})
@@ -590,8 +597,11 @@ describe('tracing a zone or a link', () => {
screen.getByRole('button', { name: 'Fermer le tracé' }),
).toBeEnabled()
fireEvent.keyDown(screen.getByTestId('annotation-canvas'), { key: 'Enter' })
expect(
await screen.findByRole('dialog', { name: 'Nouvelle zone' }),
).toBeInTheDocument()
const panel = await fillCreation(user)
expect(within(panel).getByLabelText('x du sommet 3')).toHaveValue('50')
expect(ghostShape()).toHaveAttribute('points', triangle.join(' '))
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
expect(annotations()[0]).toMatchObject({
kind: 'zone',
@@ -599,21 +609,48 @@ describe('tracing a zone or a link', () => {
})
})
it('drops the tracing on Escape with nothing created', async () => {
it('Escape on a tracing asks first (board 32 row 3); « Abandonner » drops it', async () => {
await mount({ text: drawnText() })
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Zone' })).toBeEnabled(),
)
await userEvent.setup().click(screen.getByRole('button', { name: 'Zone' }))
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Zone' }))
clickAt(20, 20)
expect(screen.getByText('1 sommet posé')).toBeInTheDocument()
fireEvent.keyDown(screen.getByTestId('annotation-canvas'), {
key: 'Escape',
})
const ask = await screen.findByRole('dialog', {
name: 'Abandonner la création ?',
})
await user.click(within(ask).getByRole('button', { name: 'Continuer' }))
expect(screen.getByText('1 sommet posé')).toBeInTheDocument()
fireEvent.keyDown(screen.getByTestId('annotation-canvas'), {
key: 'Escape',
})
await user.click(
within(
await screen.findByRole('dialog', { name: 'Abandonner la création ?' }),
).getByRole('button', { name: 'Abandonner' }),
)
expect(screen.queryByText('1 sommet posé')).toBeNull()
expect(annotations()).toHaveLength(0)
})
it('« Annuler le tracé » is an explicit cancel: it acts at once', async () => {
await mount({ text: drawnText() })
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Zone' })).toBeEnabled(),
)
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Zone' }))
clickAt(20, 20)
await user.click(screen.getByRole('button', { name: 'Annuler le tracé' }))
expect(screen.queryByRole('dialog')).toBeNull()
expect(screen.queryByText('1 sommet posé')).toBeNull()
})
it('closes on a click at the first vertex once three are placed', async () => {
await mount({ text: drawnText() })
await waitFor(() =>
@@ -792,42 +829,17 @@ describe('a second click with the point tool (H6)', () => {
await user.click(screen.getByRole('button', { name: 'Point' }))
pressAt(screen.getByTestId('annotation-canvas'), 50, 50)
const panel = await fillCreation(user)
// « Replacer le point »: the dialog hides, the next click moves the ghost and shows it.
await user.click(
within(panel).getByRole('button', { name: 'Replacer le point' }),
)
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(ghostShape()).toHaveAttribute('cx', '50')
pressAt(screen.getByTestId('annotation-canvas'), 60, 40)
await waitFor(() =>
expect(within(panel).getByLabelText('Centre x')).toHaveValue('60'),
)
expect(within(panel).getByLabelText('Nom (FR)')).toHaveValue('Nuque')
expect(within(panel).getByLabelText('Latéralité')).toHaveValue('unpaired')
expect(screen.getByTestId('annotation-creation')).toBe(panel)
})
})
describe('a typed radius (H5)', () => {
it('shows the core issue, not a corrected position', async () => {
const drawing = svgBytes('0 0 5000 5000')
sb.getSheetVersion.mockResolvedValue({
...versionAnswer(drawnText(), 3),
drawings: [{ asset_id: ASSET, sha256: drawing.sha256 }],
} as never)
sb.downloadSheetDrawing.mockResolvedValue(drawing.bytes)
store.getState().open(VERSION, USER, { canEdit: true })
await waitFor(() => expect(store.getState().status).toBe('ready'))
render(<AnnotationsTab {...props} />)
await waitFor(() =>
expect(
screen.getByRole('button', { name: 'Ajouter un point' }),
).toBeEnabled(),
)
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Ajouter un point' }))
const panel = await fillCreation(user)
const r = within(panel).getByLabelText('Rayon')
await user.clear(r)
await user.type(r, '1{Enter}')
await user.click(within(panel).getByRole('button', { name: 'Créer' }))
expect(screen.queryByTestId('correction-notice')).toBeNull()
expect(within(panel).getByRole('alert')).toBeInTheDocument()
expect(annotations()).toHaveLength(0)
const again = await screen.findByTestId('annotation-creation')
expect(ghostShape()).toHaveAttribute('cx', '60')
expect(within(again).getByLabelText('Nom (FR)')).toHaveValue('Nuque')
expect(within(again).getByLabelText('Latéralité')).toHaveValue('unpaired')
})
})
@@ -853,9 +865,9 @@ describe('the frame follows the view (H7)', () => {
).toBeEnabled(),
)
await user.click(screen.getByRole('button', { name: 'Ajouter un point' }))
const panel = await screen.findByTestId('annotation-creation')
expect(within(panel).getByLabelText('Centre x')).toHaveValue('30')
expect(within(panel).getByLabelText('Centre y')).toHaveValue('50')
await screen.findByTestId('annotation-creation')
expect(ghostShape()).toHaveAttribute('cx', '30')
expect(ghostShape()).toHaveAttribute('cy', '50')
})
})
@@ -1870,6 +1882,7 @@ describe('the strip', () => {
const { result } = renderHook(() =>
usePlacement({
ui: { ...initialUi, hint: 'Refusé' },
tracing: null,
dispatch,
frame: null,
doc,
@@ -0,0 +1,314 @@
/** U2 Task 7: creation on the drawing, then the creation dialog (A2, A4, A5, A7, A12, A15). */
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 HistoryButtons from '@/components/editor/HistoryButtons'
import { useUndoShortcuts } from '@/editor/useUndoShortcuts'
import { useAnnotationWork } from '@/editor/annotations/workStore'
import { useLocaleStore } from '@/state/localeStore'
import { drawnText, insert, point } from '../helpers/editorFixtures'
import { LayeredTab } from '../helpers/annotationLayer'
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(),
}
/** Screen = drawing: the overlay's inverse CTM is the identity in the page under test. */
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()
})
/** A second category, coloured, so the ghost's colour can follow the form (A4). */
function twoCategories(): string {
return insert(insert(drawnText(), point('anno-a', 20, 20, 5)), {
kind: 'category',
value: { id: 'cat-b', name: { fr: 'Os', en: 'Bone' }, color: '#aa3366' },
} as never)
}
/** The tab with the header's history controls, as the workspace shows them. */
function Page() {
useUndoShortcuts(true)
return (
<>
<HistoryButtons />
<LayeredTab {...props} />
</>
)
}
async function mount(text = twoCategories()) {
await openReady({ text })
render(<Page />)
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Point' })).toBeEnabled(),
)
return userEvent.setup()
}
const canvas = () => screen.getByTestId('annotation-canvas')
const ghost = () => screen.getByTestId('overlay-ghost')
const creation = () => useAnnotationWork.getState().creation
const annotations = () => store.getState().previewState!.document.annotations
const dialog = (name = 'Nouveau point') => screen.findByRole('dialog', { name })
async function placePoint(user: ReturnType<typeof userEvent.setup>) {
await user.click(screen.getByRole('button', { name: 'Point' }))
pressAt(canvas(), 50, 50)
return dialog()
}
describe('the creation dialog asks before leaving, always (A12)', () => {
it('✕ with nothing typed asks; « Continuer » keeps the shape', async () => {
const user = await mount()
const shown = await placePoint(user)
await user.click(within(shown).getByRole('button', { name: 'Fermer' }))
const ask = within(shown).getByRole('group', {
name: 'Abandonner la création ?',
})
await user.click(within(ask).getByRole('button', { name: 'Continuer' }))
expect(screen.getByRole('dialog', { name: 'Nouveau point' })).toBe(shown)
expect(creation()).not.toBeNull()
expect(ghost()).toBeInTheDocument()
})
it('Échap with nothing typed asks inside the dialog, never the workspace question', async () => {
const user = await mount()
const shown = await placePoint(user)
await user.keyboard('{Escape}')
expect(
within(shown).getByRole('group', { name: 'Abandonner la création ?' }),
).toBeInTheDocument()
expect(screen.getAllByRole('dialog')).toHaveLength(1)
})
it('« Abandonner » asks, then clears the creation; the focus goes to the tool', async () => {
const user = await mount()
const shown = await placePoint(user)
await user.click(within(shown).getByRole('button', { name: 'Abandonner' }))
expect(creation()).not.toBeNull()
const ask = within(shown).getByRole('group', {
name: 'Abandonner la création ?',
})
await user.click(within(ask).getByRole('button', { name: 'Abandonner' }))
expect(creation()).toBeNull()
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(screen.queryByTestId('overlay-ghost')).toBeNull()
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Point' })).toHaveFocus(),
)
expect(annotations()).toHaveLength(1)
})
it('a keyboard creation abandoned gives the focus back to its « Ajouter … » button', async () => {
const user = await mount()
await user.click(screen.getByRole('button', { name: 'Ajouter une zone' }))
const shown = await dialog('Nouvelle zone')
await user.click(within(shown).getByRole('button', { name: 'Abandonner' }))
await user.click(
within(
within(shown).getByRole('group', { name: 'Abandonner la création ?' }),
).getByRole('button', { name: 'Abandonner' }),
)
await waitFor(() =>
expect(
screen.getByRole('button', { name: 'Ajouter une zone' }),
).toHaveFocus(),
)
})
})
describe('placing and the form (A4, A5)', () => {
it('the category prefilled, the laterality without default; a category recolours the ghost', async () => {
const user = await mount()
const shown = await placePoint(user)
expect(within(shown).getByLabelText('Catégorie')).toHaveValue('cat-a')
expect(within(shown).getByLabelText('Latéralité')).toHaveValue('')
expect(within(shown).queryByLabelText('Couleur')).toBeNull()
expect(ghost()).toHaveAttribute('data-colour', 'var(--color-accent)')
await user.selectOptions(within(shown).getByLabelText('Catégorie'), 'cat-b')
expect(ghost()).toHaveAttribute('data-colour', '#aa3366')
})
it('the point tool previews the next point under a mouse, never under a finger', async () => {
const user = await mount()
await user.click(screen.getByRole('button', { name: 'Point' }))
const at = { clientX: 40, clientY: 30 }
fireEvent.pointerMove(canvas(), { ...at, pointerType: 'touch' })
expect(screen.queryByTestId('overlay-point-preview')).toBeNull()
fireEvent.pointerMove(canvas(), { ...at, pointerType: 'mouse' })
const preview = screen.getByTestId('overlay-point-preview')
// A5: the view's most used size (the only point has r = 5).
expect(preview.querySelector('circle')).toHaveAttribute('r', '5')
expect(preview.querySelector('circle')).toHaveAttribute('cx', '40')
fireEvent.pointerLeave(canvas())
expect(screen.queryByTestId('overlay-point-preview')).toBeNull()
})
it('a link shows « Vue ouverte »', async () => {
const text = insert(twoCategories(), {
kind: 'view',
value: {
kind: 'detail',
id: 'view-det',
name: { fr: 'Tête', en: 'Head' },
svg_asset_id: null,
view_box: { min_x: 10, min_y: 10, width: 80, height: 80 },
parent_view_id: 'view-main',
},
} as never)
const user = await mount(text)
await user.click(screen.getByRole('button', { name: 'Ajouter un accès' }))
const shown = await dialog('Nouvel accès')
expect(within(shown).getByLabelText('Vue ouverte')).toBeInTheDocument()
expect(
within(shown).getByText('Accès tracé, 3 sommets'),
).toBeInTheDocument()
})
})
describe('« Reprendre le tracé » and « Revenir aux propriétés » (board 04 C)', () => {
it('keeps the vertices and the form; a new vertex, then the dialog again', async () => {
const user = await mount()
await user.click(screen.getByRole('button', { name: 'Zone' }))
;[
[20, 20],
[80, 20],
[50, 80],
].forEach(([x, y]) => pressAt(canvas(), x, y))
await user.click(screen.getByRole('button', { name: 'Fermer le tracé' }))
let shown = await dialog('Nouvelle zone')
await user.type(within(shown).getByLabelText('Nom (FR)'), 'Tibia')
await user.click(
within(shown).getByRole('button', { name: 'Reprendre le tracé' }),
)
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
const strip = screen.getByTestId('edit-strip')
expect(strip).toHaveTextContent('Tracé repris, saisie gardée')
expect(
within(strip).getByRole('button', { name: 'Retirer le dernier sommet' }),
).toBeEnabled()
pressAt(canvas(), 30, 60)
await user.click(
within(strip).getByRole('button', { name: 'Revenir aux propriétés' }),
)
shown = await dialog('Nouvelle zone')
expect(within(shown).getByLabelText('Nom (FR)')).toHaveValue('Tibia')
expect(
within(shown).getByText('Zone tracée, 4 sommets'),
).toBeInTheDocument()
})
})
describe('« Créer » (A7, board 32)', () => {
it('one insert, one undo; « Sélectionner », the new zone selected, its row focused', async () => {
const user = await mount()
await user.click(screen.getByRole('button', { name: 'Zone' }))
;[
[20, 20],
[80, 20],
[50, 80],
].forEach(([x, y]) => pressAt(canvas(), x, y))
fireEvent.keyDown(canvas(), { key: 'Enter' })
const shown = await dialog('Nouvelle zone')
await user.type(within(shown).getByLabelText('Nom (FR)'), 'Tibia')
await user.type(within(shown).getByLabelText('Nom (EN)'), 'Tibia')
await user.selectOptions(within(shown).getByLabelText('Latéralité'), 'left')
const before = store.getState().undo.length
await user.click(within(shown).getByRole('button', { name: 'Créer' }))
expect(store.getState().undo).toHaveLength(before + 1)
const created = annotations().find((a) => a.kind === 'zone')!
expect(created).toMatchObject({ name: { fr: 'Tibia', en: 'Tibia' } })
expect(screen.getByTestId('gesture-line')).toHaveTextContent('Zone créée')
expect(
screen.getByRole('button', { name: 'Sélectionner et déplacer' }),
).toHaveAttribute('aria-pressed', 'true')
await waitFor(() =>
expect(document.activeElement).toHaveAttribute(
'data-focus-key',
JSON.stringify({ kind: 'annotation', id: created.id }),
),
)
})
})
describe('during a creation (A12, R-13)', () => {
it('the other markers are dimmed; undo is inactive; « Défaire » leaves the line', async () => {
const user = await mount()
// A kept gesture first, so the line under the drawing offers « Défaire ».
await user.click(screen.getByRole('button', { name: 'Point' }))
pressAt(canvas(), 50, 50)
const shown = await dialog()
await user.type(within(shown).getByLabelText('Nom (FR)'), 'A')
await user.type(within(shown).getByLabelText('Nom (EN)'), 'B')
await user.selectOptions(within(shown).getByLabelText('Latéralité'), 'left')
await user.click(within(shown).getByRole('button', { name: 'Créer' }))
const line = screen.getByTestId('gesture-line')
expect(within(line).getByRole('button', { name: /Défaire/ })).toBeTruthy()
expect(canvas()).not.toHaveAttribute('data-creating')
// A tracing: no dialog, the page itself is live.
await user.click(screen.getByRole('button', { name: 'Zone' }))
pressAt(canvas(), 20, 80)
expect(canvas()).toHaveAttribute('data-creating')
expect(within(line).queryByRole('button', { name: /Défaire/ })).toBeNull()
const undo = screen.getByRole('button', { name: /Défaire la dernière/ })
expect(undo).toHaveAttribute('aria-disabled', 'true')
const depth = store.getState().undo.length
await user.click(undo)
fireEvent.keyDown(window, { key: 'z', ctrlKey: true })
expect(store.getState().undo).toHaveLength(depth)
expect(creation()).not.toBeNull()
})
it('Escape while the point is replaced asks « Abandonner la création ? »', async () => {
const user = await mount()
const shown = await placePoint(user)
await user.click(
within(shown).getByRole('button', { name: 'Replacer le point' }),
)
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
act(() => canvas().focus())
fireEvent.keyDown(document.body, { key: 'Escape' })
expect(
await screen.findByRole('dialog', { name: 'Abandonner la création ?' }),
).toBeInTheDocument()
})
})
@@ -28,12 +28,22 @@ import { defaultView, targetOfKey } from '@/editor/navigation'
import { useEditorNavigation } from '@/editor/useEditorNavigation'
import { useLocaleStore } from '@/state/localeStore'
import DrawingGuardDialog from '@/components/editor/annotations/DrawingGuardDialog'
import CreationDialog from '@/components/editor/annotations/CreationDialog'
import { drawnText } from '../helpers/editorFixtures'
import {
markRedraw,
resetWork,
setModePreview,
startMove,
startRedraw,
useAnnotationWork,
} from '@/editor/annotations/workStore'
import { emptyForm } from '@/editor/annotations/creation'
import {
placePending,
replacePoint,
traceVertex,
} from '@/editor/annotations/creationWork'
afterEach(cleanup)
@@ -477,6 +487,212 @@ describe('the drawing guard (R-12): a move mode and the navigations', () => {
})
})
/**
* U2 Task 7 (R-12, A12): every guard site asks during a creation, and for a move mode or a
* redraw once work has started; with nothing started a mode ends at once.
*/
describe('the drawing guard at every site: creation, move, redraw', () => {
const STORED = { type: 'circle' as const, cx: 1, cy: 2, r: 3 }
afterEach(() => act(() => resetWork()))
const tabShown = () => screen.getByRole('tab', { selected: true })
const start = {
viewId: 'v',
frame: null,
origin: 'tool' as const,
form: emptyForm({ categories: [] } as never),
}
const point = {
kind: 'point' as const,
geometry: { type: 'circle' as const, cx: 5, cy: 5, r: 2 },
}
const WORK = {
// A point being replaced: no dialog, nothing typed, still asked (A12).
creation: () => {
placePending(start, point)
replacePoint()
},
tracing: () => traceVertex(start, 'zone', [1, 1]),
move: () => {
startMove('a', 'doc')
setModePreview({ ...STORED, cx: 9 }, STORED)
},
redraw: () => {
startRedraw('a', 'doc')
markRedraw(true)
},
}
const TITLE = {
creation: 'Abandonner la création ?',
tracing: 'Abandonner la création ?',
move: 'Abandonner le déplacement ?',
redraw: 'Abandonner le nouveau tracé ?',
}
const left = () => {
const work = useAnnotationWork.getState()
return work.creation === null && work.mode === null
}
type Kind = keyof typeof WORK
const kinds = Object.keys(WORK) as Kind[]
async function asks(kind: Kind, run: () => Promise<void>) {
const user = userEvent.setup()
await run()
const dialog = screen.getByRole('dialog', { name: TITLE[kind] })
await user.click(within(dialog).getByRole('button', { name: 'Continuer' }))
expect(left()).toBe(false)
return user
}
it.each(kinds)(
'%s: a tab click asks; « Continuer » keeps, « Abandonner » goes',
async (kind) => {
useLocaleStore.setState({ locale: 'fr' })
mount()
act(() => WORK[kind]())
const user = await asks(kind, () =>
userEvent.setup().click(screen.getByRole('tab', { name: 'Constats' })),
)
expect(tabShown()).toHaveTextContent('Général')
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await user.click(screen.getByRole('button', { name: 'Abandonner' }))
expect(tabShown()).toHaveTextContent('Constats')
expect(left()).toBe(true)
},
)
it.each(kinds)(
'%s: an arrow-key tab move asks the same way',
async (kind) => {
useLocaleStore.setState({ locale: 'fr' })
mount()
const general = screen.getByRole('tab', { name: 'Général' })
act(() => general.focus())
act(() => WORK[kind]())
await asks(kind, async () => {
fireEvent.keyDown(general, { key: 'ArrowRight' })
})
expect(tabShown()).toHaveTextContent('Général')
},
)
it.each(kinds)('%s: a section entry asks the same way', async (kind) => {
useLocaleStore.setState({ locale: 'fr' })
mount()
act(() => WORK[kind]())
const user = await asks(kind, () =>
userEvent.setup().click(screen.getByRole('button', { name: 'section' })),
)
await user.click(screen.getByRole('button', { name: 'section' }))
await user.click(screen.getByRole('button', { name: 'Abandonner' }))
expect(left()).toBe(true)
})
it.each(kinds)('%s: a Back asks and keeps the view', async (kind) => {
useLocaleStore.setState({ locale: 'fr' })
const user = userEvent.setup()
mount()
await user.click(screen.getByRole('tab', { name: 'Constats' }))
act(() => WORK[kind]())
act(() => navigate(-1))
expect(tabShown()).toHaveTextContent('Constats')
await user.click(
within(screen.getByRole('dialog', { name: TITLE[kind] })).getByRole(
'button',
{ name: 'Abandonner' },
),
)
expect(left()).toBe(true)
})
it.each(['move', 'redraw'] as const)(
'%s with nothing started: tab, arrow key and section act at once',
async (kind) => {
useLocaleStore.setState({ locale: 'fr' })
const user = userEvent.setup()
mount()
const begin = () =>
kind === 'move' ? startMove('a', 'doc') : startRedraw('a', 'doc')
act(() => begin())
const general = screen.getByRole('tab', { name: 'Général' })
act(() => general.focus())
fireEvent.keyDown(general, { key: 'ArrowRight' })
expect(tabShown()).not.toHaveTextContent('Général')
expect(useAnnotationWork.getState().mode).toBeNull()
act(() => begin())
await user.click(screen.getByRole('button', { name: 'section' }))
expect(useAnnotationWork.getState().mode).toBeNull()
expect(screen.queryByRole('dialog')).toBeNull()
},
)
})
/**
* U2 Task 7: the creation dialog is a modal without a history layer. A Back while it is
* open is refused, and its « Abandonner la création ? » shows inside it. (Under happy-dom
* the refusal is reached through the drawing guard; the browser's modal branch is proved
* by the e2e in editor-annotations.spec.ts.)
*/
describe('a Back on the creation dialog', () => {
afterEach(() => act(() => resetWork()))
const doc = JSON.parse(drawnText())
function CreationPage() {
const nav = useEditorNavigation('annotations')
navigate = useNavigate()
location = useLocation()
useEditorHistory(nav, owner, defaultView('annotations'))
return (
<>
<EditorTabs
active={nav.state.tab}
tier="wide"
onSelect={nav.selectTab}
/>
<CreationDialog doc={doc} readOnly={false} anchor={{ current: null }} />
<DrawingGuardDialog />
</>
)
}
it('with nothing typed it asks inside the dialog; « Continuer » keeps the shape', async () => {
useLocaleStore.setState({ locale: 'fr' })
const user = userEvent.setup()
render(
<MemoryRouter initialEntries={['/x']}>
<CreationPage />
</MemoryRouter>,
)
// An entry of this editor to go Back to.
await user.click(screen.getByRole('tab', { name: 'Constats' }))
act(() =>
placePending(
{
viewId: 'view-main',
frame: null,
origin: 'tool',
form: emptyForm(doc),
},
{ kind: 'point', geometry: { type: 'circle', cx: 50, cy: 50, r: 5 } },
),
)
const dialog = await screen.findByRole('dialog', { name: 'Nouveau point' })
act(() => navigate(-1))
const ask = within(dialog).getByRole('group', {
name: 'Abandonner la création ?',
})
// One question, inside the dialog: the workspace's own stays closed.
expect(screen.getAllByRole('dialog')).toHaveLength(1)
await user.click(within(ask).getByRole('button', { name: 'Continuer' }))
expect(useAnnotationWork.getState().creation).not.toBeNull()
expect(
within(dialog).queryByRole('group', { name: /Abandonner/ }),
).toBeNull()
act(() => navigate(-1))
await user.click(within(dialog).getByRole('button', { name: 'Abandonner' }))
expect(useAnnotationWork.getState().creation).toBeNull()
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
})
})
/** U2 Task 6: the annotation properties dialog is a layer of the browser history. */
describe('the annotation layer and the history', () => {
function AnnotationPage({ dirty }: { dirty: boolean }) {
+45 -46
View File
@@ -469,49 +469,38 @@ describe('a request reaches only its owner', () => {
})
})
describe('« Aller à » while a creation or a tracing is in progress', () => {
const liveText = () =>
document.querySelector('p[aria-live="polite"]')?.textContent ?? ''
describe('a tab while a creation or a tracing is in progress', () => {
function bareAnnotationText(): string {
const bare = point('anno-bare', 10, 10, 2)
const value = { ...bare.value, geometry: null, name: name('Sans tracé') }
return insert(drawnText(), { kind: 'annotation', value } as typeof bare)
}
async function gotoBare(
user: ReturnType<typeof userEvent.setup>,
start: () => Promise<void>,
) {
// U2 Task 7 (R-12, A12): a creation no longer waits for « Aller à » in the background;
// the tab that would leave it asks first. « Continuer » keeps it, « Abandonner » goes.
it('a tracing from the Zone tool: the tab asks first, « Continuer » keeps it', async () => {
const user = await mount(bareAnnotationText())
const drawing = inPlace('annotations.drawing')
await waitFor(() =>
expect(
inPlace('annotations.drawing').getByRole('button', { name: 'Zone' }),
).toBeEnabled(),
expect(drawing.getByRole('button', { name: 'Zone' })).toBeEnabled(),
)
await start()
await user.click(drawing.getByRole('button', { name: 'Zone' }))
pressAt(screen.getByTestId('annotation-canvas'), 20, 20)
await user.click(tab(/Vérification/))
const ask = await screen.findByRole('dialog', {
name: 'Abandonner la création ?',
})
await user.click(within(ask).getByRole('button', { name: 'Continuer' }))
expect(tab('Annotations')).toHaveAttribute('aria-selected', 'true')
expect(drawing.getByTestId('tracing-commands')).toBeVisible()
await user.click(tab(/Vérification/))
await user.click(
inPlace('verification').getAllByRole('button', {
name: 'Aller à Sans tracé',
})[0],
within(
await screen.findByRole('dialog', { name: 'Abandonner la création ?' }),
).getByRole('button', { name: 'Abandonner' }),
)
}
it('a tracing from the Zone tool is kept and focused', async () => {
const user = await mount(bareAnnotationText())
await gotoBare(user, async () => {
await user.click(
inPlace('annotations.drawing').getByRole('button', { name: 'Zone' }),
)
pressAt(screen.getByTestId('annotation-canvas'), 20, 20)
})
expect(tab('Annotations')).toHaveAttribute('aria-selected', 'true')
const bar = within(place('annotations.drawing')).getByTestId(
'tracing-commands',
)
expect(bar).toBeVisible()
await waitFor(() => expect(document.activeElement).toBe(bar))
expect(liveText()).toContain('tracé est en cours')
expect(tab(/Vérification/)).toHaveAttribute('aria-selected', 'true')
expect(useAnnotationWork.getState().creation).toBeNull()
})
// U2 Task 5 (R-12): « Remplacer par un polygone » is a redraw mode. With nothing placed a
@@ -557,22 +546,32 @@ describe('« Aller à » while a creation or a tracing is in progress', () => {
expect(drawing.getByTestId('tracing-commands')).toBeVisible()
})
it('a pending creation is kept and focused', async () => {
it('a point being replaced (dialog hidden): the tab asks, « Continuer » keeps the form', async () => {
const user = await mount(bareAnnotationText())
await gotoBare(user, async () => {
await user.click(
inPlace('annotations.drawing').getByRole('button', {
name: 'Ajouter un point',
}),
)
})
const panel = within(place('annotations.drawing')).getByTestId(
'annotation-creation',
)
expect(panel).toBeVisible()
const drawing = inPlace('annotations.drawing')
await waitFor(() =>
expect(document.activeElement).toHaveAttribute('data-creation-heading'),
expect(
drawing.getByRole('button', { name: 'Ajouter un point' }),
).toBeEnabled(),
)
expect(liveText()).toContain('création est en cours')
await user.click(drawing.getByRole('button', { name: 'Ajouter un point' }))
const dialog = await screen.findByRole('dialog', { name: 'Nouveau point' })
await user.type(within(dialog).getByLabelText('Nom (FR)'), 'Nuque')
await user.click(
within(dialog).getByRole('button', { name: 'Replacer le point' }),
)
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
await user.click(tab(/Vérification/))
await user.click(
within(
await screen.findByRole('dialog', { name: 'Abandonner la création ?' }),
).getByRole('button', { name: 'Continuer' }),
)
expect(tab('Annotations')).toHaveAttribute('aria-selected', 'true')
await user.click(
drawing.getByRole('button', { name: 'Revenir aux propriétés' }),
)
const back = await screen.findByRole('dialog', { name: 'Nouveau point' })
expect(within(back).getByLabelText('Nom (FR)')).toHaveValue('Nuque')
})
})
+18 -10
View File
@@ -215,7 +215,8 @@ describe('typed values come back after a 1 024 px crossing', () => {
expect(store.getState().unsaved).toBe(false)
})
it('the annotation edit body: tool, pending creation with its name', async () => {
// U2 Task 7 (R-14): the creation dialog is mounted outside the edit-only body.
it('a creation open: a crossing keeps the dialog, its form and the ghost, « Créer » off', async () => {
const user = await mount(baseText())
const drawing = within(place('annotations.drawing'))
await waitFor(() =>
@@ -223,19 +224,26 @@ describe('typed values come back after a 1 024 px crossing', () => {
)
await user.click(drawing.getByRole('button', { name: 'Zone' }))
await user.click(drawing.getByRole('button', { name: 'Ajouter un point' }))
const name = await screen.findByLabelText('Nom (FR)')
const dialog = await screen.findByRole('dialog', { name: 'Nouveau point' })
const name = within(dialog).getByLabelText('Nom (FR)')
await user.type(name, 'Futur point')
cross(800)
expect(name.closest('[hidden]')).not.toBeNull()
expect(screen.queryByRole('region', { name: 'Nouveau point' })).toBeNull()
expect(screen.queryByRole('button', { name: 'Zone' })).toBeNull()
const kept = screen.getByRole('dialog', { name: 'Nouveau point' })
expect(within(kept).getByLabelText('Nom (FR)')).toHaveValue('Futur point')
expect(within(kept).getByLabelText('Nom (FR)')).toHaveAttribute('readonly')
expect(within(kept).getByRole('button', { name: 'Créer' })).toBeDisabled()
expect(
within(kept).getByRole('button', { name: 'Replacer le point' }),
).toBeDisabled()
expect(screen.getByTestId('overlay-ghost')).toBeInTheDocument()
cross(1280)
expect(screen.getByLabelText('Nom (FR)')).toBe(name)
expect(name).toHaveValue('Futur point')
expect(drawing.getByRole('button', { name: 'Zone' })).toHaveAttribute(
'aria-pressed',
'true',
const back = screen.getByRole('dialog', { name: 'Nouveau point' })
expect(within(back).getByLabelText('Nom (FR)')).toHaveValue('Futur point')
expect(within(back).getByLabelText('Nom (FR)')).not.toHaveAttribute(
'readonly',
)
expect(within(back).getByRole('button', { name: 'Créer' })).toBeEnabled()
expect(screen.getByTestId('overlay-ghost')).toBeInTheDocument()
expect(store.getState().unsaved).toBe(false)
})
})
+13 -6
View File
@@ -459,8 +459,11 @@ describe('A5: a new point takes the most used size', () => {
await mount(sized())
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Ajouter un point' }))
const panel = await screen.findByTestId('annotation-creation')
expect(within(panel).getByLabelText('Rayon')).toHaveValue('7')
await screen.findByTestId('annotation-creation')
// A8: no « Rayon » field; the ghost under the dialog has the size.
expect(
screen.getByTestId('overlay-ghost').querySelector('circle'),
).toHaveAttribute('r', '7')
})
it('the Point tool shows the slider at that size; a new size feeds the click', async () => {
@@ -599,8 +602,10 @@ describe('A5 through the Point tool click', () => {
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Point' }))
pressAt(screen.getByTestId('annotation-canvas'), 50, 80)
const panel = await screen.findByTestId('annotation-creation')
expect(within(panel).getByLabelText('Rayon')).toHaveValue('7')
await screen.findByTestId('annotation-creation')
expect(
screen.getByTestId('overlay-ghost').querySelector('circle'),
).toHaveAttribute('r', '7')
})
it('a size chosen on the slider before the click feeds it', async () => {
@@ -609,8 +614,10 @@ describe('A5 through the Point tool click', () => {
await user.click(screen.getByRole('button', { name: 'Point' }))
fireEvent.change(slider(), { target: { value: '9' } })
pressAt(screen.getByTestId('annotation-canvas'), 50, 80)
const panel = await screen.findByTestId('annotation-creation')
expect(within(panel).getByLabelText('Rayon')).toHaveValue('9')
await screen.findByTestId('annotation-creation')
expect(
screen.getByTestId('overlay-ghost').querySelector('circle'),
).toHaveAttribute('r', '9')
})
})
+2 -2
View File
@@ -259,11 +259,11 @@ describe('« Aller à » an annotation while something is in progress', () => {
return { consumed, announce }
}
it('a pending creation is kept: its panel takes the focus, the live region says why', async () => {
it('a pending creation is kept: its dialog takes the focus, the live region says why', async () => {
const { consumed, announce } = await withProgress(addPoint)
await waitFor(() => expect(consumed).toHaveBeenCalledWith(7, 'kept'))
expect(screen.getByTestId('annotation-creation')).toBeInTheDocument()
expect(document.activeElement).toHaveAttribute('data-creation-heading')
expect(document.activeElement).toHaveAttribute('data-creation-focus')
expect(announce).toHaveBeenCalledWith(
expect.stringContaining('création est en cours'),
)
@@ -35,6 +35,8 @@ import { useLeaveGuardStore } from '@/state/leaveGuardStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import DrawingGuardDialog from '@/components/editor/annotations/DrawingGuardDialog'
import { emptyForm } from '@/editor/annotations/creation'
import { traceVertex } from '@/editor/annotations/creationWork'
import { guardDrawing } from '@/editor/annotations/drawingGuard'
import {
guardWork,
@@ -409,6 +411,32 @@ describe('AppLayout and a started move on the drawing (R-12)', () => {
).toBeInTheDocument()
})
it('during a creation a link asks « Abandonner la création ? » (R-12)', async () => {
const user = userEvent.setup()
mountDraft()
act(() =>
traceVertex(
{
viewId: 'v',
frame: null,
origin: 'tool',
form: emptyForm({ categories: [] } as never),
},
'zone',
[1, 1],
),
)
await user.click(account())
const ask = screen.getByRole('dialog', { name: 'Abandonner la création ?' })
await user.click(within(ask).getByRole('button', { name: 'Continuer' }))
expect(screen.queryByText(/account page/)).toBeNull()
expect(useAnnotationWork.getState().creation).not.toBeNull()
await user.click(account())
await user.click(screen.getByRole('button', { name: 'Abandonner' }))
expect(await screen.findByText(/account page/)).toBeInTheDocument()
expect(useAnnotationWork.getState().creation).toBeNull()
})
it('a download link is never taken, even with a started move', async () => {
const user = userEvent.setup()
mountDraft()