Files
faunosteo/apps/app/src/components/editor/references/useReferenceLibrary.ts
T

178 lines
5.9 KiB
TypeScript

import { useEffect, useState, type RefObject } from 'react'
import type { ElementKey, Reference } from '@faunosteo/core-wasm/types'
import {
focusRow,
focusRowLater,
useFocusRequest,
type FocusRequest,
} from '@/editor/focusRequest'
import { citersOf } from '@/editor/references/citations'
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'
const NO_CITERS = new Map<string, never[]>()
/**
* 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(
bibliography,
useEditedKey(layer),
resetSignal,
filter.cited,
)
return { ...bibliography, shown, finding: filter.finding }
}
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)
type Show = (key: ElementKey) => 'found' | 'none'
/** Whether the finding filter or the search hides `reference` from the list. */
function hiddenBy(lib: ReferenceLibraryState, reference: Reference) {
const cited = lib.finding && citedIds(lib.finding)
return {
filtered: !!cited && !cited.includes(reference.id),
matches: referenceMatches(reference, lib.shown.view.query),
}
}
/**
* 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 useShowReference(
lib: ReferenceLibraryState,
layer: ReferenceLayer,
): Show {
const later = useLateFocus()
return (key) => {
const at = positionOf(lib.all, key)
if (at < 0) return 'none'
lib.tiles.reveal(lib.keys[at])
const hidden = hiddenBy(lib, lib.all[at])
if (hidden.matches && !hidden.filtered) {
return focusRowLater(key) ? 'found' : 'none'
}
if (hidden.filtered) layer.clearFilter()
if (!hidden.matches) lib.shown.update({ query: '' })
later(key)
return 'found'
}
}
/** « 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 », until it is gone, or
* until the user leaves the References tab (it would be stale on their return).
*/
function useAddedNotice(
all: readonly Reference[],
added: ReferenceLayer['added'],
show: Show,
) {
const [dismissed, setDismissed] = useState(0)
const visible = usePlaceVisible()
const reference = added && all.find((r) => r.id === added.id)
if (added && !visible && dismissed !== added.serial) {
setDismissed(added.serial)
}
if (!added || !reference || added.serial === dismissed) return null
return {
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),
}
}