Files
faunosteo/apps/app/src/components/editor/annotations/CreationDialog.tsx
T
bchanot fe333c2bbd fix(editor): creation question lapses, guard sites and flip tested
The creation's « Abandonner la création ? » no longer outlives it:
« Replacer le point », « Reprendre le tracé », « Créer » (« Utiliser
cette position » included) and « Annuler le tracé » clear a question
still open, which would otherwise reappear over the page. Locals
trimmed in the creation dialog and the tracing actions (5 max).

Tests added (no assertion removed): the two lapses (RED without the
fix, GREEN with it); a view chip and a tool ask during a tracing; the
mode flip keeps the dialog, its form and the ghost; a history jump out
of the editor waits for the creation's question; e2e: « Reprendre le
tracé » and « Revenir aux propriétés » under expectNoShift at 1 024,
1 180 and 1 280 px, the strip's last command inside it, axe on the
resumed state.
2026-11-17 23:41:24 +01:00

278 lines
9.1 KiB
TypeScript

import { useRef, useState, type RefObject } from 'react'
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import DiscardConfirm from '@/components/editor/findings/DiscardConfirm'
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import { creationOpener } from '@/editor/annotations/creationAsk'
import {
confirmAttempt,
createAttempt,
type Attempt,
} from '@/editor/annotations/creationAttempt'
import {
dropCreation,
finishCreation,
patchForm,
replacePoint,
resumeTrace,
setCorrection,
} from '@/editor/annotations/creationWork'
import { answerDrawing, guardDrawing } from '@/editor/annotations/drawingGuard'
import type { MissingField } from '@/editor/annotations/missingFields'
import {
useAnnotationWork,
type Creation,
} from '@/editor/annotations/workStore'
import { visibleElement } from '@/editor/focusRequest'
import { CANVAS_BOX } from '@/editor/useEditorNavigation'
import { usePlaceVisible } from '@/lib/placeVisibility'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import { pluralKey } from '@/editor/plural'
import EditorGlyph from '../EditorGlyph'
import CorrectionNotice from './CorrectionNotice'
import CreationFields from './CreationFields'
import MissingSummary, { focusFirstMissing } from './MissingSummary'
const ID_PREFIX = 'creation-'
export interface CreationDialogProps {
doc: AnatomicalSheetDocument
readOnly: boolean
/** The column the dialog sits over (A2); null: centred. */
anchor: RefObject<HTMLElement | null>
}
/** What « Créer » left on screen: the fields R-3 names, or the core's refusal. */
interface Outcome {
missing: MissingField[]
messages: string[]
}
const NONE: Outcome = { missing: [], messages: [] }
/**
* « Créer » and « Utiliser cette position »: one `insertAnnotation` under `accept` (one
* undo); a point lets the core's verdict offer C (C26); a success ends the creation.
*/
function useCreate(work: Creation, created: { current: boolean }) {
const context = { t: useT(), locale: useLocaleStore((s) => s.locale) }
const [outcome, setOutcome] = useState<Outcome>(NONE)
const settle = (attempt: Attempt) => {
if (attempt.status === 'invalid') {
setOutcome({ missing: attempt.missing, messages: [] })
return focusFirstMissing(ID_PREFIX, attempt.missing)
}
setOutcome({
missing: [],
messages: attempt.status === 'refused' ? attempt.messages : [],
})
if (attempt.status === 'correction') setCorrection(attempt.correction)
if (attempt.status !== 'created') return
created.current = true
if (attempt.id) finishCreation(attempt.id, work.pending.kind)
else dropCreation()
}
return {
outcome,
create: () => settle(createAttempt({ ...work, context }, work.form)),
confirm: () => {
const { correction } = work.pending
if (!correction) return
settle(confirmAttempt({ ...work, context }, work.form, correction))
},
}
}
/** « Point placé · Replacer le point », « Zone tracée, 5 sommets · Reprendre le tracé ». */
const GLYPH = { point: 'point', zone: 'zone', detail_trigger: 'link' } as const
/** « Point placé », « Zone tracée, 5 sommets », « Accès tracé, 3 sommets ». */
function useShapeText(pending: Creation['pending']): string {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const { kind, geometry } = pending
if (geometry.type !== 'polygon')
return t('editor.annotations.creation.placed')
const count = geometry.points.length
const key = `editor.annotations.creation.traced.${kind}`
return t(pluralKey(locale, key, count)).replace('{count}', String(count))
}
function ShapeLine({ work, readOnly }: { work: Creation; readOnly: boolean }) {
const t = useT()
const text = useShapeText(work.pending)
const point = work.pending.kind === 'point'
return (
<div
data-creation-focus=""
tabIndex={-1}
className="flex flex-wrap items-center gap-x-2 gap-y-1 rounded-lg bg-[var(--color-surface-strong)] px-3 py-2 text-sm outline-none"
>
<EditorGlyph name={GLYPH[work.pending.kind]} size={16} />
<span>{text}</span>
<button
type="button"
disabled={readOnly}
onClick={point ? replacePoint : resumeTrace}
className="min-h-11 font-medium text-[var(--color-accent-strong)] underline underline-offset-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] disabled:cursor-not-allowed disabled:opacity-40 xl:min-h-0"
>
{t(`editor.annotations.creation.${point ? 'replace' : 'resume'}`)}
</button>
</div>
)
}
/** Board 02: « Abandonner » asks first (A12), « Créer » inserts; the question in its place. */
function CreationActions({
readOnly,
onDiscard,
}: {
readOnly: boolean
onDiscard: () => void
}) {
const t = useT()
const asking = useAnnotationWork((s) => s.question?.work === 'creation')
if (asking) {
return (
<DiscardConfirm
words={{
title: t('editor.annotations.guard.creation'),
keep: t('editor.annotations.guard.continue'),
discard: t('editor.annotations.guard.discard'),
}}
onKeepTyping={() => answerDrawing(false)}
onDiscard={() => answerDrawing(true)}
/>
)
}
return (
<div className="flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={onDiscard}>
{t('editor.annotations.creation.discard')}
</Button>
<Button type="submit" disabled={readOnly}>
{t('editor.annotations.create')}
</Button>
</div>
)
}
/** The guard is always armed (A12): ✕, Échap and « Abandonner » ask, even with nothing typed. */
const askDiscard = () => guardDrawing(() => undefined)
function CreationBody({
work,
doc,
readOnly,
created,
}: {
work: Creation
doc: AnatomicalSheetDocument
readOnly: boolean
created: { current: boolean }
}) {
const creating = useCreate(work, created)
const { outcome } = creating
return (
<form
data-testid="annotation-creation"
className="space-y-3"
noValidate
onSubmit={(event) => {
event.preventDefault()
if (!readOnly) creating.create()
}}
>
{readOnly && <ReadOnlyNotice />}
<ShapeLine work={work} readOnly={readOnly} />
<CreationFields
kind={work.pending.kind}
viewId={work.viewId}
doc={doc}
form={work.form}
onChange={patchForm}
idPrefix={ID_PREFIX}
missing={outcome.missing}
readOnly={readOnly}
/>
{work.pending.correction && (
<CorrectionNotice
onConfirm={() => !readOnly && creating.confirm()}
onCancel={() => setCorrection(null)}
/>
)}
<MissingSummary missing={outcome.missing} />
{outcome.messages.length > 0 && (
<div
role="alert"
className="space-y-1 text-sm text-[var(--color-danger-strong)]"
>
{outcome.messages.map((text) => (
<p key={text}>{text}</p>
))}
</div>
)}
<CreationActions readOnly={readOnly} onDiscard={askDiscard} />
</form>
)
}
/**
* Where the focus goes once the dialog closes (board 32): nowhere after « Créer » (the new
* row takes it), the strip's « Revenir aux propriétés » while the shape is replaced or
* retraced, else what started the creation.
*/
function useCreationReturn(work: Creation | null) {
const last = useRef<Creation | null>(null)
const created = useRef(false)
// A new creation starts with no « Créer » behind it.
if (work && last.current === null) created.current = false
last.current = work ?? last.current
const returnFocus = () => {
const ended = last.current
if (useAnnotationWork.getState().creation) {
return (
visibleElement('[data-back-to-properties]') ??
visibleElement(CANVAS_BOX)
)
}
last.current = null
if (created.current || !ended) return null
return creationOpener(ended)
}
return { created, returnFocus }
}
/**
* « Nouveau point », « Nouvelle zone », « Nouvel accès » (board 02, 04): a modal without a
* history layer over the right column, mounted outside the edit-only body so a read-only
* flip keeps it with its form and ghost, « Créer » disabled (R-14). The shape and the
* form are the work store's: they outlive « Replacer le point » and « Reprendre le tracé ».
*/
export default function CreationDialog(props: CreationDialogProps) {
const t = useT()
const visible = usePlaceVisible()
const work = useAnnotationWork((s) => s.creation)
const back = useCreationReturn(work)
return (
<Dialog
open={visible && work !== null && work.dialog}
anchor={props.anchor}
veilCloses={false}
title={work ? t(`editor.annotations.new.${work.pending.kind}`) : ''}
returnFocus={back.returnFocus}
onClose={() => (askDiscard() ? undefined : 'kept')}
>
{work && (
<CreationBody
work={work}
doc={props.doc}
readOnly={props.readOnly}
created={back.created}
/>
)}
</Dialog>
)
}