feat(editor): properties dialog over the column, transactional save

U2 Task 6 (A1, A2, A3, A9, A10, R-3, R-5, R-6, R-14, R-16).

- Dialog: `anchor` places the panel at the column's left and width,
  from its top, under a 22 % ink veil that ignores clicks; the visual
  viewport below 320 px; centred without an anchor box.
- Navigation: `annotation` layer (LAYERS, EditorView, history entry,
  leave guards, left-draft flag); Back closes, Forward reopens.
- AnnotationDialog: read body, « Modifier » form (CreationFields with
  « Couleur », missingFields, R-3 messages), one `update` on the
  current annotation by id, « Marquer comme relu », « Modifier la
  forme », « Supprimer »; read-only flip keeps the draft.
- The column always shows the overview, selected row marked; Enter on
  it, a second click or a double click, the strip's « Propriétés »
  open the dialog. « Aller à » focuses the row (R-5).
- Read-only twin: strip and read-only dialog at 1 024 px and wider,
  inline read body below. PropertiesPanel and AnnotationFields gone.
- Strip lead 256 px and a fixed status slot, so the commands fit at
  1 024 px and a status change moves nothing.
- e2e: `aside-content` exemption removed; scroll-to-top workarounds
  of editor-geometry, editor-zones and editor-journey removed.

