feat(app): Constats description, vet referral and citations, keyboard focus after collapse and delete

This commit is contained in:
bchanot committed 2026-11-04 13:50:20 +01:00
1 parent 26097852ff
commit 91d06c9817
9 files changed
+374 -13

No files matched your search

@@ -290,7 +290,14 @@ Removed: `editor.views.drawing.detail` (raw core detail no longer shown).
| `editor.findings.empty` | Aucune zone de constats pour l'instant. | No findings zone yet. | Empty tree | proposal |
| `editor.findings.mark_reviewed` | Marquer comme relu | Mark as reviewed | Selected element action | ratified REVUE |
| `editor.findings.reset_to_confirm` | Remettre à confirmer | Reset to confirm | Selected element action | ratified REVUE |
| `editor.findings.description_fr` | Description (FR) | Description (FR) | Selected element field | proposal |
| `editor.findings.description_en` | Description (EN) | Description (EN) | Selected element field | proposal |
| `editor.findings.vet_referral` | Renvoi vers un vétérinaire | Veterinary referral | Node checkbox | proposal |
| `editor.findings.yes` | Oui | Yes | Read-only value | proposal |
| `editor.findings.no` | Non | No | Read-only value | proposal |
| `editor.findings.references` | Références citées | Cited references | Selected element section | proposal |
| `editor.findings.references_none` | Aucune référence citée. | No reference cited. | Selected element section | proposal |
| `editor.findings.reference_add` | Citer une référence | Cite a reference | Selected element select | proposal |
## Lot H (Annotations tab: canvas, tools, creation, properties, geometry group)
@@ -0,0 +1,177 @@
import ActionButton from '@/components/editor/fields/ActionButton'
import ReadOnlyValue from '@/components/editor/fields/ReadOnlyValue'
import SelectField from '@/components/editor/fields/SelectField'
import TextField from '@/components/editor/fields/TextField'
import {
patchElement,
type FindingItem,
type FindingPatch,
} from '@/editor/findings/tree'
import { optionalText, useSheetDocument } from '@/editor/sheetDocument'
import type { EditCommandApi } from '@/editor/useEditCommand'
import type { Locale } from '@/i18n/types'
import { useT } from '@/i18n/useT'
interface ContentProps {
item: FindingItem
readOnly: boolean
edit: EditCommandApi
}
/** The content of a category or a node: descriptions, vet referral, cited references. */
export default function FindingContent(props: ContentProps) {
const { element } = props.item
if (element.kind === 'zone') return null
const patch = (field: string, change: FindingPatch) =>
props.edit.run(field, {
op: 'update',
key: props.item.key,
element: patchElement(props.item, change),
})
return (
<div className="space-y-3">
<Descriptions
{...props}
current={element.value.description}
patch={patch}
/>
{element.kind === 'finding_node' && (
<VetFlag
{...props}
value={element.value.requires_vet_referral}
patch={patch}
/>
)}
<Citations {...props} ids={element.value.reference_ids} patch={patch} />
</div>
)
}
type Patch = (field: string, change: FindingPatch) => boolean
function Descriptions({
item,
readOnly,
edit,
current,
patch,
}: ContentProps & {
current: { fr?: string; en?: string }
patch: Patch
}) {
const t = useT()
const commit = (locale: Locale) => (value: string) =>
patch(`description-${locale}`, {
description: optionalText(current, locale, value),
})
return (
<div className="grid gap-3 md:grid-cols-2">
{(['fr', 'en'] as const).map((locale) => (
<TextField
key={`${item.id}-${locale}`}
id={`finding-description-${locale}`}
label={t(`editor.findings.description_${locale}`)}
value={current[locale] ?? ''}
onCommit={commit(locale)}
readOnly={readOnly}
multiline
error={edit.fieldError(`description-${locale}`)}
/>
))}
</div>
)
}
function VetFlag({
readOnly,
edit,
value,
patch,
}: ContentProps & { value: boolean; patch: Patch }) {
const t = useT()
const label = t('editor.findings.vet_referral')
if (readOnly) {
const answer = t(value ? 'editor.findings.yes' : 'editor.findings.no')
return <ReadOnlyValue id="finding-vet" label={label} value={answer} />
}
return (
<div>
<label className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={value}
onChange={(e) =>
patch('vet', { requires_vet_referral: e.target.checked })
}
/>
{label}
</label>
{edit.fieldError('vet') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('vet')}
</p>
)}
</div>
)
}
function Citations({
readOnly,
edit,
ids,
patch,
}: ContentProps & { ids: readonly string[]; patch: Patch }) {
const t = useT()
const doc = useSheetDocument()
const references = doc?.references ?? []
const citation = (id: string) =>
references.find((r) => r.id === id)?.citation ?? id
const options = [
{ value: '', label: t('editor.field.choose') },
...references
.filter((r) => !ids.includes(r.id))
.map((r) => ({ value: r.id, label: r.citation })),
]
return (
<div className="space-y-2">
<p className="text-sm font-medium">{t('editor.findings.references')}</p>
{ids.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.references_none')}
</p>
)}
<ul className="space-y-1">
{ids.map((id) => (
<li key={id} className="flex items-center gap-2 text-sm">
<span className="min-w-0 flex-1">{citation(id)}</span>
<ActionButton
readOnly={readOnly}
variant="ghost"
size="sm"
aria-label={`${t('editor.action.remove')} ${citation(id)}`}
onClick={() =>
patch('references', {
reference_ids: ids.filter((other) => other !== id),
})
}
>
{t('editor.action.remove')}
</ActionButton>
</li>
))}
</ul>
{!readOnly && (
<SelectField
id="finding-add-reference"
label={t('editor.findings.reference_add')}
value=""
options={options}
onCommit={(id) =>
id !== '' && patch('references', { reference_ids: [...ids, id] })
}
error={edit.fieldError('references')}
/>
)}
</div>
)
}
@@ -2,8 +2,9 @@ import type { EditCommand } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import MoveButtons from '@/components/editor/fields/MoveButtons'
import TextField from '@/components/editor/fields/TextField'
import FindingContent from '@/components/editor/findings/FindingContent'
import StatusBadge from '@/components/editor/findings/StatusBadge'
import { withName, type FindingItem } from '@/editor/findings/tree'
import { patchElement, type FindingItem } from '@/editor/findings/tree'
import { isBlank } from '@/editor/sheetDocument'
import { useEditCommand, type EditCommandApi } from '@/editor/useEditCommand'
import type { Locale } from '@/i18n/types'
@@ -32,6 +33,7 @@ export default function FindingDetail({
{item.status && <StatusBadge status={item.status} />}
</div>
<Names item={item} readOnly={readOnly} edit={edit} />
<FindingContent item={item} readOnly={readOnly} edit={edit} />
<div className="flex flex-wrap items-center justify-end gap-1">
<ReviewActions item={item} readOnly={readOnly} edit={edit} />
<MoveButtons
@@ -76,7 +78,9 @@ function Names({
: edit.run(locale, {
op: 'update',
key: item.key,
element: withName(item, { ...item.name, [locale]: value }),
element: patchElement(item, {
name: { ...item.name, [locale]: value },
}),
})
return (
<div className="grid gap-3 md:grid-cols-2">
@@ -10,6 +10,8 @@ export interface FindingTreeProps {
expanded: ReadonlySet<string>
onSelect: (id: string) => void
onToggle: (id: string, open: boolean) => void
/** Moves focus to this item (after a deletion); null leaves focus alone. */
focusId: { id: string } | null
}
/**
@@ -21,11 +23,14 @@ export default function FindingTree(props: FindingTreeProps) {
const t = useT()
const refs = useRef(new Map<string, HTMLElement>())
const focusAfter = useRef<string | null>(null)
const { visible, selectedId, expanded, onSelect, onToggle } = props
const { visible, selectedId, expanded, onSelect, onToggle, focusId } = props
useEffect(() => {
if (focusAfter.current) refs.current.get(focusAfter.current)?.focus()
focusAfter.current = null
})
useEffect(() => {
if (focusId) refs.current.get(focusId.id)?.focus()
}, [focusId])
const current = visible.find((item) => item.id === selectedId) ?? visible[0]
const onKeyDown = (event: KeyboardEvent, item: FindingItem) => {
const move = keyMove(visible, item, expanded, event.key)
@@ -11,14 +11,27 @@ import FindingTree from '@/components/editor/findings/FindingTree'
import {
buildItems,
createdItemId,
fallbackAfterRemoval,
isUnder,
visibleItems,
type FindingItem,
} from '@/editor/findings/tree'
import { useEditorStore } from '@/editor/state/editorStore'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { EditorTabProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
/** The tree as the store holds it right now (a commit is already in). */
function currentItems(): FindingItem[] {
try {
const doc = JSON.parse(useEditorStore.getState().documentText)
return buildItems(doc)
} catch {
return []
}
}
/** Constats: the tree zones → categories → nodes, edited one command at a time. */
export default function FindingsTab({ readOnly }: EditorTabProps) {
const t = useT()
@@ -28,6 +41,8 @@ export default function FindingsTab({ readOnly }: EditorTabProps) {
const [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set())
const [seeded, setSeeded] = useState(false)
const [pending, setPending] = useState<PendingFinding | null>(null)
const [fallback, setFallback] = useState<string | null>(null)
const [focusId, setFocusId] = useState<{ id: string } | null>(null)
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
const items = useMemo(() => (doc ? buildItems(doc) : []), [doc])
if (doc && !seeded) {
@@ -37,21 +52,35 @@ export default function FindingsTab({ readOnly }: EditorTabProps) {
)
}
const selected = items.find((item) => item.id === selectedId)
const toggle = (id: string, open: boolean) =>
const toggle = (id: string, open: boolean) => {
if (!open && selectedId && isUnder(items, selectedId, id)) {
setSelectedId(id)
}
setExpanded((prev) => {
const next = new Set(prev)
if (open) next.add(id)
else next.delete(id)
return next
})
}
const created = (id: string) => {
if (!pending) return
if (pending.parent) toggle(pending.parent.id, true)
setSelectedId(createdItemId(pending.kind, pending.parent, id))
setPending(null)
}
const askDelete = (item: FindingItem) =>
const askDelete = (item: FindingItem) => {
setFallback(fallbackAfterRemoval(items, item))
setDeleting({ key: item.key, label: item.name[locale] })
}
const closeDelete = () => {
setDeleting(null)
const gone = !currentItems().some((item) => item.id === selectedId)
if (gone) {
setSelectedId(fallback)
setFocusId(fallback ? { id: fallback } : null)
}
}
return (
<section
data-testid="editor-tab-findings"
@@ -78,6 +107,7 @@ export default function FindingsTab({ readOnly }: EditorTabProps) {
expanded={expanded}
onSelect={setSelectedId}
onToggle={toggle}
focusId={focusId}
/>
{selected && (
<FindingDetail
@@ -87,7 +117,7 @@ export default function FindingsTab({ readOnly }: EditorTabProps) {
onDelete={() => askDelete(selected)}
/>
)}
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
<DeleteDialog target={deleting} onClose={closeDelete} />
</section>
)
}
+50 -6
View File
@@ -43,22 +43,66 @@ export type FindingElement =
| { kind: 'finding_category'; value: FindingCategory }
| { kind: 'finding_node'; value: FindingNode }
/** The same element under another name (the core decides what that does to its marking). */
export function withName(
/** What the detail panel edits; a zone takes the name only. */
export type FindingPatch = Partial<
Pick<
FindingNode,
'name' | 'description' | 'reference_ids' | 'requires_vet_referral'
>
>
/** The same element with `patch` applied (the core decides what it does to the marking). */
export function patchElement(
item: FindingItem,
name: LocalizedText,
patch: FindingPatch,
): FindingElement {
const { element } = item
switch (element.kind) {
case 'zone':
return { kind: 'zone', value: { ...element.value, name } }
return {
kind: 'zone',
value: { ...element.value, name: patch.name ?? element.value.name },
}
case 'finding_category':
return { kind: 'finding_category', value: { ...element.value, name } }
return {
kind: 'finding_category',
value: {
...element.value,
name: patch.name ?? element.value.name,
description: patch.description ?? element.value.description,
reference_ids: patch.reference_ids ?? element.value.reference_ids,
},
}
case 'finding_node':
return { kind: 'finding_node', value: { ...element.value, name } }
return { kind: 'finding_node', value: { ...element.value, ...patch } }
}
}
/** Whether `id` sits under `ancestorId` in the tree. */
export function isUnder(
items: readonly FindingItem[],
id: string,
ancestorId: string,
): boolean {
let parent = items.find((i) => i.id === id)?.parentId ?? null
while (parent !== null) {
if (parent === ancestorId) return true
parent = items.find((i) => i.id === parent)?.parentId ?? null
}
return false
}
/** Where the selection goes when `item` is removed: the previous sibling, else the parent. */
export function fallbackAfterRemoval(
items: readonly FindingItem[],
item: FindingItem,
): string | null {
const previous = items.find(
(i) => i.parentId === item.parentId && i.index === item.index - 1,
)
return previous?.id ?? item.parentId
}
export const itemId = (zoneId: string, path: readonly string[]): string =>
JSON.stringify([zoneId, ...path])
+8
View File
@@ -1509,4 +1509,12 @@ export const en: Dict = {
'editor.annotations.geometry.unapplied_tag': 'not applied',
'editor.annotations.geometry.revert': 'Back to the saved values',
'editor.annotations.geometry.number': 'Each field must hold a number.',
'editor.findings.description_fr': 'Description (FR)',
'editor.findings.description_en': 'Description (EN)',
'editor.findings.vet_referral': 'Veterinary referral',
'editor.findings.yes': 'Yes',
'editor.findings.no': 'No',
'editor.findings.references': 'Cited references',
'editor.findings.references_none': 'No reference cited.',
'editor.findings.reference_add': 'Cite a reference',
}
+8
View File
@@ -1540,4 +1540,12 @@ export const fr: Dict = {
'editor.annotations.geometry.unapplied_tag': 'non appliqué',
'editor.annotations.geometry.revert': 'Revenir aux valeurs enregistrées',
'editor.annotations.geometry.number': 'Chaque champ doit contenir un nombre.',
'editor.findings.description_fr': 'Description (FR)',
'editor.findings.description_en': 'Description (EN)',
'editor.findings.vet_referral': 'Renvoi vers un vétérinaire',
'editor.findings.yes': 'Oui',
'editor.findings.no': 'Non',
'editor.findings.references': 'Références citées',
'editor.findings.references_none': 'Aucune référence citée.',
'editor.findings.reference_add': 'Citer une référence',
}
@@ -355,4 +355,82 @@ describe('Constats tab', () => {
'Cat A',
)
})
it('edits descriptions (blank side omitted), the vet flag and the cited references', async () => {
let text = treeText()
text = insert(text, {
kind: 'reference',
value: {
id: 'ref-a',
type: 'book',
citation: 'Alpha',
url: null,
doi: null,
},
})
await openReady({ text })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(items()[1])
await user.keyboard('{ArrowRight}{ArrowDown}')
const node = () => doc().finding_zones[0].categories[0].children[0]
const fr = screen.getByLabelText('Description (FR)')
await user.type(fr, 'Texte')
await user.tab()
expect(node().description).toEqual({ fr: 'Texte' })
await user.clear(fr)
await user.tab()
expect(node().description).toEqual({})
await user.click(screen.getByLabelText('Renvoi vers un vétérinaire'))
expect(node().requires_vet_referral).toBe(true)
await user.selectOptions(
screen.getByLabelText('Citer une référence'),
'ref-a',
)
expect(node().reference_ids).toEqual(['ref-a'])
await user.click(screen.getByRole('button', { name: /Retirer Alpha/ }))
expect(node().reference_ids).toEqual([])
})
it('a category has no vet flag; read-only hides the editing actions', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
const { rerender } = render(<FindingsTab {...props} />)
await user.click(items()[1])
expect(screen.queryByLabelText('Renvoi vers un vétérinaire')).toBeNull()
rerender(<FindingsTab {...props} readOnly />)
expect(screen.queryByLabelText('Citer une référence')).toBeNull()
expect(screen.queryByRole('textbox')).toBeNull()
})
it('collapsing an ancestor of the selection selects the ancestor', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(items()[1])
await user.keyboard('{ArrowRight}{ArrowRight}')
expect(items()[2]).toHaveAttribute('aria-selected', 'true')
await user.click(items()[0].querySelector('span') as HTMLElement)
expect(items()[0]).toHaveAttribute('aria-selected', 'true')
expect(items()).toHaveLength(2)
})
it('after a delete the previous sibling, else the parent, is selected and focused', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(items()[2])
await user.click(screen.getByRole('button', { name: 'Supprimer' }))
const dialog = await screen.findByRole('dialog')
await user.click(within(dialog).getByRole('button', { name: 'Supprimer' }))
expect(doc().finding_zones.map((z) => z.id)).toEqual(['zone-a'])
expect(items()[0]).toHaveAttribute('aria-selected', 'true')
expect(items()[0]).toHaveFocus()
await user.click(items()[1])
await user.click(screen.getAllByRole('button', { name: 'Supprimer' })[0])
const second = (await screen.findAllByRole('dialog')).at(-1) as HTMLElement
await user.click(within(second).getByRole('button', { name: 'Supprimer' }))
expect(items()[0]).toHaveAttribute('aria-selected', 'true')
expect(items()[0]).toHaveFocus()
})
})