feat(app): Aller à selects the element in its tab, reload after submit

This commit is contained in:
bchanot committed 2026-11-04 14:06:09 +01:00
1 parent 2a54fa4c78
commit 4f223e04cd
24 files changed
+473 -66

No files matched your search

@@ -391,7 +391,7 @@ Every key below is a proposal for the owner's separate review; none is declared
| `editor.verification.to_confirm` | {count} éléments à confirmer | {count} items to confirm | Badge | L28 FR/EN |
| `editor.verification.none` | Aucun problème détecté | No issues found | Panel, no issue | L27 FR/EN |
| `editor.verification.warnings_title` | Avertissements | Warnings | Heading over the warnings | proposal |
| `editor.verification.goto` | Aller à {tab} | Go to {tab} | Issue button (tab name filled in) | plan wording « Aller à … »; form proposal |
| `editor.verification.goto` | Aller à {tab} | Go to {tab} | Issue button ({tab} = the element name, else the tab name) | plan wording « Aller à … »; form proposal |
| `editor.verification.to_confirm_info` | Des éléments restent à confirmer : cela n'empêche pas la soumission. | Some items are still to confirm: this does not prevent submission. | Info notice on to_confirm elements | proposal |
| `editor.verification.completeness` | Complétude | Completeness | Section heading | proposal |
| `editor.verification.vet_referrals` | {count} renvoi(s) vers un vétérinaire | {count} veterinary referral(s) | Completeness line | proposal |
@@ -30,7 +30,8 @@ import {
storeCanEdit,
} from '@/editor/mode'
import { leaveGuardArmed, useEditorStore } from '@/editor/state/editorStore'
import type { EditorTabId } from '@/editor/tabs'
import type { FocusRequest } from '@/editor/focusRequest'
import type { EditorTabId, EditorTabProps } from '@/editor/tabs'
import { useUndoShortcuts } from '@/editor/useUndoShortcuts'
import { useTabTier } from '@/editor/useViewport'
import { useAuthStore } from '@/state/authStore'
@@ -78,6 +79,11 @@ function DraftEditor({
const t = useT()
const tier = useTabTier()
const [tab, setTab] = useState<EditorTabId>(FIRST_TAB)
const [focus, setFocus] = useState<FocusRequest | undefined>()
const goTo: EditorTabProps['onGoTo'] = (next, key) => {
setTab(next)
setFocus((prev) => ({ key, serial: (prev?.serial ?? 0) + 1 }))
}
const saveFailure = useEditorStore((s) => s.saveFailure)
const status = useEditorStore((s) => s.status)
const sessionVersion = useEditorStore((s) => s.versionId)
@@ -127,6 +133,8 @@ function DraftEditor({
tab={tab}
readOnly={readOnly}
onSelectTab={setTab}
focus={focus}
onGoTo={goTo}
reloadSheet={reloadSheet}
/>
</div>
@@ -4,6 +4,8 @@ import type {
Annotation,
} from '@faunosteo/core-wasm/types'
import type { CommitContext } from '@/editor/annotations/annotationCommit'
import { annotationFocus } from '@/editor/annotations/focusTarget'
import { useFocusRequest } from '@/editor/focusRequest'
import { keyboardPending, type NewKind } from '@/editor/annotations/creation'
import { parseFrame, type Frame } from '@/editor/annotations/frame'
import { isEditable } from '@/editor/annotations/geometryEdit'
@@ -36,6 +38,7 @@ import ViewSwitcher from './ViewSwitcher'
interface Props {
doc: AnatomicalSheetDocument
onSelectTab: EditorTabProps['onSelectTab']
focus: EditorTabProps['focus']
}
/** What both columns read: the tab's state, the view, its frame and its selection. */
@@ -52,8 +55,14 @@ interface Scene {
onSelectTab: EditorTabProps['onSelectTab']
}
function useScene({ doc, onSelectTab }: Props): Scene {
function useScene({ doc, onSelectTab, focus }: Props): Scene {
const [ui, dispatch] = useReducer(uiReducer, initialUi)
useFocusRequest(focus, (key) => {
const target = annotationFocus(doc, key)
if (!target) return
dispatch({ type: 'view', viewId: target.viewId })
dispatch({ type: 'select', id: target.annotationId })
})
const [root, setRoot] = useState<RootAttributes | null>(null)
const viewId = ui.viewId ?? mainViewId(doc)
const model = useViewModel(doc, viewId)
@@ -1,3 +1,4 @@
import { FOCUS_CLASS, focusAttrs } from '@/editor/focusRequest'
import { useState } from 'react'
import type {
AnatomicalSheetDocument,
@@ -75,7 +76,10 @@ function CategoryRow({
: send(locale, { name: { ...category.name, [locale]: value } })
const prefix = `category-${category.id}`
return (
<li className="rounded-lg border border-[var(--color-border)] p-3">
<li
{...focusAttrs({ kind: 'category', id: category.id })}
className={`rounded-lg border border-[var(--color-border)] p-3 ${FOCUS_CLASS}`}
>
<div className="grid gap-3 md:grid-cols-3">
{(['fr', 'en'] as const).map((locale) => (
<TextField
@@ -3,6 +3,7 @@ import ActionButton from '@/components/editor/fields/ActionButton'
import MoveButtons from '@/components/editor/fields/MoveButtons'
import SelectField from '@/components/editor/fields/SelectField'
import TextField from '@/components/editor/fields/TextField'
import { FOCUS_CLASS, focusAttrs } from '@/editor/focusRequest'
import { isBlank, nullable } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
@@ -37,7 +38,10 @@ export default function ReferenceRow({
}))
const prefix = `reference-${reference.id}`
return (
<li className="space-y-3 rounded-lg border border-[var(--color-border)] p-3">
<li
{...focusAttrs(key)}
className={`space-y-3 rounded-lg border border-[var(--color-border)] p-3 ${FOCUS_CLASS}`}
>
<div className="grid gap-3 md:grid-cols-2">
<SelectField
id={`${prefix}-type`}
@@ -8,6 +8,8 @@ import EditableAnnotations from '@/components/editor/annotations/EditableAnnotat
import PropertiesPanel from '@/components/editor/annotations/PropertiesPanel'
import ViewSwitcher from '@/components/editor/annotations/ViewSwitcher'
import SelectionTag from '@/components/editor/annotations/SelectionTag'
import { annotationFocus } from '@/editor/annotations/focusTarget'
import { useFocusRequest } from '@/editor/focusRequest'
import { mainViewId, useViewModel } from '@/editor/annotations/useViewModel'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useEditorStore } from '@/editor/state/editorStore'
@@ -31,10 +33,18 @@ export default function AnnotationsTab(props: EditorTabProps) {
className="min-h-24 space-y-3"
>
{doc && preview && props.readOnly && (
<ReadOnlyAnnotations doc={doc} onSelectTab={props.onSelectTab} />
<ReadOnlyAnnotations
doc={doc}
onSelectTab={props.onSelectTab}
focus={props.focus}
/>
)}
{doc && preview && !props.readOnly && (
<EditableAnnotations doc={doc} onSelectTab={props.onSelectTab} />
<EditableAnnotations
doc={doc}
onSelectTab={props.onSelectTab}
focus={props.focus}
/>
)}
</section>
)
@@ -43,15 +53,23 @@ export default function AnnotationsTab(props: EditorTabProps) {
function ReadOnlyAnnotations({
doc,
onSelectTab,
focus,
}: {
doc: AnatomicalSheetDocument
onSelectTab: EditorTabProps['onSelectTab']
focus: EditorTabProps['focus']
}) {
const locale = useLocaleStore((s) => s.locale)
const preview = useEditorStore((s) => s.preview)
const handleVersion = useEditorStore((s) => s.handleVersion)
const [viewId, setViewId] = useState(mainViewId(doc))
const [selectedId, setSelectedId] = useState<string | null>(null)
useFocusRequest(focus, (key) => {
const target = annotationFocus(doc, key)
if (!target) return
setViewId(target.viewId)
setSelectedId(target.annotationId)
})
const model = useViewModel(doc, viewId)
const view = doc.views.find((v) => v.id === viewId)
const selected = model.annotations.find((a) => a.id === selectedId)
@@ -13,9 +13,11 @@ import {
createdItemId,
fallbackAfterRemoval,
isUnder,
itemForKey,
visibleItems,
type FindingItem,
} from '@/editor/findings/tree'
import { useFocusRequest } from '@/editor/focusRequest'
import { useEditorStore } from '@/editor/state/editorStore'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { EditorTabProps } from '@/editor/tabs'
@@ -33,7 +35,7 @@ function currentItems(): FindingItem[] {
}
/** Constats: the tree zones → categories → nodes, edited one command at a time. */
export default function FindingsTab({ readOnly }: EditorTabProps) {
export default function FindingsTab({ readOnly, focus }: EditorTabProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const doc = useSheetDocument()
@@ -63,6 +65,13 @@ export default function FindingsTab({ readOnly }: EditorTabProps) {
return next
})
}
useFocusRequest(focus, (key) => {
const found = itemForKey(items, key)
if (!found) return
setExpanded((prev) => new Set([...prev, ...found.ancestors]))
setSelectedId(found.item.id)
setFocusId({ id: found.item.id })
})
const created = (id: string) => {
if (!pending) return
if (pending.parent) toggle(pending.parent.id, true)
@@ -2,12 +2,14 @@ import AttributionSection from '@/components/editor/general/AttributionSection'
import CategoriesSection from '@/components/editor/general/CategoriesSection'
import TextsSection from '@/components/editor/general/TextsSection'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useRowFocus } from '@/editor/focusRequest'
import type { EditorTabProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
/** Général: the sheet's texts, attribution and annotation categories. */
export default function GeneralTab({ readOnly }: EditorTabProps) {
export default function GeneralTab({ readOnly, focus }: EditorTabProps) {
const t = useT()
useRowFocus(focus)
const doc = useSheetDocument()
return (
<section
@@ -5,12 +5,14 @@ import DeleteDialog, {
import ReferenceForm from '@/components/editor/references/ReferenceForm'
import ReferenceRow from '@/components/editor/references/ReferenceRow'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useRowFocus } from '@/editor/focusRequest'
import type { EditorTabProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
/** Références: the sheet's bibliography, cited by id from the findings. */
export default function ReferencesTab({ readOnly }: EditorTabProps) {
export default function ReferencesTab({ readOnly, focus }: EditorTabProps) {
const t = useT()
useRowFocus(focus)
const doc = useSheetDocument()
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
const references = doc?.references ?? []
@@ -27,6 +27,7 @@ function Panel({
doc,
readOnly,
onSelectTab,
onGoTo,
reloadSheet,
}: PanelProps) {
const t = useT()
@@ -47,6 +48,7 @@ function Panel({
tone="error"
doc={doc}
onSelectTab={onSelectTab}
onGoTo={onGoTo}
/>
{warnings.length > 0 && (
<h3 className="text-sm font-medium">
@@ -58,6 +60,7 @@ function Panel({
tone="info"
doc={doc}
onSelectTab={onSelectTab}
onGoTo={onGoTo}
/>
{to_confirm > 0 && (
<Notice tone="info">{t('editor.verification.to_confirm_info')}</Notice>
@@ -5,13 +5,15 @@ import DeleteDialog, {
import RegionForm from '@/components/editor/vertebrae/RegionForm'
import RegionRow from '@/components/editor/vertebrae/RegionRow'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useRowFocus } from '@/editor/focusRequest'
import type { EditorTabProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
/** Vertèbres: the vertebral regions (code, names, count, optional range), ordered. */
export default function VertebraeTab({ readOnly }: EditorTabProps) {
export default function VertebraeTab({ readOnly, focus }: EditorTabProps) {
const t = useT()
useRowFocus(focus)
const locale = useLocaleStore((s) => s.locale)
const doc = useSheetDocument()
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
@@ -6,6 +6,7 @@ import DetailViewForm from '@/components/editor/views/DetailViewForm'
import DetailViewRow from '@/components/editor/views/DetailViewRow'
import MainViewCard from '@/components/editor/views/MainViewCard'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useRowFocus } from '@/editor/focusRequest'
import type { EditorTabProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
@@ -14,8 +15,9 @@ import { useLocaleStore } from '@/state/localeStore'
* Vues et illustrations: the main view and its drawing, the detail views (parent, own
* drawing or crop), the upload of a drawing and the frame changes it brings.
*/
export default function ViewsTab({ readOnly }: EditorTabProps) {
export default function ViewsTab({ readOnly, focus }: EditorTabProps) {
const t = useT()
useRowFocus(focus)
const locale = useLocaleStore((s) => s.locale)
const doc = useSheetDocument()
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
@@ -1,5 +1,6 @@
import type {
AnatomicalSheetDocument,
ElementKey,
SheetIssue,
} from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
@@ -14,6 +15,7 @@ interface IssueListProps {
tone: 'error' | 'info'
doc: AnatomicalSheetDocument
onSelectTab: (tab: EditorTabId) => void
onGoTo?: (tab: EditorTabId, key: ElementKey) => void
}
/** One notice per issue: the page's own message, the element's name, « Aller à … ». */
@@ -22,6 +24,7 @@ export default function IssueList({
tone,
doc,
onSelectTab,
onGoTo,
}: IssueListProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
@@ -44,11 +47,15 @@ export default function IssueList({
size="sm"
variant="secondary"
className="mt-2"
onClick={() => onSelectTab(target.tab)}
onClick={() =>
target.key && onGoTo
? onGoTo(target.tab, target.key)
: onSelectTab(target.tab)
}
>
{t('editor.verification.goto').replace(
'{tab}',
t(`editor.tab.${target.tab}`),
target.name ?? t(`editor.tab.${target.tab}`),
)}
</Button>
)}
@@ -37,13 +37,11 @@ export function useSubmission(reloadSheet: () => void) {
const submit = async () => {
setMessage(null)
const outcome = await useEditorStore.getState().submit(note.trim())
// The round froze the draft: the route refreshes even if this tab is gone.
if (outcome.ok) reloadSheet()
if (!mounted.current) return
if (outcome.ok) {
setNote('')
reloadSheet()
} else {
setMessage(refusalMessage(t, outcome))
}
if (outcome.ok) setNote('')
else setMessage(refusalMessage(t, outcome))
}
return { note, setNote, submit, message }
}
@@ -1,3 +1,4 @@
import { FOCUS_CLASS, focusAttrs } from '@/editor/focusRequest'
import { useState } from 'react'
import type { VertebralRegion } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
@@ -49,7 +50,10 @@ export default function RegionRow({
}
const prefix = `region-${region.code}`
return (
<li className="space-y-3 rounded-lg border border-[var(--color-border)] p-3">
<li
{...focusAttrs({ kind: 'region', code: region.code })}
className={`space-y-3 rounded-lg border border-[var(--color-border)] p-3 ${FOCUS_CLASS}`}
>
<div className="grid gap-3 md:grid-cols-4">
<ReadOnlyValue
id={`${prefix}-code`}
@@ -1,3 +1,4 @@
import { FOCUS_CLASS, focusAttrs } from '@/editor/focusRequest'
import type { DetailView, SheetView } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import SelectField from '@/components/editor/fields/SelectField'
@@ -36,7 +37,8 @@ export default function DetailViewRow({
return (
<li
aria-label={view.name[locale]}
className="space-y-3 rounded-lg border border-[var(--color-border)] p-3"
{...focusAttrs({ kind: 'view', id: view.id })}
className={`space-y-3 rounded-lg border border-[var(--color-border)] p-3 ${FOCUS_CLASS}`}
>
<div className="grid gap-3 md:grid-cols-3">
<ViewNames view={view} readOnly={readOnly} views={edit} />
@@ -1,3 +1,4 @@
import { FOCUS_CLASS, focusAttrs } from '@/editor/focusRequest'
import type { MainView } from '@faunosteo/core-wasm/types'
import { useViewUpdate } from '@/editor/useViewUpdate'
import { useT } from '@/i18n/useT'
@@ -17,7 +18,8 @@ export default function MainViewCard({
return (
<section
aria-labelledby="views-main-title"
className="space-y-3 rounded-lg border border-[var(--color-border)] p-3"
{...focusAttrs({ kind: 'view', id: view.id })}
className={`space-y-3 rounded-lg border border-[var(--color-border)] p-3 ${FOCUS_CLASS}`}
>
<h3 id="views-main-title" className="text-base font-semibold">
{t('editor.views.main_title')}
@@ -0,0 +1,20 @@
import type {
AnatomicalSheetDocument,
ElementKey,
} from '@faunosteo/core-wasm/types'
/** What « Aller à … » seeds in the Annotations tab: a view, and maybe an annotation. */
export function annotationFocus(
doc: AnatomicalSheetDocument,
key: ElementKey,
): { viewId: string; annotationId: string | null } | null {
if (key.kind === 'view') {
const view = doc.views.find((v) => v.id === key.id)
return view ? { viewId: view.id, annotationId: null } : null
}
if (key.kind !== 'annotation') return null
const annotation = doc.annotations.find((a) => a.id === key.id)
return annotation
? { viewId: annotation.view_id, annotationId: annotation.id }
: null
}
+20
View File
@@ -245,3 +245,23 @@ export function createdItemId(
const path = kind === 'category' ? [id] : [...parent.path, id]
return itemId(parent.zoneId, path)
}
/** The item a focus request names (a zone or a finding), with its ancestors' ids. */
export function itemForKey(
items: readonly FindingItem[],
key: ElementKey,
): { item: FindingItem; ancestors: string[] } | null {
const item = items.find((candidate) => sameKey(candidate.key, key))
if (!item) return null
const ancestors: string[] = []
let parent = item.parentId
while (parent !== null) {
ancestors.push(parent)
parent = items.find((i) => i.id === parent)?.parentId ?? null
}
return { item, ancestors }
}
function sameKey(a: ElementKey, b: ElementKey): boolean {
return JSON.stringify(a) === JSON.stringify(b)
}
+48
View File
@@ -0,0 +1,48 @@
import { useEffect, useRef } from 'react'
import type { ElementKey } from '@faunosteo/core-wasm/types'
/** « Aller à … »: the element to show and a serial so each request is consumed once. */
export interface FocusRequest {
key: ElementKey
serial: number
}
/** The attributes that make a row of a list reachable by a focus request. */
export function focusAttrs(key: ElementKey) {
return {
'data-focus-key': JSON.stringify(key),
tabIndex: -1,
} as const
}
/** The ring a programmatically focused row shows. */
export const FOCUS_CLASS =
'focus:outline focus:outline-2 focus:outline-[var(--color-accent)]'
/** Runs `apply` once per request serial, after the tab has rendered. */
export function useFocusRequest(
focus: FocusRequest | undefined,
apply: (key: ElementKey) => void,
): void {
const handled = useRef<number | null>(null)
useEffect(() => {
if (!focus || handled.current === focus.serial) return
handled.current = focus.serial
apply(focus.key)
})
}
/** Scrolls to and focuses the row tagged with `key`. */
export function focusRow(key: ElementKey): void {
const wanted = JSON.stringify(key)
const row = [
...document.querySelectorAll<HTMLElement>('[data-focus-key]'),
].find((candidate) => candidate.dataset.focusKey === wanted)
row?.scrollIntoView?.({ block: 'center' })
row?.focus()
}
/** Row-based tabs (Général, Vues, Références, Vertèbres): focus the named row. */
export function useRowFocus(focus: FocusRequest | undefined): void {
useFocusRequest(focus, focusRow)
}
+6
View File
@@ -1,3 +1,5 @@
import type { ElementKey } from '@faunosteo/core-wasm/types'
import type { FocusRequest } from './focusRequest'
import type { TabTier } from './useViewport'
export const EDITOR_TABS = [
@@ -32,6 +34,10 @@ export interface EditorTabProps {
readOnly: boolean
/** « Aller à … » and any link between tabs. */
onSelectTab: (tab: EditorTabId) => void
/** « Aller à … » with an element: the tab seeds its own selection from it once. */
focus?: FocusRequest
/** Switches tab and asks it to show the element. */
onGoTo?: (tab: EditorTabId, key: ElementKey) => void
/** Reads the sheet's overview again (after a submission: the round freezes the draft). */
reloadSheet: () => void
}
+57 -37
View File
@@ -73,56 +73,76 @@ const ROOT_PATH = /^(\w+)\[(\d+)\]/
export interface IssueTarget {
tab: EditorTabId
/** The named element (its label), when the path resolves in the document. */
/** The element the path names, when it resolves in the document. */
key: ElementKey | null
/** Its label. */
name: string | null
}
function keyOf(
doc: AnatomicalSheetDocument,
root: string,
index: number,
): ElementKey | null {
switch (root) {
case 'views':
return idKey('view', doc.views[index])
case 'annotations':
return idKey('annotation', doc.annotations[index])
case 'categories':
return idKey('category', doc.categories[index])
case 'finding_zones':
return idKey('zone', doc.finding_zones[index])
case 'references':
return idKey('reference', doc.references[index])
default:
return null
type Kind = 'view' | 'annotation' | 'category' | 'zone' | 'reference'
const ROOT_KIND: Record<string, Kind> = {
views: 'view',
annotations: 'annotation',
categories: 'category',
finding_zones: 'zone',
references: 'reference',
}
/** The id-bearing list a path root names. */
function listOf(doc: AnatomicalSheetDocument, root: string) {
return (doc as unknown as Record<string, { id: string }[] | undefined>)[root]
}
interface NodeLike {
id: string
categories?: NodeLike[]
children?: NodeLike[]
}
/** The finding the nested part of a `finding_zones[i]...` path names (zone when none). */
function findingKey(zone: NodeLike, path: string): ElementKey {
const ids: string[] = []
let node: NodeLike | undefined = zone
for (const step of path.matchAll(/\.(categories|children)\[(\d+)\]/g)) {
node = (step[1] === 'categories' ? node?.categories : node?.children)?.[
Number(step[2])
]
if (!node) break
ids.push(node.id)
}
return ids.length === 0
? { kind: 'zone', id: zone.id }
: { kind: 'finding', zone_id: zone.id, path: ids }
}
function idKey<
K extends 'view' | 'annotation' | 'category' | 'zone' | 'reference',
>(kind: K, item: { id: string } | undefined): ElementKey | null {
return item ? ({ kind, id: item.id } as ElementKey) : null
function keyOf(doc: AnatomicalSheetDocument, path: string): ElementKey | null {
const region = REGION_PATH.exec(path)?.[1]
if (region !== undefined) {
const code = doc.vertebral_config.regions[Number(region)]?.code
return code ? { kind: 'region', code } : null
}
const match = ROOT_PATH.exec(path)
const item = match ? listOf(doc, match[1])?.[Number(match[2])] : undefined
if (!match || !item) return null
if (match[1] === 'finding_zones') return findingKey(item, path)
return { kind: ROOT_KIND[match[1]], id: item.id } as ElementKey
}
/** The tab holding the element an issue path names (« Aller à … »); null when none. */
function tabOf(path: string): EditorTabId | null {
if (REGION_PATH.test(path)) return 'vertebrae'
const root = ROOT_PATH.exec(path)?.[1]
return root ? (ROOT_TAB[root] ?? null) : null
}
/** The tab and element an issue path names (« Aller à … »); null when it names none. */
export function issueTarget(
doc: AnatomicalSheetDocument,
path: string,
locale: Locale,
): IssueTarget | null {
const region = REGION_PATH.exec(path)?.[1]
if (region !== undefined) {
const code = doc.vertebral_config.regions[Number(region)]?.code
const name = code
? elementLabel(doc, { kind: 'region', code }, locale)
: null
return { tab: 'vertebrae', name }
}
const match = ROOT_PATH.exec(path)
const tab = match ? ROOT_TAB[match[1]] : undefined
if (!match || !tab) return null
const key = keyOf(doc, match[1], Number(match[2]))
return { tab, name: key ? elementLabel(doc, key, locale) : null }
const tab = tabOf(path)
if (!tab) return null
const key = keyOf(doc, path)
return { tab, key, name: key ? elementLabel(doc, key, locale) : null }
}
/** « 2 097 152 » with plain spaces, as the plan words the size. */
@@ -0,0 +1,194 @@
/** Lot J fix: « Aller à … » seeds each tab's own selection once. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import type {
AnatomicalSheetDocument,
ElementKey,
} from '@faunosteo/core-wasm/types'
import FindingsTab from '@/components/editor/tabs/FindingsTab'
import ReferencesTab from '@/components/editor/tabs/ReferencesTab'
import VertebraeTab from '@/components/editor/tabs/VertebraeTab'
import AnnotationsTab from '@/components/editor/tabs/AnnotationsTab'
import { issueTarget } from '@/editor/verification'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert, point } 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 base = { readOnly: false, onSelectTab: vi.fn(), reloadSheet: vi.fn() }
const doc = (): AnatomicalSheetDocument =>
JSON.parse(store.getState().documentText)
const name = (n: string) => ({ fr: n, en: n })
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
})
function findingsText(): string {
let text = insert(baseText(), {
kind: 'zone',
value: { id: 'zone-a', name: name('Zone A'), 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: [],
},
},
})
return edit(text, {
op: 'insert',
parent: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] },
element: {
kind: 'finding_node',
value: {
id: 'node-a',
name: name('Nœud A'),
description: {},
requires_vet_referral: false,
reference_ids: [],
review_status: 'to_confirm',
children: [],
},
},
})
}
describe('focus requests', () => {
it('Constats: expands to the finding, selects it and shows its detail', async () => {
await openReady({ text: findingsText() })
const key: ElementKey = {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'node-a'],
}
render(<FindingsTab {...base} focus={{ key, serial: 1 }} />)
const item = await screen.findByRole('treeitem', { name: /Nœud A/ })
expect(item.getAttribute('aria-selected')).toBe('true')
})
it('Annotations: selects the annotation of the request', async () => {
const text = insert(baseText(), point('anno-b', 20, 20, 3))
await openReady({ text })
render(
<AnnotationsTab
{...base}
focus={{ key: { kind: 'annotation', id: 'anno-b' }, serial: 1 }}
/>,
)
expect(await screen.findAllByText(/anno-b|Sélection/)).not.toHaveLength(0)
})
it('Références and Vertèbres: focus the named row', async () => {
let text = insert(baseText(), {
kind: 'reference',
value: {
id: 'ref-a',
type: 'book',
citation: 'Alpha',
url: null,
doi: null,
},
})
text = insert(text, {
kind: 'region',
value: {
code: 'C',
name: name('Cervicales'),
count: 7,
count_range: null,
},
})
await openReady({ text })
render(
<ReferencesTab
{...base}
focus={{ key: { kind: 'reference', id: 'ref-a' }, serial: 1 }}
/>,
)
expect(document.activeElement?.getAttribute('data-focus-key')).toContain(
'ref-a',
)
cleanup()
render(
<VertebraeTab
{...base}
focus={{ key: { kind: 'region', code: 'C' }, serial: 1 }}
/>,
)
expect(document.activeElement?.getAttribute('data-focus-key')).toContain(
'"C"',
)
})
it('consumes a serial once', async () => {
const text = insert(baseText(), {
kind: 'reference',
value: {
id: 'ref-a',
type: 'book',
citation: 'Alpha',
url: null,
doi: null,
},
})
await openReady({ text })
const focus = {
key: { kind: 'reference', id: 'ref-a' } as ElementKey,
serial: 1,
}
const view = render(<ReferencesTab {...base} focus={focus} />)
;(document.activeElement as HTMLElement).blur()
view.rerender(<ReferencesTab {...base} focus={focus} />)
expect(document.activeElement?.getAttribute('data-focus-key')).toBeNull()
})
})
describe('issueTarget', () => {
it('resolves nested finding paths, regions and references', async () => {
await openReady({ text: findingsText() })
const d = doc()
const path = 'finding_zones[0].categories[0].children[0].reference_ids[1]'
expect(issueTarget(d, path, 'fr')).toMatchObject({
tab: 'findings',
key: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a', 'node-a'] },
name: 'Nœud A',
})
expect(issueTarget(d, 'finding_zones[0]', 'fr')?.key).toEqual({
kind: 'zone',
id: 'zone-a',
})
expect(
issueTarget(d, 'vertebral_config.regions[3].count_range', 'fr'),
).toMatchObject({
tab: 'vertebrae',
key: null,
})
expect(issueTarget(d, 'nothing', 'fr')).toBeNull()
})
})
@@ -29,7 +29,8 @@ vi.mock('@faunosteo/supabase', async (orig) => ({
const onSelectTab = vi.fn()
const reloadSheet = vi.fn()
const props = { readOnly: false, onSelectTab, reloadSheet }
const onGoTo = vi.fn()
const props = { readOnly: false, onSelectTab, onGoTo, reloadSheet }
const SUBMIT = 'Soumettre à la revue'
/** An annotation without geometry: a blocking error of the core. */
@@ -48,6 +49,7 @@ afterEach(() => {
cleanup()
resetStore()
onSelectTab.mockReset()
onGoTo.mockReset()
reloadSheet.mockReset()
})
@@ -77,9 +79,12 @@ describe('Vérification panel', () => {
expect(screen.getAllByText('Sans tracé')).toHaveLength(2)
expect(screen.getByText(/n'a pas de géométrie/)).toBeTruthy()
await user.click(
screen.getAllByRole('button', { name: 'Aller à Annotations' })[0],
screen.getAllByRole('button', { name: 'Aller à Sans tracé' })[0],
)
expect(onSelectTab).toHaveBeenCalledWith('annotations')
expect(onGoTo).toHaveBeenCalledWith('annotations', {
kind: 'annotation',
id: 'anno-bare',
})
expect(screen.queryByText('Aucun problème détecté')).toBeNull()
})
@@ -101,9 +106,9 @@ describe('Vérification panel', () => {
render(<VerificationTab {...props} />)
expect(screen.getByText('1 blocking errors')).toBeTruthy()
expect(screen.getByText(/This annotation has no geometry/)).toBeTruthy()
expect(
screen.getAllByRole('button', { name: 'Go to Annotations' }),
).toHaveLength(3)
expect(screen.getAllByRole('button', { name: 'Go to Bare' })).toHaveLength(
2,
)
})
it('hides the submission when read-only', async () => {
@@ -214,3 +219,21 @@ describe('Issue messages', () => {
expect(getDict('fr')[key]).toBeTruthy()
})
})
describe('Submission after the tab is gone', () => {
it('still reloads the sheet when the tab unmounted during the await', async () => {
await openReady()
let resolve: (id: never) => void = () => undefined
sb.submitSheetReview.mockReturnValue(new Promise((r) => (resolve = r)))
const user = userEvent.setup()
const view = render(<VerificationTab {...props} />)
await user.type(
screen.getByLabelText('Note de soumission (obligatoire)'),
'Prête',
)
await user.click(screen.getByRole('button', { name: SUBMIT }))
view.unmount()
await act(async () => resolve('review-1' as never))
await waitFor(() => expect(reloadSheet).toHaveBeenCalled())
})
})