Removed assertions mapped:
  editor-annotations-tab.test.tsx:
  - selectFromList waited for `annotation-properties` -> waits for the strip's « Propriétés » (selection without dialog, A1)
  - refused place: issues block `annotation-geometry-issues` in the panel -> the strip notice alert (present, then gone)
  - keyboard creation / C26 confirmation: `annotation-properties` after create -> strip « Propriétés » (new element selected)
  - Désélectionner from the panel -> « Désélectionner » in the strip (all 7 tests); « panel closes » -> strip has no « Propriétés »
  - undo after deselect (typed name) -> handle key series then deselect then undo
  - commits a valid typed value once without blur (name field) -> a pending handle key series committed once by the strip deselect
  - a refused typed value: the panel closes (two tests: strip deselect, tap deselect) -> removed: no field outside the dialog; the dialog's draft writes nothing before « Enregistrer » (new dialog tests)
  - not offered while a replace tracing runs: panel's Désélectionner absent -> strip offers neither « Désélectionner » nor « Propriétés » during the tracing
  - tap: isDeselected read `annotation-properties` -> strip « Propriétés » absent; link select -> strip title data-selection
  - tap: undo after tap deselect (typed name) -> handle series; typed value committed on blur -> handle series committed on blur
  - strip geometry issues: list read in the panel -> list read in the properties dialog's issues block
  - a new commit replaces the message (typed name) -> « Marquer comme relu » in the dialog
  editor-escape.test.tsx:
  - `panel()` = `annotation-properties` -> the strip's « Propriétés » or the phone twin's inline read body
  - Escape from a panel button (« Marquer comme relu ») -> from the selected row in the side column: focus on the row
  - after A then B from the panel (via « Toutes les annotations ») -> select A, select B, Escape from a button of the side column: focus on B's row
  - a text field (panel « Nom (FR) ») -> the overview « Filtrer par nom »
  - redraw via the panel's « Remplacer par un polygone » -> the strip's command
  - modal / delete dialog opened by the panel's « Supprimer » -> « Supprimer » of the properties dialog
  - read-only width: hidden `annotation-properties` -> hidden strip « Propriétés » of the kept edit body
  editor-history-buttons.test.tsx (typed text and the press, 8 tests): the annotation's committed « Nom (FR) » field of the panel -> the sheet's committed « Nom (FR) » on Général (same TextField commit-on-blur path; annotation fields are now a dialog draft)
  editor-focus-request.test.tsx: « Aller à » focuses `data-properties-heading` inside `annotation-properties` -> focuses the annotation's row, marked aria-current, no dialog (R-5)
  editor-sections.test.tsx: « Aller à » with nothing in progress focused the properties heading -> focuses the row (R-5); creation kept: no `annotation-properties` -> no strip « Propriétés »
  editor-overview.test.tsx (edit and read-only): row opens `annotation-properties`, « Toutes les annotations » returns -> row selects, stays marked aria-current, no dialog; strip « Désélectionner » returns focus to the row; filter kept across select and « Désélectionner »
  editor-citations-guards.test.tsx: LAYERS_TOP_DOWN gains 'annotation' at the bottom
  editor-keep-alive.test.tsx: `annotation-properties` visible after the round trip -> the strip's « Propriétés » visible (selection kept)
  editor-no-loss.test.tsx: ids `ro-annotation-name-fr` and `annotation-name-fr` (both panels' fields) -> the twin's inline read body (no ids), then the dialog edit form's `annotation-edit-fr`, kept through a flip to 800 px, no duplicate id; « Aller à » visible `annotation-properties` -> visible `annotation-read` (inline twin), none at 1 280
  editor-point-edit.test.tsx / editor-zone-edit.test.tsx: `select()` waited for `annotation-properties` and returned it -> waits for the strip's « Propriétés » and returns the strip (its « Désélectionner » and « Remplacer par un polygone » moved there)
  - move mode Escape: `annotation-properties` still there -> the strip's « Propriétés » back after the mode
  - « Toutes les annotations » asks first during a started move -> Enter on the selected row asks first (no dialog), and the strip offers neither « Propriétés » nor « Désélectionner » during the mode
  - Escape from the handle / slider: `annotation-properties` gone -> the strip's « Propriétés » gone
  - I-3 touch tap: `annotation-properties` gone -> the strip's « Propriétés » gone
  e2e (sandbox):
  - support/layout.ts: `aside-content` exemption removed (ShiftExemption type, the loose compare); every `swaps`/`SWAPS` argument removed (editor-annotations, editor-zones, editor-geometry)
  - support/editor.ts pickAnnotation: clicked « Toutes les annotations » first when the panel showed -> the overview is always shown: clicks the row, then scrolls back to the top (the page no longer shortens)
  - editor-annotations: `annotation-properties` visible after a creation -> strip with « Propriétés »; review toggle and « Supprimer » of the panel -> the properties dialog's; a jitter click on the selected point now opens the dialog (A1), closed by Escape before the drag; handle names exact (the marked row shares the prefix); trace close moved out of expectNoShift (creation panel until Task 7, shortcut + TODO)
  - editor-deselect: `annotation-properties` -> the strip with « Propriétés » or the twin's inline read body; Escape in a field: panel « Nom (FR) » -> overview filter; delete dialog from the panel -> from the properties dialog (Escape closes it, then the dialog); « a typed value is applied by the click that deselects » (name field, refused blank) -> a pending point-handle key series applied by the deselecting click and by « Désélectionner » (refused value: no field outside the dialog); « the selected one stays » -> a second click, double click and jitter open the dialog, Escape closes it, selection kept
  - editor-geometry: `annotation-geometry-issues` in the panel -> read in the properties dialog, then the strip notice; after the refusal the error count unchanged; scroll-to-top workaround removed
  - editor-zones: panel « Désélectionner » -> strip; scroll-to-top after pickAnnotation removed (helper does it)
  - editor-structures: panel « Supprimer » -> properties dialog « Supprimer », confirmation over it
  - editor-journey: `#annotation-name-fr` committed field + `#annotation-laterality` -> the dialog's edit form, one « Enregistrer »; scroll-to-top removed
  - editor-shell / editor-shell-journeys: « Aller à » focus on `data-properties-heading` -> the annotation's row (aria-current), no dialog (R-5)
  - editor-shell-layout: focus kind `annotation-properties` -> removed (the overview is the side)
This commit is contained in:
bchanot committed 2026-11-17 22:01:57 +01:00
1 parent e596e0765e
commit cd794f3c39
66 files changed
+3351 -1357

No files matched your search

+2 -1
View File
@@ -748,7 +748,8 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet
- [ ] V1-2.6 UX U2 implementation (contract `.claude/tasks/contracts/2026-11-17-v1-2-6-u2-implementation.md`, plan rev 3, subagent-driven): [ ] T1 core min radius · [ ] T2 press machine · [ ] T3 strip + message, no shift · [ ] T4 points, move mode, guard · [ ] T5 zones, redraw, R-18 · [ ] T6 properties dialog · [ ] T7 creation · [ ] T8 touch, loupe · [ ] T9 docs · [ ] T10 gates, verifier, security · [ ] STOP owner trial on `pnpm db:trial` before closure
- [ ] `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).
- [ ] 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). Expected to go with Task 6 (properties in a dialog); recheck then (U2 Task 5 fix round 1).
- [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; the scroll-to-top removed, the spec green (U2 Task 5 fix round 1, closed by Task 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).
- [ ] 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.
+74 -99
View File
@@ -25,6 +25,7 @@ import {
shapeWith,
standardShape,
UNSAVED_LINE,
openProperties,
} from '../support/editor'
import { expectNoShift, keepNativeFrames } from '../support/layout'
@@ -35,7 +36,9 @@ const dict = fr
const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
const creation = (page: Page) => page.getByTestId('annotation-creation')
const properties = (page: Page) => page.getByTestId('annotation-properties')
/** 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])')
const list = (page: Page) =>
page.getByRole('list', { name: dict['editor.annotations.list'] })
@@ -144,7 +147,9 @@ test.describe('editor annotations (A3)', () => {
// 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/)
await page.getByRole('button', { name: 'Point Point un' }).focus()
await page
.getByRole('button', { name: 'Point Point un', exact: true })
.focus()
await page.keyboard.press('ArrowRight')
await page.keyboard.press('ArrowRight')
await page.keyboard.press('Enter')
@@ -195,6 +200,10 @@ test.describe('editor annotations (A3)', () => {
await page.mouse.up()
await expect(shownShape(page)).toHaveAttribute('cx', x0)
await expect(shownShape(page)).toHaveAttribute('cy', y0)
// A1: a click on the selected point opens its properties (U2 Task 6); closed again.
await expect(page.getByRole('dialog')).toBeVisible()
await page.keyboard.press('Escape')
await expect(page.getByRole('dialog')).toHaveCount(0)
// A real drag: the point follows to (400, 360) in drawing units.
const to = await clientOf(page, 400, 360)
@@ -240,7 +249,9 @@ test.describe('editor annotations (A3)', () => {
// The handle keys (U2 Task 5): two steps of 5 units down, one commit on Enter.
const cy0 = await shownNumber(page, 'cy')
await page.getByRole('button', { name: 'Point Clavier' }).focus()
await page
.getByRole('button', { name: 'Point Clavier', exact: true })
.focus()
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('Enter')
@@ -282,21 +293,24 @@ test.describe('editor annotations (A3)', () => {
await fillCreation(page, { fr: 'A relire', en: 'To review' })
await createFromPanel(page)
await properties(page)
const sheet = await openProperties(page, dict)
await sheet
.getByRole('button', { name: dict['editor.annotations.mark_reviewed'] })
.click()
await expect(
properties(page).getByRole('button', {
sheet.getByRole('button', {
name: dict['editor.annotations.to_confirm'],
}),
).toBeVisible()
await properties(page)
await sheet
.getByRole('button', { name: dict['editor.action.delete'] })
.click()
await page
.getByRole('dialog')
.locator('dialog[open]')
.last()
.getByRole('button', { name: dict['editor.delete.confirm'] })
.click()
await expect(page.locator('dialog[open]')).toHaveCount(0)
await expect(list(page)).toHaveCount(0)
await expect(
page.getByText(dict['editor.annotations.list_empty']),
@@ -340,30 +354,18 @@ test.describe('editor annotations (A3)', () => {
}) => {
const actor = await openWithPoint(page, width)
requests.forbid(actor.account.email, actor.account.password)
// shortcut: the side panel still swaps the overview for the properties or the
// creation panel until Tasks 6 and 7 (dialogs); its height is exempt there only.
const swaps = ['aside-content'] as const
await expectNoShift(
page,
async () => {
await clickDrawing(page, 500, 300)
await expect(selectionTag(page)).toContainText('Pt A')
},
swaps,
)
// The first commit: the save line changes, the message shows (the properties panel
// rewrites its review badge: aside content until Task 6).
await expectNoShift(
page,
async () => {
await dragPoint(page, { x: 560, y: 330 })
await expect(line(page)).toContainText(
dict['editor.annotations.message.moved.point'],
)
await expect(saveLine(page)).toHaveText(UNSAVED_LINE)
},
swaps,
)
await expectNoShift(page, async () => {
await clickDrawing(page, 500, 300)
await expect(selectionTag(page)).toContainText('Pt A')
})
// The first commit: the save line changes, the message shows.
await expectNoShift(page, async () => {
await dragPoint(page, { x: 560, y: 330 })
await expect(line(page)).toContainText(
dict['editor.annotations.message.moved.point'],
)
await expect(saveLine(page)).toHaveText(UNSAVED_LINE)
})
// Its own row, the column's width: the message is read whole.
const cut = await line(page)
.locator('span')
@@ -377,14 +379,10 @@ test.describe('editor annotations (A3)', () => {
dict['editor.annotations.message.moved.point'],
)
})
await expectNoShift(
page,
async () => {
await clickDrawing(page, 20, 20)
await expect(selectionTag(page)).toHaveCount(0)
},
swaps,
)
await expectNoShift(page, async () => {
await clickDrawing(page, 20, 20)
await expect(selectionTag(page)).toHaveCount(0)
})
await expectNoShift(page, () => tool(page, 'zone').click())
await expectNoShift(page, () => clickDrawing(page, 600, 150))
for (const [x, y] of [
@@ -396,14 +394,11 @@ test.describe('editor annotations (A3)', () => {
button(page, 'editor.annotations.trace_pop').click(),
)
await expectNoShift(page, () => clickDrawing(page, 700, 400))
await expectNoShift(
page,
async () => {
await button(page, 'editor.annotations.trace_close').click()
await expect(creation(page)).toBeVisible()
},
swaps,
)
// 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()
})
}
@@ -413,80 +408,60 @@ test.describe('editor annotations (A3)', () => {
}) => {
const actor = await openWithPoint(page, 1280)
requests.forbid(actor.account.email, actor.account.password)
const swaps = ['aside-content'] as const
await expectNoShift(
page,
async () => {
await clickDrawing(page, 500, 300)
await expect(selectionTag(page)).toContainText('Pt A')
},
swaps,
)
const handle = page.getByRole('button', { name: 'Point Pt A' })
await expectNoShift(page, async () => {
await clickDrawing(page, 500, 300)
await expect(selectionTag(page)).toContainText('Pt A')
})
const handle = page.getByRole('button', {
name: 'Point Pt A',
exact: true,
})
await expect(handle).toHaveAttribute('tabindex', '0')
const slider = page.getByTestId('size-slider').getByRole('slider')
await expect(slider).toHaveValue('40')
await expectAccessible(page, 'a selected point: handle, slider, move')
// The handle follows the pointer; the drop is one commit.
await expectNoShift(
page,
async () => {
await dragPoint(page, { x: 560, y: 330 })
await expect(line(page)).toContainText(
dict['editor.annotations.message.moved.point'],
)
},
swaps,
)
await expectNoShift(page, async () => {
await dragPoint(page, { x: 560, y: 330 })
await expect(line(page)).toContainText(
dict['editor.annotations.message.moved.point'],
)
})
expect(Math.abs((await shownNumber(page, 'cx')) - 560)).toBeLessThan(2)
// A click on the track, no drag (WCAG 2.5.7): one commit at the release.
const track = (await slider.boundingBox())!
await expectNoShift(
page,
async () => {
await page.mouse.click(
track.x + track.width * 0.8,
track.y + track.height / 2,
)
await expect(line(page)).toContainText(
dict['editor.annotations.message.resized'],
)
},
swaps,
)
await expectNoShift(page, async () => {
await page.mouse.click(
track.x + track.width * 0.8,
track.y + track.height / 2,
)
await expect(line(page)).toContainText(
dict['editor.annotations.message.resized'],
)
})
expect(await shownNumber(page, 'r')).toBeGreaterThan(40)
await page.keyboard.press('Control+z')
await expect(shownShape(page)).toHaveAttribute('r', '40')
// The move mode: three steps (5 units each on a 1 000 px wide frame), validated once.
const x0 = await shownNumber(page, 'cx')
await expectNoShift(
page,
() => button(page, 'editor.annotations.move.point').click(),
swaps,
await expectNoShift(page, () =>
button(page, 'editor.annotations.move.point').click(),
)
const right = button(page, 'editor.annotations.move.right')
await expect(right).toBeVisible()
await expectAccessible(page, 'the move mode')
await expectNoShift(
page,
async () => {
for (let step = 0; step < 3; step++) await right.click()
},
swaps,
)
await expectNoShift(page, async () => {
for (let step = 0; step < 3; step++) await right.click()
})
// Nothing committed yet: the stored place stays, drawn as the old place.
await expect(storedShape(page)).toHaveAttribute('cx', String(x0))
await expectNoShift(
page,
async () => {
await button(page, 'editor.annotations.move.confirm').click()
await expect(right).toHaveCount(0)
},
swaps,
)
await expectNoShift(page, async () => {
await button(page, 'editor.annotations.move.confirm').click()
await expect(right).toHaveCount(0)
})
await expect(shownShape(page)).toHaveAttribute('cx', String(x0 + 15))
await expect(storedShape(page)).toHaveCount(0)
await expect(button(page, 'editor.annotations.move.point')).toBeFocused()
+52 -40
View File
@@ -37,11 +37,18 @@ import {
const dict = fr
const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
const properties = (page: Page) => page.getByTestId('annotation-properties')
const nameField = (page: Page) =>
properties(page).getByLabel(dict['editor.annotations.name_fr'], {
exact: true,
})
/**
* The selection's commands (U2 Task 6: the properties left the side column): the strip
* that offers « Propriétés », or the phone twin's inline read body.
*/
const properties = (page: Page) =>
page.locator(
'[data-testid="edit-strip"]:has([data-properties-button]), [data-annotation-aside] [data-testid="annotation-read"]',
)
/** A text field of the workspace, outside any dialog: the overview's filter. */
const filterField = (page: Page) =>
page.getByRole('searchbox', { name: dict['editor.overview.filter'] })
const pointHandle = (page: Page) => page.getByTestId('point-handle')
const overview = (page: Page) => page.getByTestId('annotation-overview')
const box = (page: Page) => page.getByTestId('annotation-canvas')
const liveRegion = (page: Page) =>
@@ -214,20 +221,30 @@ test.describe('deselect and D6b (editor, mouse and keyboard)', () => {
// A field focused: nothing happens, the field keeps the focus.
await select(page, POINT)
const name = nameField(page)
const name = filterField(page)
await name.focus()
await page.keyboard.press('Escape')
await expectKept(page, POINT)
await expect(name).toBeFocused()
// The delete dialog: only it closes (LRN-111: wait until it is gone).
// The delete dialog over the properties dialog: only it closes (LRN-111: wait until
// it is gone), then the properties dialog; the selection stays.
await properties(page)
.getByRole('button', { name: dict['editor.annotations.properties'] })
.click()
const sheet = page.getByRole('dialog', { name: POINT })
await sheet
.getByRole('button', { name: dict['editor.action.delete'] })
.click()
const dialog = page.getByRole('dialog')
await expect(dialog).toBeVisible()
const ask = page.getByRole('dialog', {
name: new RegExp(dict['editor.action.delete']),
})
await expect(ask).toBeVisible()
await page.keyboard.press('Escape')
await expect(dialog).toHaveCount(0)
await expect(ask).toHaveCount(0)
await expect(sheet).toBeVisible()
await page.keyboard.press('Escape')
await expect(sheet).toHaveCount(0)
await expectKept(page, POINT)
// The references dialog (over the finding dialog over Constats): Escape closes it
@@ -260,7 +277,7 @@ test.describe('deselect and D6b (editor, mouse and keyboard)', () => {
expect(saves).toEqual([])
})
test('mouse: empty clicks deselect, annotations select, the selected one stays', async ({
test('mouse: empty clicks deselect, annotations select, the selected one opens and stays', async ({
page,
requests,
}) => {
@@ -300,17 +317,24 @@ test.describe('deselect and D6b (editor, mouse and keyboard)', () => {
await expectSelected(page, name)
}
// The selected point and zone: click, double click and a 2 px jitter keep them.
// The selected point and zone: a click, a double click and a 2 px jitter keep them
// and open their properties (A1, U2 Task 6); Escape closes the dialog only.
const closeProperties = async (name: string) => {
await expect(page.getByRole('dialog', { name })).toBeVisible()
await page.keyboard.press('Escape')
await expect(page.getByRole('dialog')).toHaveCount(0)
await expectKept(page, name)
}
for (const [name, at] of targets.slice(0, 2)) {
await clickAt(page, at)
await expectSelected(page, name)
await clickAt(page, at)
await expectKept(page, name)
await closeProperties(name)
const now = await clientOf(page, at.x, at.y)
await page.mouse.dblclick(now.x, now.y)
await expectKept(page, name)
await closeProperties(name)
await mouseJitter(page, at.x, at.y)
await expectKept(page, name)
await closeProperties(name)
}
await expect(saveLine(page)).not.toHaveText(UNSAVED_LINE)
expect(saves).toEqual([])
@@ -386,47 +410,35 @@ test.describe('deselect and D6b (editor, mouse and keyboard)', () => {
expect(saves).toEqual([])
})
test('a typed value is applied by the click that deselects; « Désélectionner » commits in one click', async ({
test('a pending key series is applied by the click that deselects; « Désélectionner » commits it in one click', async ({
page,
requests,
}) => {
const { actor, saves } = await open(page)
requests.forbid(actor.account.email, actor.account.password)
// U2 Task 5: the coordinate fields left the panel; the name field carries the typing.
const name = nameField(page)
// U2 Task 6: the annotation's fields left the side column (one dialog save); the point
// handle's key series is the pending typing a deselect must not lose.
// Valid value, no blur, ONE click on the drawing.
// A step, no Enter, ONE click on the drawing.
await select(page, POINT)
await expect(name).toHaveValue(POINT)
await name.fill('Pt Delta')
await pointHandle(page).focus()
await page.keyboard.press('ArrowRight')
await clickAt(page, IN_CIRCLE)
await expectDeselected(page)
await expect(saveLine(page)).toHaveText(/1 modification non enregistrée/)
// Undo reverts the value.
// Undo reverts it.
await historyButton(page, dict, 'undo').click()
await expect(saveLine(page)).not.toHaveText(UNSAVED_LINE)
await select(page, POINT)
await expect(name).toHaveValue(POINT)
// « Désélectionner » with an unblurred refused value: closed at once, unchanged.
// A blank name is refused (both names are required).
const deselect = properties(page).getByRole('button', {
name: dict['editor.annotations.deselect'],
})
await name.fill('')
await deselect.click()
await expectDeselected(page)
await expect(saveLine(page)).not.toHaveText(UNSAVED_LINE)
// « Désélectionner » with a pending step: committed and closed.
await select(page, POINT)
await expect(name).toHaveValue(POINT)
// « Désélectionner » with an unblurred valid value: committed and closed.
await name.fill('Pt Epsilon')
await deselect.click()
await pointHandle(page).focus()
await page.keyboard.press('ArrowRight')
await properties(page)
.getByRole('button', { name: dict['editor.annotations.deselect'] })
.click()
await expectDeselected(page)
await expect(saveLine(page)).toHaveText(/1 modification non enregistrée/)
await select(page, 'Pt Epsilon')
await expect(name).toHaveValue('Pt Epsilon')
expect(saves).toEqual([])
})
})
+27 -27
View File
@@ -21,6 +21,7 @@ import {
serverDocument,
shapeWith,
standardShape,
openProperties,
} from '../support/editor'
// V1-2.6 geometry and adversarial cases (contract C7, C8, C21; owner 2026-11-04): a click
@@ -182,8 +183,19 @@ test.describe('editor geometry (adversarial)', () => {
requests.forbid(actor.account.email, actor.account.password)
await viewChip(page, 'Détail A').click()
await pickAnnotation(page, dict, /Hors cadre/)
const issues = page.getByTestId('annotation-geometry-issues')
await expect(issues).toBeVisible()
// The issue: an alert in the properties dialog's read mode, its text in the strip.
const properties = await openProperties(page, dict)
const issue = (
await properties
.getByTestId('annotation-geometry-issues')
.locator('li')
.first()
.innerText()
).trim()
await page.keyboard.press('Escape')
await expect(page.getByRole('dialog')).toHaveCount(0)
const notice = page.getByTestId('edit-strip-notice')
await expect(notice).toContainText(issue)
const verification = page.getByRole('tab', {
name: dict['editor.tab.verification'],
})
@@ -199,40 +211,28 @@ test.describe('editor geometry (adversarial)', () => {
})
// A partial move (still out of the frame): refused by the core, the point restored.
// Nothing around the drawing moves (A14); the side panel's content may (Task 6).
const swaps = ['aside-content'] as const
// NOT a Playwright artefact: at the page's end, the issue list leaving the panel shortens
// the page by 11 px and the scroll clamp moves the canvas (reported, U2 Task 5 fix round
// 1; Task 6 moves the panel out of the page). The check starts from the top.
await page.evaluate(() => window.scrollTo(0, 0))
await expectNoShift(page, () => move.click(), swaps)
// Nothing around the drawing moves (A14), wherever the page is scrolled: the issue
// lives in the strip and the dialog, the side column keeps the overview (U2 Task 6).
await expectNoShift(page, () => move.click())
await dragInMode(page, { x: 250, y: 250 }, { x: 260, y: 260 })
await expectNoShift(
page,
async () => {
await confirm.click()
await expect(page.getByTestId('gesture-message')).toBeVisible()
},
swaps,
)
await expectNoShift(page, async () => {
await confirm.click()
await expect(page.getByTestId('gesture-message')).toBeVisible()
})
await expect(page.getByTestId('gesture-message')).toContainText(
dict['editor.annotations.message.move_refused'].split(' :')[0],
)
await expect(page.getByTestId('overlay-refused-place')).toBeAttached()
await expect(shownShape(page)).toHaveAttribute('cx', '110')
await expect(issues).toBeVisible()
await expect(verification).toContainText(String(errorsBefore))
// Far enough inside: kept, the issue gone, one error less.
await expectNoShift(page, () => move.click(), swaps)
await expectNoShift(page, () => move.click())
await dragInMode(page, { x: 250, y: 250 }, { x: 290, y: 290 })
await expectNoShift(
page,
async () => {
await confirm.click()
await expect(issues).toHaveCount(0)
},
swaps,
)
await expectNoShift(page, async () => {
await confirm.click()
await expect(notice).not.toContainText(issue)
})
expect(Math.abs((await shownNumber(page, 'cx')) - 150)).toBeLessThan(2)
const after = (await verification.innerText()).replace(/\D/g, '')
expect(Number(after || 0)).toBeLessThan(errorsBefore)
+18 -5
View File
@@ -34,6 +34,7 @@ import {
showDrawing,
toolButton,
UNSAVED_LINE,
openProperties,
} from '../support/editor'
import { signIn } from '../support/shell'
@@ -225,9 +226,23 @@ async function modifyAnnotations(page: Page) {
const vertex = await stepRight(page, first, start, MODIFIED.vertex)
await expect.poll(async () => (await shownPoints(page))[0][0]).toBe(vertex)
await pickAnnotation(page, dict, /Accès essai/)
await commitText(page.locator('#annotation-name-fr'), 'Accès modifié')
await page.locator('#annotation-laterality').selectOption('bilateral')
await expect(page.locator('#annotation-name-fr')).toHaveValue('Accès modifié')
// U2 Task 6: the properties dialog's form, one save for both fields.
const properties = await openProperties(page, dict)
await properties
.getByRole('button', { name: dict['editor.findings.edit'], exact: true })
.click()
await properties.locator('#annotation-edit-fr').fill('Accès modifié')
await properties
.locator('#annotation-edit-laterality')
.selectOption('bilateral')
await properties
.getByRole('button', { name: dict['editor.findings.save'] })
.click()
await expect(properties.getByTestId('annotation-read')).toContainText(
'Accès modifié',
)
await page.keyboard.press('Escape')
await expect(page.getByRole('dialog')).toHaveCount(0)
return { point, vertex }
}
@@ -316,8 +331,6 @@ test.describe('editor journey (owner trial steps)', () => {
await historyButton(page, dict, 'undo').click()
await historyButton(page, dict, 'redo').click()
const modified = await modifyAnnotations(page)
// Playwright's auto-scroll to the last list row left « Enregistrer » under the top bar.
await page.evaluate(() => window.scrollTo(0, 0))
await expectAccessible(page, 'the editor with annotations')
await saveDraft(page, dict, 1)
const draftId = await sql(
@@ -0,0 +1,264 @@
import { fr } from '@/i18n/fr'
import type { CDPSession, Page, TestInfo } from '@playwright/test'
import { expect, expectAccessible, test } from '../support/browser'
import { dropLateReplays, routeToSandbox } from '../support/sandbox'
import {
clickDrawing,
clientOf,
editorActor,
openEditor,
openProperties,
pickAnnotation,
pointOf,
seedDraft,
selectionTag,
shapeWith,
shownPoints,
toolButton,
} from '../support/editor'
import { expectNoShift, keepNativeFrames } from '../support/layout'
// U2 Task 6 (A1, A2, A3, R-6, R-14, Review Focus 3 and 5): the properties dialog over the
// right column, never over the drawing; opened by « Propriétés », a second click or a
// double click; a typed form survives a Back question and a width crossing.
const dict = fr
const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
const POINT = 'Pt Alpha'
const ZONE = 'Zone Beta'
const zone = {
...pointOf('zone-b', 'main', { cx: 0, cy: 0, r: 1 }, ZONE),
kind: 'zone',
geometry: {
type: 'polygon',
points: [
[100, 100],
[400, 100],
[400, 400],
[100, 400],
],
},
}
async function open(page: Page, width = 1280) {
await page.setViewportSize({ width, height: 800 })
const actor = await editorActor('fr')
const seed = await seedDraft(actor, {
shape: shapeWith(
pointOf('pt-a', 'main', { cx: 700, cy: 250, r: 30 }, POINT),
zone,
),
})
await openEditor(page, dict, actor, seed.sheetId)
await expect(toolButton(page, dict, 'point')).toBeEnabled()
return actor
}
const strip = (page: Page) => page.getByTestId('edit-strip')
const dialog = (page: Page) => page.getByRole('dialog')
const box = async (page: Page, selector: string) =>
(await page.locator(selector).locator('visible=true').first().boundingBox())!
type TouchPoint = { x: number; y: number }
const touch = (
cdp: CDPSession,
type: 'touchStart' | 'touchEnd',
points: TouchPoint[],
) =>
cdp.send('Input.dispatchTouchEvent', {
type,
touchPoints: points.map((p, id) => ({ x: p.x, y: p.y, id })),
})
test.describe('the properties dialog (U2 Task 6)', () => {
test.use({ locale: 'fr-FR', actionTimeout: 15_000 })
test.beforeEach(async ({ context }, info) => {
test.skip(isPhone(info), 'editing needs 1 024 px') // floor-guard: allow C16 editing needs >= 1024 px; phone read-only covered in editor-access
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
for (const width of [1024, 1180, 1280]) {
test(`at ${width} px: over the column, never over the drawing; nothing moves`, async ({
page,
requests,
}) => {
await keepNativeFrames(page)
const actor = await open(page, width)
requests.forbid(actor.account.email, actor.account.password)
// The strip's commands fit (A6): for a point (its slider) and for a zone, the last
// one lies whole inside the strip.
for (const name of [POINT, ZONE]) {
await pickAnnotation(page, dict, name)
await expect(selectionTag(page)).toContainText(name)
const fence = (await strip(page).boundingBox())!
const last = (await strip(page)
.getByRole('button', { name: dict['editor.annotations.deselect'] })
.boundingBox())!
expect(last.x + last.width).toBeLessThanOrEqual(fence.x + fence.width)
}
await page.evaluate(() => window.scrollTo(0, 0))
await expectNoShift(page, async () => {
await strip(page)
.getByRole('button', { name: dict['editor.annotations.properties'] })
.click()
await expect(dialog(page)).toBeVisible()
})
const aside = await box(page, '[data-annotation-aside="edit"]')
const canvas = await box(page, '[data-testid="annotation-canvas"]')
const panelBox = page.getByTestId('dialog-panel')
// Once its opening scale (0.96 to 1) is over: its box is then its place.
const top = Math.max(12, aside.y)
await expect
.poll(async () => Math.abs((await panelBox.boundingBox())!.y - top))
.toBeLessThan(1)
const panel = (await panelBox.boundingBox())!
expect(panel.x).toBeGreaterThanOrEqual(aside.x - 1)
expect(panel.x + panel.width).toBeLessThanOrEqual(
aside.x + aside.width + 1,
)
expect(panel.x).toBeGreaterThanOrEqual(canvas.x + canvas.width)
await expectNoShift(page, async () => {
await page.keyboard.press('Escape')
await expect(dialog(page)).toHaveCount(0)
})
})
}
test('axe in read and edit modes; a click on the veil does nothing (R-6)', async ({
page,
requests,
}) => {
const actor = await open(page)
requests.forbid(actor.account.email, actor.account.password)
await pickAnnotation(page, dict, POINT)
const sheet = await openProperties(page, dict)
await expectAccessible(page, 'the properties dialog, read mode')
await page.mouse.click(20, 400)
await expect(sheet).toBeVisible()
await sheet
.getByRole('button', { name: dict['editor.findings.edit'], exact: true })
.click()
await expect(sheet.locator('#annotation-edit-fr')).toBeFocused()
await expectAccessible(page, 'the properties dialog, edit mode')
})
test('a typed form, then Back: it asks; « Abandonner » writes nothing', async ({
page,
requests,
}) => {
const actor = await open(page)
requests.forbid(actor.account.email, actor.account.password)
await pickAnnotation(page, dict, POINT)
const sheet = await openProperties(page, dict)
await sheet
.getByRole('button', { name: dict['editor.findings.edit'], exact: true })
.click()
const name = sheet.locator('#annotation-edit-fr')
await name.fill('Pt brouillon')
await page.goBack()
await expect(
sheet.getByText(dict['editor.findings.discard_ask']),
).toBeVisible()
await expect(name).toHaveValue('Pt brouillon')
await sheet
.getByRole('button', { name: dict['editor.findings.discard'] })
.click()
await expect(dialog(page)).toHaveCount(0)
await expect(selectionTag(page)).toContainText(POINT)
await expect(
page.getByTestId('history-buttons').getByRole('button', {
name: dict['editor.history.undo_title'],
}),
).toHaveAttribute('aria-disabled', 'true')
})
test('a double click on the selected zone opens it, no vertex added (R-8)', async ({
page,
requests,
}) => {
const actor = await open(page)
requests.forbid(actor.account.email, actor.account.password)
await pickAnnotation(page, dict, ZONE)
const before = await shownPoints(page)
const inside = await clientOf(page, 250, 250)
await page.mouse.dblclick(inside.x, inside.y)
await expect(dialog(page)).toBeVisible()
await page.waitForTimeout(500)
await expect(dialog(page)).toBeVisible()
await page.keyboard.press('Escape')
await expect(dialog(page)).toHaveCount(0)
expect(await shownPoints(page)).toEqual(before)
})
test('a width crossing below 1 024 px with a typed form, and back: the draft is intact', async ({
page,
requests,
}) => {
const actor = await open(page)
requests.forbid(actor.account.email, actor.account.password)
await pickAnnotation(page, dict, POINT)
const sheet = await openProperties(page, dict)
await sheet
.getByRole('button', { name: dict['editor.findings.edit'], exact: true })
.click()
const name = sheet.locator('#annotation-edit-fr')
await name.fill('Pt traversée')
await page.setViewportSize({ width: 800, height: 800 })
await expect(sheet).toBeVisible()
await expect(name).toHaveValue('Pt traversée')
await expect(
sheet.getByRole('button', { name: dict['editor.findings.save'] }),
).toBeDisabled()
await page.setViewportSize({ width: 1280, height: 800 })
await expect(name).toHaveValue('Pt traversée')
await expect(
sheet.getByRole('button', { name: dict['editor.findings.save'] }),
).toBeEnabled()
await sheet
.getByRole('button', { name: dict['editor.findings.save'] })
.click()
await expect(sheet.getByTestId('annotation-read')).toContainText(
'Pt traversée',
)
})
})
test.describe('the properties dialog by touch (U2 Task 6, Review Focus 5)', () => {
test.use({
locale: 'fr-FR',
actionTimeout: 15_000,
hasTouch: true,
viewport: { width: 1280, height: 800 },
})
test.beforeEach(async ({ context }, info) => {
test.skip(isPhone(info), 'touch at 1 280 px runs on desktop') // floor-guard: allow C16 editing needs >= 1024 px; phone read-only covered in editor-access
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('a tap on the selected shape opens the dialog, and it stays open', async ({
page,
context,
requests,
}) => {
const actor = await open(page)
requests.forbid(actor.account.email, actor.account.password)
await pickAnnotation(page, dict, ZONE)
const cdp = await context.newCDPSession(page)
const inside = await clientOf(page, 250, 250)
await touch(cdp, 'touchStart', [inside])
await touch(cdp, 'touchEnd', [])
await expect(dialog(page)).toBeVisible()
await page.waitForTimeout(500)
await expect(dialog(page)).toBeVisible()
await expect(selectionTag(page)).toContainText(ZONE)
await clickDrawing(page, 900, 600).catch(() => undefined)
await expect(dialog(page)).toBeVisible()
})
})
@@ -235,10 +235,13 @@ test.describe('editor shell journeys (H)', () => {
await selectTab(page, dict, 'verification')
await goTo('Point libre')
await expect(place(page, 'annotations.drawing')).toBeVisible()
// R-5: the annotation's row takes the focus, no dialog opens (U2 Task 6).
await expect(active(page)).toHaveAttribute(
'data-properties-heading',
'true',
'data-focus-key',
/"kind":"annotation"/,
)
await expect(active(page)).toHaveAttribute('aria-current', 'true')
await expect(page.getByRole('dialog')).toHaveCount(0)
await selectTab(page, dict, 'verification')
await goTo('Constat A')
@@ -326,7 +326,6 @@ function focusKind(page: Page): Promise<Kind> {
if (el.closest('[role="toolbar"]')) return 'tools'
if (el.closest('[data-testid="annotation-canvas"]')) return 'canvas'
if (el.closest('[data-testid="annotation-overview"]')) return 'side'
if (el.closest('[data-testid="annotation-properties"]')) return 'side'
return 'other'
}, dict['editor.history.undo_title'])
}
+5 -2
View File
@@ -172,10 +172,13 @@ test.describe('editor shell, kept places (B2a)', () => {
.first()
.click()
await expect(place(page, 'annotations.drawing')).toBeVisible()
// R-5: the annotation's row takes the focus, no dialog opens (U2 Task 6).
await expect(active(page)).toHaveAttribute(
'data-properties-heading',
'true',
'data-focus-key',
/"kind":"annotation"/,
)
await expect(active(page)).toHaveAttribute('aria-current', 'true')
await expect(page.getByRole('dialog')).toHaveCount(0)
})
test('arrowing back onto a tab keeps the focus on the tab', async ({
+6 -3
View File
@@ -24,6 +24,7 @@ import {
serverRevision,
shapeWith,
showDrawing,
openProperties,
} from '../support/editor'
// V1-2.6 A4 (contract C9 to C12, C19): the structures around the drawing. Annotation
@@ -324,13 +325,15 @@ test.describe('editor structures (A4)', () => {
// The point goes first; the zone then deletes with its descendants named.
await showDrawing(page, dict)
await pickAnnotation(page, dict, /Point lié/)
await page
.getByTestId('annotation-properties')
// U2 Task 6: « Supprimer » sits in the properties dialog; its confirmation lies over it.
const properties = await openProperties(page, dict)
await properties
.getByRole('button', { name: dict['editor.action.delete'] })
.click()
await dialog(page)
await deleteDialog(page)
.getByRole('button', { name: dict['editor.delete.confirm'] })
.click()
await expect(page.locator('dialog[open]')).toHaveCount(0)
await selectTab(page, dict, 'findings')
await zone.first().click()
await findingDialog(page)
+55 -96
View File
@@ -28,7 +28,6 @@ const DRAFT = join(
)
const THORACIC = /Vertèbres thoraciques/
// The side panel's content may change (U2 Task 6 moves it into a dialog).
const SWAPS = ['aside-content'] as const
interface Draft {
vertebral_config: unknown
@@ -84,14 +83,10 @@ async function undoTo(
points: () => Promise<unknown>,
expected: unknown,
) {
await expectNoShift(
page,
async () => {
await undo(page)
await expect.poll(points).toEqual(expected)
},
SWAPS,
)
await expectNoShift(page, async () => {
await undo(page)
await expect.poll(points).toEqual(expected)
})
}
/** A press and release at the centre of a handle's hit shape. */
@@ -144,37 +139,27 @@ test.describe('editor zones on the drawing (U2 Task 5)', () => {
await expect(page.getByTestId('edit-strip-notice')).toContainText(
dict['editor.annotations.strip.zoom_hint'],
)
// Playwright's auto-scroll to the list row left the header under the sticky top bar.
await page.evaluate(() => window.scrollTo(0, 0))
await expectAccessible(page, 'a selected zone: vertices and « + »')
const stored = await shownPoints(page)
// A vertex dragged: one commit, the vertex chosen, then undone.
await expectNoShift(
page,
async () => {
await dragDrawing(page, { x: 1103, y: 558.9 }, { x: 1103, y: 620 })
await expect(line(page)).toContainText(
dict['editor.annotations.message.vertex_moved'],
)
},
SWAPS,
)
await expectNoShift(page, async () => {
await dragDrawing(page, { x: 1103, y: 558.9 }, { x: 1103, y: 620 })
await expect(line(page)).toContainText(
dict['editor.annotations.message.vertex_moved'],
)
})
const [, moved] = await shownPoints(page)
expect(Math.abs(moved[1] - 620)).toBeLessThan(3)
await undoTo(page, () => shownPoints(page), stored)
// « + » on the segment from vertex 2: a vertex added and chosen, then undone.
await expectNoShift(
page,
async () => {
await pressHandle(page, 'Ajouter un sommet après le sommet 2')
await expect(line(page)).toContainText(
dict['editor.annotations.message.vertex_added'],
)
},
SWAPS,
)
await expectNoShift(page, async () => {
await pressHandle(page, 'Ajouter un sommet après le sommet 2')
await expect(line(page)).toContainText(
dict['editor.annotations.message.vertex_added'],
)
})
expect(await count(page)).toBe(10)
await expect(page.getByTestId('edit-strip-detail')).toContainText(
'sommet 3 choisi',
@@ -182,40 +167,28 @@ test.describe('editor zones on the drawing (U2 Task 5)', () => {
await undoTo(page, () => count(page), 9)
// « − » on the chosen vertex 3, then undone.
await expectNoShift(
page,
async () => {
await pressHandle(page, 'Sommet 3')
await expect(page.getByTestId('edit-strip-detail')).toContainText(
'sommet 3 choisi',
)
},
SWAPS,
)
await expectNoShift(
page,
async () => {
await pressHandle(page, 'Retirer le sommet 3')
await expect(line(page)).toContainText(
dict['editor.annotations.message.vertex_removed'],
)
},
SWAPS,
)
await expectNoShift(page, async () => {
await pressHandle(page, 'Sommet 3')
await expect(page.getByTestId('edit-strip-detail')).toContainText(
'sommet 3 choisi',
)
})
await expectNoShift(page, async () => {
await pressHandle(page, 'Retirer le sommet 3')
await expect(line(page)).toContainText(
dict['editor.annotations.message.vertex_removed'],
)
})
expect(await count(page)).toBe(8)
await undoTo(page, () => shownPoints(page), stored)
// The interior dragged by the mouse moves the zone as a block, then undone.
await expectNoShift(
page,
async () => {
await dragDrawing(page, { x: 914, y: 498 }, { x: 954, y: 538 })
await expect(line(page)).toContainText(
dict['editor.annotations.message.moved.zone'],
)
},
SWAPS,
)
await expectNoShift(page, async () => {
await dragDrawing(page, { x: 914, y: 498 }, { x: 954, y: 538 })
await expect(line(page)).toContainText(
dict['editor.annotations.message.moved.zone'],
)
})
const [first] = await shownPoints(page)
expect(Math.abs(first[0] - (stored[0][0] + 40))).toBeLessThan(3)
await undoTo(page, () => shownPoints(page), stored)
@@ -234,7 +207,7 @@ test.describe('editor zones on the drawing (U2 Task 5)', () => {
// Not under expectNoShift: the button returns the focus to the list row, which
// scrolls it into view by design.
await page
.getByTestId('annotation-properties')
.getByTestId('edit-strip')
.getByRole('button', { name: dict['editor.annotations.deselect'] })
.click()
await expect(line(page)).toContainText(
@@ -255,10 +228,8 @@ test.describe('editor zones on the drawing (U2 Task 5)', () => {
const stored = await shownPoints(page)
// Accepted: four clicks, « Fermer le tracé », one commit, every property kept.
await expectNoShift(
page,
() => button(page, 'editor.annotations.redraw').click(),
SWAPS,
await expectNoShift(page, () =>
button(page, 'editor.annotations.redraw').click(),
)
for (const [x, y] of [
[850, 440],
@@ -266,49 +237,37 @@ test.describe('editor zones on the drawing (U2 Task 5)', () => {
[1100, 560],
[850, 545],
])
await expectNoShift(page, () => clickAt(page, x, y), SWAPS)
await expectNoShift(page, () => clickAt(page, x, y))
await expect(page.getByTestId('overlay-old-place')).toBeAttached()
await expectNoShift(
page,
async () => {
await button(page, 'editor.annotations.trace_close').click()
await expect(line(page)).toContainText(
dict['editor.annotations.message.redrawn.zone'],
)
},
SWAPS,
)
await expectNoShift(page, async () => {
await button(page, 'editor.annotations.trace_close').click()
await expect(line(page)).toContainText(
dict['editor.annotations.message.redrawn.zone'],
)
})
await expect(selectionTag(page)).toContainText('Vertèbres thoraciques')
expect(await count(page)).toBe(4)
await undoTo(page, () => shownPoints(page), stored)
// Refused: a sliver; the tracing stays open with the core's message, then cancelled.
await expectNoShift(
page,
() => button(page, 'editor.annotations.redraw').click(),
SWAPS,
await expectNoShift(page, () =>
button(page, 'editor.annotations.redraw').click(),
)
for (const [x, y] of [
[900, 450],
[1100, 452],
[1300, 455],
])
await expectNoShift(page, () => clickAt(page, x, y), SWAPS)
await expectNoShift(
page,
async () => {
await button(page, 'editor.annotations.trace_close').click()
await expect(page.getByTestId('edit-strip-title')).toHaveText(
dict['editor.annotations.strip.close_refused'],
)
},
SWAPS,
)
await expectNoShift(page, () => clickAt(page, x, y))
await expectNoShift(page, async () => {
await button(page, 'editor.annotations.trace_close').click()
await expect(page.getByTestId('edit-strip-title')).toHaveText(
dict['editor.annotations.strip.close_refused'],
)
})
await expect(button(page, 'editor.annotations.trace_close')).toBeVisible()
await expectNoShift(
page,
() => button(page, 'editor.annotations.trace_cancel').click(),
SWAPS,
await expectNoShift(page, () =>
button(page, 'editor.annotations.trace_cancel').click(),
)
await expect.poll(() => shownPoints(page)).toEqual(stored)
})
+22 -8
View File
@@ -752,21 +752,35 @@ export const selectionTag = (page: Page) =>
export const twinSelectionTag = (page: Page) =>
page.getByTestId('annotation-selection-tag')
/** Selects an annotation from the overview card, leaving a selection first when there is one. */
/**
* Selects an annotation from the overview card: always shown beside the drawing (U2 Task 6,
* A3), a click on a row selects it (A1).
*/
export async function pickAnnotation(
page: Page,
dict: Dict,
name: RegExp | string,
) {
const all = page.getByRole('button', {
name: dict['editor.annotations.show_all'],
exact: true,
})
const list = annotationList(page, dict)
// Either the card (nothing selected) or the properties panel has settled.
await expect(all.or(list)).toBeVisible()
if (await all.isVisible()) await all.click()
await expect(list).toBeVisible()
await list.getByRole('button', { name }).click()
// The click scrolled the page to the row, lower in the column: the drawing the next
// steps press on is brought back into view (the overview no longer shortens the page).
await page.evaluate(() => window.scrollTo(0, 0))
}
/** The open properties dialog of an annotation (U2 Task 6), by its name. */
export const propertiesDialog = (page: Page, name?: string | RegExp) =>
page.getByRole('dialog', name === undefined ? {} : { name })
/** « Propriétés » in the strip: the selection's properties dialog (A1). */
export async function openProperties(page: Page, dict: Dict) {
await page
.getByTestId('edit-strip')
.getByRole('button', { name: dict['editor.annotations.properties'] })
.click()
await expect(page.getByRole('dialog')).toBeVisible()
return page.getByRole('dialog')
}
export const toolButton = (page: Page, dict: Dict, id: string) =>
+27 -54
View File
@@ -7,13 +7,6 @@
*/
import { expect, type Page } from '@playwright/test'
/**
* What may change by design until a later task, named at the call site only: the side
* panel's own content (its height, the scroll height, and shifts whose every moved node is
* inside it) while it still swaps the overview, the properties and the creation panel.
*/
export type ShiftExemption = 'aside-content'
interface Box {
x: number
y: number
@@ -83,36 +76,29 @@ export async function keepNativeFrames(page: Page): Promise<void> {
}
/** Starts summing layout-shift entries; read back with `shiftTotal`. */
function observeShifts(page: Page, asideExempt: boolean): Promise<void> {
return page.evaluate(
({ exempt, aside }) => {
const scope = window as unknown as ShiftScope
scope.__shiftObserver?.disconnect()
scope.__shift = { total: 0, moved: [] }
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
const shift = entry as unknown as {
value: number
sources: { node?: Node }[]
}
const inAside = shift.sources.every((source) =>
(source.node as Element | undefined)?.closest?.(aside),
)
if (exempt && inAside) continue
scope.__shift.total += shift.value
for (const source of shift.sources) {
const node = source.node as Element | undefined
scope.__shift.moved.push(
node?.outerHTML?.slice(0, 160) ?? String(source.node),
)
}
function observeShifts(page: Page): Promise<void> {
return page.evaluate(() => {
const scope = window as unknown as ShiftScope
scope.__shiftObserver?.disconnect()
scope.__shift = { total: 0, moved: [] }
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
const shift = entry as unknown as {
value: number
sources: { node?: Node }[]
}
})
observer.observe({ type: 'layout-shift' })
scope.__shiftObserver = observer
},
{ exempt: asideExempt, aside: PARTS.aside },
)
scope.__shift.total += shift.value
for (const source of shift.sources) {
const node = source.node as Element | undefined
scope.__shift.moved.push(
node?.outerHTML?.slice(0, 160) ?? String(source.node),
)
}
}
})
observer.observe({ type: 'layout-shift' })
scope.__shiftObserver = observer
})
}
/** Two frames for layout to settle, then the pending entries and the total. */
@@ -140,36 +126,23 @@ function shiftTotal(page: Page): Promise<ShiftScope['__shift']> {
}
/**
* Runs `act` and asserts nothing moved. `exempt: ['aside-content']` lets the side panel's
* content change (see `ShiftExemption`); the aside's position and width, the canvas, the
* strip and the header are still checked, and every shift outside the aside.
* Runs `act` and asserts nothing moved: the boxes of the canvas, the strip, the message
* row, the aside and the header, the scroll height, and no layout shift anywhere (U2 Task
* 6: the aside always shows the overview, so no exemption is left).
*/
export async function expectNoShift(
page: Page,
act: () => Promise<void>,
exempt: readonly ShiftExemption[] = [],
): Promise<void> {
const before = await snapshot(page)
// A selector that stops matching would compare null with null: every part must be there.
for (const [name, box] of Object.entries(before.boxes)) {
expect(box, `${name} box before the act`).not.toBeNull()
}
const loose = exempt.includes('aside-content')
await observeShifts(page, loose)
await observeShifts(page)
await act()
const shift = await shiftTotal(page)
const after = await snapshot(page)
const drop = (shot: Snapshot) => ({
...shot,
scrollHeight: loose ? 0 : shot.scrollHeight,
boxes: {
...shot.boxes,
aside:
loose && shot.boxes.aside
? { ...shot.boxes.aside, height: 0 }
: shot.boxes.aside,
},
})
expect(drop(after)).toEqual(drop(before))
expect(after).toEqual(before)
expect(shift.total, `layout shift of ${shift.moved.join(' | ')}`).toBe(0)
}
@@ -11,6 +11,7 @@ export type GlyphName =
| 'search'
| 'deselect'
| 'move'
| 'properties'
/** The editor's one glyph table (24-unit grid strokes); `book` and `close` are in `Icon`. */
const GLYPHS: Record<GlyphName, string> = {
@@ -25,6 +26,7 @@ const GLYPHS: Record<GlyphName, string> = {
redo: 'M15 7l5 5-5 5M20 12H9a5 5 0 0 0 0 10',
search: 'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4',
move: 'M12 3v18M3 12h18M9 6l3-3 3 3M9 18l3 3 3-3M6 9l-3 3 3 3M18 9l3 3-3 3',
properties: 'M7 3h7l4 4v14H7zM14 3v4h4M10 12h5M10 16h5',
deselect:
'M4 8V5a1 1 0 0 1 1-1h3M16 4h3a1 1 0 0 1 1 1v3M20 16v3a1 1 0 0 1-1 1h-3M8 20H5a1 1 0 0 1-1-1v-3M9 9l6 6M15 9l-6 6',
}
@@ -17,7 +17,11 @@ import useLeaveConfirm from '@/editor/history/useLeaveConfirm'
import { useSessionTag, useSessionTagStore } from '@/editor/history/sessionTag'
import { useLeftDraft, type LeaveFacts } from '@/editor/leftDraft'
import { citationsOfView, defaultView } from '@/editor/navigation'
import { findingLayerOf, referenceLayerOf } from '@/editor/findingLayer'
import {
annotationLayerOf,
findingLayerOf,
referenceLayerOf,
} from '@/editor/findingLayer'
import { initialTab } from '@/editor/tabs'
import {
useEditorNavigation,
@@ -102,6 +106,7 @@ function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
readOnly={readOnly}
navigate={nav.navigate}
layer={findingLayerOf(nav)}
annotationLayer={annotationLayerOf(nav)}
references={references}
libraryReset={state.libraryReset}
focus={state.focus}
@@ -45,6 +45,8 @@ export interface AnnotationCanvasProps {
/** The composed root as rebuilt (with its view); null on failure. */
onRoot: (root: RootAttributes | null) => void
onSelect: (id: string) => void
/** A second click on the selection, or a double click: its properties dialog (A1). */
onOpen: (id: string) => void
/** A click with a drawing tool, in drawing units, and its closing reach (R-11). */
onPlace: (at: XY, reach: number) => void
onDrop: Drop
@@ -0,0 +1,263 @@
import { useEffect, useRef, useState, type RefObject } from 'react'
import type {
AnatomicalSheetDocument,
Annotation,
Marking,
} from '@faunosteo/core-wasm/types'
import DeleteDialog from '@/components/editor/DeleteDialog'
import Button from '@/components/ui/Button'
import { useItemMode } from '@/components/editor/findings/useItemMode'
import Dialog from '@/components/ui/Dialog'
import { landAfterModalsClosed } from '@/components/ui/afterModalsClosed'
import { visibleElement } from '@/editor/focusRequest'
import { isEditable } from '@/editor/annotations/geometryEdit'
import type { AnnotationLayer } from '@/editor/tabs'
import { unmeasuredViews } from '@/editor/issues'
import { useEditorStore } from '@/editor/state/editorStore'
import { useEditCommand } from '@/editor/useEditCommand'
import { usePlaceVisible } from '@/lib/placeVisibility'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import EditorGlyph from '../EditorGlyph'
import AnnotationEditForm from './AnnotationEditForm'
import { annotationName } from './AnnotationList'
import AnnotationReadBody from './AnnotationReadBody'
export interface AnnotationDialogProps {
layer: AnnotationLayer
doc: AnatomicalSheetDocument
readOnly: boolean
/** The column the dialog sits over (A2); null: centred. */
anchor: RefObject<HTMLElement | null>
/** Where the focus goes once the dialog is closed (board 32). */
returnFocus: () => HTMLElement | null
}
const EDIT_BUTTON_ID = 'annotation-edit-button'
const ACTION = 'min-h-11 gap-1.5 xl:min-h-9'
/**
* The first handle of the selection in the tab order (board 32: « + » included); above
* the handle cap (R-7), the strip's « Déplacer la zone ».
*/
const firstHandle = () =>
visibleElement('[data-testid="handle-layer"] [tabindex="0"]') ??
visibleElement('[data-testid="edit-strip"] [data-move-entry]')
/** « Modifier la forme » is offered when the shape has handles on a measured view. */
function useShapeEditable(annotation: Annotation): boolean {
const state = useEditorStore((s) => s.previewState)
const measured =
state !== null && !unmeasuredViews(state).has(annotation.view_id)
return measured && isEditable(annotation.geometry)
}
/**
* The annotation the layer names vanished (an undo, a reload, a refresh): the layer
* closes by replace and says so, once per view of the layer.
*/
function useGoneRule(layer: AnnotationLayer, doc: AnatomicalSheetDocument) {
const t = useT()
const handled = useRef<string | null>(null)
const id = layer.view?.id ?? null
useEffect(() => {
if (id === null) handled.current = null
if (id === null || doc.annotations.some((a) => a.id === id)) return
if (handled.current === id) return
handled.current = id
const gone = t('editor.annotations.gone')
// After this commit's effects: the form's guard must still answer the forced close.
queueMicrotask(() => layer.replace(null, gone))
}, [id, doc, layer, t])
}
function StatusAction({ annotation }: { annotation: Annotation }) {
const t = useT()
const edit = useEditCommand()
const reviewed = annotation.review_status === 'reviewed'
// A10: one `set_status`, one « Défaire ».
const mark = (status: Marking) =>
edit.run('status', {
op: 'set_status',
key: { kind: 'annotation', id: annotation.id },
status,
})
return (
<>
<Button
type="button"
size="sm"
variant="secondary"
className={ACTION}
onClick={() => mark(reviewed ? 'to_confirm' : 'reviewed')}
>
{t(
reviewed
? 'editor.annotations.to_confirm'
: 'editor.annotations.mark_reviewed',
)}
</Button>
{edit.fieldError('status') && (
<p
role="alert"
className="w-full text-sm text-[var(--color-danger-strong)]"
>
{edit.fieldError('status')}
</p>
)}
</>
)
}
interface ReadProps {
annotation: Annotation
doc: AnatomicalSheetDocument
onEdit: () => void
onEditShape: () => void
/** The annotation was deleted from here: the layer closes, nothing to say. */
onDeleted: () => void
}
/** Whether the document still holds the annotation `id`. */
const stillThere = (id: string) =>
useEditorStore
.getState()
.previewState?.document.annotations.some((a) => a.id === id) ?? false
/** Board 31 A: « Modifier », « Modifier la forme », then the review and « Supprimer ». */
function ReadActions(props: ReadProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const [deleting, setDeleting] = useState(false)
const { annotation } = props
const shapeEditable = useShapeEditable(annotation)
const label = annotationName(annotation, props.doc.views, locale)
return (
<div className="space-y-2 border-t border-[var(--color-border)] pt-3">
<div className="flex flex-wrap gap-2">
<Button
id={EDIT_BUTTON_ID}
type="button"
size="sm"
variant="secondary"
className={ACTION}
onClick={props.onEdit}
>
{t('editor.findings.edit')}
</Button>
{shapeEditable && (
<Button
type="button"
size="sm"
variant="secondary"
className={ACTION}
onClick={props.onEditShape}
>
<EditorGlyph name="move" size={16} />
{t('editor.annotations.edit_shape')}
</Button>
)}
</div>
<div className="flex flex-wrap items-center justify-between gap-2">
<StatusAction annotation={annotation} />
<Button
type="button"
size="sm"
variant="danger"
className={ACTION}
onClick={() => setDeleting(true)}
>
{t('editor.action.delete')}
</Button>
</div>
<DeleteDialog
target={
deleting
? { key: { kind: 'annotation', id: annotation.id }, label }
: null
}
onClose={() => {
setDeleting(false)
if (!stillThere(annotation.id)) props.onDeleted()
}}
/>
</div>
)
}
type BodyProps = Omit<AnnotationDialogProps, 'anchor' | 'returnFocus'> & {
annotation: Annotation
}
/**
* Read first, « Modifier » for the form: a local mode of the one dialog, no history
* entry. Read-only: values only, no action (R-16); a form already open stays (R-14).
*/
function DialogBody(props: BodyProps) {
const t = useT()
const { annotation, layer, readOnly } = props
const mode = useItemMode(EDIT_BUTTON_ID)
const editShape = () => {
layer.close()
// « Modifier la forme »: the selection stays, the focus goes to its first handle.
landAfterModalsClosed(() => firstHandle()?.focus())
}
if (mode.editing) {
return (
<AnnotationEditForm
annotation={annotation}
doc={props.doc}
readOnly={readOnly}
guards={layer.guards}
onDone={mode.done}
onDiscardClose={() => layer.close(true)}
onGone={() => layer.replace(null, t('editor.annotations.gone'))}
/>
)
}
return (
<div className="space-y-3">
<AnnotationReadBody annotation={annotation} doc={props.doc} />
{!readOnly && (
<ReadActions
annotation={annotation}
doc={props.doc}
onEdit={mode.startEdit}
onEditShape={editShape}
onDeleted={() => layer.replace(null)}
/>
)}
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{mode.saved ? t('editor.findings.saved') : ''}
</p>
</div>
)
}
/**
* The annotation properties dialog (U2 Task 6, A1 A2 A9 A10): one `Dialog` over the right
* column, driven by the history layer, mounted outside the edit-only body so a read-only
* flip keeps it and its draft (R-14). It opens only while the drawing is shown.
*/
export default function AnnotationDialog(props: AnnotationDialogProps) {
const locale = useLocaleStore((s) => s.locale)
const visible = usePlaceVisible()
const { layer, doc } = props
useGoneRule(layer, doc)
const annotation = doc.annotations.find((a) => a.id === layer.view?.id)
const title = annotation ? annotationName(annotation, doc.views, locale) : ''
return (
<Dialog
open={visible && annotation !== undefined}
layer
anchor={props.anchor}
title={title}
returnFocus={props.returnFocus}
onClose={() => (layer.close() ? undefined : 'kept')}
>
{annotation && (
<DialogBody key={annotation.id} {...props} annotation={annotation} />
)}
</Dialog>
)
}
@@ -0,0 +1,213 @@
import { useState } from 'react'
import type {
AnatomicalSheetDocument,
Annotation,
} from '@faunosteo/core-wasm/types'
import { FormActions } from '@/components/editor/findings/DiscardConfirm'
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
import { useFormDraft } from '@/components/editor/findings/useDirtyGuard'
import type { CreationForm } from '@/editor/annotations/creation'
import {
missingFields,
type MissingField,
} from '@/editor/annotations/missingFields'
import { nullable } from '@/editor/sheetDocument'
import { useEditorStore } from '@/editor/state/editorStore'
import { useEditCommand } from '@/editor/useEditCommand'
import type { Guards } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
import CreationFields from './CreationFields'
/** 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. */
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 {
fr: annotation.name?.fr ?? '',
en: annotation.name?.en ?? '',
categoryId: annotation.category_id,
laterality: annotation.laterality,
color: annotation.color ?? '',
opensViewId: link ? annotation.opens_view_id : '',
zoneId: link ? '' : (annotation.finding_zone_id ?? ''),
regionCode: link ? '' : (annotation.vertebral_region_code ?? ''),
}
}
const sameDraft = (a: Draft, b: Draft) =>
JSON.stringify(a) === JSON.stringify(b)
/** The names as saved: trimmed, or none for a link left with both blank. */
function namesOf(annotation: Annotation, draft: Draft) {
const name = { fr: draft.fr.trim(), en: draft.en.trim() }
const none = name.fr === '' && name.en === ''
return annotation.kind === 'detail_trigger' && none ? null : name
}
/**
* The CURRENT annotation with only the fields the user changed (`first` → `draft`): a
* change made meanwhile elsewhere (a drag, a review toggle) is never overwritten.
*/
function merged(current: Annotation, first: Draft, draft: Draft): Annotation {
const changed = (key: keyof Draft) => first[key] !== draft[key]
const value: Record<string, unknown> = { ...current }
if (changed('fr') || changed('en')) value.name = namesOf(current, draft)
if (changed('categoryId')) value.category_id = draft.categoryId
if (changed('laterality')) value.laterality = draft.laterality
if (changed('color')) value.color = nullable(draft.color.trim())
if (current.kind === 'detail_trigger') {
if (changed('opensViewId')) value.opens_view_id = draft.opensViewId
} else {
if (changed('zoneId')) value.finding_zone_id = nullable(draft.zoneId)
if (changed('regionCode'))
value.vertebral_region_code = nullable(draft.regionCode)
}
return value as unknown as Annotation
}
/** The annotation as the document holds it now, read by id at the save. */
function currentAnnotation(id: string): Annotation | undefined {
const doc = useEditorStore.getState().previewState?.document
return doc?.annotations.find((a) => a.id === id)
}
export interface AnnotationEditFormProps {
annotation: Annotation
doc: AnatomicalSheetDocument
readOnly: boolean
guards: Guards
/** Back to the read mode; `saved` is true when a command was written. */
onDone: (saved: boolean) => void
/** « Abandonner » after a close request: the draft goes, so does the dialog. */
onDiscardClose: () => void
/** The annotation vanished before the save: the dialog closes and says so. */
onGone: () => void
}
/** The one save (R-3, transactional): missing fields named, nothing when unchanged. */
function useSave(props: AnnotationEditFormProps, form: FormDraft) {
const edit = useEditCommand()
const [missing, setMissing] = useState<MissingField[]>([])
const first = useState(() => draftOf(props.annotation))[0]
const save = () => {
if (props.readOnly) return
const absent = missingFields(props.annotation.kind, form.draft)
setMissing(absent)
if (absent.length > 0) {
document.getElementById(`${ID_PREFIX}${FIELD_ID[absent[0]!]}`)?.focus()
return
}
if (!form.dirty) return props.onDone(false)
const current = currentAnnotation(props.annotation.id)
if (!current) return props.onGone()
const key = { kind: 'annotation', id: current.id } as const
const value = merged(current, first, form.draft)
const element = { kind: 'annotation', value } as const
if (edit.run('save', { op: 'update', key, element })) props.onDone(true)
}
return { missing, save, error: edit.fieldError('save') }
}
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.
* When the editor turns read-only the draft stays, its fields disabled and the save off
* (R-14); it is editable again on the way back.
*/
export default function AnnotationEditForm(props: AnnotationEditFormProps) {
const t = useT()
const { annotation, readOnly } = props
const form = useFormDraft(
draftOf(annotation),
props.guards,
sameDraft,
'annotation',
)
const saving = useSave(props, form)
const { guard } = form
const cancel = () =>
form.dirty && !readOnly ? guard.askToLeave() : props.onDone(false)
const discard =
guard.confirming === 'dialog'
? props.onDiscardClose
: () => props.onDone(false)
return (
<form
data-draft-form
className="space-y-3"
noValidate
onSubmit={(event) => {
event.preventDefault()
saving.save()
}}
>
{readOnly && <ReadOnlyNotice />}
<CreationFields
kind={annotation.kind}
viewId={annotation.view_id}
doc={props.doc}
form={form.draft}
onChange={form.set}
color={{
value: form.draft.color,
onChange: (color) => form.set({ color }),
}}
idPrefix={ID_PREFIX}
missing={saving.missing}
readOnly={readOnly}
editing
/>
<MissingSummary missing={saving.missing} />
{saving.error && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{saving.error}
</p>
)}
<FormActions
confirming={guard.confirming}
readOnly={readOnly}
submitLabel={t('editor.findings.save')}
onCancel={cancel}
onKeepTyping={guard.keepTyping}
onDiscard={guard.discard(discard)}
/>
</form>
)
}
@@ -1,192 +0,0 @@
import type {
AnatomicalSheetDocument,
Annotation,
Laterality,
} from '@faunosteo/core-wasm/types'
import SelectField from '@/components/editor/fields/SelectField'
import TextField from '@/components/editor/fields/TextField'
import { LATERALITIES, directChildren } from '@/editor/annotations/creation'
import { isBlank, nullable } from '@/editor/sheetDocument'
import type { EditCommandApi } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
interface Props {
annotation: Annotation
doc: AnatomicalSheetDocument
readOnly: boolean
edit: EditCommandApi
/** Put before every field id (the read-only twin of the panel). */
idPrefix?: string
}
/** One `update` carrying the whole annotation with `patch` applied. */
function useSend({ annotation, edit }: Props) {
return (field: string, patch: Record<string, unknown>) =>
edit.run(field, {
op: 'update',
key: { kind: 'annotation', id: annotation.id },
element: {
kind: 'annotation',
value: { ...annotation, ...patch } as Annotation,
},
})
}
const noneOption = (label: string) => ({ value: '', label })
/** Names: both or none for a link (its name is optional), both required otherwise. */
function NameFields(props: Props) {
const t = useT()
const send = useSend(props)
const { annotation, edit, readOnly, idPrefix = '' } = props
const isLink = annotation.kind === 'detail_trigger'
const rename = (locale: 'fr' | 'en') => (value: string) => {
const name = {
fr: annotation.name?.fr ?? '',
en: annotation.name?.en ?? '',
[locale]: value,
}
const blanks = [name.fr, name.en].filter(isBlank).length
if (isLink && blanks === 2) return send(locale, { name: null })
if (blanks > 0) return edit.reject(locale, 'editor.field.required_names')
return send(locale, { name })
}
return (
<>
{(['fr', 'en'] as const).map((locale) => (
<TextField
key={locale}
id={`${idPrefix}annotation-name-${locale}`}
label={t(`editor.annotations.name_${locale}`)}
value={annotation.name?.[locale] ?? ''}
onCommit={rename(locale)}
readOnly={readOnly}
trim
error={edit.fieldError(locale)}
/>
))}
</>
)
}
export default function AnnotationFields(props: Props) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const send = useSend(props)
const { annotation, doc, readOnly, edit, idPrefix = '' } = props
const categories = doc.categories.map((c) => ({
value: c.id,
label: c.name[locale],
}))
const sides = LATERALITIES.map((l: Laterality) => ({
value: l,
label: t(`editor.annotations.laterality.${l}`),
}))
return (
<div className="grid gap-3 sm:grid-cols-2">
<NameFields {...props} />
<SelectField
id={`${idPrefix}annotation-category`}
label={t('editor.annotations.category')}
value={annotation.category_id}
options={categories}
onCommit={(value) => send('category', { category_id: value })}
readOnly={readOnly}
error={edit.fieldError('category')}
/>
<TextField
id={`${idPrefix}annotation-color`}
label={t('editor.annotations.color')}
value={annotation.color ?? ''}
onCommit={(value) => send('color', { color: nullable(value) })}
readOnly={readOnly}
hint={t('editor.annotations.color_hint')}
error={edit.fieldError('color')}
/>
<SelectField
id={`${idPrefix}annotation-laterality`}
label={t('editor.annotations.laterality')}
value={annotation.laterality}
options={sides}
onCommit={(value) => send('laterality', { laterality: value })}
readOnly={readOnly}
error={edit.fieldError('laterality')}
/>
{annotation.kind === 'detail_trigger' ? (
<OpensField {...props} />
) : (
<LinkFields {...props} annotation={annotation} />
)}
</div>
)
}
function OpensField({ annotation, doc, readOnly, edit, idPrefix = '' }: Props) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const send = useSend({ annotation, doc, readOnly, edit })
if (annotation.kind !== 'detail_trigger') return null
const options = directChildren(doc.views, annotation.view_id).map((v) => ({
value: v.id,
label: v.name[locale],
}))
const current = doc.views.find((v) => v.id === annotation.opens_view_id)
if (current && !options.some((o) => o.value === current.id)) {
options.push({ value: current.id, label: current.name[locale] })
}
return (
<SelectField
id={`${idPrefix}annotation-opens`}
label={t('editor.annotations.opens')}
value={annotation.opens_view_id}
options={options}
onCommit={(value) => send('opens', { opens_view_id: value })}
readOnly={readOnly}
error={edit.fieldError('opens')}
/>
)
}
function LinkFields(props: Props) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const send = useSend(props)
const { annotation, doc, readOnly, edit, idPrefix = '' } = props
if (annotation.kind === 'detail_trigger') return null
const regions = [
noneOption(t('editor.annotations.none')),
...doc.vertebral_config.regions.map((r) => ({
value: r.code,
label: r.name[locale],
})),
]
const zones = [
noneOption(t('editor.annotations.none')),
...doc.finding_zones.map((z) => ({ value: z.id, label: z.name[locale] })),
]
return (
<>
<SelectField
id={`${idPrefix}annotation-region`}
label={t('editor.annotations.region')}
value={annotation.vertebral_region_code ?? ''}
options={regions}
onCommit={(value) =>
send('region', { vertebral_region_code: nullable(value) })
}
readOnly={readOnly}
error={edit.fieldError('region')}
/>
<SelectField
id={`${idPrefix}annotation-zone`}
label={t('editor.annotations.zone')}
value={annotation.finding_zone_id ?? ''}
options={zones}
onCommit={(value) => send('zone', { finding_zone_id: nullable(value) })}
readOnly={readOnly}
error={edit.fieldError('zone')}
/>
</>
)
}
@@ -2,14 +2,22 @@ import type { Annotation, SheetView } from '@faunosteo/core-wasm/types'
import type { AnnotationGroup } from '@/editor/annotations/overview'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import ReviewBadge from './ReviewBadge'
import { ReviewSlot } from './ReviewBadge'
const LIST = 'max-h-96 space-y-2 overflow-y-auto'
const ROW =
'flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm ' +
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset ' +
'focus-visible:ring-[var(--color-accent)]'
'focus-visible:ring-[var(--color-accent)] ' +
'aria-[current=true]:bg-[var(--color-surface-strong)] aria-[current=true]:font-semibold'
/** What a row does: a click or Enter selects (A1); Enter on the selected row opens. */
interface RowActions {
selectedId: string | null
onSelect: (id: string) => void
onOpen: (id: string) => void
}
/** The name an annotation shows: its own, else (an unnamed link) the view it opens. */
export function annotationName(
@@ -26,14 +34,15 @@ export function annotationName(
function Row({
annotation,
views,
onSelect,
actions,
}: {
annotation: Annotation
views: readonly SheetView[]
onSelect: (id: string) => void
actions: RowActions
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const selected = actions.selectedId === annotation.id
return (
<li>
<button
@@ -42,7 +51,14 @@ function Row({
kind: 'annotation',
id: annotation.id,
})}
onClick={() => onSelect(annotation.id)}
aria-current={selected ? 'true' : undefined}
onKeyDown={(event) => {
// A held Enter selects once and never opens on its repeats.
if (event.key !== 'Enter' || !selected) return
event.preventDefault()
if (!event.repeat) actions.onOpen(annotation.id)
}}
onClick={() => actions.onSelect(annotation.id)}
className={ROW}
>
<span className="min-w-0 truncate">
@@ -51,7 +67,7 @@ function Row({
</span>{' '}
{annotationName(annotation, views, locale)}
</span>
<ReviewBadge status={annotation.review_status} />
<ReviewSlot status={annotation.review_status} />
</button>
</li>
)
@@ -80,21 +96,21 @@ function GroupTitle({ group, id }: { group: AnnotationGroup; id: string }) {
}
/**
* The annotations of the view by category, each row a button reachable from the keyboard.
* Selection works in every mode, so a read-only draft is browsable.
* The annotations of the view by category, each row a button reachable from the keyboard,
* the selected one marked (A3). Selection works in every mode, so a read-only draft is
* browsable.
*/
export default function AnnotationList({
groups,
views,
idPrefix = '',
onSelect,
...actions
}: {
groups: readonly AnnotationGroup[]
views: readonly SheetView[]
/** Put before every id (the read-only twin beside the kept edit panel). */
idPrefix?: string
onSelect: (id: string) => void
}) {
} & RowActions) {
const t = useT()
return (
<ul aria-label={t('editor.annotations.list')} className={LIST}>
@@ -109,7 +125,7 @@ export default function AnnotationList({
key={annotation.id}
annotation={annotation}
views={views}
onSelect={onSelect}
actions={actions}
/>
))}
</ul>
@@ -0,0 +1,155 @@
import type { ReactNode } from 'react'
import type {
AnatomicalSheetDocument,
Annotation,
} from '@faunosteo/core-wasm/types'
import { useGeometryIssues } from '@/editor/annotations/useGeometryIssues'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import ReviewBadge from './ReviewBadge'
function Row({ label, children }: { label: string; children: ReactNode }) {
return (
<div className="grid grid-cols-[8.5rem_minmax(0,1fr)] gap-2 py-1">
<dt className="text-sm text-[var(--color-ink-muted)]">{label}</dt>
<dd className="min-w-0 break-words text-sm">{children}</dd>
</div>
)
}
/** The category's swatch and name, as the overview shows a category. */
function CategoryValue({
annotation,
doc,
}: {
annotation: Annotation
doc: AnatomicalSheetDocument
}) {
const locale = useLocaleStore((s) => s.locale)
const category = doc.categories.find((c) => c.id === annotation.category_id)
return (
<span className="inline-flex items-center gap-2">
<span
aria-hidden="true"
className="size-3 shrink-0 rounded-full border border-[var(--color-border)]"
style={{ backgroundColor: category?.color ?? undefined }}
/>
{category ? category.name[locale] : annotation.category_id}
</span>
)
}
/** A link's opened view, or a point's or zone's region (when set) and findings zone. */
function LinkRows({
annotation,
doc,
}: {
annotation: Annotation
doc: AnatomicalSheetDocument
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
if (annotation.kind === 'detail_trigger') {
const opened = doc.views.find((v) => v.id === annotation.opens_view_id)
return (
<Row label={t('editor.annotations.opens')}>
{opened?.name[locale] ?? annotation.opens_view_id}
</Row>
)
}
const code = annotation.vertebral_region_code
const region = doc.vertebral_config.regions.find((r) => r.code === code)
const zone = doc.finding_zones.find(
(z) => z.id === annotation.finding_zone_id,
)
return (
<>
{code !== null && (
<Row label={t('editor.annotations.region')}>
{region?.name[locale] ?? code}
</Row>
)}
<Row label={t('editor.annotations.zone')}>
{zone?.name[locale] ?? t('editor.annotations.none')}
</Row>
</>
)
}
/** The geometry's state when it is not drawn as a shape, then what the core still refuses. */
function GeometryState({ annotation }: { annotation: Annotation }) {
const t = useT()
const issues = useGeometryIssues(annotation.id)
const { geometry } = annotation
const special = geometry === null || geometry.type === 'path'
return (
<>
{special && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t(
geometry === null
? 'editor.annotations.no_geometry'
: 'editor.annotations.path',
)}
</p>
)}
{issues.length > 0 && (
<ul
role="alert"
data-testid="annotation-geometry-issues"
className="list-disc pl-5 text-sm text-[var(--color-danger-strong)]"
>
{issues.map((issue) => (
<li key={issue}>{issue}</li>
))}
</ul>
)}
</>
)
}
/**
* An annotation read (board 31 A, B, F): its type and status, then its values as text.
* « Couleur » shows only for an own colour (A9), « Région vertébrale » only when set. The
* properties dialog and the phone's read-only column both render it.
*/
export default function AnnotationReadBody({
annotation,
doc,
}: {
annotation: Annotation
doc: AnatomicalSheetDocument
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const view = doc.views.find((v) => v.id === annotation.view_id)
const side = t(`editor.annotations.laterality.${annotation.laterality}`)
return (
<div data-testid="annotation-read" className="space-y-3">
<p className="flex items-center gap-2 text-sm text-[var(--color-ink-muted)]">
{t(`editor.annotations.kind.${annotation.kind}`)}
<ReviewBadge status={annotation.review_status} />
</p>
<dl>
<Row label={t('editor.annotations.name_fr')}>
{annotation.name?.fr ?? '—'}
</Row>
<Row label={t('editor.annotations.name_en')}>
{annotation.name?.en ?? '—'}
</Row>
<Row label={t('editor.annotations.category')}>
<CategoryValue annotation={annotation} doc={doc} />
</Row>
{annotation.color !== null && (
<Row label={t('editor.annotations.color')}>{annotation.color}</Row>
)}
<Row label={t('editor.annotations.laterality')}>{side}</Row>
<LinkRows annotation={annotation} doc={doc} />
<Row label={t('editor.annotations.view')}>
{view?.name[locale] ?? annotation.view_id}
</Row>
</dl>
<GeometryState annotation={annotation} />
</div>
)
}
@@ -3,7 +3,7 @@ import type {
Laterality,
} from '@faunosteo/core-wasm/types'
import DraftField from '@/components/editor/fields/DraftField'
import FormField from '@/components/ui/FormField'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Select from '@/components/ui/Select'
import {
LATERALITIES,
@@ -11,6 +11,7 @@ import {
type CreationForm,
type PendingElement,
} from '@/editor/annotations/creation'
import type { MissingField } from '@/editor/annotations/missingFields'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
@@ -18,6 +19,23 @@ interface FieldsProps {
doc: AnatomicalSheetDocument
form: CreationForm
onChange: (patch: Partial<CreationForm>) => void
/** Put before every field id: `creation-` unless another form shares the page. */
idPrefix?: string
/** The fields R-3 names as missing: each says so under itself. */
missing?: readonly MissingField[]
/** Shown but not editable (the editor turned read-only under a kept form, R-14). */
readOnly?: boolean
/**
* The edit form of an existing annotation (U2 Task 6): one column, optional links read
* « Aucune », and the view a link opens stays listed even when no longer a direct child.
*/
editing?: boolean
}
/** « Couleur » (A9): the annotation's own colour, blank for the category's. */
export interface ColorField {
value: string
onChange: (value: string) => void
}
interface Option {
@@ -32,20 +50,30 @@ function OptionSelect({
options,
blank,
onChange,
error,
readOnly,
}: {
id: string
label: string
value: string
options: Option[]
/** A « Choisir… » entry: the choice is required and has no default. */
blank: boolean
/** The first, empty entry: « Choisir… » (required, no default) or « Aucune ». */
blank: string | null
onChange: (value: string) => void
error?: string
readOnly?: boolean
}) {
const t = useT()
return (
<FormField id={id} label={label}>
<Select id={id} value={value} onChange={(e) => onChange(e.target.value)}>
{blank && <option value="">{t('editor.field.choose')}</option>}
<FormField id={id} label={label} error={error}>
<Select
id={id}
value={value}
disabled={readOnly}
aria-invalid={Boolean(error)}
aria-describedby={fieldDescribedBy(id, undefined, error)}
onChange={(e) => onChange(e.target.value)}
>
{blank !== null && <option value="">{blank}</option>}
{options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
@@ -56,15 +84,54 @@ function OptionSelect({
)
}
/** The fields the core requires, collected before the insert. */
/** The R-3 message under a missing field, else nothing. */
function useMissing(props: FieldsProps) {
const t = useT()
return (field: MissingField) =>
props.missing?.includes(field)
? t(`editor.annotations.missing.${field}`)
: undefined
}
function NameFields(props: FieldsProps) {
const t = useT()
const missing = useMissing(props)
const { form, onChange, idPrefix = 'creation-' } = props
return (
<>
{(['fr', 'en'] as const).map((locale) => (
<DraftField
key={locale}
id={`${idPrefix}${locale}`}
label={t(`editor.annotations.name_${locale}`)}
value={form[locale]}
onChange={(value) => onChange({ [locale]: value })}
readOnly={props.readOnly}
error={missing(`name_${locale}`)}
/>
))}
</>
)
}
/**
* The fields the core requires, collected before the insert or the save; « Couleur »
* shows when `color` is given (the edit form).
*/
export default function CreationFields({
kind,
viewId,
color,
...fields
}: FieldsProps & { kind: PendingElement['kind']; viewId: string }) {
}: FieldsProps & {
kind: PendingElement['kind']
viewId: string
color?: ColorField
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const { doc, form, onChange } = fields
const missing = useMissing(fields)
const { doc, form, onChange, idPrefix = 'creation-', readOnly } = fields
const categories = doc.categories.map((c) => ({
value: c.id,
label: c.name[locale],
@@ -73,37 +140,34 @@ export default function CreationFields({
value: l,
label: t(`editor.annotations.laterality.${l}`),
}))
const columns = fields.editing ? '' : 'sm:grid-cols-2'
return (
<div className="grid gap-3 sm:grid-cols-2">
<DraftField
id="creation-fr"
label={t('editor.annotations.name_fr')}
value={form.fr}
onChange={(fr) => onChange({ fr })}
/>
<DraftField
id="creation-en"
label={t('editor.annotations.name_en')}
value={form.en}
onChange={(en) => onChange({ en })}
/>
<div className={`grid gap-3 ${columns}`}>
<NameFields {...fields} />
<OptionSelect
id="creation-category"
id={`${idPrefix}category`}
label={t('editor.annotations.category')}
value={form.categoryId}
options={categories}
blank={false}
blank={null}
onChange={(categoryId) => onChange({ categoryId })}
error={missing('category')}
readOnly={readOnly}
/>
{color && (
<ColorInput {...color} id={`${idPrefix}color`} readOnly={readOnly} />
)}
<OptionSelect
id="creation-laterality"
id={`${idPrefix}laterality`}
label={t('editor.annotations.laterality')}
value={form.laterality}
options={sides}
blank
blank={t('editor.field.choose')}
onChange={(laterality) =>
onChange({ laterality: laterality as CreationForm['laterality'] })
}
error={missing('laterality')}
readOnly={readOnly}
/>
{kind === 'detail_trigger' ? (
<OpensSelect {...fields} viewId={viewId} />
@@ -114,34 +178,63 @@ export default function CreationFields({
)
}
function OpensSelect({
doc,
form,
function ColorInput({
id,
value,
onChange,
viewId,
}: FieldsProps & { viewId: string }) {
readOnly,
}: ColorField & { id: string; readOnly?: boolean }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const options = directChildren(doc.views, viewId).map((v) => ({
value: v.id,
label: v.name[locale],
}))
return (
<OptionSelect
id="creation-opens"
label={t('editor.annotations.opens')}
value={form.opensViewId}
options={options}
blank
onChange={(opensViewId) => onChange({ opensViewId })}
<DraftField
id={id}
label={t('editor.annotations.color')}
value={value}
onChange={onChange}
readOnly={readOnly}
placeholder={t('editor.annotations.color_placeholder')}
hint={t('editor.annotations.color_hint')}
/>
)
}
/** Findings zone and vertebral region: optional links of a point or a zone. */
function LinkSelects({ doc, form, onChange }: FieldsProps) {
function OpensSelect(props: FieldsProps & { viewId: string }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const missing = useMissing(props)
const { doc, form, onChange, viewId, idPrefix = 'creation-' } = props
const options = directChildren(doc.views, viewId).map((v) => ({
value: v.id,
label: v.name[locale],
}))
// An existing link keeps showing the view it opens, even once no longer a direct child.
const current = doc.views.find((v) => v.id === form.opensViewId)
if (
props.editing &&
current &&
!options.some((o) => o.value === current.id)
) {
options.push({ value: current.id, label: current.name[locale] })
}
return (
<OptionSelect
id={`${idPrefix}opens`}
label={t('editor.annotations.opens')}
value={form.opensViewId}
options={options}
blank={t('editor.field.choose')}
onChange={(opensViewId) => onChange({ opensViewId })}
error={missing('opens')}
readOnly={props.readOnly}
/>
)
}
/** Vertebral region, then findings zone: optional links of a point or a zone. */
function LinkSelects(props: FieldsProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const { doc, form, onChange, idPrefix = 'creation-', readOnly } = props
const zones = doc.finding_zones.map((z) => ({
value: z.id,
label: z.name[locale],
@@ -150,23 +243,28 @@ function LinkSelects({ doc, form, onChange }: FieldsProps) {
value: r.code,
label: r.name[locale],
}))
const blank = t(
props.editing ? 'editor.annotations.none' : 'editor.field.choose',
)
return (
<>
<OptionSelect
id="creation-zone"
label={t('editor.annotations.zone')}
value={form.zoneId}
options={zones}
blank
onChange={(zoneId) => onChange({ zoneId })}
/>
<OptionSelect
id="creation-region"
id={`${idPrefix}region`}
label={t('editor.annotations.region')}
value={form.regionCode}
options={regions}
blank
blank={blank}
onChange={(regionCode) => onChange({ regionCode })}
readOnly={readOnly}
/>
<OptionSelect
id={`${idPrefix}zone`}
label={t('editor.annotations.zone')}
value={form.zoneId}
options={zones}
blank={blank}
onChange={(zoneId) => onChange({ zoneId })}
readOnly={readOnly}
/>
</>
)
@@ -1,7 +1,7 @@
import type { ReactNode } from 'react'
import type { StripLead } from '@/editor/annotations/stripLead'
import EditorGlyph from '../EditorGlyph'
import ReviewBadge from './ReviewBadge'
import { ReviewSlot } from './ReviewBadge'
export type { StripLead }
@@ -61,8 +61,9 @@ function Lead({ lead }: { lead: StripLead }) {
<div
data-testid="edit-strip-lead"
// A fixed width: a longer or shorter lead (a mode, a tracing) never moves the
// notice beside it (A14).
className="flex w-2/5 min-w-0 shrink-0 items-start gap-2"
// notice beside it (A14). 256 px, near board 33 C: a point's slider and
// move, « Propriétés » and « Désélectionner » fit at 1 024 px (A6, U2 Task 6).
className="flex w-64 min-w-0 shrink-0 items-start gap-2"
>
<span className="mt-0.5 shrink-0 text-[var(--color-ink-muted)]">
<EditorGlyph name={lead.icon} size={16} />
@@ -77,11 +78,7 @@ function Lead({ lead }: { lead: StripLead }) {
>
{lead.title}
</span>
{lead.status && (
<span className="shrink-0">
<ReviewBadge status={lead.status} />
</span>
)}
{lead.status && <ReviewSlot status={lead.status} />}
</p>
<p
data-testid="edit-strip-detail"
@@ -18,15 +18,14 @@ import {
useModeFollowsSelection,
} from '@/editor/annotations/modeEnds'
import { handledPoints } from '@/editor/annotations/zoneEdit'
import { useAnnotationWork } from '@/editor/annotations/workStore'
import { isEditable } from '@/editor/annotations/geometryEdit'
import { useSelectionEscape } from '@/editor/annotations/deselect'
import { usePlacement } from '@/editor/annotations/usePlacement'
import { stripLeadOf } from '@/editor/annotations/stripLead'
import {
useGestureMessage,
type GestureMessage as ShownMessage,
} from '@/editor/annotations/useGestureMessage'
useLayerFollow,
type OpenDialog,
} from '@/editor/annotations/dialogOpening'
import { usePlacement } from '@/editor/annotations/usePlacement'
import { useGestureMessage } from '@/editor/annotations/useGestureMessage'
import {
initialUi,
uiReducer,
@@ -40,26 +39,18 @@ import {
useViewModel,
type ViewModel,
} from '@/editor/annotations/useViewModel'
import { targetOfKey, type AnnotationSection } from '@/editor/navigation'
import type { AnnotationSection } from '@/editor/navigation'
import { usePlaceVisible } from '@/lib/placeVisibility'
import type { EditorPlaceProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import AnnotationCanvas from './AnnotationCanvas'
import { annotationName } from './AnnotationList'
import {
SelectionPointCommands,
ToolSize,
useMoveFocusReturn,
} from './PointCommands'
import CreationPanel from './CreationPanel'
import EditStrip, { type StripNotice } from './EditStrip'
import TracingCommands from './TracingCommands'
import ZoneCommands, { moveTitleKey, useChosenVertex } from './ZoneCommands'
import GestureMessage from './GestureMessage'
import KeyboardAdd from './KeyboardAdd'
import OverviewPanel from './OverviewPanel'
import PropertiesPanel, { useGeometryIssues } from './PropertiesPanel'
import SceneStrip from './SceneStrip'
import ViewSwitcher from './ViewSwitcher'
interface Props {
@@ -67,10 +58,13 @@ interface Props {
navigate: EditorPlaceProps['navigate']
onOpenSection: (section: AnnotationSection, opener: HTMLElement) => void
focus: EditorPlaceProps['focus']
/** Opens the properties dialog (A1); the layer's id, which the selection follows. */
onOpen: OpenDialog
layerId: string | null
}
/** What both columns read: the tab's state, the view, its frame and its selection. */
interface Scene {
export interface Scene {
doc: AnatomicalSheetDocument
ui: UiState
dispatch: Dispatch<UiAction>
@@ -82,6 +76,7 @@ interface Scene {
setRoot: (root: RootAttributes | null) => void
navigate: EditorPlaceProps['navigate']
onOpenSection: Props['onOpenSection']
onOpen: OpenDialog
}
/**
@@ -106,25 +101,32 @@ function useViewFallback(
/** « Aller à » an annotation: the request, with what it needs of the drawing's state. */
function useSceneRequest(
{ doc, focus }: Props,
{ doc, focus, layerId }: Props,
ui: UiState,
viewId: string,
dispatch: Dispatch<UiAction>,
) {
useViewFallback(doc, ui.viewId, dispatch)
const show = (view: string, id: string) => {
if (view !== viewId) dispatch({ type: 'view', viewId: view })
dispatch({ type: 'select', id })
}
useAnnotationRequest(focus, doc, {
viewId,
selectedId: ui.selectedId,
busy: ui.pending ? 'creation' : ui.tracing ? 'tracing' : null,
show: (view, id) => {
dispatch({ type: 'view', viewId: view })
dispatch({ type: 'select', id })
},
show,
})
useLayerFollow(layerId, doc, {
viewId,
selectedId: ui.selectedId,
show,
clear: () => dispatch({ type: 'select', id: null }),
})
}
function useScene(props: Props): Scene {
const { doc, navigate, onOpenSection } = props
const { doc, navigate, onOpenSection, onOpen } = props
const [ui, dispatch] = useReducer(uiReducer, initialUi)
const [root, setRoot] = useState<RootAttributes | null>(null)
const viewId = ui.viewId ?? mainViewId(doc)
@@ -142,6 +144,7 @@ function useScene(props: Props): Scene {
setRoot,
navigate,
onOpenSection,
onOpen,
}
}
@@ -185,7 +188,7 @@ function useWork(scene: Scene) {
}
}
type Work = ReturnType<typeof useWork>
export type Work = ReturnType<typeof useWork>
export default function EditableAnnotations(props: Props) {
const scene = useScene(props)
@@ -206,7 +209,7 @@ export default function EditableAnnotations(props: Props) {
<SceneStrip scene={scene} work={work} />
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]">
<CanvasColumn scene={scene} work={work} onDeselect={byDrawing} />
<aside ref={asideRef}>
<aside ref={asideRef} data-annotation-aside="edit">
<SidePanel scene={scene} context={work.context} />
</aside>
</div>
@@ -311,6 +314,7 @@ function CanvasStage({
}}
onRoot={scene.setRoot}
onSelect={(id) => dispatch({ type: 'select', id })}
onOpen={(id) => scene.onOpen(id, 'drawing')}
onPlace={work.placement.onPlace}
onDrop={work.placement.onDrop}
onHandle={work.zone.onHandle}
@@ -329,7 +333,7 @@ function addAtCentre(
dispatch({ type: 'pending_new', pending: keyboardPending(kind, frame, size) })
}
/** The creation panel while an element is pending, else the selection's properties. */
/** The creation panel while an element is pending, else the overview (A3). */
function SidePanel({
scene,
context,
@@ -337,9 +341,7 @@ function SidePanel({
scene: Scene
context: CommitContext
}) {
const { doc, ui, dispatch, model, frame, selected } = scene
// During the move mode the panel offers no deselect: only the mode's own exits.
const moving = useAnnotationWork((s) => s.mode?.kind === 'move')
const { doc, ui, dispatch, frame } = scene
if (ui.pending) {
return (
<CreationPanel
@@ -353,32 +355,18 @@ function SidePanel({
/>
)
}
if (!selected) {
return (
<OverviewPanel
doc={doc}
viewId={scene.viewId}
readOnly={false}
filter={ui.filter}
onFilter={(term) => dispatch({ type: 'filter', term })}
onSelectView={(id) => dispatch({ type: 'view', viewId: id })}
onSelectAnnotation={(id) => dispatch({ type: 'select', id })}
onOpenSection={scene.onOpenSection}
/>
)
}
return (
<PropertiesPanel
key={selected.id}
annotation={selected}
<OverviewPanel
doc={doc}
viewId={scene.viewId}
readOnly={false}
geometryLocked={!model.measured}
dispatch={dispatch}
navigate={scene.navigate}
// « Tout afficher » leaves the selection: a started move asks first (R-12).
onShowAll={guarded(() => dispatch({ type: 'select', id: null }))}
busy={ui.tracing !== null || moving}
filter={ui.filter}
onFilter={(term) => dispatch({ type: 'filter', term })}
onSelectView={(id) => dispatch({ type: 'view', viewId: id })}
selectedId={scene.selected?.id ?? null}
onSelectAnnotation={(id) => dispatch({ type: 'select', id })}
onOpenAnnotation={(id) => scene.onOpen(id, 'drawing')}
onOpenSection={scene.onOpenSection}
/>
)
}
@@ -420,142 +408,3 @@ function overlayOf(
redrawing: ui.tracing?.target === 'replace',
}
}
/**
* The strip of the edit body: the lead of the scene (the move mode's own while it runs),
* its notice, the commands.
*/
function SceneStrip({ scene, work }: { scene: Scene; work: Work }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const notice = useStripNotice(scene, work)
const mode = useAnnotationWork((s) =>
s.mode?.kind === 'move' ? s.mode : null,
)
useMoveFocusReturn(mode !== null)
const { ui, selected, doc } = scene
const chosenVertex = useChosenVertex(selected?.id)
const lead = mode
? {
title: t(moveTitleKey(mode, work.target?.kind)),
detail: t('editor.annotations.move.hint'),
icon: 'move' as const,
}
: stripLeadOf(ui, selected, doc, { t, locale, chosenVertex })
const commandsKey = commandsKeyOf(
ui,
mode !== null,
work.target,
chosenVertex,
)
return (
<EditStrip
lead={lead}
notice={notice}
commands={<SceneCommands scene={scene} work={work} />}
commandsKey={commandsKey}
/>
)
}
/** One box per set of commands: a wider set never moves an existing box (A14). */
function commandsKeyOf(
ui: UiState,
moving: boolean,
target: Annotation | null,
chosen: number | null,
) {
if (ui.tracing) return 'tracing'
if (moving) return 'move'
if (target?.geometry?.type === 'polygon') return `zone-${chosen !== null}`
return target?.kind === 'point' ? 'point' : `tool-${ui.tool}`
}
/** A tracing's commands, a movable point's, or the Point tool's size (A5). */
function SceneCommands({ scene, work }: { scene: Scene; work: Work }) {
const { ui, doc, viewId, frame, dispatch } = scene
if (ui.tracing) {
return (
<TracingCommands
count={ui.tracing.points.length}
onClose={work.placement.closeTracing}
onPop={work.placement.popVertex}
onCancel={() => dispatch({ type: 'trace_cancel' })}
/>
)
}
if (work.target?.geometry?.type === 'polygon') {
const edit = work.edit
return (
<ZoneCommands annotation={work.target} edit={edit} dispatch={dispatch} />
)
}
// A link circle keeps its handle but has no size and no move mode (R-10; no label).
if (work.target?.kind === 'point') {
const props = { doc, viewId, frame, edit: work.edit }
return <SelectionPointCommands annotation={work.target} {...props} />
}
if (ui.tool !== 'point' || ui.pending || !frame) return null
const size = ui.size
return (
<ToolSize
doc={doc}
viewId={viewId}
frame={frame}
size={size}
dispatch={dispatch}
/>
)
}
/**
* The strip's middle, first match wins: a refusal (the strip's own, then a refused gesture
* whose line under the drawing may be cut short: its full text here, A6), the selection's
* geometry issues (the first, then « +n »), R-18's zoom line for a hidden « + », then why
* a tool cannot be used now.
*/
function useStripNotice(
scene: Scene,
work: Pick<Work, 'message' | 'insertsHidden'>,
): StripNotice | null {
const t = useT()
const issues = useGeometryIssues(scene.selected?.id ?? '')
const inMode = useAnnotationWork((s) => s.mode !== null)
const message: ShownMessage | null = work.message.message
const { ui, model, doc } = scene
if (ui.hint) return { tone: 'error', text: ui.hint }
if (message?.tone === 'error') {
return { tone: 'error', text: message.text, quiet: true }
}
if (scene.selected && issues.length > 0) {
return { tone: 'error', text: issues[0]!, more: issues.length - 1 }
}
// R-18: a « + » hidden for its short segment; never in a mode (move, redraw).
if (work.insertsHidden && !inMode && !ui.tracing) {
return { tone: 'info', text: t('editor.annotations.strip.zoom_hint') }
}
if (!model.measured) return unmeasuredNotice(scene, t)
if (doc.categories.length === 0) {
return { tone: 'info', text: t('editor.annotations.no_category') }
}
if (ui.tool === 'link' && model.children.length === 0) {
return { tone: 'info', text: t('editor.annotations.no_child_view') }
}
return null
}
/** Points to the views section, on the view whose drawing cannot be measured. */
function unmeasuredNotice(
scene: Scene,
t: (key: string) => string,
): StripNotice {
const target = targetOfKey({ kind: 'view', id: scene.viewId })
return {
tone: 'info',
text: t('editor.annotations.unmeasured.hint'),
link: {
label: t('editor.place.views'),
onClick: () => scene.navigate(target),
},
}
}
@@ -33,7 +33,11 @@ export interface OverviewPanelProps {
filter: string
onFilter: (term: string) => void
onSelectView: (viewId: string) => void
/** The selection, marked in the list (A3). */
selectedId: string | null
onSelectAnnotation: (annotationId: string) => void
/** Enter on the selected row: its properties dialog (A1). */
onOpenAnnotation: (annotationId: string) => void
onOpenSection: (section: AnnotationSection, opener: HTMLElement) => void
}
@@ -196,7 +200,7 @@ function CategoriesCard(props: OverviewPanelProps) {
function AnnotationsCard(props: OverviewPanelProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const { doc, viewId, filter: term, onFilter, onSelectAnnotation } = props
const { doc, viewId, filter: term, onFilter } = props
const prefix = props.idPrefix ?? ''
const total = useOverviewCounts(doc).annotationsByView.get(viewId) ?? 0
const groups = useMemo(
@@ -230,7 +234,9 @@ function AnnotationsCard(props: OverviewPanelProps) {
groups={groups}
views={doc.views}
idPrefix={prefix}
onSelect={onSelectAnnotation}
selectedId={props.selectedId}
onSelect={props.onSelectAnnotation}
onOpen={props.onOpenAnnotation}
/>
) : (
<p className="text-sm text-[var(--color-ink-muted)]">
@@ -1,294 +0,0 @@
import { useState, type Dispatch } from 'react'
import { flushSync } from 'react-dom'
import type {
AnatomicalSheetDocument,
Annotation,
Marking,
} from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import DeleteDialog from '@/components/editor/DeleteDialog'
import Button from '@/components/ui/Button'
import { useDeselect } from '@/editor/annotations/deselect'
import EditorGlyph from '@/components/editor/EditorGlyph'
import { isEditable } from '@/editor/annotations/geometryEdit'
import { beginRedraw } from '@/editor/annotations/redraw'
import type { UiAction } from '@/editor/annotations/uiState'
import { geometryErrorsById } from '@/editor/issues'
import { focusRow } from '@/editor/focusRequest'
import { targetOfKey } from '@/editor/navigation'
import type { EditorPlaceProps } from '@/editor/tabs'
import { useEditCommand } from '@/editor/useEditCommand'
import { useEditorStore } from '@/editor/state/editorStore'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import AnnotationFields from './AnnotationFields'
import { annotationName } from './AnnotationList'
import ReviewBadge from './ReviewBadge'
export interface PropertiesPanelProps {
annotation: Annotation
doc: AnatomicalSheetDocument
/** Not editable now: every field shows as text and no action is offered. */
readOnly: boolean
/** The view is not measured: geometry is shown as text only, the rest stays editable. */
geometryLocked: boolean
dispatch: Dispatch<UiAction>
navigate: EditorPlaceProps['navigate']
/** Clears the selection: the overview shows again. */
onShowAll: () => void
/** A tracing runs: the selection is not left from here. */
busy?: boolean
/** Put before every id, for a twin of the panel that lives beside another one. */
idPrefix?: string
}
/** What still names this annotation as invalid: never hidden, never shown as valid. */
export function useGeometryIssues(id: string): string[] {
const state = useEditorStore((s) => s.previewState)
const issues = state ? geometryErrorsById(state).get(id) : undefined
return [...new Set((issues ?? []).map((issue) => issue.message))]
}
export default function PropertiesPanel(props: PropertiesPanelProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const { annotation, doc, readOnly } = props
const edit = useEditCommand()
const name = annotationName(annotation, doc.views, locale)
return (
<section
aria-label={t('editor.annotations.properties')}
data-testid="annotation-properties"
className="space-y-4 rounded-xl border border-[var(--color-border)] p-4"
>
<ShowAll id={annotation.id} onShowAll={props.onShowAll} />
<header className="flex items-start justify-between gap-2">
<h3
tabIndex={-1}
data-properties-heading
className="outline-none text-base font-semibold"
>
{t(`editor.annotations.kind.${annotation.kind}`)}
</h3>
<ReviewBadge status={annotation.review_status} />
</header>
<AnnotationFields
annotation={annotation}
doc={doc}
readOnly={readOnly}
edit={edit}
idPrefix={props.idPrefix}
/>
<GeometrySection {...props} />
<StatusActions annotation={annotation} readOnly={readOnly} edit={edit} />
<div className="flex flex-wrap gap-2 border-t border-[var(--color-border)] pt-2.5">
<DeselectButton annotationId={annotation.id} {...props} />
<Deletion id={annotation.id} name={name} readOnly={readOnly} />
</div>
</section>
)
}
/** Back to the overview, focus on the row of the annotation that was open. */
function ShowAll({ id, onShowAll }: { id: string; onShowAll: () => void }) {
const t = useT()
return (
<Button
type="button"
variant="secondary"
size="sm"
onClick={() => {
flushSync(onShowAll)
focusRow({ kind: 'annotation', id })
}}
>
{t('editor.annotations.show_all')}
</Button>
)
}
/** Leaves the annotation open: the overview shows again, the focus on its row. */
function DeselectButton({
annotationId,
onShowAll,
busy,
}: { annotationId: string } & Pick<
PropertiesPanelProps,
'onShowAll' | 'busy'
>) {
const t = useT()
const { byButton } = useDeselect(annotationId, onShowAll)
if (busy) return null
return (
<Button
type="button"
variant="secondary"
size="sm"
className="min-h-11 gap-1.5 xl:min-h-9"
// Keeps the focus in a field being typed, so its blur commit runs in byButton.
onMouseDown={(event) => event.preventDefault()}
onClick={byButton}
>
<EditorGlyph name="deselect" size={16} />
{t('editor.annotations.deselect')}
</Button>
)
}
/**
* The geometry's state: no coordinate field (A8, U2 Task 5: circles and polygons are
* edited on the drawing); a path or a missing geometry says so and offers the redraw.
*/
function GeometrySection(props: PropertiesPanelProps) {
const t = useT()
const { annotation, readOnly, geometryLocked } = props
const locked = readOnly || geometryLocked
const { geometry } = annotation
const editable = isEditable(geometry)
return (
<div className="space-y-2">
{geometryLocked && !readOnly && (
<UnmeasuredHint navigate={props.navigate} viewId={annotation.view_id} />
)}
{!editable && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t(
geometry === null
? 'editor.annotations.no_geometry'
: 'editor.annotations.path',
)}
</p>
)}
{!locked && !editable && (
<TraceReplacement id={annotation.id} dispatch={props.dispatch} />
)}
<GeometryIssues id={annotation.id} />
</div>
)
}
function TraceReplacement({
id,
dispatch,
}: {
id: string
dispatch: Dispatch<UiAction>
}) {
const t = useT()
return (
<Button
type="button"
variant="secondary"
size="sm"
// The same redraw as « Redessiner »: the drawing guard asks before it is lost.
onClick={() => beginRedraw(id, dispatch)}
>
{t('editor.annotations.replace_polygon')}
</Button>
)
}
function GeometryIssues({ id }: { id: string }) {
const issues = useGeometryIssues(id)
if (issues.length === 0) return null
return (
<ul
role="alert"
data-testid="annotation-geometry-issues"
className="list-disc pl-5 text-sm text-[var(--color-danger-strong)]"
>
{issues.map((issue) => (
<li key={issue}>{issue}</li>
))}
</ul>
)
}
/** Points to the views section, on the view whose drawing cannot be measured. */
export function UnmeasuredHint({
navigate,
viewId,
}: Pick<PropertiesPanelProps, 'navigate'> & { viewId: string }) {
const t = useT()
return (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.annotations.unmeasured.hint')}{' '}
<button
type="button"
className="underline"
onClick={() => navigate(targetOfKey({ kind: 'view', id: viewId }))}
>
{t('editor.place.views')}
</button>
</p>
)
}
function StatusActions({
annotation,
readOnly,
edit,
}: {
annotation: Annotation
readOnly: boolean
edit: ReturnType<typeof useEditCommand>
}) {
const t = useT()
const mark = (status: Marking) =>
edit.run('status', {
op: 'set_status',
key: { kind: 'annotation', id: annotation.id },
status,
})
const reviewed = annotation.review_status === 'reviewed'
return (
<div className="space-y-1">
<ActionButton
readOnly={readOnly}
variant="secondary"
size="sm"
onClick={() => mark(reviewed ? 'to_confirm' : 'reviewed')}
>
{t(
reviewed
? 'editor.annotations.to_confirm'
: 'editor.annotations.mark_reviewed',
)}
</ActionButton>
{edit.fieldError('status') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('status')}
</p>
)}
</div>
)
}
function Deletion({
id,
name,
readOnly,
}: {
id: string
name: string
readOnly: boolean
}) {
const t = useT()
const [open, setOpen] = useState(false)
return (
<>
<ActionButton
readOnly={readOnly}
variant="danger"
size="sm"
onClick={() => setOpen(true)}
>
{t('editor.action.delete')}
</ActionButton>
<DeleteDialog
target={open ? { key: { kind: 'annotation', id }, label: name } : null}
onClose={() => setOpen(false)}
/>
</>
)
}
@@ -16,3 +16,21 @@ export default function ReviewBadge({ status }: { status: ReviewStatus }) {
</Badge>
)
}
/**
* The badge in a slot as wide as the widest status of the locale, left-aligned: a status
* change (an edit turns « Hérité, non relu » into « À confirmer ») never moves the badge
* nor what sits beside it (A14: the overview stays shown during a selection, U2 Task 6).
*/
export function ReviewSlot({ status }: { status: ReviewStatus }) {
return (
<span className="inline-grid shrink-0 justify-items-start">
<span className="col-start-1 row-start-1">
<ReviewBadge status={status} />
</span>
<span aria-hidden="true" className="invisible col-start-1 row-start-1">
<ReviewBadge status="inherited" />
</span>
</span>
)
}
@@ -0,0 +1,217 @@
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 { 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'
import { targetOfKey } from '@/editor/navigation'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import type { Scene, Work } from './EditableAnnotations'
import EditStrip, { type StripNotice } from './EditStrip'
import {
SelectionPointCommands,
ToolSize,
useMoveFocusReturn,
} from './PointCommands'
import SelectionCommands from './SelectionCommands'
import TracingCommands from './TracingCommands'
import ZoneCommands, { moveTitleKey, useChosenVertex } from './ZoneCommands'
/**
* The strip of the edit body: the lead of the scene (the move mode's own while it runs),
* its notice, the commands.
*/
export default function SceneStrip({
scene,
work,
}: {
scene: Scene
work: Work
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const notice = useStripNotice(scene, work)
const mode = useAnnotationWork((s) =>
s.mode?.kind === 'move' ? s.mode : null,
)
useMoveFocusReturn(mode !== null)
const { ui, selected, doc } = scene
const chosenVertex = useChosenVertex(selected?.id)
const lead = mode
? {
title: t(moveTitleKey(mode, work.target?.kind)),
detail: t('editor.annotations.move.hint'),
icon: 'move' as const,
}
: stripLeadOf(ui, selected, doc, { t, locale, chosenVertex })
const commandsKey = commandsKeyOf(
ui,
mode !== null,
work.target,
chosenVertex,
)
return (
<EditStrip
lead={lead}
notice={notice}
commands={
<SceneCommands scene={scene} work={work} moving={mode !== null} />
}
commandsKey={commandsKey}
/>
)
}
/** One box per set of commands: a wider set never moves an existing box (A14). */
function commandsKeyOf(
ui: UiState,
moving: boolean,
target: Annotation | null,
chosen: number | null,
) {
if (ui.tracing) return 'tracing'
if (moving) return 'move'
if (target?.geometry?.type === 'polygon') return `zone-${chosen !== null}`
if (target?.kind === 'point') return 'point'
return ui.selectedId !== null ? `selected-${target?.kind}` : `tool-${ui.tool}`
}
/** The selection's own commands: a polygon's, a movable point's (R-10: a link circle none). */
function ShapeCommands({ scene, work }: { scene: Scene; work: Work }) {
const t = useT()
const { doc, viewId, frame, dispatch, selected, model } = scene
if (work.target?.geometry?.type === 'polygon') {
const edit = work.edit
return (
<ZoneCommands annotation={work.target} edit={edit} dispatch={dispatch} />
)
}
if (work.target?.kind === 'point') {
const props = { doc, viewId, frame, edit: work.edit }
return <SelectionPointCommands annotation={work.target} {...props} />
}
// A path or a missing geometry: the same redraw as « Redessiner » (T16, BDR-101).
const traced = selected && !isEditable(selected.geometry)
if (!traced || !model.measured) return null
return (
<Button
type="button"
size="sm"
variant="secondary"
className="min-h-11 xl:min-h-9"
onClick={() => beginRedraw(selected.id, dispatch)}
>
{t('editor.annotations.replace_polygon')}
</Button>
)
}
/**
* A tracing's commands; a selection's own, then « Propriétés » and « Désélectionner »;
* or the Point tool's size (A5).
*/
function SceneCommands({
scene,
work,
moving,
}: {
scene: Scene
work: Work
moving: boolean
}) {
const { ui, doc, viewId, frame, dispatch, selected } = scene
const { byButton } = useDeselect(selected?.id ?? null, () =>
dispatch({ type: 'select', id: null }),
)
if (ui.tracing) {
return (
<TracingCommands
count={ui.tracing.points.length}
onClose={work.placement.closeTracing}
onPop={work.placement.popVertex}
onCancel={() => dispatch({ type: 'trace_cancel' })}
/>
)
}
if (selected) {
return (
<>
<ShapeCommands scene={scene} work={work} />
{/* During the move mode only the mode's own exits (its bar). */}
{!moving && (
<SelectionCommands
onProperties={() => scene.onOpen(selected.id, 'button')}
onDeselect={byButton}
/>
)}
</>
)
}
if (ui.tool !== 'point' || ui.pending || !frame) return null
return (
<ToolSize
doc={doc}
viewId={viewId}
frame={frame}
size={ui.size}
dispatch={dispatch}
/>
)
}
/**
* The strip's middle, first match wins: a refusal (the strip's own, then a refused gesture
* whose line under the drawing may be cut short: its full text here, A6), the selection's
* geometry issues (the first, then « +n »), R-18's zoom line for a hidden « + », then why
* a tool cannot be used now.
*/
function useStripNotice(
scene: Scene,
work: Pick<Work, 'message' | 'insertsHidden'>,
): StripNotice | null {
const t = useT()
const issues = useGeometryIssues(scene.selected?.id ?? '')
const inMode = useAnnotationWork((s) => s.mode !== null)
const message: ShownMessage | null = work.message.message
const { ui, model, doc } = scene
if (ui.hint) return { tone: 'error', text: ui.hint }
if (message?.tone === 'error') {
return { tone: 'error', text: message.text, quiet: true }
}
if (scene.selected && issues.length > 0) {
return { tone: 'error', text: issues[0]!, more: issues.length - 1 }
}
// R-18: a « + » hidden for its short segment; never in a mode (move, redraw).
if (work.insertsHidden && !inMode && !ui.tracing) {
return { tone: 'info', text: t('editor.annotations.strip.zoom_hint') }
}
if (!model.measured) return unmeasuredNotice(scene, t)
if (doc.categories.length === 0) {
return { tone: 'info', text: t('editor.annotations.no_category') }
}
if (ui.tool === 'link' && model.children.length === 0) {
return { tone: 'info', text: t('editor.annotations.no_child_view') }
}
return null
}
/** Points to the views section, on the view whose drawing cannot be measured. */
function unmeasuredNotice(
scene: Scene,
t: (key: string) => string,
): StripNotice {
const target = targetOfKey({ kind: 'view', id: scene.viewId })
return {
tone: 'info',
text: t('editor.annotations.unmeasured.hint'),
link: {
label: t('editor.place.views'),
onClick: () => scene.navigate(target),
},
}
}
@@ -0,0 +1,47 @@
import Button from '@/components/ui/Button'
import { useT } from '@/i18n/useT'
import EditorGlyph from '../EditorGlyph'
const COMMAND = 'min-h-11 gap-1.5 xl:min-h-9'
/**
* The strip's commands of any selection, after its own (boards 33 C to E): « Propriétés »
* opens the dialog (A1), « Désélectionner » leaves the selection.
*/
export default function SelectionCommands({
onProperties,
onDeselect,
}: {
onProperties: () => void
onDeselect: () => void
}) {
const t = useT()
return (
<>
<Button
// The focus comes back here when the dialog it opened closes (board 32).
data-properties-button=""
type="button"
size="sm"
variant="secondary"
className={COMMAND}
onClick={onProperties}
>
<EditorGlyph name="properties" size={16} />
{t('editor.annotations.properties')}
</Button>
<Button
type="button"
size="sm"
variant="secondary"
className={COMMAND}
// Keeps the focus on a handle being keyed, so its series commits in the deselect.
onMouseDown={(event) => event.preventDefault()}
onClick={onDeselect}
>
<EditorGlyph name="deselect" size={16} />
{t('editor.annotations.deselect')}
</Button>
</>
)
}
@@ -16,6 +16,7 @@ export default function DraftField({
readOnly,
hint,
error,
placeholder,
}: {
id: string
label: string
@@ -28,6 +29,8 @@ export default function DraftField({
readOnly?: boolean
hint?: string
error?: string
/** Shown while the field is blank (« Couleur »: the category's). */
placeholder?: string
}) {
const shared = {
id,
@@ -35,6 +38,7 @@ export default function DraftField({
onChange: (e: { target: { value: string } }) => onChange(e.target.value),
onBlur,
readOnly,
placeholder,
'aria-readonly': readOnly || undefined,
'aria-invalid': Boolean(error),
'aria-describedby': fieldDescribedBy(id, hint, error),
@@ -1,24 +1,38 @@
import { useEffect, useState } from 'react'
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import type {
AnatomicalSheetDocument,
Annotation,
} from '@faunosteo/core-wasm/types'
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 EditableAnnotations from '@/components/editor/annotations/EditableAnnotations'
import EditStrip from '@/components/editor/annotations/EditStrip'
import OverviewPanel from '@/components/editor/annotations/OverviewPanel'
import PropertiesPanel from '@/components/editor/annotations/PropertiesPanel'
import AnnotationSection from '@/components/editor/annotations/sections/AnnotationSection'
import SelectionCommands from '@/components/editor/annotations/SelectionCommands'
import ViewSwitcher from '@/components/editor/annotations/ViewSwitcher'
import SelectionTag from '@/components/editor/annotations/SelectionTag'
import EditOnly from '@/components/editor/EditOnly'
import KeptPlace from '@/components/editor/KeptPlace'
import Button from '@/components/ui/Button'
import { ownedBy } from '@/editor/focusRequest'
import { useSelectionEscape } from '@/editor/annotations/deselect'
import { useDeselect, useSelectionEscape } from '@/editor/annotations/deselect'
import {
useDialogOpening,
useLayerFollow,
type OpenDialog,
} from '@/editor/annotations/dialogOpening'
import { useAnnotationRequest } from '@/editor/annotations/focusTarget'
import { selectionLead } from '@/editor/annotations/stripLead'
import { mainViewId, useViewModel } from '@/editor/annotations/useViewModel'
import type { AnnotationSection as SectionId } from '@/editor/navigation'
import { usePlaceVisible } from '@/lib/placeVisibility'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useEditorStore } from '@/editor/state/editorStore'
import type { EditorPlaceProps } from '@/editor/tabs'
import { useEditWidth } from '@/editor/useViewport'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
@@ -53,13 +67,18 @@ function SectionPlace({
)
}
/** The drawing workspace: edit or read-only body of the same view. */
/**
* 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).
*/
function DrawingPlace(props: AnnotationsTabProps) {
const t = useT()
const doc = useSheetDocument()
const preview = useEditorStore((s) => s.preview)
const { readOnly, navigate, onOpenSection, focus } = props
const body = { navigate, onOpenSection }
const { readOnly, navigate, onOpenSection, focus, annotationLayer } = props
const dialog = useDialogOpening(annotationLayer, readOnly)
const layerId = annotationLayer?.view?.id ?? null
const body = { navigate, onOpenSection, onOpen: dialog.open, layerId }
const ready = doc && preview
return (
<section
@@ -79,6 +98,15 @@ function DrawingPlace(props: AnnotationsTabProps) {
/>
</EditOnly>
)}
{doc && annotationLayer && (
<AnnotationDialog
layer={annotationLayer}
doc={doc}
readOnly={readOnly}
anchor={dialog.anchor}
returnFocus={dialog.returnFocus}
/>
)}
</section>
)
}
@@ -92,9 +120,9 @@ function SectionBody(props: AnnotationsTabProps & { id: SectionId }) {
}
/**
* Annotations: the drawing workspace (canvas with its tools, the overview or the
* properties and creation panels), 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.
* 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
* 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.
*/
export default function AnnotationsTab(props: AnnotationsTabProps) {
@@ -129,102 +157,196 @@ function useViewFallback(
}, [doc, shown, setViewId, setSelectedId])
}
/**
* The read-only body shares the tab with the kept (hidden) edit body: whatever both
* render takes this prefix here, so no id repeats in the page.
*/
const READ_ONLY_IDS = 'ro-'
function ReadOnlyAnnotations({
doc,
navigate,
onOpenSection,
focus,
}: {
/** What both read-only layouts get of the twin. */
interface TwinProps {
doc: AnatomicalSheetDocument
navigate: EditorPlaceProps['navigate']
onOpenSection: AnnotationsTabProps['onOpenSection']
focus: EditorPlaceProps['focus']
}) {
const locale = useLocaleStore((s) => s.locale)
const preview = useEditorStore((s) => s.preview)
const handleVersion = useEditorStore((s) => s.handleVersion)
onOpen: OpenDialog
layerId: string | null
}
/** The twin's selection, view and filter, kept in step with requests and the layer. */
function useTwinState({ doc, focus, layerId }: TwinProps) {
const [viewId, setViewId] = useState(mainViewId(doc))
const [selectedId, setSelectedId] = useState<string | null>(null)
const [filter, setFilter] = useState('')
useViewFallback(doc, viewId, setViewId, setSelectedId)
useAnnotationRequest(focus, doc, {
viewId,
selectedId,
busy: null,
show: (view, id) => {
setViewId(view)
setSelectedId(id)
},
})
const model = useViewModel(doc, viewId)
const view = doc.views.find((v) => v.id === viewId)
const selected = model.annotations.find((a) => a.id === selectedId)
const visible = usePlaceVisible()
const { asideRef, byDrawing } = useSelectionEscape(
selected?.id ?? null,
() => setSelectedId(null),
visible && selected !== undefined,
)
const show = (view: string, id: string) => {
setViewId(view)
setSelectedId(id)
}
useAnnotationRequest(focus, doc, { viewId, selectedId, busy: null, show })
const clear = () => setSelectedId(null)
useLayerFollow(layerId, doc, { viewId, selectedId, show, clear })
// A view of its own has its own list: the filter and the selection start over.
const showView = (id: string) => {
setViewId(id)
setSelectedId(null)
setFilter('')
}
return { viewId, selectedId, setSelectedId, filter, setFilter, showView }
}
/**
* The read-only strip at 1 024 px and wider (R-16, board 33 E): the selection with
* « fiche en lecture seule », then « Propriétés » and « Désélectionner »; nothing else.
*/
function ReadOnlyStrip({
selected,
doc,
onProperties,
onDeselect,
}: {
selected: Annotation | undefined
doc: AnatomicalSheetDocument
onProperties: () => void
onDeselect: () => void
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const lead = selected
? selectionLead(selected, doc.views, { t, locale, readOnly: true })
: {
title: t('editor.annotations.strip.select'),
detail: '',
icon: 'select' as const,
}
return (
<EditStrip
lead={lead}
notice={null}
commandsKey={selected ? 'selected' : 'none'}
commands={
selected && (
<SelectionCommands
onProperties={onProperties}
onDeselect={onDeselect}
/>
)
}
/>
)
}
/** Below 1 024 px (boards 14 and 16): the selection read inline in the stacked column. */
function InlineRead({
annotation,
doc,
onDeselect,
}: {
annotation: Annotation
doc: AnatomicalSheetDocument
onDeselect: () => void
}) {
const t = useT()
return (
<section
aria-label={t('editor.annotations.properties')}
className="space-y-3 rounded-xl border border-[var(--color-border)] p-4"
>
<Button
type="button"
variant="secondary"
size="sm"
className="min-h-11"
onClick={onDeselect}
>
{t('editor.annotations.deselect')}
</Button>
<AnnotationReadBody annotation={annotation} doc={doc} />
</section>
)
}
/**
* The read-only body shares the tab with the kept (hidden) edit body: whatever both
* render takes this prefix here, so no id repeats in the page.
*/
const READ_ONLY_IDS = 'ro-'
/**
* The read-only body: the same view browsable, nothing editable. At 1 024 px and wider
* the strip and the properties dialog as in the edit body, read-only (R-16); below, the
* read body inline.
*/
function ReadOnlyAnnotations(props: TwinProps) {
const { doc, onOpen } = props
const locale = useLocaleStore((s) => s.locale)
const preview = useEditorStore((s) => s.preview)
const handleVersion = useEditorStore((s) => s.handleVersion)
const wide = useEditWidth()
const twin = useTwinState(props)
const { viewId, selectedId, setSelectedId } = twin
const model = useViewModel(doc, viewId)
const view = doc.views.find((v) => v.id === viewId)
const selected = model.annotations.find((a) => a.id === selectedId)
const visible = usePlaceVisible()
const clear = () => setSelectedId(null)
const active = visible && selected !== undefined
const { asideRef, byDrawing } = useSelectionEscape(
selected?.id ?? null,
clear,
active,
)
const { byButton } = useDeselect(selected?.id ?? null, clear)
// A1: a second click (or the second of a double click) on the selection opens it.
const pick = (id: string) =>
wide && id === selectedId ? onOpen(id, 'drawing') : setSelectedId(id)
if (!preview || !view) return null
return (
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]">
<div className="min-w-0 space-y-3">
<ViewSwitcher views={doc.views} current={viewId} onSelect={showView} />
{selected && (
<SelectionTag
kind={selected.kind}
name={annotationName(selected, doc.views, locale)}
/>
)}
<CatalogueCanvas
key={handleVersion}
preview={preview}
viewId={viewId}
viewName={view.name[locale]}
selectedId={selectedId}
onAnnotation={setSelectedId}
onEmpty={byDrawing}
<div className="space-y-3">
{wide && (
<ReadOnlyStrip
selected={selected}
doc={doc}
onProperties={() => selected && onOpen(selected.id, 'button')}
onDeselect={byButton}
/>
</div>
<aside ref={asideRef}>
{selected ? (
<PropertiesPanel
key={selected.id}
annotation={selected}
doc={doc}
idPrefix={READ_ONLY_IDS}
readOnly
geometryLocked={!model.measured}
dispatch={() => undefined}
navigate={navigate}
onShowAll={() => setSelectedId(null)}
)}
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]">
<div className="min-w-0 space-y-3">
<ViewSwitcher
views={doc.views}
current={viewId}
onSelect={twin.showView}
/>
) : (
<OverviewPanel
doc={doc}
{selected && (
<SelectionTag
kind={selected.kind}
name={annotationName(selected, doc.views, locale)}
/>
)}
<CatalogueCanvas
key={handleVersion}
preview={preview}
viewId={viewId}
idPrefix={READ_ONLY_IDS}
readOnly
filter={filter}
onFilter={setFilter}
onSelectView={showView}
onSelectAnnotation={setSelectedId}
onOpenSection={onOpenSection}
viewName={view.name[locale]}
selectedId={selectedId}
onAnnotation={pick}
onEmpty={byDrawing}
/>
)}
</aside>
</div>
<aside ref={asideRef} data-annotation-aside="read">
{!wide && selected ? (
<InlineRead annotation={selected} doc={doc} onDeselect={byButton} />
) : (
<OverviewPanel
doc={doc}
viewId={viewId}
idPrefix={READ_ONLY_IDS}
readOnly
filter={twin.filter}
onFilter={twin.setFilter}
onSelectView={twin.showView}
selectedId={selectedId}
onSelectAnnotation={setSelectedId}
onOpenAnnotation={(id) => onOpen(id, 'drawing')}
onOpenSection={props.onOpenSection}
/>
)}
</aside>
</div>
</div>
)
}
+28 -4
View File
@@ -1,6 +1,7 @@
import { useId, type ReactNode } from 'react'
import { useId, type ReactNode, type RefObject } from 'react'
import { AnimatePresence, motion, useReducedMotion } from 'motion/react'
import ModalDialog, { type ModalDialogProps } from './ModalDialog'
import { useAnchoredPlace, type AnchoredPlace } from './anchoredPlace'
import { useT } from '@/i18n/useT'
export interface DialogProps {
@@ -21,6 +22,11 @@ export interface DialogProps {
description?: ReactNode
children: ReactNode
size?: 'sm' | 'md' | 'lg' | 'xl'
/**
* A box to sit over (A2: the editor's right column): the panel takes its left and width,
* under a lighter veil that ignores clicks (R-6). Without a box, the panel is centred.
*/
anchor?: RefObject<HTMLElement | null>
}
const SIZE: Record<NonNullable<DialogProps['size']>, string> = {
@@ -48,6 +54,19 @@ const CLOSE =
'text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)] ' +
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
/** The veil over a column (A2): 22 % of the ink, lighter than the centred dialogs'. */
const VEIL_LIGHT = 'bg-[color-mix(in_srgb,var(--color-ink)_22%,transparent)]'
const PANEL =
'overflow-y-auto overscroll-contain rounded-2xl bg-[var(--color-surface)] shadow-xl'
/** Centred: the size's width, 85 % of the height; anchored: the place says it all. */
function panelClass(place: AnchoredPlace | null, size: string): string {
if (place) return `absolute ${PANEL}`
const width = SIZE[size as keyof typeof SIZE]
return `relative w-full ${width} max-h-[85vh] ${PANEL}`
}
export default function Dialog({ open, ...surface }: DialogProps) {
return (
<AnimatePresence>{open && <DialogSurface {...surface} />}</AnimatePresence>
@@ -63,12 +82,14 @@ function DialogSurface({
description,
children,
size = 'md',
anchor,
}: Omit<DialogProps, 'open'>) {
const t = useT()
const reduced = useReducedMotion()
const scale = reduced ? 1 : 0.96
const ownTitleId = useId()
const descriptionId = useId()
const place = useAnchoredPlace(anchor)
return (
<ModalDialog
onClose={onClose}
@@ -80,19 +101,22 @@ function DialogSurface({
>
<motion.div
data-testid="dialog-backdrop"
className="absolute inset-0 bg-black/40"
className={`absolute inset-0 ${place ? VEIL_LIGHT : 'bg-black/40'}`}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: reduced ? 0 : 0.15 }}
onClick={onClose}
// R-6: over a column, the tap that opened the dialog never closes it.
onClick={place ? undefined : onClose}
/>
<motion.div
data-testid="dialog-panel"
initial={{ opacity: 0, scale }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale }}
transition={{ duration: reduced ? 0 : 0.18 }}
className={`relative w-full ${SIZE[size]} max-h-[85vh] overflow-y-auto overscroll-contain rounded-2xl bg-[var(--color-surface)] shadow-xl`}
className={panelClass(place, size)}
style={place ?? undefined}
>
<header className={HEADER}>
<h2
@@ -0,0 +1,59 @@
import { useLayoutEffect, useState, type RefObject } from 'react'
/** The panel's place over its anchor, in px of the viewport (the dialog fills it). */
export interface AnchoredPlace {
left: number
width: number
top: number
maxHeight?: number
height?: number
}
/** The space a dialog keeps from the viewport's edges. */
const EDGE = 12
/** Under this, the column's height is no form's: the visible viewport takes over. */
const MIN_SPACE = 320
/**
* The panel at the anchor's left and width, from its top (never above 12 px), down to
* 12 px above the visible bottom. A tablet keyboard that leaves less than 320 px moves it
* to the top of the visual viewport, its height then. No anchor box: null (centred).
*/
export function placeOver(anchor: HTMLElement | null): AnchoredPlace | null {
if (!anchor) return null
const box = anchor.getBoundingClientRect()
const viewport = window.visualViewport
const bottom = viewport
? viewport.offsetTop + viewport.height
: window.innerHeight
const top = Math.max(EDGE, box.top)
const side = { left: box.left, width: box.width }
if (bottom - top - EDGE >= MIN_SPACE) {
return { ...side, top, maxHeight: window.innerHeight - top - EDGE }
}
const shown = viewport?.height ?? window.innerHeight
const offset = viewport?.offsetTop ?? 0
return { ...side, top: offset + EDGE, height: shown - 2 * EDGE }
}
/** The anchored place, measured at open and on every resize of the window or the keyboard. */
export function useAnchoredPlace(
anchor: RefObject<HTMLElement | null> | undefined,
): AnchoredPlace | null {
const [place, setPlace] = useState<AnchoredPlace | null>(() =>
anchor ? placeOver(anchor.current) : null,
)
useLayoutEffect(() => {
if (!anchor) return
const measure = () => setPlace(placeOver(anchor.current))
measure()
const viewport = window.visualViewport
window.addEventListener('resize', measure)
viewport?.addEventListener('resize', measure)
return () => {
window.removeEventListener('resize', measure)
viewport?.removeEventListener('resize', measure)
}
}, [anchor])
return place
}
@@ -0,0 +1,100 @@
import { useEffect, useMemo, useRef, type RefObject } from 'react'
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import { visibleElement } from '../focusRequest'
import { MIN_EDIT_WIDTH } from '../mode'
import type { AnnotationLayer } from '../tabs'
import { CANVAS_BOX } from '../useEditorNavigation'
import { guardDrawing } from './drawingGuard'
/** What opened the properties dialog: the strip's « Propriétés », or the drawing or the list. */
export type OpenedBy = 'button' | 'drawing'
/** Opens the properties dialog of `id` (A1). */
export type OpenDialog = (id: string, by: OpenedBy) => void
/**
* The column the dialog sits over (A2), resolved when measured: the right column of the
* body shown (`data-annotation-aside`: `edit`, or `read` while read-only) at 1 024 px and
* wider, none below (stacked layout: the dialog is centred, R-14).
*/
function columnAnchor(readOnly: boolean): RefObject<HTMLElement | null> {
const column = `[data-annotation-aside="${readOnly ? 'read' : 'edit'}"]`
return {
get current() {
if (window.innerWidth < MIN_EDIT_WIDTH) return null
return visibleElement(column)
},
}
}
/** The visible row of the annotation `id` in the overview. */
function rowOf(id: string): HTMLElement | null {
const wanted = JSON.stringify({ kind: 'annotation', id })
return visibleElement('[data-focus-key]', (row) => {
return row.dataset.focusKey === wanted
})
}
/**
* The dialog's way in, out and place (board 32): an opening first commits a key series and
* asks started drawing work (R-12); once closed, the focus goes back to « Propriétés »
* when it opened it, else to the annotation's row, or the drawing when a filter hides it.
* The anchor is measured again when the editor turns read-only or back.
*/
export function useDialogOpening(
layer: AnnotationLayer | undefined,
readOnly: boolean,
) {
const opened = useRef<{ id: string; by: OpenedBy } | null>(null)
const latest = useRef(layer)
latest.current = layer
const open: OpenDialog = (id, by) => {
const go = () => {
opened.current = { id, by }
latest.current?.open(id)
}
if (guardDrawing(go)) go()
}
const returnFocus = () => {
const last = opened.current
if (!last) return null
const button =
last.by === 'button' && visibleElement('[data-properties-button]')
return button || rowOf(last.id) || visibleElement(CANVAS_BOX)
}
// A new object per flip: the dialog measures its place again (no resize fires).
const anchor = useMemo(() => columnAnchor(readOnly), [readOnly])
return { open, returnFocus, anchor }
}
/** What a body lets the layer do with its selection. */
export interface LayerSelection {
viewId: string
selectedId: string | null
show: (viewId: string, annotationId: string) => void
clear: () => void
}
/**
* The selection follows the layer (a Back, a Forward, a reload): its annotation is shown
* on its view and selected; a layer whose annotation is gone leaves nothing selected.
*/
export function useLayerFollow(
layerId: string | null,
doc: AnatomicalSheetDocument,
body: LayerSelection,
): void {
const latest = useRef(body)
latest.current = body
const { viewId, selectedId } = body
useEffect(() => {
if (layerId === null) return
const found = doc.annotations.find((a) => a.id === layerId)
if (!found) {
if (selectedId !== null) latest.current.clear()
return
}
if (found.id === selectedId && found.view_id === viewId) return
latest.current.show(found.view_id, found.id)
}, [layerId, doc, viewId, selectedId])
}
@@ -11,6 +11,7 @@ import {
type FocusRequest,
} from '../focusRequest'
import { useT } from '@/i18n/useT'
import { focusRowOrDrawing } from './deselect'
/** What « Aller à … » seeds on the drawing: the view and the annotation a key names. */
export function annotationFocus(
@@ -60,7 +61,7 @@ function showAnnotation(
const same =
drawing.selectedId === found.annotationId && drawing.viewId === found.viewId
if (same) {
focusFirst('[data-properties-heading]')
focusRowOrDrawing(found.annotationId)
return
}
awaiting.current = found.annotationId
@@ -68,8 +69,8 @@ function showAnnotation(
}
/**
* « Aller à » an annotation on the drawing: shows its view, selects it, then focuses the
* properties heading once it has rendered. While a creation or a tracing is in progress
* « Aller à » an annotation on the drawing (R-5): shows its view, selects it, then focuses
* its row (the drawing when a filter hides it) once it has rendered; no dialog opens (A1). While a creation or a tracing is in progress
* the request is kept: nothing is dispatched (it would drop the work), the panel or the
* strip's tracing commands take the focus and the live region says why.
*/
@@ -98,7 +99,8 @@ export function useAnnotationRequest(
if (awaiting.current === null || drawing.selectedId !== awaiting.current) {
return
}
const id = awaiting.current
awaiting.current = null
focusFirst('[data-properties-heading]')
focusRowOrDrawing(id)
})
}
@@ -0,0 +1,28 @@
import type { CreationForm, NewKind } from './creation'
/** A field the creation dialog and the edit form require (R-3). */
export type MissingField =
| 'name_fr'
| 'name_en'
| 'category'
| 'laterality'
| 'opens'
const blank = (v: string) => v.trim() === ''
/** Board 33 adjustment: only what is really missing, in the form's order. */
export function missingFields(
kind: NewKind,
form: CreationForm,
): MissingField[] {
const missing: MissingField[] = []
const bothOrNone =
kind === 'detail_trigger' && blank(form.fr) && blank(form.en)
if (!bothOrNone && blank(form.fr)) missing.push('name_fr')
if (!bothOrNone && blank(form.en)) missing.push('name_en')
if (form.categoryId === '') missing.push('category')
if (form.laterality === '') missing.push('laterality')
if (kind === 'detail_trigger' && form.opensViewId === '')
missing.push('opens')
return missing
}
@@ -0,0 +1,9 @@
import { geometryErrorsById } from '../issues'
import { useEditorStore } from '../state/editorStore'
/** What still names this annotation as invalid: never hidden, never shown as valid. */
export function useGeometryIssues(id: string): string[] {
const state = useEditorStore((s) => s.previewState)
const issues = state ? geometryErrorsById(state).get(id) : undefined
return [...new Set((issues ?? []).map((issue) => issue.message))]
}
@@ -32,6 +32,8 @@ export interface PressInput extends BlockDragInput {
selectedId: string | null
viewport: RefObject<HTMLDivElement | null>
onSelect: (id: string) => void
/** A second click on the selection, or a double click: its properties dialog (A1). */
onOpen: (id: string) => void
/** A click with a drawing tool, in drawing units, with its closing reach (R-11). */
onPlace: (at: XY, reach: number) => void
/** A click on a vertex handle, a « + » or the « − » bubble. */
@@ -107,9 +109,10 @@ const isHandleAction = (action: ClickAction): action is HandleAction =>
action.type === 'insert' ||
action.type === 'remove'
/** What a click does with the select tool. `open` (the properties dialog) has nothing yet. */
/** What a click does with the select tool. */
function runClick(action: ClickAction, input: PressInput): void {
if (action.type === 'select') input.onSelect(action.id)
else if (action.type === 'open') input.onOpen(action.id)
else if (action.type === 'deselect') input.onDeselect()
else if (action.type === 'unchoose') {
useAnnotationWork.setState({ chosen: null })
+13 -1
View File
@@ -1,4 +1,4 @@
import type { FindingLayer, ReferenceLayer } from './tabs'
import type { AnnotationLayer, FindingLayer, ReferenceLayer } from './tabs'
import type { EditorNavigation } from './useEditorNavigation'
/** What Constats needs of the navigation for its dialog and the citations dialog over it. */
@@ -25,3 +25,15 @@ export function referenceLayerOf(nav: EditorNavigation): ReferenceLayer {
...nav.references,
}
}
/** What the drawing needs of the navigation for the annotation properties dialog. */
export function annotationLayerOf(nav: EditorNavigation): AnnotationLayer {
return {
view: nav.state.annotation,
guards: nav.guards,
open: nav.openAnnotation,
close: nav.closeAnnotation,
replace: nav.replaceAnnotation,
announce: nav.announce,
}
}
+21 -4
View File
@@ -103,6 +103,20 @@ function sanitizeFilter(raw: unknown, tab: unknown): ElementKey | null {
return key && isCitable(key) ? key : null
}
/**
* The annotation dialog of a view: over the drawing of Annotations only. Whether the
* annotation still exists is the dialog's own gone rule.
*/
function sanitizeAnnotation(
raw: Record<string, unknown>,
section: AnnotationSection,
): EditorView['annotation'] {
const layer = raw.annotation
const onDrawing = raw.tab === 'annotations' && section === 'drawing'
if (!onDrawing || !isRecord(layer) || !isId(layer.id)) return null
return layer.id === '' ? null : { id: layer.id }
}
/**
* A view read back from a history entry, or null when it is no view. The finding layer
* must name a well-formed key and sit on the Constats tab; whether the element still
@@ -118,9 +132,11 @@ export function sanitizeView(raw: unknown, forms = true): EditorView | null {
const reference = forms
? sanitizeReference(raw.reference, finding, raw.tab)
: null
const section = known ? (raw.section as AnnotationSection) : 'drawing'
return {
tab: raw.tab as EditorTabId,
section: known ? (raw.section as AnnotationSection) : 'drawing',
section,
annotation: sanitizeAnnotation(raw, section),
finding,
reference,
referenceFilter: sanitizeFilter(raw.referenceFilter, raw.tab),
@@ -168,13 +184,14 @@ export function ownedEntry(
export const entryState = (entry: HistoryEntry) => ({ [ENTRY_KEY]: entry })
/**
* Layers over the place: the finding dialog and the citations dialog over it, the
* reference dialog, each count one.
* Layers over the place: the annotation dialog, the finding dialog and the citations
* dialog over it, the reference dialog, each count one.
*/
export function layerCount(view: EditorView): number {
const { finding } = view
const cited = finding && 'key' in finding && finding.citations
return (finding ? 1 : 0) + (cited ? 1 : 0) + (view.reference ? 1 : 0)
const dialogs = (view.annotation ? 1 : 0) + (finding ? 1 : 0)
return dialogs + (cited ? 1 : 0) + (view.reference ? 1 : 0)
}
/** An Annotations section other than the drawing is a step over it, like a layer. */
@@ -208,8 +208,8 @@ function useReconcile(
/** The layers (dialogs) two views show: a POP between them opens or closes a dialog. */
function sameLayers(a: EditorView, b: EditorView): boolean {
return (
JSON.stringify([a.finding, a.reference]) ===
JSON.stringify([b.finding, b.reference])
JSON.stringify([a.annotation, a.finding, a.reference]) ===
JSON.stringify([b.annotation, b.finding, b.reference])
)
}
@@ -227,7 +227,8 @@ const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
*/
function leavingLayers(from: EditorView, to: EditorView): LayerName[] {
const cited = citationsOfView(from)
const leaving = {
const leaving: Record<LayerName, boolean> = {
annotation: !!from.annotation && !same(from.annotation, to.annotation),
reference: !!from.reference && !same(from.reference, to.reference),
citations: !!cited && !same(cited, citationsOfView(to)),
finding: !!from.finding && !same(dialogOf(from), dialogOf(to)),
@@ -394,10 +395,11 @@ function useLanding(
/** The view the reducer holds, as one object that changes only when the view does. */
function useViewOf(state: EditorNavigation['state']): EditorView {
const { tab, section, finding, reference, referenceFilter } = state
const { tab, section, annotation, finding, reference, referenceFilter } =
state
return useMemo(
() => ({ tab, section, finding, reference, referenceFilter }),
[tab, section, finding, reference, referenceFilter],
() => ({ tab, section, annotation, finding, reference, referenceFilter }),
[tab, section, annotation, finding, reference, referenceFilter],
)
}
+4
View File
@@ -54,6 +54,10 @@ function storage(): Storage | null {
/** The element the layer showed: a key, a reference, a creation's parent. Never text. */
function elementOf(state: NavigationState, layer: LayerName): unknown {
if (layer === 'annotation') {
const { annotation } = state
return annotation && { kind: 'annotation', id: annotation.id }
}
if (layer === 'reference') {
const { reference } = state
return reference && 'edit' in reference
+44 -9
View File
@@ -31,11 +31,13 @@ export interface FocusRequest {
* they typed. A layer (`finding`, `reference`) is a dialog over a place; `citations` is
* the citations dialog over the finding dialog; `reference` is the reference dialog above
* either; `referenceFilter` (only on the References tab) narrows the library to the
* references a finding cites. The search text is a personal search: never part of a view.
* references a finding cites. `annotation` is the properties dialog of an annotation over
* the drawing (U2 Task 6). The search text is a personal search: never part of a view.
*/
export interface EditorView {
tab: EditorTabId
section: AnnotationSection
annotation: { id: string } | null
finding:
| { key: ElementKey; citations: boolean }
| { create: { kind: string; parent: ElementKey | null } }
@@ -59,6 +61,8 @@ export type NavigationAction =
| { type: 'select_tab'; tab: EditorTabId }
| { type: 'open_section'; section: AnnotationSection }
| { type: 'back_to_drawing' }
| { type: 'open_annotation'; id: string }
| { type: 'close_annotation' }
| { type: 'open_finding'; key: ElementKey }
| { type: 'create_finding'; kind: string; parent: ElementKey | null }
| { type: 'close_finding' }
@@ -119,11 +123,19 @@ function shown(state: NavigationState): NavigationState {
return { ...state, visitedTabs, visitedSections }
}
/** What a move to another tab leaves behind: the reference dialog and the filter. */
const LEFT_REFERENCES = { reference: null, referenceFilter: null } as const
/**
* What a move to another tab leaves behind: the reference dialog, the filter and the
* annotation dialog (a layer of the drawing only).
*/
const LEFT_REFERENCES = {
reference: null,
referenceFilter: null,
annotation: null,
} as const
const DEFAULT_VIEW = {
section: 'drawing',
annotation: null,
finding: null,
reference: null,
referenceFilter: null,
@@ -158,8 +170,9 @@ export function initialNavigation(
/** The part of the state the browser history records. */
export function viewOf(state: NavigationState): EditorView {
const { tab, section, finding, reference, referenceFilter } = state
return { tab, section, finding, reference, referenceFilter }
const { tab, section, annotation, finding, reference, referenceFilter } =
state
return { tab, section, annotation, finding, reference, referenceFilter }
}
/**
@@ -171,8 +184,13 @@ export function sameView(a: EditorView, b: EditorView): boolean {
return (
a.tab === b.tab &&
section &&
JSON.stringify([a.finding, a.reference, a.referenceFilter]) ===
JSON.stringify([b.finding, b.reference, b.referenceFilter])
JSON.stringify([
a.annotation,
a.finding,
a.reference,
a.referenceFilter,
]) ===
JSON.stringify([b.annotation, b.finding, b.reference, b.referenceFilter])
)
}
@@ -262,6 +280,7 @@ function goTo(state: NavigationState, target: EditorTarget): NavigationState {
tab: target.tab,
section: target.section ?? state.section,
finding: dialogOf(target),
annotation: null,
reference: null,
referenceFilter: keep ? state.referenceFilter : null,
focus: { target, serial },
@@ -282,6 +301,7 @@ function showAllReferences(
...state,
tab: 'references' as const,
finding: null,
annotation: null,
reference: null,
referenceFilter: filter,
libraryReset: state.libraryReset + 1,
@@ -292,7 +312,12 @@ function showAllReferences(
/** A tab other than References has no filter: the filter belongs to that tab's view. */
function selectTab(state: NavigationState, tab: EditorTabId): NavigationState {
const filter = tab === 'references' ? state.referenceFilter : null
const left = { finding: null, reference: null, referenceFilter: filter }
const left = {
finding: null,
annotation: null,
reference: null,
referenceFilter: filter,
}
return shown({ ...state, ...left, tab })
}
@@ -312,6 +337,12 @@ function createReference(state: NavigationState): NavigationState {
return shown({ ...state, tab: 'references', reference })
}
/** The properties dialog of `id`, over the drawing of Annotations. */
function openAnnotation(state: NavigationState, id: string): NavigationState {
const place = { tab: 'annotations', section: 'drawing' } as const
return shown({ ...state, ...place, annotation: { id } })
}
export function navigationReducer(
state: NavigationState,
action: NavigationAction,
@@ -320,9 +351,13 @@ export function navigationReducer(
case 'select_tab':
return selectTab(state, action.tab)
case 'open_section':
return shown({ ...state, section: action.section })
return shown({ ...state, section: action.section, annotation: null })
case 'back_to_drawing':
return shown({ ...state, section: 'drawing' })
case 'open_annotation':
return openAnnotation(state, action.id)
case 'close_annotation':
return { ...state, annotation: null }
case 'open_finding':
return openFinding(state, action.key)
case 'create_finding':
+16
View File
@@ -54,6 +54,20 @@ export interface FindingLayer {
announce: (text: string) => void
}
/**
* What the drawing needs of the navigation for the annotation properties dialog (U2 Task
* 6): the layer the view holds and the moves on it. A user close answers false when the
* form refused it.
*/
export interface AnnotationLayer {
view: EditorView['annotation']
guards: Guards
open: (id: string) => void
close: (forced?: boolean) => boolean
replace: (id: string | null, text?: string) => void
announce: (text: string) => void
}
/**
* What the References tab and the reference dialog need of the navigation (R2F-5, R2F-6):
* the layer and the filter the view holds, and the moves on them.
@@ -85,6 +99,8 @@ export interface EditorPlaceProps {
navigate: (target: EditorTarget) => void
/** « Aller à … » with an element: the place seeds its own selection from it once. */
focus?: FocusRequest
/** The annotation properties dialog (only Annotations has it). */
annotationLayer?: AnnotationLayer
/** The finding dialog and the citations dialog over it (only Constats has them). */
layer?: FindingLayer
/** The reference dialog and the filter (the References tab and the citations dialog). */
+61 -4
View File
@@ -56,10 +56,16 @@ export type CanLeave = (forced: boolean) => LeaveAnswer
/**
* The layers that can hold a form the user must settle before leaving, in stacking order
* (top one last): the finding dialog, the citations dialog over it (its edit mode, Rev 5),
* the reference dialog over either.
* (top one last): the annotation dialog (never with the next ones: another tab), the
* finding dialog, the citations dialog over it (its edit mode, Rev 5), the reference
* dialog over either.
*/
export const LAYERS = ['finding', 'citations', 'reference'] as const
export const LAYERS = [
'annotation',
'finding',
'citations',
'reference',
] as const
export type LayerName = (typeof LAYERS)[number]
/** One guard per layer (R2F-1): each layer registers its own check while it is mounted. */
@@ -135,6 +141,16 @@ export interface EditorNavigation {
* once the dialogs are closed.
*/
replaceFinding: (key: ElementKey | null, text?: string) => void
/** The properties dialog of an annotation, over the drawing (U2 Task 6). */
openAnnotation: (id: string) => void
/** A user close of it; false when its form refused (a dirty draft asks first). */
closeAnnotation: (forced?: boolean) => boolean
/**
* The annotation layer becomes another view of itself, by replace (no Back entry): null
* closes it. With `text`, a close the user did not ask for (the annotation vanished):
* forced, said once the dialog is closed.
*/
replaceAnnotation: (id: string | null, text?: string) => void
/** Opens the citations dialog of a family or a node; any other key is ignored. */
openCitations: (citedBy: ElementKey, opener?: Opener) => void
/**
@@ -397,6 +413,46 @@ function useFindingClosing({ dispatch, announce, guards, mark }: LayerContext) {
return { closeFinding, replaceFinding }
}
/**
* The annotation properties dialog (U2 Task 6): a user close asks its form; the replace
* is no Back step (a deletion, an annotation that vanished).
*/
function useAnnotationLayer({
dispatch,
announce,
guards,
mark,
}: LayerContext) {
const openAnnotation = useCallback(
(id: string) => {
mark()
dispatch({ type: 'open_annotation', id })
},
[dispatch, mark],
)
const closeAnnotation = useCallback(
(forced = false) => {
if (!guards.ask('annotation', forced).allowed) return false
mark()
dispatch({ type: 'close_annotation' })
return true
},
[guards, dispatch, mark],
)
const replaceAnnotation = useCallback(
(id: string | null, text?: string) => {
const note = text ? guards.ask('annotation', true).note : undefined
if (text) announce(note ? `${note}. ${text}` : text)
mark(true)
dispatch(
id ? { type: 'open_annotation', id } : { type: 'close_annotation' },
)
},
[guards, announce, dispatch, mark],
)
return { openAnnotation, closeAnnotation, replaceAnnotation }
}
/** The citations dialog over the finding dialog: opened for a family or a node only. */
function useCitationsLayer(ctx: LayerContext, openers: Openers) {
const { dispatch, announce, guards, mark } = ctx
@@ -444,7 +500,7 @@ function useAskLeaving(ctx: LayerContext, state: NavigationState) {
.filter((layer) => !guards.ask(layer, false).allowed)
if (refused.length === 0) return true
const above = layersAbove(refused[0])
const shown = { finding: false, citations, reference }
const shown = { annotation: false, finding: false, citations, reference }
if (!above.some((layer) => shown[layer])) return false
mark()
if (above.includes('reference') && reference) {
@@ -639,6 +695,7 @@ export function useEditorNavigation(
selectTab: useTabSelect(base.dispatch, base.mark),
...useSectionMoves(base.go, openers),
...useFindingLayer(ctx),
...useAnnotationLayer(ctx),
...useCitationsLayer(ctx, openers),
...useLeavingMoves(base.go, useAskLeaving(ctx, base.state)),
references: useReferenceMoves(ctx, base.trace, base.state.reference),
+14
View File
@@ -53,3 +53,17 @@ export function useTabTier(): TabTier {
}, [tier])
return tier
}
/**
* Whether the window is 1 024 px wide or more, kept in step with it; nothing else (no
* focus fix-up: `useTabTier` owns that).
*/
export function useEditWidth(): boolean {
const [wide, setWide] = useState(() => window.innerWidth >= MIN_EDIT_WIDTH)
useEffect(() => {
const update = () => setWide(window.innerWidth >= MIN_EDIT_WIDTH)
window.addEventListener('resize', update)
return () => window.removeEventListener('resize', update)
}, [])
return wide
}
+11 -2
View File
@@ -1241,7 +1241,6 @@ export const en: Dict = {
'editor.overview.filter': 'Filter by name',
'editor.overview.uncategorised': 'No category',
'editor.overview.no_match': 'No annotation matches.',
'editor.annotations.show_all': 'All annotations',
'editor.annotations.deselect': 'Deselect',
'editor.annotations.deselected': 'No annotation selected.',
'editor.references.search': 'Search a reference',
@@ -1641,7 +1640,17 @@ export const en: Dict = {
'editor.annotations.list': 'Annotations of the view',
'editor.annotations.list_empty': 'No annotation in this view.',
'editor.annotations.selection': 'Selection: {kind} « {name} »',
'editor.annotations.properties': 'Annotation properties',
'editor.annotations.properties': 'Properties',
'editor.annotations.edit_shape': 'Edit shape',
'editor.annotations.view': 'View',
'editor.annotations.gone': 'This annotation no longer exists',
'editor.annotations.color_placeholder': "The category's",
'editor.annotations.missing.name_fr': 'Enter the French name.',
'editor.annotations.missing.name_en': 'Enter the English name.',
'editor.annotations.missing.category': 'Choose a category.',
'editor.annotations.missing.laterality': 'Choose a laterality.',
'editor.annotations.missing.opens': 'Choose the view it opens.',
'editor.annotations.missing.summary': 'To complete: {fields}.',
'editor.annotations.tracing_one': '{count} vertex placed',
'editor.annotations.tracing_other': '{count} vertices placed',
'editor.annotations.trace_close': 'Close the tracing',
+11 -2
View File
@@ -1272,7 +1272,6 @@ export const fr: Dict = {
'editor.overview.filter': 'Filtrer par nom',
'editor.overview.uncategorised': 'Sans catégorie',
'editor.overview.no_match': 'Aucune annotation ne correspond.',
'editor.annotations.show_all': 'Toutes les annotations',
'editor.annotations.deselect': 'Désélectionner',
'editor.annotations.deselected': 'Aucune annotation sélectionnée.',
'editor.references.search': 'Rechercher une référence',
@@ -1671,7 +1670,17 @@ export const fr: Dict = {
'editor.annotations.list': 'Annotations de la vue',
'editor.annotations.list_empty': 'Aucune annotation dans cette vue.',
'editor.annotations.selection': 'Sélection : {kind} « {name} »',
'editor.annotations.properties': "Propriétés de l'annotation",
'editor.annotations.properties': 'Propriétés',
'editor.annotations.edit_shape': 'Modifier la forme',
'editor.annotations.view': 'Vue',
'editor.annotations.gone': "Cette annotation n'existe plus",
'editor.annotations.color_placeholder': 'Celle de la catégorie',
'editor.annotations.missing.name_fr': 'Saisissez le nom en français.',
'editor.annotations.missing.name_en': 'Saisissez le nom en anglais.',
'editor.annotations.missing.category': 'Choisissez une catégorie.',
'editor.annotations.missing.laterality': 'Choisissez une latéralité.',
'editor.annotations.missing.opens': 'Choisissez la vue ouverte.',
'editor.annotations.missing.summary': 'À compléter : {fields}.',
'editor.annotations.tracing_one': '{count} sommet posé',
'editor.annotations.tracing_other': '{count} sommets posés',
'editor.annotations.trace_close': 'Fermer le tracé',
@@ -0,0 +1,40 @@
/** U2 Task 6: the Annotations tab with a real navigation, so its properties dialog opens. */
import AnnotationsTab, {
type AnnotationsTabProps,
} from '@/components/editor/tabs/AnnotationsTab'
import { annotationLayerOf } from '@/editor/findingLayer'
import { AnnounceContext } from '@/editor/focusRequest'
import {
useEditorNavigation,
type EditorNavigation,
} from '@/editor/useEditorNavigation'
/** The last navigation a `LayeredTab` rendered with, for the tests to drive (Back, Forward). */
export const layered: { nav: EditorNavigation | null } = { nav: null }
export function LayeredTab(
props: Omit<AnnotationsTabProps, 'annotationLayer'>,
) {
const nav = useEditorNavigation('annotations')
layered.nav = nav
return (
<AnnounceContext value={nav.announce}>
<AnnotationsTab {...props} annotationLayer={annotationLayerOf(nav)} />
<p data-testid="live-region">{nav.live}</p>
</AnnounceContext>
)
}
/** « Propriétés » in the strip, then the dialog it opened. */
export async function openProperties(
user: { click: (element: Element) => Promise<void> },
within: (element: HTMLElement) => {
getByRole: (role: string, o: object) => HTMLElement
},
): Promise<HTMLElement> {
const strip = document.querySelector<HTMLElement>(
'[data-testid="edit-strip"]',
)!
await user.click(within(strip).getByRole('button', { name: 'Propriétés' }))
return document.querySelector<HTMLElement>('dialog[open]')!
}
@@ -0,0 +1,52 @@
/** U2 Task 6, R-3: only what is really missing, in the form's order (board 33 adjustment 3). */
import { describe, expect, it } from 'vitest'
import type { CreationForm } from '@/editor/annotations/creation'
import { missingFields } from '@/editor/annotations/missingFields'
const form = (patch: Partial<CreationForm> = {}): CreationForm => ({
fr: 'Grasset',
en: 'Stifle',
categoryId: 'cat-1',
laterality: 'bilateral',
opensViewId: '',
zoneId: '',
regionCode: '',
...patch,
})
describe('missingFields', () => {
it('a full point or zone misses nothing', () => {
expect(missingFields('point', form())).toEqual([])
expect(missingFields('zone', form())).toEqual([])
})
it('a chosen category is never listed; only the laterality is', () => {
expect(missingFields('point', form({ laterality: '' }))).toEqual([
'laterality',
])
})
it('a link with both names blank is fine; with one blank it names that one', () => {
const link = form({ fr: ' ', en: '', opensViewId: 'head' })
expect(missingFields('detail_trigger', link)).toEqual([])
const half = form({ fr: '', opensViewId: 'head' })
expect(missingFields('detail_trigger', half)).toEqual(['name_fr'])
})
it('names, category, laterality, opened view: in the form’s order', () => {
const empty = form({ fr: '', en: 'x', categoryId: '', laterality: '' })
expect(missingFields('detail_trigger', empty)).toEqual([
'name_fr',
'category',
'laterality',
'opens',
])
const blank = form({ fr: '', en: ' ', categoryId: '', laterality: '' })
expect(missingFields('point', blank)).toEqual([
'name_fr',
'name_en',
'category',
'laterality',
])
})
})
@@ -0,0 +1,497 @@
/** U2 Task 6: the properties dialog over the column (A1, A2, A3, A9, A10, R-3, R-14, R-16). */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
act,
cleanup,
fireEvent,
render,
screen,
waitFor,
within,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Annotation, Point } from '@faunosteo/core-wasm/types'
import { resetWork, useAnnotationWork } from '@/editor/annotations/workStore'
import { useLocaleStore } from '@/state/localeStore'
import { LayeredTab, layered } from '../helpers/annotationLayer'
import { drawnText, insert, point } from '../helpers/editorFixtures'
import { openReady, pressAt, resetStore, store } from '../helpers/editorHarness'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
getSheetVersion: vi.fn(),
downloadSheetDrawing: vi.fn(),
saveSheetDraft: vi.fn(),
getOfficialSheetAdmin: vi.fn(),
submitSheetReview: vi.fn(),
}))
const props = {
navigate: vi.fn(),
reloadSheet: vi.fn(),
section: 'drawing' as const,
visited: ['drawing'] as const,
onOpenSection: vi.fn(),
onBack: vi.fn(),
}
const SQUARE: Point[] = [
[20, 20],
[80, 20],
[80, 80],
[20, 80],
]
const annotationOf = (id: string) =>
store
.getState()
.previewState!.document.annotations.find((a: Annotation) => a.id === id)!
const depth = () => store.getState().undo.length
const zone = (id: string, patch: Partial<Annotation> = {}): Annotation =>
({
...(point(id, 0, 0, 1).value as Annotation),
kind: 'zone',
geometry: { type: 'polygon', points: SQUARE },
...patch,
}) as Annotation
function stubCtm(): void {
const identity = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }
Object.defineProperty(window.SVGElement.prototype, 'getScreenCTM', {
configurable: true,
value: () => ({ ...identity, inverse: () => identity }),
})
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
stubCtm()
})
afterEach(() => {
cleanup()
resetStore()
resetWork()
window.innerWidth = 1024
})
const tab = (readOnly = false) => (
<div data-editor-workspace>
<LayeredTab {...props} readOnly={readOnly} />
</div>
)
async function mount(text: string, readOnly = false) {
await openReady({ text })
const view = render(tab(readOnly))
const drawing = readOnly
? 'catalogue-canvas-drawing'
: 'annotation-canvas-drawing'
await waitFor(() =>
expect(screen.getByTestId(drawing).querySelector('svg')).not.toBeNull(),
)
return view
}
const rowOf = (id: string) =>
document.querySelector<HTMLElement>(
`[data-focus-key='{"kind":"annotation","id":"${id}"}']`,
)!
const strip = () => screen.getByTestId('edit-strip')
const dialog = () => screen.queryByRole('dialog')
const live = () => screen.getByTestId('live-region')
const marker = (id: string) =>
screen
.getByTestId('annotation-canvas-drawing')
.querySelector(`[data-anno-id="${id}"]`)!
async function selectRow(id: string) {
await userEvent.setup().click(rowOf(id))
await within(strip()).findByRole('button', { name: 'Propriétés' })
}
async function openProperties() {
await userEvent
.setup()
.click(within(strip()).getByRole('button', { name: 'Propriétés' }))
return screen.findByRole('dialog')
}
async function startEdit() {
const opened = await openProperties()
await userEvent
.setup()
.click(within(opened).getByRole('button', { name: 'Modifier' }))
return opened
}
const field = (label: string) =>
within(dialog()!).getByLabelText(label) as HTMLInputElement
describe('opening (A1)', () => {
it('a first click and Enter on a row only select; Enter on the selected row opens', async () => {
await mount(insert(drawnText(), point('a', 50, 50, 5)))
await selectRow('a')
expect(dialog()).toBeNull()
expect(rowOf('a')).toHaveAttribute('aria-current', 'true')
fireEvent.keyDown(rowOf('a'), { key: 'Enter', repeat: true })
expect(dialog()).toBeNull()
fireEvent.keyDown(rowOf('a'), { key: 'Enter' })
expect(await screen.findByRole('dialog', { name: 'N' })).toBeVisible()
})
it('a second click on the interior opens; with a chosen vertex it unchooses only', async () => {
await mount(insert(drawnText(), { kind: 'annotation', value: zone('z') }))
await selectRow('z')
useAnnotationWork.setState({
chosen: {
annotationId: 'z',
vertex: 1,
base: store.getState().documentText,
},
})
pressAt(marker('z'), 50, 50)
expect(useAnnotationWork.getState().chosen).toBeNull()
expect(dialog()).toBeNull()
await new Promise((resolve) => setTimeout(resolve, 450))
pressAt(marker('z'), 50, 50)
expect(await screen.findByRole('dialog')).toBeVisible()
})
it('« Propriétés » opens it; ✕ closes it and the focus goes back to the button', async () => {
await mount(insert(drawnText(), point('a', 50, 50, 5)))
await selectRow('a')
const opened = await openProperties()
await userEvent
.setup()
.click(within(opened).getByRole('button', { name: 'Fermer' }))
await waitFor(() => expect(dialog()).toBeNull())
await waitFor(() =>
expect(document.activeElement).toBe(
within(strip()).getByRole('button', { name: 'Propriétés' }),
),
)
// The selection stays after the close.
expect(rowOf('a')).toHaveAttribute('aria-current', 'true')
})
})
describe('the read mode (board 31 A, B)', () => {
const rows = () =>
within(dialog()!)
.getAllByRole('term')
.map((term) => term.textContent)
it('a point: names, category, laterality, findings zone and view; no colour, no region', async () => {
await mount(insert(drawnText(), point('a', 50, 50, 5)))
await selectRow('a')
await openProperties()
expect(rows()).toEqual([
'Nom (FR)',
'Nom (EN)',
'Catégorie',
'Latéralité',
'Zone de constats',
'Vue',
])
expect(within(dialog()!).getByTestId('annotation-read')).toHaveTextContent(
'Point',
)
})
it('a zone with its own colour and a region shows both', async () => {
const text = insert(drawnText(), {
kind: 'annotation',
value: zone('z', { color: '#aa0000' }),
})
const regions = JSON.parse(text)
const code = regions.vertebral_config.regions[0]?.code ?? null
const value = zone('z', {
color: '#aa0000',
vertebral_region_code: code,
} as Partial<Annotation>)
await mount(insert(drawnText(), { kind: 'annotation', value } as never))
await selectRow('z')
await openProperties()
expect(rows()).toContain('Couleur')
if (code !== null) expect(rows()).toContain('Région vertébrale')
expect(within(dialog()!).getByText('#aa0000')).toBeInTheDocument()
})
it('« Marquer comme relu » is one change and one undo (A10)', async () => {
await mount(insert(drawnText(), point('a', 50, 50, 5)))
await selectRow('a')
const opened = await openProperties()
const before = depth()
await userEvent
.setup()
.click(within(opened).getByRole('button', { name: 'Marquer comme relu' }))
expect(annotationOf('a').review_status).toBe('reviewed')
expect(depth()).toBe(before + 1)
expect(
within(opened).getByRole('button', { name: 'Remettre à confirmer' }),
).toBeInTheDocument()
act(() => void store.getState().undoStep())
expect(annotationOf('a').review_status).toBe('to_confirm')
})
it('the issues block names the inherited out-of-frame point', async () => {
await mount(insert(drawnText(), point('a', 150, 150, 5)))
await selectRow('a')
const opened = await openProperties()
expect(
within(opened).getByTestId('annotation-geometry-issues'),
).toHaveAttribute('role', 'alert')
})
it('« Modifier la forme » closes it, keeps the selection, focuses the first handle', async () => {
await mount(insert(drawnText(), point('a', 50, 50, 5)))
await selectRow('a')
const opened = await openProperties()
await userEvent
.setup()
.click(within(opened).getByRole('button', { name: 'Modifier la forme' }))
await waitFor(() => expect(dialog()).toBeNull())
await waitFor(() =>
expect(document.activeElement).toBe(screen.getByTestId('point-handle')),
)
expect(rowOf('a')).toHaveAttribute('aria-current', 'true')
})
})
describe('the edit form (board 31 C, R-3)', () => {
it('category and both names saved: ONE history entry, the read mode back', async () => {
await mount(insert(drawnText(), point('a', 50, 50, 5)))
await selectRow('a')
await startEdit()
const user = userEvent.setup()
const before = depth()
await user.clear(field('Nom (FR)'))
await user.type(field('Nom (FR)'), 'Grasset')
await user.clear(field('Nom (EN)'))
await user.type(field('Nom (EN)'), 'Stifle')
const category = within(dialog()!).getByLabelText(
'Catégorie',
) as HTMLSelectElement
const other = [...category.options].find((o) => !o.selected)
if (other) await user.selectOptions(category, other.value)
expect(depth()).toBe(before)
await user.click(
within(dialog()!).getByRole('button', { name: 'Enregistrer' }),
)
expect(depth()).toBe(before + 1)
expect(annotationOf('a').name).toEqual({ fr: 'Grasset', en: 'Stifle' })
if (other) expect(annotationOf('a').category_id).toBe(other.value)
expect(
within(dialog()!).getByText('Modifications enregistrées'),
).toBeInTheDocument()
})
it('the save merges onto the current annotation: a move made meanwhile stays', async () => {
await mount(insert(drawnText(), point('a', 50, 50, 5)))
await selectRow('a')
await startEdit()
const user = userEvent.setup()
await user.type(field('Nom (FR)'), 'x')
const moved = {
...annotationOf('a'),
geometry: { type: 'circle', cx: 40, cy: 50, r: 5 },
}
act(
() =>
void store.getState().commit({
op: 'update',
key: { kind: 'annotation', id: 'a' },
element: { kind: 'annotation', value: moved as Annotation },
}),
)
await user.click(
within(dialog()!).getByRole('button', { name: 'Enregistrer' }),
)
expect(annotationOf('a').geometry).toMatchObject({ cx: 40 })
expect(annotationOf('a').name?.fr).toBe('Nx')
})
it('a blank name: named under its field and in the summary, focused, nothing written', async () => {
await mount(insert(drawnText(), point('a', 50, 50, 5)))
await selectRow('a')
await startEdit()
const user = userEvent.setup()
const before = store.getState().documentText
await user.clear(field('Nom (EN)'))
await user.click(
within(dialog()!).getByRole('button', { name: 'Enregistrer' }),
)
expect(
within(dialog()!).getByText('Saisissez le nom en anglais.'),
).toBeInTheDocument()
expect(
within(dialog()!).getByText('À compléter : Nom (EN).'),
).toHaveAttribute('role', 'alert')
expect(within(dialog()!).queryByText(/Choisissez/)).toBeNull()
expect(document.activeElement).toBe(field('Nom (EN)'))
expect(store.getState().documentText).toBe(before)
})
it('« Annuler » with changes asks; « Abandonner » writes nothing', async () => {
await mount(insert(drawnText(), point('a', 50, 50, 5)))
await selectRow('a')
await startEdit()
const user = userEvent.setup()
const before = store.getState().documentText
await user.type(field('Nom (FR)'), 'x')
await user.click(within(dialog()!).getByRole('button', { name: 'Annuler' }))
expect(
within(dialog()!).getByText('Abandonner les modifications ?'),
).toBeInTheDocument()
await user.click(
within(dialog()!).getByRole('button', { name: 'Abandonner' }),
)
expect(store.getState().documentText).toBe(before)
expect(
within(dialog()!).getByRole('button', { name: 'Modifier' }),
).toBeInTheDocument()
})
it('« Couleur » sits in the form with the category’s placeholder (A9)', async () => {
await mount(insert(drawnText(), point('a', 50, 50, 5)))
await selectRow('a')
await startEdit()
expect(field('Couleur')).toHaveAttribute(
'placeholder',
'Celle de la catégorie',
)
})
})
describe('a read-only flip (R-14, Review Focus 3)', () => {
it('the dialog stays with its draft, read-only, nothing committed; editable on the way back', async () => {
const view = await mount(insert(drawnText(), point('a', 50, 50, 5)))
await selectRow('a')
await startEdit()
const user = userEvent.setup()
await user.type(field('Nom (FR)'), 'x')
const before = store.getState().documentText
view.rerender(tab(true))
expect(dialog()).not.toBeNull()
expect(field('Nom (FR)')).toHaveValue('Nx')
expect(field('Nom (FR)')).toHaveAttribute('readonly')
expect(within(dialog()!).getByLabelText('Catégorie')).toBeDisabled()
expect(
within(dialog()!).getByRole('button', { name: 'Enregistrer' }),
).toBeDisabled()
expect(store.getState().documentText).toBe(before)
view.rerender(tab(false))
expect(field('Nom (FR)')).toHaveValue('Nx')
expect(field('Nom (FR)')).not.toHaveAttribute('readonly')
await user.click(
within(dialog()!).getByRole('button', { name: 'Enregistrer' }),
)
expect(annotationOf('a').name?.fr).toBe('Nx')
})
it('a started move mode is suspended and resumes with its position', async () => {
const view = await mount(insert(drawnText(), point('a', 50, 50, 5)))
await selectRow('a')
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'Déplacer le point' }))
fireEvent.click(
screen.getByRole('button', { name: 'Déplacer vers la droite' }),
)
view.rerender(tab(true))
expect(useAnnotationWork.getState().mode?.started).toBe(true)
view.rerender(tab(false))
await user.click(
screen.getByRole('button', { name: 'Valider la position' }),
)
expect(annotationOf('a').geometry).toMatchObject({ cx: 50.5 })
})
})
describe('a read-only sheet at 1 024 px and wider (R-16)', () => {
it('the strip says « fiche en lecture seule »; « Propriétés » opens values only', async () => {
window.innerWidth = 1280
await mount(insert(drawnText(), point('a', 50, 50, 5)), true)
await userEvent.setup().click(rowOf('a'))
expect(
await within(strip()).findByTestId('edit-strip-detail'),
).toHaveTextContent('Point · fiche en lecture seule')
expect(screen.queryByTestId('point-handle')).toBeNull()
expect(screen.queryByTestId('size-slider')).toBeNull()
const opened = await openProperties()
expect(within(opened).getByTestId('annotation-read')).toBeInTheDocument()
expect(
within(opened).queryByRole('button', { name: 'Modifier' }),
).toBeNull()
expect(
within(opened).queryByRole('button', { name: 'Supprimer' }),
).toBeNull()
})
it('below 1 024 px the twin reads it inline, with no strip', async () => {
window.innerWidth = 800
await mount(insert(drawnText(), point('a', 50, 50, 5)), true)
await userEvent.setup().click(rowOf('a'))
expect(await screen.findByTestId('annotation-read')).toBeInTheDocument()
expect(screen.getByTestId('annotation-selection-tag')).toBeInTheDocument()
expect(screen.queryByTestId('edit-strip')).toBeNull()
})
})
describe('the layer (history)', () => {
it('an annotation that vanished closes the dialog and is said', async () => {
await mount(insert(drawnText(), point('a', 50, 50, 5)))
await selectRow('a')
await openProperties()
act(
() =>
void store
.getState()
.commit({ op: 'remove', key: { kind: 'annotation', id: 'a' } }),
)
await waitFor(() => expect(dialog()).toBeNull())
await waitFor(() =>
expect(live()).toHaveTextContent("Cette annotation n'existe plus"),
)
expect(layered.nav?.state.annotation).toBeNull()
})
it('a layer for an annotation of another view shows that view and selects it', async () => {
const detail = insert(drawnText(), {
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',
},
})
const text = insert(
insert(detail, point('a', 50, 50, 5)),
point('b', 40, 40, 5, 'view-det'),
)
await mount(text)
act(() => layered.nav!.openAnnotation('b'))
await waitFor(() =>
expect(rowOf('b')).toHaveAttribute('aria-current', 'true'),
)
expect(
screen.getByRole('button', { name: 'Tête', pressed: true }),
).toBeInTheDocument()
})
it('a deletion from the dialog closes it, unsaid as a vanish', async () => {
await mount(insert(drawnText(), point('a', 50, 50, 5)))
await selectRow('a')
const opened = await openProperties()
const user = userEvent.setup()
await user.click(within(opened).getByRole('button', { name: 'Supprimer' }))
const ask = await screen.findByRole('dialog', { name: /Supprimer/ })
await user.click(within(ask).getByRole('button', { name: 'Supprimer' }))
await waitFor(() => expect(screen.queryAllByRole('dialog')).toHaveLength(0))
expect(live()).not.toHaveTextContent("n'existe plus")
})
})
@@ -27,6 +27,7 @@ import {
point,
svgBytes,
} from '../helpers/editorFixtures'
import { LayeredTab } from '../helpers/annotationLayer'
import {
USER,
VERSION,
@@ -61,8 +62,6 @@ const props = {
const named = (id: string, cx: number, cy: number, r: number) =>
point(id, cx, cy, r)
const annotations = () => store.getState().previewState!.document.annotations
const nameOf = (id: string) =>
annotations().find((a: Annotation) => a.id === id)?.name?.fr
const geometryOf = (id: string) =>
annotations().find((a: Annotation) => a.id === id)?.geometry
/** The selection as the overlay draws it (U2 Task 5: no coordinate field in the panel). */
@@ -106,7 +105,7 @@ const text = () => insert(drawnText(), named('anno-a', 50, 50, 5))
async function mount(options: { text?: string; readOnly?: boolean } = {}) {
await openReady({ text: options.text ?? text() })
render(<AnnotationsTab {...props} readOnly={options.readOnly ?? false} />)
render(<LayeredTab {...props} readOnly={options.readOnly ?? false} />)
const drawing = options.readOnly
? 'catalogue-canvas-drawing'
: 'annotation-canvas-drawing'
@@ -121,7 +120,17 @@ async function selectFromList(name: RegExp | string = /N/) {
})
await userEvent.setup().click(within(list).getAllByRole('button')[0])
void name
return screen.findByTestId('annotation-properties')
// A1: a row selects only; the strip names the selection (the dialog stays closed).
await screen.findByRole('button', { name: 'Propriétés' })
return screen.getByTestId('edit-strip')
}
/** « Propriétés » in the strip: the properties dialog of the selection (A1). */
async function openProperties() {
await userEvent
.setup()
.click(screen.getByRole('button', { name: 'Propriétés' }))
return screen.findByRole('dialog')
}
describe('selection and the list', () => {
@@ -165,11 +174,11 @@ describe('an edit on the drawing (U2 Task 5: the numeric group left the panel)',
it('a refused place keeps the stored shape, then a place inside the frame repairs it', async () => {
await mount({ text: insert(drawnText(), named('anno-a', 150, 150, 5)) })
const panel = await selectFromList()
const strip = await selectFromList()
const before = store.getState().documentText
expect(
within(panel).getByTestId('annotation-geometry-issues'),
).toBeInTheDocument()
// The issue shows in the strip's notice (U2 Task 6: the panel left).
const issue = () => within(strip).queryByRole('alert')
expect(issue()).toBeInTheDocument()
mouseDrag(pointHandle(), [150, 150], [50, 150])
expect(store.getState().documentText).toBe(before)
expect(screen.getByTestId('overlay-refused-place')).toBeInTheDocument()
@@ -181,7 +190,7 @@ describe('an edit on the drawing (U2 Task 5: the numeric group left the panel)',
cy: 50,
r: 5,
})
expect(screen.queryByTestId('annotation-geometry-issues')).toBeNull()
expect(issue()).toBeNull()
})
it('Escape drops a pending series: the stored shape shows again', async () => {
@@ -231,8 +240,9 @@ describe('the keyboard creation path', () => {
laterality: 'unpaired',
geometry: { type: 'circle', cx: 50, cy: 50 },
})
// A7: the new point selected (the strip offers its properties).
expect(
await screen.findByTestId('annotation-properties'),
await screen.findByRole('button', { name: 'Propriétés' }),
).toBeInTheDocument()
})
@@ -308,7 +318,7 @@ describe('the point tool and the corrected position (C26)', () => {
})
expect(panel).not.toBeInTheDocument()
expect(screen.queryByTestId('overlay-click-cross')).toBeNull()
await screen.findByTestId('annotation-properties')
await screen.findByRole('button', { name: 'Propriétés' })
expect(shownCircle()).toHaveAttribute('cx', '15')
})
@@ -1001,7 +1011,7 @@ describe('« Désélectionner » (R1, A6)', () => {
const panel = await selectFromList()
const before = snapshot()
await userEvent.setup().click(button(panel))
expect(screen.queryByTestId('annotation-properties')).toBeNull()
expect(screen.queryByRole('button', { name: 'Propriétés' })).toBeNull()
expect(screen.getByTestId('annotation-overview')).toBeInTheDocument()
expect(document.activeElement).toBe(rowOf('anno-a'))
expect(announce).toHaveBeenCalledWith('Aucune annotation sélectionnée.')
@@ -1020,22 +1030,22 @@ describe('« Désélectionner » (R1, A6)', () => {
.getByTestId('annotation-canvas-drawing')
.querySelector('[data-anno-id="anno-a"]')!,
)
const reopened = await screen.findByTestId('annotation-properties')
await userEvent.setup().click(button(reopened))
await screen.findByRole('button', { name: 'Propriétés' })
await userEvent.setup().click(button(screen.getByTestId('edit-strip')))
expect(document.activeElement).toBe(screen.getByTestId('annotation-canvas'))
expect(screen.queryByTestId('annotation-properties')).toBeNull()
expect(screen.queryByRole('button', { name: 'Propriétés' })).toBeNull()
})
it('undo after it undoes the earlier edit', async () => {
await mountSpy()
const panel = await selectFromList()
const user = userEvent.setup()
await user.clear(within(panel).getByLabelText('Nom (FR)'))
await user.type(within(panel).getByLabelText('Nom (FR)'), 'Nuque{Enter}')
expect(nameOf('anno-a')).toBe('Nuque')
await user.click(button(panel))
const handle = screen.getByTestId('point-handle')
fireEvent.keyDown(handle, { key: 'ArrowRight' })
fireEvent.keyDown(handle, { key: 'Enter' })
expect(geometryOf('anno-a')).toMatchObject({ cx: 50.5 })
await userEvent.setup().click(button(panel))
act(() => void store.getState().undoStep())
expect(nameOf('anno-a')).toBe('N')
expect(geometryOf('anno-a')).toMatchObject({ cx: 50 })
})
it('read-only: no « Supprimer », it deselects and focuses the ro- row', async () => {
@@ -1045,7 +1055,7 @@ describe('« Désélectionner » (R1, A6)', () => {
within(panel).queryByRole('button', { name: 'Supprimer' }),
).toBeNull()
await userEvent.setup().click(button(panel))
expect(screen.queryByTestId('annotation-properties')).toBeNull()
expect(screen.queryByRole('button', { name: 'Propriétés' })).toBeNull()
const row = document.querySelector(
'[data-focus-key=\'{"kind":"annotation","id":"anno-a"}\']',
)
@@ -1053,38 +1063,27 @@ describe('« Désélectionner » (R1, A6)', () => {
expect(announce).toHaveBeenCalledTimes(1)
})
it('commits a valid typed value once when the field is not blurred', async () => {
it('commits a pending key series once when the handle is not blurred', async () => {
await mountSpy()
const panel = await selectFromList()
const user = userEvent.setup()
const name = within(panel).getByLabelText('Nom (FR)')
await user.clear(name)
await user.type(name, 'Nuque')
const handle = screen.getByTestId('point-handle')
handle.focus()
fireEvent.keyDown(handle, { key: 'ArrowRight' })
const depth = store.getState().undo.length
await user.click(button(panel))
expect(nameOf('anno-a')).toBe('Nuque')
await userEvent.setup().click(button(panel))
expect(geometryOf('anno-a')).toMatchObject({ cx: 50.5 })
expect(store.getState().undo.length).toBe(depth + 1)
})
it('a refused typed value: the panel closes, the document is unchanged', async () => {
await mountSpy()
const panel = await selectFromList()
const user = userEvent.setup()
const before = store.getState().documentText
// A blank name is refused (both names are required).
await user.clear(within(panel).getByLabelText('Nom (FR)'))
await user.click(button(panel))
expect(screen.queryByTestId('annotation-properties')).toBeNull()
expect(store.getState().documentText).toBe(before)
})
it('speaks English', async () => {
useLocaleStore.setState({ locale: 'en' })
await mountSpy()
await screen.findByTestId('annotation-overview')
await userEvent.setup().click(rowOf('anno-a')!)
const panel = await screen.findByTestId('annotation-properties')
await userEvent.setup().click(button(panel, 'Deselect'))
await screen.findByRole('button', { name: 'Properties' })
await userEvent
.setup()
.click(button(screen.getByTestId('edit-strip'), 'Deselect'))
expect(announce).toHaveBeenCalledWith('No annotation selected.')
})
@@ -1101,10 +1100,9 @@ describe('« Désélectionner » (R1, A6)', () => {
name: 'Remplacer par un polygone',
}),
)
const open = await screen.findByTestId('annotation-properties')
expect(
within(open).queryByRole('button', { name: 'Désélectionner' }),
).toBeNull()
await screen.findByRole('button', { name: 'Annuler le tracé' })
expect(screen.queryByRole('button', { name: 'Désélectionner' })).toBeNull()
expect(screen.queryByRole('button', { name: 'Propriétés' })).toBeNull()
})
})
@@ -1173,8 +1171,9 @@ describe('a tap on the drawing (D6b)', () => {
expect(drawing(readOnly).querySelector('svg')).not.toBeNull(),
)
}
// U2 Task 6: a selection shows « Propriétés » in the strip (the panel left).
const isDeselected = () =>
screen.queryByTestId('annotation-properties') === null
screen.queryByRole('button', { name: 'Propriétés' }) === null
async function selected(options: { text?: string } = {}) {
await mountSpy(options)
await selectFromList()
@@ -1252,7 +1251,9 @@ describe('a tap on the drawing (D6b)', () => {
} as Annotation
await mountSpy({ text: insert(view, { kind: 'annotation', value: link }) })
tap(marker('link-a'))
expect(screen.getByTestId('annotation-properties')).toBeInTheDocument()
expect(screen.getByTestId('edit-strip-title')).toHaveAttribute(
'data-selection',
)
expect(announce).not.toHaveBeenCalled()
})
@@ -1575,47 +1576,31 @@ describe('a tap on the drawing (D6b)', () => {
it('undo after a tap deselect undoes the earlier edit, redo restores it', async () => {
await selected()
const user = userEvent.setup()
const name = screen.getByLabelText('Nom (FR)')
await user.clear(name)
await user.type(name, 'Nuque{Enter}')
const handle = screen.getByTestId('point-handle')
fireEvent.keyDown(handle, { key: 'ArrowRight' })
fireEvent.keyDown(handle, { key: 'Enter' })
tap(rect())
act(() => void store.getState().undoStep())
expect(nameOf('anno-a')).toBe('N')
expect(geometryOf('anno-a')).toMatchObject({ cx: 50 })
act(() => void store.getState().redoStep())
expect(nameOf('anno-a')).toBe('Nuque')
expect(geometryOf('anno-a')).toMatchObject({ cx: 50.5 })
})
it('commits a typed valid value once and deselects when the press blurs the field', async () => {
it('commits a pending key series once and deselects when the press blurs the handle', async () => {
await selected()
const user = userEvent.setup()
const name = screen.getByLabelText('Nom (FR)')
await user.clear(name)
await user.type(name, 'Nuque')
const handle = screen.getByTestId('point-handle')
act(() => handle.focus())
fireEvent.keyDown(handle, { key: 'ArrowRight' })
const depth = store.getState().undo.length
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
// What mousedown does: the focus moves to the box, the field commits, the drawing rebuilds.
// What mousedown does: the focus moves to the box, the series commits on the blur.
act(() => box().focus())
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.click(rect())
expect(nameOf('anno-a')).toBe('Nuque')
expect(geometryOf('anno-a')).toMatchObject({ cx: 50.5 })
expect(store.getState().undo.length).toBe(depth + 1)
expect(isDeselected()).toBe(true)
})
it('a refused typed value: the panel closes, the document is unchanged', async () => {
await selected()
const user = userEvent.setup()
const before = store.getState().documentText
// A blank name is refused (both names are required).
await user.clear(screen.getByLabelText('Nom (FR)'))
fireEvent.pointerDown(rect(), { ...init(), clientX: 10, clientY: 10 })
act(() => box().focus())
fireEvent.pointerUp(rect(), { ...init(), clientX: 10, clientY: 10 })
fireEvent.click(rect())
expect(isDeselected()).toBe(true)
expect(store.getState().documentText).toBe(before)
})
})
describe('the strip', () => {
@@ -1765,7 +1750,10 @@ describe('the strip', () => {
]),
})
await selectFromList()
const issues = within(screen.getByTestId('annotation-properties'))
const dialog = await openProperties()
const issues = within(
within(dialog).getByTestId('annotation-geometry-issues'),
)
.getAllByRole('listitem')
.map((item) => item.textContent)
// The core gives one frame fault per annotation: « +n » is shown by the strip below.
@@ -1805,10 +1793,13 @@ describe('the strip', () => {
await selectFromList()
drag(marker('anno-a'), [60, 40])
expect(line()).toHaveTextContent('Point déplacé')
const name = screen.getByLabelText('Nom (FR)')
// A commit that is no gesture: the review toggle of the properties dialog (A10).
const user = userEvent.setup()
await user.clear(name)
await user.type(name, 'Nuque{Enter}')
const dialog = await openProperties()
await user.click(
within(dialog).getByRole('button', { name: 'Marquer comme relu' }),
)
await user.click(within(dialog).getByRole('button', { name: 'Fermer' }))
expect(line()).not.toHaveTextContent('Point déplacé')
drag(marker('anno-a'), [40, 40])
expect(line()).toHaveTextContent('Point déplacé')
@@ -65,7 +65,12 @@ function cited() {
describe('the layer order', () => {
it('reference, citations, finding: asked top down', () => {
expect(LAYERS_TOP_DOWN).toEqual(['reference', 'citations', 'finding'])
expect(LAYERS_TOP_DOWN).toEqual([
'reference',
'citations',
'finding',
'annotation',
])
mount()
const order: string[] = []
for (const layer of ['finding', 'citations', 'reference'] as const) {
+29 -13
View File
@@ -112,7 +112,14 @@ const shown = (selector: string) =>
[...document.querySelectorAll<HTMLElement>(selector)].find(
(element) => !element.closest('[hidden]'),
)
const panel = () => shown('[data-testid="annotation-properties"]')
/**
* The visible selection (U2 Task 6: the properties left the side panel): the strip's
* « Propriétés », or the phone twin's inline read body.
*/
const panel = () =>
shown('[data-properties-button]') ?? shown('[data-testid="annotation-read"]')
/** The shown body's right column: the overview (A3). */
const aside = () => shown('[data-annotation-aside]')!
const rowOf = (id: string) =>
shown(`[data-focus-key='{"kind":"annotation","id":"${id}"}']`)
const live = () => document.querySelector('[aria-live="polite"]')!
@@ -147,7 +154,17 @@ async function openCitations(user: ReturnType<typeof userEvent.setup>) {
await user.click(screen.getByRole('button', { name: '1 référence' }))
expect(citations()).not.toBeNull()
}
const inPanel = (name: string) => within(panel()!).getByRole('button', { name })
const inStrip = (name: string) =>
within(shown('[data-testid="edit-strip"]')!).getByRole('button', { name })
/** « Propriétés », then a button of the properties dialog. */
async function inDialog(
user: ReturnType<typeof userEvent.setup>,
name: string,
) {
await user.click(inStrip('Propriétés'))
const dialog = await screen.findByRole('dialog')
return within(dialog).getByRole('button', { name })
}
describe('Escape deselects', () => {
it('from the canvas box: deselected, the focus stays, announced', async () => {
@@ -162,10 +179,10 @@ describe('Escape deselects', () => {
)
})
it('from a button of the panel: deselected, the focus on the row', async () => {
it('from a button of the side column: deselected, the focus on the row', async () => {
const user = await mount()
await select(user)
inPanel('Marquer comme relu').focus()
rowOf('anno-a')!.focus()
escape(document.activeElement!)
expect(panel()).toBeUndefined()
expect(document.activeElement).toBe(rowOf('anno-a'))
@@ -174,9 +191,8 @@ describe('Escape deselects', () => {
it("after A then B, from the panel: the focus on B's row", async () => {
const user = await mount()
await select(user, 'anno-a')
await user.click(inPanel('Toutes les annotations'))
await select(user, 'anno-b')
inPanel('Marquer comme relu').focus()
within(aside()).getAllByRole('button')[0]!.focus()
escape(document.activeElement!)
expect(document.activeElement).toBe(rowOf('anno-b'))
})
@@ -206,7 +222,7 @@ describe('Escape leaves alone', () => {
it('a text field', async () => {
const user = await mount()
await select(user)
const field = within(panel()!).getByLabelText('Nom (FR)')
const field = within(aside()).getByLabelText('Filtrer par nom')
field.focus()
escape(field)
expect(panel()).toBeDefined()
@@ -256,7 +272,7 @@ describe('Escape leaves alone', () => {
it('a redraw: Escape on the strip commands or on the canvas box cancels the tracing only', async () => {
const user = await mount(ZONE())
await select(user, 'zone-a')
await user.click(inPanel('Remplacer par un polygone'))
await user.click(inStrip('Remplacer par un polygone'))
const bar = await screen.findByTestId('tracing-commands')
bar.focus()
escape(bar)
@@ -264,7 +280,7 @@ describe('Escape leaves alone', () => {
expect(screen.queryByTestId('tracing-commands')).toBeNull(),
)
expect(panel()).toBeDefined()
await user.click(inPanel('Remplacer par un polygone'))
await user.click(inStrip('Remplacer par un polygone'))
await screen.findByTestId('tracing-commands')
canvasBox().focus()
escape(canvasBox())
@@ -277,8 +293,8 @@ describe('Escape leaves alone', () => {
it('a modal dialog open: only its own handling (wiring proof)', async () => {
const user = await mount()
await select(user)
await user.click(inPanel('Supprimer'))
const dialog = document.querySelector('dialog')!
await user.click(await inDialog(user, 'Supprimer'))
const dialog = document.querySelectorAll('dialog[open]')[1]!
expect(dialog).not.toBeNull()
escape(dialog)
expect(panel()).toBeDefined()
@@ -289,7 +305,7 @@ describe('Escape with the focus on the page', () => {
it('a delete dialog open: the selection is kept', async () => {
const user = await mount()
await select(user)
await user.click(inPanel('Supprimer'))
await user.click(await inDialog(user, 'Supprimer'))
expect(document.querySelector('dialog[open]')).not.toBeNull()
document.body.focus()
escape(document.body)
@@ -367,7 +383,7 @@ describe('Escape and the other layers', () => {
escape(document.body)
expect(panel()).toBeUndefined()
const hidden = [
...document.querySelectorAll('[data-testid="annotation-properties"]'),
...document.querySelectorAll('[data-properties-button]'),
].filter((element) => element.closest('[hidden]'))
expect(hidden).toHaveLength(1)
})
@@ -123,7 +123,7 @@ describe('focus requests', () => {
await waitFor(() => expect(document.activeElement).toBe(item))
})
it('Annotations: selects the annotation and focuses the properties heading', async () => {
it('Annotations (R-5): selects the annotation and focuses its row, no dialog', async () => {
const text = insert(baseText(), point('anno-b', 20, 20, 3))
await openReady({ text })
render(
@@ -134,16 +134,16 @@ describe('focus requests', () => {
/>,
)
// anno-b and anno-a share a name: the circle's centre tells which one is selected.
const properties = await screen.findByTestId('annotation-properties')
expect(properties).toBeInTheDocument()
// U2 Task 5: no coordinate field in the panel; the overlay draws the selection.
await screen.findByRole('button', { name: 'Propriétés' })
expect(
screen.getByTestId('overlay-selection').querySelector('circle'),
).toHaveAttribute('cx', '20')
await waitFor(() =>
expect(document.activeElement).toHaveAttribute('data-properties-heading'),
const row = document.querySelector(
'[data-focus-key=\'{"kind":"annotation","id":"anno-b"}\']',
)
expect(properties).toContainElement(document.activeElement as HTMLElement)
await waitFor(() => expect(document.activeElement).toBe(row))
expect(row).toHaveAttribute('aria-current', 'true')
expect(screen.queryByRole('dialog')).toBeNull()
})
it('Références and Régions: focus the named row', async () => {
@@ -58,16 +58,15 @@ const disabled = (button: HTMLElement) =>
button.getAttribute('aria-disabled') === 'true'
const geometry = () =>
store.getState().previewState?.document.annotations[0].geometry
const nameFr = () =>
store.getState().previewState?.document.annotations[0].name?.fr
const nameFr = () => store.getState().previewState?.document.name.fr
/**
* A committed field (it writes on its blur): the sheet's French name on Général. U2 Task 6
* took the annotation's committed fields out of the drawing (one dialog save).
*/
async function selectAnnotation(user: ReturnType<typeof userEvent.setup>) {
const list = await screen.findByRole('list', {
name: 'Annotations de la vue',
})
await user.click(within(list).getAllByRole('button')[0])
const panel = await screen.findByTestId('annotation-properties')
return within(panel).getByLabelText('Nom (FR)') as HTMLInputElement
await user.click(screen.getByRole('tab', { name: 'Général' }))
return (await screen.findByLabelText('Nom (FR)')) as HTMLInputElement
}
describe('the buttons', () => {
@@ -420,3 +420,32 @@ describe('final review: read-back values are capped', () => {
expect(sanitizeView(onFindings(sparse))?.finding).toBeNull()
})
})
/** U2 Task 6: the annotation dialog's layer in an entry. */
describe('the annotation layer in the history', () => {
it('is read back on the drawing of Annotations only, with an id within the cap', () => {
const raw = {
tab: 'annotations',
section: 'drawing',
annotation: { id: 'a1' },
}
expect(sanitizeView(raw)?.annotation).toEqual({ id: 'a1' })
expect(layerCount(sanitizeView(raw)!)).toBe(1)
expect(sanitizeView({ ...raw, section: 'views' })?.annotation).toBeNull()
expect(sanitizeView({ ...raw, tab: 'general' })?.annotation).toBeNull()
expect(
sanitizeView({ ...raw, annotation: { id: 7 } })?.annotation,
).toBeNull()
const long = { ...raw, annotation: { id: 'x'.repeat(200) } }
expect(sanitizeView(long)?.annotation).toBeNull()
})
it('opened pushes, closed goes back to the drawing below', () => {
const drawing = view('annotations')
const dialog = view('annotations', { annotation: { id: 'a1' } })
expect(sameView(drawing, dialog)).toBe(false)
expect(planWrite(entry({ view: drawing }), dialog, false)).toBe('push')
const top = entry({ view: dialog, below: drawing })
expect(planWrite(top, drawing, false)).toBe('back')
})
})
@@ -476,3 +476,68 @@ describe('the drawing guard (R-12): a move mode and the navigations', () => {
expect(useAnnotationWork.getState().mode).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 }) {
const nav = useEditorNavigation('annotations')
navigate = useNavigate()
location = useLocation()
useEditorHistory(nav, owner, defaultView('annotations'))
return (
<>
<button onClick={() => nav.openAnnotation('a1')}>open</button>
<button onClick={() => nav.closeAnnotation()}>close</button>
<button
onClick={() =>
nav.guards.register('annotation', () =>
dirty ? { allowed: false } : { allowed: true },
)
}
>
guard
</button>
<p data-testid="layer">{JSON.stringify(nav.state.annotation)}</p>
</>
)
}
const layer = () => JSON.parse(screen.getByTestId('layer').textContent!)
const mountPage = (dirty = false) =>
render(
<MemoryRouter initialEntries={['/x']}>
<AnnotationPage dirty={dirty} />
</MemoryRouter>,
)
it('opening pushes; Back closes it, Forward opens it again', async () => {
const user = userEvent.setup()
mountPage()
await user.click(screen.getByRole('button', { name: 'open' }))
expect(layer()).toEqual({ id: 'a1' })
expect(entry().view.annotation).toEqual({ id: 'a1' })
expect(entry().below?.annotation).toBeNull()
act(() => navigate(-1))
expect(layer()).toBeNull()
act(() => navigate(1))
expect(layer()).toEqual({ id: 'a1' })
})
it('a user close goes back to the drawing entry below', async () => {
const user = userEvent.setup()
mountPage()
await user.click(screen.getByRole('button', { name: 'open' }))
await user.click(screen.getByRole('button', { name: 'close' }))
await waitFor(() => expect(entry().view.annotation).toBeNull())
expect(layer()).toBeNull()
})
it('a dirty form keeps the dialog on a Back: its view is pushed again', async () => {
const user = userEvent.setup()
mountPage(true)
await user.click(screen.getByRole('button', { name: 'guard' }))
await user.click(screen.getByRole('button', { name: 'open' }))
act(() => navigate(-1))
expect(layer()).toEqual({ id: 'a1' })
expect(entry().view.annotation).toEqual({ id: 'a1' })
})
})
@@ -247,7 +247,8 @@ describe('findings and canvas state across a tab change', () => {
await user.click(tab('Général'))
await user.click(tab('Annotations'))
await stillSelected()
expect(drawing.getByTestId('annotation-properties')).toBeVisible()
// U2 Task 6: the selection's strip offers its properties (the panel left the column).
expect(drawing.getByRole('button', { name: 'Propriétés' })).toBeVisible()
})
it('the unmeasured hint opens the views section and « Retour au dessin » restores the same canvas', async () => {
@@ -343,3 +343,42 @@ describe('final review', () => {
expect(state.reference).toBeNull()
})
})
/** U2 Task 6: the annotation properties dialog is a layer of the drawing. */
describe('the annotation layer', () => {
it('open_annotation shows the dialog over the drawing, close_annotation takes it away', () => {
const base = run(initialNavigation('general'), {
type: 'open_section',
section: 'views',
})
const opened = run(base, { type: 'open_annotation', id: 'a1' })
expect(opened.tab).toBe('annotations')
expect(opened.section).toBe('drawing')
expect(opened.annotation).toEqual({ id: 'a1' })
expect(viewOf(opened).annotation).toEqual({ id: 'a1' })
expect(run(opened, { type: 'close_annotation' }).annotation).toBeNull()
})
it('every move away from the drawing leaves it: a tab, a section, « Aller à »', () => {
const opened = run(initialNavigation('annotations'), {
type: 'open_annotation',
id: 'a1',
})
const moves = [
{ type: 'select_tab', tab: 'general' },
{ type: 'open_section', section: 'views' },
{ type: 'go_to', target: targetOfKey({ kind: 'sheet' }) },
{ type: 'open_finding', key: finding },
{ type: 'show_all_references', filter: finding },
] as const
for (const move of moves) expect(run(opened, move).annotation).toBeNull()
})
it('restore_view puts it back', () => {
const base = initialNavigation('annotations')
const view = { ...viewOf(base), annotation: { id: 'a2' } }
expect(run(base, { type: 'restore_view', view }).annotation).toEqual({
id: 'a2',
})
})
})
+13 -6
View File
@@ -432,10 +432,18 @@ describe('ids stay unique', () => {
.find((candidate) => !candidate.closest('[hidden]'))!
await user.click(within(twin).getAllByRole('button')[0])
expect(duplicateIds()).toEqual([])
expect(document.getElementById('ro-annotation-name-fr')).not.toBeNull()
expect(document.getElementById('annotation-name-fr')).not.toBeNull()
expect(screen.getByTestId('annotation-read')).toBeInTheDocument()
cross(1280)
expect(duplicateIds()).toEqual([])
// The properties dialog's edit form, kept through a flip (R-14): its own ids.
await user.click(screen.getByRole('button', { name: 'Propriétés' }))
const dialog = await screen.findByRole('dialog')
await user.click(within(dialog).getByRole('button', { name: 'Modifier' }))
expect(document.getElementById('annotation-edit-fr')).not.toBeNull()
expect(duplicateIds()).toEqual([])
cross(800)
expect(document.getElementById('annotation-edit-fr')).not.toBeNull()
expect(duplicateIds()).toEqual([])
})
})
@@ -459,11 +467,10 @@ describe('focus requests', () => {
[...document.querySelectorAll(`[data-testid="${id}"]`)].filter(
(element) => !element.closest('[hidden]'),
)
await waitFor(() =>
expect(visible('annotation-properties')).toHaveLength(1),
)
// Below 1 024 px the twin reads it inline (R-16; U2 Task 6: no properties panel).
await waitFor(() => expect(visible('annotation-read')).toHaveLength(1))
cross(1280)
expect(visible('annotation-properties')).toHaveLength(0)
expect(visible('annotation-read')).toHaveLength(0)
expect(visible('annotation-overview')).toHaveLength(1)
})
})
+7 -9
View File
@@ -129,17 +129,17 @@ describe.each([
).toBeInTheDocument()
})
it('a row selects the annotation; « Toutes les annotations » returns with focus on its row', async () => {
it('a row selects the annotation and stays marked (A3); « Désélectionner » focuses its row', async () => {
await mount(readOnly)
const user = userEvent.setup()
await user.click(rows()[1])
expect(
await within(body()).findByTestId('annotation-properties'),
).toBeVisible()
await user.click(
screen.getByRole('button', { name: 'Toutes les annotations' }),
await waitFor(() =>
expect(rows()[1]).toHaveAttribute('aria-current', 'true'),
)
expect(overview()).toBeVisible()
expect(within(body()).queryByRole('dialog')).toBeNull()
await user.click(screen.getByRole('button', { name: 'Désélectionner' }))
expect(rows()[1]).not.toHaveAttribute('aria-current')
await waitFor(() => expect(document.activeElement).toBe(rows()[1]))
})
@@ -150,9 +150,7 @@ describe.each([
within(overview()).getByRole('searchbox', { name: 'Filtrer par nom' })
await user.type(field(), 'epaule')
await user.click(rows()[0])
await user.click(
screen.getByRole('button', { name: 'Toutes les annotations' }),
)
await user.click(screen.getByRole('button', { name: 'Désélectionner' }))
expect(field()).toHaveValue('epaule')
expect(rows()).toHaveLength(1)
expect(rows()[0]).toHaveTextContent('Épaule')
+16 -10
View File
@@ -167,7 +167,9 @@ async function select(index = 0) {
name: 'Annotations de la vue',
})
await userEvent.setup().click(within(list).getAllByRole('button')[index])
return screen.findByTestId('annotation-properties')
// U2 Task 6: a row selects only (A1); the strip holds the selection's commands.
await screen.findByRole('button', { name: 'Propriétés' })
return screen.getByTestId('edit-strip')
}
const slider = () =>
@@ -316,7 +318,9 @@ describe('the move mode (A11, R-12, R-13)', () => {
fireEvent.keyDown(arrow('la droite'), { key: 'Escape' })
expect(useAnnotationWork.getState().mode).toBeNull()
expect(screen.queryByTestId('move-mode-bar')).toBeNull()
expect(screen.getByTestId('annotation-properties')).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Propriétés' }),
).toBeInTheDocument()
})
it('a click on another annotation selects nothing during the mode', async () => {
@@ -480,15 +484,17 @@ describe('review fixes: no silent loss, no empty commit, no lost focus', () => {
}
const question = () => useAnnotationWork.getState().question?.work ?? null
it('« Toutes les annotations », a tool and « Ajouter un point » ask first', async () => {
it('Enter on the selected row, a tool and « Ajouter un point » ask first', async () => {
await started()
const panel = screen.getByTestId('annotation-properties')
fireEvent.click(
within(panel).getByRole('button', { name: 'Toutes les annotations' }),
)
// During the mode the strip offers only its exits (U2 Task 6: no « Propriétés »).
expect(screen.queryByRole('button', { name: 'Propriétés' })).toBeNull()
expect(screen.queryByRole('button', { name: 'Désélectionner' })).toBeNull()
const list = screen.getByRole('list', { name: 'Annotations de la vue' })
const row = within(list).getByRole('button', { current: true })
fireEvent.keyDown(row, { key: 'Enter' })
expect(question()).toBe('move')
expect(useAnnotationWork.getState().mode?.started).toBe(true)
expect(screen.getByTestId('annotation-properties')).toBeInTheDocument()
expect(screen.queryByRole('dialog')).toBeNull()
act(() => useAnnotationWork.setState({ question: null }))
fireEvent.click(screen.getByRole('button', { name: 'Point' }))
expect(question()).toBe('move')
@@ -526,12 +532,12 @@ describe('review fixes: no silent loss, no empty commit, no lost focus', () => {
await select()
handle().focus()
fireEvent.keyDown(handle(), { key: 'Escape' })
expect(screen.queryByTestId('annotation-properties')).toBeNull()
expect(screen.queryByRole('button', { name: 'Propriétés' })).toBeNull()
expect(document.activeElement).not.toBe(document.body)
await select()
slider().focus()
fireEvent.keyDown(slider(), { key: 'Escape' })
expect(screen.queryByTestId('annotation-properties')).toBeNull()
expect(screen.queryByRole('button', { name: 'Propriétés' })).toBeNull()
expect(document.activeElement).not.toBe(document.body)
})
+6 -3
View File
@@ -267,7 +267,7 @@ describe('« Aller à » an annotation while something is in progress', () => {
expect(announce).toHaveBeenCalledWith(
expect.stringContaining('création est en cours'),
)
expect(screen.queryByTestId('annotation-properties')).toBeNull()
expect(screen.queryByRole('button', { name: 'Propriétés' })).toBeNull()
})
it('an open zone tracing is kept: the strip tracing commands take the focus', async () => {
@@ -285,11 +285,14 @@ describe('« Aller à » an annotation while something is in progress', () => {
)
})
it('with nothing in progress the annotation is selected and its heading focused', async () => {
it('with nothing in progress the annotation is selected and its row focused (R-5)', async () => {
const { consumed } = await withProgress(async () => undefined)
await waitFor(() => expect(consumed).toHaveBeenCalledWith(7, 'found'))
await waitFor(() =>
expect(document.activeElement).toHaveAttribute('data-properties-heading'),
expect(document.activeElement).toHaveAttribute(
'data-focus-key',
JSON.stringify({ kind: 'annotation', id: 'anno-a' }),
),
)
})
})
@@ -116,7 +116,9 @@ async function select(index = 0) {
name: 'Annotations de la vue',
})
await userEvent.setup().click(within(list).getAllByRole('button')[index])
return screen.findByTestId('annotation-properties')
// U2 Task 6: a row selects only (A1); the strip holds the selection's commands.
await screen.findByRole('button', { name: 'Propriétés' })
return screen.getByTestId('edit-strip')
}
const mouse = {
@@ -737,7 +739,7 @@ describe('I-3: the click a touch tap synthesises is absorbed', () => {
await mount(squareText())
await select()
tapOn(screen.getByTestId('annotation-canvas'), 'touch')
expect(screen.queryByTestId('annotation-properties')).toBeNull()
expect(screen.queryByRole('button', { name: 'Propriétés' })).toBeNull()
clickAtTap(addPoint())
expect(creation()).toBeNull()
clickAtTap(addPoint())
+97
View File
@@ -234,3 +234,100 @@ describe('Dialog focus return', () => {
expect(screen.getByRole('button', { name: 'Sibling' })).toHaveFocus()
})
})
/** U2 Task 6 (A2, R-6): the panel over an anchor box, the keyboard fallback, the veil. */
describe('Dialog anchored over a column', () => {
const rect = (box: Partial<DOMRect>) =>
({ left: 0, top: 0, width: 0, height: 0, ...box }) as DOMRect
function anchorAt(box: Partial<DOMRect>) {
const element = document.createElement('aside')
element.getBoundingClientRect = () => rect(box)
document.body.append(element)
return { current: element }
}
const panel = () => screen.getByTestId('dialog-panel')
const withViewport = (value: unknown) =>
Object.defineProperty(window, 'visualViewport', {
configurable: true,
value,
})
it('sits at the anchor’s left and width, from its top, down to 12 px above the bottom', () => {
withViewport(undefined)
window.innerHeight = 800
const anchor = anchorAt({ left: 900, top: 140, width: 352 })
render(
<Dialog open anchor={anchor} onClose={() => {}} title="X">
body
</Dialog>,
)
expect(panel().style.left).toBe('900px')
expect(panel().style.width).toBe('352px')
expect(panel().style.top).toBe('140px')
expect(panel().style.maxHeight).toBe('648px')
})
it('never starts above 12 px when the column’s top is scrolled away', () => {
withViewport(undefined)
window.innerHeight = 800
const anchor = anchorAt({ left: 900, top: -300, width: 352 })
render(
<Dialog open anchor={anchor} onClose={() => {}} title="X">
body
</Dialog>,
)
expect(panel().style.top).toBe('12px')
expect(panel().style.maxHeight).toBe('776px')
})
it('a tablet keyboard leaving under 320 px: the visual viewport’s top and height', () => {
window.innerHeight = 800
withViewport({
height: 350,
offsetTop: 0,
addEventListener: () => undefined,
removeEventListener: () => undefined,
})
const anchor = anchorAt({ left: 900, top: 140, width: 352 })
render(
<Dialog open anchor={anchor} onClose={() => {}} title="X">
body
</Dialog>,
)
expect(panel().style.top).toBe('12px')
expect(panel().style.height).toBe('326px')
expect(panel().style.left).toBe('900px')
withViewport(undefined)
})
it('without an anchor box the panel is centred, as before', () => {
render(
<Dialog open anchor={{ current: null }} onClose={() => {}} title="X">
body
</Dialog>,
)
expect(panel().style.left).toBe('')
expect(panel().className).toContain('max-w-md')
})
it('the veil of an anchored dialog ignores clicks; a centred one still asks', async () => {
withViewport(undefined)
const onClose = vi.fn()
const anchor = anchorAt({ left: 900, top: 140, width: 352 })
const { unmount } = render(
<Dialog open anchor={anchor} onClose={onClose} title="X">
body
</Dialog>,
)
await userEvent.click(screen.getByTestId('dialog-backdrop'))
expect(onClose).not.toHaveBeenCalled()
unmount()
render(
<Dialog open onClose={onClose} title="X">
body
</Dialog>,
)
await userEvent.click(screen.getByTestId('dialog-backdrop'))
expect(onClose).toHaveBeenCalled()
})
})