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

@@ -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
}