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

@@ -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. */