feat(editor): edit mode of the references dialog
« Modifier » turns the references dialog into a draft of adds and removes, saved as one update on the current citations. A new layer, citations, guards it between the finding and the reference dialogs: close, Back, POP refusal and the leave cascade ask it. « Modifier la référence » and « Nouvelle référence » stack the reference dialog over it; a creation it started joins its draft.
This commit is contained in:
1 parent
d9dbcf1609
commit
3dc5820e3a
29 files changed
+1489
-243
No files matched your search
@@ -118,6 +118,8 @@ function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
|
||||
onShowAll={() => cited && nav.showAllReferences(cited)}
|
||||
navigate={nav.navigate}
|
||||
returnFocus={nav.citationsTrigger}
|
||||
guards={nav.guards}
|
||||
references={nav.references}
|
||||
/>
|
||||
<ReferenceDialog layer={references} readOnly={readOnly} />
|
||||
</>
|
||||
|
||||
@@ -10,10 +10,19 @@ import { useT } from '@/i18n/useT'
|
||||
const BOX =
|
||||
'space-y-2 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-strong)] p-3'
|
||||
|
||||
/** True when no open dialog lies over `host`: each open one is `host` or holds it. */
|
||||
/**
|
||||
* True when no open dialog lies over `host`: each open one is `host`, holds it, or comes
|
||||
* before it in the page (the editor's layers are stacked in tree order: the references
|
||||
* dialog after the finding dialog, the reference dialog after both).
|
||||
*/
|
||||
const onTop = (host: Element) =>
|
||||
[...document.querySelectorAll('dialog[open]')].every(
|
||||
(dialog) => dialog === host || dialog.contains(host),
|
||||
(dialog) =>
|
||||
dialog === host ||
|
||||
dialog.contains(host) ||
|
||||
!!(
|
||||
host.compareDocumentPosition(dialog) & Node.DOCUMENT_POSITION_PRECEDING
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import Icon from '@/components/ui/Icon'
|
||||
import ActionButton from '@/components/editor/fields/ActionButton'
|
||||
import type { FindingItem } from '@/editor/findings/tree'
|
||||
import { usePlural } from '@/editor/plural'
|
||||
import { useSheetDocument } from '@/editor/sheetDocument'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
interface CitationsProps {
|
||||
@@ -38,42 +36,6 @@ function CitationsTrigger({
|
||||
)
|
||||
}
|
||||
|
||||
/** A list of cited references; removable only where `remove` is given. */
|
||||
export function CitationList({
|
||||
ids,
|
||||
readOnly,
|
||||
remove,
|
||||
}: {
|
||||
ids: readonly string[]
|
||||
readOnly: boolean
|
||||
remove?: (id: string) => void
|
||||
}) {
|
||||
const t = useT()
|
||||
const doc = useSheetDocument()
|
||||
const citation = (id: string) =>
|
||||
doc?.references.find((r) => r.id === id)?.citation ?? id
|
||||
return (
|
||||
<ul className="space-y-1">
|
||||
{ids.map((id) => (
|
||||
<li key={id} className="flex items-center gap-2 text-sm">
|
||||
<span className="min-w-0 flex-1">{citation(id)}</span>
|
||||
{remove && (
|
||||
<ActionButton
|
||||
readOnly={readOnly}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-label={`${t('editor.action.remove')} ${citation(id)}`}
|
||||
onClick={() => remove(id)}
|
||||
>
|
||||
{t('editor.action.remove')}
|
||||
</ActionButton>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* « Références citées » and « X références » of a family or a node, the same in the view
|
||||
* and the edit mode (Rev 5): the count is the document's, the citations are read and
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import FindingCreateForm, {
|
||||
type PendingFinding,
|
||||
} from '@/components/editor/findings/FindingCreateForm'
|
||||
import FindingEditForm from '@/components/editor/findings/FindingEditForm'
|
||||
import FindingView from '@/components/editor/findings/FindingView'
|
||||
import { useItemMode } from '@/components/editor/findings/useItemMode'
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import { usePlaceVisible } from '@/lib/placeVisibility'
|
||||
import type { FindingItem, FindingKind } from '@/editor/findings/tree'
|
||||
@@ -33,38 +33,11 @@ interface ItemBodyProps {
|
||||
|
||||
const EDIT_BUTTON_ID = 'finding-edit-button'
|
||||
|
||||
/** After the form closes its button is gone: « Modifier » takes the focus back. */
|
||||
function useFocusEditButton(editing: boolean) {
|
||||
const wanted = useRef(false)
|
||||
useEffect(() => {
|
||||
if (editing || !wanted.current) return
|
||||
wanted.current = false
|
||||
document.getElementById(EDIT_BUTTON_ID)?.focus()
|
||||
}, [editing])
|
||||
return () => {
|
||||
wanted.current = true
|
||||
}
|
||||
}
|
||||
|
||||
/** The local mode of the one dialog: view or edit, and whether a save was just made. */
|
||||
function useItemMode() {
|
||||
const [mode, setMode] = useState({ editing: false, saved: false })
|
||||
const returnToEdit = useFocusEditButton(mode.editing)
|
||||
return {
|
||||
...mode,
|
||||
startEdit: () => setMode({ editing: true, saved: false }),
|
||||
done: (saved: boolean) => {
|
||||
returnToEdit()
|
||||
setMode({ editing: false, saved })
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** View mode, or the edit form: a local mode of the one dialog, no history entry. */
|
||||
function ItemBody(props: ItemBodyProps) {
|
||||
const { layer } = props
|
||||
const t = useT()
|
||||
const mode = useItemMode()
|
||||
const mode = useItemMode(EDIT_BUTTON_ID)
|
||||
const showReferences = (opener: HTMLElement) =>
|
||||
layer.openCitations(props.item.key, opener)
|
||||
return (
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import SelectField from '@/components/editor/fields/SelectField'
|
||||
import { CitationList } from '@/components/editor/findings/FindingCitations'
|
||||
import { useSheetDocument } from '@/editor/sheetDocument'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
interface Props {
|
||||
/** The draft's cited ids: what the form shows. */
|
||||
ids: readonly string[]
|
||||
readOnly: boolean
|
||||
onChange: (ids: string[]) => void
|
||||
}
|
||||
|
||||
/** The references the draft does not cite yet, after the « choose » placeholder. */
|
||||
function useCitableOptions(ids: readonly string[]) {
|
||||
const t = useT()
|
||||
const doc = useSheetDocument()
|
||||
const options = (doc?.references ?? [])
|
||||
.filter((r) => !ids.includes(r.id))
|
||||
.map((r) => ({ value: r.id, label: r.citation }))
|
||||
return [{ value: '', label: t('editor.field.choose') }, ...options]
|
||||
}
|
||||
|
||||
/**
|
||||
* The cited references of a draft: the list, each « Retirer », and « Citer une référence ».
|
||||
* Nothing is written before « Enregistrer ». Mounted by no form since Rev 5 Task 11: the
|
||||
* references dialog's edit mode (Task 12) takes it over.
|
||||
*/
|
||||
export default function FindingEditCitations(props: Props) {
|
||||
const { ids, readOnly, onChange } = props
|
||||
const t = useT()
|
||||
const options = useCitableOptions(ids)
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{ids.length === 0 ? (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.findings.references_none')}
|
||||
</p>
|
||||
) : (
|
||||
<CitationList
|
||||
ids={ids}
|
||||
readOnly={readOnly}
|
||||
remove={(id) => onChange(ids.filter((other) => other !== id))}
|
||||
/>
|
||||
)}
|
||||
{!readOnly && (
|
||||
<SelectField
|
||||
id="finding-add-reference"
|
||||
label={t('editor.findings.reference_add')}
|
||||
value=""
|
||||
options={options}
|
||||
onCommit={(id) => id !== '' && onChange([...ids, id])}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
/** After the form closes its button is gone: « Modifier » (`buttonId`) takes the focus back. */
|
||||
function useFocusEditButton(editing: boolean, buttonId: string) {
|
||||
const wanted = useRef(false)
|
||||
useEffect(() => {
|
||||
if (editing || !wanted.current) return
|
||||
wanted.current = false
|
||||
document.getElementById(buttonId)?.focus()
|
||||
}, [editing, buttonId])
|
||||
return () => {
|
||||
wanted.current = true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The local mode of a dialog (the finding dialog, the references dialog): view or edit,
|
||||
* and whether a save was just made. No history entry. `buttonId` is its « Modifier ».
|
||||
*/
|
||||
export function useItemMode(buttonId: string) {
|
||||
const [mode, setMode] = useState({ editing: false, saved: false })
|
||||
const returnToEdit = useFocusEditButton(mode.editing, buttonId)
|
||||
return {
|
||||
...mode,
|
||||
startEdit: () => setMode({ editing: true, saved: false }),
|
||||
done: (saved: boolean) => {
|
||||
returnToEdit()
|
||||
setMode({ editing: false, saved })
|
||||
},
|
||||
/** Back to the view mode, nothing said: the dialog shows another element. */
|
||||
reset: () => setMode({ editing: false, saved: false }),
|
||||
}
|
||||
}
|
||||
@@ -1,49 +1,149 @@
|
||||
import { useState } from 'react'
|
||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||
import ActionButton from '@/components/editor/fields/ActionButton'
|
||||
import { useItemMode } from '@/components/editor/findings/useItemMode'
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import { useEditorReadOnly } from '@/editor/editingContext'
|
||||
import type { EditorTarget } from '@/editor/navigation'
|
||||
import { findingPath } from '@/editor/references/panel'
|
||||
import { useSheetDocument } from '@/editor/sheetDocument'
|
||||
import type { Guards } from '@/editor/useEditorNavigation'
|
||||
import type { ReferenceMoves } from '@/editor/useReferenceMoves'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import CitationsPanel from './CitationsPanel'
|
||||
import CitationsEditForm from './CitationsEditForm'
|
||||
import CitationsPanel, { FindingPath } from './CitationsPanel'
|
||||
import { CITATIONS_TITLE_ID } from './useCitationsPanel'
|
||||
|
||||
export interface CitationsDialogProps {
|
||||
/** The family or finding node whose citations it shows; null while it is closed. */
|
||||
citedBy: ElementKey | null
|
||||
/** A user close (✕, Escape, the backdrop). */
|
||||
onClose: () => boolean
|
||||
/** A close: a user one (✕, Escape, the backdrop) is refused by a draft; forced goes. */
|
||||
onClose: (forced?: boolean) => boolean
|
||||
/** « Tout afficher dans l'onglet Références ». */
|
||||
onShowAll: () => void
|
||||
/** « Aller à » a citing finding or a reference. */
|
||||
navigate: (target: EditorTarget) => void
|
||||
/** « X références » of the finding dialog under it, where the focus returns. */
|
||||
returnFocus: () => HTMLElement | null
|
||||
guards: Guards
|
||||
/** The reference dialog over this one (the edit mode's edit and creation). */
|
||||
references: Pick<ReferenceMoves, 'open' | 'start'>
|
||||
}
|
||||
|
||||
/** The dialog's « Modifier »: the focus comes back to it after the edit mode. */
|
||||
const EDIT_BUTTON_ID = 'citations-edit-button'
|
||||
|
||||
/** The local mode, back to the view for each element the dialog shows (no history entry). */
|
||||
function useCitationsMode(citedBy: ElementKey | null) {
|
||||
const shownFor = citedBy && JSON.stringify(citedBy)
|
||||
const mode = useItemMode(EDIT_BUTTON_ID)
|
||||
const [modeFor, setModeFor] = useState(shownFor)
|
||||
if (modeFor !== shownFor) {
|
||||
setModeFor(shownFor)
|
||||
mode.reset()
|
||||
}
|
||||
return { ...mode, shownFor }
|
||||
}
|
||||
|
||||
type Mode = ReturnType<typeof useCitationsMode>
|
||||
|
||||
interface BodyProps {
|
||||
citedBy: ElementKey
|
||||
mode: Mode
|
||||
props: CitationsDialogProps
|
||||
}
|
||||
|
||||
/** The edit mode: where the finding sits, then the draft form. */
|
||||
function EditBody({ citedBy, mode, props }: BodyProps) {
|
||||
const doc = useSheetDocument()
|
||||
const readOnly = useEditorReadOnly()
|
||||
return (
|
||||
<>
|
||||
<FindingPath path={doc ? findingPath(doc, citedBy) : []} />
|
||||
<CitationsEditForm
|
||||
key={mode.shownFor}
|
||||
citedBy={citedBy}
|
||||
readOnly={readOnly}
|
||||
guards={props.guards}
|
||||
references={props.references}
|
||||
onDone={mode.done}
|
||||
onDiscardClose={() => props.onClose(true)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** The view mode: the cited references, then « Modifier » (edit tier only). */
|
||||
function ViewBody({ citedBy, mode, props }: BodyProps) {
|
||||
const t = useT()
|
||||
const readOnly = useEditorReadOnly()
|
||||
return (
|
||||
<>
|
||||
<CitationsPanel
|
||||
citedBy={citedBy}
|
||||
onShowAll={props.onShowAll}
|
||||
navigate={props.navigate}
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<ActionButton
|
||||
id={EDIT_BUTTON_ID}
|
||||
readOnly={readOnly}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={mode.startEdit}
|
||||
>
|
||||
{t('editor.citations.edit')}
|
||||
</ActionButton>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** The place of the dialog's content, in both modes, then what a save says. */
|
||||
function Body(body: BodyProps) {
|
||||
const t = useT()
|
||||
const { mode } = body
|
||||
return (
|
||||
<section
|
||||
id="editor-citations-panel"
|
||||
data-testid="editor-citations-panel"
|
||||
data-place="citations"
|
||||
aria-labelledby={CITATIONS_TITLE_ID}
|
||||
className="space-y-3"
|
||||
>
|
||||
{mode.editing ? <EditBody {...body} /> : <ViewBody {...body} />}
|
||||
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
|
||||
{mode.saved ? t('editor.findings.saved') : ''}
|
||||
</p>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The references dialog of a family or a finding node (Rev 5): a modal layer over the
|
||||
* finding dialog. The host sits after the tab body in the tree, so it is shown after the
|
||||
* finding dialog and lies on top of it; Escape, ✕ and the backdrop close it only. The
|
||||
* view mode reads the cited references.
|
||||
* view mode reads the cited references; its « Modifier » turns it into a form (local
|
||||
* mode, no history entry) whose draft the layer `citations` guards.
|
||||
*/
|
||||
export default function CitationsDialog(props: CitationsDialogProps) {
|
||||
const { citedBy, onClose } = props
|
||||
const t = useT()
|
||||
const mode = useCitationsMode(citedBy)
|
||||
const title = mode.editing
|
||||
? 'editor.citations.edit_title'
|
||||
: 'editor.references.dialog_title'
|
||||
return (
|
||||
<Dialog
|
||||
open={citedBy !== null}
|
||||
layer
|
||||
size="lg"
|
||||
title={t('editor.references.dialog_title')}
|
||||
title={t(title)}
|
||||
titleId={CITATIONS_TITLE_ID}
|
||||
returnFocus={props.returnFocus}
|
||||
onClose={() => (onClose() ? undefined : 'kept')}
|
||||
>
|
||||
{citedBy && (
|
||||
<CitationsPanel
|
||||
citedBy={citedBy}
|
||||
onShowAll={props.onShowAll}
|
||||
navigate={props.navigate}
|
||||
/>
|
||||
)}
|
||||
{citedBy && <Body citedBy={citedBy} mode={mode} props={props} />}
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import SelectField from '@/components/editor/fields/SelectField'
|
||||
import Button from '@/components/ui/Button'
|
||||
import { useSheetDocument } from '@/editor/sheetDocument'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface DraftListProps {
|
||||
/** The draft's cited ids, in the order they will be saved. */
|
||||
ids: readonly string[]
|
||||
readOnly: boolean
|
||||
onAdd: (id: string) => void
|
||||
onRemove: (id: string) => void
|
||||
/** « Modifier la référence »: the reference dialog over this one. */
|
||||
onEditReference: (id: string, opener: HTMLElement) => void
|
||||
/** « Nouvelle référence »: the creation dialog over this one. */
|
||||
onNew: (opener: HTMLElement) => void
|
||||
}
|
||||
|
||||
/** The add choice: its id, so the focus can land on it once the last row is removed. */
|
||||
const ADD_ID = 'citations-add-reference'
|
||||
|
||||
/** The references the draft does not cite yet, after the « choose » placeholder. */
|
||||
function useCitableOptions(ids: readonly string[]) {
|
||||
const t = useT()
|
||||
const doc = useSheetDocument()
|
||||
const options = (doc?.references ?? [])
|
||||
.filter((r) => !ids.includes(r.id))
|
||||
.map((r) => ({ value: r.id, label: r.citation }))
|
||||
return [{ value: '', label: t('editor.field.choose') }, ...options]
|
||||
}
|
||||
|
||||
/**
|
||||
* A removed row takes its buttons with it: the focus goes to the row now at its place,
|
||||
* else the one before, else the add choice.
|
||||
*/
|
||||
function useRemovalFocus(ids: readonly string[]) {
|
||||
const list = useRef<HTMLUListElement>(null)
|
||||
const removedAt = useRef<number | null>(null)
|
||||
useEffect(() => {
|
||||
const at = removedAt.current
|
||||
if (at === null) return
|
||||
removedAt.current = null
|
||||
const rows = [...(list.current?.children ?? [])]
|
||||
const row = rows[at] ?? rows[at - 1]
|
||||
const target =
|
||||
row?.querySelector('button') ?? document.getElementById(ADD_ID)
|
||||
target?.focus()
|
||||
}, [ids])
|
||||
return { list, removing: (at: number) => (removedAt.current = at) }
|
||||
}
|
||||
|
||||
interface RowProps {
|
||||
id: string
|
||||
props: DraftListProps
|
||||
onRemove: () => void
|
||||
}
|
||||
|
||||
/** One cited id: its citation (or « Référence introuvable »), its edit and its removal. */
|
||||
function DraftRow({ id, props, onRemove }: RowProps) {
|
||||
const t = useT()
|
||||
const doc = useSheetDocument()
|
||||
const citation = doc?.references.find((r) => r.id === id)?.citation
|
||||
const shown = citation ?? `${t('editor.references.missing')} ${id}`
|
||||
return (
|
||||
<li data-citation-row={id} className="flex flex-wrap items-center gap-2">
|
||||
<span className="min-w-0 flex-1 text-sm">{shown}</span>
|
||||
{citation !== undefined && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
disabled={props.readOnly}
|
||||
aria-label={`${t('editor.citations.edit_reference')} ${citation}`}
|
||||
onClick={(event) => props.onEditReference(id, event.currentTarget)}
|
||||
>
|
||||
{t('editor.citations.edit_reference')}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={props.readOnly}
|
||||
aria-label={`${t('editor.action.remove')} ${citation ?? id}`}
|
||||
onClick={onRemove}
|
||||
>
|
||||
{t('editor.action.remove')}
|
||||
</Button>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
/** « Citer une référence » among those not cited yet, and « Nouvelle référence ». */
|
||||
function AddRow({ props }: { props: DraftListProps }) {
|
||||
const t = useT()
|
||||
const options = useCitableOptions(props.ids)
|
||||
return (
|
||||
<div className="flex flex-wrap items-end gap-2">
|
||||
{!props.readOnly && (
|
||||
<div className="min-w-0 flex-1">
|
||||
<SelectField
|
||||
id={ADD_ID}
|
||||
label={t('editor.findings.reference_add')}
|
||||
value=""
|
||||
options={options}
|
||||
onCommit={(id) => id !== '' && props.onAdd(id)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
disabled={props.readOnly}
|
||||
onClick={(event) => props.onNew(event.currentTarget)}
|
||||
>
|
||||
{t('editor.citations.new_reference')}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The cited references of the draft (the references dialog's edit mode, Rev 5): each with
|
||||
* « Modifier la référence » and « Retirer » (a dangling id too), then the ways to cite one.
|
||||
* Nothing is written before « Enregistrer ». Read only: every control off.
|
||||
*/
|
||||
export default function CitationsDraftList(props: DraftListProps) {
|
||||
const { ids } = props
|
||||
const t = useT()
|
||||
const focus = useRemovalFocus(ids)
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{ids.length === 0 && (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editor.findings.references_none')}
|
||||
</p>
|
||||
)}
|
||||
<ul ref={focus.list} className="space-y-2">
|
||||
{ids.map((id, at) => (
|
||||
<DraftRow
|
||||
key={id}
|
||||
id={id}
|
||||
props={props}
|
||||
onRemove={() => {
|
||||
focus.removing(at)
|
||||
props.onRemove(id)
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
<AddRow props={props} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||
import { FormActions } from '@/components/editor/findings/DiscardConfirm'
|
||||
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
|
||||
import { useFormDraft } from '@/components/editor/findings/useDirtyGuard'
|
||||
import { patchElement } from '@/editor/findings/tree'
|
||||
import {
|
||||
addId,
|
||||
applyEdits,
|
||||
NO_EDITS,
|
||||
removeId,
|
||||
sameEdits,
|
||||
type CitationEdits,
|
||||
} from '@/editor/references/citationEdits'
|
||||
import { citedIds, citingFinding } from '@/editor/references/filter'
|
||||
import { useSheetDocument } from '@/editor/sheetDocument'
|
||||
import { useEditCommand } from '@/editor/useEditCommand'
|
||||
import type { Guards } from '@/editor/useEditorNavigation'
|
||||
import type { ReferenceMoves } from '@/editor/useReferenceMoves'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import CitationsDraftList from './CitationsDraftList'
|
||||
|
||||
export interface CitationsEditFormProps {
|
||||
citedBy: ElementKey
|
||||
readOnly: boolean
|
||||
guards: Guards
|
||||
/** The reference dialog over this one: an edit, or a creation cited in the draft. */
|
||||
references: Pick<ReferenceMoves, 'open' | 'start'>
|
||||
/** Back to the view mode; `saved` is true when a command was written. */
|
||||
onDone: (saved: boolean) => void
|
||||
/** « Abandonner » after a close request: the draft goes, so does the dialog. */
|
||||
onDiscardClose: () => void
|
||||
}
|
||||
|
||||
/** The family or node as the document holds it now, and the ids it cites now. */
|
||||
function useCurrent(citedBy: ElementKey) {
|
||||
const doc = useSheetDocument()
|
||||
const item = doc ? citingFinding(doc, citedBy) : null
|
||||
return { item, ids: item ? citedIds(item) : [] }
|
||||
}
|
||||
|
||||
const sameIds = (a: readonly string[], b: readonly string[]) =>
|
||||
a.length === b.length && a.every((id, at) => id === b[at])
|
||||
|
||||
type Draft = ReturnType<typeof useFormDraft<CitationEdits>>
|
||||
|
||||
/** The save: the draft applied to the current citations, one `update`, none unchanged. */
|
||||
function useCitationsSave(props: CitationsEditFormProps, form: Draft) {
|
||||
const { item, ids } = useCurrent(props.citedBy)
|
||||
const edit = useEditCommand()
|
||||
const save = () => {
|
||||
const next = applyEdits(ids, form.draft)
|
||||
if (!item || sameIds(next, ids)) return props.onDone(false)
|
||||
const element = patchElement(item, { reference_ids: next })
|
||||
const command = { op: 'update', key: item.key, element } as const
|
||||
if (edit.run('save', command)) props.onDone(true)
|
||||
}
|
||||
return {
|
||||
shown: applyEdits(ids, form.draft),
|
||||
save,
|
||||
error: edit.fieldError('save'),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* « Nouvelle référence »: the creation dialog over this one; the new id joins the draft,
|
||||
* only while this form is still there (an abandoned draft cites nothing).
|
||||
*/
|
||||
function useCreation(props: CitationsEditFormProps, form: Draft) {
|
||||
const latest = useRef(form)
|
||||
latest.current = form
|
||||
const alive = useRef(true)
|
||||
useEffect(() => {
|
||||
alive.current = true
|
||||
return () => {
|
||||
alive.current = false
|
||||
}
|
||||
}, [])
|
||||
return (opener: HTMLElement) =>
|
||||
props.references.start(opener, (id) => {
|
||||
const now = latest.current
|
||||
if (alive.current) now.set(addId(now.draft, id))
|
||||
})
|
||||
}
|
||||
|
||||
/** The form's state: the draft, its guard, its save, its cancel and its creation. */
|
||||
function useCitationsForm(props: CitationsEditFormProps) {
|
||||
const form = useFormDraft(NO_EDITS, props.guards, sameEdits, 'citations')
|
||||
const saving = useCitationsSave(props, form)
|
||||
const cancel = () =>
|
||||
form.dirty && !props.readOnly
|
||||
? form.guard.askToLeave()
|
||||
: props.onDone(false)
|
||||
return { ...form, ...saving, cancel, create: useCreation(props, form) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The references dialog's edit mode (Rev 5): a draft of the citations (cite, remove, a new
|
||||
* reference cited), one `update` on « Enregistrer » (none when nothing changed), nothing on
|
||||
* « Annuler » or a close. The draft's layer is `citations`: a dirty one is asked before a
|
||||
* close, a Back or a leave. Read only: the draft stays, only « Abandonner » is left.
|
||||
*/
|
||||
export default function CitationsEditForm(props: CitationsEditFormProps) {
|
||||
const t = useT()
|
||||
const form = useCitationsForm(props)
|
||||
const { guard } = form
|
||||
const discard =
|
||||
guard.confirming === 'dialog'
|
||||
? props.onDiscardClose
|
||||
: () => props.onDone(false)
|
||||
return (
|
||||
<form
|
||||
data-draft-form
|
||||
className="space-y-3"
|
||||
noValidate
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
form.save()
|
||||
}}
|
||||
>
|
||||
{props.readOnly && <ReadOnlyNotice />}
|
||||
<CitationsDraftList
|
||||
ids={form.shown}
|
||||
readOnly={props.readOnly}
|
||||
onAdd={(id) => form.set(addId(form.draft, id))}
|
||||
onRemove={(id) => form.set(removeId(form.draft, id))}
|
||||
onEditReference={props.references.open}
|
||||
onNew={form.create}
|
||||
/>
|
||||
{form.error && (
|
||||
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
||||
{form.error}
|
||||
</p>
|
||||
)}
|
||||
<FormActions
|
||||
confirming={guard.confirming}
|
||||
readOnly={props.readOnly}
|
||||
submitLabel={t('editor.findings.save')}
|
||||
onCancel={form.cancel}
|
||||
onKeepTyping={guard.keepTyping}
|
||||
onDiscard={guard.discard(discard)}
|
||||
/>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -6,11 +6,7 @@ import type { CitationEntry } from '@/editor/references/panel'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import ReferenceTile from './ReferenceTile'
|
||||
import {
|
||||
CITATIONS_TITLE_ID,
|
||||
useCitationsPanel,
|
||||
type PanelHooks,
|
||||
} from './useCitationsPanel'
|
||||
import { useCitationsPanel, type PanelHooks } from './useCitationsPanel'
|
||||
|
||||
interface Props extends PanelHooks {
|
||||
/** « Tout afficher dans l'onglet Références ». */
|
||||
@@ -23,7 +19,7 @@ const RING =
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
|
||||
|
||||
/** « Zone › Famille › **Constat** »: where the finding sits, the finding itself in bold. */
|
||||
function FindingPath({ path }: { path: readonly LocalizedText[] }) {
|
||||
export function FindingPath({ path }: { path: readonly LocalizedText[] }) {
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const names = path.map((name) => name[locale])
|
||||
const own = names.pop()
|
||||
@@ -143,10 +139,10 @@ function Entries({ panel, props }: { panel: Panel; props: Props }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The citations of one family or finding node, the body of the references dialog
|
||||
* The citations of one family or finding node, the view mode of the references dialog
|
||||
* (CitationsDialog): where it sits, the references it cites as tiles, the dangling ids
|
||||
* named, « Tout afficher » for the whole library. The view mode: no search, add, remove,
|
||||
* order or « Modifier » (P7).
|
||||
* named, « Tout afficher » for the whole library. No search, add, remove, order or
|
||||
* « Modifier » on a tile (P7): the dialog's own « Modifier » opens the edit mode.
|
||||
*/
|
||||
export default function CitationsPanel(props: Props) {
|
||||
const { onShowAll } = props
|
||||
@@ -154,13 +150,7 @@ export default function CitationsPanel(props: Props) {
|
||||
const panel = useCitationsPanel(props)
|
||||
const count = panel.entries.length
|
||||
return (
|
||||
<section
|
||||
id="editor-citations-panel"
|
||||
data-testid="editor-citations-panel"
|
||||
data-place="citations"
|
||||
aria-labelledby={CITATIONS_TITLE_ID}
|
||||
className="space-y-3"
|
||||
>
|
||||
<>
|
||||
<FindingPath path={panel.path} />
|
||||
<Summary count={count} onShowAll={onShowAll} />
|
||||
{count === 0 && (
|
||||
@@ -169,6 +159,6 @@ export default function CitationsPanel(props: Props) {
|
||||
</p>
|
||||
)}
|
||||
<Entries panel={panel} props={props} />
|
||||
</section>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -41,7 +41,7 @@ function useGoneRule(layer: ReferenceLayer) {
|
||||
}, [view, doc, layer, t])
|
||||
}
|
||||
|
||||
/** Where a closed dialog returns the focus: the tile's header, or the add button. */
|
||||
/** Where a closed dialog returns the focus: its opener, else the tile header or « Ajouter ». */
|
||||
function useReturnTarget(layer: ReferenceLayer) {
|
||||
const last = useRef(layer.view)
|
||||
if (layer.view) last.current = layer.view
|
||||
@@ -49,7 +49,9 @@ function useReturnTarget(layer: ReferenceLayer) {
|
||||
return useCallback((): HTMLElement | null => {
|
||||
const shown = last.current
|
||||
if (!shown) return null
|
||||
if ('create' in shown) return document.getElementById(ADD_BUTTON_ID)
|
||||
// A creation over the citations dialog returns to its « Nouvelle référence ».
|
||||
if ('create' in shown)
|
||||
return opener() ?? document.getElementById(ADD_BUTTON_ID)
|
||||
const wanted = JSON.stringify({ kind: 'reference', id: shown.edit })
|
||||
return (
|
||||
opener() ??
|
||||
@@ -104,10 +106,10 @@ function useOnSaved(
|
||||
}
|
||||
|
||||
/**
|
||||
* The reference dialog (R2F-5): one `Dialog` over the References tab or the citations
|
||||
* sheet, a form for a reference's type, DOI, citation and URL, or for a new one. The view
|
||||
* layer of the browser history drives it; it is no part of a kept place, so it is never a
|
||||
* native modal inside a hidden one.
|
||||
* The reference dialog (R2F-5): one `Dialog` over the References tab or the references
|
||||
* dialog's edit mode (Rev 5), a form for a reference's type, DOI, citation and URL, or for
|
||||
* a new one. The view layer of the browser history drives it; it is no part of a kept
|
||||
* place, so it is never a native modal inside a hidden one.
|
||||
*/
|
||||
export default function ReferenceDialog({
|
||||
layer,
|
||||
|
||||
@@ -11,9 +11,10 @@ import {
|
||||
} from '@/components/ui/afterModalsClosed'
|
||||
import { focusActiveTab } from '../focusRequest'
|
||||
import { LAYERS_TOP_DOWN } from '../leftDraft'
|
||||
import { sameView, type EditorView } from '../navigation'
|
||||
import { citationsOfView, sameView, type EditorView } from '../navigation'
|
||||
import {
|
||||
headingOf,
|
||||
layersAbove,
|
||||
shownPlace,
|
||||
useMoveText,
|
||||
type EditorNavigation,
|
||||
@@ -211,23 +212,26 @@ function sameLayers(a: EditorView, b: EditorView): boolean {
|
||||
)
|
||||
}
|
||||
|
||||
/** The finding dialog a view shows, without its citations dialog: that one holds no form. */
|
||||
/** The finding dialog a view shows, without its citations dialog (a layer of its own). */
|
||||
function dialogOf({ finding }: EditorView): unknown {
|
||||
return finding && 'key' in finding ? { key: finding.key } : finding
|
||||
}
|
||||
|
||||
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
|
||||
|
||||
/**
|
||||
* The layers holding a form that a POP from `from` to `to` takes away, top down: the
|
||||
* citations dialog alone is no such layer, so a Back that only closes it asks nothing.
|
||||
* The layers that a POP from `from` to `to` takes away, top down: the reference dialog
|
||||
* changed, the citations dialog closed or shown for another finding, the finding dialog
|
||||
* changed. Each is asked; one holding no draft (no guard, or a clean one) lets it go.
|
||||
*/
|
||||
function leavingLayers(from: EditorView, to: EditorView): LayerName[] {
|
||||
const same = (a: unknown, b: unknown) =>
|
||||
JSON.stringify(a) === JSON.stringify(b)
|
||||
const reference = from.reference && !same(from.reference, to.reference)
|
||||
const finding = from.finding && !same(dialogOf(from), dialogOf(to))
|
||||
return LAYERS_TOP_DOWN.filter((l) =>
|
||||
l === 'reference' ? reference : finding,
|
||||
)
|
||||
const cited = citationsOfView(from)
|
||||
const leaving = {
|
||||
reference: !!from.reference && !same(from.reference, to.reference),
|
||||
citations: !!cited && !same(cited, citationsOfView(to)),
|
||||
finding: !!from.finding && !same(dialogOf(from), dialogOf(to)),
|
||||
}
|
||||
return LAYERS_TOP_DOWN.filter((layer) => leaving[layer])
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -249,12 +253,14 @@ function refusal(
|
||||
return leaving.find((layer) => !nav.guards.ask(layer, false).allowed) ?? null
|
||||
}
|
||||
|
||||
/** The finding dialog alone: the clean citations and reference dialogs over it go. */
|
||||
function bareFinding(view: EditorView): EditorView {
|
||||
/** `view` without the dialogs over `layer`: the clean layers above the one that asks. */
|
||||
function upTo(view: EditorView, layer: LayerName): EditorView {
|
||||
const above = layersAbove(layer)
|
||||
const { finding } = view
|
||||
const shown =
|
||||
finding && 'key' in finding ? { ...finding, citations: false } : finding
|
||||
return { ...view, finding: shown, reference: null }
|
||||
const closes = above.includes('citations') && finding && 'key' in finding
|
||||
const shown = closes ? { ...finding, citations: false } : finding
|
||||
const reference = above.includes('reference') ? null : view.reference
|
||||
return { ...view, finding: shown, reference }
|
||||
}
|
||||
|
||||
interface PopContext {
|
||||
@@ -278,15 +284,16 @@ function landOnForeign(ctx: PopContext): Landing | null {
|
||||
|
||||
/**
|
||||
* A POP refused (see `refusal`): the view stays, pushed again above the entry landed on.
|
||||
* When the finding dialog refused, the clean citations and reference dialogs over it close
|
||||
* first, so its question is not hidden under them. True when refused.
|
||||
* The clean dialogs over the layer that refused close first (the reference dialog over a
|
||||
* citations draft; both over a finding draft), so its question is not hidden under them.
|
||||
* True when refused.
|
||||
*/
|
||||
function refusePop(ctx: PopContext, landed: HistoryEntry | null): boolean {
|
||||
const refused = refusal(ctx, landed)
|
||||
if (!refused) return false
|
||||
const { book, writer, view } = ctx
|
||||
if (landed) adopt(book, landed)
|
||||
const kept = refused === 'finding' ? bareFinding(view) : view
|
||||
const kept = refused === 'modal' ? view : upTo(view, refused)
|
||||
if (!sameView(kept, view)) ctx.nav.restoreView(kept)
|
||||
writer.push(kept)
|
||||
return true
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { useCallback, useEffect, useRef } from 'react'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { topDirtyLayer } from '../leftDraft'
|
||||
import type {
|
||||
EditorNavigation,
|
||||
Guards,
|
||||
LayerExit,
|
||||
LayerName,
|
||||
import { citationsOfView } from '../navigation'
|
||||
import {
|
||||
layersAbove,
|
||||
type EditorNavigation,
|
||||
type Guards,
|
||||
type LayerExit,
|
||||
type LayerName,
|
||||
} from '../useEditorNavigation'
|
||||
|
||||
/** The part of a Navigation API `navigate` event this guard reads (not in the DOM types). */
|
||||
@@ -41,10 +43,11 @@ function leavesEditor(event: NavigateEventLike, path: string): boolean {
|
||||
interface Watch {
|
||||
guards: Guards
|
||||
/**
|
||||
* Closes the citations dialog and a reference dialog over it: they lie over the finding
|
||||
* dialog, so its question would be hidden under them.
|
||||
* Closes the dialogs over `layer` (clean: it is the top dirty one), so its question is
|
||||
* not hidden under them: the reference dialog over the citations dialog, both over the
|
||||
* finding dialog.
|
||||
*/
|
||||
clearAbove: () => void
|
||||
clearAbove: (layer: LayerName) => void
|
||||
path: string
|
||||
/** The key of the jump the user confirmed: it passes, and leaves no flag. */
|
||||
passing: { current: string | null }
|
||||
@@ -72,15 +75,14 @@ function jumpTo({ api, key, watch }: Jump, keep: () => void): void {
|
||||
}
|
||||
|
||||
/**
|
||||
* `layer` asks « Abandonner les modifications ? » and holds the jump. Its « Abandonner »
|
||||
* closes it, with the citations dialog it may have been opened from (so the next question
|
||||
* is not hidden under the citations dialog), and the next dirty layer under it asks in turn; the
|
||||
* last one lets the jump go. Any « Continuer la saisie » drops the jump. The finding
|
||||
* dialog asks once the layers over it are closed (they are clean: it is the top dirty one).
|
||||
* `layer` asks « Abandonner les modifications ? » and holds the jump, once the layers over
|
||||
* it are closed (they are clean: it is the top dirty one). Its « Abandonner » closes it,
|
||||
* and the next dirty layer under it asks in turn; the last one lets the jump go. Any
|
||||
* « Continuer la saisie » drops the jump.
|
||||
*/
|
||||
function askLeave(jump: Jump, layer: LayerName): void {
|
||||
const { guards, clearAbove } = jump.watch
|
||||
if (layer === 'finding') clearAbove()
|
||||
clearAbove(layer)
|
||||
guards.ask(layer, false)
|
||||
guards.holdLeave({
|
||||
layer,
|
||||
@@ -113,13 +115,17 @@ type LeaveNav = Pick<
|
||||
'guards' | 'state' | 'closeCitations' | 'references'
|
||||
>
|
||||
|
||||
/** Closes the citations and reference dialogs of the navigation `latest` holds, if open. */
|
||||
function clearerOf(latest: { current: LeaveNav }): () => void {
|
||||
return () => {
|
||||
/**
|
||||
* Closes the open dialogs over `layer` of the navigation `latest` holds. Forced: they hold
|
||||
* no draft, or one just abandoned (the state read may still show it, one commit behind).
|
||||
*/
|
||||
function clearerOf(latest: { current: LeaveNav }): (layer: LayerName) => void {
|
||||
return (layer) => {
|
||||
const { state, closeCitations, references } = latest.current
|
||||
const { finding } = state
|
||||
if (finding && 'key' in finding && finding.citations) closeCitations()
|
||||
if (state.reference) references.close(true)
|
||||
const above = layersAbove(layer)
|
||||
if (above.includes('reference') && state.reference) references.close(true)
|
||||
const cited = above.includes('citations') && citationsOfView(state)
|
||||
if (cited) closeCitations(true)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,12 @@ import { useEffect, useRef, useState } from 'react'
|
||||
import type { HistoryOwner } from './history/entry'
|
||||
import { fingerprintOf, randomHex } from './history/fingerprint'
|
||||
import type { NavigationState } from './navigation'
|
||||
import type { EditorNavigation, Guards, LayerName } from './useEditorNavigation'
|
||||
import {
|
||||
LAYERS,
|
||||
type EditorNavigation,
|
||||
type Guards,
|
||||
type LayerName,
|
||||
} from './useEditorNavigation'
|
||||
|
||||
/**
|
||||
* A dirty dialog lost when the editor goes (a Back of several entries the browser does
|
||||
@@ -24,7 +29,7 @@ export const leftDraftKey = ({ sheetId, tag }: HistoryOwner) =>
|
||||
`${PREFIX}${sheetId}:${tag}`
|
||||
|
||||
/** The top layer first: the dialog the user was typing in when they left. */
|
||||
export const LAYERS_TOP_DOWN: readonly LayerName[] = ['reference', 'finding']
|
||||
export const LAYERS_TOP_DOWN: readonly LayerName[] = [...LAYERS].reverse()
|
||||
|
||||
/**
|
||||
* The top layer whose form holds changes, or the first one under `below`; a forced ask
|
||||
@@ -55,6 +60,7 @@ function elementOf(state: NavigationState, layer: LayerName): unknown {
|
||||
? { kind: 'reference', id: reference.edit }
|
||||
: null
|
||||
}
|
||||
// The citations dialog's element is the finding whose citations it edits.
|
||||
const { finding } = state
|
||||
if (!finding) return null
|
||||
return 'key' in finding ? finding.key : finding.create.parent
|
||||
|
||||
@@ -291,9 +291,14 @@ function openReference(state: NavigationState, id: string): NavigationState {
|
||||
return shown({ ...state, reference: { edit: id } })
|
||||
}
|
||||
|
||||
/** The creation form of a reference: only the References tab adds one. */
|
||||
/**
|
||||
* The creation form of a reference: over the References tab, or over the citations dialog
|
||||
* (its edit mode cites the new reference, Rev 5), which keeps its tab.
|
||||
*/
|
||||
function createReference(state: NavigationState): NavigationState {
|
||||
return shown({ ...state, tab: 'references', reference: { create: true } })
|
||||
const reference = { create: true } as const
|
||||
if (citationsOfView(state)) return shown({ ...state, reference })
|
||||
return shown({ ...state, tab: 'references', reference })
|
||||
}
|
||||
|
||||
export function navigationReducer(
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* The draft of the references dialog's edit mode (Rev 5): what the user added and removed,
|
||||
* never a whole list. It is applied to the element's CURRENT citations at save, so a
|
||||
* change made elsewhere meanwhile (an undo, a reload) is kept, never overwritten.
|
||||
*/
|
||||
export interface CitationEdits {
|
||||
added: readonly string[]
|
||||
removed: readonly string[]
|
||||
}
|
||||
|
||||
export const NO_EDITS: CitationEdits = { added: [], removed: [] }
|
||||
|
||||
export const sameEdits = (a: CitationEdits, b: CitationEdits) =>
|
||||
JSON.stringify(a) === JSON.stringify(b)
|
||||
|
||||
/** `current` with the removals dropped and the additions appended, each id once. */
|
||||
export function applyEdits(
|
||||
current: readonly string[],
|
||||
edits: CitationEdits,
|
||||
): string[] {
|
||||
const kept = current.filter((id) => !edits.removed.includes(id))
|
||||
return [...kept, ...edits.added.filter((id) => !kept.includes(id))]
|
||||
}
|
||||
|
||||
/** Cites `id`: undoes its removal, else adds it. */
|
||||
export function addId(edits: CitationEdits, id: string): CitationEdits {
|
||||
if (edits.removed.includes(id)) {
|
||||
return { ...edits, removed: edits.removed.filter((other) => other !== id) }
|
||||
}
|
||||
if (edits.added.includes(id)) return edits
|
||||
return { ...edits, added: [...edits.added, id] }
|
||||
}
|
||||
|
||||
/** Removes `id`: undoes its addition, else records the removal. */
|
||||
export function removeId(edits: CitationEdits, id: string): CitationEdits {
|
||||
if (edits.added.includes(id)) {
|
||||
return { ...edits, added: edits.added.filter((other) => other !== id) }
|
||||
}
|
||||
if (edits.removed.includes(id)) return edits
|
||||
return { ...edits, removed: [...edits.removed, id] }
|
||||
}
|
||||
@@ -53,8 +53,12 @@ export interface LeaveAnswer {
|
||||
}
|
||||
export type CanLeave = (forced: boolean) => LeaveAnswer
|
||||
|
||||
/** The layers that can hold a form the user must settle before leaving, top one last. */
|
||||
const LAYERS = ['finding', 'reference'] as const
|
||||
/**
|
||||
* The layers that can hold a form the user must settle before leaving, in stacking order
|
||||
* (top one last): the finding dialog, the citations dialog over it (its edit mode, Rev 5),
|
||||
* the reference dialog over either.
|
||||
*/
|
||||
export const LAYERS = ['finding', 'citations', 'reference'] as const
|
||||
export type LayerName = (typeof LAYERS)[number]
|
||||
|
||||
/** One guard per layer (R2F-1): each layer registers its own check while it is mounted. */
|
||||
@@ -132,8 +136,11 @@ export interface EditorNavigation {
|
||||
replaceFinding: (key: ElementKey | null, text?: string) => void
|
||||
/** Opens the citations dialog of a family or a node; any other key is ignored. */
|
||||
openCitations: (citedBy: ElementKey, opener?: Opener) => void
|
||||
/** A user close of the citations dialog. */
|
||||
closeCitations: () => boolean
|
||||
/**
|
||||
* A close of the citations dialog: a user one is refused by its draft (it asks first),
|
||||
* a forced one goes (the draft is dropped).
|
||||
*/
|
||||
closeCitations: (forced?: boolean) => boolean
|
||||
/** « X références », where the focus returns once the citations dialog is closed. */
|
||||
citationsTrigger: () => HTMLElement | null
|
||||
/**
|
||||
@@ -386,7 +393,7 @@ function useFindingClosing({ dispatch, announce, guards, mark }: LayerContext) {
|
||||
|
||||
/** The citations dialog over the finding dialog: opened for a family or a node only. */
|
||||
function useCitationsLayer(ctx: LayerContext, openers: Openers) {
|
||||
const { dispatch, mark } = ctx
|
||||
const { dispatch, guards, mark } = ctx
|
||||
const openCitations = useCallback(
|
||||
(citedBy: ElementKey, opener?: Opener) => {
|
||||
if (!isCitable(citedBy)) return
|
||||
@@ -397,35 +404,48 @@ function useCitationsLayer(ctx: LayerContext, openers: Openers) {
|
||||
},
|
||||
[openers, dispatch, mark],
|
||||
)
|
||||
const closeCitations = useCallback(() => {
|
||||
mark()
|
||||
dispatch({ type: 'close_citations' })
|
||||
return true
|
||||
}, [dispatch, mark])
|
||||
const closeCitations = useCallback(
|
||||
(forced = false) => {
|
||||
if (!guards.ask('citations', forced).allowed) return false
|
||||
mark()
|
||||
dispatch({ type: 'close_citations' })
|
||||
return true
|
||||
},
|
||||
[guards, dispatch, mark],
|
||||
)
|
||||
return { openCitations, closeCitations }
|
||||
}
|
||||
|
||||
/** The layers stacked over `layer`, top one last. */
|
||||
export const layersAbove = (layer: LayerName): LayerName[] =>
|
||||
LAYERS.slice(LAYERS.indexOf(layer) + 1)
|
||||
|
||||
/**
|
||||
* Asks every layer, top down, before a move that leaves them all; true when none refused.
|
||||
* When the finding dialog is the top one to refuse, the clean dialogs over it close first
|
||||
* so its question is the one in view (as a refused Back, `bareFinding`).
|
||||
* The clean dialogs over the top one to refuse close first so its question is the one in
|
||||
* view (as a refused Back, `refusePop`).
|
||||
*/
|
||||
function useAskLeaving(ctx: LayerContext, state: NavigationState) {
|
||||
const { guards, dispatch, mark } = ctx
|
||||
const cited = citationsOfView(state) !== null
|
||||
const citations = citationsOfView(state) !== null
|
||||
const reference = state.reference !== null
|
||||
return useCallback((): boolean => {
|
||||
const refused = [...LAYERS]
|
||||
.reverse()
|
||||
.filter((layer) => !guards.ask(layer, false).allowed)
|
||||
if (refused[0] !== 'finding' || !(cited || reference)) {
|
||||
return refused.length === 0
|
||||
}
|
||||
if (refused.length === 0) return true
|
||||
const above = layersAbove(refused[0])
|
||||
const shown = { finding: false, citations, reference }
|
||||
if (!above.some((layer) => shown[layer])) return false
|
||||
mark()
|
||||
if (reference) dispatch({ type: 'close_reference' })
|
||||
if (cited) dispatch({ type: 'close_citations' })
|
||||
if (above.includes('reference') && reference) {
|
||||
dispatch({ type: 'close_reference' })
|
||||
}
|
||||
if (above.includes('citations') && citations) {
|
||||
dispatch({ type: 'close_citations' })
|
||||
}
|
||||
return false
|
||||
}, [guards, dispatch, mark, cited, reference])
|
||||
}, [guards, dispatch, mark, citations, reference])
|
||||
}
|
||||
|
||||
/** « Aller à » and « Tout afficher » leave every layer: a layer in edit may refuse. */
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useRef, useState, type RefObject } from 'react'
|
||||
import { useCallback, useRef, useState } from 'react'
|
||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||
import type { LayerContext, MoveTrace } from './useEditorNavigation'
|
||||
|
||||
@@ -10,12 +10,19 @@ export interface AddedReference {
|
||||
|
||||
type Opener = HTMLElement | null | undefined
|
||||
|
||||
/** What a creation started from the citations dialog's edit form does with the new id. */
|
||||
export type CiteCreated = (id: string) => void
|
||||
|
||||
/** What the reference dialog (R2F-5) and the References tab's filter (R2F-6) do to the view. */
|
||||
export interface ReferenceMoves {
|
||||
/** The dialog of reference `id`, over the place the view shows. */
|
||||
open: (id: string, opener?: Opener) => void
|
||||
/** The creation dialog, over the References tab. */
|
||||
start: (opener?: Opener) => void
|
||||
/**
|
||||
* The creation dialog, over the References tab or the citations dialog. `cite` is the
|
||||
* citations edit form that started it (Rev 5): the new id goes to its draft, and the
|
||||
* library shows no « added » notice for it.
|
||||
*/
|
||||
start: (opener?: Opener, cite?: CiteCreated) => void
|
||||
/** A user close; false when the form refused it (a dirty draft asks first). */
|
||||
close: (forced?: boolean) => boolean
|
||||
/**
|
||||
@@ -35,19 +42,27 @@ export interface ReferenceMoves {
|
||||
backToFinding: (key: ElementKey) => void
|
||||
}
|
||||
|
||||
/** What the open dialog was started from: its opener, and a citing form for a creation. */
|
||||
interface Held {
|
||||
opener: Opener
|
||||
cite: CiteCreated | null
|
||||
}
|
||||
|
||||
/** The moves that add the dialog: an edit of a reference, a creation. */
|
||||
function useOpening({ dispatch, mark }: LayerContext, held: RefObject<Opener>) {
|
||||
function useOpening({ dispatch, mark }: LayerContext, held: Held) {
|
||||
const open = useCallback(
|
||||
(id: string, opener?: Opener) => {
|
||||
held.current = opener
|
||||
held.opener = opener
|
||||
held.cite = null
|
||||
mark()
|
||||
dispatch({ type: 'open_reference', id })
|
||||
},
|
||||
[dispatch, mark, held],
|
||||
)
|
||||
const start = useCallback(
|
||||
(opener?: Opener) => {
|
||||
held.current = opener
|
||||
(opener?: Opener, cite?: CiteCreated) => {
|
||||
held.opener = opener
|
||||
held.cite = cite ?? null
|
||||
mark()
|
||||
dispatch({ type: 'create_reference' })
|
||||
},
|
||||
@@ -89,14 +104,24 @@ function useClosing(ctx: LayerContext) {
|
||||
return { close: useClose(ctx), replace: useReplace(ctx) }
|
||||
}
|
||||
|
||||
/** A creation that succeeded: its entry becomes the reference's own, then it closes. */
|
||||
function useCreated(ctx: LayerContext, replace: ReferenceMoves['replace']) {
|
||||
/**
|
||||
* A creation that succeeded: its entry becomes the reference's own, then it closes. The
|
||||
* citing form that started it takes the id (no notice); else the library says it.
|
||||
*/
|
||||
function useCreated(
|
||||
ctx: LayerContext,
|
||||
replace: ReferenceMoves['replace'],
|
||||
held: Held,
|
||||
) {
|
||||
const { dispatch, mark } = ctx
|
||||
const [added, setAdded] = useState<AddedReference | null>(null)
|
||||
const created = useCallback(
|
||||
(id: string) => {
|
||||
const citing = held.cite
|
||||
held.cite = null
|
||||
replace(id)
|
||||
setAdded((last) => ({ id, serial: (last?.serial ?? 0) + 1 }))
|
||||
if (citing) citing(id)
|
||||
else setAdded((last) => ({ id, serial: (last?.serial ?? 0) + 1 }))
|
||||
// Precondition: the caller is a discrete event (the form's submit). React then
|
||||
// renders the replace and runs the history effect before this microtask, so the
|
||||
// entry is the reference's own before the close goes back over it and a Forward
|
||||
@@ -108,7 +133,7 @@ function useCreated(ctx: LayerContext, replace: ReferenceMoves['replace']) {
|
||||
dispatch({ type: 'close_reference' })
|
||||
})
|
||||
},
|
||||
[replace, mark, dispatch],
|
||||
[replace, mark, dispatch, held],
|
||||
)
|
||||
return { created, added }
|
||||
}
|
||||
@@ -139,16 +164,16 @@ export function useReferenceMoves(
|
||||
ctx: LayerContext,
|
||||
trace: MoveTrace,
|
||||
): ReferenceMoves {
|
||||
const held = useRef<Opener>(null)
|
||||
const held = useRef<Held>({ opener: null, cite: null }).current
|
||||
const opener = useCallback((): HTMLElement | null => {
|
||||
const element = held.current
|
||||
const element = held.opener
|
||||
return element?.isConnected && !element.closest('[hidden]') ? element : null
|
||||
}, [held])
|
||||
const closing = useClosing(ctx)
|
||||
return {
|
||||
...useOpening(ctx, held),
|
||||
...closing,
|
||||
...useCreated(ctx, closing.replace),
|
||||
...useCreated(ctx, closing.replace, held),
|
||||
...useFilter(ctx, trace),
|
||||
opener,
|
||||
}
|
||||
|
||||
@@ -1229,6 +1229,10 @@ export const en: Dict = {
|
||||
'editor.annotations.deselected': 'No annotation selected.',
|
||||
'editor.references.search': 'Search a reference',
|
||||
'editor.references.dialog_title': 'References of the finding',
|
||||
'editor.citations.edit': 'Edit',
|
||||
'editor.citations.edit_title': 'Edit the references of the finding',
|
||||
'editor.citations.edit_reference': 'Edit the reference',
|
||||
'editor.citations.new_reference': 'New reference',
|
||||
'editor.references.panel_count_one': '{count} reference cited by this finding',
|
||||
'editor.references.panel_count_other': '{count} references cited by this finding',
|
||||
'editor.references.panel_show_all': 'Show all in the References tab',
|
||||
|
||||
@@ -1260,6 +1260,10 @@ export const fr: Dict = {
|
||||
'editor.annotations.deselected': 'Aucune annotation sélectionnée.',
|
||||
'editor.references.search': 'Rechercher une référence',
|
||||
'editor.references.dialog_title': 'Références du constat',
|
||||
'editor.citations.edit': 'Modifier',
|
||||
'editor.citations.edit_title': 'Modifier les références du constat',
|
||||
'editor.citations.edit_reference': 'Modifier la référence',
|
||||
'editor.citations.new_reference': 'Nouvelle référence',
|
||||
'editor.references.panel_count_one': '{count} référence citée par ce constat',
|
||||
'editor.references.panel_count_other': '{count} références citées par ce constat',
|
||||
'editor.references.panel_show_all': 'Tout afficher dans l\'onglet Références',
|
||||
|
||||
@@ -31,6 +31,8 @@ export default function FindingsHost({
|
||||
onShowAll={() => undefined}
|
||||
navigate={nav.navigate}
|
||||
returnFocus={nav.citationsTrigger}
|
||||
guards={nav.guards}
|
||||
references={nav.references}
|
||||
/>
|
||||
</ReadOnlyContext>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/** Rev 5 Task 12: the citations draft, held as additions and removals. */
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
addId,
|
||||
applyEdits,
|
||||
NO_EDITS,
|
||||
removeId,
|
||||
} from '@/editor/references/citationEdits'
|
||||
|
||||
describe('citation edits', () => {
|
||||
it('applies removals and additions to the current list, each id once', () => {
|
||||
const edits = addId(removeId(NO_EDITS, 'a'), 'b')
|
||||
expect(applyEdits(['a', 'c'], edits)).toEqual(['c', 'b'])
|
||||
expect(applyEdits(['a', 'b'], edits)).toEqual(['b'])
|
||||
expect(applyEdits([], edits)).toEqual(['b'])
|
||||
})
|
||||
|
||||
it('a removal then a citation of the same id is no change at all', () => {
|
||||
expect(addId(removeId(NO_EDITS, 'a'), 'a')).toEqual(NO_EDITS)
|
||||
expect(removeId(addId(NO_EDITS, 'n'), 'n')).toEqual(NO_EDITS)
|
||||
})
|
||||
|
||||
it('a repeat is ignored', () => {
|
||||
const once = addId(NO_EDITS, 'b')
|
||||
expect(addId(once, 'b')).toBe(once)
|
||||
const gone = removeId(NO_EDITS, 'a')
|
||||
expect(removeId(gone, 'a')).toBe(gone)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,581 @@
|
||||
/** Rev 5 Task 12: the references dialog's edit mode (draft, save, guards, stacked dialogs). */
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import type { Location, NavigateFunction } from 'react-router-dom'
|
||||
import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry'
|
||||
import {
|
||||
forgetSessionTag,
|
||||
resolveSessionTag,
|
||||
} from '@/editor/history/sessionTag'
|
||||
import { useAuthStore } from '@/state/authStore'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { edit, insert } from '../helpers/editorFixtures'
|
||||
import {
|
||||
baseText,
|
||||
resetStore,
|
||||
serverHas,
|
||||
SHEET,
|
||||
store,
|
||||
USER,
|
||||
} from '../helpers/editorHarness'
|
||||
import { mountDraft, setWidth } from '../helpers/editorRoute'
|
||||
import {
|
||||
findingDialog,
|
||||
inFindingDialog,
|
||||
openFinding,
|
||||
} from '../helpers/findingDialog'
|
||||
|
||||
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
|
||||
vi.mock('@faunosteo/supabase', async (orig) => ({
|
||||
...(await orig<typeof import('@faunosteo/supabase')>()),
|
||||
getSheetVersion: vi.fn(),
|
||||
downloadSheetDrawing: vi.fn(),
|
||||
saveSheetDraft: vi.fn(),
|
||||
getOfficialSheetAdmin: vi.fn(),
|
||||
submitSheetReview: vi.fn(),
|
||||
}))
|
||||
|
||||
let navigate: NavigateFunction
|
||||
let location: Location
|
||||
const probe = (n: NavigateFunction, l: Location) => {
|
||||
navigate = n
|
||||
location = l
|
||||
}
|
||||
const written = () =>
|
||||
(location.state as Record<string, HistoryEntry> | null)?.[ENTRY_KEY]
|
||||
|
||||
let TAG: string
|
||||
beforeEach(() => {
|
||||
useLocaleStore.setState({ locale: 'fr' })
|
||||
TAG = resolveSessionTag(USER)
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
resetStore()
|
||||
setWidth(1024)
|
||||
})
|
||||
|
||||
const name = (n: string) => ({ fr: n, en: n })
|
||||
const ref = (id: string, citation: string) =>
|
||||
({
|
||||
kind: 'reference',
|
||||
value: { id, type: 'book', citation, url: null, doi: null },
|
||||
}) as const
|
||||
|
||||
/** Barone (ref-a), Denoix (ref-b), Code rural (ref-c); Node A cites `ids`. */
|
||||
function sheetText(ids = ['ref-a', 'ref-c']): string {
|
||||
let text = baseText()
|
||||
text = insert(text, ref('ref-a', 'Barone, Ostéologie'))
|
||||
text = insert(text, ref('ref-b', 'Denoix'))
|
||||
text = insert(text, ref('ref-c', 'Code rural'))
|
||||
text = insert(text, {
|
||||
kind: 'zone',
|
||||
value: { id: 'zone-a', name: name('Zone A'), categories: [] },
|
||||
})
|
||||
text = edit(text, {
|
||||
op: 'insert',
|
||||
parent: { kind: 'zone', id: 'zone-a' },
|
||||
element: {
|
||||
kind: 'finding_category',
|
||||
value: {
|
||||
id: 'fcat-a',
|
||||
kind: 'dysfunction',
|
||||
name: name('Cat A'),
|
||||
description: {},
|
||||
reference_ids: [],
|
||||
review_status: 'to_confirm',
|
||||
children: [],
|
||||
},
|
||||
},
|
||||
})
|
||||
return edit(text, {
|
||||
op: 'insert',
|
||||
parent: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] },
|
||||
element: {
|
||||
kind: 'finding_node',
|
||||
value: {
|
||||
id: 'fnode-a',
|
||||
name: name('Node A'),
|
||||
description: {},
|
||||
reference_ids: ids,
|
||||
requires_vet_referral: false,
|
||||
review_status: 'to_confirm',
|
||||
children: [],
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const nodeKey = {
|
||||
kind: 'finding' as const,
|
||||
zone_id: 'zone-a',
|
||||
path: ['fcat-a', 'fnode-a'],
|
||||
}
|
||||
|
||||
type User = ReturnType<typeof userEvent.setup>
|
||||
|
||||
async function mount(width = 1280, text = sheetText()): Promise<User> {
|
||||
serverHas(text, 3)
|
||||
const user = userEvent.setup()
|
||||
mountDraft({ width, probe })
|
||||
await screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
|
||||
await user.click(screen.getByRole('tab', { name: 'Constats' }))
|
||||
await waitFor(() => expect(written()?.view.tab).toBe('findings'))
|
||||
return user
|
||||
}
|
||||
|
||||
const doc = () => JSON.parse(store.getState().documentText)
|
||||
const nodeA = () =>
|
||||
doc().finding_zones[0].categories[0].children[0] as {
|
||||
name: { fr: string }
|
||||
reference_ids: string[]
|
||||
}
|
||||
const library = () =>
|
||||
(doc().references as { id: string; citation: string }[]).map(
|
||||
(r) => r.citation,
|
||||
)
|
||||
const undos = () => store.getState().undo.length
|
||||
const back = (steps = 1) => act(async () => navigate(-steps))
|
||||
const question = 'Abandonner les modifications ?'
|
||||
|
||||
const openDialogs = () => [
|
||||
...document.querySelectorAll<HTMLElement>('dialog[open][data-layer]'),
|
||||
]
|
||||
const citations = () =>
|
||||
openDialogs().find((d) => d.querySelector('[data-place="citations"]'))
|
||||
const inCitations = () => within(citations()!)
|
||||
const referenceDialog = () =>
|
||||
openDialogs().find((d) => d.querySelector('#reference-form-citation'))
|
||||
const inReference = () => within(referenceDialog()!)
|
||||
const button = (label: string | RegExp) =>
|
||||
inCitations().getByRole('button', { name: label })
|
||||
const rows = () =>
|
||||
[...citations()!.querySelectorAll('[data-citation-row]')].map((row) =>
|
||||
row.getAttribute('data-citation-row'),
|
||||
)
|
||||
|
||||
/** Node A's dialog, then its references dialog. */
|
||||
async function openCitations(user: User, trigger = '2 références') {
|
||||
await openFinding(user, /Node A/)
|
||||
await user.click(inFindingDialog().getByRole('button', { name: trigger }))
|
||||
await waitFor(() => expect(citations()).toBeDefined())
|
||||
}
|
||||
|
||||
/** The references dialog of Node A, in its edit mode. */
|
||||
async function editCitations(user: User, trigger?: string) {
|
||||
await openCitations(user, trigger)
|
||||
await user.click(button('Modifier'))
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
inCitations().getByRole('heading', {
|
||||
name: 'Modifier les références du constat',
|
||||
}),
|
||||
).toBeVisible(),
|
||||
)
|
||||
}
|
||||
|
||||
const removeRow = (user: User, citation: RegExp) =>
|
||||
user.click(
|
||||
inCitations().getByRole('button', {
|
||||
name: new RegExp(`^Retirer ${citation.source}`),
|
||||
}),
|
||||
)
|
||||
const cite = (user: User, id: string) =>
|
||||
user.selectOptions(inCitations().getByLabelText('Citer une référence'), id)
|
||||
|
||||
describe('the « Modifier » of the references dialog', () => {
|
||||
it('switches to the edit mode: no history entry, no « Tout afficher », no « Aller à »', async () => {
|
||||
const user = await mount()
|
||||
await openCitations(user)
|
||||
const before = written()!.id
|
||||
await user.click(button('Modifier'))
|
||||
expect(written()!.id).toBe(before)
|
||||
expect(rows()).toEqual(['ref-a', 'ref-c'])
|
||||
expect(
|
||||
inCitations().queryByRole('button', { name: /Tout afficher/ }),
|
||||
).toBeNull()
|
||||
expect(inCitations().queryByRole('button', { name: 'Aller à' })).toBeNull()
|
||||
})
|
||||
|
||||
it('is not offered read only (below 1 024 px)', async () => {
|
||||
const user = await mount(900)
|
||||
await openCitations(user)
|
||||
expect(inCitations().queryByRole('button', { name: 'Modifier' })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('the draft', () => {
|
||||
it('stages a removal and a citation, writes nothing until « Enregistrer »', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await removeRow(user, /Barone/)
|
||||
await cite(user, 'ref-b')
|
||||
expect(rows()).toEqual(['ref-c', 'ref-b'])
|
||||
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
|
||||
expect(undos()).toBe(0)
|
||||
})
|
||||
|
||||
it('one save is one update, one undo; back to the view mode, focus on « Modifier »', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await removeRow(user, /Barone/)
|
||||
await cite(user, 'ref-b')
|
||||
await user.click(button('Enregistrer'))
|
||||
expect(nodeA().reference_ids).toEqual(['ref-c', 'ref-b'])
|
||||
expect(undos()).toBe(1)
|
||||
await waitFor(() => expect(button('Modifier')).toHaveFocus())
|
||||
expect(
|
||||
inCitations().getByText('Modifications enregistrées'),
|
||||
).toBeInTheDocument()
|
||||
act(() => {
|
||||
store.getState().undoStep()
|
||||
})
|
||||
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
|
||||
})
|
||||
|
||||
it('a pristine save writes nothing', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await user.click(button('Enregistrer'))
|
||||
expect(undos()).toBe(0)
|
||||
await waitFor(() => expect(button('Modifier')).toHaveFocus())
|
||||
expect(inCitations().queryByText('Modifications enregistrées')).toBeNull()
|
||||
})
|
||||
|
||||
it('a dangling id is named and removable', async () => {
|
||||
const user = await mount(1280, sheetText(['ref-a', 'ref-x']))
|
||||
await editCitations(user)
|
||||
expect(inCitations().getByText(/^Référence introuvable/)).toBeVisible()
|
||||
await removeRow(user, /ref-x/)
|
||||
await user.click(button('Enregistrer'))
|
||||
expect(nodeA().reference_ids).toEqual(['ref-a'])
|
||||
})
|
||||
|
||||
it('a save keeps citations changed elsewhere: removals and additions on the current list', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await removeRow(user, /Barone/)
|
||||
act(() => {
|
||||
const node = doc().finding_zones[0].categories[0].children[0]
|
||||
store.getState().commit({
|
||||
op: 'update',
|
||||
key: nodeKey,
|
||||
element: {
|
||||
kind: 'finding_node',
|
||||
value: { ...node, reference_ids: ['ref-a', 'ref-c', 'ref-b'] },
|
||||
},
|
||||
})
|
||||
})
|
||||
await user.click(button('Enregistrer'))
|
||||
expect(nodeA().reference_ids).toEqual(['ref-c', 'ref-b'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('leaving the edit mode with changes', () => {
|
||||
it('« Annuler » asks; « Abandonner » goes back to the view, nothing written', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await removeRow(user, /Barone/)
|
||||
await user.click(button('Annuler'))
|
||||
expect(inCitations().getByText(question)).toBeVisible()
|
||||
await user.click(button('Abandonner'))
|
||||
await waitFor(() => expect(button('Modifier')).toHaveFocus())
|
||||
expect(citations()).toBeDefined()
|
||||
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
|
||||
})
|
||||
|
||||
it('« Annuler » without changes goes back at once', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await user.click(button('Annuler'))
|
||||
await waitFor(() => expect(button('Modifier')).toHaveFocus())
|
||||
})
|
||||
|
||||
it('Escape and ✕ ask; the dialog stays', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await removeRow(user, /Barone/)
|
||||
await user.click(button('Fermer'))
|
||||
expect(citations()).toBeDefined()
|
||||
expect(inCitations().getByText(question)).toBeVisible()
|
||||
await user.click(button('Continuer la saisie'))
|
||||
act(() => button('Annuler').focus())
|
||||
await user.keyboard('{Escape}')
|
||||
expect(citations()).toBeDefined()
|
||||
expect(inCitations().getByText(question)).toBeVisible()
|
||||
})
|
||||
|
||||
it('a Back that closes only the references dialog asks; the draft stays', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await removeRow(user, /Barone/)
|
||||
await back()
|
||||
expect(citations()).toBeDefined()
|
||||
expect(inCitations().getByText(question)).toBeVisible()
|
||||
expect(rows()).toEqual(['ref-c'])
|
||||
expect(written()!.view.finding).toMatchObject({ citations: true })
|
||||
})
|
||||
|
||||
it('a flip to read only keeps the draft, every control off, only « Abandonner »', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await removeRow(user, /Barone/)
|
||||
act(() => {
|
||||
setWidth(900)
|
||||
window.dispatchEvent(new Event('resize'))
|
||||
})
|
||||
expect(rows()).toEqual(['ref-c'])
|
||||
expect(inCitations().getByText(/Élargissez la fenêtre/)).toBeVisible()
|
||||
expect(button('Enregistrer')).toBeDisabled()
|
||||
expect(button(/^Retirer/)).toBeDisabled()
|
||||
expect(button(/^Modifier la référence/)).toBeDisabled()
|
||||
expect(button('Nouvelle référence')).toBeDisabled()
|
||||
expect(inCitations().queryByLabelText('Citer une référence')).toBeNull()
|
||||
expect(inCitations().queryByRole('button', { name: 'Annuler' })).toBeNull()
|
||||
await user.click(button('Abandonner'))
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
inCitations().getByRole('heading', { name: 'Références du constat' }),
|
||||
).toBeVisible(),
|
||||
)
|
||||
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('the reference dialog over the edit mode', () => {
|
||||
it('« Modifier la référence » stacks it; closed, the draft and the focus are back', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await removeRow(user, /Code rural/)
|
||||
const opener = button(/^Modifier la référence Barone/)
|
||||
await user.click(opener)
|
||||
await waitFor(() => expect(referenceDialog()).toBeDefined())
|
||||
expect(openDialogs()).toHaveLength(3)
|
||||
expect(
|
||||
inReference().getByRole('heading', { name: 'Modifier la référence' }),
|
||||
).toBeVisible()
|
||||
await user.click(inReference().getByRole('button', { name: 'Fermer' }))
|
||||
await waitFor(() => expect(referenceDialog()).toBeUndefined())
|
||||
await waitFor(() => expect(opener).toHaveFocus())
|
||||
expect(rows()).toEqual(['ref-a'])
|
||||
})
|
||||
|
||||
it('« Nouvelle référence » creates it and cites it in the draft only', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await user.click(button('Nouvelle référence'))
|
||||
await waitFor(() => expect(referenceDialog()).toBeDefined())
|
||||
expect(screen.getByRole('tab', { name: 'Constats' })).toHaveAttribute(
|
||||
'aria-selected',
|
||||
'true',
|
||||
)
|
||||
await user.selectOptions(inReference().getByLabelText('Type'), 'book')
|
||||
await user.type(inReference().getByLabelText('Citation'), 'Neuf')
|
||||
await user.click(
|
||||
inReference().getByRole('button', { name: 'Ajouter la référence' }),
|
||||
)
|
||||
await waitFor(() => expect(referenceDialog()).toBeUndefined())
|
||||
expect(library()).toContain('Neuf')
|
||||
const id = doc().references.find(
|
||||
(r: { citation: string }) => r.citation === 'Neuf',
|
||||
).id
|
||||
expect(rows()).toEqual(['ref-a', 'ref-c', id])
|
||||
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
|
||||
await user.click(button('Enregistrer'))
|
||||
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c', id])
|
||||
expect(undos()).toBe(2)
|
||||
})
|
||||
|
||||
it('a reference created, then the draft abandoned, stays in the library uncited', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await user.click(button('Nouvelle référence'))
|
||||
await waitFor(() => expect(referenceDialog()).toBeDefined())
|
||||
await user.selectOptions(inReference().getByLabelText('Type'), 'book')
|
||||
await user.type(inReference().getByLabelText('Citation'), 'Neuf')
|
||||
await user.click(
|
||||
inReference().getByRole('button', { name: 'Ajouter la référence' }),
|
||||
)
|
||||
await waitFor(() => expect(referenceDialog()).toBeUndefined())
|
||||
await user.click(button('Annuler'))
|
||||
await user.click(button('Abandonner'))
|
||||
expect(library()).toContain('Neuf')
|
||||
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
|
||||
expect(undos()).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('a finding draft and a references draft on the same element', () => {
|
||||
it('are both saved; neither overwrites the other', async () => {
|
||||
const user = await mount()
|
||||
await openFinding(user, /Node A/)
|
||||
await user.click(
|
||||
inFindingDialog().getByRole('button', { name: 'Modifier' }),
|
||||
)
|
||||
await user.type(inFindingDialog().getByLabelText('Nom (FR)'), ' bis')
|
||||
await user.click(
|
||||
inFindingDialog().getByRole('button', { name: '2 références' }),
|
||||
)
|
||||
await waitFor(() => expect(citations()).toBeDefined())
|
||||
await user.click(button('Modifier'))
|
||||
await removeRow(user, /Barone/)
|
||||
await user.click(button('Enregistrer'))
|
||||
await user.click(button('Fermer'))
|
||||
await waitFor(() => expect(citations()).toBeUndefined())
|
||||
await user.click(
|
||||
inFindingDialog().getByRole('button', { name: 'Enregistrer' }),
|
||||
)
|
||||
expect(nodeA().name.fr).toBe('Node A bis')
|
||||
expect(nodeA().reference_ids).toEqual(['ref-c'])
|
||||
expect(undos()).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('leaving the editor with a citations draft', () => {
|
||||
it('a sign-out leaves the account flag of the citations layer', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await removeRow(user, /Barone/)
|
||||
act(() => {
|
||||
forgetSessionTag()
|
||||
useAuthStore.setState({ user: null })
|
||||
})
|
||||
await waitFor(() => expect(citations()).toBeUndefined())
|
||||
const flags = Object.keys(sessionStorage)
|
||||
.filter((k) => k.startsWith('faunosteo:editor:left-draft-account:'))
|
||||
.map((k) => JSON.parse(sessionStorage.getItem(k)!))
|
||||
expect(flags).toHaveLength(1)
|
||||
expect(flags[0]).toMatchObject({ kind: 'citations', key: nodeKey })
|
||||
expect(JSON.stringify(flags)).not.toContain('Barone')
|
||||
})
|
||||
|
||||
it('a plain leave flags the citations layer', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await removeRow(user, /Barone/)
|
||||
cleanup()
|
||||
const flag = sessionStorage.getItem(
|
||||
`faunosteo:editor:left-draft:${SHEET}:${TAG}`,
|
||||
)
|
||||
expect(JSON.parse(flag!)).toEqual({ kind: 'citations', key: nodeKey })
|
||||
})
|
||||
})
|
||||
|
||||
/** The Navigation API as the leave guard reads it: `navigate` events and `traverseTo`. */
|
||||
class NavigationStub extends EventTarget {
|
||||
traverseTo = vi.fn((key: string) => {
|
||||
void key
|
||||
return { committed: Promise.resolve(), finished: Promise.resolve() }
|
||||
})
|
||||
}
|
||||
|
||||
describe('a reference over the references dialog of a dirty finding (criterion 23)', () => {
|
||||
let api: NavigationStub
|
||||
beforeEach(() => {
|
||||
api = new NavigationStub()
|
||||
Object.defineProperty(window, 'navigation', {
|
||||
value: api,
|
||||
configurable: true,
|
||||
})
|
||||
})
|
||||
afterEach(() => {
|
||||
Reflect.deleteProperty(window, 'navigation')
|
||||
})
|
||||
|
||||
function jump() {
|
||||
const url = new URL('/app/admin/sheets', window.location.origin).href
|
||||
const event = Object.assign(new Event('navigate', { cancelable: true }), {
|
||||
navigationType: 'traverse',
|
||||
destination: { url, key: 'list', sameDocument: true },
|
||||
})
|
||||
act(() => {
|
||||
api.dispatchEvent(event)
|
||||
})
|
||||
return event
|
||||
}
|
||||
|
||||
/** Node A in edit with a typed name, its references in edit, Barone in edit, typed. */
|
||||
async function stacked(user: User) {
|
||||
await openFinding(user, /Node A/)
|
||||
await user.click(
|
||||
inFindingDialog().getByRole('button', { name: 'Modifier' }),
|
||||
)
|
||||
await user.type(inFindingDialog().getByLabelText('Nom (FR)'), ' bis')
|
||||
await user.click(
|
||||
inFindingDialog().getByRole('button', { name: '2 références' }),
|
||||
)
|
||||
await waitFor(() => expect(citations()).toBeDefined())
|
||||
await user.click(button('Modifier'))
|
||||
await user.click(button(/^Modifier la référence Barone/))
|
||||
await waitFor(() => expect(referenceDialog()).toBeDefined())
|
||||
await user.type(inReference().getByLabelText('Citation'), ' x')
|
||||
}
|
||||
|
||||
it('the finding asks next with the references dialog closed, focused; the jump goes after it', async () => {
|
||||
const user = await mount()
|
||||
await stacked(user)
|
||||
expect(jump().defaultPrevented).toBe(true)
|
||||
expect(inReference().getByText(question)).toBeVisible()
|
||||
await user.click(inReference().getByRole('button', { name: 'Abandonner' }))
|
||||
await waitFor(() => expect(referenceDialog()).toBeUndefined())
|
||||
await waitFor(() => expect(citations()).toBeUndefined())
|
||||
const finding = within(findingDialog()!)
|
||||
expect(finding.getByText(question)).toBeVisible()
|
||||
const keep = finding.getByRole('button', { name: 'Continuer la saisie' })
|
||||
await waitFor(() => expect(keep).toHaveFocus())
|
||||
expect(api.traverseTo).not.toHaveBeenCalled()
|
||||
await user.click(finding.getByRole('button', { name: 'Abandonner' }))
|
||||
expect(api.traverseTo).toHaveBeenCalledWith('list')
|
||||
})
|
||||
|
||||
it('« Continuer la saisie » there keeps the finding draft and drops the jump', async () => {
|
||||
const user = await mount()
|
||||
await stacked(user)
|
||||
jump()
|
||||
await user.click(inReference().getByRole('button', { name: 'Abandonner' }))
|
||||
await waitFor(() => expect(citations()).toBeUndefined())
|
||||
const finding = within(findingDialog()!)
|
||||
await user.click(
|
||||
finding.getByRole('button', { name: 'Continuer la saisie' }),
|
||||
)
|
||||
expect(finding.getByLabelText('Nom (FR)')).toHaveValue('Node A bis')
|
||||
expect(api.traverseTo).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('a citations draft under a clean reference dialog asks once the reference is closed', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await removeRow(user, /Code rural/)
|
||||
await user.click(button(/^Modifier la référence Barone/))
|
||||
await waitFor(() => expect(referenceDialog()).toBeDefined())
|
||||
expect(jump().defaultPrevented).toBe(true)
|
||||
await waitFor(() => expect(referenceDialog()).toBeUndefined())
|
||||
expect(inCitations().getByText(question)).toBeVisible()
|
||||
const keep = inCitations().getByRole('button', {
|
||||
name: 'Continuer la saisie',
|
||||
})
|
||||
await waitFor(() => expect(keep).toHaveFocus())
|
||||
await user.click(button('Abandonner'))
|
||||
expect(api.traverseTo).toHaveBeenCalledWith('list')
|
||||
})
|
||||
})
|
||||
|
||||
describe('a Back over a citations draft under a clean reference dialog', () => {
|
||||
it('the reference dialog closes, the draft asks, the view is pushed again', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await removeRow(user, /Code rural/)
|
||||
await user.click(button(/^Modifier la référence Barone/))
|
||||
await waitFor(() => expect(referenceDialog()).toBeDefined())
|
||||
await back(2)
|
||||
await waitFor(() => expect(referenceDialog()).toBeUndefined())
|
||||
expect(citations()).toBeDefined()
|
||||
expect(inCitations().getByText(question)).toBeVisible()
|
||||
expect(rows()).toEqual(['ref-a'])
|
||||
expect(written()!.view).toMatchObject({
|
||||
reference: null,
|
||||
finding: { citations: true },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,172 @@
|
||||
/** Rev 5 Task 12: the citations layer's guard (Back, refusal, close, order, creation). */
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, render } from '@testing-library/react'
|
||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||
import {
|
||||
MemoryRouter,
|
||||
useLocation,
|
||||
useNavigate,
|
||||
type Location,
|
||||
type NavigateFunction,
|
||||
} from 'react-router-dom'
|
||||
import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry'
|
||||
import useEditorHistory from '@/editor/history/useEditorHistory'
|
||||
import { LAYERS_TOP_DOWN, topDirtyLayer } from '@/editor/leftDraft'
|
||||
import { defaultView } from '@/editor/navigation'
|
||||
import {
|
||||
useEditorNavigation,
|
||||
type EditorNavigation,
|
||||
type LayerName,
|
||||
} from '@/editor/useEditorNavigation'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const owner = { sheetId: 'S', tag: 'T' }
|
||||
const node: ElementKey = {
|
||||
kind: 'finding',
|
||||
zone_id: 'zone',
|
||||
path: ['family', 'node'],
|
||||
}
|
||||
|
||||
let nav: EditorNavigation
|
||||
let navigate: NavigateFunction
|
||||
let location: Location
|
||||
const entry = () => (location.state as Record<string, HistoryEntry>)[ENTRY_KEY]
|
||||
|
||||
function Page() {
|
||||
nav = useEditorNavigation('findings')
|
||||
navigate = useNavigate()
|
||||
location = useLocation()
|
||||
useEditorHistory(nav, owner, defaultView('findings'))
|
||||
return null
|
||||
}
|
||||
|
||||
function mount() {
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/x']}>
|
||||
<Page />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
}
|
||||
|
||||
/** A layer whose form holds changes: a user ask refuses, a forced one says the note. */
|
||||
const dirty = vi.fn((forced: boolean) =>
|
||||
forced ? { allowed: true, note: 'dropped' } : { allowed: false },
|
||||
)
|
||||
const register = (layer: LayerName) =>
|
||||
act(() => nav.guards.register(layer, dirty))
|
||||
|
||||
/** Node's finding dialog, then its citations dialog: two entries. */
|
||||
function cited() {
|
||||
mount()
|
||||
act(() => nav.openFinding(node))
|
||||
act(() => nav.openCitations(node))
|
||||
}
|
||||
|
||||
describe('the layer order', () => {
|
||||
it('reference, citations, finding: asked top down', () => {
|
||||
expect(LAYERS_TOP_DOWN).toEqual(['reference', 'citations', 'finding'])
|
||||
mount()
|
||||
const order: string[] = []
|
||||
for (const layer of ['finding', 'citations', 'reference'] as const) {
|
||||
nav.guards.register(layer, () => {
|
||||
order.push(layer)
|
||||
return { allowed: true }
|
||||
})
|
||||
}
|
||||
nav.guards.askAll(false)
|
||||
expect(order).toEqual(['reference', 'citations', 'finding'])
|
||||
})
|
||||
|
||||
it('topDirtyLayer: citations over finding, reference over both', () => {
|
||||
mount()
|
||||
register('finding')
|
||||
register('citations')
|
||||
expect(topDirtyLayer(nav.guards)).toBe('citations')
|
||||
expect(topDirtyLayer(nav.guards, 'citations')).toBe('finding')
|
||||
register('reference')
|
||||
expect(topDirtyLayer(nav.guards)).toBe('reference')
|
||||
expect(topDirtyLayer(nav.guards, 'reference')).toBe('citations')
|
||||
})
|
||||
})
|
||||
|
||||
describe('a Back over a citations draft', () => {
|
||||
it('closing only the citations dialog asks; the view and the entry stay', () => {
|
||||
cited()
|
||||
register('citations')
|
||||
dirty.mockClear()
|
||||
act(() => navigate(-1))
|
||||
expect(dirty).toHaveBeenCalledWith(false)
|
||||
expect(nav.state.finding).toMatchObject({ citations: true })
|
||||
expect(entry().view.finding).toMatchObject({ citations: true })
|
||||
})
|
||||
|
||||
it('a clean citations layer lets it close', () => {
|
||||
cited()
|
||||
act(() => nav.guards.register('citations', () => ({ allowed: true })))
|
||||
act(() => navigate(-1))
|
||||
expect(nav.state.finding).toMatchObject({ citations: false })
|
||||
})
|
||||
|
||||
it('under a clean reference dialog: the reference closes, the draft asks', () => {
|
||||
cited()
|
||||
act(() => nav.references.open('ref-a'))
|
||||
register('citations')
|
||||
dirty.mockClear()
|
||||
act(() => navigate(-2))
|
||||
expect(dirty).toHaveBeenCalledWith(false)
|
||||
expect(nav.state.reference).toBeNull()
|
||||
expect(nav.state.finding).toMatchObject({ citations: true })
|
||||
expect(entry().view).toMatchObject({
|
||||
reference: null,
|
||||
finding: { citations: true },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('closeCitations', () => {
|
||||
it('a user close is refused by a draft; a forced one goes', () => {
|
||||
cited()
|
||||
register('citations')
|
||||
let closed = true
|
||||
act(() => {
|
||||
closed = nav.closeCitations()
|
||||
})
|
||||
expect(closed).toBe(false)
|
||||
expect(nav.state.finding).toMatchObject({ citations: true })
|
||||
act(() => {
|
||||
closed = nav.closeCitations(true)
|
||||
})
|
||||
expect(closed).toBe(true)
|
||||
expect(nav.state.finding).toMatchObject({ citations: false })
|
||||
})
|
||||
})
|
||||
|
||||
describe('a creation started over the citations dialog', () => {
|
||||
it('hands its id to the form that started it; no « added » notice', async () => {
|
||||
cited()
|
||||
const cite = vi.fn()
|
||||
act(() => nav.references.start(null, cite))
|
||||
expect(nav.state).toMatchObject({
|
||||
tab: 'findings',
|
||||
reference: { create: true },
|
||||
})
|
||||
await act(async () => nav.references.created('ref-new'))
|
||||
expect(cite).toHaveBeenCalledWith('ref-new')
|
||||
expect(nav.references.added).toBeNull()
|
||||
expect(nav.state.reference).toBeNull()
|
||||
expect(nav.state.finding).toMatchObject({ citations: true })
|
||||
})
|
||||
|
||||
it('a later creation from the library sets the notice, cites nothing', async () => {
|
||||
cited()
|
||||
const cite = vi.fn()
|
||||
act(() => nav.references.start(null, cite))
|
||||
act(() => nav.references.close(true))
|
||||
act(() => nav.selectTab('references'))
|
||||
act(() => nav.references.start(null))
|
||||
await act(async () => nav.references.created('ref-lib'))
|
||||
expect(cite).not.toHaveBeenCalled()
|
||||
expect(nav.references.added).toMatchObject({ id: 'ref-lib' })
|
||||
})
|
||||
})
|
||||
@@ -281,10 +281,10 @@ describe('Escape with the focus on the page', () => {
|
||||
await select(user)
|
||||
await openCitations(user)
|
||||
const trigger = screen.getByRole('button', { name: '1 référence' })
|
||||
expect(trigger).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(trigger).toHaveAttribute('aria-haspopup', 'dialog')
|
||||
await user.keyboard('{Escape}')
|
||||
await waitFor(() => expect(citations()).toBeNull())
|
||||
expect(trigger).toHaveAttribute('aria-expanded', 'false')
|
||||
await waitFor(() => expect(trigger).toHaveFocus())
|
||||
// the finding dialog under the sheet is still there: a second Escape closes it
|
||||
expect(document.querySelector('dialog[open]')).not.toBeNull()
|
||||
await user.keyboard('{Escape}')
|
||||
|
||||
@@ -109,6 +109,10 @@ describe('sanitizeView', () => {
|
||||
expect(sanitizeView(creation)?.reference).toEqual({ create: true })
|
||||
const elsewhere = { ...view('general'), reference: { create: true } }
|
||||
expect(sanitizeView(elsewhere)?.reference).toBeNull()
|
||||
// Rev 5: a creation over the citations dialog is never read back (POP, reload).
|
||||
const overCitations = { ...sheet, reference: { create: true } }
|
||||
expect(sanitizeView(overCitations)?.reference).toBeNull()
|
||||
expect(sanitizeView(overCitations)?.finding).toEqual(sheet.finding)
|
||||
expect(
|
||||
sanitizeView({ ...tab, reference: { edit: '' } })?.reference,
|
||||
).toBeNull()
|
||||
|
||||
@@ -46,6 +46,7 @@ function Editor() {
|
||||
return (
|
||||
<>
|
||||
<Layer guards={nav.guards} layer="finding" />
|
||||
<Layer guards={nav.guards} layer="citations" />
|
||||
<Layer guards={nav.guards} layer="reference" />
|
||||
</>
|
||||
)
|
||||
@@ -93,23 +94,28 @@ const layer = (name: LayerName) => screen.queryByTestId(name)
|
||||
const button = (name: LayerName, label: string) =>
|
||||
within(layer(name)!).getByRole('button', { name: label })
|
||||
|
||||
describe('a reference dialog over a finding dialog, both dirty', () => {
|
||||
it('asks the reference, then the finding, then the jump goes', async () => {
|
||||
describe('reference, citations and finding dialogs, all dirty', () => {
|
||||
it('asks the reference, the citations, then the finding, then the jump goes', async () => {
|
||||
const user = userEvent.setup()
|
||||
expect(jump().defaultPrevented).toBe(true)
|
||||
expect(within(layer('finding')!).queryByRole('group')).toBeNull()
|
||||
expect(within(layer('citations')!).queryByRole('group')).toBeNull()
|
||||
await user.click(button('reference', 'Abandonner'))
|
||||
expect(layer('reference')).toBeNull()
|
||||
expect(within(layer('finding')!).queryByRole('group')).toBeNull()
|
||||
await user.click(button('citations', 'Abandonner'))
|
||||
expect(layer('citations')).toBeNull()
|
||||
expect(api.traverseTo).not.toHaveBeenCalled()
|
||||
await user.click(button('finding', 'Abandonner'))
|
||||
expect(api.traverseTo).toHaveBeenCalledTimes(1)
|
||||
expect(api.traverseTo).toHaveBeenCalledWith('list')
|
||||
})
|
||||
|
||||
it('« Continuer la saisie » on the second keeps the finding, no jump', async () => {
|
||||
it('« Continuer la saisie » on the last keeps the finding, no jump', async () => {
|
||||
const user = userEvent.setup()
|
||||
jump()
|
||||
await user.click(button('reference', 'Abandonner'))
|
||||
await user.click(button('citations', 'Abandonner'))
|
||||
await user.click(button('finding', 'Continuer la saisie'))
|
||||
expect(layer('finding')).not.toBeNull()
|
||||
expect(within(layer('finding')!).queryByRole('group')).toBeNull()
|
||||
@@ -121,6 +127,7 @@ describe('a reference dialog over a finding dialog, both dirty', () => {
|
||||
jump()
|
||||
await user.click(button('reference', 'Continuer la saisie'))
|
||||
expect(layer('reference')).not.toBeNull()
|
||||
expect(layer('citations')).not.toBeNull()
|
||||
expect(layer('finding')).not.toBeNull()
|
||||
expect(api.traverseTo).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -180,6 +180,20 @@ describe('navigationReducer', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('a creation over the citations dialog keeps the tab and both dialogs under it', () => {
|
||||
const created = run(
|
||||
initialNavigation('findings'),
|
||||
{ type: 'open_finding', key: node },
|
||||
{ type: 'open_citations', citedBy: node },
|
||||
{ type: 'create_reference' },
|
||||
)
|
||||
expect(created).toMatchObject({
|
||||
tab: 'findings',
|
||||
finding: { key: node, citations: true },
|
||||
reference: { create: true },
|
||||
})
|
||||
})
|
||||
|
||||
it('the filter belongs to the References tab: any move to another tab drops it', () => {
|
||||
const filtered = run(initialNavigation('findings'), {
|
||||
type: 'show_all_references',
|
||||
|
||||
@@ -223,7 +223,7 @@ describe('opening', () => {
|
||||
expect(panel()).not.toHaveTextContent('Denoix')
|
||||
})
|
||||
|
||||
it('view mode: an open tile marks the current finding, « Aller à » only, no edit control', async () => {
|
||||
it('view mode: an open tile marks the current finding, « Aller à » only; « Modifier » is the dialog’s', async () => {
|
||||
const user = await mount()
|
||||
await openFromFinding(user)
|
||||
await user.click(within(panel()).getByRole('button', { name: /^Barone/ }))
|
||||
@@ -239,9 +239,14 @@ describe('opening', () => {
|
||||
'Monter',
|
||||
'Descendre',
|
||||
]) {
|
||||
expect(within(tile).queryByRole('button', { name: absent })).toBeNull()
|
||||
expect(
|
||||
within(citationsDialog()).queryByRole('button', { name: absent }),
|
||||
).toBeNull()
|
||||
).toBe(
|
||||
absent === 'Modifier'
|
||||
? document.getElementById('citations-edit-button')
|
||||
: null,
|
||||
)
|
||||
}
|
||||
expect(within(citationsDialog()).queryByRole('searchbox')).toBeNull()
|
||||
expect(within(citationsDialog()).queryByRole('textbox')).toBeNull()
|
||||
|
||||
Reference in new issue
Block a user