Files
faunosteo/apps/app/src/components/editor/tabs/FindingsTab.tsx
T

364 lines
12 KiB
TypeScript

import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import AddBar from '@/components/editor/findings/AddBar'
import FindingDialog from '@/components/editor/findings/FindingDialog'
import type { PendingFinding } from '@/components/editor/findings/FindingCreateForm'
import FindingTree from '@/components/editor/findings/FindingTree'
import { landAfterModalsClosed } from '@/components/ui/afterModalsClosed'
import {
buildItems,
createdItemId,
createdKey,
fallbackAfterRemoval,
isUnder,
itemForKey,
sameKey,
visibleItems,
type FindingItem,
type FindingKind,
} from '@/editor/findings/tree'
import { useFocusRequest, visibleElement } from '@/editor/focusRequest'
import { useEditorStore } from '@/editor/state/editorStore'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { EditorPlaceProps, FindingLayer } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { usePlaceVisible } from '@/lib/placeVisibility'
import { useLocaleStore } from '@/state/localeStore'
/** The tree as the store holds it right now (a commit is already in). */
function currentItems(): FindingItem[] {
try {
const doc = JSON.parse(useEditorStore.getState().documentText)
return buildItems(doc)
} catch {
return []
}
}
const ADD_BUTTON: Record<string, string> = {
zone: 'finding-add-zone',
category: 'finding-add-category',
node: 'finding-add-node',
}
/** The deletion flow: the target, the item to select after it, and the focus left behind. */
function useFindingDeletion(
items: readonly FindingItem[],
selectedId: string | null,
actions: {
select: (id: string | null) => void
focusItem: (id: string | null) => void
closeLayer: () => void
},
) {
const locale = useLocaleStore((s) => s.locale)
const [ask, setAsk] = useState<{
target: DeleteTarget
fallback: string | null
} | null>(null)
const askDelete = (item: FindingItem) => {
const target = { key: item.key, label: item.name[locale] }
setAsk({ target, fallback: fallbackAfterRemoval(items, item) })
}
// The element is gone: its dialog closes in the same move, by the pop of its entry (a
// Back step that was taken, never a dead one left behind) and the focus lands on the nearest row once every dialog is closed, unless a newer
// landing supersedes it.
const closeDelete = () => {
setAsk(null)
if (!ask || currentItems().some((item) => item.id === selectedId)) return
actions.select(ask.fallback)
actions.closeLayer()
landAfterModalsClosed(() => actions.focusItem(ask.fallback))
}
return { deleting: ask?.target ?? null, askDelete, closeDelete }
}
/** The layer's element follows the view: a Back or a reload selects and shows its row. */
function useSelectionOfLayer(
layer: FindingLayer,
items: readonly FindingItem[],
show: (found: { item: FindingItem; ancestors: string[] }) => void,
) {
const { view } = layer
const wanted = view && 'key' in view ? JSON.stringify(view.key) : null
// `show` only sets state: the layer's key and the tree are what the effect follows.
const reveal = useRef(show)
reveal.current = show
useEffect(() => {
const found = wanted && itemForKey(items, JSON.parse(wanted))
if (found) reveal.current(found)
}, [wanted, items])
}
/**
* The element the dialog shows, or the parent of a creation, vanished (a reload after a
* conflict): the layer closes by replace and says so, with the dropped entry if any.
*/
function useGoneRule(layer: FindingLayer, loaded: boolean) {
const t = useT()
const { view } = layer
const handled = useRef<string | null>(null)
useEffect(() => {
if (!view) handled.current = null
if (!loaded || !view) return
const key = 'key' in view ? view.key : view.create.parent
const stamp = JSON.stringify(view)
const present = (i: FindingItem) => key !== null && sameKey(i.key, key)
if (key === null || currentItems().some(present)) return
if (handled.current === stamp) return
handled.current = stamp
// After this commit's effects: a tile in edit re-registers its guard in them, and the
// forced close below must still be able to ask it.
queueMicrotask(() => layer.replace(null, t('editor.findings.gone')))
}, [loaded, view, layer, t])
}
/** Where a closed dialog returns the focus: its tree row, or the button that started it. */
function useReturnTarget(view: FindingLayer['view']) {
const last = useRef(view)
if (view) last.current = view
return useCallback((): HTMLElement | null => {
const shown = last.current
if (!shown) return null
if ('create' in shown) {
return document.getElementById(ADD_BUTTON[shown.create.kind])
}
const wanted = JSON.stringify(shown.key)
return visibleElement('[data-finding-key]', (el) => {
return el.dataset.findingKey === wanted
})
}, [])
}
/** The creation the view holds, with its parent read from the tree; null when none. */
function pendingOf(
view: FindingLayer['view'],
items: readonly FindingItem[],
): PendingFinding | null {
if (!view || !('create' in view)) return null
const { kind, parent } = view.create
const found = parent ? itemForKey(items, parent) : null
if (parent && !found) return null
return { kind: kind as FindingKind, parent: found?.item ?? null }
}
interface TreeSelection {
selectedId: string | null
selected: FindingItem | undefined
expanded: ReadonlySet<string>
select: (id: string | null) => void
toggle: (id: string, open: boolean) => void
reveal: (found: { item: FindingItem; ancestors: string[] }) => void
}
/** Which branches are open: the zones start open once the sheet has loaded. */
function useExpansion(items: readonly FindingItem[], loaded: boolean) {
const [state, setState] = useState({ ids: new Set<string>(), seeded: false })
if (loaded && !state.seeded) {
const zones = items.filter((i) => i.kind === 'zone')
setState({ ids: new Set(zones.map((i) => i.id)), seeded: true })
}
const open = (ids: readonly string[]) =>
setState((prev) => ({ ...prev, ids: new Set([...prev.ids, ...ids]) }))
const set = (id: string, on: boolean) =>
setState((prev) => {
const ids = new Set(prev.ids)
if (on) ids.add(id)
else ids.delete(id)
return { ...prev, ids }
})
return { expanded: state.ids as ReadonlySet<string>, open, set }
}
/** Selection of the tree; a closed branch takes the selection of what it hides. */
function useTreeSelection(
items: readonly FindingItem[],
loaded: boolean,
): TreeSelection {
const [selectedId, select] = useState<string | null>(null)
const exp = useExpansion(items, loaded)
const reveal: TreeSelection['reveal'] = (found) => {
exp.open(found.ancestors)
select(found.item.id)
}
const toggle = (id: string, open: boolean) => {
if (!open && selectedId && isUnder(items, selectedId, id)) select(id)
exp.set(id, open)
}
return {
selectedId,
selected: items.find((item) => item.id === selectedId),
expanded: exp.expanded,
select,
toggle,
reveal,
}
}
/** The row the focus lands on after a move: set, applied once the dialogs are gone, cleared. */
function useFocusLanding() {
const [focusId, setFocusId] = useState<{ id: string } | null>(null)
const clear = useCallback(() => setFocusId(null), [])
const land = useCallback(
(id: string | null) => setFocusId(id ? { id } : null),
[],
)
return { focusId, clear, land }
}
interface TabContext {
layer: FindingLayer
items: readonly FindingItem[]
sel: TreeSelection
land: (id: string | null) => void
}
/** « Aller à » and the layer's own element: both select the row, the first opens the dialog. */
function useLayerFollow(focus: EditorPlaceProps['focus'], ctx: TabContext) {
const { layer, items, sel, land } = ctx
useFocusRequest(focus, (target) => {
const found = target.key && itemForKey(items, target.key)
if (!found) return 'none'
sel.reveal(found)
// The row takes the focus again when the dialog is closed.
layer.open(found.item.key)
land(found.item.id)
return 'found'
})
useSelectionOfLayer(layer, items, sel.reveal)
}
/**
* A step of « Défaire » or « Refaire » brought a finding back: its branch opens, its row is
* selected and takes the focus. Only the shown tab answers; the workspace shows it first.
*/
function useRevealRestored(items: readonly FindingItem[], ctx: TabContext) {
const revealed = useEditorStore((s) => s.revealed)
const visible = usePlaceVisible()
const { sel, land } = ctx
const reveal = useRef({ sel, land })
reveal.current = { sel, land }
useEffect(() => {
if (!revealed || !visible) return
const found = itemForKey(items, revealed.key)
if (found) {
reveal.current.sel.reveal(found)
reveal.current.land(found.item.id)
}
useEditorStore.getState().clearRevealed()
}, [revealed, visible, items])
}
/** What the tab does with the layer: creation, a row's dialog, deletion. */
function useFindingActions(ctx: TabContext) {
const { layer, sel } = ctx
const deletion = useFindingDeletion(ctx.items, sel.selectedId, {
select: sel.select,
focusItem: ctx.land,
closeLayer: () => void layer.close(true),
})
const created = (
id: string,
parent: FindingItem | null,
kind: FindingKind,
) => {
if (parent) sel.toggle(parent.id, true)
sel.select(createdItemId(kind, parent, id))
layer.replace(createdKey(kind, parent, id))
}
const activate = (item: FindingItem) => {
sel.select(item.id)
layer.open(item.key)
}
return { ...deletion, created, activate }
}
/** The sheet's document and the tree built from it. */
function useFindingsData() {
const doc = useSheetDocument()
const items = useMemo(() => (doc ? buildItems(doc) : []), [doc])
return { doc, items }
}
/** The element the layer's dialog shows, read from the tree; null for none or a creation. */
function shownOf(view: FindingLayer['view'], items: readonly FindingItem[]) {
return view && 'key' in view ? itemForKey(items, view.key) : null
}
/** Everything the tab shows and does, so the component only lays it out. */
function useFindingsTab(focus: EditorPlaceProps['focus'], layer: FindingLayer) {
const data = useFindingsData()
const sel = useTreeSelection(data.items, data.doc !== null)
const landing = useFocusLanding()
const ctx = { layer, items: data.items, sel, land: landing.land }
useLayerFollow(focus, ctx)
useGoneRule(layer, data.doc !== null)
useRevealRestored(data.items, ctx)
return {
...data,
sel,
landing,
actions: useFindingActions(ctx),
returnFocus: useReturnTarget(layer.view),
shown: shownOf(layer.view, data.items),
}
}
/** Constats: the tree zones → categories → nodes; each element opens in a dialog. */
export default function FindingsTab(props: EditorPlaceProps) {
const { layer } = props
if (!layer)
throw new Error('Constats needs the finding layer of the workspace')
return <FindingsBody {...props} layer={layer} />
}
function FindingsBody(props: EditorPlaceProps & { layer: FindingLayer }) {
const { layer } = props
const t = useT()
const tab = useFindingsTab(props.focus, layer)
return (
<section
data-testid="editor-tab-findings"
aria-label={t('editor.tab.findings')}
className="min-h-24 space-y-3"
>
<AddBar
selected={tab.sel.selected}
hasZone={tab.items.some((item) => item.kind === 'zone')}
readOnly={props.readOnly}
onStart={(p) => layer.start(p.kind, p.parent?.key ?? null)}
/>
{tab.doc && tab.items.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.findings.empty')}
</p>
)}
<FindingTree
visible={visibleItems(tab.items, tab.sel.expanded)}
selectedId={tab.sel.selected?.id ?? null}
expanded={tab.sel.expanded}
onSelect={tab.sel.select}
onActivate={tab.actions.activate}
onToggle={tab.sel.toggle}
focusId={tab.landing.focusId}
onFocused={tab.landing.clear}
/>
<FindingDialog
layer={layer}
item={tab.shown?.item ?? null}
pending={pendingOf(layer.view, tab.items)}
readOnly={props.readOnly}
returnFocus={tab.returnFocus}
onDelete={tab.actions.askDelete}
onCreated={tab.actions.created}
/>
<DeleteDialog
target={tab.actions.deleting}
onClose={tab.actions.closeDelete}
/>
</section>
)
}