diff --git a/.claude/audits/2026-11-03-v1-2-6-label-proposals.md b/.claude/audits/2026-11-03-v1-2-6-label-proposals.md index ed146051..78e73ae6 100644 --- a/.claude/audits/2026-11-03-v1-2-6-label-proposals.md +++ b/.claude/audits/2026-11-03-v1-2-6-label-proposals.md @@ -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 | diff --git a/apps/app/src/app/routes/app/admin/AdminSheetDraftRoute.tsx b/apps/app/src/app/routes/app/admin/AdminSheetDraftRoute.tsx index e1aed3dd..e5cbeef6 100644 --- a/apps/app/src/app/routes/app/admin/AdminSheetDraftRoute.tsx +++ b/apps/app/src/app/routes/app/admin/AdminSheetDraftRoute.tsx @@ -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(FIRST_TAB) + const [focus, setFocus] = useState() + 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} /> diff --git a/apps/app/src/components/editor/annotations/EditableAnnotations.tsx b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx index 78cced80..73c5190e 100644 --- a/apps/app/src/components/editor/annotations/EditableAnnotations.tsx +++ b/apps/app/src/components/editor/annotations/EditableAnnotations.tsx @@ -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(null) const viewId = ui.viewId ?? mainViewId(doc) const model = useViewModel(doc, viewId) diff --git a/apps/app/src/components/editor/general/CategoriesSection.tsx b/apps/app/src/components/editor/general/CategoriesSection.tsx index 945e29b3..cf3fb3ca 100644 --- a/apps/app/src/components/editor/general/CategoriesSection.tsx +++ b/apps/app/src/components/editor/general/CategoriesSection.tsx @@ -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 ( -
  • +
  • {(['fr', 'en'] as const).map((locale) => ( +
  • {doc && preview && props.readOnly && ( - + )} {doc && preview && !props.readOnly && ( - + )} ) @@ -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(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) diff --git a/apps/app/src/components/editor/tabs/FindingsTab.tsx b/apps/app/src/components/editor/tabs/FindingsTab.tsx index b6c1fced..d602a297 100644 --- a/apps/app/src/components/editor/tabs/FindingsTab.tsx +++ b/apps/app/src/components/editor/tabs/FindingsTab.tsx @@ -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) diff --git a/apps/app/src/components/editor/tabs/GeneralTab.tsx b/apps/app/src/components/editor/tabs/GeneralTab.tsx index cd2f2f56..93b38a6d 100644 --- a/apps/app/src/components/editor/tabs/GeneralTab.tsx +++ b/apps/app/src/components/editor/tabs/GeneralTab.tsx @@ -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 (
    (null) const references = doc?.references ?? [] diff --git a/apps/app/src/components/editor/tabs/VerificationTab.tsx b/apps/app/src/components/editor/tabs/VerificationTab.tsx index 3b5cbc75..ca435571 100644 --- a/apps/app/src/components/editor/tabs/VerificationTab.tsx +++ b/apps/app/src/components/editor/tabs/VerificationTab.tsx @@ -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 && (

    @@ -58,6 +60,7 @@ function Panel({ tone="info" doc={doc} onSelectTab={onSelectTab} + onGoTo={onGoTo} /> {to_confirm > 0 && ( {t('editor.verification.to_confirm_info')} diff --git a/apps/app/src/components/editor/tabs/VertebraeTab.tsx b/apps/app/src/components/editor/tabs/VertebraeTab.tsx index a20b69c8..459eb130 100644 --- a/apps/app/src/components/editor/tabs/VertebraeTab.tsx +++ b/apps/app/src/components/editor/tabs/VertebraeTab.tsx @@ -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(null) diff --git a/apps/app/src/components/editor/tabs/ViewsTab.tsx b/apps/app/src/components/editor/tabs/ViewsTab.tsx index 1c2fed60..8aa76aec 100644 --- a/apps/app/src/components/editor/tabs/ViewsTab.tsx +++ b/apps/app/src/components/editor/tabs/ViewsTab.tsx @@ -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(null) diff --git a/apps/app/src/components/editor/verification/IssueList.tsx b/apps/app/src/components/editor/verification/IssueList.tsx index d2d085d6..cdd716a7 100644 --- a/apps/app/src/components/editor/verification/IssueList.tsx +++ b/apps/app/src/components/editor/verification/IssueList.tsx @@ -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}`), )} )} diff --git a/apps/app/src/components/editor/verification/useSubmission.ts b/apps/app/src/components/editor/verification/useSubmission.ts index 8e75e816..cfc5f81a 100644 --- a/apps/app/src/components/editor/verification/useSubmission.ts +++ b/apps/app/src/components/editor/verification/useSubmission.ts @@ -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 } } diff --git a/apps/app/src/components/editor/vertebrae/RegionRow.tsx b/apps/app/src/components/editor/vertebrae/RegionRow.tsx index 9a23d0b0..e44f6b39 100644 --- a/apps/app/src/components/editor/vertebrae/RegionRow.tsx +++ b/apps/app/src/components/editor/vertebrae/RegionRow.tsx @@ -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 ( -
  • +
  • diff --git a/apps/app/src/components/editor/views/MainViewCard.tsx b/apps/app/src/components/editor/views/MainViewCard.tsx index d09ff1ac..c651e371 100644 --- a/apps/app/src/components/editor/views/MainViewCard.tsx +++ b/apps/app/src/components/editor/views/MainViewCard.tsx @@ -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 (

    {t('editor.views.main_title')} diff --git a/apps/app/src/editor/annotations/focusTarget.ts b/apps/app/src/editor/annotations/focusTarget.ts new file mode 100644 index 00000000..c0367234 --- /dev/null +++ b/apps/app/src/editor/annotations/focusTarget.ts @@ -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 +} diff --git a/apps/app/src/editor/findings/tree.ts b/apps/app/src/editor/findings/tree.ts index 0d95f512..dd332d30 100644 --- a/apps/app/src/editor/findings/tree.ts +++ b/apps/app/src/editor/findings/tree.ts @@ -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) +} diff --git a/apps/app/src/editor/focusRequest.ts b/apps/app/src/editor/focusRequest.ts new file mode 100644 index 00000000..a40c93bd --- /dev/null +++ b/apps/app/src/editor/focusRequest.ts @@ -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(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('[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) +} diff --git a/apps/app/src/editor/tabs.ts b/apps/app/src/editor/tabs.ts index 07d0f7eb..6728e9a5 100644 --- a/apps/app/src/editor/tabs.ts +++ b/apps/app/src/editor/tabs.ts @@ -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 } diff --git a/apps/app/src/editor/verification.ts b/apps/app/src/editor/verification.ts index 318efea3..bb219c3e 100644 --- a/apps/app/src/editor/verification.ts +++ b/apps/app/src/editor/verification.ts @@ -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 = { + 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)[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. */ diff --git a/apps/app/tests/unit/editor-focus-request.test.tsx b/apps/app/tests/unit/editor-focus-request.test.tsx new file mode 100644 index 00000000..e2d75514 --- /dev/null +++ b/apps/app/tests/unit/editor-focus-request.test.tsx @@ -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()), + 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() + 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( + , + ) + 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( + , + ) + expect(document.activeElement?.getAttribute('data-focus-key')).toContain( + 'ref-a', + ) + cleanup() + render( + , + ) + 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() + ;(document.activeElement as HTMLElement).blur() + view.rerender() + 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() + }) +}) diff --git a/apps/app/tests/unit/editor-verification.test.tsx b/apps/app/tests/unit/editor-verification.test.tsx index fa20e86b..e3ac4028 100644 --- a/apps/app/tests/unit/editor-verification.test.tsx +++ b/apps/app/tests/unit/editor-verification.test.tsx @@ -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() 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() + 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()) + }) +})