feat(editor): collapsible reference tiles in the Références tab

Board 23 / 24 / 27 tiles: closed (citation on two lines, type, « Citée
{n} fois » / « Non citée »), open (Type, DOI, URL as safe links, the
citers with « famille » badge and « Aller à »), edit (« Terminer » with a
leave guard re-committing every changed field; a refusal keeps edit
and focuses the field). A cited reference shows the deletion hint, an
uncited one keeps « Supprimer ». Read-only keeps DOI, URL, « Aller à ».
« Terminer » keeps focus in the field on press, so a refusal message
can no longer move the button under the pointer.

Gates: typecheck, lint, test:run (app 1419), build, e2e:ui 251;
e2e:shell 16 specs on db:sandbox (editor-equine never listed): 111
passed / 99 skipped / 3 failed in the new editor-references.spec (two
test bugs, one app bug), fixed and rerun: 5 passed / 4 skipped; full-row
guard: no pre-existing row changed in any table.

## R-24 (removed or rewritten assertions)
| file | old | new |
|---|---|---|
| editor-citations.test.ts | `citationCounts` counts 2/1/0, memoised, empty | `citersOf`: ordered citers (Cat, Node), family flag, trail from zone, key, memoised, empty |
| editor-references-tab.test.tsx | cards say « citée N fois » (ref-a 1, ref-c 0) | « Citée 2 fois » (fixture gains a node citing ref-a), « Citée 1 fois », « Non citée » |
| same | ids `#tab-reference-ref-a-citation` exist when closed | header id `#tab-reference-0-ref-a-header`; field ids only inside an open edit tile |
| same | ↑/↓ on every card | in open tiles only, absent under a search |
| same | Ctrl+Z on an always-visible field | open tile, Modifier, then same assertion on `#tab-reference-0-ref-a-citation` |
| same | « Aller à » focuses the card (`listitem` count 3, focus key) | tile opened (aria-expanded true), header focused, 3 tiles |
| same | add: `getByText('Nouvelle source')` | tile header named « Nouvelle source » |
| same | read-only: no Supprimer / add | same after opening every tile |
| editor-tabs-lists.test.tsx | edit on blur and arrows on always-open cards | open tile, Modifier, blur applies, Terminer, Monter on opened tile |
| same | cited reference deletion refused in a dialog listing citers | REMOVED: no Supprimer on a cited tile (hint asserted, citer listed); uncited delete kept. The dialog's blocked path stays covered by `DeleteDialog`'s own tests |
| same | read-only: no button at all | read-only: facts shown, no Modifier / Supprimer / Citation textbox (header buttons exist now) |
| editor-keep-alive.test.tsx:~330 | tab-click commit of `#tab-reference-ref-1-citation` | opens tile + Modifier first, id `#tab-reference-0-ref-1-citation` |
| editor-keep-alive.test.tsx:~350,367 | `#panel-reference-ref-1-citation` | `#panel-reference-0-ref-1-citation` |
| editor-references-panel.test.tsx | « citée 2 fois / 1 fois » | « Citée 2 fois / 1 fois » |
| same | `#panel-reference-ref-a-citation`; no `#tab-reference-ref-a-citation` | `#panel-reference-0-ref-a-citation`; no `[id^="tab-reference-"]` while the tab tiles are closed |
| same | ids unique, tab and panel field ids present | tab tile opened in edit first; `tab-reference-0-ref-a-citation` and `panel-reference-0-ref-a-citation` unique |
| e2e editor-structures.spec.ts:~88-110 | citation inputs count 3/1/2, « citée 0 fois » x2, « citée 1 fois », move via row buttons | tile headers count, « Non citée » x2, « Citée 1 fois », tile opened before Monter/Supprimer, `tiles.nth(1)` contains the moved text (saved-list assertion unchanged) |

