feat(editor): reference dialog, reading tiles and finding filter in the history
R2F-5 and R2F-6: the reference dialog is a view layer above the References tab or the citations sheet (local draft, one command per changed save, creation entry becomes the reference's own). Tiles only read. « Tout afficher » filters the library by the finding, « Revenir au constat » pops or pushes. Inline tile edit, draft tile and their guards removed.
This commit is contained in:
1 parent
e2d020bd3d
commit
8031e0078f
28 files changed
+1072
-1512
No files matched your search
@@ -10,7 +10,7 @@ import { useEditorStore } from '@/editor/state/editorStore'
|
||||
import { ownedEntry, withoutForms } from '@/editor/history/entry'
|
||||
import useEditorHistory from '@/editor/history/useEditorHistory'
|
||||
import { citationsOfView, defaultView } from '@/editor/navigation'
|
||||
import { findingLayerOf } from '@/editor/findingLayer'
|
||||
import { findingLayerOf, referenceLayerOf } from '@/editor/findingLayer'
|
||||
import { initialTab } from '@/editor/tabs'
|
||||
import {
|
||||
useEditorNavigation,
|
||||
@@ -27,6 +27,7 @@ import EditorTabs from './EditorTabs'
|
||||
import ModeNotice from './ModeNotice'
|
||||
import RecoveryNotice from './RecoveryNotice'
|
||||
import CitationsSheet from './references/CitationsSheet'
|
||||
import ReferenceDialog from './references/ReferenceDialog'
|
||||
|
||||
interface Props {
|
||||
sheet: OfficialSheetAdmin
|
||||
@@ -77,11 +78,14 @@ interface PlacesProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* The tab panels, then the citations sheet: the sheet comes after the tab body (which
|
||||
* holds the finding dialog) so it is shown after it and lies over it.
|
||||
* The tab panels, then the citations sheet and the reference dialog: each comes after the
|
||||
* one under it in the tree (the tab body holds the finding dialog), so it is shown after
|
||||
* it and lies over it.
|
||||
*/
|
||||
function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
|
||||
const { state } = nav
|
||||
const references = referenceLayerOf(nav)
|
||||
const cited = citationsOfView(state)
|
||||
return (
|
||||
<>
|
||||
<EditorTabBody
|
||||
@@ -90,6 +94,7 @@ function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
|
||||
readOnly={readOnly}
|
||||
navigate={nav.navigate}
|
||||
layer={findingLayerOf(nav)}
|
||||
references={references}
|
||||
libraryReset={state.libraryReset}
|
||||
focus={state.focus}
|
||||
reloadSheet={reloadSheet}
|
||||
@@ -101,14 +106,15 @@ function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
|
||||
}}
|
||||
/>
|
||||
<CitationsSheet
|
||||
citedBy={citationsOfView(state)}
|
||||
citedBy={cited}
|
||||
readOnly={readOnly}
|
||||
guards={nav.guards}
|
||||
onClose={nav.closeCitations}
|
||||
onShowAll={nav.showAllReferences}
|
||||
onShowAll={() => cited && nav.showAllReferences(cited)}
|
||||
navigate={nav.navigate}
|
||||
onEdit={nav.references.open}
|
||||
returnFocus={nav.citationsTrigger}
|
||||
/>
|
||||
<ReferenceDialog layer={references} readOnly={readOnly} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,34 +1,38 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useBeforeUnload } from '@/app/useLeaveGuard'
|
||||
import type { Guards } from '@/editor/useEditorNavigation'
|
||||
import type { Guards, LayerName } from '@/editor/useEditorNavigation'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** What the footer's « Abandonner » does: leave the form, or the whole dialog. */
|
||||
export type DiscardTarget = 'form' | 'dialog'
|
||||
|
||||
/**
|
||||
* The finding layer's guard while a form holds changes (R2F-3): a user close that reaches
|
||||
* the layer (✕, Escape, scrim, Back) is refused and the form asks « Abandonner les
|
||||
* The layer's guard (the finding dialog's, or the reference dialog's) while a form holds
|
||||
* changes (R2F-3, R2F-5): a user close that reaches the layer (✕, Escape, scrim, Back) is refused and the form asks « Abandonner les
|
||||
* modifications ? » (`confirming`). A forced close (the element vanished) goes ahead and
|
||||
* says the draft was dropped (BDR-115); a form with nothing typed says nothing.
|
||||
* `askToLeave` is the form's own « Annuler ». The browser's unload is guarded too.
|
||||
*/
|
||||
export function useDirtyGuard(guards: Guards, dirty: boolean) {
|
||||
export function useDirtyGuard(
|
||||
guards: Guards,
|
||||
dirty: boolean,
|
||||
layer: LayerName,
|
||||
) {
|
||||
const t = useT()
|
||||
const [confirming, setConfirming] = useState<DiscardTarget | null>(null)
|
||||
const latest = useRef({ dirty, dropped: t('editor.findings.draft_dropped') })
|
||||
latest.current = { dirty, dropped: t('editor.findings.draft_dropped') }
|
||||
useBeforeUnload(dirty)
|
||||
useEffect(() => {
|
||||
guards.register('finding', (forced) => {
|
||||
guards.register(layer, (forced) => {
|
||||
const { dirty: held, dropped } = latest.current
|
||||
if (!held) return { allowed: true }
|
||||
if (forced) return { allowed: true, note: dropped }
|
||||
setConfirming('dialog')
|
||||
return { allowed: false }
|
||||
})
|
||||
return () => guards.register('finding', null)
|
||||
}, [guards])
|
||||
return () => guards.register(layer, null)
|
||||
}, [guards, layer])
|
||||
return {
|
||||
confirming,
|
||||
askToLeave: () => setConfirming('form'),
|
||||
@@ -44,11 +48,12 @@ export function useFormDraft<T extends object>(
|
||||
initial: T,
|
||||
guards: Guards,
|
||||
same: (a: T, b: T) => boolean,
|
||||
layer: LayerName = 'finding',
|
||||
) {
|
||||
const first = useRef(initial).current
|
||||
const [draft, setDraft] = useState(first)
|
||||
const dirty = !same(draft, first)
|
||||
const guard = useDirtyGuard(guards, dirty)
|
||||
const guard = useDirtyGuard(guards, dirty, layer)
|
||||
return {
|
||||
draft,
|
||||
dirty,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useLayoutEffect, useRef, type RefObject } from 'react'
|
||||
import type { 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'
|
||||
@@ -17,6 +17,8 @@ interface Props extends PanelHooks {
|
||||
onShowAll: () => void
|
||||
/** « Aller à » a citing finding or family: closes the panel, then moves. */
|
||||
navigate: (target: EditorTarget) => void
|
||||
/** « Modifier »: the reference dialog over the sheet, `opener` is where the focus returns. */
|
||||
onEdit: (id: string, opener: HTMLElement) => void
|
||||
}
|
||||
|
||||
const RING =
|
||||
@@ -134,35 +136,17 @@ function MissingRow({
|
||||
|
||||
type Panel = ReturnType<typeof useCitationsPanel>
|
||||
|
||||
/**
|
||||
* True once the panel unmounts (its list with it). It only unmounts after a close its leave check allowed,
|
||||
* which already said any refused draft (`note`). React runs a deleted parent's layout
|
||||
* cleanups before its children's, so a tile's edit view reads true when it drops then.
|
||||
*/
|
||||
function useLeaving() {
|
||||
const leaving = useRef(false)
|
||||
useLayoutEffect(() => {
|
||||
leaving.current = false
|
||||
return () => {
|
||||
leaving.current = true
|
||||
}
|
||||
}, [])
|
||||
return useCallback(() => leaving.current, [])
|
||||
}
|
||||
|
||||
/** One cited reference as a tile (« Modifier », « Retirer de ce constat »). */
|
||||
function EntryTile({
|
||||
entry,
|
||||
reference,
|
||||
panel,
|
||||
props,
|
||||
leaving,
|
||||
}: {
|
||||
entry: CitationEntry
|
||||
reference: Reference
|
||||
panel: Panel
|
||||
props: Props
|
||||
leaving: () => boolean
|
||||
}) {
|
||||
const { tiles, keys, citers, entries, remove } = panel
|
||||
const { readOnly, citedBy, navigate } = props
|
||||
@@ -176,17 +160,12 @@ function EntryTile({
|
||||
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, readOnly),
|
||||
edit: () => void tiles.startEdit(key),
|
||||
done: tiles.finish,
|
||||
toggle: () => tiles.toggle(key),
|
||||
edit: (opener) => props.onEdit(reference.id, opener),
|
||||
goTo: (target) => navigate(targetOfKey(target)),
|
||||
registerLeave: tiles.registerLeave,
|
||||
takeFocus: () => tiles.takeFocus(key),
|
||||
hostLeaving: leaving,
|
||||
}}
|
||||
/>
|
||||
)
|
||||
@@ -194,7 +173,6 @@ function EntryTile({
|
||||
|
||||
/** The cited references as tiles, the dangling ids as rows. */
|
||||
function Entries({ panel, props }: { panel: Panel; props: Props }) {
|
||||
const leaving = useLeaving()
|
||||
return (
|
||||
<ul
|
||||
ref={panel.list}
|
||||
@@ -209,7 +187,6 @@ function Entries({ panel, props }: { panel: Panel; props: Props }) {
|
||||
reference={entry.reference}
|
||||
panel={panel}
|
||||
props={props}
|
||||
leaving={leaving}
|
||||
/>
|
||||
) : (
|
||||
<MissingRow
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import { AnimatePresence, motion, useReducedMotion } from 'motion/react'
|
||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||
import ModalDialog from '@/components/ui/ModalDialog'
|
||||
import { isTextField } from '@/editor/focusRequest'
|
||||
import type { EditorTarget } from '@/editor/navigation'
|
||||
import type { Guards } from '@/editor/useEditorNavigation'
|
||||
import CitationsPanel from './CitationsPanel'
|
||||
|
||||
/** Sheet motion (board 25): enter decelerates, the shorter exit accelerates (P9). */
|
||||
@@ -14,13 +12,14 @@ export interface CitationsSheetProps {
|
||||
/** The finding whose citations the view shows; null while the sheet is closed. */
|
||||
citedBy: ElementKey | null
|
||||
readOnly: boolean
|
||||
guards: Guards
|
||||
/** A user close (✕, Escape, scrim): false when a tile in edit refused it. */
|
||||
/** A user close (✕, Escape, scrim). */
|
||||
onClose: () => boolean
|
||||
/** « Tout afficher dans l'onglet Références ». */
|
||||
onShowAll: () => void
|
||||
/** « Aller à » a citing finding or a reference. */
|
||||
navigate: (target: EditorTarget) => void
|
||||
/** « Modifier » on a tile: the reference dialog over the sheet. */
|
||||
onEdit: (id: string, opener: HTMLElement) => void
|
||||
/** « X références » of the dialog under the sheet, where the focus returns. */
|
||||
returnFocus: () => HTMLElement | null
|
||||
}
|
||||
@@ -38,8 +37,7 @@ function useSheetMotion() {
|
||||
/**
|
||||
* The citations of a finding as a modal side sheet at the right edge, over the finding
|
||||
* dialog (R2F-4): the host sits after the tab body in the tree, so it is shown after the
|
||||
* dialog and lies on top of it. Escape and the scrim close the sheet only. Interim until
|
||||
* the tiles stop editing inline: an Escape typed in a tile's field is the field's.
|
||||
* dialog and lies on top of it. Escape and the scrim close the sheet only.
|
||||
*/
|
||||
function SheetSurface(props: CitationsSheetProps & { citedBy: ElementKey }) {
|
||||
const { citedBy, onClose } = props
|
||||
@@ -50,7 +48,6 @@ function SheetSurface(props: CitationsSheetProps & { citedBy: ElementKey }) {
|
||||
layer
|
||||
onClose={close}
|
||||
returnFocus={props.returnFocus}
|
||||
ignoreEscape={isTextField}
|
||||
labelledBy="editor-citations-title"
|
||||
className="open:block"
|
||||
>
|
||||
@@ -73,10 +70,10 @@ function SheetSurface(props: CitationsSheetProps & { citedBy: ElementKey }) {
|
||||
<CitationsPanel
|
||||
readOnly={props.readOnly}
|
||||
citedBy={citedBy}
|
||||
guards={props.guards}
|
||||
onClose={onClose}
|
||||
onShowAll={props.onShowAll}
|
||||
navigate={props.navigate}
|
||||
onEdit={props.onEdit}
|
||||
/>
|
||||
</motion.div>
|
||||
</ModalDialog>
|
||||
|
||||
@@ -1,145 +0,0 @@
|
||||
import { useEffect, useState, type KeyboardEvent } from 'react'
|
||||
import type { ReferenceType } from '@faunosteo/core-wasm/types'
|
||||
import ActionButton from '@/components/editor/fields/ActionButton'
|
||||
import DraftField from '@/components/editor/fields/DraftField'
|
||||
import SelectField from '@/components/editor/fields/SelectField'
|
||||
import Icon from '@/components/ui/Icon'
|
||||
import { isBlank, nullable } from '@/editor/sheetDocument'
|
||||
import { useEditCommand } from '@/editor/useEditCommand'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { REFERENCE_TYPES } from './referenceTypes'
|
||||
|
||||
const EMPTY = { type: '', citation: '', url: '', doi: '' }
|
||||
const ID = 'tab-reference-new'
|
||||
|
||||
interface Props {
|
||||
/** Bumped by each « Ajouter une référence »: the citation takes the focus again. */
|
||||
focusSerial: number
|
||||
/** The reference was created in one modification, under this id. */
|
||||
onAdded: (id: string) => void
|
||||
/** « Annuler l'ajout »: the draft goes, nothing was written. */
|
||||
onCancel: () => void
|
||||
}
|
||||
|
||||
const isTextTarget = (target: EventTarget) =>
|
||||
target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement
|
||||
const isPristine = (form: typeof EMPTY) =>
|
||||
Object.values(form).every((v) => v === '')
|
||||
const isComposing = (event: KeyboardEvent) =>
|
||||
event.nativeEvent.isComposing || event.keyCode === 229
|
||||
|
||||
/**
|
||||
* The draft tile of « Ajouter une référence » (board 24 E): type « Choisir… » and citation
|
||||
* required, DOI and URL optional. Nothing reaches the document before « Ajouter la
|
||||
* référence », which inserts the reference as one modification.
|
||||
*/
|
||||
export default function NewReferenceTile({
|
||||
focusSerial,
|
||||
onAdded,
|
||||
onCancel,
|
||||
}: Props) {
|
||||
const t = useT()
|
||||
const edit = useEditCommand()
|
||||
const [form, setForm] = useState(EMPTY)
|
||||
const set = (patch: Partial<typeof EMPTY>) => setForm({ ...form, ...patch })
|
||||
useEffect(() => {
|
||||
document.getElementById(`${ID}-citation`)?.focus()
|
||||
}, [focusSerial])
|
||||
const options = [
|
||||
{ value: '', label: t('editor.field.choose') },
|
||||
...REFERENCE_TYPES.map((type) => ({
|
||||
value: type,
|
||||
label: t(`editor.reference.type.${type}`),
|
||||
})),
|
||||
]
|
||||
const create = () => {
|
||||
if (form.type === '' || isBlank(form.citation)) {
|
||||
edit.reject('form', 'editor.reference.required')
|
||||
return
|
||||
}
|
||||
let created = ''
|
||||
const added = edit.runNew('form', 'ref', (id) => {
|
||||
created = id
|
||||
return {
|
||||
op: 'insert',
|
||||
element: {
|
||||
kind: 'reference',
|
||||
value: {
|
||||
id,
|
||||
type: form.type as ReferenceType,
|
||||
citation: form.citation,
|
||||
url: nullable(form.url),
|
||||
doi: nullable(form.doi),
|
||||
},
|
||||
},
|
||||
}
|
||||
})
|
||||
if (added) onAdded(created)
|
||||
}
|
||||
// Escape cancels from anywhere in the tile; a text field with typed text keeps it.
|
||||
const escape = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'Escape' || event.defaultPrevented) return
|
||||
if (isComposing(event)) return
|
||||
if (isTextTarget(event.target) && !isPristine(form)) return
|
||||
event.preventDefault()
|
||||
onCancel()
|
||||
}
|
||||
return (
|
||||
<section
|
||||
aria-label={t('editor.reference.new')}
|
||||
onKeyDown={escape}
|
||||
className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)]"
|
||||
>
|
||||
<div className="flex items-center gap-3 p-3">
|
||||
<Icon name="chevron-down" size={18} />
|
||||
<h3 className="text-sm font-semibold">{t('editor.reference.new')}</h3>
|
||||
</div>
|
||||
<div className="space-y-3 border-t border-[var(--color-border)] p-3">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<SelectField
|
||||
id={`${ID}-type`}
|
||||
label={t('editor.reference.type')}
|
||||
value={form.type}
|
||||
options={options}
|
||||
onCommit={(type) => set({ type })}
|
||||
/>
|
||||
<DraftField
|
||||
id={`${ID}-doi`}
|
||||
label={t('editor.reference.doi')}
|
||||
value={form.doi}
|
||||
onChange={(doi) => set({ doi })}
|
||||
/>
|
||||
</div>
|
||||
<DraftField
|
||||
id={`${ID}-citation`}
|
||||
label={t('editor.reference.citation')}
|
||||
value={form.citation}
|
||||
onChange={(citation) => set({ citation })}
|
||||
multiline
|
||||
/>
|
||||
<DraftField
|
||||
id={`${ID}-url`}
|
||||
label={t('editor.reference.url')}
|
||||
value={form.url}
|
||||
onChange={(url) => set({ url })}
|
||||
/>
|
||||
{edit.fieldError('form') && (
|
||||
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
||||
{edit.fieldError('form')}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<ActionButton readOnly={false} variant="primary" onClick={create}>
|
||||
{t('editor.reference.add')}
|
||||
</ActionButton>
|
||||
<ActionButton readOnly={false} variant="secondary" onClick={onCancel}>
|
||||
{t('editor.references.add_cancel')}
|
||||
</ActionButton>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.references.add_help')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -14,6 +14,17 @@ export default function NoResult({
|
||||
onClear: () => void
|
||||
}) {
|
||||
const t = useT()
|
||||
// A filtered finding that cites nothing: no search to clear, the chip has the way out.
|
||||
if (query.trim() === '') {
|
||||
return (
|
||||
<p
|
||||
data-testid="editor-references-no-result"
|
||||
className="text-sm text-[var(--color-ink-muted)]"
|
||||
>
|
||||
{t('editor.references.panel_empty')}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div
|
||||
data-testid="editor-references-no-result"
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { useCallback, useEffect, useRef } from 'react'
|
||||
import type { Reference } from '@faunosteo/core-wasm/types'
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import { visibleElement } from '@/editor/focusRequest'
|
||||
import { useSheetDocument } from '@/editor/sheetDocument'
|
||||
import type { ReferenceLayer } from '@/editor/tabs'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { ADD_BUTTON_ID } from './addButton'
|
||||
import ReferenceForm from './ReferenceForm'
|
||||
|
||||
export interface ReferenceDialogProps {
|
||||
layer: ReferenceLayer
|
||||
readOnly: boolean
|
||||
}
|
||||
|
||||
type View = ReferenceLayer['view']
|
||||
|
||||
/** The reference the view edits, read from the current document; null once it is gone. */
|
||||
function editedIn(view: View, references: readonly Reference[] | undefined) {
|
||||
if (!view || !('edit' in view)) return null
|
||||
return references?.find((reference) => reference.id === view.edit) ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference the dialog edits vanished (a reload after a conflict, a Back onto a dead
|
||||
* entry): the layer closes by replace and says so (R2F-5). After this commit's effects,
|
||||
* as the finding dialog's rule: a form that registered a guard in them can still be asked.
|
||||
*/
|
||||
function useGoneRule(layer: ReferenceLayer) {
|
||||
const t = useT()
|
||||
const doc = useSheetDocument()
|
||||
const handled = useRef<string | null>(null)
|
||||
const { view } = layer
|
||||
useEffect(() => {
|
||||
if (!view) handled.current = null
|
||||
if (!doc || !view || !('edit' in view)) return
|
||||
const stamp = JSON.stringify(view)
|
||||
if (editedIn(view, doc.references) || handled.current === stamp) return
|
||||
handled.current = stamp
|
||||
queueMicrotask(() => layer.replace(null, t('editor.references.gone')))
|
||||
}, [view, doc, layer, t])
|
||||
}
|
||||
|
||||
/** Where a closed dialog returns the focus: the tile's header, or the add button. */
|
||||
function useReturnTarget(layer: ReferenceLayer) {
|
||||
const last = useRef(layer.view)
|
||||
if (layer.view) last.current = layer.view
|
||||
const { opener } = layer
|
||||
return useCallback((): HTMLElement | null => {
|
||||
const shown = last.current
|
||||
if (!shown) return null
|
||||
if ('create' in shown) return document.getElementById(ADD_BUTTON_ID)
|
||||
const wanted = JSON.stringify({ kind: 'reference', id: shown.edit })
|
||||
return (
|
||||
opener() ??
|
||||
visibleElement('[data-tile-header]', (element) => {
|
||||
return element.dataset.focusKey === wanted
|
||||
})
|
||||
)
|
||||
}, [opener])
|
||||
}
|
||||
|
||||
/** What the layer shows: a creation, or the reference it edits (null once it is gone). */
|
||||
function useShownReference(layer: ReferenceLayer) {
|
||||
const t = useT()
|
||||
const doc = useSheetDocument()
|
||||
const creating = !!layer.view && 'create' in layer.view
|
||||
const edited = editedIn(layer.view, doc?.references)
|
||||
const title = creating
|
||||
? 'editor.reference.new'
|
||||
: 'editor.references.edit_title'
|
||||
return { creating, edited, title: t(title), open: creating || !!edited }
|
||||
}
|
||||
|
||||
/** What a save does: a creation is announced, then handed over; an edit closes the layer. */
|
||||
function useOnSaved(layer: ReferenceLayer, creating: boolean) {
|
||||
const t = useT()
|
||||
return (id: string, citation: string) => {
|
||||
if (!creating) return void layer.close(true)
|
||||
layer.announce(t('editor.references.added').replace('{citation}', citation))
|
||||
layer.created(id)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference dialog (R2F-5): one `Dialog` over the References tab or the citations
|
||||
* sheet, a form for a reference's type, DOI, citation and URL, or for a new one. The view
|
||||
* layer of the browser history drives it; it is no part of a kept place, so it is never a
|
||||
* native modal inside a hidden one.
|
||||
*/
|
||||
export default function ReferenceDialog({
|
||||
layer,
|
||||
readOnly,
|
||||
}: ReferenceDialogProps) {
|
||||
const shown = useShownReference(layer)
|
||||
const returnFocus = useReturnTarget(layer)
|
||||
const onSaved = useOnSaved(layer, shown.creating)
|
||||
useGoneRule(layer)
|
||||
return (
|
||||
<Dialog
|
||||
open={shown.open}
|
||||
layer
|
||||
size="lg"
|
||||
title={shown.title}
|
||||
returnFocus={returnFocus}
|
||||
onClose={() => (layer.close() ? undefined : 'kept')}
|
||||
>
|
||||
<ReferenceForm
|
||||
key={shown.edited?.id ?? 'new'}
|
||||
reference={shown.edited}
|
||||
readOnly={readOnly}
|
||||
guards={layer.guards}
|
||||
onSaved={onSaved}
|
||||
onClose={(forced) => layer.close(forced)}
|
||||
/>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
import type { Reference, ReferenceType } from '@faunosteo/core-wasm/types'
|
||||
import DraftField from '@/components/editor/fields/DraftField'
|
||||
import SelectField from '@/components/editor/fields/SelectField'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { REFERENCE_TYPES } from './referenceTypes'
|
||||
import {
|
||||
useReferenceEdit,
|
||||
type EditHooks,
|
||||
type Field,
|
||||
} from './useReferenceEdit'
|
||||
|
||||
interface Props {
|
||||
reference: Reference
|
||||
/** DOM id prefix of the tile (host, position and id): the fields' ids derive from it. */
|
||||
base: string
|
||||
/** The tile's leave guard (registered while mounted), focus ticket and dropped-draft slot. */
|
||||
hooks: EditHooks
|
||||
}
|
||||
|
||||
/** The edit view of one reference (board 24 D): type, DOI, citation and URL. */
|
||||
export default function ReferenceEditor(props: Props) {
|
||||
const { reference, base } = props
|
||||
const t = useT()
|
||||
const { edit, drafts, setDraft, commitField, setType } = useReferenceEdit(
|
||||
reference,
|
||||
base,
|
||||
props.hooks,
|
||||
)
|
||||
const text = (field: Field, label: string, multiline = false) => (
|
||||
<DraftField
|
||||
id={`${base}-${field}`}
|
||||
label={label}
|
||||
value={drafts[field]}
|
||||
onChange={(value) => setDraft(field, value)}
|
||||
onBlur={() => commitField(field)}
|
||||
multiline={multiline}
|
||||
error={edit.fieldError(field)}
|
||||
/>
|
||||
)
|
||||
const options = REFERENCE_TYPES.map((type) => ({
|
||||
value: type,
|
||||
label: t(`editor.reference.type.${type}`),
|
||||
}))
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<SelectField
|
||||
id={`${base}-type`}
|
||||
label={t('editor.reference.type')}
|
||||
value={reference.type}
|
||||
options={options}
|
||||
onCommit={(type) => setType(type as ReferenceType)}
|
||||
error={edit.fieldError('type')}
|
||||
/>
|
||||
{text('doi', t('editor.reference.doi'))}
|
||||
</div>
|
||||
{text('citation', t('editor.reference.citation'), true)}
|
||||
{text('url', t('editor.reference.url'))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import { useRef } from 'react'
|
||||
import type {
|
||||
EditCommand,
|
||||
Reference,
|
||||
ReferenceType,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
import DraftField from '@/components/editor/fields/DraftField'
|
||||
import SelectField from '@/components/editor/fields/SelectField'
|
||||
import { FormActions } from '@/components/editor/findings/DiscardConfirm'
|
||||
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
|
||||
import { useFormDraft } from '@/components/editor/findings/useDirtyGuard'
|
||||
import { webHref } from '@/editor/references/safeLink'
|
||||
import { isBlank, nullable } from '@/editor/sheetDocument'
|
||||
import { useEditCommand } from '@/editor/useEditCommand'
|
||||
import type { Guards } from '@/editor/useEditorNavigation'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { REFERENCE_TYPES } from './referenceTypes'
|
||||
|
||||
/** What the form edits, as plain strings: nothing is written before « Enregistrer ». */
|
||||
interface Draft {
|
||||
type: string
|
||||
citation: string
|
||||
doi: string
|
||||
url: string
|
||||
}
|
||||
|
||||
const EMPTY: Draft = { type: '', citation: '', doi: '', url: '' }
|
||||
|
||||
const draftOf = (reference: Reference): Draft => ({
|
||||
type: reference.type,
|
||||
citation: reference.citation,
|
||||
doi: reference.doi ?? '',
|
||||
url: reference.url ?? '',
|
||||
})
|
||||
|
||||
/** The draft as the document would hold it: a blank optional field is absent. */
|
||||
const normalized = (draft: Draft): Draft => ({
|
||||
...draft,
|
||||
doi: nullable(draft.doi) ?? '',
|
||||
url: nullable(draft.url) ?? '',
|
||||
})
|
||||
|
||||
const sameDraft = (a: Draft, b: Draft) =>
|
||||
JSON.stringify(normalized(a)) === JSON.stringify(normalized(b))
|
||||
|
||||
type Field = 'type' | 'citation' | 'url'
|
||||
|
||||
/** The first field the core would refuse, with the words for it; null when none. */
|
||||
function refusalOf(
|
||||
draft: Draft,
|
||||
creating: boolean,
|
||||
): { field: Field; key: string } | null {
|
||||
const required = 'editor.field.required'
|
||||
if (creating && draft.type === '') return { field: 'type', key: required }
|
||||
if (isBlank(draft.citation)) return { field: 'citation', key: required }
|
||||
const url = nullable(draft.url)
|
||||
if (url !== null && webHref(url) === null) {
|
||||
return { field: 'url', key: 'editor.reference.url_invalid' }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** The reference the draft makes under `id`. */
|
||||
function valueOf(draft: Draft, id: string): Reference {
|
||||
const now = normalized(draft)
|
||||
return {
|
||||
id,
|
||||
type: now.type as ReferenceType,
|
||||
citation: now.citation,
|
||||
doi: nullable(now.doi),
|
||||
url: nullable(now.url),
|
||||
}
|
||||
}
|
||||
|
||||
export interface ReferenceFormProps {
|
||||
/** The reference edited; null for a creation. */
|
||||
reference: Reference | null
|
||||
readOnly: boolean
|
||||
guards: Guards
|
||||
/** One command was written; `id` and `citation` are the reference's. */
|
||||
onSaved: (id: string, citation: string) => void
|
||||
/** Nothing was written (pristine save, « Annuler », « Abandonner »); forced drops a draft. */
|
||||
onClose: (forced: boolean) => void
|
||||
}
|
||||
|
||||
type Form = ReturnType<typeof useFormDraft<Draft>>
|
||||
|
||||
/**
|
||||
* The one command of a save: an `update` of the reference, or an `insert` under a new id.
|
||||
* The dialog closes after a save: a second submit while it plays its exit writes nothing.
|
||||
*/
|
||||
function useWrite(reference: Reference | null, draft: Draft) {
|
||||
const edit = useEditCommand()
|
||||
const saved = useRef(false)
|
||||
const run = (): string | null => {
|
||||
if (reference) {
|
||||
const element = { kind: 'reference', value: valueOf(draft, reference.id) }
|
||||
const key = { kind: 'reference', id: reference.id }
|
||||
const command = { op: 'update', key, element } as EditCommand
|
||||
return edit.run('form', command) ? reference.id : null
|
||||
}
|
||||
let id = ''
|
||||
const added = edit.runNew('form', 'ref', (fresh) => {
|
||||
id = fresh
|
||||
const element = { kind: 'reference', value: valueOf(draft, fresh) }
|
||||
return { op: 'insert', element } as EditCommand
|
||||
})
|
||||
return added ? id : null
|
||||
}
|
||||
const write = (): string | null => {
|
||||
const id = saved.current ? null : run()
|
||||
saved.current = saved.current || id !== null
|
||||
return id
|
||||
}
|
||||
return { edit, write }
|
||||
}
|
||||
|
||||
/** The save: refused on its field, nothing written when unchanged, else one command. */
|
||||
function useReferenceSave(props: ReferenceFormProps, form: Form) {
|
||||
const { edit, write } = useWrite(props.reference, form.draft)
|
||||
const save = () => {
|
||||
const refusal = refusalOf(form.draft, props.reference === null)
|
||||
if (refusal) {
|
||||
edit.reject(refusal.field, refusal.key)
|
||||
document.getElementById(`reference-form-${refusal.field}`)?.focus()
|
||||
return
|
||||
}
|
||||
if (!form.dirty) return props.onClose(false)
|
||||
const id = write()
|
||||
if (id !== null) props.onSaved(id, form.draft.citation)
|
||||
}
|
||||
return { save, edit }
|
||||
}
|
||||
|
||||
/** The form's state: the local draft, its guard and its save. */
|
||||
function useReferenceForm(props: ReferenceFormProps) {
|
||||
const first = props.reference ? draftOf(props.reference) : EMPTY
|
||||
const form = useFormDraft(first, props.guards, sameDraft, 'reference')
|
||||
return { ...form, ...useReferenceSave(props, form) }
|
||||
}
|
||||
|
||||
type ReferenceFormState = ReturnType<typeof useReferenceForm>
|
||||
|
||||
/** One of the three text fields of the form, a draft field with its own refusal. */
|
||||
function Text(props: {
|
||||
form: ReferenceFormState
|
||||
field: 'doi' | 'citation' | 'url'
|
||||
readOnly: boolean
|
||||
multiline?: boolean
|
||||
}) {
|
||||
const t = useT()
|
||||
const { form, field } = props
|
||||
return (
|
||||
<DraftField
|
||||
id={`reference-form-${field}`}
|
||||
label={t(`editor.reference.${field}`)}
|
||||
value={form.draft[field]}
|
||||
onChange={(value) => form.set({ [field]: value })}
|
||||
readOnly={props.readOnly}
|
||||
multiline={props.multiline}
|
||||
error={form.edit.fieldError(field)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** The type, then the three texts, as draft fields. */
|
||||
function FormFields({
|
||||
form,
|
||||
readOnly,
|
||||
}: {
|
||||
form: ReferenceFormState
|
||||
readOnly: boolean
|
||||
}) {
|
||||
const t = useT()
|
||||
const options = [
|
||||
{ value: '', label: t('editor.field.choose') },
|
||||
...REFERENCE_TYPES.map((type) => ({
|
||||
value: type,
|
||||
label: t(`editor.reference.type.${type}`),
|
||||
})),
|
||||
]
|
||||
return (
|
||||
<>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<SelectField
|
||||
id="reference-form-type"
|
||||
label={t('editor.reference.type')}
|
||||
value={form.draft.type}
|
||||
options={options}
|
||||
onCommit={(type) => form.set({ type })}
|
||||
readOnly={readOnly}
|
||||
error={form.edit.fieldError('type')}
|
||||
/>
|
||||
<Text form={form} field="doi" readOnly={readOnly} />
|
||||
</div>
|
||||
<Text form={form} field="citation" readOnly={readOnly} multiline />
|
||||
<Text form={form} field="url" readOnly={readOnly} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A reference edited or created in the reference dialog (R2F-5): a local draft, one
|
||||
* command on « Enregistrer » (none when nothing changed), nothing on « Annuler », a close
|
||||
* or a move. When the editor turns read-only the draft stays, its fields read-only, and
|
||||
* only « Abandonner » is left.
|
||||
*/
|
||||
export default function ReferenceForm(props: ReferenceFormProps) {
|
||||
const t = useT()
|
||||
const form = useReferenceForm(props)
|
||||
const { guard } = form
|
||||
const creating = props.reference === null
|
||||
return (
|
||||
<form
|
||||
data-draft-form
|
||||
className="space-y-3"
|
||||
noValidate
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
form.save()
|
||||
}}
|
||||
>
|
||||
{props.readOnly && <ReadOnlyNotice />}
|
||||
<FormFields form={form} readOnly={props.readOnly} />
|
||||
{form.edit.fieldError('form') && (
|
||||
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
||||
{form.edit.fieldError('form')}
|
||||
</p>
|
||||
)}
|
||||
<FormActions
|
||||
confirming={guard.confirming}
|
||||
readOnly={props.readOnly}
|
||||
submitLabel={t(
|
||||
creating ? 'editor.reference.add' : 'editor.findings.save',
|
||||
)}
|
||||
onCancel={() =>
|
||||
form.dirty && !props.readOnly
|
||||
? guard.askToLeave()
|
||||
: props.onClose(props.readOnly)
|
||||
}
|
||||
onKeepTyping={guard.keepTyping}
|
||||
onDiscard={() => props.onClose(true)}
|
||||
/>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -1,43 +1,23 @@
|
||||
import {
|
||||
useCallback,
|
||||
useContext,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type RefObject,
|
||||
} from 'react'
|
||||
import type { ElementKey, Reference } from '@faunosteo/core-wasm/types'
|
||||
import ActionButton from '@/components/editor/fields/ActionButton'
|
||||
import Icon from '@/components/ui/Icon'
|
||||
import { AnnounceContext } from '@/editor/focusRequest'
|
||||
import { usePlural } from '@/editor/plural'
|
||||
import type { CiterItem } from '@/editor/references/citations'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import CitersList from './CitersList'
|
||||
import ReferenceEditor from './ReferenceEditor'
|
||||
import ReferenceFacts from './ReferenceFacts'
|
||||
import type { ReferenceHost } from './referenceTypes'
|
||||
import { useDroppedText, type Field, type LeaveGuard } from './useReferenceEdit'
|
||||
|
||||
/** What a tile asks of the library that owns its state. */
|
||||
export interface TileHandlers {
|
||||
toggle: () => void
|
||||
edit: () => void
|
||||
/** Leaves the edit view; false (the view stays) when a field refuses. */
|
||||
done: () => boolean
|
||||
/** « Modifier »: opens the reference dialog; `opener` is where the focus returns. */
|
||||
edit: (opener: HTMLElement) => 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
|
||||
/** True once after « Modifier »: the edit view then focuses its Citation field. */
|
||||
takeFocus: () => boolean
|
||||
/**
|
||||
* True while the host itself unmounts: the leave that closed it already said the dropped
|
||||
* drafts (the citations panel's forced close), so the tile does not say them again.
|
||||
*/
|
||||
hostLeaving?: () => boolean
|
||||
}
|
||||
|
||||
/** What a tile of the citations panel adds: the finding it belongs to and « Retirer ». */
|
||||
@@ -56,7 +36,6 @@ export interface TileProps {
|
||||
count: number
|
||||
citers: readonly CiterItem[]
|
||||
open: boolean
|
||||
editing: boolean
|
||||
readOnly: boolean
|
||||
/** ↑ / ↓ only while neither the search nor a sort narrows or reorders the list. */
|
||||
movable: boolean
|
||||
@@ -82,58 +61,34 @@ const BUTTON_RING =
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
|
||||
|
||||
/** The disclosure button: citation (two lines when closed), type and how often it is cited. */
|
||||
function TileHeader({
|
||||
base,
|
||||
props,
|
||||
headerRef,
|
||||
onToggle,
|
||||
}: {
|
||||
base: string
|
||||
props: TileProps
|
||||
headerRef: RefObject<HTMLButtonElement | null>
|
||||
onToggle: () => void
|
||||
}) {
|
||||
function TileHeader({ base, props }: { base: string; props: TileProps }) {
|
||||
const t = useT()
|
||||
const plural = usePlural()
|
||||
const { reference, open, editing, citers } = props
|
||||
const { reference, open, citers } = props
|
||||
const cited = citers.length
|
||||
const key = JSON.stringify({ kind: 'reference', id: reference.id })
|
||||
return (
|
||||
<button
|
||||
ref={headerRef}
|
||||
type="button"
|
||||
id={`${base}-header`}
|
||||
data-focus-key={key}
|
||||
data-tile-header
|
||||
aria-expanded={open || editing}
|
||||
aria-expanded={open}
|
||||
aria-controls={`${base}-body`}
|
||||
aria-describedby={props.outsideSearch ? `${base}-outside` : undefined}
|
||||
onClick={onToggle}
|
||||
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 ${META_COLUMN[props.host]} ${BUTTON_RING}`}
|
||||
>
|
||||
<Icon
|
||||
name={open || editing ? 'chevron-down' : 'chevron-right'}
|
||||
size={18}
|
||||
/>
|
||||
<Icon name={open ? 'chevron-down' : 'chevron-right'} size={18} />
|
||||
<span
|
||||
className={`min-w-0 break-words text-sm ${open || editing ? '' : 'line-clamp-2'} ${editing ? 'font-semibold' : ''}`}
|
||||
className={`min-w-0 break-words text-sm ${open ? '' : 'line-clamp-2'}`}
|
||||
>
|
||||
{editing ? (
|
||||
// In edit this button ends the edit: its name says so, the title stays visible (M7).
|
||||
<>
|
||||
<span className="sr-only">{t('editor.references.done')}. </span>
|
||||
{t('editor.references.edit_title')}
|
||||
</>
|
||||
) : (
|
||||
reference.citation
|
||||
)}
|
||||
{reference.citation}
|
||||
</span>
|
||||
<span className="col-start-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-[var(--color-ink-muted)] sm:col-start-3 sm:row-start-1 sm:flex-col sm:items-end">
|
||||
{!editing && (
|
||||
<span className="rounded-md bg-[var(--color-surface-strong)] px-2 py-0.5 font-medium text-[var(--color-ink)]">
|
||||
{t(`editor.reference.type.${reference.type}`)}
|
||||
</span>
|
||||
)}
|
||||
<span className="rounded-md bg-[var(--color-surface-strong)] px-2 py-0.5 font-medium text-[var(--color-ink)]">
|
||||
{t(`editor.reference.type.${reference.type}`)}
|
||||
</span>
|
||||
<span>
|
||||
{cited === 0
|
||||
? t('editor.references.uncited')
|
||||
@@ -159,7 +114,7 @@ function PanelActions({
|
||||
readOnly={false}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={props.on.edit}
|
||||
onClick={(event) => props.on.edit(event.currentTarget)}
|
||||
>
|
||||
{t('editor.references.edit')}
|
||||
</ActionButton>
|
||||
@@ -188,7 +143,7 @@ function TileActions({ props }: { props: TileProps }) {
|
||||
readOnly={false}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={on.edit}
|
||||
onClick={(event) => on.edit(event.currentTarget)}
|
||||
>
|
||||
{t('editor.references.edit')}
|
||||
</ActionButton>
|
||||
@@ -236,96 +191,21 @@ function TileActions({ props }: { props: TileProps }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The refused drafts an edit view was unmounted with (a read-only flip, an undo that removes
|
||||
* the reference), as the tile keeps them: shown by the tile until its next action. The drop
|
||||
* is said once in the polite live region from `onDrop` itself, not from an effect: an undo
|
||||
* unmounts the tile with its view, and a dying tile runs no effect (V1). An edit view that
|
||||
* ends on purpose (« Terminer », another tile's « Modifier ») ends the note; a flip does not.
|
||||
*/
|
||||
function useDroppedDrafts(
|
||||
editing: boolean,
|
||||
readOnly: boolean,
|
||||
hostLeaving?: () => boolean,
|
||||
) {
|
||||
const droppedText = useDroppedText()
|
||||
const announce = useContext(AnnounceContext)
|
||||
const [dropped, setDropped] = useState<readonly Field[] | null>(null)
|
||||
const [wasEditing, setWasEditing] = useState(editing)
|
||||
if (wasEditing !== editing) {
|
||||
setWasEditing(editing)
|
||||
if (wasEditing && !readOnly) setDropped(null)
|
||||
}
|
||||
// `onDrop` must stay stable (the view's cleanup depends on it): it reads the latest
|
||||
// render's words and host through this ref.
|
||||
const latest = useRef({ droppedText, announce, hostLeaving })
|
||||
useLayoutEffect(() => {
|
||||
latest.current = { droppedText, announce, hostLeaving }
|
||||
})
|
||||
const onDrop = useCallback((fields: readonly Field[]) => {
|
||||
setDropped(fields)
|
||||
const now = latest.current
|
||||
if (!now.hostLeaving?.()) now.announce(now.droppedText(fields))
|
||||
}, [])
|
||||
return { dropped, setDropped, onDrop }
|
||||
}
|
||||
|
||||
/** The tile's own actions: « Terminer » refocuses the header, a toggle ends the note. */
|
||||
function useTileActions(
|
||||
props: TileProps,
|
||||
headerRef: RefObject<HTMLButtonElement | null>,
|
||||
) {
|
||||
const { on, editing, readOnly } = props
|
||||
const { dropped, setDropped, onDrop } = useDroppedDrafts(
|
||||
editing,
|
||||
readOnly,
|
||||
on.hostLeaving,
|
||||
)
|
||||
return {
|
||||
dropped,
|
||||
onDrop,
|
||||
done: () => {
|
||||
if (on.done()) headerRef.current?.focus()
|
||||
},
|
||||
toggle: () => {
|
||||
setDropped(null)
|
||||
on.toggle()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** « Saisie non appliquée : … »: plain text, the live region says it once elsewhere. */
|
||||
function DroppedNote({ fields }: { fields: readonly Field[] }) {
|
||||
const droppedText = useDroppedText()
|
||||
return (
|
||||
<p className="flex items-start gap-2 rounded-md bg-amber-50 p-2 text-sm text-amber-800">
|
||||
<Icon name="alert" size={16} className="mt-0.5 shrink-0" />
|
||||
{droppedText(fields)}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* One reference as a collapsible tile (boards 23, 24): closed, open (facts, citers,
|
||||
* actions), or in edit (fields, citers, « Terminer »). Read-only: the facts and the
|
||||
* citers' « Aller à » only, no control that changes the draft.
|
||||
* One reference as a collapsible tile (boards 23, 24): closed, or open (facts, citers,
|
||||
* actions). « Modifier » opens the reference dialog; no field is edited in the tile
|
||||
* (R2F-5). Read-only: the facts and the citers' « Aller à » only, no control that changes
|
||||
* the document.
|
||||
*/
|
||||
export default function ReferenceTile(props: TileProps) {
|
||||
const { host, reference, position, open, editing, on } = props
|
||||
const { host, reference, position, open, on } = props
|
||||
const t = useT()
|
||||
const base = tileBase(host, position, reference)
|
||||
const headerRef = useRef<HTMLButtonElement>(null)
|
||||
const { dropped, onDrop, done, toggle } = useTileActions(props, headerRef)
|
||||
return (
|
||||
<li
|
||||
data-reference-tile
|
||||
className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)]"
|
||||
>
|
||||
<TileHeader
|
||||
base={base}
|
||||
props={props}
|
||||
headerRef={headerRef}
|
||||
onToggle={toggle}
|
||||
/>
|
||||
<TileHeader base={base} props={props} />
|
||||
{props.outsideSearch && (
|
||||
<p
|
||||
id={`${base}-outside`}
|
||||
@@ -334,45 +214,18 @@ export default function ReferenceTile(props: TileProps) {
|
||||
{t('editor.references.outside_search')}
|
||||
</p>
|
||||
)}
|
||||
{(open || editing) && (
|
||||
{open && (
|
||||
<div
|
||||
id={`${base}-body`}
|
||||
className="space-y-3 border-t border-[var(--color-border)] p-3"
|
||||
>
|
||||
{editing ? (
|
||||
<ReferenceEditor
|
||||
reference={reference}
|
||||
base={base}
|
||||
hooks={{
|
||||
registerLeave: on.registerLeave,
|
||||
takeFocus: on.takeFocus,
|
||||
onDrop,
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<ReferenceFacts reference={reference} />
|
||||
)}
|
||||
<ReferenceFacts reference={reference} />
|
||||
<CitersList
|
||||
citers={props.citers}
|
||||
current={props.panel?.current}
|
||||
onGoTo={on.goTo}
|
||||
/>
|
||||
{dropped && <DroppedNote fields={dropped} />}
|
||||
{editing ? (
|
||||
<ActionButton
|
||||
readOnly={false}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
// A press keeps the focus in its field: a refusal shown on blur would move
|
||||
// the button before the click lands. The click applies every field itself.
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onClick={done}
|
||||
>
|
||||
{t('editor.references.done')}
|
||||
</ActionButton>
|
||||
) : (
|
||||
<TileActions props={props} />
|
||||
)}
|
||||
<TileActions props={props} />
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
|
||||
@@ -19,7 +19,7 @@ interface Props {
|
||||
readOnly: boolean
|
||||
movable: boolean
|
||||
navigate: (target: EditorTarget) => void
|
||||
onEdit: (position: number) => void
|
||||
onEdit: (position: number, opener: HTMLElement) => void
|
||||
onDelete: (reference: Reference) => void
|
||||
}
|
||||
|
||||
@@ -49,19 +49,15 @@ export default function ReferenceTiles(props: Props) {
|
||||
count={all.length}
|
||||
citers={citers.get(reference.id) ?? []}
|
||||
open={tiles.openKeys.has(key)}
|
||||
editing={!props.readOnly && tiles.editingKey === key}
|
||||
readOnly={props.readOnly}
|
||||
movable={props.movable}
|
||||
outsideSearch={!referenceMatches(reference, props.query)}
|
||||
on={{
|
||||
toggle: () => tiles.toggle(key, props.readOnly),
|
||||
edit: () => props.onEdit(position),
|
||||
done: tiles.finish,
|
||||
toggle: () => tiles.toggle(key),
|
||||
edit: (opener) => props.onEdit(position, opener),
|
||||
remove: () => props.onDelete(reference),
|
||||
move: (to) => move(reference, to),
|
||||
goTo: (target) => navigate(targetOfKey(target)),
|
||||
registerLeave: tiles.registerLeave,
|
||||
takeFocus: () => tiles.takeFocus(key),
|
||||
}}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -20,7 +20,51 @@ interface Props {
|
||||
total: number
|
||||
/** « Ajouter une référence »: absent while the editor is read-only. */
|
||||
canAdd: boolean
|
||||
onAdd: () => void
|
||||
onAdd: (opener: HTMLElement) => void
|
||||
/** The finding the list is filtered by (R2F-6), with the two ways out of the filter. */
|
||||
filter: FilterChip | null
|
||||
}
|
||||
|
||||
/** The finding filter: its name, « × » and « Revenir au constat ». */
|
||||
export interface FilterChip {
|
||||
name: string
|
||||
onRemove: () => void
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
const BUTTON =
|
||||
'inline-flex min-h-11 items-center justify-center rounded-md px-2 ' +
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
|
||||
|
||||
/** « Références du constat : X » with « × », and the way back to the finding. */
|
||||
function FilterBar({ filter }: { filter: FilterChip }) {
|
||||
const t = useT()
|
||||
const fill = (key: string) => t(key).replace('{name}', () => filter.name)
|
||||
return (
|
||||
<div
|
||||
data-testid="editor-references-filter"
|
||||
className="flex flex-wrap items-center gap-x-3 gap-y-1"
|
||||
>
|
||||
<span className="inline-flex items-center gap-1 rounded-full border border-[var(--color-border)] bg-[var(--color-surface-strong)] pl-3 text-sm">
|
||||
{fill('editor.references.filter_chip')}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={fill('editor.references.filter_remove')}
|
||||
onClick={filter.onRemove}
|
||||
className={`${BUTTON} rounded-full`}
|
||||
>
|
||||
<Icon name="close" size={14} />
|
||||
</button>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={filter.onBack}
|
||||
className={`${BUTTON} text-sm text-[var(--color-accent-strong)] underline`}
|
||||
>
|
||||
{t('editor.references.filter_back')}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The count line: « {n} références » or « {n} références sur {total} ». */
|
||||
@@ -88,6 +132,7 @@ export default function ReferenceToolbar(props: Props) {
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
{props.filter && <FilterBar filter={props.filter} />}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<CountLine shown={props.shown} total={props.total} />
|
||||
<ActionButton
|
||||
@@ -95,7 +140,7 @@ export default function ReferenceToolbar(props: Props) {
|
||||
readOnly={!props.canAdd}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={props.onAdd}
|
||||
onClick={(event) => props.onAdd(event.currentTarget)}
|
||||
>
|
||||
{t('editor.references.add')}
|
||||
</ActionButton>
|
||||
|
||||
@@ -6,15 +6,11 @@ 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 { Guards, LeaveAnswer } from '@/editor/useEditorNavigation'
|
||||
import { useDroppedText } from './useReferenceEdit'
|
||||
import { tileKeys, useTileState } from './useTileState'
|
||||
|
||||
export interface PanelHooks {
|
||||
readOnly: boolean
|
||||
citedBy: ElementKey
|
||||
/** The layers' guards: the tile in edit registers its own for the sheet. */
|
||||
guards: Guards
|
||||
}
|
||||
|
||||
/** The finding read from the current document; null once the document lacks it. */
|
||||
@@ -27,29 +23,6 @@ function useCitedFinding(citedBy: ElementKey) {
|
||||
return { doc, item }
|
||||
}
|
||||
|
||||
/**
|
||||
* P22'': a move that leaves the sheet asks the tile in edit first (a refusal cancels the
|
||||
* move); a forced one (the finding vanished) drops a refused draft and says so. Interim
|
||||
* until the reference dialog replaces the inline tile edit.
|
||||
*/
|
||||
function useLeaveCheck(tiles: ReturnType<typeof useTileState>, guards: Guards) {
|
||||
const droppedText = useDroppedText()
|
||||
const check = (forced: boolean): LeaveAnswer => {
|
||||
const refused = tiles.leave()
|
||||
if (refused.length === 0) return { allowed: true }
|
||||
if (!forced) return { allowed: false }
|
||||
return { allowed: true, note: droppedText(refused) }
|
||||
}
|
||||
// Registered once and kept: the layers' effects of one commit run cleanups first, so a
|
||||
// guard re-registered on every render would be absent when another layer asks.
|
||||
const latest = useRef(check)
|
||||
latest.current = check
|
||||
useEffect(() => {
|
||||
guards.register('citations', (forced) => latest.current(forced))
|
||||
return () => guards.register('citations', null)
|
||||
}, [guards])
|
||||
}
|
||||
|
||||
/** The row the focus is in: its element, its index in the list and the list's length. */
|
||||
interface Held {
|
||||
element: Element
|
||||
@@ -135,12 +108,11 @@ export function useCitationsPanel(hooks: PanelHooks) {
|
||||
const edit = useEditCommand()
|
||||
const tiles = useTileState(doc ? keys : null)
|
||||
const focus = useFocusRescue()
|
||||
useLeaveCheck(tiles, hooks.guards)
|
||||
// « 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
|
||||
if (!item) 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
|
||||
|
||||
@@ -1,178 +0,0 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import type { Reference, ReferenceType } from '@faunosteo/core-wasm/types'
|
||||
import { isBlank, nullable } from '@/editor/sheetDocument'
|
||||
import { useEditCommand } from '@/editor/useEditCommand'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** The text fields of the edit view, in the order the leave guard tries them. */
|
||||
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: every pending field is tried; the fields that refused
|
||||
* (their drafts stay, the first one is focused), empty when all were applied.
|
||||
*/
|
||||
export type LeaveGuard = () => Field[]
|
||||
|
||||
/** What the tile hands its edit view (the library owns the state). */
|
||||
export interface EditHooks {
|
||||
registerLeave: (guard: LeaveGuard | null) => void
|
||||
/** True once per « Modifier »: the mount focuses Citation, a remount never does. */
|
||||
takeFocus: () => boolean
|
||||
/** The view unmounted with these refused drafts; stable (it runs from a cleanup). */
|
||||
onDrop: (fields: readonly Field[]) => void
|
||||
}
|
||||
|
||||
const committedOf = (reference: Reference): Drafts => ({
|
||||
citation: reference.citation,
|
||||
doi: reference.doi ?? '',
|
||||
url: reference.url ?? '',
|
||||
})
|
||||
|
||||
/** The document value a draft gives (a blank optional field is null, so ''). */
|
||||
const normalized = (field: Field, draft: string) =>
|
||||
field === 'citation' ? draft : (nullable(draft) ?? '')
|
||||
|
||||
const patched = (reference: Reference, field: Field, draft: string) =>
|
||||
field === 'citation'
|
||||
? { ...reference, citation: draft }
|
||||
: { ...reference, [field]: nullable(draft) }
|
||||
|
||||
/** One draft per text field; a new committed value (undo, reload) replaces its draft. */
|
||||
function useDrafts(reference: Reference) {
|
||||
const committed = committedOf(reference)
|
||||
const [drafts, setDrafts] = useState(committed)
|
||||
const [seen, setSeen] = useState(committed)
|
||||
const changed = FIELDS.filter((field) => seen[field] !== committed[field])
|
||||
if (changed.length > 0) {
|
||||
setSeen(committed)
|
||||
const fresh = changed.map((field) => [field, committed[field]])
|
||||
setDrafts({ ...drafts, ...Object.fromEntries(fresh) })
|
||||
}
|
||||
const setDraft = (field: Field, value: string) =>
|
||||
setDrafts({ ...drafts, [field]: value })
|
||||
return [drafts, setDraft] as const
|
||||
}
|
||||
|
||||
/** The fields whose draft differs from `reference`, in `FIELDS` order. */
|
||||
const pendingFields = (reference: Reference, drafts: Drafts) =>
|
||||
FIELDS.filter(
|
||||
(field) =>
|
||||
normalized(field, drafts[field]) !== committedOf(reference)[field],
|
||||
)
|
||||
|
||||
/**
|
||||
* The reference as the document holds it now, and the drafts as typed. A blur right after
|
||||
* an apply (« Terminer » focusing the header, a close) runs before the next render, so
|
||||
* the rendered `reference` is stale there: `applied` advances with every apply and is
|
||||
* replaced when the document hands a new reference (undo, reload) (C1).
|
||||
*/
|
||||
function useAppliedReference(reference: Reference, drafts: Drafts) {
|
||||
const applied = useRef(reference)
|
||||
const typed = useRef(drafts)
|
||||
useLayoutEffect(() => {
|
||||
applied.current = reference
|
||||
}, [reference])
|
||||
useLayoutEffect(() => {
|
||||
typed.current = drafts
|
||||
})
|
||||
return { applied, typed }
|
||||
}
|
||||
|
||||
/** What the view does to the document: `update`, `apply` a draft, which drafts are `pending`. */
|
||||
function useWriter(reference: Reference, drafts: Drafts) {
|
||||
const edit = useEditCommand()
|
||||
const { applied, typed } = useAppliedReference(reference, drafts)
|
||||
const update = (field: string, value: Reference) => {
|
||||
const key = { kind: 'reference', id: reference.id } as const
|
||||
const element = { kind: 'reference', value } as const
|
||||
const done = edit.run(field, { op: 'update', key, element })
|
||||
if (done) applied.current = value
|
||||
return done
|
||||
}
|
||||
const apply = (field: Field): boolean => {
|
||||
if (field === 'citation' && isBlank(drafts[field])) {
|
||||
return edit.reject(field, 'editor.field.required')
|
||||
}
|
||||
return update(field, patched(applied.current, field, drafts[field]))
|
||||
}
|
||||
const pending = (field: Field) =>
|
||||
normalized(field, drafts[field]) !== committedOf(applied.current)[field]
|
||||
return { edit, applied, typed, update, apply, pending }
|
||||
}
|
||||
|
||||
/** The view's three effects: its guard, the focus ticket and the dropped-draft report. */
|
||||
function useEditLifecycle(
|
||||
base: string,
|
||||
hooks: EditHooks,
|
||||
leave: LeaveGuard,
|
||||
writer: Pick<ReturnType<typeof useWriter>, 'applied' | 'typed'>,
|
||||
) {
|
||||
const { registerLeave, takeFocus, onDrop } = hooks
|
||||
const { applied, typed } = writer
|
||||
useEffect(() => {
|
||||
registerLeave(leave)
|
||||
return () => registerLeave(null)
|
||||
})
|
||||
useEffect(() => {
|
||||
if (takeFocus()) document.getElementById(`${base}-citation`)?.focus()
|
||||
}, [base, takeFocus])
|
||||
// Never clears a report (a StrictMode remount runs this cleanup with nothing pending).
|
||||
useLayoutEffect(
|
||||
() => () => {
|
||||
const pending = pendingFields(applied.current, typed.current)
|
||||
if (pending.length > 0) onDrop(pending)
|
||||
},
|
||||
[applied, typed, onDrop],
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The write path of one reference's edit view. A field applies to the draft when it
|
||||
* loses the focus (`commitField`); `leave` re-applies every field whose text differs from
|
||||
* the document, focuses the first refused field and shows that field's refusal (the view
|
||||
* has one error slot; the other refused drafts stay as typed) (P22, P22', I1).
|
||||
* `base` is the DOM id prefix of the tile; `registerLeave` hands `leave` to the library.
|
||||
* `takeFocus` says whether this mount is a user's « Modifier » (it focuses Citation) and
|
||||
* `onDrop` receives the fields of the refused drafts the view is unmounted with (M1).
|
||||
*/
|
||||
export function useReferenceEdit(
|
||||
reference: Reference,
|
||||
base: string,
|
||||
hooks: EditHooks,
|
||||
) {
|
||||
const [drafts, setDraft] = useDrafts(reference)
|
||||
const writer = useWriter(reference, drafts)
|
||||
const { edit, applied, apply, pending } = writer
|
||||
const leave: LeaveGuard = () => {
|
||||
const refused = FIELDS.filter(pending).filter((field) => !apply(field))
|
||||
if (refused.length === 0) return refused
|
||||
// The focus move runs the blur commit of the field that held it, which writes the
|
||||
// one error slot; re-applying the first refusal last makes the focused field the
|
||||
// one that shows its message (I1). Refused again, it writes nothing.
|
||||
document.getElementById(`${base}-${refused[0]}`)?.focus()
|
||||
apply(refused[0])
|
||||
return refused
|
||||
}
|
||||
useEditLifecycle(base, hooks, leave, writer)
|
||||
return {
|
||||
edit,
|
||||
drafts,
|
||||
setDraft,
|
||||
commitField: (field: Field) => pending(field) && apply(field),
|
||||
setType: (type: ReferenceType) =>
|
||||
writer.update('type', { ...applied.current, type }),
|
||||
}
|
||||
}
|
||||
|
||||
/** « Saisie non appliquée : Citation, Adresse web (URL) »: the words for dropped drafts. */
|
||||
export function useDroppedText(): (fields: readonly Field[]) => string {
|
||||
const t = useT()
|
||||
return (fields) => {
|
||||
const names = fields.map((field) => t(`editor.reference.${field}`))
|
||||
return t('editor.references.draft_dropped').replace('{field}', () =>
|
||||
names.join(', '),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -7,27 +7,69 @@ import {
|
||||
type FocusRequest,
|
||||
} from '@/editor/focusRequest'
|
||||
import { citersOf } from '@/editor/references/citations'
|
||||
import { referenceMatches } from '@/editor/references/filter'
|
||||
import {
|
||||
citedIds,
|
||||
citingFinding,
|
||||
referenceMatches,
|
||||
} from '@/editor/references/filter'
|
||||
import { useSheetDocument } from '@/editor/sheetDocument'
|
||||
import type { ReferenceLayer } from '@/editor/tabs'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { usePlaceVisible } from '@/lib/placeVisibility'
|
||||
import { tileKeys, useTileState } from './useTileState'
|
||||
import { useReferenceView } from './useReferenceView'
|
||||
import { ADD_BUTTON_ID } from './addButton'
|
||||
|
||||
const NO_CITERS = new Map<string, never[]>()
|
||||
|
||||
/** The document's references with the tab's tile state and display order. */
|
||||
export function useReferenceLibrary(resetSignal: number) {
|
||||
/**
|
||||
* The finding the filter names, read from the current document, with the ids it cites. A
|
||||
* filter whose finding is gone (an undo, a reload, a Back onto a dead entry) is removed by
|
||||
* replace and says so once (R2F-6).
|
||||
*/
|
||||
function useFilterFinding(layer: ReferenceLayer) {
|
||||
const t = useT()
|
||||
const doc = useSheetDocument()
|
||||
const finding = doc ? citingFinding(doc, layer.filter) : null
|
||||
const gone = doc !== null && layer.filter !== null && finding === null
|
||||
useEffect(() => {
|
||||
if (gone) layer.clearFilter(t('editor.references.filter_gone'))
|
||||
// The wording and the move are stable per render; the vanished finding is the trigger.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [gone])
|
||||
return { finding, cited: finding ? new Set(citedIds(finding)) : null }
|
||||
}
|
||||
|
||||
/** The tile key of the reference the dialog edits, while this tab is the place shown. */
|
||||
function useEditedKey(layer: ReferenceLayer): string | null {
|
||||
const shown = usePlaceVisible()
|
||||
const { view } = layer
|
||||
return shown && view && 'edit' in view ? `${view.edit}#0` : null
|
||||
}
|
||||
|
||||
/** The document's references, one tile key each, the tile state and who cites what. */
|
||||
function useBibliography() {
|
||||
const doc = useSheetDocument()
|
||||
const all: readonly Reference[] = doc?.references ?? []
|
||||
const keys = tileKeys(all)
|
||||
const tiles = useTileState(doc ? keys : null)
|
||||
const citers = doc ? citersOf(doc) : NO_CITERS
|
||||
return { loaded: doc !== null, all, keys, tiles, citers }
|
||||
}
|
||||
|
||||
/** The document's references with the tab's tile state and display order. */
|
||||
export function useReferenceLibrary(
|
||||
resetSignal: number,
|
||||
layer: ReferenceLayer,
|
||||
) {
|
||||
const bibliography = useBibliography()
|
||||
const filter = useFilterFinding(layer)
|
||||
const shown = useReferenceView(
|
||||
{ all, keys, citers },
|
||||
tiles.editingKey,
|
||||
bibliography,
|
||||
useEditedKey(layer),
|
||||
resetSignal,
|
||||
filter.cited,
|
||||
)
|
||||
return { loaded: doc !== null, all, keys, tiles, citers, shown }
|
||||
return { ...bibliography, shown, finding: filter.finding }
|
||||
}
|
||||
export type ReferenceLibraryState = ReturnType<typeof useReferenceLibrary>
|
||||
|
||||
@@ -45,65 +87,76 @@ function useLateFocus() {
|
||||
const positionOf = (all: readonly Reference[], key: ElementKey) =>
|
||||
all.findIndex((r) => key.kind === 'reference' && r.id === key.id)
|
||||
|
||||
type Show = (key: ElementKey) => 'found' | 'none'
|
||||
|
||||
/**
|
||||
* « Aller à » a reference: its tile is opened, the search is cleared (only it, P3) when it
|
||||
* hides the tile, and the tile's button is focused after the commit that shows it (P8).
|
||||
* Shows a reference's tile: opened, the search cleared (only it, P3) and the finding
|
||||
* filter removed when they hide it, its button focused after the commit that shows it
|
||||
* (P8). `none` when the sheet holds no such reference.
|
||||
*/
|
||||
function useReferenceFocus(
|
||||
focus: FocusRequest | undefined,
|
||||
function useShowReference(
|
||||
lib: ReferenceLibraryState,
|
||||
later: (key: ElementKey) => void,
|
||||
) {
|
||||
const { all, keys, tiles, shown } = lib
|
||||
useFocusRequest(focus, (target) => {
|
||||
const at = target.key === null ? -1 : positionOf(all, target.key)
|
||||
if (target.key === null || at < 0) return 'none'
|
||||
tiles.reveal(keys[at])
|
||||
if (referenceMatches(all[at], shown.view.query)) {
|
||||
return focusRowLater(target.key) ? 'found' : 'none'
|
||||
}
|
||||
shown.update({ query: '' })
|
||||
later(target.key)
|
||||
layer: ReferenceLayer,
|
||||
): Show {
|
||||
const later = useLateFocus()
|
||||
return (key) => {
|
||||
const at = positionOf(lib.all, key)
|
||||
if (at < 0) return 'none'
|
||||
const reference = lib.all[at]
|
||||
lib.tiles.reveal(lib.keys[at])
|
||||
const cited = lib.finding && citedIds(lib.finding)
|
||||
const filtered = !!cited && !cited.includes(reference.id)
|
||||
const matches = referenceMatches(reference, lib.shown.view.query)
|
||||
if (matches && !filtered) return focusRowLater(key) ? 'found' : 'none'
|
||||
if (filtered) layer.clearFilter()
|
||||
if (!matches) lib.shown.update({ query: '' })
|
||||
later(key)
|
||||
return 'found'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** What the library's controls do: search, « Ajouter une référence », edit and « Aller à ». */
|
||||
export function useReferenceActions(
|
||||
lib: ReferenceLibraryState,
|
||||
focus: FocusRequest | undefined,
|
||||
searchRef: RefObject<HTMLInputElement | null>,
|
||||
/** « Aller à » a reference: its tile is shown and focused. */
|
||||
function useReferenceFocus(focus: FocusRequest | undefined, show: Show) {
|
||||
useFocusRequest(focus, (target) =>
|
||||
target.key === null ? 'none' : show(target.key),
|
||||
)
|
||||
}
|
||||
|
||||
/** The notice of a reference just added: shown until « Afficher », or until it is gone. */
|
||||
function useAddedNotice(
|
||||
all: readonly Reference[],
|
||||
added: ReferenceLayer['added'],
|
||||
show: Show,
|
||||
) {
|
||||
const { keys, tiles, shown } = lib
|
||||
const [draft, setDraft] = useState<number | null>(null)
|
||||
const later = useLateFocus()
|
||||
useReferenceFocus(focus, lib, later)
|
||||
const [dismissed, setDismissed] = useState(0)
|
||||
const reference = added && all.find((r) => r.id === added.id)
|
||||
if (!added || !reference || added.serial === dismissed) return null
|
||||
return {
|
||||
draft,
|
||||
clearSearch: () => {
|
||||
shown.update({ query: '' })
|
||||
searchRef.current?.focus()
|
||||
},
|
||||
// P24 (and P22): leave the tile in edit first, then a clean view and the draft.
|
||||
startAdd: () => {
|
||||
if (!tiles.finish()) return
|
||||
shown.reset(null)
|
||||
setDraft((serial) => (serial ?? 0) + 1)
|
||||
},
|
||||
// P24: the new tile is shown whatever was typed meanwhile, so the view is reset.
|
||||
added: (id: string) => {
|
||||
setDraft(null)
|
||||
shown.reset(tiles.editingKey)
|
||||
tiles.reveal(`${id}#0`)
|
||||
later({ kind: 'reference', id })
|
||||
},
|
||||
// C2: nothing was written; the search and sort reset by the add stay as they are.
|
||||
cancelAdd: () => {
|
||||
setDraft(null)
|
||||
document.getElementById(ADD_BUTTON_ID)?.focus()
|
||||
},
|
||||
edit: (position: number) => {
|
||||
if (tiles.startEdit(keys[position])) shown.markEdited(keys[position])
|
||||
citation: reference.citation,
|
||||
show: () => {
|
||||
show({ kind: 'reference', id: added.id })
|
||||
setDismissed(added.serial)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** What the library's controls do: search, « Ajouter une référence », « Modifier », « Aller à ». */
|
||||
export function useReferenceActions(
|
||||
lib: ReferenceLibraryState,
|
||||
focus: FocusRequest | undefined,
|
||||
layer: ReferenceLayer,
|
||||
searchRef: RefObject<HTMLInputElement | null>,
|
||||
) {
|
||||
const show = useShowReference(lib, layer)
|
||||
useReferenceFocus(focus, show)
|
||||
return {
|
||||
notice: useAddedNotice(lib.all, layer.added, show),
|
||||
clearSearch: () => {
|
||||
lib.shown.update({ query: '' })
|
||||
searchRef.current?.focus()
|
||||
},
|
||||
startAdd: (opener: HTMLElement) => layer.start(opener),
|
||||
edit: (position: number, opener: HTMLElement) =>
|
||||
layer.open(lib.all[position].id, opener),
|
||||
}
|
||||
}
|
||||
@@ -26,70 +26,61 @@ interface Shown {
|
||||
|
||||
/**
|
||||
* The search, the sort and the resulting tile order of the Références tab. All three are
|
||||
* display state: nothing here reaches the document (BDR-114). `resetSignal` (« Tout
|
||||
* afficher ») empties the search once per bump and keeps the sort (R2F-4); the tab stays
|
||||
* mounted (A2).
|
||||
* The tile that entered edit is pinned at the index it was shown at, whatever the search
|
||||
* or the sort, and stays pinned after « Terminer » until the next search or sort change,
|
||||
* so the tile the user just edited never vanishes under their focus (P23, I1). A
|
||||
* read-only flip keeps the pin: the tile in edit stays shown across it, with its note.
|
||||
* `editingKey` is the tile in edit, if any.
|
||||
* display state: nothing here reaches the document (BDR-114), and the search is a personal
|
||||
* search that never reaches the browser history. `resetSignal` (« Tout afficher ») empties
|
||||
* the search once per bump and keeps the sort (R2F-4); the tab stays mounted (A2).
|
||||
* `cited` (the ids one finding cites, null for none) narrows the list and the counts
|
||||
* (R2F-6); it is navigation, held by the history.
|
||||
* The tile the dialog edits (`editingKey`) is pinned at the index it was shown at, whatever
|
||||
* the search or the sort, and stays pinned after the dialog closes until the next search
|
||||
* or sort change, so the tile the user just edited never vanishes under their focus (P23,
|
||||
* I1). With a filter nothing is pinned: a tile outside it never shows.
|
||||
*/
|
||||
export function useReferenceView(
|
||||
{ all, keys, citers }: Shown,
|
||||
editingKey: string | null,
|
||||
resetSignal: number,
|
||||
cited: ReadonlySet<string> | null,
|
||||
) {
|
||||
const locale = useLocaleStore((state) => state.locale)
|
||||
const [view, setView] = useState(INITIAL)
|
||||
const [seen, setSeen] = useState(resetSignal)
|
||||
const [pinned, setPinned] = useState<Pinned | null>(null)
|
||||
// The reset view is the sheet order: the tile in edit sits at its own position.
|
||||
const pinEdited = (key: string | null): Pinned | null =>
|
||||
key === null || !keys.includes(key)
|
||||
? null
|
||||
: { key, index: keys.indexOf(key) }
|
||||
if (seen !== resetSignal) {
|
||||
setSeen(resetSignal)
|
||||
setView({ ...view, query: '' })
|
||||
setPinned(pinEdited(editingKey))
|
||||
setPinned(null)
|
||||
}
|
||||
const pinAt = pinned === null ? -1 : keys.indexOf(pinned.key)
|
||||
const pin =
|
||||
pinned !== null && pinAt >= 0 && !isSheetView(view)
|
||||
? { position: pinAt, index: pinned.index }
|
||||
: null
|
||||
const context = {
|
||||
locale,
|
||||
citedCount: (id: string) => citers.get(id)?.length ?? 0,
|
||||
}
|
||||
const positions = shownPositions(all, view, context, pin)
|
||||
// The count is the matches: a pinned tile the search misses is shown, not counted.
|
||||
const matchCount = all.filter((r) => referenceMatches(r, view.query)).length
|
||||
const pinAtShown = (key: string) =>
|
||||
Math.max(0, positions.indexOf(keys.indexOf(key)))
|
||||
// A new search or sort: the tile in edit stays where it is shown, any other pin ends.
|
||||
const pinAfterChange = (): Pinned | null => {
|
||||
if (pinned === null || pinned.key !== editingKey) return null
|
||||
return { key: pinned.key, index: pinAtShown(pinned.key) }
|
||||
const plain = shownPositions(all, view, context, null, cited)
|
||||
const editedAt = editingKey === null ? -1 : keys.indexOf(editingKey)
|
||||
// Only a tile that is shown is pinned: a reference just created is not part of the list.
|
||||
if (plain.includes(editedAt) && pinned?.key !== editingKey) {
|
||||
setPinned({ key: editingKey as string, index: plain.indexOf(editedAt) })
|
||||
}
|
||||
const pinAt = pinned === null ? -1 : keys.indexOf(pinned.key)
|
||||
const pin =
|
||||
pinned !== null && pinAt >= 0 && !isSheetView(view, cited !== null)
|
||||
? { position: pinAt, index: Math.max(0, pinned.index) }
|
||||
: null
|
||||
const positions = shownPositions(all, view, context, pin, cited)
|
||||
const inFilter = (r: Reference) => cited === null || cited.has(r.id)
|
||||
// The count is the matches: a pinned tile the search misses is shown, not counted.
|
||||
const matchCount = all.filter(
|
||||
(r) => inFilter(r) && referenceMatches(r, view.query),
|
||||
).length
|
||||
return {
|
||||
view,
|
||||
positions,
|
||||
matchCount,
|
||||
total: all.filter(inFilter).length,
|
||||
filtered: cited !== null,
|
||||
update: (patch: Partial<ReferenceView>) => {
|
||||
setPinned(pinAfterChange())
|
||||
setPinned(null)
|
||||
setView((current) => ({ ...current, ...patch }))
|
||||
},
|
||||
/**
|
||||
* The clean view; `keep` is the tile still in edit, passed by the caller because a
|
||||
* `finish()` in the same handler has not reached this render's `editingKey` (M3).
|
||||
*/
|
||||
reset: (keep: string | null) => {
|
||||
setView(INITIAL)
|
||||
setPinned(pinEdited(keep))
|
||||
},
|
||||
/** The tile `key` enters edit: remember where it is shown. */
|
||||
markEdited: (key: string) => setPinned({ key, index: pinAtShown(key) }),
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import type { LeaveGuard, Field } from './useReferenceEdit'
|
||||
import { useState } from 'react'
|
||||
|
||||
/**
|
||||
* One key per tile: the id and its occurrence among equal ids, so a duplicated id stays
|
||||
@@ -15,75 +14,25 @@ export function tileKeys(all: readonly { id: string }[]): string[] {
|
||||
}
|
||||
|
||||
/**
|
||||
* Which tiles are open and which one is in edit. Lives in the library, which the tab keeps
|
||||
* mounted (A2), so both survive a tab change and reset when the editor is reopened.
|
||||
* Leaving the edit view asks the tile's guard first: a refusal keeps it (P22). `keys` are
|
||||
* the tiles the document has (null while it is not loaded): state of a tile that is gone
|
||||
* is dropped at once (P23').
|
||||
* Which tiles are open. Lives in the library, which the tab keeps mounted (A2), so it
|
||||
* survives a tab change and resets when the editor is reopened. `keys` are the tiles the
|
||||
* document has (null while it is not loaded): state of a tile that is gone is dropped at
|
||||
* once (P23'). Nothing here edits a tile: « Modifier » opens the reference dialog.
|
||||
*/
|
||||
export function useTileState(keys: readonly string[] | null) {
|
||||
const [openKeys, setOpenKeys] = useState<ReadonlySet<string>>(() => new Set())
|
||||
const [editingKey, setEditingKey] = useState<string | null>(null)
|
||||
if (keys !== null) {
|
||||
const live = new Set(keys)
|
||||
if ([...openKeys].some((key) => !live.has(key))) {
|
||||
setOpenKeys(new Set([...openKeys].filter((key) => live.has(key))))
|
||||
}
|
||||
if (editingKey !== null && !live.has(editingKey)) setEditingKey(null)
|
||||
}
|
||||
const guard = useRef<LeaveGuard | null>(null)
|
||||
// The tile a « Modifier » just opened: its edit view focuses Citation once, a remount
|
||||
// after a read-only interval does not (M1).
|
||||
const focusTicket = useRef<string | null>(null)
|
||||
/** Applies the tile in edit; the fields that refused, none when nothing is left to apply. */
|
||||
const leave = (): Field[] => guard.current?.() ?? []
|
||||
const open = (key: string) => setOpenKeys((prev) => new Set(prev).add(key))
|
||||
const finish = () => {
|
||||
if (leave().length > 0) return false
|
||||
setEditingKey(null)
|
||||
return true
|
||||
}
|
||||
// Read-only, the edit view is gone: a toggle ends the edit state and collapses.
|
||||
const toggle = (key: string, readOnly = false) => {
|
||||
if (editingKey === key) {
|
||||
if (!readOnly) return void finish()
|
||||
setEditingKey(null)
|
||||
return setOpenKeys((prev) => {
|
||||
const next = new Set(prev)
|
||||
next.delete(key)
|
||||
return next
|
||||
})
|
||||
}
|
||||
const toggle = (key: string) =>
|
||||
setOpenKeys((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (!next.delete(key)) next.add(key)
|
||||
return next
|
||||
})
|
||||
}
|
||||
const startEdit = (key: string) => {
|
||||
if (editingKey !== null && editingKey !== key && leave().length > 0)
|
||||
return false
|
||||
focusTicket.current = key
|
||||
setEditingKey(key)
|
||||
open(key)
|
||||
return true
|
||||
}
|
||||
const takeFocus = (key: string) => {
|
||||
const mine = focusTicket.current === key
|
||||
if (mine) focusTicket.current = null
|
||||
return mine
|
||||
}
|
||||
return {
|
||||
openKeys,
|
||||
editingKey,
|
||||
toggle,
|
||||
startEdit,
|
||||
finish,
|
||||
leave,
|
||||
takeFocus,
|
||||
reveal: open,
|
||||
registerLeave: (next: LeaveGuard | null) => {
|
||||
guard.current = next
|
||||
},
|
||||
}
|
||||
return { openKeys, toggle, reveal: open }
|
||||
}
|
||||
@@ -2,18 +2,20 @@ 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 Button from '@/components/ui/Button'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import NoResult from '@/components/editor/references/NoResult'
|
||||
import ReferenceTiles from '@/components/editor/references/ReferenceTiles'
|
||||
import ReferenceToolbar from '@/components/editor/references/ReferenceToolbar'
|
||||
import {
|
||||
useReferenceActions,
|
||||
useReferenceLibrary,
|
||||
type ReferenceLibraryState,
|
||||
} from '@/components/editor/references/useReferenceLibrary'
|
||||
import { isSheetView } from '@/editor/references/view'
|
||||
import type { EditorPlaceProps } from '@/editor/tabs'
|
||||
import type { EditorPlaceProps, ReferenceLayer } from '@/editor/tabs'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
/** The empty line: the sheet has no reference at all. */
|
||||
function EmptyLine() {
|
||||
@@ -27,21 +29,106 @@ function EmptyLine() {
|
||||
|
||||
type Props = Pick<EditorPlaceProps, 'readOnly' | 'navigate' | 'focus'> & {
|
||||
resetSignal: number
|
||||
layer: ReferenceLayer
|
||||
}
|
||||
|
||||
/** « Référence ajoutée : … » with « Afficher »: the list did not move. */
|
||||
function AddedNotice({
|
||||
citation,
|
||||
onShow,
|
||||
}: {
|
||||
citation: string
|
||||
onShow: () => void
|
||||
}) {
|
||||
const t = useT()
|
||||
return (
|
||||
<Notice tone="success" className="items-center">
|
||||
<span className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
{t('editor.references.added').replace('{citation}', () => citation)}
|
||||
<Button type="button" variant="secondary" size="sm" onClick={onShow}>
|
||||
{t('editor.references.added_show')}
|
||||
</Button>
|
||||
</span>
|
||||
</Notice>
|
||||
)
|
||||
}
|
||||
|
||||
/** The chip of the finding the list is filtered by, null for the whole bibliography. */
|
||||
function useFilterChip(lib: ReferenceLibraryState, layer: ReferenceLayer) {
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const { finding } = lib
|
||||
if (!finding || !layer.filter) return null
|
||||
const key = layer.filter
|
||||
return {
|
||||
name: finding.name[locale],
|
||||
onRemove: () => layer.clearFilter(),
|
||||
onBack: () => layer.backToFinding(key),
|
||||
}
|
||||
}
|
||||
|
||||
type Actions = ReturnType<typeof useReferenceActions>
|
||||
|
||||
interface BodyProps {
|
||||
lib: ReferenceLibraryState
|
||||
act: Actions
|
||||
props: Props
|
||||
}
|
||||
|
||||
/** The notice, the empty and no-result lines, the hint and the tiles. */
|
||||
function LibraryBody({ lib, act, props }: BodyProps) {
|
||||
const t = useT()
|
||||
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
|
||||
const { all, shown } = lib
|
||||
const sheetView = isSheetView(shown.view, shown.filtered)
|
||||
return (
|
||||
<>
|
||||
{act.notice && (
|
||||
<AddedNotice citation={act.notice.citation} onShow={act.notice.show} />
|
||||
)}
|
||||
{all.length === 0 && <EmptyLine />}
|
||||
{all.length > 0 && shown.positions.length === 0 && (
|
||||
<NoResult query={shown.view.query} onClear={act.clearSearch} />
|
||||
)}
|
||||
{!props.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}
|
||||
query={shown.view.query}
|
||||
readOnly={props.readOnly}
|
||||
movable={sheetView}
|
||||
navigate={props.navigate}
|
||||
onEdit={act.edit}
|
||||
onDelete={(reference) =>
|
||||
setDeleting({
|
||||
key: { kind: 'reference', id: reference.id },
|
||||
label: reference.citation,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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).
|
||||
* The sheet's bibliography: toolbar (search, sort, filter, count, add), one collapsible
|
||||
* tile per reference and the delete dialog. « Modifier » and « Ajouter » open the
|
||||
* reference dialog (a layer of the workspace). 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(resetSignal)
|
||||
function Library(props: Props) {
|
||||
const lib = useReferenceLibrary(props.resetSignal, props.layer)
|
||||
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)
|
||||
const act = useReferenceActions(lib, props.focus, props.layer, searchRef)
|
||||
const chip = useFilterChip(lib, props.layer)
|
||||
const { shown } = lib
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<ReferenceToolbar
|
||||
@@ -52,51 +139,12 @@ function Library({ readOnly, navigate, focus, resetSignal }: Props) {
|
||||
sort={shown.view.sort}
|
||||
onSort={(sort) => shown.update({ sort })}
|
||||
shown={shown.matchCount}
|
||||
total={all.length}
|
||||
canAdd={!readOnly}
|
||||
total={shown.total}
|
||||
canAdd={!props.readOnly}
|
||||
onAdd={act.startAdd}
|
||||
filter={chip}
|
||||
/>
|
||||
{lib.loaded && (
|
||||
<>
|
||||
{all.length === 0 && <EmptyLine />}
|
||||
{all.length > 0 && shown.positions.length === 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}
|
||||
query={shown.view.query}
|
||||
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}
|
||||
onCancel={act.cancelAdd}
|
||||
/>
|
||||
)}
|
||||
</EditOnly>
|
||||
</>
|
||||
)}
|
||||
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
|
||||
{lib.loaded && <LibraryBody lib={lib} act={act} props={props} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -107,8 +155,11 @@ export default function ReferencesTab({
|
||||
navigate,
|
||||
focus,
|
||||
libraryReset = 0,
|
||||
references,
|
||||
}: EditorPlaceProps) {
|
||||
const t = useT()
|
||||
if (!references)
|
||||
throw new Error('Références needs the reference layer of the workspace')
|
||||
return (
|
||||
<section
|
||||
data-testid="editor-tab-references"
|
||||
@@ -128,6 +179,7 @@ export default function ReferencesTab({
|
||||
navigate={navigate}
|
||||
focus={focus}
|
||||
resetSignal={libraryReset}
|
||||
layer={references}
|
||||
/>
|
||||
</section>
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user