feat(editor): contextual citations panel of a finding (board 25)
The panel opens only from a finding's « {n} références » trigger: 34 rem
at most, never wider than the room, a scrim, slide in 180 ms and out
140 ms (motion/react; none under reduced motion, callbacks still fire).
It lists the finding's references as tiles with « Modifier », « Retirer
de ce constat » (one « Défaire » restores it and the review status) and
« Aller à »; dangling ids read « Référence introuvable »; zero left
reads « Ce constat ne cite plus aucune référence. ». « Tout afficher
dans l'onglet Références » resets search and sort, keeps open tiles and
edits. Every close (✕, Escape outside fields, scrim, tab, « Aller à »,
« Tout afficher », element gone) records one pending move applied
after the exit, page inert until then; focus back to the trigger, else
the active tab button. A refused draft cancels a user close; a forced
close drops it and announces « Saisie non appliquée : {field} ». Places
keeps a permanent dvh min-height; the panel fits the visible viewport
at every scroll position, document size unchanged.
Gates: typecheck, lint, test:run (app 1488), build, e2e:ui 251;
e2e:shell 16 specs on db:sandbox (admin and editor-equine excluded):
117 passed / 107 skipped / 0 failed, rerun after the fix rounds: 118
passed / 108 skipped / 0 failed; layout spec 13 passed after round 2;
full-row guard: no pre-existing row changed in any table. Known limit:
landscape 667 x 375 at scroll 0 leaves ~13 px of panel (the trigger is
below the fold there).
## R-24 (removed or rewritten assertions)
| file | old | new |
|---|---|---|
| editor-references-panel.test.tsx (whole file) | R2.1 interim-panel tests, synchronous closes | rewritten: 39 tests (opening, motion, close matrix in both modes, exit, Retirer, P22'', library + history) |
| same, opening | heading `Références` focused right after the click | heading `Références citées` focused after the enter (`waitFor`), `aria-expanded` only after click |
| same | chip `references-filter-chip` « Citées par « Node A » (2) » | REMOVED (REVUE: path line + count line « 2 références citées par ce constat ») |
| same | `listitem` cards « Citée 2 fois » | tiles (`ul > li`) with the same counts, in the finding's order |
| same | field id `#panel-reference-0-ref-a-citation` present at once | tile opened + « Modifier » first (tiles since R2.2) |
| same | « Tout afficher (3) », sync | « Tout afficher dans l'onglet Références », after exit, heading focus asserted |
| same | Escape / ✕ / scrim / tab / vanish: sync null panel | all `await closed()` + `document.activeElement` checks, `describe.each` normal / reduced motion |
| same | « makes the tab panels inert while open, header usable » | split: inert page + inert panel until the exit ends then lifted; « Défaire / Refaire usable »; the `Enregistrer` enabled check dropped (covered by the focus-moved-off test) |
| same | Ctrl+Z test on an always-open field | open tile + Modifier first |
| same | read-only: no Supprimer, no textbox | open tile: no Modifier, no Retirer, no textbox |
| same | P6 under « Plus »: sync | in the close matrix, awaited |
| editor-escape.test.tsx (2 tests) | `expect(citations()).toBeNull()` right after Escape | `await waitFor(...)`; trigger `aria-expanded` false after exit |
| editor-keep-alive.test.tsx | « Escape in a citations panel field commits the text before the panel closes » | REPLACED by « Escape in a field of a panel tile neither closes nor commits » (A5, P27) |
| same | scrim click closes the panel after committing, sync, id on a closed tile | tile opened in edit first, close awaited, commit asserted before the exit |
| editor-focus-request.test.tsx | `ReferenceLibrary` with `resetSignal`; `ownedBy(ref,'citations')` undefined | `ReferencesTab` (+ `reloadSheet`); the `'citations'` assertion removed with the type |
| editor-references-tab / -view.test.tsx | `ReferenceLibrary`, `resetSignal` | `ReferencesTab`, `libraryReset` (+ `reloadSheet`) |
| e2e support `openCitations` | waited for the panel visible | also waits for the heading focus (slide over) |
New unit coverage: editor-citations-exit.test.tsx (hook, fake timers), editor-findings (aria-expanded per finding),
`useDecisionsOpen` gate, panel file (Retirer + status + one undo, P20 chain, zero state, dangling id, P4 reset, P6 after undo,
P22'' four paths, reduced motion, inert/exit, second close, tab replace, focus-moved-off).
## i18n (FR / EN)
Added: `editor.references.panel_title` Références citées / Cited references; `panel_count_one|other` « {count} référence citée par
ce constat » / « {count} références citées par ce constat » and « {count} reference cited by this finding » / « … references … »;
`panel_show_all` Tout afficher dans l'onglet Références / Show all in the References tab; `panel_empty` Ce constat ne cite plus
aucune référence. / This finding no longer cites any reference.; `remove_citation` Retirer de ce constat / Remove from this finding;
`this_finding` ce constat / this finding; `missing` Référence introuvable / Reference not found; `draft_dropped`
Saisie non appliquée : {field} / Entry not applied: {field}.
Changed: none. Removed: `editor.references.cited_by` (« Citées par « {name} » ({count}) » / « Cited by « {name} » ({count}) »),
`editor.references.show_all` (« Tout afficher ({count}) » / « Show all ({count}) »). R10 grep over src, tests and e2e including
editor-equine: no reader left. `editor-equine` has no panel reference: « updated, not run » (nothing to update). The three
provisional FR labels are exactly as listed in the brief; `…` = the refused field's label.
This commit is contained in:
1 parent
3baac4dbb5
commit
8db6f4287f
38 files changed
+2524
-705
No files matched your search
@@ -1,8 +1,14 @@
|
||||
import { useEffect, useRef, type ReactNode } from 'react'
|
||||
import { AnimatePresence } from 'motion/react'
|
||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||
import type { OfficialSheetAdmin } from '@faunosteo/supabase'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import { ReadOnlyContext, ReferencesOpenContext } from '@/editor/editingContext'
|
||||
import { AnnounceContext, FocusConsumedContext } from '@/editor/focusRequest'
|
||||
import {
|
||||
AnnounceContext,
|
||||
FocusConsumedContext,
|
||||
isTextField,
|
||||
} from '@/editor/focusRequest'
|
||||
import { saveFailureMessage } from '@/editor/messages'
|
||||
import type { EditorMode } from '@/editor/mode'
|
||||
import { useEditorStore } from '@/editor/state/editorStore'
|
||||
@@ -18,10 +24,9 @@ import CopyIssueNotice from './CopyIssueNotice'
|
||||
import DraftHeader from './DraftHeader'
|
||||
import EditorTabBody from './EditorTabBody'
|
||||
import EditorTabs from './EditorTabs'
|
||||
import KeptPlace from './KeptPlace'
|
||||
import ModeNotice from './ModeNotice'
|
||||
import RecoveryNotice from './RecoveryNotice'
|
||||
import ReferencesPanel from './references/ReferencesPanel'
|
||||
import CitationsLayer from './references/CitationsLayer'
|
||||
|
||||
interface Props {
|
||||
sheet: OfficialSheetAdmin
|
||||
@@ -51,16 +56,16 @@ function SaveFailureNotice() {
|
||||
/** What dialogs and edit-only parts below need of the editor's state. */
|
||||
function EditingState({
|
||||
readOnly,
|
||||
referencesOpen,
|
||||
citationsOf,
|
||||
children,
|
||||
}: {
|
||||
readOnly: boolean
|
||||
referencesOpen: boolean
|
||||
citationsOf: ElementKey | null
|
||||
children: ReactNode
|
||||
}) {
|
||||
return (
|
||||
<ReadOnlyContext value={readOnly}>
|
||||
<ReferencesOpenContext value={referencesOpen}>
|
||||
<ReferencesOpenContext value={citationsOf}>
|
||||
{children}
|
||||
</ReferencesOpenContext>
|
||||
</ReadOnlyContext>
|
||||
@@ -76,35 +81,29 @@ interface PlacesProps {
|
||||
/**
|
||||
* Under the tab row: the tab panels and the citations panel of a finding beside them. The
|
||||
* container starts after the tab row, so the panel and its scrim never cover the header or
|
||||
* the tabs; while the panel is open the tab panels are inert (the scrim sits over them).
|
||||
* the tabs; from the opening to the end of the exit the tab panels are inert. Its minimum
|
||||
* height is permanent (never toggled): the panel and the scrim reach the bottom of the
|
||||
* window and the document never changes size when the panel opens or closes (P16').
|
||||
*/
|
||||
function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
|
||||
const { state } = nav
|
||||
const open = state.citationsOf !== null
|
||||
return (
|
||||
<div className={`relative ${open ? 'min-h-[calc(100dvh-3.5rem)]' : ''}`}>
|
||||
{state.citationsOf && (
|
||||
<KeptPlace
|
||||
name="citations"
|
||||
visible
|
||||
className="absolute bottom-0 right-0 top-0 z-20 w-[min(27rem,100%)]"
|
||||
>
|
||||
<ReferencesPanel
|
||||
<div className="relative min-h-[calc(100dvh-3.5rem)]">
|
||||
<AnimatePresence onExitComplete={nav.exitComplete}>
|
||||
{state.citationsOf && !nav.exiting && (
|
||||
<CitationsLayer
|
||||
key="citations"
|
||||
readOnly={readOnly}
|
||||
citedBy={state.citationsOf}
|
||||
onClose={nav.closeCitations}
|
||||
onGone={nav.dropCitations}
|
||||
onShowAll={nav.showAllReferences}
|
||||
navigate={nav.navigate}
|
||||
registerCanLeave={nav.registerCanLeave}
|
||||
/>
|
||||
</KeptPlace>
|
||||
)}
|
||||
{open && (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
data-testid="references-scrim"
|
||||
onClick={nav.closeCitations}
|
||||
className="absolute inset-0 z-10 bg-[rgba(31,27,22,0.25)]"
|
||||
/>
|
||||
)}
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<div inert={open}>
|
||||
<EditorTabBody
|
||||
tab={state.tab}
|
||||
@@ -163,13 +162,14 @@ export default function EditorWorkspace(props: Props) {
|
||||
const open = nav.state.citationsOf !== null
|
||||
useBodyEscape(open, nav.closeCitations)
|
||||
return (
|
||||
<EditingState readOnly={readOnly} referencesOpen={open}>
|
||||
<EditingState readOnly={readOnly} citationsOf={nav.state.citationsOf}>
|
||||
<div
|
||||
className="space-y-4"
|
||||
data-editor-workspace
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== 'Escape' || event.defaultPrevented) return
|
||||
if (event.nativeEvent.isComposing || !open) return
|
||||
if (isTextField(event.target)) return
|
||||
event.preventDefault()
|
||||
nav.closeCitations()
|
||||
}}
|
||||
|
||||
@@ -7,6 +7,7 @@ import Icon from '@/components/ui/Icon'
|
||||
import { ReferencesOpenContext } from '@/editor/editingContext'
|
||||
import {
|
||||
patchElement,
|
||||
sameKey,
|
||||
type FindingItem,
|
||||
type FindingPatch,
|
||||
} from '@/editor/findings/tree'
|
||||
@@ -139,7 +140,8 @@ function Citations({
|
||||
const t = useT()
|
||||
const plural = usePlural()
|
||||
const doc = useSheetDocument()
|
||||
const panelOpen = useContext(ReferencesOpenContext)
|
||||
const citationsOf = useContext(ReferencesOpenContext)
|
||||
const panelOpen = citationsOf !== null && sameKey(citationsOf, item.key)
|
||||
const references = doc?.references ?? []
|
||||
const citation = (id: string) =>
|
||||
references.find((r) => r.id === id)?.citation ?? id
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { useEffect, useLayoutEffect, useRef, type RefObject } from 'react'
|
||||
import { motion, useIsPresent, useReducedMotion } from 'motion/react'
|
||||
import { PANEL_ENTER_S, PANEL_EXIT_S } from '@/editor/useCitationsExit'
|
||||
import KeptPlace from '../KeptPlace'
|
||||
import CitationsPanel from './CitationsPanel'
|
||||
|
||||
type Props = Parameters<typeof CitationsPanel>[0]
|
||||
|
||||
/** The top bar (`h-14`): the panel sticks right under it. */
|
||||
const TOP_BAR_REM = 3.5
|
||||
|
||||
/**
|
||||
* The panel's visible height: from its top (under the top bar once the page has scrolled)
|
||||
* to the nearer of the container's bottom and the viewport's bottom. Kept right on scroll,
|
||||
* resize and visual-viewport changes (mobile URL bar, keyboard); only the panel's own
|
||||
* height is written, so the document never changes size.
|
||||
*/
|
||||
function useFitToViewport(panel: RefObject<HTMLElement | null>) {
|
||||
useLayoutEffect(() => {
|
||||
const element = panel.current
|
||||
const container = element?.parentElement
|
||||
if (!element || !container) return
|
||||
const bar =
|
||||
TOP_BAR_REM *
|
||||
parseFloat(getComputedStyle(document.documentElement).fontSize)
|
||||
const fit = () => {
|
||||
const box = container.getBoundingClientRect()
|
||||
const viewport = window.visualViewport?.height ?? window.innerHeight
|
||||
const visible = Math.min(box.bottom, viewport) - Math.max(box.top, bar)
|
||||
element.style.height = `${Math.max(visible, 0)}px`
|
||||
}
|
||||
fit()
|
||||
const watched: EventTarget[] = [window]
|
||||
if (window.visualViewport) watched.push(window.visualViewport)
|
||||
for (const target of watched) {
|
||||
target.addEventListener('scroll', fit, { passive: true })
|
||||
target.addEventListener('resize', fit)
|
||||
}
|
||||
const observer =
|
||||
typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(fit)
|
||||
// Content above the container reflowing moves its top without resizing it.
|
||||
observer?.observe(container)
|
||||
observer?.observe(document.documentElement)
|
||||
return () => {
|
||||
for (const target of watched) {
|
||||
target.removeEventListener('scroll', fit)
|
||||
target.removeEventListener('resize', fit)
|
||||
}
|
||||
observer?.disconnect()
|
||||
}
|
||||
}, [panel])
|
||||
}
|
||||
|
||||
/**
|
||||
* The citations panel and its scrim over the places (board 25). The panel slides in from
|
||||
* the right (translateX only), the scrim fades on the same timings; under reduced motion
|
||||
* both change at once, the callbacks still fire (P29). While it exits, the panel is inert
|
||||
* (the page behind stays inert until the workspace lifts it, P9).
|
||||
*
|
||||
* Geometry (P16, P16'): the wrapper fills the Places container, clips the slide on the x
|
||||
* axis only (`clip`, never `hidden`) and is 34 rem at most; the panel inside sticks under
|
||||
* the top bar, is exactly as tall as what is visible (`useFitToViewport`) and scrolls its
|
||||
* own list, so the page's size never changes.
|
||||
*/
|
||||
export default function CitationsLayer(props: Props) {
|
||||
const reduced = useReducedMotion()
|
||||
const present = useIsPresent()
|
||||
const layer = useRef<HTMLDivElement>(null)
|
||||
const focused = useRef(false)
|
||||
useFitToViewport(layer)
|
||||
// A reopen during a slow exit reuses this instance: it focuses its heading again.
|
||||
useEffect(() => {
|
||||
if (!present) focused.current = false
|
||||
}, [present])
|
||||
const slide = { x: reduced ? 0 : '100%' }
|
||||
const enter = {
|
||||
duration: reduced ? 0 : PANEL_ENTER_S,
|
||||
ease: 'easeOut',
|
||||
} as const
|
||||
const leave = {
|
||||
duration: reduced ? 0 : PANEL_EXIT_S,
|
||||
ease: 'easeIn',
|
||||
} as const
|
||||
// The heading takes the focus once the panel is in place (P9, P29).
|
||||
const entered = () => {
|
||||
if (!present || focused.current) return
|
||||
focused.current = true
|
||||
layer.current
|
||||
?.querySelector<HTMLElement>('[data-place-heading]')
|
||||
?.focus({ preventScroll: true })
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<motion.div
|
||||
aria-hidden="true"
|
||||
data-testid="references-scrim"
|
||||
onClick={props.onClose}
|
||||
className="absolute inset-0 z-10 bg-[rgba(31,27,22,0.25)]"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1, transition: enter }}
|
||||
exit={{ opacity: 0, transition: leave }}
|
||||
/>
|
||||
<KeptPlace
|
||||
name="citations"
|
||||
visible
|
||||
inert={!present}
|
||||
className="absolute inset-y-0 right-0 z-20 w-[min(34rem,100%)] overflow-x-clip"
|
||||
>
|
||||
<motion.div
|
||||
ref={layer}
|
||||
className="sticky top-14"
|
||||
initial={slide}
|
||||
animate={{ x: 0, transition: enter }}
|
||||
exit={{ ...slide, transition: leave }}
|
||||
onAnimationComplete={entered}
|
||||
>
|
||||
<CitationsPanel {...props} />
|
||||
</motion.div>
|
||||
</KeptPlace>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import type { KeyboardEvent, RefObject } from 'react'
|
||||
import type { LocalizedText, Reference } from '@faunosteo/core-wasm/types'
|
||||
import ActionButton from '@/components/editor/fields/ActionButton'
|
||||
import Icon from '@/components/ui/Icon'
|
||||
import { isTextField } from '@/editor/focusRequest'
|
||||
import { targetOfKey, type EditorTarget } from '@/editor/navigation'
|
||||
import { usePlural } from '@/editor/plural'
|
||||
import type { CitationEntry } from '@/editor/references/panel'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import ReferenceTile from './ReferenceTile'
|
||||
import { useCitationsPanel, type PanelHooks } from './useCitationsPanel'
|
||||
|
||||
interface Props extends PanelHooks {
|
||||
/** ✕, Escape and the scrim: a close the tile in edit may refuse. */
|
||||
onClose: () => void
|
||||
/** « Tout afficher dans l'onglet Références ». */
|
||||
onShowAll: () => void
|
||||
/** « Aller à » a citing finding or family: closes the panel, then moves. */
|
||||
navigate: (target: EditorTarget) => void
|
||||
}
|
||||
|
||||
const RING =
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
|
||||
|
||||
interface HeaderProps {
|
||||
onClose: () => void
|
||||
headingRef: RefObject<HTMLHeadingElement | null>
|
||||
}
|
||||
|
||||
function PanelHeader({ onClose, headingRef }: HeaderProps) {
|
||||
const t = useT()
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h2
|
||||
ref={headingRef}
|
||||
id="editor-citations-title"
|
||||
tabIndex={-1}
|
||||
data-place-heading
|
||||
className="flex items-center gap-2 font-serif text-xl outline-none"
|
||||
>
|
||||
<Icon name="book" size={20} />
|
||||
{t('editor.references.panel_title')}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('editor.references.close')}
|
||||
onClick={onClose}
|
||||
className={`inline-flex h-11 w-11 items-center justify-center rounded-md ${RING}`}
|
||||
>
|
||||
<Icon name="close" size={18} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** « Zone › Famille › **Constat** »: where the finding sits, the finding itself in bold. */
|
||||
function FindingPath({ path }: { path: readonly LocalizedText[] }) {
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const names = path.map((name) => name[locale])
|
||||
const own = names.pop()
|
||||
return (
|
||||
<p className="text-sm">
|
||||
<span className="text-[var(--color-ink-muted)]">
|
||||
{names.map((name) => `${name} › `).join('')}
|
||||
</span>
|
||||
<b className="font-semibold">{own}</b>
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
function ShowAllLink({ onShowAll }: { onShowAll: () => void }) {
|
||||
const t = useT()
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onShowAll}
|
||||
className={`inline-flex min-h-11 items-center gap-1 text-sm text-[var(--color-accent-strong)] underline ${RING}`}
|
||||
>
|
||||
{t('editor.references.panel_show_all')}
|
||||
<Icon name="chevron-right" size={14} />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/** « {n} références citées par ce constat » and the way to the whole library. */
|
||||
function Summary({
|
||||
count,
|
||||
onShowAll,
|
||||
}: {
|
||||
count: number
|
||||
onShowAll: () => void
|
||||
}) {
|
||||
const plural = usePlural()
|
||||
return (
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-3">
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{count > 0 && plural('editor.references.panel_count', count)}
|
||||
</p>
|
||||
<ShowAllLink onShowAll={onShowAll} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** A cited id the sheet no longer holds (P30): named, and removable like any citation. */
|
||||
function MissingRow({
|
||||
entry,
|
||||
readOnly,
|
||||
onRemove,
|
||||
}: {
|
||||
entry: CitationEntry
|
||||
readOnly: boolean
|
||||
onRemove: () => void
|
||||
}) {
|
||||
const t = useT()
|
||||
const missing = t('editor.references.missing')
|
||||
return (
|
||||
<li className="flex items-center gap-2 rounded-lg border border-[var(--color-border)] p-3 text-sm">
|
||||
<span className="min-w-0 flex-1">
|
||||
{missing}
|
||||
<span className="ml-2 text-[var(--color-ink-muted)]">{entry.id}</span>
|
||||
</span>
|
||||
<ActionButton
|
||||
readOnly={readOnly}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
aria-label={`${t('editor.action.remove')} ${missing} ${entry.id}`}
|
||||
onClick={onRemove}
|
||||
>
|
||||
{t('editor.action.remove')}
|
||||
</ActionButton>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
type Panel = ReturnType<typeof useCitationsPanel>
|
||||
|
||||
/** One cited reference as a tile (« Modifier », « Retirer de ce constat »). */
|
||||
function EntryTile({
|
||||
entry,
|
||||
reference,
|
||||
panel,
|
||||
props,
|
||||
}: {
|
||||
entry: CitationEntry
|
||||
reference: Reference
|
||||
panel: Panel
|
||||
props: Props
|
||||
}) {
|
||||
const { tiles, keys, citers, entries, remove } = panel
|
||||
const { readOnly, citedBy, navigate } = props
|
||||
const key = keys[entry.index]
|
||||
return (
|
||||
<ReferenceTile
|
||||
host="panel"
|
||||
panel={{ current: citedBy, onRemove: () => remove(entry.index) }}
|
||||
reference={reference}
|
||||
position={entry.index}
|
||||
count={entries.length}
|
||||
citers={citers.get(reference.id) ?? []}
|
||||
open={tiles.openKeys.has(key)}
|
||||
editing={!readOnly && tiles.editingKey === key}
|
||||
readOnly={readOnly}
|
||||
movable={false}
|
||||
on={{
|
||||
toggle: () => tiles.toggle(key),
|
||||
edit: () => void tiles.startEdit(key),
|
||||
done: tiles.finish,
|
||||
goTo: (target) => navigate(targetOfKey(target)),
|
||||
registerLeave: tiles.registerLeave,
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** The cited references as tiles, the dangling ids as rows. */
|
||||
function Entries({ panel, props }: { panel: Panel; props: Props }) {
|
||||
return (
|
||||
<ul ref={panel.list} className="space-y-3">
|
||||
{panel.entries.map((entry) =>
|
||||
entry.reference ? (
|
||||
<EntryTile
|
||||
key={panel.keys[entry.index]}
|
||||
entry={entry}
|
||||
reference={entry.reference}
|
||||
panel={panel}
|
||||
props={props}
|
||||
/>
|
||||
) : (
|
||||
<MissingRow
|
||||
key={`${entry.index}-${entry.id}`}
|
||||
entry={entry}
|
||||
readOnly={props.readOnly}
|
||||
onRemove={() => panel.remove(entry.index)}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
/** Escape closes the panel, unless a field of it is being typed in (A5, P27). */
|
||||
function closeOnEscape(onClose: () => void) {
|
||||
return (event: KeyboardEvent) => {
|
||||
if (event.key !== 'Escape' || event.defaultPrevented) return
|
||||
if (event.nativeEvent.isComposing || isTextField(event.target)) return
|
||||
event.stopPropagation()
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The citations of one finding (board 25): the references it cites as tiles, « Tout
|
||||
* afficher » for the whole library. No search, add, delete or order (P7). Not a dialog:
|
||||
* the workspace makes the page behind it inert. Opens from a finding's trigger only.
|
||||
*/
|
||||
export default function CitationsPanel(props: Props) {
|
||||
const { onClose, onShowAll } = props
|
||||
const t = useT()
|
||||
const panel = useCitationsPanel(props)
|
||||
const count = panel.entries.length
|
||||
return (
|
||||
<section
|
||||
id="editor-citations-panel"
|
||||
data-testid="editor-citations-panel"
|
||||
aria-labelledby="editor-citations-title"
|
||||
onKeyDown={closeOnEscape(onClose)}
|
||||
className="flex h-full flex-col gap-3 border-l border-[var(--color-border)] bg-[var(--color-surface)] p-4 shadow-xl"
|
||||
>
|
||||
<PanelHeader onClose={onClose} headingRef={panel.heading} />
|
||||
<FindingPath path={panel.path} />
|
||||
<Summary count={count} onShowAll={onShowAll} />
|
||||
<div className="min-h-0 flex-1 space-y-3 overflow-y-auto pr-2">
|
||||
{count === 0 && (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.references.panel_empty')}
|
||||
</p>
|
||||
)}
|
||||
{panel.error && (
|
||||
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
||||
{panel.error}
|
||||
</p>
|
||||
)}
|
||||
<Entries panel={panel} props={props} />
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||
import type { CiterItem } from '@/editor/references/citations'
|
||||
import { sameKey } from '@/editor/findings/tree'
|
||||
import { usePlural } from '@/editor/plural'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
@@ -7,9 +8,12 @@ import { useLocaleStore } from '@/state/localeStore'
|
||||
/** « Citée {n} fois, par : » and who cites, each with « Aller à »; the empty line when none. */
|
||||
export default function CitersList({
|
||||
citers,
|
||||
current,
|
||||
onGoTo,
|
||||
}: {
|
||||
citers: readonly CiterItem[]
|
||||
/** The finding the citations panel belongs to: its row carries « ce constat ». */
|
||||
current?: ElementKey
|
||||
onGoTo: (key: ElementKey) => void
|
||||
}) {
|
||||
const t = useT()
|
||||
@@ -36,6 +40,11 @@ export default function CitersList({
|
||||
{' › '}
|
||||
</span>
|
||||
{citer.name[locale]}
|
||||
{current && sameKey(citer.key, current) && (
|
||||
<span className="ml-1 rounded-md bg-[var(--color-surface-strong)] px-2 py-0.5 text-xs">
|
||||
{t('editor.references.this_finding')}
|
||||
</span>
|
||||
)}
|
||||
{citer.isFamily && (
|
||||
<span className="ml-1 rounded-md bg-[var(--color-surface-strong)] px-2 py-0.5 text-xs">
|
||||
{t('editor.references.family')}
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import DeleteDialog, {
|
||||
type DeleteTarget,
|
||||
} from '@/components/editor/DeleteDialog'
|
||||
import EditOnly from '@/components/editor/EditOnly'
|
||||
import type { FocusRequest } from '@/editor/focusRequest'
|
||||
import type { EditorTarget } from '@/editor/navigation'
|
||||
import { isSheetView } from '@/editor/references/view'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import NewReferenceTile from './NewReferenceTile'
|
||||
import NoResult from './NoResult'
|
||||
import { EmptyLine } from './ReferenceList'
|
||||
import ReferenceTiles from './ReferenceTiles'
|
||||
import ReferenceToolbar from './ReferenceToolbar'
|
||||
import { useReferenceActions, useReferenceLibrary } from './useReferenceLibrary'
|
||||
|
||||
interface Props {
|
||||
readOnly: boolean
|
||||
/** « Aller à » a citing finding or family. */
|
||||
navigate: (target: EditorTarget) => void
|
||||
focus?: FocusRequest
|
||||
/** Bumped by « Tout afficher »: the search and the sort are reset once per bump. */
|
||||
resetSignal?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* The sheet's bibliography: toolbar (search, sort, count, add), one collapsible tile per
|
||||
* reference, the draft tile and the delete dialog. Lives in the Références tab (ids
|
||||
* prefixed `tab-`).
|
||||
*/
|
||||
export default function ReferenceLibrary(props: Props) {
|
||||
const { readOnly, navigate, focus, resetSignal = 0 } = props
|
||||
const t = useT()
|
||||
const lib = useReferenceLibrary(readOnly, resetSignal)
|
||||
const searchRef = useRef<HTMLInputElement>(null)
|
||||
const act = useReferenceActions(lib, focus, searchRef)
|
||||
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
|
||||
const { all, shown } = lib
|
||||
const sheetView = isSheetView(shown.view)
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<ReferenceToolbar
|
||||
query={shown.view.query}
|
||||
onQuery={(query) => shown.update({ query })}
|
||||
onClear={act.clearSearch}
|
||||
searchRef={searchRef}
|
||||
sort={shown.view.sort}
|
||||
onSort={(sort) => shown.update({ sort })}
|
||||
shown={shown.matchCount}
|
||||
total={all.length}
|
||||
canAdd={!readOnly}
|
||||
onAdd={act.startAdd}
|
||||
/>
|
||||
{lib.loaded && (
|
||||
<>
|
||||
{all.length === 0 && <EmptyLine />}
|
||||
{all.length > 0 && shown.matchCount === 0 && (
|
||||
<NoResult query={shown.view.query} onClear={act.clearSearch} />
|
||||
)}
|
||||
{!readOnly && !sheetView && shown.positions.length > 0 && (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.references.reorder_hint')}
|
||||
</p>
|
||||
)}
|
||||
<ReferenceTiles
|
||||
positions={shown.positions}
|
||||
all={all}
|
||||
keys={lib.keys}
|
||||
citers={lib.citers}
|
||||
tiles={lib.tiles}
|
||||
readOnly={readOnly}
|
||||
movable={sheetView}
|
||||
navigate={navigate}
|
||||
onEdit={act.edit}
|
||||
onDelete={(reference) =>
|
||||
setDeleting({
|
||||
key: { kind: 'reference', id: reference.id },
|
||||
label: reference.citation,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<EditOnly readOnly={readOnly}>
|
||||
{act.draft !== null && (
|
||||
<NewReferenceTile focusSerial={act.draft} onAdded={act.added} />
|
||||
)}
|
||||
</EditOnly>
|
||||
</>
|
||||
)}
|
||||
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import type { Reference } from '@faunosteo/core-wasm/types'
|
||||
import type { CiterItem } from '@/editor/references/citations'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import ReferenceRow from './ReferenceRow'
|
||||
import type { ReferenceHost } from './referenceTypes'
|
||||
|
||||
interface ListProps {
|
||||
host: ReferenceHost
|
||||
shown: readonly Reference[]
|
||||
all: readonly Reference[]
|
||||
citers: ReadonlyMap<string, readonly CiterItem[]>
|
||||
readOnly: boolean
|
||||
onDelete: (reference: Reference) => void
|
||||
}
|
||||
|
||||
/** The panel's cards of `shown`, each knowing its place in the whole bibliography `all`. */
|
||||
export function ReferenceList({ shown, all, citers, ...rest }: ListProps) {
|
||||
return (
|
||||
<ul className="space-y-3">
|
||||
{shown.map((reference) => {
|
||||
const index = all.indexOf(reference)
|
||||
return (
|
||||
<ReferenceRow
|
||||
key={`${index}-${reference.id}`}
|
||||
host={rest.host}
|
||||
reference={reference}
|
||||
index={index}
|
||||
cited={citers.get(reference.id)?.length ?? 0}
|
||||
readOnly={rest.readOnly}
|
||||
onDelete={() => rest.onDelete(reference)}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
/** The empty line: the sheet has no reference at all. */
|
||||
export function EmptyLine() {
|
||||
const t = useT()
|
||||
return (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.reference.empty')}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
import type { Reference, ReferenceType } from '@faunosteo/core-wasm/types'
|
||||
import ActionButton from '@/components/editor/fields/ActionButton'
|
||||
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 { usePlural } from '@/editor/plural'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { REFERENCE_TYPES, type ReferenceHost } from './referenceTypes'
|
||||
|
||||
const CARD = 'space-y-3 rounded-lg border border-[var(--color-border)] p-3'
|
||||
|
||||
/** One reference as the citations panel shows it (interim until R2.4): fields commit one by one. */
|
||||
export default function ReferenceRow({
|
||||
host,
|
||||
reference,
|
||||
index,
|
||||
cited,
|
||||
readOnly,
|
||||
onDelete,
|
||||
}: {
|
||||
/** The place showing the row: its field ids carry it, both can be mounted at once. */
|
||||
host: ReferenceHost
|
||||
reference: Reference
|
||||
/** Position in the whole bibliography, not in a filtered list. */
|
||||
index: number
|
||||
/** How many findings cite it. */
|
||||
cited: number
|
||||
readOnly: boolean
|
||||
onDelete: () => void
|
||||
}) {
|
||||
const plural = usePlural()
|
||||
const t = useT()
|
||||
const edit = useEditCommand()
|
||||
const key = { kind: 'reference', id: reference.id } as const
|
||||
const send = (field: string, patch: Partial<Reference>) =>
|
||||
edit.run(field, {
|
||||
op: 'update',
|
||||
key,
|
||||
element: { kind: 'reference', value: { ...reference, ...patch } },
|
||||
})
|
||||
const options = REFERENCE_TYPES.map((type) => ({
|
||||
value: type,
|
||||
label: t(`editor.reference.type.${type}`),
|
||||
}))
|
||||
const prefix = `${host}-reference-${index}-${reference.id}`
|
||||
return (
|
||||
<li {...focusAttrs(key)} className={`${CARD} ${FOCUS_CLASS}`}>
|
||||
<p className="text-right text-sm text-[var(--color-ink-muted)]">
|
||||
{cited === 0
|
||||
? t('editor.references.uncited')
|
||||
: plural('editor.references.cited', cited)}
|
||||
</p>
|
||||
<div className="grid gap-3">
|
||||
<SelectField
|
||||
id={`${prefix}-type`}
|
||||
label={t('editor.reference.type')}
|
||||
value={reference.type}
|
||||
options={options}
|
||||
onCommit={(type) => send('type', { type: type as ReferenceType })}
|
||||
readOnly={readOnly}
|
||||
error={edit.fieldError('type')}
|
||||
/>
|
||||
<TextField
|
||||
id={`${prefix}-citation`}
|
||||
label={t('editor.reference.citation')}
|
||||
value={reference.citation}
|
||||
onCommit={(value) =>
|
||||
isBlank(value)
|
||||
? edit.reject('citation', 'editor.field.required')
|
||||
: send('citation', { citation: value })
|
||||
}
|
||||
readOnly={readOnly}
|
||||
multiline
|
||||
error={edit.fieldError('citation')}
|
||||
/>
|
||||
<TextField
|
||||
id={`${prefix}-url`}
|
||||
label={t('editor.reference.url')}
|
||||
value={reference.url ?? ''}
|
||||
onCommit={(value) => send('url', { url: nullable(value) })}
|
||||
readOnly={readOnly}
|
||||
error={edit.fieldError('url')}
|
||||
/>
|
||||
<TextField
|
||||
id={`${prefix}-doi`}
|
||||
label={t('editor.reference.doi')}
|
||||
value={reference.doi ?? ''}
|
||||
onCommit={(value) => send('doi', { doi: nullable(value) })}
|
||||
readOnly={readOnly}
|
||||
error={edit.fieldError('doi')}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-end gap-1">
|
||||
<ActionButton
|
||||
readOnly={readOnly}
|
||||
variant="danger"
|
||||
size="sm"
|
||||
onClick={onDelete}
|
||||
>
|
||||
{t('editor.action.delete')}
|
||||
</ActionButton>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
@@ -17,14 +17,24 @@ export interface TileHandlers {
|
||||
edit: () => void
|
||||
/** Leaves the edit view; false (the view stays) when a field refuses. */
|
||||
done: () => boolean
|
||||
remove: () => void
|
||||
move: (position: number) => void
|
||||
/** « Supprimer »: the Références tab only. */
|
||||
remove?: () => void
|
||||
/** « Monter » / « Descendre »: the Références tab only. */
|
||||
move?: (position: number) => void
|
||||
goTo: (key: ElementKey) => void
|
||||
registerLeave: (guard: LeaveGuard | null) => void
|
||||
}
|
||||
|
||||
/** What a tile of the citations panel adds: the finding it belongs to and « Retirer ». */
|
||||
export interface PanelTile {
|
||||
current: ElementKey
|
||||
onRemove: () => void
|
||||
}
|
||||
|
||||
export interface TileProps {
|
||||
host: ReferenceHost
|
||||
/** Set for the citations panel: « ce constat » marks, « Retirer de ce constat ». */
|
||||
panel?: PanelTile
|
||||
reference: Reference
|
||||
/** Position in the whole bibliography, not in a filtered list. */
|
||||
position: number
|
||||
@@ -45,6 +55,12 @@ export const tileBase = (
|
||||
reference: Reference,
|
||||
) => `${host}-reference-${position}-${reference.id}`
|
||||
|
||||
/** The meta column (type, count) from 640 px: the panel gives it a fixed 132 px. */
|
||||
const META_COLUMN = {
|
||||
tab: 'sm:grid-cols-[1.25rem_1fr_auto]',
|
||||
panel: 'sm:grid-cols-[1.25rem_1fr_8.25rem]',
|
||||
} as const
|
||||
|
||||
const BUTTON_RING =
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
|
||||
|
||||
@@ -72,7 +88,7 @@ function TileHeader({
|
||||
aria-expanded={open || editing}
|
||||
aria-controls={`${base}-body`}
|
||||
onClick={props.on.toggle}
|
||||
className={`grid min-h-11 w-full grid-cols-[1.25rem_1fr] items-start gap-x-3 gap-y-1 rounded-lg p-3 text-left sm:grid-cols-[1.25rem_1fr_auto] ${BUTTON_RING}`}
|
||||
className={`grid min-h-11 w-full grid-cols-[1.25rem_1fr] items-start gap-x-3 gap-y-1 rounded-lg p-3 text-left ${META_COLUMN[props.host]} ${BUTTON_RING}`}
|
||||
>
|
||||
<Icon
|
||||
name={open || editing ? 'chevron-down' : 'chevron-right'}
|
||||
@@ -99,11 +115,43 @@ function TileHeader({
|
||||
)
|
||||
}
|
||||
|
||||
/** The panel's actions (P7): « Modifier » and « Retirer de ce constat », nothing else. */
|
||||
function PanelActions({
|
||||
props,
|
||||
panel,
|
||||
}: {
|
||||
props: TileProps
|
||||
panel: PanelTile
|
||||
}) {
|
||||
const t = useT()
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<ActionButton
|
||||
readOnly={false}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={props.on.edit}
|
||||
>
|
||||
{t('editor.references.edit')}
|
||||
</ActionButton>
|
||||
<ActionButton
|
||||
readOnly={false}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={panel.onRemove}
|
||||
>
|
||||
{t('editor.references.remove_citation')}
|
||||
</ActionButton>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** « Modifier », « Supprimer » (uncited only, else the hint), « Monter » / « Descendre ». */
|
||||
function TileActions({ props }: { props: TileProps }) {
|
||||
const t = useT()
|
||||
const { position, count, citers, readOnly, movable, on } = props
|
||||
if (readOnly) return null
|
||||
if (props.panel) return <PanelActions props={props} panel={props.panel} />
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
@@ -115,7 +163,7 @@ function TileActions({ props }: { props: TileProps }) {
|
||||
>
|
||||
{t('editor.references.edit')}
|
||||
</ActionButton>
|
||||
{citers.length === 0 && (
|
||||
{citers.length === 0 && on.remove && (
|
||||
<ActionButton
|
||||
readOnly={false}
|
||||
variant="ghost"
|
||||
@@ -126,14 +174,14 @@ function TileActions({ props }: { props: TileProps }) {
|
||||
{t('editor.action.delete')}
|
||||
</ActionButton>
|
||||
)}
|
||||
{movable && (
|
||||
{movable && on.move && (
|
||||
<>
|
||||
<ActionButton
|
||||
readOnly={false}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
disabled={position === 0}
|
||||
onClick={() => on.move(position - 1)}
|
||||
onClick={() => on.move?.(position - 1)}
|
||||
>
|
||||
{t('editor.action.move_up')}
|
||||
</ActionButton>
|
||||
@@ -142,7 +190,7 @@ function TileActions({ props }: { props: TileProps }) {
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
disabled={position >= count - 1}
|
||||
onClick={() => on.move(position + 1)}
|
||||
onClick={() => on.move?.(position + 1)}
|
||||
>
|
||||
{t('editor.action.move_down')}
|
||||
</ActionButton>
|
||||
@@ -188,7 +236,11 @@ export default function ReferenceTile(props: TileProps) {
|
||||
) : (
|
||||
<ReferenceFacts reference={reference} />
|
||||
)}
|
||||
<CitersList citers={props.citers} onGoTo={on.goTo} />
|
||||
<CitersList
|
||||
citers={props.citers}
|
||||
current={props.panel?.current}
|
||||
onGoTo={on.goTo}
|
||||
/>
|
||||
{editing ? (
|
||||
<ActionButton
|
||||
readOnly={false}
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
import { useEffect, useMemo, useState, type KeyboardEvent } from 'react'
|
||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||
import DeleteDialog, {
|
||||
type DeleteTarget,
|
||||
} from '@/components/editor/DeleteDialog'
|
||||
import Icon from '@/components/ui/Icon'
|
||||
import { citersOf } from '@/editor/references/citations'
|
||||
import {
|
||||
citedIds,
|
||||
citingFinding,
|
||||
visibleReferences,
|
||||
} from '@/editor/references/filter'
|
||||
import { useSheetDocument } from '@/editor/sheetDocument'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { ReferenceList } from './ReferenceList'
|
||||
|
||||
interface Props {
|
||||
readOnly: boolean
|
||||
/** The finding whose citations the panel lists. */
|
||||
citedBy: ElementKey
|
||||
/** ✕, Escape, and the finding vanishing (deleted, or an undo removed it). */
|
||||
onClose: () => void
|
||||
/** « Tout afficher »: closes the panel and opens the Références tab. */
|
||||
onShowAll: () => void
|
||||
}
|
||||
|
||||
function PanelHeader({ onClose }: { onClose: () => void }) {
|
||||
const t = useT()
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h2
|
||||
id="editor-citations-title"
|
||||
tabIndex={-1}
|
||||
data-place-heading
|
||||
className="flex items-center gap-2 outline-none font-serif text-xl"
|
||||
>
|
||||
<Icon name="book" size={20} />
|
||||
{t('editor.place.references')}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('editor.references.close')}
|
||||
onClick={onClose}
|
||||
className="inline-flex min-h-11 min-w-11 items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
|
||||
>
|
||||
<Icon name="close" size={18} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** « Citées par « nom » (n) » and « Tout afficher (N) ». */
|
||||
function FilterChip({
|
||||
name,
|
||||
cited,
|
||||
total,
|
||||
onShowAll,
|
||||
}: {
|
||||
name: string
|
||||
cited: number
|
||||
total: number
|
||||
onShowAll: () => void
|
||||
}) {
|
||||
const t = useT()
|
||||
const text = t('editor.references.cited_by')
|
||||
.replace('{name}', name)
|
||||
.replace('{count}', String(cited))
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span
|
||||
data-testid="references-filter-chip"
|
||||
className="rounded-full border border-[var(--color-accent)] bg-[var(--color-surface-strong)] px-3 py-1 text-sm"
|
||||
>
|
||||
{text}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onShowAll}
|
||||
className="min-h-11 text-sm underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
|
||||
>
|
||||
{t('editor.references.show_all').replace('{count}', String(total))}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The finding read from the current document; `gone` once the document lacks it. */
|
||||
function useCitingFinding(citedBy: ElementKey, onGone: () => void) {
|
||||
const doc = useSheetDocument()
|
||||
const finding = useMemo(
|
||||
() => (doc ? citingFinding(doc, citedBy) : null),
|
||||
[doc, citedBy],
|
||||
)
|
||||
const gone = doc !== null && finding === null
|
||||
useEffect(() => {
|
||||
if (gone) onGone()
|
||||
}, [gone, onGone])
|
||||
return { doc, finding }
|
||||
}
|
||||
|
||||
/**
|
||||
* The citations of one finding: the references it cites, each with how often it is cited.
|
||||
* Not a dialog: the workspace makes the page behind it inert. Opened only from a finding's
|
||||
* trigger; the whole library lives in the Références tab.
|
||||
*/
|
||||
export default function ReferencesPanel(props: Props) {
|
||||
const { readOnly, citedBy, onClose, onShowAll } = props
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
|
||||
const { doc, finding } = useCitingFinding(citedBy, onClose)
|
||||
const all = doc?.references ?? []
|
||||
const cited = finding ? citedIds(finding) : []
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'Escape' || event.defaultPrevented) return
|
||||
event.stopPropagation()
|
||||
onClose()
|
||||
}
|
||||
return (
|
||||
<section
|
||||
id="editor-citations-panel"
|
||||
data-testid="editor-citations-panel"
|
||||
aria-labelledby="editor-citations-title"
|
||||
onKeyDown={onKeyDown}
|
||||
className="sticky top-14 h-[calc(100dvh-3.5rem)] space-y-3 overflow-y-auto border-l border-[var(--color-border)] bg-[var(--color-surface)] p-4 shadow-xl"
|
||||
>
|
||||
<PanelHeader onClose={onClose} />
|
||||
{finding && (
|
||||
<FilterChip
|
||||
name={finding.name[locale]}
|
||||
cited={cited.length}
|
||||
total={all.length}
|
||||
onShowAll={onShowAll}
|
||||
/>
|
||||
)}
|
||||
{doc && (
|
||||
<ReferenceList
|
||||
host="panel"
|
||||
shown={visibleReferences(all, cited, '')}
|
||||
all={all}
|
||||
citers={citersOf(doc)}
|
||||
readOnly={readOnly}
|
||||
onDelete={(reference) =>
|
||||
setDeleting({
|
||||
key: { kind: 'reference', id: reference.id },
|
||||
label: reference.citation,
|
||||
})
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
export { REFERENCE_TYPES } from '@/editor/references/referenceTypes'
|
||||
|
||||
/** Where reference cards are shown: the Références tab or a finding's citations panel. */
|
||||
/** Where reference tiles are shown: the Références tab or a finding's citations panel. */
|
||||
export type ReferenceHost = 'tab' | 'panel'
|
||||
@@ -0,0 +1,140 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||
import { patchElement, type FindingItem } from '@/editor/findings/tree'
|
||||
import { citersOf } from '@/editor/references/citations'
|
||||
import { citedIds, citingFinding } from '@/editor/references/filter'
|
||||
import { citationEntries, findingPath } from '@/editor/references/panel'
|
||||
import { useSheetDocument } from '@/editor/sheetDocument'
|
||||
import { useEditCommand } from '@/editor/useEditCommand'
|
||||
import type { CanLeave } from '@/editor/useEditorNavigation'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { tileKeys, useTileState } from './useTileState'
|
||||
|
||||
export interface PanelHooks {
|
||||
readOnly: boolean
|
||||
citedBy: ElementKey
|
||||
/** The finding vanished: a close nobody can refuse. */
|
||||
onGone: () => void
|
||||
registerCanLeave: (guard: CanLeave | null) => void
|
||||
}
|
||||
|
||||
/** The finding read from the current document; null once the document lacks it. */
|
||||
function useCitedFinding(citedBy: ElementKey) {
|
||||
const doc = useSheetDocument()
|
||||
const item = useMemo(
|
||||
() => (doc ? citingFinding(doc, citedBy) : null),
|
||||
[doc, citedBy],
|
||||
)
|
||||
return { doc, item }
|
||||
}
|
||||
|
||||
/**
|
||||
* The panel closes once its finding is gone: a forced close. It runs after the leave
|
||||
* check registered itself (effects of one component run in order), so a tile in edit is
|
||||
* still asked. A read-only flip does not close it: the panel stays, as the crossing
|
||||
* specs expect, and its tiles stop being editable.
|
||||
*/
|
||||
function useCloseWhenGone(gone: boolean, onGone: () => void) {
|
||||
useEffect(() => {
|
||||
if (gone) onGone()
|
||||
}, [gone, onGone])
|
||||
}
|
||||
|
||||
/** P22'': a user close asks the tile in edit first; a forced one drops a refused draft. */
|
||||
function useLeaveCheck(
|
||||
tiles: ReturnType<typeof useTileState>,
|
||||
register: PanelHooks['registerCanLeave'],
|
||||
) {
|
||||
const t = useT()
|
||||
useEffect(() => {
|
||||
register((forced) => {
|
||||
const refused = tiles.leave()
|
||||
if (refused === null) return { allowed: true }
|
||||
if (!forced) return { allowed: false }
|
||||
const field = t(`editor.reference.${refused}`)
|
||||
const note = t('editor.references.draft_dropped').replace(
|
||||
'{field}',
|
||||
field,
|
||||
)
|
||||
return { allowed: true, note }
|
||||
})
|
||||
return () => register(null)
|
||||
})
|
||||
}
|
||||
|
||||
/** After a removal the focus goes to the next row's button, else the previous, else the heading. */
|
||||
function useFocusAfterRemoval(count: number) {
|
||||
const list = useRef<HTMLUListElement>(null)
|
||||
const heading = useRef<HTMLHeadingElement>(null)
|
||||
const [removed, setRemoved] = useState<{ at: number; before: number } | null>(
|
||||
null,
|
||||
)
|
||||
useEffect(() => {
|
||||
if (removed === null || count >= removed.before) return
|
||||
setRemoved(null)
|
||||
const rows = [...(list.current?.children ?? [])]
|
||||
const row = rows[removed.at] ?? rows[removed.at - 1]
|
||||
const target = row?.querySelector('button') ?? heading.current
|
||||
target?.focus()
|
||||
}, [removed, count])
|
||||
return { list, heading, afterRemoval: setRemoved }
|
||||
}
|
||||
|
||||
/**
|
||||
* What the panel shows of the finding: its cited ids and its path. Once the finding is
|
||||
* gone (the panel is leaving) the last known answer stays, so the panel does not empty
|
||||
* while it slides out and a tile in edit can still be asked to apply its draft.
|
||||
*/
|
||||
function useShownFinding(
|
||||
doc: ReturnType<typeof useSheetDocument>,
|
||||
item: FindingItem | null,
|
||||
citedBy: ElementKey,
|
||||
) {
|
||||
const found = useMemo(
|
||||
() =>
|
||||
doc && item
|
||||
? { ids: citedIds(item), path: findingPath(doc, citedBy) }
|
||||
: null,
|
||||
[doc, item, citedBy],
|
||||
)
|
||||
const [last, setLast] = useState(found)
|
||||
if (found !== null && found !== last) setLast(found)
|
||||
return found ?? last ?? { ids: [], path: [] }
|
||||
}
|
||||
|
||||
/** What the citations panel reads and does: the cited entries, tiles, « Retirer ». */
|
||||
export function useCitationsPanel(hooks: PanelHooks) {
|
||||
const { doc, item } = useCitedFinding(hooks.citedBy)
|
||||
const edit = useEditCommand()
|
||||
const { ids, path } = useShownFinding(doc, item, hooks.citedBy)
|
||||
const entries = citationEntries(doc?.references ?? [], ids)
|
||||
const keys = tileKeys(entries)
|
||||
const tiles = useTileState(doc ? keys : null)
|
||||
const focus = useFocusAfterRemoval(ids.length)
|
||||
useLeaveCheck(tiles, hooks.registerCanLeave)
|
||||
useCloseWhenGone(doc !== null && item === null, hooks.onGone)
|
||||
// « Retirer de ce constat » is the detail's « Retirer »: the same update of the finding's
|
||||
// reference_ids, so the core marks the finding « À confirmer » (P15) and one « Défaire »
|
||||
// restores the citation and the status together. The reference itself stays in the sheet.
|
||||
const remove = (at: number) => {
|
||||
if (!item || !tiles.finish()) return
|
||||
const rest = ids.filter((_, index) => index !== at)
|
||||
const element = patchElement(item, { reference_ids: rest })
|
||||
const command = { op: 'update', key: item.key, element } as const
|
||||
if (edit.run('references', command)) {
|
||||
focus.afterRemoval({ at, before: ids.length })
|
||||
}
|
||||
}
|
||||
return {
|
||||
doc,
|
||||
entries,
|
||||
tiles,
|
||||
keys,
|
||||
citers: doc ? citersOf(doc) : new Map<string, never[]>(),
|
||||
path,
|
||||
error: edit.fieldError('references'),
|
||||
remove,
|
||||
list: focus.list,
|
||||
heading: focus.heading,
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,11 @@ export const FIELDS = ['citation', 'doi', 'url'] as const
|
||||
export type Field = (typeof FIELDS)[number]
|
||||
type Drafts = Record<Field, string>
|
||||
|
||||
/** What the guard calls on a leave: true when every pending field was applied. */
|
||||
export type LeaveGuard = () => boolean
|
||||
/**
|
||||
* What the guard calls on a leave: null when every pending field was applied, else the
|
||||
* field that refused (its draft stays, the field is focused).
|
||||
*/
|
||||
export type LeaveGuard = () => Field | null
|
||||
|
||||
const committedOf = (reference: Reference): Drafts => ({
|
||||
citation: reference.citation,
|
||||
@@ -79,11 +82,11 @@ export function useReferenceEdit(
|
||||
const next = apply(current, field)
|
||||
if (!next) {
|
||||
document.getElementById(`${base}-${field}`)?.focus()
|
||||
return false
|
||||
return field
|
||||
}
|
||||
current = next
|
||||
}
|
||||
return true
|
||||
return null
|
||||
}
|
||||
useEffect(() => {
|
||||
registerLeave(leave)
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import type { Reference } from '@faunosteo/core-wasm/types'
|
||||
import type { LeaveGuard } from './useReferenceEdit'
|
||||
import type { LeaveGuard, Field } from './useReferenceEdit'
|
||||
|
||||
/**
|
||||
* One key per tile: the id and its occurrence among equal ids, so a duplicated id stays
|
||||
* two distinct tiles (P31) and a tile keeps its state when ↑ / ↓ changes its position.
|
||||
*/
|
||||
export function tileKeys(all: readonly Reference[]): string[] {
|
||||
export function tileKeys(all: readonly { id: string }[]): string[] {
|
||||
const seen = new Map<string, number>()
|
||||
return all.map((reference) => {
|
||||
const occurrence = seen.get(reference.id) ?? 0
|
||||
@@ -33,10 +32,11 @@ export function useTileState(keys: readonly string[] | null) {
|
||||
if (editingKey !== null && !live.has(editingKey)) setEditingKey(null)
|
||||
}
|
||||
const guard = useRef<LeaveGuard | null>(null)
|
||||
const leave = () => guard.current?.() ?? true
|
||||
/** Applies the tile in edit; the field that refused, null when nothing is left to apply. */
|
||||
const leave = (): Field | null => guard.current?.() ?? null
|
||||
const open = (key: string) => setOpenKeys((prev) => new Set(prev).add(key))
|
||||
const finish = () => {
|
||||
if (!leave()) return false
|
||||
if (leave() !== null) return false
|
||||
setEditingKey(null)
|
||||
return true
|
||||
}
|
||||
@@ -49,7 +49,8 @@ export function useTileState(keys: readonly string[] | null) {
|
||||
})
|
||||
}
|
||||
const startEdit = (key: string) => {
|
||||
if (editingKey !== null && editingKey !== key && !leave()) return false
|
||||
if (editingKey !== null && editingKey !== key && leave() !== null)
|
||||
return false
|
||||
setEditingKey(key)
|
||||
open(key)
|
||||
return true
|
||||
@@ -60,6 +61,7 @@ export function useTileState(keys: readonly string[] | null) {
|
||||
toggle,
|
||||
startEdit,
|
||||
finish,
|
||||
leave,
|
||||
reveal: open,
|
||||
registerLeave: (next: LeaveGuard | null) => {
|
||||
guard.current = next
|
||||
|
||||
@@ -1,13 +1,107 @@
|
||||
import ReferenceLibrary from '@/components/editor/references/ReferenceLibrary'
|
||||
import { useRef, useState } from 'react'
|
||||
import DeleteDialog, {
|
||||
type DeleteTarget,
|
||||
} from '@/components/editor/DeleteDialog'
|
||||
import EditOnly from '@/components/editor/EditOnly'
|
||||
import NewReferenceTile from '@/components/editor/references/NewReferenceTile'
|
||||
import NoResult from '@/components/editor/references/NoResult'
|
||||
import ReferenceTiles from '@/components/editor/references/ReferenceTiles'
|
||||
import ReferenceToolbar from '@/components/editor/references/ReferenceToolbar'
|
||||
import {
|
||||
useReferenceActions,
|
||||
useReferenceLibrary,
|
||||
} from '@/components/editor/references/useReferenceLibrary'
|
||||
import { isSheetView } from '@/editor/references/view'
|
||||
import type { EditorPlaceProps } from '@/editor/tabs'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** The empty line: the sheet has no reference at all. */
|
||||
function EmptyLine() {
|
||||
const t = useT()
|
||||
return (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.reference.empty')}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
type Props = Pick<EditorPlaceProps, 'readOnly' | 'navigate' | 'focus'> & {
|
||||
resetSignal: number
|
||||
}
|
||||
|
||||
/**
|
||||
* The sheet's bibliography: toolbar (search, sort, count, add), one collapsible tile per
|
||||
* reference, the draft tile and the delete dialog. Ids carry the `tab-` prefix. The
|
||||
* citations panel shares only the tile (R2.4).
|
||||
*/
|
||||
function Library({ readOnly, navigate, focus, resetSignal }: Props) {
|
||||
const t = useT()
|
||||
const lib = useReferenceLibrary(readOnly, resetSignal)
|
||||
const searchRef = useRef<HTMLInputElement>(null)
|
||||
const act = useReferenceActions(lib, focus, searchRef)
|
||||
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
|
||||
const { all, shown } = lib
|
||||
const sheetView = isSheetView(shown.view)
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<ReferenceToolbar
|
||||
query={shown.view.query}
|
||||
onQuery={(query) => shown.update({ query })}
|
||||
onClear={act.clearSearch}
|
||||
searchRef={searchRef}
|
||||
sort={shown.view.sort}
|
||||
onSort={(sort) => shown.update({ sort })}
|
||||
shown={shown.matchCount}
|
||||
total={all.length}
|
||||
canAdd={!readOnly}
|
||||
onAdd={act.startAdd}
|
||||
/>
|
||||
{lib.loaded && (
|
||||
<>
|
||||
{all.length === 0 && <EmptyLine />}
|
||||
{all.length > 0 && shown.matchCount === 0 && (
|
||||
<NoResult query={shown.view.query} onClear={act.clearSearch} />
|
||||
)}
|
||||
{!readOnly && !sheetView && shown.positions.length > 0 && (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.references.reorder_hint')}
|
||||
</p>
|
||||
)}
|
||||
<ReferenceTiles
|
||||
positions={shown.positions}
|
||||
all={all}
|
||||
keys={lib.keys}
|
||||
citers={lib.citers}
|
||||
tiles={lib.tiles}
|
||||
readOnly={readOnly}
|
||||
movable={sheetView}
|
||||
navigate={navigate}
|
||||
onEdit={act.edit}
|
||||
onDelete={(reference) =>
|
||||
setDeleting({
|
||||
key: { kind: 'reference', id: reference.id },
|
||||
label: reference.citation,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<EditOnly readOnly={readOnly}>
|
||||
{act.draft !== null && (
|
||||
<NewReferenceTile focusSerial={act.draft} onAdded={act.added} />
|
||||
)}
|
||||
</EditOnly>
|
||||
</>
|
||||
)}
|
||||
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The fifth tab: the sheet's reference library under its own heading. */
|
||||
export default function ReferencesTab({
|
||||
readOnly,
|
||||
navigate,
|
||||
focus,
|
||||
libraryReset,
|
||||
libraryReset = 0,
|
||||
}: EditorPlaceProps) {
|
||||
const t = useT()
|
||||
return (
|
||||
@@ -24,7 +118,7 @@ export default function ReferencesTab({
|
||||
>
|
||||
{t('editor.tab.references')}
|
||||
</h2>
|
||||
<ReferenceLibrary
|
||||
<Library
|
||||
readOnly={readOnly}
|
||||
navigate={navigate}
|
||||
focus={focus}
|
||||
|
||||
@@ -102,8 +102,8 @@ export function useSelectionEscape(
|
||||
) {
|
||||
const asideRef = useRef<HTMLElement>(null)
|
||||
const deselect = useDeselect(id, clear)
|
||||
const referencesOpen = useContext(ReferencesOpenContext)
|
||||
useEscapeDeselect(active && !referencesOpen, (event) =>
|
||||
const citationsOf = useContext(ReferencesOpenContext)
|
||||
useEscapeDeselect(active && citationsOf === null, (event) =>
|
||||
deselect.byKey(asideRef.current?.contains(event.target as Node) ?? false),
|
||||
)
|
||||
return { asideRef, byDrawing: deselect.byDrawing }
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import { createContext, useContext, useState } from 'react'
|
||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||
import { usePlaceVisible } from '@/lib/placeVisibility'
|
||||
|
||||
/** The editor cannot be edited now (route rule: mode, recovery, store not in step). */
|
||||
export const ReadOnlyContext = createContext(false)
|
||||
|
||||
/** The citations panel is open: a place beside it is not where a modal may open. */
|
||||
export const ReferencesOpenContext = createContext(false)
|
||||
/**
|
||||
* The finding whose citations panel is open, null when none. Set from the opening to the
|
||||
* end of the exit animation: a place beside the panel is not where a modal may open, and
|
||||
* only that finding's trigger reads « expanded ».
|
||||
*/
|
||||
export const ReferencesOpenContext = createContext<ElementKey | null>(null)
|
||||
|
||||
export function useEditorReadOnly(): boolean {
|
||||
return useContext(ReadOnlyContext)
|
||||
@@ -18,9 +23,9 @@ export function useEditorReadOnly(): boolean {
|
||||
*/
|
||||
export function useDecisionsOpen(): boolean {
|
||||
const readOnly = useContext(ReadOnlyContext)
|
||||
const referencesOpen = useContext(ReferencesOpenContext)
|
||||
const citationsOf = useContext(ReferencesOpenContext)
|
||||
const visible = usePlaceVisible()
|
||||
return !readOnly && visible && !referencesOpen
|
||||
return !readOnly && visible && citationsOf === null
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -262,6 +262,6 @@ export function itemForKey(
|
||||
return { item, ancestors }
|
||||
}
|
||||
|
||||
function sameKey(a: ElementKey, b: ElementKey): boolean {
|
||||
export function sameKey(a: ElementKey, b: ElementKey): boolean {
|
||||
return JSON.stringify(a) === JSON.stringify(b)
|
||||
}
|
||||
@@ -15,14 +15,8 @@ export type { FocusRequest }
|
||||
*/
|
||||
export type FocusOutcome = 'found' | 'kept' | 'none'
|
||||
|
||||
/**
|
||||
* The `data-place` name of a place. `citations` (the panel) is no navigation target: it
|
||||
* is a name only for its heading and its focus scope.
|
||||
*/
|
||||
export type PlaceName =
|
||||
| EditorTabId
|
||||
| `annotations.${AnnotationSection}`
|
||||
| 'citations'
|
||||
/** The `data-place` name of a place a request can name (the citations panel is none). */
|
||||
export type PlaceName = EditorTabId | `annotations.${AnnotationSection}`
|
||||
|
||||
export function placeOf(target: EditorTarget): PlaceName {
|
||||
if (target.tab !== 'annotations') return target.tab
|
||||
|
||||
@@ -32,16 +32,3 @@ export function referenceMatches(reference: Reference, query: string): boolean {
|
||||
(field) => folded(field).includes(term),
|
||||
)
|
||||
}
|
||||
|
||||
/** The references to list: those the finding cites (when filtered) that match the query. */
|
||||
export function visibleReferences(
|
||||
references: readonly Reference[],
|
||||
cited: readonly string[] | null,
|
||||
query: string,
|
||||
): Reference[] {
|
||||
return references.filter(
|
||||
(reference) =>
|
||||
(cited === null || cited.includes(reference.id)) &&
|
||||
referenceMatches(reference, query),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type {
|
||||
AnatomicalSheetDocument,
|
||||
ElementKey,
|
||||
LocalizedText,
|
||||
Reference,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import { buildItems, itemForKey } from '@/editor/findings/tree'
|
||||
|
||||
/**
|
||||
* One citation of the finding, in the order it lists them. A reference the sheet no
|
||||
* longer holds is kept as a row of its own (`reference` null), so the count, the list and
|
||||
* the trigger all describe the same ids (P30). `index` tells two entries of one id apart.
|
||||
*/
|
||||
export interface CitationEntry {
|
||||
id: string
|
||||
index: number
|
||||
reference: Reference | null
|
||||
}
|
||||
|
||||
export function citationEntries(
|
||||
references: readonly Reference[],
|
||||
ids: readonly string[],
|
||||
): CitationEntry[] {
|
||||
return ids.map((id, index) => ({
|
||||
id,
|
||||
index,
|
||||
reference: references.find((candidate) => candidate.id === id) ?? null,
|
||||
}))
|
||||
}
|
||||
|
||||
/** The zone and the families above a finding, then the finding itself, outermost first. */
|
||||
export function findingPath(
|
||||
doc: AnatomicalSheetDocument,
|
||||
key: ElementKey,
|
||||
): LocalizedText[] {
|
||||
const items = buildItems(doc)
|
||||
const found = itemForKey(items, key)
|
||||
if (!found) return []
|
||||
const names = found.ancestors.map(
|
||||
(id) => items.find((item) => item.id === id)?.name,
|
||||
)
|
||||
return [...names.reverse(), found.item.name].filter(
|
||||
(name): name is LocalizedText => name !== undefined,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { NavigationAction } from './navigation'
|
||||
|
||||
/** Panel motion (board 25): enter decelerates, the shorter exit accelerates (P9). */
|
||||
export const PANEL_ENTER_S = 0.18
|
||||
export const PANEL_EXIT_S = 0.14
|
||||
|
||||
/** The exit plus a margin: past it, a callback that never came is applied by the timer. */
|
||||
const FALLBACK_MS = PANEL_EXIT_S * 1000 + 100
|
||||
|
||||
export type PendingKind =
|
||||
| 'go_to'
|
||||
| 'citations_closed'
|
||||
| 'show_all'
|
||||
| 'tab_selected'
|
||||
|
||||
/** The one move a close records: applied when the exit is over (P9). */
|
||||
export interface PendingClose {
|
||||
action: NavigationAction
|
||||
kind: PendingKind
|
||||
text: string
|
||||
/** Said before `text`: a draft dropped by a forced close. It survives a replacement. */
|
||||
note?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* The close of the citations panel as a two-step move (P9, P28): `record` starts the exit
|
||||
* (the page stays inert, the panel is inert too); `complete` runs once, from the panel's
|
||||
* `onExitComplete` or from a one-shot timer when that never fires, and hands the pending
|
||||
* move to `apply`. A second close is a no-op; a tab choice replaces the pending move.
|
||||
*/
|
||||
export function useCitationsExit(apply: (move: PendingClose) => void) {
|
||||
const [exiting, setExiting] = useState(false)
|
||||
const pending = useRef<PendingClose | null>(null)
|
||||
const timer = useRef<number | undefined>(undefined)
|
||||
const complete = useCallback(() => {
|
||||
const move = pending.current
|
||||
if (move === null) return
|
||||
pending.current = null
|
||||
window.clearTimeout(timer.current)
|
||||
setExiting(false)
|
||||
apply(move)
|
||||
}, [apply])
|
||||
const record = useCallback(
|
||||
(move: PendingClose) => {
|
||||
if (pending.current !== null) {
|
||||
if (move.kind !== 'tab_selected') return
|
||||
const note = pending.current.note ?? move.note
|
||||
pending.current = note ? { ...move, note } : move
|
||||
return
|
||||
}
|
||||
pending.current = move
|
||||
setExiting(true)
|
||||
timer.current = window.setTimeout(complete, FALLBACK_MS)
|
||||
},
|
||||
[complete],
|
||||
)
|
||||
const busy = useCallback(() => pending.current !== null, [])
|
||||
useEffect(() => () => window.clearTimeout(timer.current), [])
|
||||
return { exiting, record, complete, busy }
|
||||
}
|
||||
@@ -27,21 +27,34 @@ import {
|
||||
type NavigationState,
|
||||
} from './navigation'
|
||||
import { MORE_BUTTON_ID, tabDomId, type EditorTabId } from './tabs'
|
||||
import {
|
||||
useCitationsExit,
|
||||
type PendingClose,
|
||||
type PendingKind,
|
||||
} from './useCitationsExit'
|
||||
|
||||
type MoveKind =
|
||||
| 'go_to'
|
||||
| 'section'
|
||||
| 'back'
|
||||
| 'citations'
|
||||
| 'citations_closed'
|
||||
| 'show_all'
|
||||
| 'tab_selected'
|
||||
type MoveKind = PendingKind | 'section' | 'back'
|
||||
|
||||
/** A programmatic move: a new object per move, so the effect after it runs once. */
|
||||
/**
|
||||
* A programmatic move: a new object per move, so the effect after it runs once.
|
||||
* `afterExit`: it is the pending move of a closed panel, so a focus the user already
|
||||
* placed elsewhere during the exit is left alone (P28).
|
||||
*/
|
||||
interface Move {
|
||||
kind: MoveKind
|
||||
afterExit?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* The panel's answer before a close (P22''): `allowed` false cancels a user close. A forced
|
||||
* close always goes ahead; `note` (a draft dropped) is said with the close.
|
||||
*/
|
||||
export interface LeaveAnswer {
|
||||
allowed: boolean
|
||||
note?: string
|
||||
}
|
||||
export type CanLeave = (forced: boolean) => LeaveAnswer
|
||||
|
||||
type Opener = HTMLElement | null | undefined
|
||||
|
||||
export interface EditorNavigation {
|
||||
@@ -54,10 +67,18 @@ export interface EditorNavigation {
|
||||
backToDrawing: () => void
|
||||
/** Opens the citations panel of a finding node; any other key is ignored. */
|
||||
openCitations: (citedBy: ElementKey, opener?: Opener) => void
|
||||
/** Every close (✕, Escape, scrim, element gone): the focus goes to P6's fallbacks. */
|
||||
/** A user close (✕, Escape, scrim): the panel exits, then the focus goes to P6's fallbacks. */
|
||||
closeCitations: () => void
|
||||
/** The finding vanished: the same close, never refused (a refused draft is dropped, said aloud). */
|
||||
dropCitations: () => void
|
||||
/** « Tout afficher dans l'onglet Références »: panel closed, tab shown, library reset. */
|
||||
showAllReferences: () => void
|
||||
/** The panel is playing its exit: the state still holds it, the page stays inert. */
|
||||
exiting: boolean
|
||||
/** The panel's `onExitComplete`: applies the pending move. */
|
||||
exitComplete: () => void
|
||||
/** The panel hands its `canLeave` over while it is mounted (P22''). */
|
||||
registerCanLeave: (guard: CanLeave | null) => void
|
||||
consumed: (serial: number, outcome: FocusOutcome) => void
|
||||
announce: (text: string) => void
|
||||
}
|
||||
@@ -113,10 +134,21 @@ interface Openers {
|
||||
|
||||
type Go = (action: NavigationAction, kind: MoveKind, text: string) => void
|
||||
|
||||
/** The one way to move: commit the typed text, announce, dispatch, record the move. */
|
||||
/**
|
||||
* The one way to move: commit the typed text, announce, dispatch, record the move.
|
||||
* `finish` is the same without the commit, for the move a closed panel recorded.
|
||||
*/
|
||||
function useGo(dispatch: Dispatch<NavigationAction>) {
|
||||
const { live, announce } = useLiveRegion()
|
||||
const [move, setMove] = useState<Move | null>(null)
|
||||
const finish = useCallback(
|
||||
(move: PendingClose) => {
|
||||
announce(move.note ? `${move.note}. ${move.text}` : move.text)
|
||||
dispatch(move.action)
|
||||
setMove({ kind: move.kind, afterExit: true })
|
||||
},
|
||||
[announce, dispatch],
|
||||
)
|
||||
const go: Go = useCallback(
|
||||
(action, kind, text) => {
|
||||
commitFocusedField()
|
||||
@@ -126,7 +158,7 @@ function useGo(dispatch: Dispatch<NavigationAction>) {
|
||||
},
|
||||
[announce, dispatch],
|
||||
)
|
||||
return { move, go, live, announce }
|
||||
return { move, go, finish, live, announce }
|
||||
}
|
||||
|
||||
/** Tab and section moves: « Aller à », a section entry, « Retour au dessin ». */
|
||||
@@ -154,33 +186,92 @@ function useSectionMoves(go: Go, openers: Openers) {
|
||||
return { navigate, openSection, backToDrawing }
|
||||
}
|
||||
|
||||
/** The citations panel moves: open from a finding, close, « Tout afficher ». */
|
||||
function useCitationsMoves(go: Go, openers: Openers) {
|
||||
/** What the panel's moves need of the hook: its state, the exit and the leave check. */
|
||||
interface PanelContext {
|
||||
open: boolean
|
||||
go: Go
|
||||
openers: Openers
|
||||
dispatch: Dispatch<NavigationAction>
|
||||
announce: (text: string) => void
|
||||
exit: ReturnType<typeof useCitationsExit>
|
||||
canLeave: RefObject<CanLeave | null>
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a close of the panel. A user close asks the panel first (P22''): a refused
|
||||
* draft cancels it. While an exit is playing, a close is a no-op (a tab choice replaces
|
||||
* the pending move) and asks nothing: the draft was settled by the first close.
|
||||
*/
|
||||
function useRequestClose(ctx: PanelContext) {
|
||||
const { open, exit, canLeave } = ctx
|
||||
const { busy, record } = exit
|
||||
return useCallback(
|
||||
(move: PendingClose, forced: boolean) => {
|
||||
if (!open) return
|
||||
if (busy()) return record(move)
|
||||
commitFocusedField()
|
||||
const { allowed, note } = canLeave.current?.(forced) ?? { allowed: true }
|
||||
if (!allowed) return
|
||||
record(note ? { ...move, note } : move)
|
||||
},
|
||||
[open, busy, record, canLeave],
|
||||
)
|
||||
}
|
||||
|
||||
/** Opens the panel of a finding node: no move is recorded, the panel focuses itself. */
|
||||
function useOpenCitations(ctx: PanelContext) {
|
||||
const t = useT()
|
||||
const openCitations = useCallback(
|
||||
const { openers, dispatch, announce } = ctx
|
||||
return useCallback(
|
||||
(citedBy: ElementKey, opener?: Opener) => {
|
||||
if (!isFindingNode(citedBy)) return
|
||||
commitFocusedField()
|
||||
openers.citations.current = opener ?? null
|
||||
openers.citedBy.current = citedBy
|
||||
const action = { type: 'open_citations', citedBy } as const
|
||||
go(action, 'citations', t('editor.place.references'))
|
||||
announce(t('editor.place.references'))
|
||||
dispatch({ type: 'open_citations', citedBy })
|
||||
},
|
||||
[go, openers, t],
|
||||
[openers, dispatch, announce, t],
|
||||
)
|
||||
const closeCitations = useCallback(() => {
|
||||
const text = t('editor.live.references_closed')
|
||||
go({ type: 'close_citations' }, 'citations_closed', text)
|
||||
}, [go, t])
|
||||
const showAllReferences = useCallback(
|
||||
() =>
|
||||
go(
|
||||
{ type: 'show_all_references' },
|
||||
'show_all',
|
||||
t('editor.tab.references'),
|
||||
),
|
||||
[go, t],
|
||||
}
|
||||
|
||||
/** The closes of the panel: ✕ / Escape / scrim, the vanished finding, « Tout afficher », « Aller à ». */
|
||||
function useCloseMoves(ctx: PanelContext) {
|
||||
const t = useT()
|
||||
const moveText = useMoveText()
|
||||
const { open, go } = ctx
|
||||
const request = useRequestClose(ctx)
|
||||
const closing = useCallback(
|
||||
(forced: boolean) => {
|
||||
const text = t('editor.live.references_closed')
|
||||
request(
|
||||
{ action: { type: 'close_citations' }, kind: 'citations_closed', text },
|
||||
forced,
|
||||
)
|
||||
},
|
||||
[request, t],
|
||||
)
|
||||
return { openCitations, closeCitations, showAllReferences }
|
||||
// With no panel open there is nothing to exit: the tab shows at once.
|
||||
const showAllReferences = useCallback(() => {
|
||||
const action = { type: 'show_all_references' } as const
|
||||
const text = t('editor.tab.references')
|
||||
if (!open) return go(action, 'show_all', text)
|
||||
request({ action, kind: 'show_all', text }, false)
|
||||
}, [open, go, request, t])
|
||||
const navigate = useCallback(
|
||||
(target: EditorTarget) => {
|
||||
const action = { type: 'go_to', target } as const
|
||||
request({ action, kind: 'go_to', text: moveText(target) }, false)
|
||||
},
|
||||
[request, moveText],
|
||||
)
|
||||
return {
|
||||
closeCitations: useCallback(() => closing(false), [closing]),
|
||||
dropCitations: useCallback(() => closing(true), [closing]),
|
||||
showAllReferences,
|
||||
navigate,
|
||||
request,
|
||||
}
|
||||
}
|
||||
|
||||
/** « Retour au dessin »: the entry that opened the section, else the canvas box. */
|
||||
@@ -212,9 +303,18 @@ function focusAfterClose(openers: Openers) {
|
||||
if (!focusHeld(triggerOf(openers))) focusActiveTab()
|
||||
}
|
||||
|
||||
/** Nothing the user chose holds the focus: `body`, or what the closing panel still has. */
|
||||
function focusIsFree(): boolean {
|
||||
const active = document.activeElement
|
||||
return (
|
||||
active === null ||
|
||||
active === document.body ||
|
||||
active.closest('[data-place="citations"]') !== null
|
||||
)
|
||||
}
|
||||
|
||||
/** Where the focus lands after a programmatic move; never `body`. */
|
||||
function landingOf(move: Move, state: NavigationState): HTMLElement | null {
|
||||
if (move.kind === 'citations') return headingOf('citations')
|
||||
if (move.kind === 'show_all') {
|
||||
return headingOf('references') ?? tabButton(state.tab)
|
||||
}
|
||||
@@ -238,10 +338,6 @@ function useMoveFocus(
|
||||
useEffect(() => {
|
||||
if (!move || handled.current === move) return
|
||||
handled.current = move
|
||||
if (move.kind === 'citations_closed') {
|
||||
focusAfterClose(openers)
|
||||
return
|
||||
}
|
||||
const serial = state.focus?.serial
|
||||
if (move.kind === 'go_to' && serial !== undefined) {
|
||||
const outcome = outcomes.current.get(serial)
|
||||
@@ -249,7 +345,9 @@ function useMoveFocus(
|
||||
if (outcome === 'found' || outcome === 'kept') return
|
||||
dispatch({ type: 'focus_consumed', serial })
|
||||
}
|
||||
if (move.kind === 'back') backTarget(openers.section.current)?.focus()
|
||||
if (move.afterExit && !focusIsFree()) return
|
||||
if (move.kind === 'citations_closed') focusAfterClose(openers)
|
||||
else if (move.kind === 'back') backTarget(openers.section.current)?.focus()
|
||||
else landingOf(move, state)?.focus()
|
||||
}, [move, state, outcomes, dispatch, openers])
|
||||
}
|
||||
@@ -269,7 +367,7 @@ function useReceipts(dispatch: Dispatch<NavigationAction>) {
|
||||
|
||||
/** A tab choice; with the citations panel open it closes and the new tab takes the focus. */
|
||||
function useTabSelect(
|
||||
go: Go,
|
||||
request: ReturnType<typeof useCloseMoves>['request'],
|
||||
dispatch: Dispatch<NavigationAction>,
|
||||
open: boolean,
|
||||
) {
|
||||
@@ -277,11 +375,14 @@ function useTabSelect(
|
||||
return useCallback(
|
||||
(tab: EditorTabId) => {
|
||||
const action = { type: 'select_tab', tab } as const
|
||||
if (open) return go(action, 'tab_selected', t(`editor.tab.${tab}`))
|
||||
if (open) {
|
||||
const text = t(`editor.tab.${tab}`)
|
||||
return request({ action, kind: 'tab_selected', text }, false)
|
||||
}
|
||||
commitFocusedField()
|
||||
dispatch(action)
|
||||
},
|
||||
[go, dispatch, open, t],
|
||||
[request, dispatch, open, t],
|
||||
)
|
||||
}
|
||||
|
||||
@@ -292,21 +393,39 @@ export function useEditorNavigation(initialTab: EditorTabId): EditorNavigation {
|
||||
initialTab,
|
||||
initialNavigation,
|
||||
)
|
||||
const { move, go, live, announce } = useGo(dispatch)
|
||||
const { move, go, finish, live, announce } = useGo(dispatch)
|
||||
const openers = useRef<Openers>({
|
||||
citations: { current: null },
|
||||
citedBy: { current: null },
|
||||
section: { current: null },
|
||||
}).current
|
||||
const canLeave = useRef<CanLeave | null>(null)
|
||||
const exit = useCitationsExit(finish)
|
||||
const registerCanLeave = useCallback((guard: CanLeave | null) => {
|
||||
canLeave.current = guard
|
||||
}, [])
|
||||
const open = state.citationsOf !== null
|
||||
const receipts = useReceipts(dispatch)
|
||||
useMoveFocus(move, state, receipts.outcomes, dispatch, openers)
|
||||
const sections = useSectionMoves(go, openers)
|
||||
const ctx = { open, go, openers, dispatch, announce, exit, canLeave }
|
||||
const openCitations = useOpenCitations(ctx)
|
||||
const panel = useCloseMoves(ctx)
|
||||
return {
|
||||
state,
|
||||
live,
|
||||
announce,
|
||||
consumed: receipts.consumed,
|
||||
selectTab: useTabSelect(go, dispatch, state.citationsOf !== null),
|
||||
...useSectionMoves(go, openers),
|
||||
...useCitationsMoves(go, openers),
|
||||
selectTab: useTabSelect(panel.request, dispatch, open),
|
||||
openSection: sections.openSection,
|
||||
backToDrawing: sections.backToDrawing,
|
||||
navigate: open ? panel.navigate : sections.navigate,
|
||||
openCitations,
|
||||
closeCitations: panel.closeCitations,
|
||||
dropCitations: panel.dropCitations,
|
||||
showAllReferences: panel.showAllReferences,
|
||||
exiting: exit.exiting,
|
||||
exitComplete: exit.complete,
|
||||
registerCanLeave,
|
||||
}
|
||||
}
|
||||
@@ -1230,8 +1230,15 @@ export const en: Dict = {
|
||||
'editor.annotations.deselected': 'No annotation selected.',
|
||||
'editor.references.close': 'Close the references',
|
||||
'editor.references.search': 'Search a reference',
|
||||
'editor.references.cited_by': 'Cited by « {name} » ({count})',
|
||||
'editor.references.show_all': 'Show all ({count})',
|
||||
'editor.references.panel_title': 'Cited references',
|
||||
'editor.references.panel_count_one': '{count} reference cited by this finding',
|
||||
'editor.references.panel_count_other': '{count} references cited by this finding',
|
||||
'editor.references.panel_show_all': 'Show all in the References tab',
|
||||
'editor.references.panel_empty': 'This finding no longer cites any reference.',
|
||||
'editor.references.remove_citation': 'Remove from this finding',
|
||||
'editor.references.this_finding': 'this finding',
|
||||
'editor.references.missing': 'Reference not found',
|
||||
'editor.references.draft_dropped': 'Entry not applied: {field}',
|
||||
'editor.references.cited_one': 'Cited {count} time',
|
||||
'editor.references.cited_other': 'Cited {count} times',
|
||||
'editor.references.uncited': 'Not cited',
|
||||
|
||||
@@ -1261,8 +1261,15 @@ export const fr: Dict = {
|
||||
'editor.annotations.deselected': 'Aucune annotation sélectionnée.',
|
||||
'editor.references.close': 'Fermer les références',
|
||||
'editor.references.search': 'Rechercher une référence',
|
||||
'editor.references.cited_by': 'Citées par « {name} » ({count})',
|
||||
'editor.references.show_all': 'Tout afficher ({count})',
|
||||
'editor.references.panel_title': 'Références citées',
|
||||
'editor.references.panel_count_one': '{count} référence citée par ce constat',
|
||||
'editor.references.panel_count_other': '{count} références citées par ce constat',
|
||||
'editor.references.panel_show_all': 'Tout afficher dans l\'onglet Références',
|
||||
'editor.references.panel_empty': 'Ce constat ne cite plus aucune référence.',
|
||||
'editor.references.remove_citation': 'Retirer de ce constat',
|
||||
'editor.references.this_finding': 'ce constat',
|
||||
'editor.references.missing': 'Référence introuvable',
|
||||
'editor.references.draft_dropped': 'Saisie non appliquée : {field}',
|
||||
'editor.references.cited_one': 'Citée {count} fois',
|
||||
'editor.references.cited_other': 'Citée {count} fois',
|
||||
'editor.references.uncited': 'Non citée',
|
||||
|
||||
Reference in new issue
Block a user