## i18n (fr / en)
Changed (in place, P18): `editor.references.cited_one|other`: « citée {count} fois » -> « Citée {count} fois »; « cited {count} time(s) » -> « Cited {count} time(s) ».
Added: `editor.references.uncited` Non citée / Not cited; `citers_one|other` « Citée {count} fois, par : » / « Cited {count} time(s), by: »; `no_citers` « Aucun constat ni aucune famille ne cite cette référence. » / « No finding or family cites this reference. »; `family` famille / family; `go_to` Aller à / Go to; `edit` Modifier / Edit; `done` Terminer / Done; `edit_title` Modifier la référence / Edit the reference; `url_label` URL / URL; `none_doi` Aucun / None; `none_url` Aucune / None; `new_tab` (nouvel onglet) / (new tab) (sr-only); `delete_hint` (REVUE wording, fr and en).
Removed: none. R10 grep (src, tests, e2e incl. editor-equine) found no reader of the old lowercase wording left.
This commit is contained in:
bchanot committed 2026-11-12 20:50:25 +01:00
1 parent 4499bc740c
commit c21995b3fb
26 files changed
+1532 -155

No files matched your search

@@ -11,6 +11,7 @@ export default function DraftField({
label,
value,
onChange,
onBlur,
multiline,
hint,
error,
@@ -19,6 +20,8 @@ export default function DraftField({
label: string
value: string
onChange: (value: string) => void
/** Optional: a form field that applies its text when it loses the focus. */
onBlur?: () => void
multiline?: boolean
hint?: string
error?: string
@@ -27,6 +30,7 @@ export default function DraftField({
id,
value,
onChange: (e: { target: { value: string } }) => onChange(e.target.value),
onBlur,
'aria-invalid': Boolean(error),
'aria-describedby': fieldDescribedBy(id, hint, error),
}
@@ -0,0 +1,57 @@
import type { ElementKey } from '@faunosteo/core-wasm/types'
import type { CiterItem } from '@/editor/references/citations'
import { usePlural } from '@/editor/plural'
import { useT } from '@/i18n/useT'
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,
onGoTo,
}: {
citers: readonly CiterItem[]
onGoTo: (key: ElementKey) => void
}) {
const t = useT()
const plural = usePlural()
const locale = useLocaleStore((s) => s.locale)
if (citers.length === 0) {
return (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.references.no_citers')}
</p>
)
}
return (
<div className="space-y-1">
<p className="text-sm font-semibold">
{plural('editor.references.citers', citers.length)}
</p>
<ul>
{citers.map((citer, index) => (
<li key={index} className="flex items-start gap-2 py-1 text-sm">
<span className="min-w-0 flex-1">
<span className="text-[var(--color-ink-muted)]">
{citer.trail.map((name) => name[locale]).join(' › ')}
{' › '}
</span>
{citer.name[locale]}
{citer.isFamily && (
<span className="ml-1 rounded-md bg-[var(--color-surface-strong)] px-2 py-0.5 text-xs">
{t('editor.references.family')}
</span>
)}
</span>
<button
type="button"
onClick={() => onGoTo(citer.key)}
className="inline-flex min-h-11 items-center whitespace-nowrap text-[var(--color-accent-strong)] underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
>
{t('editor.references.go_to')}
</button>
</li>
))}
</ul>
</div>
)
}
@@ -0,0 +1,63 @@
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 Field,
type LeaveGuard,
} 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 the view is mounted and null after. */
registerLeave: (guard: LeaveGuard | null) => void
}
/** 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.registerLeave,
)
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({ ...reference, type: 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,62 @@
import type { Reference } from '@faunosteo/core-wasm/types'
import Icon from '@/components/ui/Icon'
import { doiHref, webHref } from '@/editor/references/safeLink'
import { useT } from '@/i18n/useT'
const LINK =
'inline-flex max-w-full items-center gap-1 text-[var(--color-accent-strong)] underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
/** An external link (new tab); plain text when the address is not a safe link. */
function Address({ text, href }: { text: string; href: string | null }) {
const t = useT()
if (href === null) return <span className="break-all">{text}</span>
return (
<a href={href} target="_blank" rel="noopener noreferrer" className={LINK}>
<span className="break-all">{text}</span>
<Icon name="external" size={14} />
<span className="sr-only">{t('editor.references.new_tab')}</span>
</a>
)
}
function Absent({ label }: { label: string }) {
return <span className="text-[var(--color-ink-muted)]">{label}</span>
}
/** Type, DOI and URL of a reference; the links only for http(s) and a well-formed DOI. */
export default function ReferenceFacts({
reference,
}: {
reference: Reference
}) {
const t = useT()
const { doi, url } = reference
return (
<dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm">
<dt className="text-[var(--color-ink-muted)]">
{t('editor.reference.type')}
</dt>
<dd>{t(`editor.reference.type.${reference.type}`)}</dd>
<dt className="text-[var(--color-ink-muted)]">
{t('editor.reference.doi')}
</dt>
<dd className="min-w-0">
{doi ? (
<Address text={doi} href={doiHref(doi)} />
) : (
<Absent label={t('editor.references.none_doi')} />
)}
</dd>
<dt className="text-[var(--color-ink-muted)]">
{t('editor.references.url_label')}
</dt>
<dd className="min-w-0">
{url ? (
<Address text={url} href={webHref(url)} />
) : (
<Absent label={t('editor.references.none_url')} />
)}
</dd>
</dl>
)
}
@@ -10,28 +10,33 @@ import {
useFocusRequest,
type FocusRequest,
} from '@/editor/focusRequest'
import { citationCounts } from '@/editor/references/citations'
import type { EditorTarget } from '@/editor/navigation'
import { citersOf } from '@/editor/references/citations'
import { visibleReferences } from '@/editor/references/filter'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useT } from '@/i18n/useT'
import ReferenceForm from './ReferenceForm'
import { EmptyLine, ReferenceList } from './ReferenceList'
import { EmptyLine } from './ReferenceList'
import ReferenceTiles from './ReferenceTiles'
import { tileKeys, useTileState } from './useTileState'
interface Props {
readOnly: boolean
/** « Aller à » a citing finding or family. */
navigate: (target: EditorTarget) => void
focus?: FocusRequest
/** Bumped by « Tout afficher »: the search is emptied once per bump. */
resetSignal?: number
}
/**
* « Aller à » a reference: the search is cleared first when it may hide the card, and the
* card is focused after the commit that shows it (it does not exist while hidden).
* « Aller à » a reference: its tile is opened, the search is cleared first when it may
* hide the tile, and the tile's button is focused after the commit that shows it.
*/
function useReferenceFocus(
focus: FocusRequest | undefined,
query: string,
clearQuery: () => void,
actions: { clearQuery: () => void; reveal: (key: ElementKey) => void },
) {
const [late, setLate] = useState<ElementKey | null>(null)
useEffect(() => {
@@ -41,8 +46,9 @@ function useReferenceFocus(
}, [late])
useFocusRequest(focus, (target) => {
if (target.key === null) return 'none'
actions.reveal(target.key)
if (query === '') return focusRow(target.key) ? 'found' : 'none'
clearQuery()
actions.clearQuery()
setLate(target.key)
return 'found'
})
@@ -60,21 +66,27 @@ function useSearchQuery(resetSignal: number) {
}
/**
* The sheet's bibliography: a search, one card per reference with how often it is cited,
* the add form and the delete dialog. Lives in the Références tab (ids prefixed `tab-`).
* The sheet's bibliography: a search, one collapsible tile per reference, the add form
* and the delete dialog. Lives in the Références tab (ids prefixed `tab-`).
*/
export default function ReferenceLibrary({
readOnly,
focus,
resetSignal = 0,
}: Props) {
export default function ReferenceLibrary(props: Props) {
const { readOnly, navigate, focus, resetSignal = 0 } = props
const t = useT()
const doc = useSheetDocument()
const tiles = useTileState()
const [query, setQuery] = useSearchQuery(resetSignal)
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
useReferenceFocus(focus, query, () => setQuery(''))
const all: readonly Reference[] = doc?.references ?? []
const keys = tileKeys(all)
const reveal = (key: ElementKey) => {
const at = all.findIndex(
(reference) => key.kind === 'reference' && reference.id === key.id,
)
if (at >= 0) tiles.reveal(keys[at])
}
useReferenceFocus(focus, query, { clearQuery: () => setQuery(''), reveal })
const shown = visibleReferences(all, null, query)
const citers = doc ? citersOf(doc) : new Map()
return (
<div className="space-y-3">
<Input
@@ -87,13 +99,15 @@ export default function ReferenceLibrary({
{doc && (
<>
<EmptyLine total={all.length} shown={shown.length} />
<ReferenceList
host="tab"
<ReferenceTiles
shown={shown}
all={all}
counts={citationCounts(doc)}
movable={query.trim() === ''}
keys={keys}
citers={citers}
tiles={tiles}
readOnly={readOnly}
movable={query.trim() === ''}
navigate={navigate}
onDelete={(reference) =>
setDeleting({
key: { kind: 'reference', id: reference.id },
@@ -1,4 +1,5 @@
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'
@@ -7,29 +8,29 @@ interface ListProps {
host: ReferenceHost
shown: readonly Reference[]
all: readonly Reference[]
counts: ReadonlyMap<string, number>
movable: boolean
citers: ReadonlyMap<string, readonly CiterItem[]>
readOnly: boolean
onDelete: (reference: Reference) => void
}
/** The cards of `shown`, each knowing its place in the whole bibliography `all`. */
export function ReferenceList({ shown, all, counts, ...rest }: ListProps) {
/** 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) => (
<ReferenceRow
key={reference.id}
host={rest.host}
reference={reference}
index={all.indexOf(reference)}
count={all.length}
cited={counts.get(reference.id) ?? 0}
movable={rest.movable}
readOnly={rest.readOnly}
onDelete={() => rest.onDelete(reference)}
/>
))}
{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>
)
}
@@ -1,6 +1,5 @@
import type { Reference, ReferenceType } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import MoveButtons from '@/components/editor/fields/MoveButtons'
import SelectField from '@/components/editor/fields/SelectField'
import TextField from '@/components/editor/fields/TextField'
import { FOCUS_CLASS, focusAttrs } from '@/editor/focusRequest'
@@ -12,14 +11,12 @@ import { REFERENCE_TYPES, type ReferenceHost } from './referenceTypes'
const CARD = 'space-y-3 rounded-lg border border-[var(--color-border)] p-3'
/** One reference: fields commit one by one, ↑ / ↓ reorder, delete asks the core. */
/** One reference as the citations panel shows it (interim until R2.4): fields commit one by one. */
export default function ReferenceRow({
host,
reference,
index,
count,
cited,
movable,
readOnly,
onDelete,
}: {
@@ -28,11 +25,8 @@ export default function ReferenceRow({
reference: Reference
/** Position in the whole bibliography, not in a filtered list. */
index: number
count: number
/** How many findings cite it. */
cited: number
/** ↑ / ↓ only while neither the finding filter nor the search narrows the list. */
movable: boolean
readOnly: boolean
onDelete: () => void
}) {
@@ -50,11 +44,13 @@ export default function ReferenceRow({
value: type,
label: t(`editor.reference.type.${type}`),
}))
const prefix = `${host}-reference-${reference.id}`
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)]">
{plural('editor.references.cited', cited)}
{cited === 0
? t('editor.references.uncited')
: plural('editor.references.cited', cited)}
</p>
<div className="grid gap-3">
<SelectField
@@ -97,16 +93,6 @@ export default function ReferenceRow({
/>
</div>
<div className="flex flex-wrap items-center justify-end gap-1">
{movable && (
<MoveButtons
index={index}
count={count}
readOnly={readOnly}
onMove={(position) =>
edit.run('move', { op: 'move', key, position })
}
/>
)}
<ActionButton
readOnly={readOnly}
variant="danger"
@@ -116,11 +102,6 @@ export default function ReferenceRow({
{t('editor.action.delete')}
</ActionButton>
</div>
{edit.fieldError('move') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('move')}
</p>
)}
</li>
)
}
@@ -0,0 +1,211 @@
import { useRef, 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 { 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 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
remove: () => void
move: (position: number) => void
goTo: (key: ElementKey) => void
registerLeave: (guard: LeaveGuard | null) => void
}
export interface TileProps {
host: ReferenceHost
reference: Reference
/** Position in the whole bibliography, not in a filtered list. */
position: number
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
on: TileHandlers
}
/** DOM id prefix of a tile: host, position and id keep duplicates distinct (P31). */
export const tileBase = (
host: ReferenceHost,
position: number,
reference: Reference,
) => `${host}-reference-${position}-${reference.id}`
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,
}: {
base: string
props: TileProps
headerRef: RefObject<HTMLButtonElement | null>
}) {
const t = useT()
const plural = usePlural()
const { reference, open, editing, 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}
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}`}
>
<Icon
name={open || editing ? 'chevron-down' : 'chevron-right'}
size={18}
/>
<span
className={`min-w-0 break-words text-sm ${open || editing ? '' : 'line-clamp-2'} ${editing ? 'font-semibold' : ''}`}
>
{editing ? t('editor.references.edit_title') : 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>
{cited === 0
? t('editor.references.uncited')
: plural('editor.references.cited', cited)}
</span>
</span>
</button>
)
}
/** « 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
return (
<>
<div className="flex flex-wrap items-center gap-2">
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
onClick={on.edit}
>
{t('editor.references.edit')}
</ActionButton>
{citers.length === 0 && (
<ActionButton
readOnly={false}
variant="ghost"
size="sm"
className="text-[var(--color-danger-strong)]"
onClick={on.remove}
>
{t('editor.action.delete')}
</ActionButton>
)}
{movable && (
<>
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
disabled={position === 0}
onClick={() => on.move(position - 1)}
>
{t('editor.action.move_up')}
</ActionButton>
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
disabled={position >= count - 1}
onClick={() => on.move(position + 1)}
>
{t('editor.action.move_down')}
</ActionButton>
</>
)}
</div>
{citers.length > 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.references.delete_hint')}
</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.
*/
export default function ReferenceTile(props: TileProps) {
const { host, reference, position, open, editing, on } = props
const t = useT()
const base = tileBase(host, position, reference)
const headerRef = useRef<HTMLButtonElement>(null)
const done = () => {
if (on.done()) headerRef.current?.focus()
}
return (
<li className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)]">
<TileHeader base={base} props={props} headerRef={headerRef} />
{(open || editing) && (
<div
id={`${base}-body`}
className="space-y-3 border-t border-[var(--color-border)] p-3"
>
{editing ? (
<ReferenceEditor
reference={reference}
base={base}
registerLeave={on.registerLeave}
/>
) : (
<ReferenceFacts reference={reference} />
)}
<CitersList citers={props.citers} onGoTo={on.goTo} />
{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} />
)}
</div>
)}
</li>
)
}
@@ -0,0 +1,71 @@
import type { Reference } from '@faunosteo/core-wasm/types'
import { targetOfKey, type EditorTarget } from '@/editor/navigation'
import type { CiterItem } from '@/editor/references/citations'
import { useEditCommand } from '@/editor/useEditCommand'
import ReferenceTile from './ReferenceTile'
import type { useTileState } from './useTileState'
interface Props {
/** The tiles to list, each placed by its index in the whole bibliography `all`. */
shown: readonly Reference[]
all: readonly Reference[]
/** One key per position of `all` (`tileKeys`). */
keys: readonly string[]
citers: ReadonlyMap<string, readonly CiterItem[]>
tiles: ReturnType<typeof useTileState>
readOnly: boolean
movable: boolean
navigate: (target: EditorTarget) => void
onDelete: (reference: Reference) => void
}
/** The tiles of the Références tab, wired to the library's open / edit state. */
export default function ReferenceTiles(props: Props) {
const { shown, all, keys, citers, tiles, navigate } = props
const edit = useEditCommand()
const move = (reference: Reference, position: number) =>
edit.run('move', {
op: 'move',
key: { kind: 'reference', id: reference.id },
position,
})
const moveError = edit.fieldError('move')
return (
<>
<ul className="space-y-3">
{shown.map((reference) => {
const position = all.indexOf(reference)
const key = keys[position]
return (
<ReferenceTile
key={key}
host="tab"
reference={reference}
position={position}
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}
on={{
toggle: () => tiles.toggle(key),
edit: () => tiles.startEdit(key),
done: tiles.finish,
remove: () => props.onDelete(reference),
move: (to) => move(reference, to),
goTo: (target) => navigate(targetOfKey(target)),
registerLeave: tiles.registerLeave,
}}
/>
)
})}
</ul>
{moveError && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{moveError}
</p>
)}
</>
)
}
@@ -4,7 +4,7 @@ import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import Icon from '@/components/ui/Icon'
import { citationCounts } from '@/editor/references/citations'
import { citersOf } from '@/editor/references/citations'
import {
citedIds,
citingFinding,
@@ -138,8 +138,7 @@ export default function ReferencesPanel(props: Props) {
host="panel"
shown={visibleReferences(all, cited, '')}
all={all}
counts={citationCounts(doc)}
movable={false}
citers={citersOf(doc)}
readOnly={readOnly}
onDelete={(reference) =>
setDeleting({
@@ -0,0 +1,103 @@
import { useEffect, useState } from 'react'
import type { Reference } from '@faunosteo/core-wasm/types'
import { isBlank, nullable } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
/** 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: true when every pending field was applied. */
export type LeaveGuard = () => boolean
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 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, stops at the first refusal, shows it and focuses that field (P22, P22').
* `base` is the DOM id prefix of the tile; `registerLeave` hands `leave` to the library.
*/
export function useReferenceEdit(
reference: Reference,
base: string,
registerLeave: (guard: LeaveGuard | null) => void,
) {
const edit = useEditCommand()
const [drafts, setDraft] = useDrafts(reference)
const key = { kind: 'reference', id: reference.id } as const
const update = (field: string, value: Reference) =>
edit.run(field, {
op: 'update',
key,
element: { kind: 'reference', value },
})
const apply = (current: Reference, field: Field): Reference | null => {
const draft = drafts[field]
if (field === 'citation' && isBlank(draft)) {
edit.reject(field, 'editor.field.required')
return null
}
const next = patched(current, field, draft)
return update(field, next) ? next : null
}
const pending = (current: Reference, field: Field) =>
normalized(field, drafts[field]) !== committedOf(current)[field]
const leave: LeaveGuard = () => {
let current = reference
for (const field of FIELDS.filter((name) => pending(current, name))) {
const next = apply(current, field)
if (!next) {
document.getElementById(`${base}-${field}`)?.focus()
return false
}
current = next
}
return true
}
useEffect(() => {
registerLeave(leave)
return () => registerLeave(null)
})
useEffect(() => {
document.getElementById(`${base}-citation`)?.focus()
}, [base])
return {
edit,
drafts,
setDraft,
commitField: (field: Field) =>
pending(reference, field) && apply(reference, field),
setType: (value: Reference) => update('type', value),
}
}
@@ -0,0 +1,58 @@
import { useRef, useState } from 'react'
import type { Reference } from '@faunosteo/core-wasm/types'
import type { LeaveGuard } 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[] {
const seen = new Map<string, number>()
return all.map((reference) => {
const occurrence = seen.get(reference.id) ?? 0
seen.set(reference.id, occurrence + 1)
return `${reference.id}#${occurrence}`
})
}
/**
* 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).
*/
export function useTileState() {
const [openKeys, setOpenKeys] = useState<ReadonlySet<string>>(() => new Set())
const [editingKey, setEditingKey] = useState<string | null>(null)
const guard = useRef<LeaveGuard | null>(null)
const leave = () => guard.current?.() ?? true
const open = (key: string) => setOpenKeys((prev) => new Set(prev).add(key))
const finish = () => {
if (!leave()) return false
setEditingKey(null)
return true
}
const toggle = (key: string) => {
if (editingKey === key) return void finish()
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()) return
setEditingKey(key)
open(key)
}
return {
openKeys,
editingKey,
toggle,
startEdit,
finish,
reveal: open,
registerLeave: (next: LeaveGuard | null) => {
guard.current = next
},
}
}
@@ -5,6 +5,7 @@ import { useT } from '@/i18n/useT'
/** The fifth tab: the sheet's reference library under its own heading. */
export default function ReferencesTab({
readOnly,
navigate,
focus,
libraryReset,
}: EditorPlaceProps) {
@@ -25,6 +26,7 @@ export default function ReferencesTab({
</h2>
<ReferenceLibrary
readOnly={readOnly}
navigate={navigate}
focus={focus}
resetSignal={libraryReset}
/>
+6
View File
@@ -18,6 +18,9 @@ export type IconName =
| 'lock'
| 'google'
| 'apple'
| 'chevron-right'
| 'chevron-down'
| 'external'
/** Stroke paths on a 24-unit grid; decorative by default (aria-hidden). */
const PATHS: Record<IconName, string> = {
@@ -35,6 +38,9 @@ const PATHS: Record<IconName, string> = {
'eye-off':
'M3 3l18 18M10.6 10.6A3 3 0 0 0 13.4 13.4M9.9 5.2A10.5 10.5 0 0 1 12 5c6 0 10 7 10 7a17 17 0 0 1-3.2 3.9M6.1 6.1A17 17 0 0 0 2 12s4 7 10 7a10 10 0 0 0 4-.8',
check: 'M5 12l5 5L20 7',
'chevron-right': 'M9 6l6 6-6 6',
'chevron-down': 'M6 9l6 6 6-6',
external: 'M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5',
lock: 'M6 11h12v9H6zM8 11V8a4 4 0 0 1 8 0v3',
alert: 'M12 9v4M12 17h.01M10.3 3.9L2.8 17a2 2 0 0 0 1.7 3h15a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z',
google: