feat(editor): search, sort, count and add in the Références tab
Search (citation, DOI, URL) with « Effacer la recherche » and Escape;
« Trier par » sheet order, citation (locale collator), citation count,
type (business order); every sort stable on stored order, display only:
document, stored order, ids and history unchanged (unit + e2e). Count
« {n} références » / « {n} sur {total} » counts matching references
only. « Monter » / « Descendre » only in sheet order without search
(A1). « Ajouter une référence » resets search and sort and appends a
draft tile in edit; a tile in edit stays pinned while sorted or
searched; tile state pruned of absent ids. Reset path ready for « Tout
afficher » (R2.4).
Gates: typecheck, lint, test:run (app 1452), build, e2e:ui 251;
e2e:shell 16 specs on db:sandbox (editor-equine never listed): 115
passed / 102 skipped / 2 failed: editor-structures (test-side, fixed,
rerun with editor-references 12 passed / 11 skipped) and admin.spec A0
« Target crashed » during axe on the rights screen (not R2: that
screen renders every grant, 1 282 accumulated e2e fixtures; reported as
an open risk); full-row guard: no pre-existing row changed in any table.
## R-24 (removed or rewritten assertions)
| file | old | new |
|---|---|---|
| editor-references-tab.test.tsx | `#tab-reference-new-citation` present on load | null until « Ajouter une référence » |
| same | no match text « Aucune référence ne correspond. » | notice « Aucune référence ne contient « zzz ». » |
| same | add: form always visible, add clears the search, `getByText('Nouvelle source')` | click « Ajouter une référence » first; new tile header open, focused, search empty, 4 tiles |
| same | « a refused add keeps the search » | REMOVED (P24: add resets the search at once); replaced by « draft opens with citation focused, refused add keeps the draft, no write » |
| editor-tabs-lists.test.tsx | add form directly | click « Ajouter une référence » before the form assertions (same assertions after) |
| editor-keep-alive.test.tsx | form survives tab round trip | same, after opening the draft |
| editor-no-loss.test.tsx | reference form keeps typed text | same, after opening the draft |
| e2e editor-shell.spec (2), editor-shell-crossing.spec, editor-structures.spec | fill `#tab-reference-new-*` directly; `getByText(citation)` visible | open the draft first; structures asserts the new header is focused |
| e2e editor-references.spec keyboard walk | focus search, Tab reaches header 0 | focus « Ajouter une référence » (search, sort, add precede the headers) |
Other readers of `editor.reference.add`/new ids: grep of src, tests, e2e incl. editor-equine found none left unlisted. editor-equine is not affected ("updated, not run": nothing to update).
## i18n (fr / en)
Added: `editor.references.add` Ajouter une référence / Add a reference; `add_help` Type et citation obligatoires. / Type and citation required.; `clear_search` Effacer la recherche / Clear the search; `sort_by` Trier par / Sort by; `sort.sheet|citation|count|type` Ordre de la fiche, Citation (A → Z), Nombre de citations, Type / Sheet order, Citation (A → Z), Number of citations, Type; `count_one|other` {count} référence(s) / reference(s); `count_of_one|other` {count} référence(s) sur {total} / {count} reference(s) of {total}; `reorder_hint` Pour réorganiser, affichez l'ordre de la fiche sans recherche. / To reorder, show the sheet order without a search.; `no_result` Aucune référence ne contient « {q} ». / No reference contains “{q}”.; `no_result_scope` La recherche porte sur la citation, le DOI et l'URL. / The search covers the citation, the DOI and the URL. (REVUE sentence split in two keys so the first half is bold).
Changed: none. Removed: none (`editor.references.no_match` kept, the panel's EmptyLine still uses it).
This commit is contained in:
1 parent
c21995b3fb
commit
3baac4dbb5
26 files changed
+1544
-219
No files matched your search
@@ -0,0 +1,120 @@
|
||||
import { useEffect, useState } 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
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 }: 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)
|
||||
}
|
||||
return (
|
||||
<section
|
||||
aria-label={t('editor.reference.new')}
|
||||
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>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.references.add_help')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import Button from '@/components/ui/Button'
|
||||
import Icon from '@/components/ui/Icon'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** Board 24 B: nothing contains the search; the notice offers to clear it. */
|
||||
export default function NoResult({
|
||||
query,
|
||||
onClear,
|
||||
}: {
|
||||
query: string
|
||||
onClear: () => void
|
||||
}) {
|
||||
const t = useT()
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
className="space-y-2 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-strong)] p-3 text-sm"
|
||||
>
|
||||
<p>
|
||||
<strong>
|
||||
{t('editor.references.no_result').replace('{q}', query.trim())}
|
||||
</strong>{' '}
|
||||
{t('editor.references.no_result_scope')}
|
||||
</p>
|
||||
<Button type="button" variant="secondary" size="sm" onClick={onClear}>
|
||||
<Icon name="close" size={14} className="mr-1" />
|
||||
{t('editor.references.clear_search')}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
import { useState } 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 { isBlank, nullable } from '@/editor/sheetDocument'
|
||||
import { useEditCommand } from '@/editor/useEditCommand'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { REFERENCE_TYPES, type ReferenceHost } from './referenceTypes'
|
||||
|
||||
const EMPTY = { type: '', citation: '', url: '', doi: '' }
|
||||
|
||||
/**
|
||||
* Adds a reference: the type and the citation are required, URL and DOI optional.
|
||||
* `onAdded` runs after a successful add, so the list can show the new reference.
|
||||
*/
|
||||
export default function ReferenceForm({
|
||||
host,
|
||||
onAdded,
|
||||
}: {
|
||||
host: ReferenceHost
|
||||
onAdded?: () => void
|
||||
}) {
|
||||
const t = useT()
|
||||
const edit = useEditCommand()
|
||||
const [form, setForm] = useState(EMPTY)
|
||||
const set = (patch: Partial<typeof EMPTY>) => setForm({ ...form, ...patch })
|
||||
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
|
||||
}
|
||||
const added = edit.runNew('form', 'ref', (id) => ({
|
||||
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) return
|
||||
setForm(EMPTY)
|
||||
onAdded?.()
|
||||
}
|
||||
return (
|
||||
<div className="space-y-2 rounded-lg border border-dashed border-[var(--color-border)] p-3">
|
||||
<p className="text-sm font-medium">{t('editor.reference.new')}</p>
|
||||
<div className="grid gap-3">
|
||||
<SelectField
|
||||
id={`${host}-reference-new-type`}
|
||||
label={t('editor.reference.type')}
|
||||
value={form.type}
|
||||
options={options}
|
||||
onCommit={(type) => set({ type })}
|
||||
/>
|
||||
<DraftField
|
||||
id={`${host}-reference-new-citation`}
|
||||
label={t('editor.reference.citation')}
|
||||
value={form.citation}
|
||||
onChange={(citation) => set({ citation })}
|
||||
multiline
|
||||
/>
|
||||
<DraftField
|
||||
id={`${host}-reference-new-url`}
|
||||
label={t('editor.reference.url')}
|
||||
value={form.url}
|
||||
onChange={(url) => set({ url })}
|
||||
/>
|
||||
<DraftField
|
||||
id={`${host}-reference-new-doi`}
|
||||
label={t('editor.reference.doi')}
|
||||
value={form.doi}
|
||||
onChange={(doi) => set({ doi })}
|
||||
/>
|
||||
</div>
|
||||
{edit.fieldError('form') && (
|
||||
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
||||
{edit.fieldError('form')}
|
||||
</p>
|
||||
)}
|
||||
<ActionButton readOnly={false} variant="secondary" onClick={create}>
|
||||
{t('editor.reference.add')}
|
||||
</ActionButton>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,113 +1,77 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { ElementKey, Reference } from '@faunosteo/core-wasm/types'
|
||||
import { useRef, useState } from 'react'
|
||||
import DeleteDialog, {
|
||||
type DeleteTarget,
|
||||
} from '@/components/editor/DeleteDialog'
|
||||
import EditOnly from '@/components/editor/EditOnly'
|
||||
import Input from '@/components/ui/Input'
|
||||
import {
|
||||
focusRow,
|
||||
useFocusRequest,
|
||||
type FocusRequest,
|
||||
} from '@/editor/focusRequest'
|
||||
import type { FocusRequest } from '@/editor/focusRequest'
|
||||
import type { EditorTarget } from '@/editor/navigation'
|
||||
import { citersOf } from '@/editor/references/citations'
|
||||
import { visibleReferences } from '@/editor/references/filter'
|
||||
import { useSheetDocument } from '@/editor/sheetDocument'
|
||||
import { isSheetView } from '@/editor/references/view'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import ReferenceForm from './ReferenceForm'
|
||||
import NewReferenceTile from './NewReferenceTile'
|
||||
import NoResult from './NoResult'
|
||||
import { EmptyLine } from './ReferenceList'
|
||||
import ReferenceTiles from './ReferenceTiles'
|
||||
import { tileKeys, useTileState } from './useTileState'
|
||||
import ReferenceToolbar from './ReferenceToolbar'
|
||||
import { useReferenceActions, useReferenceLibrary } from './useReferenceLibrary'
|
||||
|
||||
interface Props {
|
||||
readOnly: boolean
|
||||
/** « Aller à » a citing finding or family. */
|
||||
navigate: (target: EditorTarget) => void
|
||||
focus?: FocusRequest
|
||||
/** Bumped by « Tout afficher »: the search is emptied once per bump. */
|
||||
/** Bumped by « Tout afficher »: the search and the sort are reset once per bump. */
|
||||
resetSignal?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* « 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,
|
||||
actions: { clearQuery: () => void; reveal: (key: ElementKey) => void },
|
||||
) {
|
||||
const [late, setLate] = useState<ElementKey | null>(null)
|
||||
useEffect(() => {
|
||||
if (late === null) return
|
||||
focusRow(late)
|
||||
setLate(null)
|
||||
}, [late])
|
||||
useFocusRequest(focus, (target) => {
|
||||
if (target.key === null) return 'none'
|
||||
actions.reveal(target.key)
|
||||
if (query === '') return focusRow(target.key) ? 'found' : 'none'
|
||||
actions.clearQuery()
|
||||
setLate(target.key)
|
||||
return 'found'
|
||||
})
|
||||
}
|
||||
|
||||
/** The search text, emptied each time `resetSignal` changes (the tab stays mounted). */
|
||||
function useSearchQuery(resetSignal: number) {
|
||||
const [query, setQuery] = useState('')
|
||||
const [seen, setSeen] = useState(resetSignal)
|
||||
if (seen !== resetSignal) {
|
||||
setSeen(resetSignal)
|
||||
setQuery('')
|
||||
}
|
||||
return [query, setQuery] as const
|
||||
}
|
||||
|
||||
/**
|
||||
* 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-`).
|
||||
* The sheet's bibliography: toolbar (search, sort, count, add), one collapsible tile per
|
||||
* reference, the draft tile and the delete dialog. Lives in the Références tab (ids
|
||||
* prefixed `tab-`).
|
||||
*/
|
||||
export default function ReferenceLibrary(props: Props) {
|
||||
const { readOnly, navigate, focus, resetSignal = 0 } = props
|
||||
const t = useT()
|
||||
const doc = useSheetDocument()
|
||||
const tiles = useTileState()
|
||||
const [query, setQuery] = useSearchQuery(resetSignal)
|
||||
const lib = useReferenceLibrary(readOnly, resetSignal)
|
||||
const searchRef = useRef<HTMLInputElement>(null)
|
||||
const act = useReferenceActions(lib, focus, searchRef)
|
||||
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
|
||||
const all: 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()
|
||||
const { all, shown } = lib
|
||||
const sheetView = isSheetView(shown.view)
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Input
|
||||
type="search"
|
||||
aria-label={t('editor.references.search')}
|
||||
placeholder={t('editor.references.search')}
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
<ReferenceToolbar
|
||||
query={shown.view.query}
|
||||
onQuery={(query) => shown.update({ query })}
|
||||
onClear={act.clearSearch}
|
||||
searchRef={searchRef}
|
||||
sort={shown.view.sort}
|
||||
onSort={(sort) => shown.update({ sort })}
|
||||
shown={shown.matchCount}
|
||||
total={all.length}
|
||||
canAdd={!readOnly}
|
||||
onAdd={act.startAdd}
|
||||
/>
|
||||
{doc && (
|
||||
{lib.loaded && (
|
||||
<>
|
||||
<EmptyLine total={all.length} shown={shown.length} />
|
||||
{all.length === 0 && <EmptyLine />}
|
||||
{all.length > 0 && shown.matchCount === 0 && (
|
||||
<NoResult query={shown.view.query} onClear={act.clearSearch} />
|
||||
)}
|
||||
{!readOnly && !sheetView && shown.positions.length > 0 && (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.references.reorder_hint')}
|
||||
</p>
|
||||
)}
|
||||
<ReferenceTiles
|
||||
shown={shown}
|
||||
positions={shown.positions}
|
||||
all={all}
|
||||
keys={keys}
|
||||
citers={citers}
|
||||
tiles={tiles}
|
||||
keys={lib.keys}
|
||||
citers={lib.citers}
|
||||
tiles={lib.tiles}
|
||||
readOnly={readOnly}
|
||||
movable={query.trim() === ''}
|
||||
movable={sheetView}
|
||||
navigate={navigate}
|
||||
onEdit={act.edit}
|
||||
onDelete={(reference) =>
|
||||
setDeleting({
|
||||
key: { kind: 'reference', id: reference.id },
|
||||
@@ -116,7 +80,9 @@ export default function ReferenceLibrary(props: Props) {
|
||||
}
|
||||
/>
|
||||
<EditOnly readOnly={readOnly}>
|
||||
<ReferenceForm host="tab" onAdded={() => setQuery('')} />
|
||||
{act.draft !== null && (
|
||||
<NewReferenceTile focusSerial={act.draft} onAdded={act.added} />
|
||||
)}
|
||||
</EditOnly>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -35,11 +35,12 @@ export function ReferenceList({ shown, all, citers, ...rest }: ListProps) {
|
||||
)
|
||||
}
|
||||
|
||||
/** The empty line: no reference at all, or none that matches. */
|
||||
export function EmptyLine({ total, shown }: { total: number; shown: number }) {
|
||||
/** The empty line: the sheet has no reference at all. */
|
||||
export function EmptyLine() {
|
||||
const t = useT()
|
||||
if (shown > 0) return null
|
||||
const key =
|
||||
total === 0 ? 'editor.reference.empty' : 'editor.references.no_match'
|
||||
return <p className="text-sm text-[var(--color-ink-muted)]">{t(key)}</p>
|
||||
return (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.reference.empty')}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
@@ -6,8 +6,8 @@ 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[]
|
||||
/** The tiles to list, in display order, as positions in the whole bibliography `all`. */
|
||||
positions: readonly number[]
|
||||
all: readonly Reference[]
|
||||
/** One key per position of `all` (`tileKeys`). */
|
||||
keys: readonly string[]
|
||||
@@ -16,12 +16,13 @@ interface Props {
|
||||
readOnly: boolean
|
||||
movable: boolean
|
||||
navigate: (target: EditorTarget) => void
|
||||
onEdit: (position: number) => 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 { positions, all, keys, citers, tiles, navigate } = props
|
||||
const edit = useEditCommand()
|
||||
const move = (reference: Reference, position: number) =>
|
||||
edit.run('move', {
|
||||
@@ -33,8 +34,8 @@ export default function ReferenceTiles(props: Props) {
|
||||
return (
|
||||
<>
|
||||
<ul className="space-y-3">
|
||||
{shown.map((reference) => {
|
||||
const position = all.indexOf(reference)
|
||||
{positions.map((position) => {
|
||||
const reference = all[position]
|
||||
const key = keys[position]
|
||||
return (
|
||||
<ReferenceTile
|
||||
@@ -50,7 +51,7 @@ export default function ReferenceTiles(props: Props) {
|
||||
movable={props.movable}
|
||||
on={{
|
||||
toggle: () => tiles.toggle(key),
|
||||
edit: () => tiles.startEdit(key),
|
||||
edit: () => props.onEdit(position),
|
||||
done: tiles.finish,
|
||||
remove: () => props.onDelete(reference),
|
||||
move: (to) => move(reference, to),
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import type { KeyboardEvent, RefObject } from 'react'
|
||||
import ActionButton from '@/components/editor/fields/ActionButton'
|
||||
import Icon from '@/components/ui/Icon'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Select from '@/components/ui/Select'
|
||||
import { usePlural } from '@/editor/plural'
|
||||
import { REFERENCE_SORTS, type ReferenceSort } from '@/editor/references/sort'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
interface Props {
|
||||
query: string
|
||||
onQuery: (query: string) => void
|
||||
/** Empties the search and gives the focus back to its field. */
|
||||
onClear: () => void
|
||||
searchRef: RefObject<HTMLInputElement | null>
|
||||
sort: ReferenceSort
|
||||
onSort: (sort: ReferenceSort) => void
|
||||
shown: number
|
||||
total: number
|
||||
/** « Ajouter une référence »: absent while the editor is read-only. */
|
||||
canAdd: boolean
|
||||
onAdd: () => void
|
||||
}
|
||||
|
||||
/** The count line: « {n} références » or « {n} références sur {total} ». */
|
||||
function CountLine({ shown, total }: { shown: number; total: number }) {
|
||||
const plural = usePlural()
|
||||
const key = shown === total ? 'count' : 'count_of'
|
||||
const text = plural(`editor.references.${key}`, shown)
|
||||
return (
|
||||
<p aria-live="polite" className="text-sm text-[var(--color-ink-muted)]">
|
||||
{text.replace('{total}', String(total))}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
/** Search with its clear button, the sort, the count and the add button (boards 23, 24). */
|
||||
export default function ReferenceToolbar(props: Props) {
|
||||
const { query, onQuery, onClear, searchRef, sort, onSort } = props
|
||||
const t = useT()
|
||||
// P12: Escape empties a non-empty search; an empty one lets the event bubble (A5).
|
||||
const escape = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'Escape' || query === '') return
|
||||
event.preventDefault()
|
||||
onClear()
|
||||
}
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
|
||||
<div className="relative flex-1">
|
||||
<Input
|
||||
ref={searchRef}
|
||||
type="search"
|
||||
aria-label={t('editor.references.search')}
|
||||
placeholder={t('editor.references.search')}
|
||||
value={query}
|
||||
onChange={(event) => onQuery(event.target.value)}
|
||||
onKeyDown={escape}
|
||||
className="pr-11 max-sm:h-11 [&::-webkit-search-cancel-button]:appearance-none"
|
||||
/>
|
||||
{query !== '' && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('editor.references.clear_search')}
|
||||
onClick={onClear}
|
||||
className="absolute right-0 top-0 flex size-10 max-sm:size-11 items-center justify-center rounded-lg text-[var(--color-ink-muted)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
|
||||
>
|
||||
<Icon name="close" size={16} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
|
||||
<label htmlFor="tab-reference-sort" className="text-sm">
|
||||
{t('editor.references.sort_by')}
|
||||
</label>
|
||||
<Select
|
||||
id="tab-reference-sort"
|
||||
value={sort}
|
||||
onChange={(event) => onSort(event.target.value as ReferenceSort)}
|
||||
className="max-sm:h-11 sm:w-52"
|
||||
>
|
||||
{REFERENCE_SORTS.map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{t(`editor.references.sort.${value}`)}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<CountLine shown={props.shown} total={props.total} />
|
||||
<ActionButton
|
||||
readOnly={!props.canAdd}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={props.onAdd}
|
||||
>
|
||||
{t('editor.references.add')}
|
||||
</ActionButton>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,13 +1,4 @@
|
||||
import type { ReferenceType } from '@faunosteo/core-wasm/types'
|
||||
|
||||
export const REFERENCE_TYPES: readonly ReferenceType[] = [
|
||||
'book',
|
||||
'journal',
|
||||
'standard',
|
||||
'legal',
|
||||
'web',
|
||||
'manual',
|
||||
]
|
||||
export { REFERENCE_TYPES } from '@/editor/references/referenceTypes'
|
||||
|
||||
/** Where reference cards are shown: the Références tab or a finding's citations panel. */
|
||||
export type ReferenceHost = 'tab' | 'panel'
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useEffect, useState, type RefObject } from 'react'
|
||||
import type { ElementKey, Reference } from '@faunosteo/core-wasm/types'
|
||||
import {
|
||||
focusRow,
|
||||
useFocusRequest,
|
||||
type FocusRequest,
|
||||
} from '@/editor/focusRequest'
|
||||
import { citersOf } from '@/editor/references/citations'
|
||||
import { referenceMatches } from '@/editor/references/filter'
|
||||
import { useSheetDocument } from '@/editor/sheetDocument'
|
||||
import { tileKeys, useTileState } from './useTileState'
|
||||
import { useReferenceView } from './useReferenceView'
|
||||
|
||||
const NO_CITERS = new Map<string, never[]>()
|
||||
|
||||
/** The document's references with the tab's tile state and display order. */
|
||||
export function useReferenceLibrary(readOnly: boolean, resetSignal: number) {
|
||||
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
|
||||
const editedAt = readOnly ? -1 : keys.indexOf(tiles.editingKey ?? '')
|
||||
const shown = useReferenceView(all, citers, editedAt, resetSignal)
|
||||
return { loaded: doc !== null, all, keys, tiles, citers, shown }
|
||||
}
|
||||
export type ReferenceLibraryState = ReturnType<typeof useReferenceLibrary>
|
||||
|
||||
/** Focuses a row after the commit that shows it (the request ran before it rendered). */
|
||||
function useLateFocus() {
|
||||
const [late, setLate] = useState<ElementKey | null>(null)
|
||||
useEffect(() => {
|
||||
if (late === null) return
|
||||
focusRow(late)
|
||||
setLate(null)
|
||||
}, [late])
|
||||
return setLate
|
||||
}
|
||||
|
||||
const positionOf = (all: readonly Reference[], key: ElementKey) =>
|
||||
all.findIndex((r) => key.kind === 'reference' && r.id === key.id)
|
||||
|
||||
/**
|
||||
* « 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).
|
||||
*/
|
||||
function useReferenceFocus(
|
||||
focus: FocusRequest | undefined,
|
||||
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 focusRow(target.key) ? 'found' : 'none'
|
||||
}
|
||||
shown.update({ query: '' })
|
||||
later(target.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>,
|
||||
) {
|
||||
const { keys, tiles, shown } = lib
|
||||
const [draft, setDraft] = useState<number | null>(null)
|
||||
const later = useLateFocus()
|
||||
useReferenceFocus(focus, lib, later)
|
||||
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()
|
||||
setDraft((serial) => (serial ?? 0) + 1)
|
||||
},
|
||||
added: (id: string) => {
|
||||
setDraft(null)
|
||||
tiles.reveal(`${id}#0`)
|
||||
later({ kind: 'reference', id })
|
||||
},
|
||||
edit: (position: number) => {
|
||||
if (tiles.startEdit(keys[position])) shown.markEdited(position)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useState } from 'react'
|
||||
import { referenceMatches } from '@/editor/references/filter'
|
||||
import type { Reference } from '@faunosteo/core-wasm/types'
|
||||
import type { CiterItem } from '@/editor/references/citations'
|
||||
import {
|
||||
isSheetView,
|
||||
shownPositions,
|
||||
type ReferenceView,
|
||||
} from '@/editor/references/view'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
const INITIAL: ReferenceView = { query: '', sort: 'sheet' }
|
||||
|
||||
/**
|
||||
* 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 and the sort once per bump; the tab stays mounted (A2).
|
||||
* `editedAt` is the position of the tile in edit: while the view is not the sheet view it
|
||||
* keeps the index it had when the view last changed (P23).
|
||||
*/
|
||||
export function useReferenceView(
|
||||
all: readonly Reference[],
|
||||
citers: ReadonlyMap<string, readonly CiterItem[]>,
|
||||
editedAt: number,
|
||||
resetSignal: number,
|
||||
) {
|
||||
const locale = useLocaleStore((state) => state.locale)
|
||||
const [view, setView] = useState(INITIAL)
|
||||
const [seen, setSeen] = useState(resetSignal)
|
||||
const [pinIndex, setPinIndex] = useState(0)
|
||||
if (seen !== resetSignal) {
|
||||
setSeen(resetSignal)
|
||||
setView(INITIAL)
|
||||
}
|
||||
const pin =
|
||||
editedAt >= 0 && !isSheetView(view)
|
||||
? { position: editedAt, index: pinIndex }
|
||||
: 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
|
||||
return {
|
||||
view,
|
||||
positions,
|
||||
matchCount,
|
||||
/** A new search or sort: the tile in edit stays where it is shown now. */
|
||||
update: (patch: Partial<ReferenceView>) => {
|
||||
setPinIndex(positions.indexOf(editedAt))
|
||||
setView((current) => ({ ...current, ...patch }))
|
||||
},
|
||||
reset: () => setView(INITIAL),
|
||||
/** The tile at `position` enters edit: remember where it is shown. */
|
||||
markEdited: (position: number) => setPinIndex(positions.indexOf(position)),
|
||||
}
|
||||
}
|
||||
@@ -18,11 +18,20 @@ export function tileKeys(all: readonly Reference[]): 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).
|
||||
* 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').
|
||||
*/
|
||||
export function useTileState() {
|
||||
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)
|
||||
const leave = () => guard.current?.() ?? true
|
||||
const open = (key: string) => setOpenKeys((prev) => new Set(prev).add(key))
|
||||
@@ -40,9 +49,10 @@ export function useTileState() {
|
||||
})
|
||||
}
|
||||
const startEdit = (key: string) => {
|
||||
if (editingKey !== null && editingKey !== key && !leave()) return
|
||||
if (editingKey !== null && editingKey !== key && !leave()) return false
|
||||
setEditingKey(key)
|
||||
open(key)
|
||||
return true
|
||||
}
|
||||
return {
|
||||
openKeys,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { ReferenceType } from '@faunosteo/core-wasm/types'
|
||||
|
||||
/** The reference types in business order (the « Type » sort and the pickers). */
|
||||
export const REFERENCE_TYPES: readonly ReferenceType[] = [
|
||||
'book',
|
||||
'journal',
|
||||
'standard',
|
||||
'legal',
|
||||
'web',
|
||||
'manual',
|
||||
]
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { Reference } from '@faunosteo/core-wasm/types'
|
||||
import { REFERENCE_TYPES } from './referenceTypes'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
|
||||
/** The four display orders of the Références tab; `sheet` is the stored order. */
|
||||
export const REFERENCE_SORTS = ['sheet', 'citation', 'count', 'type'] as const
|
||||
export type ReferenceSort = (typeof REFERENCE_SORTS)[number]
|
||||
|
||||
export interface SortContext {
|
||||
locale: Locale
|
||||
/** How many findings and families cite each reference id. */
|
||||
citedCount: (id: string) => number
|
||||
}
|
||||
|
||||
/** A type outside the list sorts after the listed ones. */
|
||||
const typeRank = (reference: Reference) => {
|
||||
const rank = REFERENCE_TYPES.indexOf(reference.type)
|
||||
return rank < 0 ? REFERENCE_TYPES.length : rank
|
||||
}
|
||||
|
||||
function comparator(
|
||||
references: readonly Reference[],
|
||||
sort: ReferenceSort,
|
||||
context: SortContext,
|
||||
): (a: number, b: number) => number {
|
||||
const collator = new Intl.Collator(context.locale, {
|
||||
sensitivity: 'base',
|
||||
numeric: true,
|
||||
})
|
||||
const count = (at: number) => context.citedCount(references[at].id)
|
||||
switch (sort) {
|
||||
case 'citation':
|
||||
return (a, b) =>
|
||||
collator.compare(references[a].citation, references[b].citation)
|
||||
case 'count':
|
||||
return (a, b) => count(b) - count(a)
|
||||
case 'type':
|
||||
return (a, b) => typeRank(references[a]) - typeRank(references[b])
|
||||
case 'sheet':
|
||||
return () => 0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The positions (indexes into `references`, P31) in display order. Display only: the
|
||||
* inputs are not touched and a new array is returned. Equal keys keep the stored order,
|
||||
* so the result never depends on the order of `positions`.
|
||||
*/
|
||||
export function sortReferenceIds(
|
||||
references: readonly Reference[],
|
||||
positions: readonly number[],
|
||||
sort: ReferenceSort,
|
||||
context: SortContext,
|
||||
): number[] {
|
||||
const compare = comparator(references, sort, context)
|
||||
return [...positions].sort((a, b) => compare(a, b) || a - b)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { Reference } from '@faunosteo/core-wasm/types'
|
||||
import { referenceMatches } from './filter'
|
||||
import { sortReferenceIds, type ReferenceSort, type SortContext } from './sort'
|
||||
|
||||
export interface ReferenceView {
|
||||
query: string
|
||||
sort: ReferenceSort
|
||||
}
|
||||
|
||||
/** Stored order, no search: the only view where ↑ / ↓ mean something (A1). */
|
||||
export const isSheetView = (view: ReferenceView) =>
|
||||
view.sort === 'sheet' && view.query.trim() === ''
|
||||
|
||||
/**
|
||||
* The tile in edit, kept in the shown set at `index` whatever the search or the sort
|
||||
* (P23); only worth passing when the view is not the sheet view.
|
||||
*/
|
||||
export interface Pin {
|
||||
position: number
|
||||
index: number
|
||||
}
|
||||
|
||||
/** The positions to show: the search, then the sort, then the pinned tile put back. */
|
||||
export function shownPositions(
|
||||
references: readonly Reference[],
|
||||
view: ReferenceView,
|
||||
context: SortContext,
|
||||
pin: Pin | null,
|
||||
): number[] {
|
||||
const matching = references.flatMap((reference, position) =>
|
||||
referenceMatches(reference, view.query) ? [position] : [],
|
||||
)
|
||||
const sorted = sortReferenceIds(references, matching, view.sort, context)
|
||||
if (pin === null) return sorted
|
||||
const rest = sorted.filter((position) => position !== pin.position)
|
||||
rest.splice(Math.min(pin.index, rest.length), 0, pin.position)
|
||||
return rest
|
||||
}
|
||||
+15
-1
@@ -1232,7 +1232,6 @@ export const en: Dict = {
|
||||
'editor.references.search': 'Search a reference',
|
||||
'editor.references.cited_by': 'Cited by « {name} » ({count})',
|
||||
'editor.references.show_all': 'Show all ({count})',
|
||||
'editor.references.no_match': 'No reference matches.',
|
||||
'editor.references.cited_one': 'Cited {count} time',
|
||||
'editor.references.cited_other': 'Cited {count} times',
|
||||
'editor.references.uncited': 'Not cited',
|
||||
@@ -1249,6 +1248,21 @@ export const en: Dict = {
|
||||
'editor.references.none_url': 'None',
|
||||
'editor.references.new_tab': '(new tab)',
|
||||
'editor.references.delete_hint': "To delete this reference, first remove each of its citations: “Go to”, then “Remove” in the finding's or family's detail.",
|
||||
'editor.references.add': 'Add a reference',
|
||||
'editor.references.add_help': 'Type and citation required.',
|
||||
'editor.references.clear_search': 'Clear the search',
|
||||
'editor.references.sort_by': 'Sort by',
|
||||
'editor.references.sort.sheet': 'Sheet order',
|
||||
'editor.references.sort.citation': 'Citation (A → Z)',
|
||||
'editor.references.sort.count': 'Number of citations',
|
||||
'editor.references.sort.type': 'Type',
|
||||
'editor.references.count_one': '{count} reference',
|
||||
'editor.references.count_other': '{count} references',
|
||||
'editor.references.count_of_one': '{count} reference of {total}',
|
||||
'editor.references.count_of_other': '{count} references of {total}',
|
||||
'editor.references.reorder_hint': 'To reorder, show the sheet order without a search.',
|
||||
'editor.references.no_result': 'No reference contains “{q}”.',
|
||||
'editor.references.no_result_scope': 'The search covers the citation, the DOI and the URL.',
|
||||
'editor.findings.references_open_one': '{count} reference',
|
||||
'editor.findings.references_open_other': '{count} references',
|
||||
'editor.draft.loading': 'Loading the draft…',
|
||||
|
||||
+15
-1
@@ -1263,7 +1263,6 @@ export const fr: Dict = {
|
||||
'editor.references.search': 'Rechercher une référence',
|
||||
'editor.references.cited_by': 'Citées par « {name} » ({count})',
|
||||
'editor.references.show_all': 'Tout afficher ({count})',
|
||||
'editor.references.no_match': 'Aucune référence ne correspond.',
|
||||
'editor.references.cited_one': 'Citée {count} fois',
|
||||
'editor.references.cited_other': 'Citée {count} fois',
|
||||
'editor.references.uncited': 'Non citée',
|
||||
@@ -1280,6 +1279,21 @@ export const fr: Dict = {
|
||||
'editor.references.none_url': 'Aucune',
|
||||
'editor.references.new_tab': '(nouvel onglet)',
|
||||
'editor.references.delete_hint': 'Pour supprimer cette référence, retirez d\'abord chacune de ses citations : « Aller à », puis « Retirer » dans le détail du constat ou de la famille.',
|
||||
'editor.references.add': 'Ajouter une référence',
|
||||
'editor.references.add_help': 'Type et citation obligatoires.',
|
||||
'editor.references.clear_search': 'Effacer la recherche',
|
||||
'editor.references.sort_by': 'Trier par',
|
||||
'editor.references.sort.sheet': 'Ordre de la fiche',
|
||||
'editor.references.sort.citation': 'Citation (A → Z)',
|
||||
'editor.references.sort.count': 'Nombre de citations',
|
||||
'editor.references.sort.type': 'Type',
|
||||
'editor.references.count_one': '{count} référence',
|
||||
'editor.references.count_other': '{count} références',
|
||||
'editor.references.count_of_one': '{count} référence sur {total}',
|
||||
'editor.references.count_of_other': '{count} références sur {total}',
|
||||
'editor.references.reorder_hint': 'Pour réorganiser, affichez l\'ordre de la fiche sans recherche.',
|
||||
'editor.references.no_result': 'Aucune référence ne contient « {q} ».',
|
||||
'editor.references.no_result_scope': 'La recherche porte sur la citation, le DOI et l\'URL.',
|
||||
'editor.findings.references_open_one': '{count} référence',
|
||||
'editor.findings.references_open_other': '{count} références',
|
||||
'editor.draft.loading': 'Chargement du brouillon…',
|
||||
|
||||
Reference in new issue
Block a user