feat(editor): resumed trace edits the closed shape with its handles

« Reprendre le tracé » keeps the pending shape closed; the zone handles
(vertex, « + », « − », vertex keys) edit it through the same press path
and useZoneEdit, the target generalised to points + drop. A drop on
PENDING_ID patches creation.pending only: document, history and unsaved
count untouched, message without « Défaire ». Strip: « Tracé repris,
saisie gardée » with « Revenir aux propriétés » and « Abandonner ».
Handle names fall back to « la nouvelle zone » / « le nouvel accès ».

Removed (resumed branch of popVertex, backToProperties -> closeTrace,
CreationCommands tracedCount and its « Retirer le dernier sommet »).

Removed assertions, editor-creation-dialog.test.tsx, « keeps the
vertices and the form; a new vertex, then the dialog again »:
- strip « Tracé repris, saisie gardée » -> kept in « keeps the shape
  closed and the form, shows its handles; two strip commands »
- « Retirer le dernier sommet » enabled -> absent; commands are exactly
  « Revenir aux propriétés », « Abandonner » (same test)
- a click on the drawing adds a 4th vertex -> « a click off the handles
  adds and selects nothing; a double « + » inserts once »
- dialog again with Nom (FR) « Tibia » -> « « Revenir aux propriétés »
  shows the edited shape; « Créer » inserts it »
- « Zone tracée, 4 sommets » -> « Zone tracée, 5 sommets » after « + »
  (same test)
This commit is contained in:
bchanot committed 2026-11-19 09:42:58 +01:00
1 parent 816d0f4f9a
commit a5896710e5
17 files changed
+677 -116

No files matched your search

@@ -746,4 +746,118 @@ test.describe('editor annotations (A3)', () => {
expect(await gutter()).toBe('auto') expect(await gutter()).toBe('auto')
}) })
}) })
// Rev 4 point 3 (board 04 C, criterion 27): « Reprendre le tracé » edits the closed shape
// with its handles; the document and the history wait for « Créer ».
test('a resumed trace is edited with its handles, then created in one step', async ({
page,
requests,
}) => {
await page.setViewportSize({ width: 1280, height: 800 })
const { actor } = await openAnnotations(page)
requests.forbid(actor.account.email, actor.account.password)
const line = page.getByTestId('gesture-line')
const strip = page.getByTestId('edit-strip')
const ghostPoints = async () =>
(
(await page
.getByTestId('overlay-ghost')
.locator('polygon')
.first()
.getAttribute('points')) ?? ''
)
.trim()
.split(/\s+/)
.map((pair) => pair.split(',').map(Number))
const handle = (name: string) =>
page.getByRole('button', { name, exact: true })
const button = (_page: Page, key: string) => handle(dict[key])
const pressHandle = async (name: string) => {
const box = (await handle(name).locator('[data-handle]').boundingBox())!
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2)
}
await tool(page, 'zone').click()
for (const [x, y] of [
[200, 150],
[450, 150],
[500, 350],
[350, 450],
[150, 350],
])
await clickDrawing(page, x, y)
await button(page, 'editor.annotations.trace_close').click()
await expect(creationDialog(page, 'zone')).toBeVisible()
await creation(page)
.getByLabel(dict['editor.annotations.name_fr'])
.fill('Tibia')
const saved = await saveLine(page).textContent()
await expectNoShift(page, async () => {
await creationDialog(page, 'zone')
.getByRole('button', {
name: dict['editor.annotations.creation.resume'],
})
.click()
await expect(creationDialog(page, 'zone')).toHaveCount(0)
await expect(handle('Sommet 1 de Tibia')).toBeAttached()
})
await expect(strip).toContainText(dict['editor.annotations.strip.resumed'])
await expect(
strip.getByRole('button', { name: dict['editor.annotations.trace_pop'] }),
).toHaveCount(0)
await expect(
page.getByRole('group', { name: 'Sommets de Tibia', exact: true }),
).toBeAttached()
await expectAccessible(page, 'a resumed trace with its handles')
// A vertex dragged: the ghost changes, said without « Défaire »; nothing else moves.
const from = await clientOf(page, 450, 150)
const to = await clientOf(page, 480, 110)
await page.mouse.move(from.x, from.y)
await page.mouse.down()
await page.mouse.move(to.x, to.y, { steps: 6 })
await page.mouse.up()
await expect(line).toContainText(
dict['editor.annotations.message.vertex_moved'],
)
await expect(
line.getByRole('button', { name: dict['editor.history.undo_title'] }),
).toHaveCount(0)
const [, moved] = await ghostPoints()
expect(Math.abs(moved[0] - 480)).toBeLessThan(3)
expect(Math.abs(moved[1] - 110)).toBeLessThan(3)
// « + » then « − »: six vertices, then five again; the document never changed.
await pressHandle('Ajouter un sommet après le sommet 1 de Tibia')
await expect.poll(async () => (await ghostPoints()).length).toBe(6)
await expect(line).toContainText(
dict['editor.annotations.message.vertex_added'],
)
await pressHandle('Sommet 4 de Tibia')
await pressHandle('Retirer le sommet 4 de Tibia')
await expect.poll(async () => (await ghostPoints()).length).toBe(5)
await expect(saveLine(page)).toHaveText(saved ?? '')
await expect(historyButton(page, dict, 'undo')).toHaveAttribute(
'aria-disabled',
'true',
)
const edited = await ghostPoints()
await expectNoShift(page, async () => {
await button(page, 'editor.annotations.back_to_properties').click()
await expect(creationDialog(page, 'zone')).toBeVisible()
})
await expect(
creation(page).getByLabel(dict['editor.annotations.name_fr']),
).toHaveValue('Tibia')
await fillCreation(page, { fr: 'Tibia', en: 'Tibia' })
await createFromPanel(page)
await expect(selectionTag(page)).toContainText('Tibia')
expect(await shownPoints(page)).toEqual(edited)
// One step: a single undo removes the whole new zone.
const rows = list(page).getByRole('button')
await expect(rows.filter({ hasText: 'Tibia' })).toHaveCount(1)
await historyButton(page, dict, 'undo').click()
await expect(rows.filter({ hasText: 'Tibia' })).toHaveCount(0)
})
}) })
+113
View File
@@ -3,6 +3,7 @@ import type { CDPSession, Page, TestInfo } from '@playwright/test'
import { expect, test } from '../support/browser' import { expect, test } from '../support/browser'
import { dropLateReplays, routeToSandbox } from '../support/sandbox' import { dropLateReplays, routeToSandbox } from '../support/sandbox'
import { import {
annotationList,
clientOf, clientOf,
creationPanel, creationPanel,
editorActor, editorActor,
@@ -438,3 +439,115 @@ for (const width of WIDTHS) {
}) })
}) })
} }
// Rev 4 point 3 (board 04 C, criterion 27): a resumed trace edited by finger at 1 180 px.
test.describe('a resumed trace by finger at 1 180 px (rev 4)', () => {
test.use({
locale: 'fr-FR',
actionTimeout: 15_000,
hasTouch: true,
viewport: { width: 1180, height: 800 },
})
test.beforeEach(async ({ context }, info) => {
test.skip(isPhone(info), 'editing needs 1 024 px') // floor-guard: allow C16 editing needs >= 1024 px; phone read-only covered in editor-access
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
const ghostPoints = async (page: Page) =>
(
(await page
.getByTestId('overlay-ghost')
.locator('polygon')
.first()
.getAttribute('points')) ?? ''
)
.trim()
.split(/\s+/)
.map((pair) => pair.split(',').map(Number))
const centreOf = async (page: Page, name: string) => {
const hit = page
.getByRole('button', { name, exact: true })
.locator('[data-handle]')
const box = (await hit.boundingBox())!
return { x: box.x + box.width / 2, y: box.y + box.height / 2 }
}
test('drag with the loupe, « + », « − », back, « Créer »: one undo removes it', async ({
page,
context,
requests,
}) => {
const { actor } = await open(page)
requests.forbid(actor.account.email, actor.account.password)
const cdp = await context.newCDPSession(page)
await toolButton(page, dict, 'zone').click()
await canvas(page).scrollIntoViewIfNeeded()
// Quick taps, each within the absorber's 400 ms of the last: each one places.
for (const [x, y] of [
[100, 100],
[260, 90],
[270, 250],
[180, 300],
[80, 230],
])
await tap(cdp, await clientOf(page, x, y))
await button(page, 'editor.annotations.trace_close').click()
await expect(creationPanel(page)).toBeVisible()
await creationPanel(page)
.getByLabel(dict['editor.annotations.name_fr'])
.fill('Tibia')
await expectNoShift(page, async () => {
await button(page, 'editor.annotations.creation.resume').click()
await expect(creationPanel(page)).toHaveCount(0)
})
await expectFingerSizedHandles(page)
const undoHeld = historyButton(page, dict, 'undo')
await expect(undoHeld).toHaveAttribute('aria-disabled', 'true')
await canvas(page).scrollIntoViewIfNeeded()
const from = await clientOf(page, 260, 90)
await dragWithLoupe(page, cdp, from, { x: from.x + 30, y: from.y + 30 })
await expect(message(page)).toContainText(
dict['editor.annotations.message.vertex_moved'],
)
expect((await ghostPoints(page))[1]).not.toEqual([260, 90])
await tap(
cdp,
await centreOf(page, 'Ajouter un sommet après le sommet 1 de Tibia'),
)
await expect.poll(async () => (await ghostPoints(page)).length).toBe(6)
await tap(cdp, await centreOf(page, 'Sommet 4 de Tibia'))
await tap(cdp, await centreOf(page, 'Retirer le sommet 4 de Tibia'))
await expect.poll(async () => (await ghostPoints(page)).length).toBe(5)
await expect(undoHeld).toHaveAttribute('aria-disabled', 'true')
const edited = await ghostPoints(page)
await expectNoShift(page, async () => {
await button(page, 'editor.annotations.back_to_properties').click()
await expect(creationPanel(page)).toBeVisible()
})
const panel = creationPanel(page)
await expect(
panel.getByLabel(dict['editor.annotations.name_fr']),
).toHaveValue('Tibia')
await panel.getByLabel(dict['editor.annotations.name_en']).fill('Tibia')
await panel
.getByLabel(dict['editor.annotations.laterality'])
.selectOption('unpaired')
await panel
.getByRole('button', { name: dict['editor.annotations.create'] })
.click()
await expect(creationPanel(page)).toHaveCount(0)
await expect(selectionTag(page)).toContainText('Tibia')
expect(await shownPoints(page)).toEqual(edited)
// One step: a single undo removes the whole new zone.
const rows = annotationList(page, dict).getByRole('button')
await expect(rows.filter({ hasText: 'Tibia' })).toHaveCount(1)
await historyButton(page, dict, 'undo').click()
await expect(rows.filter({ hasText: 'Tibia' })).toHaveCount(0)
})
})
@@ -1,26 +1,18 @@
import Button from '@/components/ui/Button' import Button from '@/components/ui/Button'
import { askCreation } from '@/editor/annotations/creationAsk' import { askCreation } from '@/editor/annotations/creationAsk'
import { backToProperties, popVertex } from '@/editor/annotations/creationWork' import { backToProperties } from '@/editor/annotations/creationWork'
import type { Creation } from '@/editor/annotations/workStore'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
import EditorGlyph from '../EditorGlyph' import EditorGlyph from '../EditorGlyph'
const COMMAND = 'min-h-11 gap-1.5 xl:min-h-9' const COMMAND = 'min-h-11 gap-1.5 xl:min-h-9'
/** The vertices a resumed tracing holds now; null for a point. */
const tracedCount = (work: Creation) =>
!work.closed && work.pending.geometry.type === 'polygon'
? work.pending.geometry.points.length
: null
/** /**
* Board 04 C: the dialog hidden by « Replacer le point » or « Reprendre le tracé ». « Revenir * Board 04 C: the dialog hidden by « Replacer le point » or « Reprendre le tracé ». « Revenir
* aux propriétés » shows it again (a tracing closes first, three vertices at least); * aux propriétés » shows it again with the shape as it is now (a resumed trace stays closed:
* « Abandonner » asks first, the shape always exists (A12). * its handles edit it); « Abandonner » asks first, the shape always exists (A12).
*/ */
export default function CreationCommands({ creation }: { creation: Creation }) { export default function CreationCommands() {
const t = useT() const t = useT()
const count = tracedCount(creation)
return ( return (
<div <div
tabIndex={-1} tabIndex={-1}
@@ -33,24 +25,11 @@ export default function CreationCommands({ creation }: { creation: Creation }) {
type="button" type="button"
size="sm" size="sm"
className={COMMAND} className={COMMAND}
disabled={count !== null && count < 3} onClick={backToProperties}
onClick={() => backToProperties()}
> >
<EditorGlyph name="properties" size={16} /> <EditorGlyph name="properties" size={16} />
{t('editor.annotations.back_to_properties')} {t('editor.annotations.back_to_properties')}
</Button> </Button>
{count !== null && (
<Button
type="button"
size="sm"
variant="secondary"
className={COMMAND}
disabled={count === 0}
onClick={popVertex}
>
{t('editor.annotations.trace_pop')}
</Button>
)}
<Button <Button
type="button" type="button"
size="sm" size="sm"
@@ -13,6 +13,7 @@ import {
} from '@/editor/annotations/creationWork' } from '@/editor/annotations/creationWork'
import { useCreationFollow } from '@/editor/annotations/useCreationFollow' import { useCreationFollow } from '@/editor/annotations/useCreationFollow'
import { import {
PENDING_ID,
useAnnotationWork, useAnnotationWork,
type Creation, type Creation,
} from '@/editor/annotations/workStore' } from '@/editor/annotations/workStore'
@@ -20,7 +21,7 @@ import { parseFrame, type Frame } from '@/editor/annotations/frame'
import { newPointSize } from '@/editor/annotations/pointSize' import { newPointSize } from '@/editor/annotations/pointSize'
import { guardDrawing } from '@/editor/annotations/drawingGuard' import { guardDrawing } from '@/editor/annotations/drawingGuard'
import { usePointEdit } from '@/editor/annotations/usePointEdit' import { usePointEdit } from '@/editor/annotations/usePointEdit'
import { useZoneEdit } from '@/editor/annotations/useZoneEdit' import { useZoneEdit, type ZoneTarget } from '@/editor/annotations/useZoneEdit'
import { useRedrawFollowsTracing } from '@/editor/annotations/redraw' import { useRedrawFollowsTracing } from '@/editor/annotations/redraw'
import { import {
useDroppedNotice, useDroppedNotice,
@@ -55,6 +56,7 @@ import {
import type { AnnotationSection } from '@/editor/navigation' import type { AnnotationSection } from '@/editor/navigation'
import { usePlaceVisible } from '@/lib/placeVisibility' import { usePlaceVisible } from '@/lib/placeVisibility'
import type { EditorPlaceProps } from '@/editor/tabs' import type { EditorPlaceProps } from '@/editor/tabs'
import type { Locale } from '@/i18n/types'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore' import { useLocaleStore } from '@/state/localeStore'
import AnnotationCanvas from './AnnotationCanvas' import AnnotationCanvas from './AnnotationCanvas'
@@ -116,10 +118,9 @@ function useViewFallback(
} }
/** « Aller à » an annotation: the request, with what it needs of the drawing's state. */ /** « Aller à » an annotation: the request, with what it needs of the drawing's state. */
/** A fresh tracing reads as a tracing; a placed, closed or resumed shape as a creation. */ /** A fresh tracing reads as a tracing; a placed or closed shape (resumed too) as a creation. */
function busyOf(creation: Creation | null, ui: UiState) { function busyOf(creation: Creation | null, ui: UiState) {
if (creation) if (creation) return creation.closed ? 'creation' : 'tracing'
return creation.closed || creation.resumed ? 'creation' : 'tracing'
return ui.tracing ? 'tracing' : null return ui.tracing ? 'tracing' : null
} }
@@ -192,10 +193,21 @@ function useCommitContext(): CommitContext {
return { t, locale } return { t, locale }
} }
/**
* The resumed creation's closed polygon (« Reprendre le tracé », board 04 C) while its
* handles edit it: the dialog hidden, the view measured, as a selected zone needs.
*/
function resumedOf({ creation, model }: Scene): ZoneTarget | null {
if (!creation?.resumed || creation.dialog || !model.measured) return null
const { geometry } = creation.pending
return geometry.type === 'polygon' ? { id: PENDING_ID, geometry } : null
}
/** /**
* The tab's work: the commit context, the line under the drawing, the placement, the * The tab's work: the commit context, the line under the drawing, the placement, the
* editing of the movable selection (point handle keys, slider, move mode) and of a * editing of the movable selection (point handle keys, slider, move mode) and of a
* polygon's vertices, the redraw kept in step with its tracing. * polygon's vertices (the selection's, or the resumed creation's shape), the redraw kept
* in step with its tracing.
*/ */
function useWork(scene: Scene) { function useWork(scene: Scene) {
const context = useCommitContext() const context = useCommitContext()
@@ -203,11 +215,13 @@ function useWork(scene: Scene) {
const placement = usePlacement({ ...scene, context, message }) const placement = usePlacement({ ...scene, context, message })
useCreationFollow({ ...scene, message, t: context.t }) useCreationFollow({ ...scene, message, t: context.t })
const target = movableOf(scene.selected, scene.model, scene.ui.tool) const target = movableOf(scene.selected, scene.model, scene.ui.tool)
const resumed = resumedOf(scene)
// One drop for both: a pending shape's change is routed to the creation by its id.
const onDrop = placement.onDrop const onDrop = placement.onDrop
const edit = usePointEdit({ target, frame: scene.frame, onDrop }) const edit = usePointEdit({ target, frame: scene.frame, onDrop })
const polygon = target?.geometry?.type === 'polygon' ? target : null const polygon = target?.geometry?.type === 'polygon' ? target : null
const zone = useZoneEdit({ const zone = useZoneEdit({
...{ target: polygon, frame: scene.frame, onDrop, message }, ...{ target: resumed ?? polygon, frame: scene.frame, onDrop, message },
t: context.t, t: context.t,
confirmMove: edit.confirmMove, confirmMove: edit.confirmMove,
}) })
@@ -222,6 +236,7 @@ function useWork(scene: Scene) {
edit, edit,
zone, zone,
target, target,
resumed,
insertsHidden, insertsHidden,
setInsertsHidden, setInsertsHidden,
} }
@@ -310,6 +325,54 @@ function useHandle(target: Annotation | null, doc: AnatomicalSheetDocument) {
} }
} }
/** The resumed shape's name: the form's in the current locale, else « la nouvelle zone ». */
function pendingName(
creation: Creation,
locale: Locale,
t: (key: string) => string,
): string {
const typed = creation.form[locale].trim()
return (
typed || t(`editor.annotations.handle.unnamed.${creation.pending.kind}`)
)
}
/** The polygon whose handles the layer draws: the resumed shape, else the selection. */
function useZoneHandle(scene: Scene, work: Work, shown: boolean) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const { resumed, target } = work
const points = shown
? handledPoints((resumed ?? target)?.geometry ?? null)
: null
if (!points) return null
if (resumed && scene.creation) {
const name = pendingName(scene.creation, locale, t)
return { annotationId: PENDING_ID, name, points }
}
const name = annotationName(target!, scene.doc.views, locale)
return { annotationId: target!.id, name, points }
}
/**
* What the press machine works on: the selection with its tool, or, for a resumed shape,
* its handles as a selection's (a click off them adds no vertex and selects nothing).
*/
function pressSubject({ ui, model, selected, creation }: Scene, work: Work) {
const { resumed } = work
if (!resumed?.geometry || !creation) {
const moveTarget = moveTargetOf(selected, model, ui.tool)
return { tool: ui.tool, selectedId: ui.selectedId, moveTarget }
}
const { kind } = creation.pending
const moveTarget = {
id: PENDING_ID,
kind,
geometry: creation.pending.geometry,
}
return { tool: 'select' as const, selectedId: PENDING_ID, moveTarget }
}
function CanvasStage({ function CanvasStage({
scene, scene,
work, work,
@@ -322,16 +385,12 @@ function CanvasStage({
const locale = useLocaleStore((s) => s.locale) const locale = useLocaleStore((s) => s.locale)
// Hidden (the editor is read-only): no drag in flight survives, none is committed. // Hidden (the editor is read-only): no drag in flight survives, none is committed.
const shown = usePlaceVisible() const shown = usePlaceVisible()
const { doc, ui, dispatch, model, selected, creation } = scene const { doc, ui, dispatch, model, creation } = scene
const handle = useHandle(shown ? work.target : null, doc) const handle = useHandle(shown ? work.target : null, doc)
// A12: during a creation nothing else is selected or opened from the drawing. // A12: during a creation nothing else is selected or opened from the drawing.
const free = creation === null const free = creation === null
const points = shown ? handledPoints(work.target?.geometry ?? null) : null const zone = useZoneHandle(scene, work, shown)
const zone = points && { const subject = pressSubject(scene, work)
annotationId: work.target!.id,
name: annotationName(work.target!, doc.views, locale),
points,
}
const view = doc.views.find((v) => v.id === scene.viewId) const view = doc.views.find((v) => v.id === scene.viewId)
const blocked = !model.measured || doc.categories.length === 0 const blocked = !model.measured || doc.categories.length === 0
if (!view) return null if (!view) return null
@@ -339,11 +398,11 @@ function CanvasStage({
<AnnotationCanvas <AnnotationCanvas
viewId={scene.viewId} viewId={scene.viewId}
viewName={view.name[locale]} viewName={view.name[locale]}
tool={ui.tool} tool={subject.tool}
selectedId={ui.selectedId} selectedId={subject.selectedId}
previewRadius={previewRadiusOf(scene)} previewRadius={previewRadiusOf(scene)}
creating={!free} creating={!free}
moveTarget={shown ? moveTargetOf(selected, model, ui.tool) : null} moveTarget={shown ? subject.moveTarget : null}
overlay={overlayOf(scene, work.message.message?.place)} overlay={overlayOf(scene, work.message.message?.place)}
handles={{ handles={{
handle, handle,
@@ -92,8 +92,7 @@ function commandsKeyOf(
chosen: number | null, chosen: number | null,
) { ) {
if (creation?.dialog) return 'creation-dialog' if (creation?.dialog) return 'creation-dialog'
if (creation?.resumed) if (creation?.resumed) return `creation-${creation.pending.geometry.type}`
return `creation-${creation.closed ? 'point' : 'trace'}`
if (tracing) return 'tracing' if (tracing) return 'tracing'
if (moving) return 'move' if (moving) return 'move'
if (target?.geometry?.type === 'polygon') return `zone-${chosen !== null}` if (target?.geometry?.type === 'polygon') return `zone-${chosen !== null}`
@@ -155,7 +154,7 @@ function SceneCommands({
if (creation?.dialog) return null if (creation?.dialog) return null
if (creation?.resumed) { if (creation?.resumed) {
// A point being replaced: its size is still chosen here (board 02, R-10). // A point being replaced: its size is still chosen here (board 02, R-10).
const replacing = creation.closed && frame const replacing = creation.pending.geometry.type === 'circle' && frame
return ( return (
<> <>
{replacing && ( {replacing && (
@@ -167,7 +166,7 @@ function SceneCommands({
dispatch={dispatch} dispatch={dispatch}
/> />
)} )}
<CreationCommands creation={creation} /> <CreationCommands />
</> </>
) )
} }
+50 -21
View File
@@ -1,9 +1,13 @@
import type { Point } from '@faunosteo/core-wasm/types' import type { Point, Polygon } from '@faunosteo/core-wasm/types'
import type { CreationForm, NewKind, PendingElement } from './creation' import type { CreationForm, NewKind, PendingElement } from './creation'
import type { Correction } from './correction' import type { Correction } from './correction'
import type { Frame } from './frame' import type { Frame } from './frame'
import type { Tracing } from './uiState' import type { Tracing } from './uiState'
import { useAnnotationWork, type Creation } from './workStore' import {
choiceAfterCreation,
useAnnotationWork,
type Creation,
} from './workStore'
/** Where a creation starts: its view, F, how it began, and the form it starts with. */ /** Where a creation starts: its view, F, how it began, and the form it starts with. */
export interface CreationStart { export interface CreationStart {
@@ -69,8 +73,11 @@ export function traceVertex(
kind: NewKind, kind: NewKind,
point: Point, point: Point,
): void { ): void {
const points = tracedPoints(creation()) const work = creation()
const points = tracedPoints(work)
if (points) return patch({ pending: polygonOf(kind, [...points, point]) }) if (points) return patch({ pending: polygonOf(kind, [...points, point]) })
// A closed shape is edited by its handles: no click ever starts another over its form.
if (work?.closed) return
useAnnotationWork.setState({ useAnnotationWork.setState({
creation: { creation: {
...start, ...start,
@@ -82,13 +89,13 @@ export function traceVertex(
}) })
} }
/** Backspace or « Retirer le dernier sommet »; a fresh tracing left empty is no creation. */ /** Backspace or « Retirer le dernier sommet »; a tracing left empty is no creation. */
export function popVertex(): void { export function popVertex(): void {
const work = creation() const work = creation()
const points = tracedPoints(work) const points = tracedPoints(work)
if (!work || !points) return if (!work || !points) return
const left = points.slice(0, -1) const left = points.slice(0, -1)
if (left.length === 0 && !work.resumed) return dropCreation() if (left.length === 0) return dropCreation()
patch({ pending: polygonOf(work.pending.kind, left) }) patch({ pending: polygonOf(work.pending.kind, left) })
} }
@@ -100,10 +107,32 @@ export function closeTrace(): boolean {
return true return true
} }
/** « Reprendre le tracé »: the dialog hides, the vertices and the form are kept. */ /**
* « Reprendre le tracé » (board 04 C): the dialog hides, the form is kept, and the closed
* shape is edited with its handles; no vertex is chosen yet.
*/
export function resumeTrace(): void { export function resumeTrace(): void {
useAnnotationWork.setState({ question: lapsed() }) const { chosen } = useAnnotationWork.getState()
patch({ closed: false, dialog: false, resumed: true }) useAnnotationWork.setState({
question: lapsed(),
chosen: choiceAfterCreation(chosen),
})
patch({ dialog: false, resumed: true })
}
/**
* A handle change of the resumed shape (a drag, « + », « − », a vertex key): only
* `creation.pending` changes, never the document nor the history (rev 4). The choice is
* dropped, as a commit's new text drops it on a stored zone: the caller chooses again.
*/
export function patchPendingShape(geometry: Polygon): boolean {
const work = creation()
if (!work?.closed || work.pending.geometry.type !== 'polygon') return false
useAnnotationWork.setState({
creation: { ...work, pending: { ...work.pending, geometry } },
chosen: null,
})
return true
} }
/** « Replacer le point »: the dialog hides; the next click moves the ghost. */ /** « Replacer le point »: the dialog hides; the next click moves the ghost. */
@@ -112,15 +141,9 @@ export function replacePoint(): void {
patch({ dialog: false, resumed: true }) patch({ dialog: false, resumed: true })
} }
/** « Revenir aux propriétés »: a resumed tracing closes again, a point shows its dialog. */ /** « Revenir aux propriétés »: the dialog again, with the shape as it is now. */
export function backToProperties(): boolean { export function backToProperties(): void {
const work = creation()
if (!work) return false
if (work.closed) {
patch({ dialog: true }) patch({ dialog: true })
return true
}
return closeTrace()
} }
export function patchForm(change: Partial<CreationForm>): void { export function patchForm(change: Partial<CreationForm>): void {
@@ -136,25 +159,31 @@ export function setCorrection(correction: Correction | null): void {
/** « Abandonner », or a guard's « Abandonner »: nothing of the creation is left. */ /** « Abandonner », or a guard's « Abandonner »: nothing of the creation is left. */
export function dropCreation(): void { export function dropCreation(): void {
useAnnotationWork.setState({ creation: null, question: lapsed() }) useAnnotationWork.setState((work) => ({
creation: null,
question: lapsed(),
chosen: choiceAfterCreation(work.chosen),
}))
} }
/** A document change removed the creation's view (R-13): dropped, and said by the tab. */ /** A document change removed the creation's view (R-13): dropped, and said by the tab. */
export function dropCreationGone(): void { export function dropCreationGone(): void {
useAnnotationWork.setState({ useAnnotationWork.setState((work) => ({
creation: null, creation: null,
question: lapsed(), question: lapsed(),
chosen: choiceAfterCreation(work.chosen),
dropped: 'creation', dropped: 'creation',
}) }))
} }
/** « Créer » succeeded: the creation ends, the drawing selects `id` (A7). */ /** « Créer » succeeded: the creation ends, the drawing selects `id` (A7). */
export function finishCreation(id: string, kind: NewKind): void { export function finishCreation(id: string, kind: NewKind): void {
useAnnotationWork.setState({ useAnnotationWork.setState((work) => ({
creation: null, creation: null,
created: { id, kind }, created: { id, kind },
question: lapsed(), question: lapsed(),
}) chosen: choiceAfterCreation(work.chosen),
}))
} }
/** The open tracing of a new shape on `viewId`, as the drawing reads a tracing. */ /** The open tracing of a new shape on `viewId`, as the drawing reads a tracing. */
@@ -1,4 +1,9 @@
import { endMode, guardWork, useAnnotationWork } from './workStore' import {
choiceAfterCreation,
endMode,
guardWork,
useAnnotationWork,
} from './workStore'
/** /**
* A keyboard series or a size change still pending (no blur yet: a mouse Back button) * A keyboard series or a size change still pending (no blur yet: a mouse Back button)
@@ -51,7 +56,10 @@ export function answerDrawing(discard: boolean): void {
useAnnotationWork.setState({ question: null }) useAnnotationWork.setState({ question: null })
if (!discard || !question) return if (!discard || !question) return
if (question.work === 'creation') if (question.work === 'creation')
useAnnotationWork.setState({ creation: null }) useAnnotationWork.setState((work) => ({
creation: null,
chosen: choiceAfterCreation(work.chosen),
}))
else endMode() else endMode()
question.proceed() question.proceed()
} }
+12 -12
View File
@@ -131,26 +131,26 @@ function pendingLead(pending: PendingElement, ctx: LeadContext): StripLead {
} }
} }
const HIDDEN_DETAIL = {
circle: 'editor.annotations.strip.place_point',
polygon: 'editor.annotations.strip.resumed',
} as const
/** /**
* A creation whose dialog is shown or was (board 04 C): placed or closed, waiting for its * A creation whose dialog is shown or was (board 04 C): placed or closed, waiting for its
* properties; a point being replaced says where to click; a resumed tracing says the * properties; with the dialog hidden, a point being replaced says where to click and a
* input is kept. A fresh tracing reads as a tracing. * resumed trace says the input is kept. A fresh tracing reads as a tracing.
*/ */
function creationLead(work: Creation, ctx: LeadContext): StripLead | null { function creationLead(work: Creation, ctx: LeadContext): StripLead | null {
const { pending } = work const { pending } = work
const title = ctx.t(`editor.annotations.new.${pending.kind}`) if (!work.closed) return null
const icon = ICON[pending.kind] if (work.dialog) return pendingLead(pending, ctx)
if (work.closed && !work.dialog && pending.geometry.type === 'circle') {
return { return {
title, title: ctx.t(`editor.annotations.new.${pending.kind}`),
detail: ctx.t('editor.annotations.strip.place_point'), detail: ctx.t(HIDDEN_DETAIL[pending.geometry.type]),
icon, icon: ICON[pending.kind],
} }
} }
if (work.closed) return pendingLead(pending, ctx)
if (!work.resumed) return null
return { title, detail: ctx.t('editor.annotations.strip.resumed'), icon }
}
const TOOL_LEAD: Record< const TOOL_LEAD: Record<
ToolId, ToolId,
@@ -25,8 +25,9 @@ export interface CreationFollow {
/** /**
* The drawing kept in step with the creation: nothing selected once its shape is placed, its tool * The drawing kept in step with the creation: nothing selected once its shape is placed, its tool
* on while the dialog is hidden (« Replacer le point » places with the point tool, a * on while the dialog is hidden (« Replacer le point » places with the point tool; a
* resumed tracing traces), and dropped, said, when its view no longer exists (R-13). * resumed trace keeps its tool shown while its handles edit it), and dropped, said, when
* its view no longer exists (R-13).
*/ */
function useDrawingFollows({ doc, ui, dispatch, creation }: CreationFollow) { function useDrawingFollows({ doc, ui, dispatch, creation }: CreationFollow) {
const wanted = const wanted =
@@ -10,6 +10,7 @@ import { updateGeometry, type CommitContext } from './annotationCommit'
import { emptyForm, pendingForClick, type NewKind } from './creation' import { emptyForm, pendingForClick, type NewKind } from './creation'
import { import {
closeTrace, closeTrace,
patchPendingShape,
placePending, placePending,
popVertex, popVertex,
traceVertex, traceVertex,
@@ -18,7 +19,7 @@ import {
import { askCreation } from './creationAsk' import { askCreation } from './creationAsk'
import { round2, type Frame, type XY } from './frame' import { round2, type Frame, type XY } from './frame'
import { newPointSize } from './pointSize' import { newPointSize } from './pointSize'
import { endMode, useAnnotationWork } from './workStore' import { endMode, PENDING_ID, useAnnotationWork } from './workStore'
import type { ToolId, Tracing, UiAction, UiState } from './uiState' import type { ToolId, Tracing, UiAction, UiState } from './uiState'
import type { GestureMessages } from './useGestureMessage' import type { GestureMessages } from './useGestureMessage'
@@ -147,16 +148,34 @@ function changeKeys(change: GeometryChange, kind: Annotation['kind']) {
return { kept, refused: moved ? 'move_refused' : 'edit_refused' } return { kept, refused: moved ? 'move_refused' : 'edit_refused' }
} }
/**
* A change of the resumed creation's shape: patched, said without « Défaire » (undo stays
* inactive during a creation, rev 4); the core judges it at « Créer ».
*/
function dropPending(
{ context, message }: PlacementInput,
geometry: Geometry,
change: GeometryChange,
): boolean {
if (change === 'move' || geometry.type !== 'polygon') return false
if (!patchPendingShape(geometry)) return false
const text = context.t(`editor.annotations.message.${KEPT[change]}`)
message.show(text, { undo: false, tone: 'info' })
return true
}
/** /**
* A drop commits one update; the line under the drawing says it, or the core's refusal * A drop commits one update; the line under the drawing says it, or the core's refusal
* with the refused place drawn (the shape stays where it was). * with the refused place drawn (the shape stays where it was).
*/ */
function dropAction({ doc, context, message, dispatch }: PlacementInput) { function dropAction(input: PlacementInput) {
const { doc, context, message, dispatch } = input
return ( return (
id: string, id: string,
geometry: Geometry, geometry: Geometry,
change: GeometryChange = 'move', change: GeometryChange = 'move',
): boolean => { ): boolean => {
if (id === PENDING_ID) return dropPending(input, geometry, change)
const annotation = doc.annotations.find((a) => a.id === id) const annotation = doc.annotations.find((a) => a.id === id)
if (!annotation) return false if (!annotation) return false
const keys = changeKeys(change, annotation.kind) const keys = changeKeys(change, annotation.kind)
+28 -7
View File
@@ -1,17 +1,25 @@
import type { KeyboardEvent } from 'react' import type { KeyboardEvent } from 'react'
import type { Annotation, Point } from '@faunosteo/core-wasm/types' import type { Annotation, Point } from '@faunosteo/core-wasm/types'
import { moveStep, type Frame } from './frame' import { moveStep, type Frame, type XY } from './frame'
import { movedBy } from './gesture'
import { insertMidpoint, removeVertex } from './polygonEdit' import { insertMidpoint, removeVertex } from './polygonEdit'
import { stepSelection, takePreview } from './previewCommit' import { stepSelection, takePreview } from './previewCommit'
import type { Drop } from './usePlacement' import type { Drop } from './usePlacement'
import type { GestureMessages } from './useGestureMessage' import type { GestureMessages } from './useGestureMessage'
import type { HandleAction } from './usePressGesture' import type { HandleAction } from './usePressGesture'
import { chooseVertex, currentPoints, freshChosen } from './zoneEdit' import { chooseVertex, currentPoints, freshChosen } from './zoneEdit'
import { useAnnotationWork } from './workStore' import { PENDING_ID, useAnnotationWork } from './workStore'
/**
* What the handles edit: its id and its geometry as rendered. Its points are read from the
* store and its changes go through `onDrop`, which commits a stored zone or patches the
* resumed creation's shape (`PENDING_ID`).
*/
export type ZoneTarget = Pick<Annotation, 'id' | 'geometry'>
export interface ZoneEditInput { export interface ZoneEditInput {
/** The selected polygon when its vertices can be edited now (editable, measured). */ /** The polygon whose vertices can be edited now: the selection, or the resumed shape. */
target: Annotation | null target: ZoneTarget | null
frame: Frame | null frame: Frame | null
onDrop: Drop onDrop: Drop
message: Pick<GestureMessages, 'show'> message: Pick<GestureMessages, 'show'>
@@ -27,8 +35,8 @@ const STEP: Record<string, [number, number]> = {
ArrowRight: [1, 0], ArrowRight: [1, 0],
} }
/** The selected polygon as stored now (not as this render saw it). */ /** The target's polygon as the store holds it now (not as this render saw it). */
const pointsOf = (target: Annotation | null): Point[] | null => const pointsOf = (target: ZoneTarget | null): Point[] | null =>
target ? currentPoints(target.id) : null target ? currentPoints(target.id) : null
/** « + »: the midpoint commits once, and the new vertex is chosen on the new text. */ /** « + »: the midpoint commits once, and the new vertex is chosen on the new text. */
@@ -69,12 +77,25 @@ function commitKeys(input: ZoneEditInput): void {
if (kept && vertex !== null) chooseVertex(target.id, vertex) if (kept && vertex !== null) chooseVertex(target.id, vertex)
} }
/**
* A pending vertex moves at once (rev 4): there is no undo during a creation, so no series
* is held for it; it stays chosen.
*/
function stepPending(input: ZoneEditInput, index: number, delta: XY) {
const points = pointsOf(input.target)
const moved = points && movedBy({ type: 'polygon', points }, delta, index)
if (moved && input.onDrop(PENDING_ID, moved, 'vertex'))
chooseVertex(PENDING_ID, index)
}
function stepVertex(input: ZoneEditInput, index: number, event: KeyboardEvent) { function stepVertex(input: ZoneEditInput, index: number, event: KeyboardEvent) {
const { target, frame } = input const { target, frame } = input
const [x, y] = STEP[event.key] const [x, y] = STEP[event.key]
if (!target?.geometry || !frame) return if (!target?.geometry || !frame) return
const size = moveStep(frame, event.shiftKey) const size = moveStep(frame, event.shiftKey)
stepSelection(target.id, target.geometry, { x: x * size, y: y * size }, index) const delta = { x: x * size, y: y * size }
if (target.id === PENDING_ID) return stepPending(input, index, delta)
stepSelection(target.id, target.geometry, delta, index)
} }
const inMoveMode = () => useAnnotationWork.getState().mode?.kind === 'move' const inMoveMode = () => useAnnotationWork.getState().mode?.kind === 'move'
@@ -10,6 +10,12 @@ export interface Preview {
base: string base: string
source: 'move' | 'size' | 'keys' source: 'move' | 'size' | 'keys'
} }
/**
* The handles' target id of a resumed creation's shape (rev 4 point 3): it is not in the
* document, so its vertex choice can never land on a stored annotation (ids are UUIDs).
*/
export const PENDING_ID = '\u0000pending'
export interface Chosen { export interface Chosen {
annotationId: string annotationId: string
vertex: number vertex: number
@@ -51,6 +57,11 @@ export interface ModeWork {
/** The chosen vertex a move mode moves alone (« Déplacer le sommet »); null: the shape. */ /** The chosen vertex a move mode moves alone (« Déplacer le sommet »); null: the shape. */
vertex: number | null vertex: number | null
} }
/** The chosen vertex once the creation ends: a choice on its shape ends with it. */
export function choiceAfterCreation(chosen: Chosen | null): Chosen | null {
return chosen?.annotationId === PENDING_ID ? null : chosen
}
export type GuardWork = 'creation' | 'move' | 'redraw' | null export type GuardWork = 'creation' | 'move' | 'redraw' | null
/** A navigation held by the drawing guard (R-12): what it asks about, and the move itself. */ /** A navigation held by the drawing guard (R-12): what it asks about, and the move itself. */
export interface DrawingQuestion { export interface DrawingQuestion {
+7 -3
View File
@@ -1,7 +1,7 @@
import type { Geometry, Point } from '@faunosteo/core-wasm/types' import type { Geometry, Point } from '@faunosteo/core-wasm/types'
import { useEditorStore } from '../state/editorStore' import { useEditorStore } from '../state/editorStore'
import { HANDLE_CAP } from './polygonEdit' import { HANDLE_CAP } from './polygonEdit'
import { useAnnotationWork } from './workStore' import { PENDING_ID, useAnnotationWork } from './workStore'
/** A polygon's vertices when it gets handles (R-7: at most HANDLE_CAP), else null. */ /** A polygon's vertices when it gets handles (R-7: at most HANDLE_CAP), else null. */
export function handledPoints(geometry: Geometry | null): Point[] | null { export function handledPoints(geometry: Geometry | null): Point[] | null {
@@ -24,10 +24,14 @@ export function freshChosen(annotationId: string): number | null {
} }
/** /**
* The polygon of `annotationId` in the current document, read from the store: a commit * The polygon of `annotationId` in the current document (or the resumed creation's shape),
* made earlier in the same event (a pending series committed first) counts. * read from the store: a change made earlier in the same event counts.
*/ */
export function currentPoints(annotationId: string): Point[] | null { export function currentPoints(annotationId: string): Point[] | null {
if (annotationId === PENDING_ID) {
const pending = useAnnotationWork.getState().creation?.pending.geometry
return pending?.type === 'polygon' ? pending.points : null
}
const doc = useEditorStore.getState().previewState?.document const doc = useEditorStore.getState().previewState?.document
const geometry = doc?.annotations.find((a) => a.id === annotationId)?.geometry const geometry = doc?.annotations.find((a) => a.id === annotationId)?.geometry
return geometry?.type === 'polygon' ? geometry.points : null return geometry?.type === 'polygon' ? geometry.points : null
+2
View File
@@ -1841,6 +1841,8 @@ export const en: Dict = {
'editor.annotations.handle.vertex': 'Vertex {n} of {name}', 'editor.annotations.handle.vertex': 'Vertex {n} of {name}',
'editor.annotations.handle.insert': 'Add a vertex after vertex {n} of {name}', 'editor.annotations.handle.insert': 'Add a vertex after vertex {n} of {name}',
'editor.annotations.handle.remove': 'Remove vertex {n} of {name}', 'editor.annotations.handle.remove': 'Remove vertex {n} of {name}',
'editor.annotations.handle.unnamed.zone': 'the new zone',
'editor.annotations.handle.unnamed.detail_trigger': 'the new link',
'editor.annotations.strip.vertex_chosen': '{detail} · vertex {n} chosen', 'editor.annotations.strip.vertex_chosen': '{detail} · vertex {n} chosen',
'editor.annotations.strip.too_many_one': 'editor.annotations.strip.too_many_one':
'{kind} · {count} vertex, too many for handles', '{kind} · {count} vertex, too many for handles',
+2
View File
@@ -1911,6 +1911,8 @@ export const fr: Dict = {
'editor.annotations.handle.insert': 'editor.annotations.handle.insert':
'Ajouter un sommet après le sommet {n} de {name}', 'Ajouter un sommet après le sommet {n} de {name}',
'editor.annotations.handle.remove': 'Retirer le sommet {n} de {name}', 'editor.annotations.handle.remove': 'Retirer le sommet {n} de {name}',
'editor.annotations.handle.unnamed.zone': 'la nouvelle zone',
'editor.annotations.handle.unnamed.detail_trigger': 'le nouvel accès',
'editor.annotations.strip.vertex_chosen': '{detail} · sommet {n} choisi', 'editor.annotations.strip.vertex_chosen': '{detail} · sommet {n} choisi',
'editor.annotations.strip.too_many_one': 'editor.annotations.strip.too_many_one':
'{kind} · {count} sommet, trop pour les poignées', '{kind} · {count} sommet, trop pour les poignées',
@@ -10,12 +10,17 @@ import {
within, within,
} from '@testing-library/react' } from '@testing-library/react'
import userEvent from '@testing-library/user-event' import userEvent from '@testing-library/user-event'
import type { Point } from '@faunosteo/core-wasm/types'
import HistoryButtons from '@/components/editor/HistoryButtons' import HistoryButtons from '@/components/editor/HistoryButtons'
import { useUndoShortcuts } from '@/editor/useUndoShortcuts' import { useUndoShortcuts } from '@/editor/useUndoShortcuts'
import { resetWork, useAnnotationWork } from '@/editor/annotations/workStore' import {
PENDING_ID,
resetWork,
useAnnotationWork,
} from '@/editor/annotations/workStore'
import DrawingGuardDialog from '@/components/editor/annotations/DrawingGuardDialog' import DrawingGuardDialog from '@/components/editor/annotations/DrawingGuardDialog'
import { emptyForm } from '@/editor/annotations/creation' import { emptyForm } from '@/editor/annotations/creation'
import { placePending } from '@/editor/annotations/creationWork' import { dropCreation, placePending } from '@/editor/annotations/creationWork'
import { guardDrawing } from '@/editor/annotations/drawingGuard' import { guardDrawing } from '@/editor/annotations/drawingGuard'
import { useLocaleStore } from '@/state/localeStore' import { useLocaleStore } from '@/state/localeStore'
import { drawnText, insert, point } from '../helpers/editorFixtures' import { drawnText, insert, point } from '../helpers/editorFixtures'
@@ -223,36 +228,220 @@ describe('placing and the form (A4, A5)', () => {
}) })
}) })
describe('« Reprendre le tracé » and « Revenir aux propriétés » (board 04 C)', () => { describe('« Reprendre le tracé » edits the closed shape with its handles (board 04 C)', () => {
it('keeps the vertices and the form; a new vertex, then the dialog again', async () => { const SQUARE: Point[] = [
const user = await mount()
await user.click(screen.getByRole('button', { name: 'Zone' }))
;[
[20, 20], [20, 20],
[80, 20], [80, 20],
[50, 80], [80, 80],
].forEach(([x, y]) => pressAt(canvas(), x, y)) [20, 80],
]
const mouse = {
pointerId: 1,
isPrimary: true,
button: 0,
buttons: 1,
pointerType: 'mouse',
}
const hitOf = (name: string) =>
screen.getByRole('button', { name }).querySelector('[data-handle]')!
const clickHandle = (name: string, [x, y]: [number, number]) =>
pressAt(hitOf(name), x, y)
const shape = () => {
const geometry = creation()!.pending.geometry
return geometry.type === 'polygon' ? geometry.points : null
}
/** What a pending change must leave alone: the document, both histories (unsaved count). */
const untouched = () => {
const { documentText, undo, redo } = store.getState()
return { documentText, undo: undo.length, redo: redo.length }
}
const line = () => screen.getByTestId('gesture-line')
const strip = () => screen.getByTestId('edit-strip')
/** A traced square, its dialog, the name typed (unless empty), then « Reprendre le tracé ». */
async function resumed(name = 'Tibia', points = SQUARE) {
const user = await mount()
await user.click(screen.getByRole('button', { name: 'Zone' }))
points.forEach(([x, y]) => pressAt(canvas(), x, y))
await user.click(screen.getByRole('button', { name: 'Fermer le tracé' })) await user.click(screen.getByRole('button', { name: 'Fermer le tracé' }))
let shown = await dialog('Nouvelle zone') const shown = await dialog('Nouvelle zone')
await user.type(within(shown).getByLabelText('Nom (FR)'), 'Tibia') if (name) await user.type(within(shown).getByLabelText('Nom (FR)'), name)
await user.click( await user.click(
within(shown).getByRole('button', { name: 'Reprendre le tracé' }), within(shown).getByRole('button', { name: 'Reprendre le tracé' }),
) )
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
const strip = screen.getByTestId('edit-strip') return user
expect(strip).toHaveTextContent('Tracé repris, saisie gardée') }
it('keeps the shape closed and the form, shows its handles; two strip commands', async () => {
await resumed()
expect(creation()).toMatchObject({ closed: true, dialog: false })
expect(shape()).toEqual(SQUARE)
expect(ghost()).toBeInTheDocument()
expect( expect(
within(strip).getByRole('button', { name: 'Retirer le dernier sommet' }), screen.getByRole('group', { name: 'Sommets de Tibia' }),
).toBeEnabled() ).toBeInTheDocument()
pressAt(canvas(), 30, 60) expect(
screen.getByRole('button', { name: 'Sommet 4 de Tibia' }),
).toBeInTheDocument()
expect(
screen.getByRole('button', {
name: 'Ajouter un sommet après le sommet 1 de Tibia',
}),
).toBeInTheDocument()
expect(strip()).toHaveTextContent('Nouvelle zone')
expect(strip()).toHaveTextContent('Tracé repris, saisie gardée')
const commands = within(screen.getByTestId('creation-commands'))
.getAllByRole('button')
.map((b) => b.textContent)
expect(commands).toEqual(['Revenir aux propriétés', 'Abandonner'])
expect(
screen.queryByRole('button', { name: 'Retirer le dernier sommet' }),
).toBeNull()
})
it('a vertex drag changes the pending shape only, said without « Défaire »', async () => {
await resumed()
const before = untouched()
const el = hitOf('Sommet 2 de Tibia')
fireEvent.pointerDown(el, { ...mouse, clientX: 80, clientY: 20 })
fireEvent.pointerMove(el, { ...mouse, clientX: 90, clientY: 10 })
fireEvent.pointerUp(el, { ...mouse, buttons: 0, clientX: 90, clientY: 10 })
expect(shape()![1]).toEqual([90, 10])
expect(useAnnotationWork.getState().chosen).toMatchObject({
annotationId: PENDING_ID,
vertex: 1,
})
expect(line()).toHaveTextContent('Sommet déplacé')
expect(within(line()).queryByRole('button', { name: 'Défaire' })).toBeNull()
expect(untouched()).toEqual(before)
})
it('« + » and « − » change the pending shape only', async () => {
await resumed()
const before = untouched()
clickHandle('Ajouter un sommet après le sommet 1 de Tibia', [50, 20])
expect(shape()).toEqual([[20, 20], [50, 20], ...SQUARE.slice(1)])
expect(useAnnotationWork.getState().chosen).toMatchObject({ vertex: 1 })
expect(line()).toHaveTextContent('Sommet ajouté')
clickHandle('Retirer le sommet 2 de Tibia', [50, 10])
expect(shape()).toEqual(SQUARE)
expect(line()).toHaveTextContent('Sommet retiré')
expect(within(line()).queryByRole('button', { name: 'Défaire' })).toBeNull()
expect(untouched()).toEqual(before)
})
it('vertex keys: arrows move at once, Insert adds, Delete removes; nothing held', async () => {
await resumed()
const before = untouched()
const vertex = (n: number) =>
screen.getByRole('button', { name: `Sommet ${n} de Tibia` })
vertex(1).focus()
fireEvent.keyDown(vertex(1), { key: 'ArrowRight' })
expect(shape()![0]).toEqual([20.5, 20])
expect(useAnnotationWork.getState().preview).toBeNull()
fireEvent.keyDown(vertex(1), { key: 'Insert' })
expect(shape()).toHaveLength(5)
expect(shape()![1]).toEqual([50.25, 20])
fireEvent.keyDown(vertex(2), { key: 'Delete' })
expect(shape()).toHaveLength(4)
expect(untouched()).toEqual(before)
})
it('« − » at three vertices is refused with its reason', async () => {
await resumed('Tibia', SQUARE.slice(0, 3))
clickHandle('Sommet 1 de Tibia', [20, 20])
expect(
screen.getByRole('button', { name: 'Retirer le sommet 1 de Tibia' }),
).toHaveAttribute('aria-disabled', 'true')
clickHandle('Retirer le sommet 1 de Tibia', [20, 10])
expect(shape()).toEqual(SQUARE.slice(0, 3))
expect(line()).toHaveTextContent('Une zone garde au moins 3 sommets')
})
it('a click off the handles adds and selects nothing; a double « + » inserts once', async () => {
await resumed()
pressAt(canvas(), 50, 50)
pressAt(canvas(), 5, 5)
expect(shape()).toEqual(SQUARE)
expect(creation()!.form.fr).toBe('Tibia')
expect(screen.queryByRole('dialog')).toBeNull()
const plus = hitOf('Ajouter un sommet après le sommet 1 de Tibia')
pressAt(plus, 50, 20)
pressAt(plus, 50, 20)
expect(shape()).toHaveLength(5)
})
it('Escape on a vertex asks « Abandonner la création ? »', async () => {
await resumed()
// The tab sits in the editor's workspace, where the page's Escape applies.
view.container.setAttribute('data-editor-workspace', '')
const vertex = screen.getByRole('button', { name: 'Sommet 1 de Tibia' })
act(() => vertex.focus())
fireEvent.keyDown(vertex, { key: 'Escape' })
expect(useAnnotationWork.getState().question?.work).toBe('creation')
expect(creation()).not.toBeNull()
})
it('« Revenir aux propriétés » shows the edited shape; « Créer » inserts it', async () => {
const user = await resumed()
clickHandle('Ajouter un sommet après le sommet 1 de Tibia', [50, 20])
await user.click( await user.click(
within(strip).getByRole('button', { name: 'Revenir aux propriétés' }), within(strip()).getByRole('button', { name: 'Revenir aux propriétés' }),
) )
shown = await dialog('Nouvelle zone') const shown = await dialog('Nouvelle zone')
expect(within(shown).getByLabelText('Nom (FR)')).toHaveValue('Tibia') expect(within(shown).getByLabelText('Nom (FR)')).toHaveValue('Tibia')
expect( expect(
within(shown).getByText('Zone tracée, 4 sommets'), within(shown).getByText('Zone tracée, 5 sommets'),
).toBeInTheDocument() ).toBeInTheDocument()
await user.type(within(shown).getByLabelText('Nom (EN)'), 'Tibia')
await user.selectOptions(within(shown).getByLabelText('Latéralité'), 'left')
const before = store.getState().undo.length
await user.click(within(shown).getByRole('button', { name: 'Créer' }))
expect(store.getState().undo).toHaveLength(before + 1)
const created = annotations().find((a) => a.kind === 'zone')!
expect(created.geometry).toEqual({
type: 'polygon',
points: [[20, 20], [50, 20], ...SQUARE.slice(1)],
})
expect(useAnnotationWork.getState().chosen).toBeNull()
})
it('the chosen vertex ends with the creation when it is dropped', async () => {
await resumed()
clickHandle('Sommet 2 de Tibia', [80, 20])
expect(useAnnotationWork.getState().chosen).not.toBeNull()
act(() => dropCreation())
expect(useAnnotationWork.getState().chosen).toBeNull()
})
it('names: « la nouvelle zone » while the name is empty; English: « the new zone »', async () => {
await resumed('')
expect(
screen.getByRole('group', { name: 'Sommets de la nouvelle zone' }),
).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'Sommet 1 de la nouvelle zone' }),
).toBeInTheDocument()
act(() => useLocaleStore.setState({ locale: 'en' }))
expect(
await screen.findByRole('group', { name: 'Vertices of the new zone' }),
).toBeInTheDocument()
})
it('a keyboard link resumes with handles, « le nouvel accès » while unnamed', async () => {
const user = await mount(withDetail())
await user.click(screen.getByRole('button', { name: 'Ajouter un accès' }))
const shown = await dialog('Nouvel accès')
await user.click(
within(shown).getByRole('button', { name: 'Reprendre le tracé' }),
)
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(strip()).toHaveTextContent('Nouvel accès')
expect(
screen.getByRole('group', { name: 'Sommets de le nouvel accès' }),
).toBeInTheDocument()
expect(creation()).toMatchObject({ closed: true, dialog: false })
}) })
}) })
+13 -2
View File
@@ -195,7 +195,8 @@ while the polygon has three vertices. Above 40 vertices (`HANDLE_CAP`, T18)
the layer draws no handle at all: the overlay keeps the selection outline. the layer draws no handle at all: the overlay keeps the selection outline.
No handle covers the polygon's interior: a press inside it still reads the No handle covers the polygon's interior: a press inside it still reads the
core's markers, so an annotation drawn on top is the one a click reaches. A core's markers, so an annotation drawn on top is the one a click reaches. A
path, or an annotation without geometry, gets no handle. path, or an annotation without geometry, gets no handle. The pending shape of
a resumed creation gets the same handles (see the creation marks below).
Marks of a gesture in progress, drawn by the overlay: Marks of a gesture in progress, drawn by the overlay:
@@ -238,7 +239,17 @@ core, since the new shape is not in the document until « Créer »:
white stroke under it) and an accent dashed outline over the halo. It stays white stroke under it) and an accent dashed outline over the halo. It stays
visible under the creation dialog's light veil; visible under the creation dialog's light veil;
- the corrected position of a point (C26): the proposal in accent dashes and - the corrected position of a point (C26): the proposal in accent dashes and
the click marked apart by a hollow cross. the click marked apart by a hollow cross;
- a resumed trace (« Reprendre le tracé », board 04 C, rev 4): the closed
ghost stays drawn as above, and the handle layer draws the polygon handles
on it exactly as on a selected polygon (« + », vertices, the chosen vertex's
« − » bubble, the 40-vertex cap, the R-9 zoom rule). Their names carry the
form's name in the current locale, or « la nouvelle zone » / « le nouvel
accès » while it is empty. During a vertex drag the ghost stays at its last
place and the dragged outline is drawn as a selection preview (dashed ink,
its vertices), without the grey old place; the loupe follows a finger as on
a stored zone. A change of the shape only replaces the ghost's geometry: the
document is untouched until « Créer ».
While a creation is in progress the canvas box carries `data-creating`. The While a creation is in progress the canvas box carries `data-creating`. The
stylesheet then dims every core marker (`[data-anno-id]` at 0.35 opacity, no stylesheet then dims every core marker (`[data-anno-id]` at 0.35 opacity, no