feat(app): editor Constats tree with review states and reorder

This commit is contained in:
bchanot committed 2026-11-04 13:45:34 +01:00
1 parent 66663dc0ca
commit 92c595caa1
11 files changed
+1219 -4

No files matched your search

@@ -261,3 +261,33 @@ Removed: `editor.views.drawing.detail` (raw core detail no longer shown).
| `editor.cleaning.style` | L'élément <style> a été retiré : les classes qu'il définissait s'afficheront sans style. | The <style> element was removed: the classes it defined will show unstyled. | Cleaning dialog | plan (style named) |
| `editor.cleaning.confirm` | Nettoyer et utiliser cette version | Clean and use this version | Cleaning dialog button | plan wording FR; EN proposal |
| `editor.cleaning.cancel` | Annuler | Cancel | Cleaning dialog button | plan wording FR; EN proposal |
## Lot I (Constats tree)
| Key | FR | EN | Where | Status |
|---|---|---|---|---|
| `editor.findings.tree` | Arbre des constats | Findings tree | Tree accessible name | proposal |
| `editor.findings.status.to_confirm` | À confirmer | To confirm | Review badge | ratified REVUE |
| `editor.findings.status.reviewed` | Relu | Reviewed | Review badge | ratified REVUE |
| `editor.findings.status.inherited` | Hérité, non relu | Inherited, not reviewed | Review badge | ratified REVUE |
| `editor.findings.type.zone` | Zone de constats | Findings zone | Selected element kind | proposal |
| `editor.findings.type.category` | Catégorie de constats | Findings category | Selected element kind | proposal |
| `editor.findings.type.node` | Constat | Finding | Selected element kind | proposal |
| `editor.findings.add_zone` | Ajouter une zone | Add a zone | Tree toolbar | plan wording FR; EN proposal |
| `editor.findings.add_category` | Ajouter une catégorie | Add a category | Tree toolbar | plan wording FR; EN proposal |
| `editor.findings.add_node` | Ajouter un constat | Add a finding | Tree toolbar, disabled at depth 8 | plan wording FR; EN proposal |
| `editor.findings.new.zone` | Nouvelle zone de constats | New findings zone | Creation form title | proposal |
| `editor.findings.new.category` | Nouvelle catégorie de constats | New findings category | Creation form title | proposal |
| `editor.findings.new.node` | Nouveau constat | New finding | Creation form title | proposal |
| `editor.findings.kind` | Type de catégorie | Category type | Creation form field | proposal |
| `editor.findings.kind.dysfunction` | Dysfonction | Dysfunction | Category type option | proposal |
| `editor.findings.kind.consultation_reason` | Motif de consultation | Reason for consultation | Category type option | proposal |
| `editor.findings.kind.anamnesis` | Anamnèse | Anamnesis | Category type option | proposal |
| `editor.findings.kind.custom` | Personnalisée | Custom | Category type option | proposal |
| `editor.findings.required` | Renseignez le nom en français et en anglais (et le type d'une catégorie). | Fill in the name in French and English (and the type of a category). | Creation form refusal | proposal |
| `editor.findings.create` | Créer | Create | Creation form button | proposal |
| `editor.findings.cancel` | Annuler | Cancel | Creation form button | proposal |
| `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 |
@@ -0,0 +1,47 @@
import ActionButton from '@/components/editor/fields/ActionButton'
import type { PendingFinding } from '@/components/editor/findings/FindingCreateForm'
import { canAddNode, type FindingItem } from '@/editor/findings/tree'
import { useT } from '@/i18n/useT'
/** « Ajouter une zone / une catégorie / un constat »: each starts a creation form. */
export default function AddBar({
selected,
readOnly,
onStart,
}: {
selected: FindingItem | undefined
readOnly: boolean
onStart: (pending: PendingFinding) => void
}) {
const t = useT()
return (
<div className="flex flex-wrap gap-2">
<ActionButton
readOnly={readOnly}
variant="secondary"
size="sm"
onClick={() => onStart({ kind: 'zone', parent: null })}
>
{t('editor.findings.add_zone')}
</ActionButton>
<ActionButton
readOnly={readOnly}
variant="secondary"
size="sm"
disabled={!selected}
onClick={() => onStart({ kind: 'category', parent: selected ?? null })}
>
{t('editor.findings.add_category')}
</ActionButton>
<ActionButton
readOnly={readOnly}
variant="secondary"
size="sm"
disabled={!canAddNode(selected)}
onClick={() => onStart({ kind: 'node', parent: selected ?? null })}
>
{t('editor.findings.add_node')}
</ActionButton>
</div>
)
}
@@ -0,0 +1,163 @@
import { useState } from 'react'
import type {
EditCommand,
FindingCategoryKind,
FindingNode,
} from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import DraftField from '@/components/editor/fields/DraftField'
import SelectField from '@/components/editor/fields/SelectField'
import type { FindingItem, FindingKind } from '@/editor/findings/tree'
import type { IdPrefix } from '@/editor/ids'
import { isBlank } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
export const CATEGORY_KINDS: readonly FindingCategoryKind[] = [
'dysfunction',
'consultation_reason',
'anamnesis',
'custom',
]
export interface PendingFinding {
kind: FindingKind
/** The zone, category or node the new element goes under; null for a zone. */
parent: FindingItem | null
}
/**
* Collects what the core requires (names FR/EN, the kind of a category), then one
* `insert`: no element exists with default labels.
*/
export default function FindingCreateForm({
pending,
onCreated,
onCancel,
}: {
pending: PendingFinding
onCreated: (id: string) => void
onCancel: () => void
}) {
const t = useT()
const edit = useEditCommand()
const [fr, setFr] = useState('')
const [en, setEn] = useState('')
const [kind, setKind] = useState('')
const create = () => {
const incomplete =
isBlank(fr) || isBlank(en) || (pending.kind === 'category' && !kind)
if (incomplete) {
edit.reject('form', 'editor.findings.required')
return
}
let createdId = ''
const added = edit.runNew('form', PREFIX[pending.kind], (id) => {
createdId = id
return insertCommand(pending, id, { fr, en }, kind)
})
if (added) onCreated(createdId)
}
return (
<div className="space-y-2 rounded-lg border border-dashed border-[var(--color-border)] p-3">
<p className="text-sm font-medium">
{t(`editor.findings.new.${pending.kind}`)}
</p>
<div className="grid gap-3 md:grid-cols-2">
{pending.kind === 'category' && (
<SelectField
id="finding-new-kind"
label={t('editor.findings.kind')}
value={kind}
options={[
{ value: '', label: t('editor.field.choose') },
...CATEGORY_KINDS.map((k) => ({
value: k,
label: t(`editor.findings.kind.${k}`),
})),
]}
onCommit={setKind}
/>
)}
<DraftField
id="finding-new-name-fr"
label={t('editor.general.name_fr')}
value={fr}
onChange={setFr}
/>
<DraftField
id="finding-new-name-en"
label={t('editor.general.name_en')}
value={en}
onChange={setEn}
/>
</div>
{edit.fieldError('form') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('form')}
</p>
)}
<div className="flex gap-2">
<ActionButton readOnly={false} variant="secondary" onClick={create}>
{t('editor.findings.create')}
</ActionButton>
<ActionButton readOnly={false} variant="ghost" onClick={onCancel}>
{t('editor.findings.cancel')}
</ActionButton>
</div>
</div>
)
}
const PREFIX: Record<FindingKind, IdPrefix> = {
zone: 'zone',
category: 'fcat',
node: 'node',
}
function insertCommand(
pending: PendingFinding,
id: string,
name: { fr: string; en: string },
kind: string,
): EditCommand {
const parent = pending.parent?.key
if (pending.kind === 'zone') {
return {
op: 'insert',
element: { kind: 'zone', value: { id, name, categories: [] } },
}
}
if (pending.kind === 'category') {
return {
op: 'insert',
parent: { kind: 'zone', id: pending.parent?.zoneId ?? '' },
element: {
kind: 'finding_category',
value: {
id,
kind: kind as FindingCategoryKind,
name,
description: {},
reference_ids: [],
review_status: 'to_confirm',
children: [],
},
},
}
}
const node: FindingNode = {
id,
name,
description: {},
requires_vet_referral: false,
reference_ids: [],
review_status: 'to_confirm',
children: [],
}
return {
op: 'insert',
parent,
element: { kind: 'finding_node', value: node },
}
}
@@ -0,0 +1,144 @@
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 StatusBadge from '@/components/editor/findings/StatusBadge'
import { withName, type FindingItem } from '@/editor/findings/tree'
import { isBlank } from '@/editor/sheetDocument'
import { useEditCommand, type EditCommandApi } from '@/editor/useEditCommand'
import type { Locale } from '@/i18n/types'
import { useT } from '@/i18n/useT'
export interface FindingDetailProps {
item: FindingItem
readOnly: boolean
onDelete: () => void
}
/** The selected element: its names, its review state and the actions on it. */
export default function FindingDetail({
item,
readOnly,
onDelete,
}: FindingDetailProps) {
const t = useT()
const edit = useEditCommand()
return (
<div className="space-y-3 rounded-lg border border-[var(--color-border)] p-3">
<div className="flex flex-wrap items-center gap-2">
<p className="text-sm font-medium">
{t(`editor.findings.type.${item.kind}`)}
</p>
{item.status && <StatusBadge status={item.status} />}
</div>
<Names 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
index={item.index}
count={item.siblings}
readOnly={readOnly}
onMove={(position) =>
edit.run('actions', { op: 'move', key: item.key, position })
}
/>
<ActionButton
readOnly={readOnly}
variant="danger"
size="sm"
onClick={onDelete}
>
{t('editor.action.delete')}
</ActionButton>
</div>
{edit.fieldError('actions') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('actions')}
</p>
)}
</div>
)
}
function Names({
item,
readOnly,
edit,
}: {
item: FindingItem
readOnly: boolean
edit: EditCommandApi
}) {
const t = useT()
const rename = (locale: Locale) => (value: string) =>
isBlank(value)
? edit.reject(locale, 'editor.field.required')
: edit.run(locale, {
op: 'update',
key: item.key,
element: withName(item, { ...item.name, [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-name-${locale}`}
label={t(`editor.general.name_${locale}`)}
value={item.name[locale]}
onCommit={rename(locale)}
readOnly={readOnly}
error={edit.fieldError(locale)}
/>
))}
</div>
)
}
function statusCommand(
item: FindingItem,
status: 'reviewed' | 'to_confirm',
): EditCommand {
const wholeBranch = status === 'reviewed' && item.kind !== 'node'
return wholeBranch
? { op: 'mark_reviewed', key: item.key }
: { op: 'set_status', key: item.key, status }
}
function ReviewActions({
item,
readOnly,
edit,
}: {
item: FindingItem
readOnly: boolean
edit: EditCommandApi
}) {
const t = useT()
const canMark = item.kind === 'zone' || item.status !== 'reviewed'
const canReset = item.kind !== 'zone' && item.status === 'reviewed'
return (
<>
{canMark && (
<ActionButton
readOnly={readOnly}
variant="secondary"
size="sm"
onClick={() => edit.run('actions', statusCommand(item, 'reviewed'))}
>
{t('editor.findings.mark_reviewed')}
</ActionButton>
)}
{canReset && (
<ActionButton
readOnly={readOnly}
variant="secondary"
size="sm"
onClick={() => edit.run('actions', statusCommand(item, 'to_confirm'))}
>
{t('editor.findings.reset_to_confirm')}
</ActionButton>
)}
</>
)
}
@@ -0,0 +1,126 @@
import { useEffect, useRef, type KeyboardEvent } from 'react'
import StatusBadge from '@/components/editor/findings/StatusBadge'
import { keyMove, type FindingItem } from '@/editor/findings/tree'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
export interface FindingTreeProps {
visible: readonly FindingItem[]
selectedId: string | null
expanded: ReadonlySet<string>
onSelect: (id: string) => void
onToggle: (id: string, open: boolean) => void
}
/**
* The findings tree (WAI-ARIA tree pattern): one tab stop, arrows move and open, the
* selected item is the one the actions below act on. Items are a flat list with
* `aria-level`, so the markup stays valid whatever the depth.
*/
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
useEffect(() => {
if (focusAfter.current) refs.current.get(focusAfter.current)?.focus()
focusAfter.current = null
})
const current = visible.find((item) => item.id === selectedId) ?? visible[0]
const onKeyDown = (event: KeyboardEvent, item: FindingItem) => {
const move = keyMove(visible, item, expanded, event.key)
if (!move) return
event.preventDefault()
if (move.expand) onToggle(move.expand, true)
if (move.collapse) onToggle(move.collapse, false)
if (move.select) {
focusAfter.current = move.select
onSelect(move.select)
}
}
return (
<ul
role="tree"
aria-label={t('editor.findings.tree')}
className="space-y-0.5"
>
{visible.map((item) => (
<TreeRow
key={item.id}
item={item}
tabbable={item.id === current?.id}
selected={item.id === selectedId}
open={expanded.has(item.id)}
register={(el) => {
if (el) refs.current.set(item.id, el)
else refs.current.delete(item.id)
}}
onKeyDown={onKeyDown}
onSelect={onSelect}
onToggle={onToggle}
/>
))}
</ul>
)
}
interface TreeRowProps {
item: FindingItem
tabbable: boolean
selected: boolean
open: boolean
register: (el: HTMLElement | null) => void
onKeyDown: (event: KeyboardEvent, item: FindingItem) => void
onSelect: (id: string) => void
onToggle: (id: string, open: boolean) => void
}
function TreeRow({
item,
tabbable,
selected,
open,
register,
onKeyDown,
onSelect,
onToggle,
}: TreeRowProps) {
const locale = useLocaleStore((s) => s.locale)
return (
<li
ref={register}
role="treeitem"
aria-level={item.level}
aria-setsize={item.siblings}
aria-posinset={item.index + 1}
aria-selected={selected}
aria-expanded={item.hasChildren ? open : undefined}
tabIndex={tabbable ? 0 : -1}
data-testid="finding-item"
onKeyDown={(event) => {
if (event.target === event.currentTarget) onKeyDown(event, item)
}}
onClick={() => onSelect(item.id)}
style={{ paddingLeft: `${(item.level - 1) * 1.25 + 0.5}rem` }}
className={`flex cursor-pointer items-center gap-2 rounded-md py-1.5 pr-2 text-sm ${
selected
? 'bg-[var(--color-surface-strong)] font-medium'
: 'hover:bg-[var(--color-surface-strong)]'
}`}
>
<span
aria-hidden="true"
className="w-4 shrink-0 text-center"
onClick={(event) => {
if (!item.hasChildren) return
event.stopPropagation()
onToggle(item.id, !open)
}}
>
{item.hasChildren ? (open ? '▾' : '▸') : ''}
</span>
<span className="min-w-0 flex-1 truncate">{item.name[locale]}</span>
{item.status && <StatusBadge status={item.status} />}
</li>
)
}
@@ -0,0 +1,17 @@
import type { ReviewStatus } from '@faunosteo/core-wasm/types'
import Badge from '@/components/ui/Badge'
import { useT } from '@/i18n/useT'
const TONES = {
to_confirm: 'warn',
reviewed: 'accent',
inherited: 'neutral',
} as const
/** The review badge of a category or a node; a zone has none. */
export default function StatusBadge({ status }: { status: ReviewStatus }) {
const t = useT()
return (
<Badge tone={TONES[status]}>{t(`editor.findings.status.${status}`)}</Badge>
)
}
@@ -1,14 +1,93 @@
import { useMemo, useState } from 'react'
import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import AddBar from '@/components/editor/findings/AddBar'
import FindingCreateForm, {
type PendingFinding,
} from '@/components/editor/findings/FindingCreateForm'
import FindingDetail from '@/components/editor/findings/FindingDetail'
import FindingTree from '@/components/editor/findings/FindingTree'
import {
buildItems,
createdItemId,
visibleItems,
type FindingItem,
} from '@/editor/findings/tree'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { EditorTabProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
/** Placeholder: Lot I replaces the body and keeps the props contract (`EditorTabProps`). */
export default function FindingsTab(_props: EditorTabProps) {
/** Constats: the tree zones → categories → nodes, edited one command at a time. */
export default function FindingsTab({ readOnly }: EditorTabProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const doc = useSheetDocument()
const [selectedId, setSelectedId] = useState<string | null>(null)
const [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set())
const [seeded, setSeeded] = useState(false)
const [pending, setPending] = useState<PendingFinding | null>(null)
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
const items = useMemo(() => (doc ? buildItems(doc) : []), [doc])
if (doc && !seeded) {
setSeeded(true)
setExpanded(
new Set(items.filter((i) => i.kind === 'zone').map((i) => i.id)),
)
}
const selected = items.find((item) => item.id === selectedId)
const toggle = (id: string, open: boolean) =>
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) =>
setDeleting({ key: item.key, label: item.name[locale] })
return (
<section
data-testid="editor-tab-findings"
aria-label={t('editor.tab.findings')}
className="min-h-24"
/>
className="min-h-24 space-y-3"
>
<AddBar selected={selected} readOnly={readOnly} onStart={setPending} />
{pending && !readOnly && (
<FindingCreateForm
key={`${pending.kind}-${pending.parent?.id ?? ''}`}
pending={pending}
onCreated={created}
onCancel={() => setPending(null)}
/>
)}
{doc && items.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.empty')}
</p>
)}
<FindingTree
visible={visibleItems(items, expanded)}
selectedId={selected?.id ?? null}
expanded={expanded}
onSelect={setSelectedId}
onToggle={toggle}
/>
{selected && (
<FindingDetail
key={selected.id}
item={selected}
readOnly={readOnly}
onDelete={() => askDelete(selected)}
/>
)}
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
</section>
)
}
+203
View File
@@ -0,0 +1,203 @@
import type {
AnatomicalSheetDocument,
ElementKey,
FindingCategory,
FindingNode,
FindingZone,
LocalizedText,
ReviewStatus,
} from '@faunosteo/core-wasm/types'
/**
* Levels a finding may have under its zone (category = 1). The core refuses a deeper
* insert (`too_deep`); the page only stops offering the button.
*/
export const MAX_FINDING_PATH = 8
export type FindingKind = 'zone' | 'category' | 'node'
/** One element of the tree, flattened in document order. */
export interface FindingItem {
/** Stable within the document: zone id then the path ids, as JSON. */
id: string
key: ElementKey
kind: FindingKind
zoneId: string
path: readonly string[]
/** `aria-level`: zone 1, category 2, nodes below. */
level: number
name: LocalizedText
/** null for a zone: it has no status. */
status: ReviewStatus | null
parentId: string | null
/** Position among its siblings and their count. */
index: number
siblings: number
hasChildren: boolean
/** The element as `update` takes it. */
element: FindingElement
}
export type FindingElement =
| { kind: 'zone'; value: FindingZone }
| { 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(
item: FindingItem,
name: LocalizedText,
): FindingElement {
const { element } = item
switch (element.kind) {
case 'zone':
return { kind: 'zone', value: { ...element.value, name } }
case 'finding_category':
return { kind: 'finding_category', value: { ...element.value, name } }
case 'finding_node':
return { kind: 'finding_node', value: { ...element.value, name } }
}
}
export const itemId = (zoneId: string, path: readonly string[]): string =>
JSON.stringify([zoneId, ...path])
function nodeItems(
zone: FindingZone,
nodes: readonly FindingNode[],
path: readonly string[],
parentId: string,
): FindingItem[] {
return nodes.flatMap((node, index) => {
const here = [...path, node.id]
const id = itemId(zone.id, here)
const self: FindingItem = {
id,
key: { kind: 'finding', zone_id: zone.id, path: here },
kind: 'node',
zoneId: zone.id,
path: here,
level: here.length + 1,
name: node.name,
status: node.review_status,
parentId,
index,
siblings: nodes.length,
hasChildren: node.children.length > 0,
element: { kind: 'finding_node', value: node },
}
return [self, ...nodeItems(zone, node.children, here, id)]
})
}
function categoryItems(zone: FindingZone, zoneItemId: string): FindingItem[] {
return zone.categories.flatMap((category, index) => {
const path = [category.id]
const id = itemId(zone.id, path)
const self: FindingItem = {
id,
key: { kind: 'finding', zone_id: zone.id, path },
kind: 'category',
zoneId: zone.id,
path,
level: 2,
name: category.name,
status: category.review_status,
parentId: zoneItemId,
index,
siblings: zone.categories.length,
hasChildren: category.children.length > 0,
element: { kind: 'finding_category', value: category },
}
return [self, ...nodeItems(zone, category.children, path, id)]
})
}
/** Every element of the findings tree in document order, collapsed or not. */
export function buildItems(doc: AnatomicalSheetDocument): FindingItem[] {
return doc.finding_zones.flatMap((zone, index) => {
const id = itemId(zone.id, [])
const self: FindingItem = {
id,
key: { kind: 'zone', id: zone.id },
kind: 'zone',
zoneId: zone.id,
path: [],
level: 1,
name: zone.name,
status: null,
parentId: null,
index,
siblings: doc.finding_zones.length,
hasChildren: zone.categories.length > 0,
element: { kind: 'zone', value: zone },
}
return [self, ...categoryItems(zone, id)]
})
}
/** The items whose ancestors are all expanded. */
export function visibleItems(
items: readonly FindingItem[],
expanded: ReadonlySet<string>,
): FindingItem[] {
const shown = new Set<string>()
return items.filter((item) => {
const open =
item.parentId === null ||
(shown.has(item.parentId) && expanded.has(item.parentId))
if (open) shown.add(item.id)
return open
})
}
export const canAddNode = (item: FindingItem | undefined): boolean =>
item !== undefined &&
item.kind !== 'zone' &&
item.path.length < MAX_FINDING_PATH
export interface TreeMove {
select?: string
expand?: string
collapse?: string
}
/** WAI-ARIA tree keys: what a key does from `current`, among the visible items. */
export function keyMove(
visible: readonly FindingItem[],
current: FindingItem,
expanded: ReadonlySet<string>,
key: string,
): TreeMove | null {
const at = visible.findIndex((item) => item.id === current.id)
const open = expanded.has(current.id)
switch (key) {
case 'ArrowDown':
return at < visible.length - 1 ? { select: visible[at + 1].id } : null
case 'ArrowUp':
return at > 0 ? { select: visible[at - 1].id } : null
case 'Home':
return { select: visible[0].id }
case 'End':
return { select: visible[visible.length - 1].id }
case 'ArrowRight':
if (!current.hasChildren) return null
return open ? { select: visible[at + 1].id } : { expand: current.id }
case 'ArrowLeft':
if (open && current.hasChildren) return { collapse: current.id }
return current.parentId ? { select: current.parentId } : null
default:
return null
}
}
/** The item id of a just-inserted element, appended under `parent` (null = a zone). */
export function createdItemId(
kind: FindingKind,
parent: FindingItem | null,
id: string,
): string {
if (kind === 'zone' || !parent) return itemId(id, [])
const path = kind === 'category' ? [id] : [...parent.path, id]
return itemId(parent.zoneId, path)
}
+24
View File
@@ -1410,4 +1410,28 @@ export const en: Dict = {
'editor.cleaning.style': 'The <style> element was removed: the classes it defined will show unstyled.',
'editor.cleaning.confirm': 'Clean and use this version',
'editor.cleaning.cancel': 'Cancel',
'editor.findings.tree': 'Findings tree',
'editor.findings.status.to_confirm': 'To confirm',
'editor.findings.status.reviewed': 'Reviewed',
'editor.findings.status.inherited': 'Inherited, not reviewed',
'editor.findings.type.zone': 'Findings zone',
'editor.findings.type.category': 'Findings category',
'editor.findings.type.node': 'Finding',
'editor.findings.add_zone': 'Add a zone',
'editor.findings.add_category': 'Add a category',
'editor.findings.add_node': 'Add a finding',
'editor.findings.new.zone': 'New findings zone',
'editor.findings.new.category': 'New findings category',
'editor.findings.new.node': 'New finding',
'editor.findings.kind': 'Category type',
'editor.findings.kind.dysfunction': 'Dysfunction',
'editor.findings.kind.consultation_reason': 'Reason for consultation',
'editor.findings.kind.anamnesis': 'Anamnesis',
'editor.findings.kind.custom': 'Custom',
'editor.findings.required': 'Fill in the name in French and English (and the type of a category).',
'editor.findings.create': 'Create',
'editor.findings.cancel': 'Cancel',
'editor.findings.empty': 'No findings zone yet.',
'editor.findings.mark_reviewed': 'Mark as reviewed',
'editor.findings.reset_to_confirm': 'Reset to confirm',
}
+24
View File
@@ -1441,4 +1441,28 @@ export const fr: Dict = {
'editor.cleaning.style': "L'élément <style> a été retiré : les classes qu'il définissait s'afficheront sans style.",
'editor.cleaning.confirm': 'Nettoyer et utiliser cette version',
'editor.cleaning.cancel': 'Annuler',
'editor.findings.tree': 'Arbre des constats',
'editor.findings.status.to_confirm': 'À confirmer',
'editor.findings.status.reviewed': 'Relu',
'editor.findings.status.inherited': 'Hérité, non relu',
'editor.findings.type.zone': 'Zone de constats',
'editor.findings.type.category': 'Catégorie de constats',
'editor.findings.type.node': 'Constat',
'editor.findings.add_zone': 'Ajouter une zone',
'editor.findings.add_category': 'Ajouter une catégorie',
'editor.findings.add_node': 'Ajouter un constat',
'editor.findings.new.zone': 'Nouvelle zone de constats',
'editor.findings.new.category': 'Nouvelle catégorie de constats',
'editor.findings.new.node': 'Nouveau constat',
'editor.findings.kind': 'Type de catégorie',
'editor.findings.kind.dysfunction': 'Dysfonction',
'editor.findings.kind.consultation_reason': 'Motif de consultation',
'editor.findings.kind.anamnesis': 'Anamnèse',
'editor.findings.kind.custom': 'Personnalisée',
'editor.findings.required': "Renseignez le nom en français et en anglais (et le type d'une catégorie).",
'editor.findings.create': 'Créer',
'editor.findings.cancel': 'Annuler',
'editor.findings.empty': "Aucune zone de constats pour l'instant.",
'editor.findings.mark_reviewed': 'Marquer comme relu',
'editor.findings.reset_to_confirm': 'Remettre à confirmer',
}
@@ -0,0 +1,358 @@
/** Lot I: the Constats tree. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type {
AnatomicalSheetDocument,
FindingNode,
} from '@faunosteo/core-wasm/types'
import FindingsTab from '@/components/editor/tabs/FindingsTab'
import { buildItems, keyMove, visibleItems } from '@/editor/findings/tree'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
baseText,
openReady,
resetStore,
store,
} from '../helpers/editorHarness'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
getSheetVersion: vi.fn(),
downloadSheetDrawing: vi.fn(),
saveSheetDraft: vi.fn(),
getOfficialSheetAdmin: vi.fn(),
submitSheetReview: vi.fn(),
}))
const props = { readOnly: false, onSelectTab: vi.fn(), reloadSheet: vi.fn() }
const doc = (): AnatomicalSheetDocument =>
JSON.parse(store.getState().documentText)
const name = (n: string) => ({ fr: n, en: n })
const node = (id: string): FindingNode => ({
id,
name: name(id),
description: {},
requires_vet_referral: false,
reference_ids: [],
review_status: 'to_confirm',
children: [],
})
/** zone-a > fcat-a > node-a > node-b, and zone-b alone. */
function treeText(): string {
let text = insert(baseText(), {
kind: 'zone',
value: { id: 'zone-a', name: name('Zone A'), categories: [] },
})
text = insert(text, {
kind: 'zone',
value: { id: 'zone-b', name: name('Zone B'), categories: [] },
})
text = edit(text, {
op: 'insert',
parent: { kind: 'zone', id: 'zone-a' },
element: {
kind: 'finding_category',
value: {
id: 'fcat-a',
kind: 'dysfunction',
name: name('Cat A'),
description: {},
reference_ids: [],
review_status: 'to_confirm',
children: [],
},
},
})
const under = (id: string, path: string[]) =>
edit(text, {
op: 'insert',
parent: { kind: 'finding', zone_id: 'zone-a', path },
element: { kind: 'finding_node', value: node(id) },
})
text = under('node-a', ['fcat-a'])
return under('node-b', ['fcat-a', 'node-a'])
}
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
})
const items = () => screen.getAllByRole('treeitem')
const labels = () => items().map((i) => i.textContent ?? '')
describe('findings tree model', () => {
it('flattens in order and hides collapsed branches', async () => {
await openReady({ text: treeText() })
const all = buildItems(doc())
expect(all.map((i) => i.level)).toEqual([1, 2, 3, 4, 1])
const shown = visibleItems(all, new Set(['["zone-a"]']))
expect(shown.map((i) => i.kind)).toEqual(['zone', 'category', 'zone'])
})
it('maps the WAI-ARIA keys', async () => {
await openReady({ text: treeText() })
const all = buildItems(doc())
const open = new Set(all.map((i) => i.id))
const [zone, category] = all
expect(keyMove(all, zone, open, 'ArrowDown')).toEqual({
select: category.id,
})
expect(keyMove(all, category, open, 'ArrowLeft')).toEqual({
collapse: category.id,
})
expect(keyMove(all, all[4], open, 'ArrowRight')).toBeNull()
expect(keyMove(all, all[4], open, 'End')).toEqual({ select: all[4].id })
expect(keyMove(all, zone, new Set(), 'ArrowRight')).toEqual({
expand: zone.id,
})
})
})
describe('Constats tab', () => {
it('renders a tree with levels, and zones carry no badge', async () => {
await openReady({ text: treeText() })
render(<FindingsTab {...props} />)
expect(screen.getByRole('tree')).toBeInTheDocument()
const [zoneA] = items()
expect(zoneA).toHaveAttribute('aria-level', '1')
expect(zoneA).toHaveAttribute('aria-expanded', 'true')
expect(within(zoneA).queryByText('À confirmer')).toBeNull()
expect(items()).toHaveLength(3)
expect(within(items()[1]).getByText('À confirmer')).toBeInTheDocument()
})
it('moves with the arrows, opens and closes branches', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
items()[0].focus()
await user.keyboard('{ArrowDown}')
expect(items()[1]).toHaveFocus()
expect(items()[1]).toHaveAttribute('aria-selected', 'true')
await user.keyboard('{ArrowRight}')
expect(items()).toHaveLength(4)
await user.keyboard('{ArrowRight}')
expect(items()[2]).toHaveFocus()
await user.keyboard('{ArrowLeft}')
expect(items()[1]).toHaveFocus()
await user.keyboard('{ArrowLeft}')
expect(items()).toHaveLength(3)
await user.keyboard('{ArrowLeft}')
expect(items()[0]).toHaveFocus()
})
it('creates a zone only with both names', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(screen.getByRole('button', { name: 'Ajouter une zone' }))
await user.type(
screen.getByLabelText('Nom (FR)', { selector: '#finding-new-name-fr' }),
'Tête',
)
await user.click(screen.getByRole('button', { name: 'Créer' }))
expect(screen.getByRole('alert')).toHaveTextContent('Renseignez le nom')
expect(doc().finding_zones).toHaveLength(2)
await user.type(
screen.getByLabelText('Nom (EN)', { selector: '#finding-new-name-en' }),
'Head',
)
await user.click(screen.getByRole('button', { name: 'Créer' }))
expect(doc().finding_zones).toHaveLength(3)
expect(doc().finding_zones[2].id).toMatch(/^zone-[a-z2-7]{10}$/)
expect(
screen.getByLabelText('Nom (FR)', { selector: '#finding-name-fr' }),
).toHaveValue('Tête')
})
it('creates a category with a kind and a node under the selection', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(items()[0])
await user.click(
screen.getByRole('button', { name: 'Ajouter une catégorie' }),
)
await user.type(
screen.getByLabelText('Nom (FR)', { selector: '#finding-new-name-fr' }),
'Nouv',
)
await user.type(
screen.getByLabelText('Nom (EN)', { selector: '#finding-new-name-en' }),
'New',
)
await user.click(screen.getByRole('button', { name: 'Créer' }))
expect(screen.getByRole('alert')).toBeInTheDocument()
await user.selectOptions(
screen.getByLabelText('Type de catégorie'),
'anamnesis',
)
await user.click(screen.getByRole('button', { name: 'Créer' }))
const categories = doc().finding_zones[0].categories
expect(categories).toHaveLength(2)
expect(categories[1]).toMatchObject({
kind: 'anamnesis',
review_status: 'to_confirm',
})
await user.click(screen.getByRole('button', { name: 'Ajouter un constat' }))
await user.type(
screen.getByLabelText('Nom (FR)', { selector: '#finding-new-name-fr' }),
'Fr',
)
await user.type(
screen.getByLabelText('Nom (EN)', { selector: '#finding-new-name-en' }),
'En',
)
await user.click(screen.getByRole('button', { name: 'Créer' }))
expect(doc().finding_zones[0].categories[1].children).toHaveLength(1)
})
it('disables « Ajouter un constat » on a zone and at depth 8', async () => {
let text = treeText()
let path = ['fcat-a', 'node-a', 'node-b']
for (let i = 0; i < 5; i++) {
const id = `deep-${i}`
text = edit(text, {
op: 'insert',
parent: { kind: 'finding', zone_id: 'zone-a', path },
element: { kind: 'finding_node', value: node(id) },
})
path = [...path, id]
}
await openReady({ text })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
const add = screen.getByRole('button', { name: 'Ajouter un constat' })
await user.click(items()[0])
expect(add).toBeDisabled()
await user.click(items()[1])
for (let i = 0; i < 30; i++) {
if (document.activeElement?.getAttribute('aria-level') === '8') break
await user.keyboard('{ArrowRight}')
}
expect(add).toBeEnabled()
await user.keyboard('{ArrowRight}{ArrowRight}')
expect(document.activeElement).toHaveAttribute('aria-level', '9')
expect(add).toBeDisabled()
})
it('renames, marks reviewed and resets to confirm', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(items()[1])
await user.click(screen.getByRole('button', { name: 'Marquer comme relu' }))
expect(doc().finding_zones[0].categories[0].review_status).toBe('reviewed')
expect(within(items()[1]).getByText('Relu')).toBeInTheDocument()
await user.click(
screen.getByRole('button', { name: 'Remettre à confirmer' }),
)
expect(doc().finding_zones[0].categories[0].review_status).toBe(
'to_confirm',
)
const fr = screen.getByLabelText('Nom (FR)', {
selector: '#finding-name-fr',
})
await user.clear(fr)
await user.type(fr, 'Renommée')
await user.tab()
expect(doc().finding_zones[0].categories[0].name.fr).toBe('Renommée')
})
it('marks a node with set_status and a zone with mark_reviewed', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(items()[0])
expect(
screen.queryByRole('button', { name: 'Remettre à confirmer' }),
).toBeNull()
await user.click(screen.getByRole('button', { name: 'Marquer comme relu' }))
const cat = doc().finding_zones[0].categories[0]
expect(cat.review_status).toBe('reviewed')
expect(cat.children[0].children[0].review_status).toBe('reviewed')
await user.click(items()[1])
await user.keyboard('{ArrowRight}{ArrowDown}')
await user.click(
screen.getByRole('button', { name: 'Remettre à confirmer' }),
)
expect(doc().finding_zones[0].categories[0].children[0].review_status).toBe(
'to_confirm',
)
})
it('reorders siblings with the arrows', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(items()[1])
expect(screen.getByRole('button', { name: 'Monter' })).toBeDisabled()
await user.click(items()[0])
await user.click(screen.getByRole('button', { name: 'Descendre' }))
expect(doc().finding_zones.map((z) => z.id)).toEqual(['zone-b', 'zone-a'])
expect(labels()[0]).toContain('Zone B')
})
it('deletes with the descendants listed, then removes them', async () => {
await openReady({ text: treeText() })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(items()[1])
await user.click(screen.getByRole('button', { name: 'Supprimer' }))
const dialog = await screen.findByRole('dialog')
expect(within(dialog).getByText(/aussi supprimés/)).toBeInTheDocument()
expect(within(dialog).getAllByRole('listitem')).toHaveLength(2)
await user.click(within(dialog).getByRole('button', { name: 'Supprimer' }))
expect(doc().finding_zones[0].categories).toEqual([])
expect(screen.queryByText('Cat A')).toBeNull()
})
it('lists the annotations that still use a zone and offers no deletion', async () => {
let text = treeText()
const anno = JSON.parse(text).annotations[0]
text = edit(text, {
op: 'update',
key: { kind: 'annotation', id: 'anno-a' },
element: {
kind: 'annotation',
value: { ...anno, finding_zone_id: 'zone-a' },
},
})
await openReady({ text })
const user = userEvent.setup()
render(<FindingsTab {...props} />)
await user.click(items()[0])
await user.click(screen.getByRole('button', { name: 'Supprimer' }))
const dialog = await screen.findByRole('dialog')
expect(
within(dialog).getByText(/ne peut pas être supprimé/),
).toBeInTheDocument()
expect(
within(dialog).queryByRole('button', { name: 'Supprimer' }),
).toBeNull()
expect(doc().finding_zones).toHaveLength(2)
})
it('is plain text and keyboard-navigable when read-only', async () => {
await openReady({ text: treeText() })
render(<FindingsTab {...props} readOnly />)
expect(
screen.queryByRole('button', { name: 'Ajouter une zone' }),
).toBeNull()
expect(screen.queryByRole('button', { name: 'Supprimer' })).toBeNull()
expect(items()).toHaveLength(3)
const user = userEvent.setup()
await user.click(items()[1])
expect(screen.queryByRole('textbox')).toBeNull()
expect(document.querySelector('#finding-name-fr')).toHaveTextContent(
'Cat A',
)
})
})