feat(editor): a reference made in the citations draft saves with it
This commit is contained in:
1 parent
8c3fcca0b9
commit
70eb2fcbb4
15 files changed
+671
-162
No files matched your search
@@ -585,17 +585,16 @@ test.describe('references dialog, edit mode', () => {
|
||||
expect(nodeOf(saved).reference_ids).toEqual(['ref-a', 'ref-b'])
|
||||
})
|
||||
|
||||
test('« Nouvelle référence » is created over the dialog and cited by the save', async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000)
|
||||
const { seed } = await open(page)
|
||||
await editCitations(page)
|
||||
/** « Nouvelle référence » over the edit mode, typed, then « Ajouter la référence ». */
|
||||
async function createPending(page: Page) {
|
||||
const create = inDialog(page, dict['editor.citations.new_reference'])
|
||||
await create.click()
|
||||
const form = referenceDialog(page)
|
||||
await expect(form).toBeVisible()
|
||||
await expect(page.locator('dialog[open]')).toHaveCount(3)
|
||||
await expect(
|
||||
form.getByRole('heading', { name: dict['editor.reference.new'] }),
|
||||
).toBeVisible()
|
||||
await form.locator('#reference-form-type').selectOption('manual')
|
||||
await form.locator('#reference-form-citation').fill('Source nouvelle')
|
||||
await form
|
||||
@@ -605,14 +604,54 @@ test.describe('references dialog, edit mode', () => {
|
||||
await expect(create).toBeFocused()
|
||||
await expect(draftRows(page)).toHaveCount(4)
|
||||
await expect(draftRows(page).last()).toContainText('Source nouvelle')
|
||||
await expect(draftRows(page).last()).toContainText(
|
||||
dict['editor.citations.pending'],
|
||||
)
|
||||
await expect(citationsDialog(page).getByRole('status')).toContainText(
|
||||
'Source nouvelle',
|
||||
)
|
||||
}
|
||||
|
||||
test('« Nouvelle référence » then « Abandonner »: the library is unchanged', async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000)
|
||||
await open(page)
|
||||
await editCitations(page)
|
||||
await createPending(page)
|
||||
await inDialog(page, dict['common.cancel']).click()
|
||||
await inDialog(page, dict['editor.findings.discard']).click()
|
||||
await expect(editButton(page)).toBeFocused()
|
||||
await closeCitations(page, dict)
|
||||
await closeFinding(page, dict)
|
||||
await expect(historyButton(page, dict, 'undo')).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
)
|
||||
await expect(
|
||||
page.locator('p.sr-only[aria-live="polite"]'),
|
||||
).not.toContainText('sera enregistrée')
|
||||
await openTab(page, dict, 'references')
|
||||
await expect(libraryRoot(page)).toContainText('Source libre')
|
||||
await expect(libraryRoot(page)).not.toContainText('Source nouvelle')
|
||||
})
|
||||
|
||||
test('« Nouvelle référence » then « Enregistrer »: one « Défaire » removes both', async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(150_000)
|
||||
const { seed } = await open(page)
|
||||
await editCitations(page)
|
||||
await createPending(page)
|
||||
await inDialog(page, dict['editor.findings.save']).click()
|
||||
await expect(editButton(page)).toBeFocused()
|
||||
await closeCitations(page, dict)
|
||||
await closeFinding(page, dict)
|
||||
await saveDraft(page, dict, seed.revision + 1)
|
||||
const saved = await serverDocument<Record<string, unknown>>(seed.draftId)
|
||||
const refs = saved.references as { id: string; citation: string }[]
|
||||
const added = refs.find((ref) => ref.citation === 'Source nouvelle')
|
||||
let saved = await serverDocument<Record<string, unknown>>(seed.draftId)
|
||||
const added = (saved.references as { id: string; citation: string }[]).find(
|
||||
(ref) => ref.citation === 'Source nouvelle',
|
||||
)
|
||||
expect(added).toBeDefined()
|
||||
expect(nodeOf(saved).reference_ids).toEqual([
|
||||
'ref-a',
|
||||
@@ -620,6 +659,16 @@ test.describe('references dialog, edit mode', () => {
|
||||
'ref-c',
|
||||
added!.id,
|
||||
])
|
||||
const undo = historyButton(page, dict, 'undo')
|
||||
await undo.click()
|
||||
await expect(undo).toHaveAttribute('aria-disabled', 'true')
|
||||
await saveDraft(page, dict, seed.revision + 2)
|
||||
saved = await serverDocument<Record<string, unknown>>(seed.draftId)
|
||||
const citations = (saved.references as { citation: string }[]).map(
|
||||
(ref) => ref.citation,
|
||||
)
|
||||
expect(citations).not.toContain('Source nouvelle')
|
||||
expect(nodeOf(saved).reference_ids).toEqual(['ref-a', 'ref-b', 'ref-c'])
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -54,10 +54,12 @@ interface BodyProps {
|
||||
citedBy: ElementKey
|
||||
mode: Mode
|
||||
props: CitationsDialogProps
|
||||
/** The edit mode's status line (a draft creation, a pending one removed; Rev 6). */
|
||||
onNotice: (text: string) => void
|
||||
}
|
||||
|
||||
/** The edit mode: where the finding sits, then the draft form. */
|
||||
function EditBody({ citedBy, mode, props }: BodyProps) {
|
||||
function EditBody({ citedBy, mode, props, onNotice }: BodyProps) {
|
||||
const doc = useSheetDocument()
|
||||
const readOnly = useEditorReadOnly()
|
||||
return (
|
||||
@@ -70,6 +72,7 @@ function EditBody({ citedBy, mode, props }: BodyProps) {
|
||||
guards={props.guards}
|
||||
references={props.references}
|
||||
onDone={mode.done}
|
||||
onNotice={onNotice}
|
||||
onDiscardClose={() => props.onClose(true, true)}
|
||||
/>
|
||||
</>
|
||||
@@ -102,10 +105,15 @@ function ViewBody({ citedBy, mode, props }: BodyProps) {
|
||||
)
|
||||
}
|
||||
|
||||
/** The place of the dialog's content, in both modes, then what a save says. */
|
||||
function Body(body: BodyProps) {
|
||||
/**
|
||||
* The place of the dialog's content, in both modes, then its status line: what a save
|
||||
* says, or what the edit mode's draft just did (never the editor's live region, Rev 6).
|
||||
*/
|
||||
function Body(body: Omit<BodyProps, 'onNotice'>) {
|
||||
const t = useT()
|
||||
const { mode } = body
|
||||
const [notice, setNotice] = useState('')
|
||||
if (!mode.editing && notice !== '') setNotice('')
|
||||
return (
|
||||
<section
|
||||
id="editor-citations-panel"
|
||||
@@ -114,9 +122,13 @@ function Body(body: BodyProps) {
|
||||
aria-labelledby={CITATIONS_TITLE_ID}
|
||||
className="space-y-3"
|
||||
>
|
||||
{mode.editing ? <EditBody {...body} /> : <ViewBody {...body} />}
|
||||
{mode.editing ? (
|
||||
<EditBody {...body} onNotice={setNotice} />
|
||||
) : (
|
||||
<ViewBody {...body} onNotice={setNotice} />
|
||||
)}
|
||||
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
|
||||
{mode.saved ? t('editor.findings.saved') : ''}
|
||||
{notice || (mode.saved ? t('editor.findings.saved') : '')}
|
||||
</p>
|
||||
</section>
|
||||
)
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import type { Reference } from '@faunosteo/core-wasm/types'
|
||||
import Badge from '@/components/ui/Badge'
|
||||
import Button from '@/components/ui/Button'
|
||||
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
|
||||
import Select from '@/components/ui/Select'
|
||||
@@ -20,11 +22,13 @@ export interface CiteChoice {
|
||||
export interface DraftListProps {
|
||||
/** The draft's cited ids, in the order they will be saved. */
|
||||
ids: readonly string[]
|
||||
/** The references made in the draft (Rev 6): written only by « Enregistrer ». */
|
||||
pending: readonly Reference[]
|
||||
readOnly: boolean
|
||||
choice: CiteChoice
|
||||
onAdd: (id: string) => void
|
||||
onRemove: (id: string) => void
|
||||
/** « Modifier la référence »: the reference dialog over this one. */
|
||||
/** « Modifier la référence »: the reference dialog over this one (a pending one too). */
|
||||
onEditReference: (id: string, opener: HTMLElement) => void
|
||||
/** « Nouvelle référence »: the creation dialog over this one. */
|
||||
onNew: (opener: HTMLElement) => void
|
||||
@@ -72,15 +76,28 @@ interface RowProps {
|
||||
onRemove: () => void
|
||||
}
|
||||
|
||||
/** One cited id: its citation (or « Référence introuvable »), its edit and its removal. */
|
||||
/**
|
||||
* One cited id: its citation (or « Référence introuvable »), « Nouvelle » when the draft
|
||||
* made it, 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 pending = props.pending.some((r) => r.id === id)
|
||||
const citation = [...props.pending, ...(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>
|
||||
<span className="min-w-0 flex-1 text-sm">
|
||||
<span>{shown}</span>
|
||||
{pending && (
|
||||
<Badge tone="accent" className="ms-2">
|
||||
{t('editor.citations.pending')}
|
||||
</Badge>
|
||||
)}
|
||||
</span>
|
||||
{citation !== undefined && (
|
||||
<Button
|
||||
type="button"
|
||||
@@ -179,7 +196,8 @@ function AddRow({ props }: { props: DraftListProps }) {
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* « Modifier la référence » and « Retirer » (a dangling id too; a pending one, Rev 6,
|
||||
* badged « Nouvelle »), then the ways to cite one.
|
||||
* Nothing is written before « Enregistrer ». Read only: every control off.
|
||||
*/
|
||||
export default function CitationsDraftList(props: DraftListProps) {
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||
import type { ElementKey, Reference } 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 { patchElement, type FindingItem } from '@/editor/findings/tree'
|
||||
import { newElementId } from '@/editor/ids'
|
||||
import { isFamilyKey } from '@/editor/navigation'
|
||||
import {
|
||||
addId,
|
||||
applyEdits,
|
||||
citationCommands,
|
||||
NO_EDITS,
|
||||
putCreated,
|
||||
removeId,
|
||||
sameEdits,
|
||||
type CitationEdits,
|
||||
@@ -31,6 +35,8 @@ export interface CitationsEditFormProps {
|
||||
references: Pick<ReferenceMoves, 'open' | 'start'>
|
||||
/** Back to the view mode; `saved` is true when a command was written. */
|
||||
onDone: (saved: boolean) => void
|
||||
/** What the draft did that the dialog's status line says (a draft creation, Rev 6). */
|
||||
onNotice: (text: string) => void
|
||||
/** « Abandonner » after a close request: the draft goes, so does the dialog. */
|
||||
onDiscardClose: () => void
|
||||
}
|
||||
@@ -46,30 +52,65 @@ 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>>
|
||||
type Translate = ReturnType<typeof useT>
|
||||
|
||||
/** The save: the draft applied to the current citations, one `update`, none unchanged. */
|
||||
/** The save's batch: the created references' inserts under fresh ids, then the `update`. */
|
||||
function saveCommands(
|
||||
item: FindingItem,
|
||||
ids: readonly string[],
|
||||
draft: CitationEdits,
|
||||
) {
|
||||
const update = (next: string[]) => {
|
||||
const element = patchElement(item, { reference_ids: next })
|
||||
return { op: 'update', key: item.key, element } as const
|
||||
}
|
||||
return citationCommands(draft, ids, update, () => newElementId('ref'))
|
||||
}
|
||||
|
||||
/** A refused save with references made in the draft: the line names them, still pending. */
|
||||
function savedError(
|
||||
t: Translate,
|
||||
error: string | undefined,
|
||||
draft: CitationEdits,
|
||||
) {
|
||||
if (!error || draft.created.length === 0) return error
|
||||
const citations = draft.created.map((r) => r.citation).join(' ; ')
|
||||
return `${error} ${t('editor.citations.pending_kept').replace('{citation}', citations)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* The save: one batch (the created references, then the element's `update`, one undo
|
||||
* step), none when nothing changed; refused, the draft stays (an element gone too).
|
||||
*/
|
||||
function useCitationsSave(props: CitationsEditFormProps, form: Draft) {
|
||||
const t = useT()
|
||||
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)
|
||||
if (!item) {
|
||||
const gone = isFamilyKey(props.citedBy)
|
||||
? 'editor.findings.gone_family'
|
||||
: 'editor.findings.gone'
|
||||
return void edit.reject('save', gone)
|
||||
}
|
||||
if (sameIds(applyEdits(ids, form.draft), ids)) return props.onDone(false)
|
||||
const build = () => saveCommands(item, ids, form.draft)
|
||||
if (edit.runBatch('save', build)) props.onDone(true)
|
||||
}
|
||||
return {
|
||||
shown: applyEdits(ids, form.draft),
|
||||
save,
|
||||
error: edit.fieldError('save'),
|
||||
error: savedError(t, edit.fieldError('save'), form.draft),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* « 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).
|
||||
* « Nouvelle référence », or « Modifier la référence » of a pending one (Rev 6): the
|
||||
* reference dialog over this one writes nothing; its value joins the draft, only while
|
||||
* this form is still there, and the status line says so.
|
||||
*/
|
||||
function useCreation(props: CitationsEditFormProps, form: Draft) {
|
||||
const t = useT()
|
||||
const latest = useRef(form)
|
||||
latest.current = form
|
||||
const alive = useRef(true)
|
||||
@@ -79,11 +120,37 @@ function useCreation(props: CitationsEditFormProps, form: Draft) {
|
||||
alive.current = false
|
||||
}
|
||||
}, [])
|
||||
return (opener: HTMLElement) =>
|
||||
props.references.start(opener, (id) => {
|
||||
const now = latest.current
|
||||
if (alive.current) now.set(addId(now.draft, id))
|
||||
})
|
||||
const cite = (value: Reference) => {
|
||||
if (!alive.current) return
|
||||
const now = latest.current
|
||||
now.set(putCreated(now.draft, value))
|
||||
const text = t('editor.citations.created_draft')
|
||||
props.onNotice(text.replace('{citation}', value.citation))
|
||||
}
|
||||
return (opener: HTMLElement, initial?: Reference) =>
|
||||
props.references.start(opener, cite, initial)
|
||||
}
|
||||
|
||||
/** « Modifier la référence » and « Retirer » of a row: a pending one stays in the draft. */
|
||||
function useRowMoves(props: CitationsEditFormProps, form: Draft) {
|
||||
const t = useT()
|
||||
const create = useCreation(props, form)
|
||||
const pendingOf = (id: string) => form.draft.created.find((r) => r.id === id)
|
||||
return {
|
||||
create,
|
||||
editReference: (id: string, opener: HTMLElement) => {
|
||||
const pending = pendingOf(id)
|
||||
if (pending) create(opener, pending)
|
||||
else props.references.open(id, opener)
|
||||
},
|
||||
remove: (id: string) => {
|
||||
const pending = pendingOf(id)
|
||||
form.set(removeId(form.draft, id))
|
||||
if (!pending) return
|
||||
const text = t('editor.citations.pending_removed')
|
||||
props.onNotice(text.replace('{citation}', pending.citation))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -109,7 +176,7 @@ function useCiteChoice(ids: readonly string[]) {
|
||||
}
|
||||
}
|
||||
|
||||
/** The form's state: the draft, its guard, its save, its cancel and its creation. */
|
||||
/** The form's state: the draft, its guard, its save, its cancel and its rows' moves. */
|
||||
function useCitationsForm(props: CitationsEditFormProps) {
|
||||
const form = useFormDraft(NO_EDITS, props.guards, sameEdits, 'citations')
|
||||
const saving = useCitationsSave(props, form)
|
||||
@@ -125,16 +192,17 @@ function useCitationsForm(props: CitationsEditFormProps) {
|
||||
choice,
|
||||
cancel,
|
||||
submit,
|
||||
create: useCreation(props, form),
|
||||
rows: useRowMoves(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; refused
|
||||
* while a choice in the select waits for « Citer », Rev 6), 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.
|
||||
* reference made in the draft, Rev 6), one batch on « Enregistrer » (the new references
|
||||
* and the `update`, one undo step; none when nothing changed; refused while a choice in
|
||||
* the select waits for « Citer »), 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()
|
||||
@@ -157,12 +225,13 @@ export default function CitationsEditForm(props: CitationsEditFormProps) {
|
||||
{props.readOnly && <ReadOnlyNotice />}
|
||||
<CitationsDraftList
|
||||
ids={form.shown}
|
||||
pending={form.draft.created}
|
||||
readOnly={props.readOnly}
|
||||
choice={form.choice}
|
||||
onAdd={(id) => form.set(addId(form.draft, id))}
|
||||
onRemove={(id) => form.set(removeId(form.draft, id))}
|
||||
onEditReference={props.references.open}
|
||||
onNew={form.create}
|
||||
onRemove={form.rows.remove}
|
||||
onEditReference={form.rows.editReference}
|
||||
onNew={(opener) => form.rows.create(opener)}
|
||||
/>
|
||||
{form.error && (
|
||||
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
||||
|
||||
@@ -90,7 +90,10 @@ function useShownReference(layer: ReferenceLayer, handed: string | null) {
|
||||
return { creating, edited, title: t(title), open: creating || !!edited }
|
||||
}
|
||||
|
||||
/** What a save does: a creation is announced, then handed over; an edit closes the layer. */
|
||||
/**
|
||||
* What a save does: a library creation is announced, then handed over; an edit, or a
|
||||
* draft creation (its value already with the citing form, which says it), closes the layer.
|
||||
*/
|
||||
function useOnSaved(
|
||||
layer: ReferenceLayer,
|
||||
creating: boolean,
|
||||
@@ -98,7 +101,7 @@ function useOnSaved(
|
||||
) {
|
||||
const t = useT()
|
||||
return (id: string, citation: string) => {
|
||||
if (!creating) return void layer.close(true)
|
||||
if (!creating || layer.drafting()) return void layer.close(true)
|
||||
handOver(id)
|
||||
layer.announce(t('editor.references.added').replace('{citation}', citation))
|
||||
layer.created(id)
|
||||
@@ -108,8 +111,10 @@ function useOnSaved(
|
||||
/**
|
||||
* 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.
|
||||
* a new one. Over the edit mode it is a draft creation (Rev 6): titled « Nouvelle
|
||||
* référence », it writes nothing and hands the value to the citing form. 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,
|
||||
@@ -119,6 +124,8 @@ export default function ReferenceDialog({
|
||||
const shown = useShownReference(layer, creation.handed)
|
||||
const returnFocus = useReturnTarget(layer)
|
||||
const onSaved = useOnSaved(layer, shown.creating, creation.handOver)
|
||||
const drafting = layer.drafting()
|
||||
const reference = drafting ? drafting.initial : shown.edited
|
||||
useGoneRule(layer)
|
||||
return (
|
||||
<Dialog
|
||||
@@ -130,11 +137,12 @@ export default function ReferenceDialog({
|
||||
onClose={() => (layer.close() ? undefined : 'kept')}
|
||||
>
|
||||
<ReferenceForm
|
||||
key={shown.edited?.id ?? 'new'}
|
||||
reference={shown.edited}
|
||||
key={reference?.id ?? 'new'}
|
||||
reference={reference}
|
||||
readOnly={readOnly}
|
||||
guards={layer.guards}
|
||||
onSaved={onSaved}
|
||||
onValue={drafting?.cite}
|
||||
onClose={(forced) => layer.close(forced)}
|
||||
/>
|
||||
</Dialog>
|
||||
|
||||
@@ -9,6 +9,7 @@ import SelectField from '@/components/editor/fields/SelectField'
|
||||
import { FormActions } from '@/components/editor/findings/DiscardConfirm'
|
||||
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
|
||||
import { useFormDraft } from '@/components/editor/findings/useDirtyGuard'
|
||||
import { newElementId } from '@/editor/ids'
|
||||
import { webHref } from '@/editor/references/safeLink'
|
||||
import { isBlank, nullable } from '@/editor/sheetDocument'
|
||||
import { useEditCommand } from '@/editor/useEditCommand'
|
||||
@@ -77,36 +78,71 @@ export interface ReferenceFormProps {
|
||||
reference: Reference | null
|
||||
readOnly: boolean
|
||||
guards: Guards
|
||||
/** One command was written; `id` and `citation` are the reference's. */
|
||||
/** One command was written, or the value handed over; `id` and `citation` are its. */
|
||||
onSaved: (id: string, citation: string) => void
|
||||
/**
|
||||
* A draft creation (Rev 6): the save writes nothing and hands the value here instead;
|
||||
* `reference` is then the pending value modified (its id kept), or null.
|
||||
*/
|
||||
onValue?: (value: Reference) => void
|
||||
/** Nothing was written (pristine save, « Annuler », « Abandonner »); forced drops a draft. */
|
||||
onClose: (forced: boolean) => void
|
||||
}
|
||||
|
||||
type Form = ReturnType<typeof useFormDraft<Draft>>
|
||||
|
||||
type EditApi = ReturnType<typeof useEditCommand>
|
||||
|
||||
/** The one command of a library save: an `update`, or an `insert` under a new id. */
|
||||
function writeCommand(
|
||||
edit: EditApi,
|
||||
reference: Reference | null,
|
||||
draft: Draft,
|
||||
): string | null {
|
||||
if (reference) {
|
||||
const element = { kind: 'reference', value: valueOf(draft, reference.id) }
|
||||
const key = { kind: 'reference', id: reference.id }
|
||||
const command = { op: 'update', key, element } as EditCommand
|
||||
return edit.run('form', command) ? reference.id : null
|
||||
}
|
||||
let id = ''
|
||||
const added = edit.runNew('form', 'ref', (fresh) => {
|
||||
id = fresh
|
||||
const element = { kind: 'reference', value: valueOf(draft, fresh) }
|
||||
return { op: 'insert', element } as EditCommand
|
||||
})
|
||||
return added ? id : null
|
||||
}
|
||||
|
||||
/**
|
||||
* The one command of a save: an `update` of the reference, or an `insert` under a new id.
|
||||
* The dialog closes after a save: a second submit while it plays its exit writes nothing.
|
||||
* A draft creation (Rev 6): the value under the pending id or a fresh one, its insert
|
||||
* dry-run on the current document (a refusal shows here, nothing is stored), then handed
|
||||
* to the citing form.
|
||||
*/
|
||||
function useWrite(reference: Reference | null, draft: Draft) {
|
||||
function offerValue(
|
||||
edit: EditApi,
|
||||
props: ReferenceFormProps,
|
||||
draft: Draft,
|
||||
onValue: (value: Reference) => void,
|
||||
): string | null {
|
||||
const value = valueOf(draft, props.reference?.id ?? newElementId('ref'))
|
||||
const element = { kind: 'reference', value } as const
|
||||
if (!edit.check('form', { op: 'insert', element })) return null
|
||||
onValue(value)
|
||||
return value.id
|
||||
}
|
||||
|
||||
/**
|
||||
* The save's one move: a command written, or a value handed to a citing form. The dialog
|
||||
* closes after it: a second submit while it plays its exit does nothing.
|
||||
*/
|
||||
function useWrite(props: ReferenceFormProps, draft: Draft) {
|
||||
const edit = useEditCommand()
|
||||
const saved = useRef(false)
|
||||
const run = (): string | null => {
|
||||
if (reference) {
|
||||
const element = { kind: 'reference', value: valueOf(draft, reference.id) }
|
||||
const key = { kind: 'reference', id: reference.id }
|
||||
const command = { op: 'update', key, element } as EditCommand
|
||||
return edit.run('form', command) ? reference.id : null
|
||||
}
|
||||
let id = ''
|
||||
const added = edit.runNew('form', 'ref', (fresh) => {
|
||||
id = fresh
|
||||
const element = { kind: 'reference', value: valueOf(draft, fresh) }
|
||||
return { op: 'insert', element } as EditCommand
|
||||
})
|
||||
return added ? id : null
|
||||
}
|
||||
const run = (): string | null =>
|
||||
props.onValue
|
||||
? offerValue(edit, props, draft, props.onValue)
|
||||
: writeCommand(edit, props.reference, draft)
|
||||
const write = (): string | null => {
|
||||
const id = saved.current ? null : run()
|
||||
saved.current = saved.current || id !== null
|
||||
@@ -117,7 +153,7 @@ function useWrite(reference: Reference | null, draft: Draft) {
|
||||
|
||||
/** The save: refused on its field, nothing written when unchanged, else one command. */
|
||||
function useReferenceSave(props: ReferenceFormProps, form: Form) {
|
||||
const { edit, write } = useWrite(props.reference, form.draft)
|
||||
const { edit, write } = useWrite(props, form.draft)
|
||||
const save = () => {
|
||||
const refusal = refusalOf(form.draft, props.reference === null)
|
||||
if (refusal) {
|
||||
@@ -201,15 +237,21 @@ function FormFields({
|
||||
|
||||
/**
|
||||
* A reference edited or created in the reference dialog (R2F-5): a local draft, one
|
||||
* command on « Enregistrer » (none when nothing changed), nothing on « Annuler », a close
|
||||
* or a move. When the editor turns read-only the draft stays, its fields read-only, and
|
||||
* only « Abandonner » is left.
|
||||
* command on « Enregistrer » (none when nothing changed; in a draft creation, none at all:
|
||||
* the value goes to the citing form), nothing on « Annuler », a close or a move. When
|
||||
* the editor turns read-only the draft stays, its fields read-only, and only
|
||||
* « Abandonner » is left.
|
||||
*/
|
||||
export default function ReferenceForm(props: ReferenceFormProps) {
|
||||
const t = useT()
|
||||
const form = useReferenceForm(props)
|
||||
const { guard } = form
|
||||
const creating = props.reference === null
|
||||
const submitLabel =
|
||||
props.reference === null
|
||||
? 'editor.reference.add'
|
||||
: props.onValue
|
||||
? 'common.confirm'
|
||||
: 'editor.findings.save'
|
||||
return (
|
||||
<form
|
||||
data-draft-form
|
||||
@@ -230,9 +272,7 @@ export default function ReferenceForm(props: ReferenceFormProps) {
|
||||
<FormActions
|
||||
confirming={guard.confirming}
|
||||
readOnly={props.readOnly}
|
||||
submitLabel={t(
|
||||
creating ? 'editor.reference.add' : 'editor.findings.save',
|
||||
)}
|
||||
submitLabel={t(submitLabel)}
|
||||
onCancel={() =>
|
||||
form.dirty && !props.readOnly
|
||||
? guard.askToLeave()
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
import type { EditCommand, Reference } from '@faunosteo/core-wasm/types'
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* `created` (Rev 6): the references made in this draft, absent from the document; each
|
||||
* id is in `added` as long as it is in `created`.
|
||||
*/
|
||||
export interface CitationEdits {
|
||||
added: readonly string[]
|
||||
removed: readonly string[]
|
||||
created: readonly Reference[]
|
||||
}
|
||||
|
||||
export const NO_EDITS: CitationEdits = { added: [], removed: [] }
|
||||
export const NO_EDITS: CitationEdits = { added: [], removed: [], created: [] }
|
||||
|
||||
export const sameEdits = (a: CitationEdits, b: CitationEdits) =>
|
||||
JSON.stringify(a) === JSON.stringify(b)
|
||||
@@ -31,11 +36,53 @@ export function addId(edits: CitationEdits, id: string): CitationEdits {
|
||||
return { ...edits, added: [...edits.added, id] }
|
||||
}
|
||||
|
||||
/** Removes `id`: undoes its addition, else records the removal. */
|
||||
/** Removes `id`: undoes its addition (a created reference goes with it), else records it. */
|
||||
export function removeId(edits: CitationEdits, id: string): CitationEdits {
|
||||
if (edits.added.includes(id)) {
|
||||
return { ...edits, added: edits.added.filter((other) => other !== id) }
|
||||
return {
|
||||
...edits,
|
||||
added: edits.added.filter((other) => other !== id),
|
||||
created: edits.created.filter((reference) => reference.id !== id),
|
||||
}
|
||||
}
|
||||
if (edits.removed.includes(id)) return edits
|
||||
return { ...edits, removed: [...edits.removed, id] }
|
||||
}
|
||||
|
||||
/** A reference made in the draft: cited under its id, or replacing the pending one. */
|
||||
export function putCreated(
|
||||
edits: CitationEdits,
|
||||
value: Reference,
|
||||
): CitationEdits {
|
||||
if (edits.created.some((reference) => reference.id === value.id)) {
|
||||
const created = edits.created.map((reference) =>
|
||||
reference.id === value.id ? value : reference,
|
||||
)
|
||||
return { ...edits, created }
|
||||
}
|
||||
return { ...addId(edits, value.id), created: [...edits.created, value] }
|
||||
}
|
||||
|
||||
/**
|
||||
* The save's commands, in order: an `insert` per created reference under a minted id,
|
||||
* then `update(ids)` with the citations applied to `current`, the created ids remapped.
|
||||
*/
|
||||
export function citationCommands(
|
||||
edits: CitationEdits,
|
||||
current: readonly string[],
|
||||
update: (ids: string[]) => EditCommand,
|
||||
mint: () => string,
|
||||
): EditCommand[] {
|
||||
const fresh = new Map(edits.created.map((r) => [r.id, mint()]))
|
||||
const inserts = edits.created.map(
|
||||
(r): EditCommand => ({
|
||||
op: 'insert',
|
||||
element: {
|
||||
kind: 'reference',
|
||||
value: { ...r, id: fresh.get(r.id) ?? r.id },
|
||||
},
|
||||
}),
|
||||
)
|
||||
const ids = applyEdits(current, edits).map((id) => fresh.get(id) ?? id)
|
||||
return [...inserts, update(ids)]
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import type { EditorTarget, EditorView, FocusRequest } from './navigation'
|
||||
import { unmeasuredViews } from './issues'
|
||||
import type { TabTier } from './useViewport'
|
||||
import type { Guards } from './useEditorNavigation'
|
||||
import type { AddedReference } from './useReferenceMoves'
|
||||
import type { AddedReference, ReferenceMoves } from './useReferenceMoves'
|
||||
|
||||
export const EDITOR_TABS = [
|
||||
'general',
|
||||
@@ -64,7 +64,9 @@ export interface ReferenceLayer {
|
||||
filter: ElementKey | null
|
||||
guards: Guards
|
||||
open: (id: string, opener?: HTMLElement | null) => void
|
||||
start: (opener?: HTMLElement | null) => void
|
||||
start: ReferenceMoves['start']
|
||||
/** The open dialog's draft creation (over the citations edit mode, Rev 6); else null. */
|
||||
drafting: ReferenceMoves['drafting']
|
||||
close: (forced?: boolean) => boolean
|
||||
replace: (id: string | null, text?: string) => void
|
||||
created: (id: string) => void
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useState } from 'react'
|
||||
import type { EditCommand } from '@faunosteo/core-wasm/types'
|
||||
import type { CommitOutcome } from './state/editorTypes'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { applyEdit } from './core/editOps'
|
||||
import { newElementId, type IdPrefix } from './ids'
|
||||
import { refusalMessage } from './refusal'
|
||||
import { useEditorStore } from './state/editorStore'
|
||||
@@ -21,11 +23,24 @@ export interface EditCommandApi {
|
||||
prefix: IdPrefix,
|
||||
build: (id: string) => EditCommand,
|
||||
) => boolean
|
||||
/**
|
||||
* Commits `build()` as one batch (one undo step); `build` is called once more when the
|
||||
* core answers `duplicate_key` (it mints its new ids again).
|
||||
*/
|
||||
runBatch: (field: string, build: () => readonly EditCommand[]) => boolean
|
||||
/** Dry-runs one command on the current document text: nothing is stored. */
|
||||
check: (field: string, command: EditCommand) => boolean
|
||||
/** A refusal that never reached the core (a required field left blank). */
|
||||
reject: (field: string, messageKey: string) => false
|
||||
clear: () => void
|
||||
}
|
||||
|
||||
/** The core refused an insert because its new id is taken: worth one more mint. */
|
||||
const isClash = (outcome: CommitOutcome) =>
|
||||
!outcome.ok &&
|
||||
outcome.reason === 'core' &&
|
||||
outcome.failure.kind === 'duplicate_key'
|
||||
|
||||
/** The write path of an editor panel: commit once, keep the refusal next to the control. */
|
||||
export function useEditCommand(): EditCommandApi {
|
||||
const t = useT()
|
||||
@@ -34,27 +49,42 @@ export function useEditCommand(): EditCommandApi {
|
||||
const attempt = (command: EditCommand) =>
|
||||
useEditorStore.getState().commit(command)
|
||||
|
||||
const run = (field: string, command: EditCommand): boolean => {
|
||||
const outcome = attempt(command)
|
||||
const run = (field: string, command: EditCommand): boolean =>
|
||||
settle(field, attempt(command))
|
||||
|
||||
const settle = (field: string, outcome: CommitOutcome): boolean => {
|
||||
setError(outcome.ok ? null : { field, message: refusalMessage(t, outcome) })
|
||||
return outcome.ok
|
||||
}
|
||||
|
||||
const runNew: EditCommandApi['runNew'] = (field, prefix, build) => {
|
||||
let outcome = attempt(build(newElementId(prefix)))
|
||||
const clash =
|
||||
!outcome.ok &&
|
||||
outcome.reason === 'core' &&
|
||||
outcome.failure.kind === 'duplicate_key'
|
||||
if (clash) outcome = attempt(build(newElementId(prefix)))
|
||||
setError(outcome.ok ? null : { field, message: refusalMessage(t, outcome) })
|
||||
return outcome.ok
|
||||
if (isClash(outcome)) outcome = attempt(build(newElementId(prefix)))
|
||||
return settle(field, outcome)
|
||||
}
|
||||
|
||||
const runBatch: EditCommandApi['runBatch'] = (field, build) => {
|
||||
const store = useEditorStore.getState()
|
||||
let outcome = store.commitBatch(build())
|
||||
if (isClash(outcome)) outcome = store.commitBatch(build())
|
||||
return settle(field, outcome)
|
||||
}
|
||||
|
||||
const check: EditCommandApi['check'] = (field, command) => {
|
||||
const text = useEditorStore.getState().documentText
|
||||
const edited = applyEdit(text, command)
|
||||
const outcome: CommitOutcome = edited.ok
|
||||
? { ok: true }
|
||||
: { ok: false, reason: 'core', failure: edited }
|
||||
return settle(field, outcome)
|
||||
}
|
||||
|
||||
return {
|
||||
fieldError: (field) => (error?.field === field ? error.message : undefined),
|
||||
run,
|
||||
runNew,
|
||||
runBatch,
|
||||
check,
|
||||
reject: (field, messageKey) => {
|
||||
setError({ field, message: t(messageKey) })
|
||||
return false
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { ElementKey } from '@faunosteo/core-wasm/types'
|
||||
import type { ElementKey, Reference } from '@faunosteo/core-wasm/types'
|
||||
import type { NavigationState } from './navigation'
|
||||
import type { LayerContext, MoveTrace } from './useEditorNavigation'
|
||||
|
||||
@@ -11,8 +11,17 @@ 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 a creation started from the citations dialog's edit form does with its value
|
||||
* (Rev 6): the reference joins that form's draft, nothing is written.
|
||||
*/
|
||||
export type CiteCreated = (value: Reference) => void
|
||||
|
||||
/** A draft creation: the citing form, and the pending reference modified (null: a new one). */
|
||||
export interface Drafting {
|
||||
initial: Reference | null
|
||||
cite: CiteCreated
|
||||
}
|
||||
|
||||
/** What the reference dialog (R2F-5) and the References tab's filter (R2F-6) do to the view. */
|
||||
export interface ReferenceMoves {
|
||||
@@ -20,10 +29,12 @@ export interface ReferenceMoves {
|
||||
open: (id: string, 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.
|
||||
* citations edit form that started it (Rev 6): the dialog writes nothing and hands the
|
||||
* value to its draft; `initial` is the pending reference it modifies.
|
||||
*/
|
||||
start: (opener?: Opener, cite?: CiteCreated) => void
|
||||
start: (opener?: Opener, cite?: CiteCreated, initial?: Reference) => void
|
||||
/** The open dialog's draft creation, read from what started it; null for any other. */
|
||||
drafting: () => Drafting | null
|
||||
/** A user close; false when the form refused it (a dirty draft asks first). */
|
||||
close: (forced?: boolean) => boolean
|
||||
/**
|
||||
@@ -32,7 +43,10 @@ export interface ReferenceMoves {
|
||||
* said once the dialogs are closed.
|
||||
*/
|
||||
replace: (id: string | null, text?: string) => void
|
||||
/** A creation succeeded: its entry becomes the reference's own, then the dialog closes. */
|
||||
/**
|
||||
* A library creation succeeded: its entry becomes the reference's own, then the dialog
|
||||
* closes and the library says it.
|
||||
*/
|
||||
created: (id: string) => void
|
||||
added: AddedReference | null
|
||||
/** The element that opened the dialog, while it is still on the page. */
|
||||
@@ -44,12 +58,19 @@ export interface ReferenceMoves {
|
||||
}
|
||||
|
||||
/**
|
||||
* What the open dialog was started from: its opener, and a citing form for a creation
|
||||
* (forgotten once the dialog closes or is replaced).
|
||||
* What the open dialog was started from: its opener, and for a draft creation the citing
|
||||
* form and the pending value (both forgotten once the dialog closes or is replaced).
|
||||
*/
|
||||
interface Held {
|
||||
opener: Opener
|
||||
cite: CiteCreated | null
|
||||
initial: Reference | null
|
||||
}
|
||||
|
||||
/** No draft creation any more: the citing form and its pending value go together. */
|
||||
function forget(held: Held) {
|
||||
held.cite = null
|
||||
held.initial = null
|
||||
}
|
||||
|
||||
/** The moves that add the dialog: an edit of a reference, a creation. */
|
||||
@@ -57,16 +78,17 @@ function useOpening({ dispatch, mark }: LayerContext, held: Held) {
|
||||
const open = useCallback(
|
||||
(id: string, opener?: Opener) => {
|
||||
held.opener = opener
|
||||
held.cite = null
|
||||
forget(held)
|
||||
mark()
|
||||
dispatch({ type: 'open_reference', id })
|
||||
},
|
||||
[dispatch, mark, held],
|
||||
)
|
||||
const start = useCallback(
|
||||
(opener?: Opener, cite?: CiteCreated) => {
|
||||
(opener?: Opener, cite?: CiteCreated, initial?: Reference) => {
|
||||
held.opener = opener
|
||||
held.cite = cite ?? null
|
||||
held.initial = cite ? (initial ?? null) : null
|
||||
mark()
|
||||
dispatch({ type: 'create_reference' })
|
||||
},
|
||||
@@ -80,7 +102,7 @@ function useClose({ dispatch, guards, mark }: LayerContext, held: Held) {
|
||||
return useCallback(
|
||||
(forced = false) => {
|
||||
if (!guards.ask('reference', forced).allowed) return false
|
||||
held.cite = null
|
||||
forget(held)
|
||||
mark()
|
||||
dispatch({ type: 'close_reference' })
|
||||
return true
|
||||
@@ -94,7 +116,7 @@ function useReplace(ctx: LayerContext, held: Held) {
|
||||
const { dispatch, announce, guards, mark } = ctx
|
||||
return useCallback(
|
||||
(id: string | null, text?: string) => {
|
||||
held.cite = null
|
||||
forget(held)
|
||||
const note = text ? guards.ask('reference', true).note : undefined
|
||||
if (text) announce(note ? `${note}. ${text}` : text)
|
||||
mark(true)
|
||||
@@ -112,23 +134,16 @@ function useClosing(ctx: LayerContext, held: Held) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* A library creation that succeeded: its entry becomes the reference's own, then it
|
||||
* closes, and the library says it. A draft creation never comes here (it writes nothing).
|
||||
*/
|
||||
function useCreated(
|
||||
ctx: LayerContext,
|
||||
replace: ReferenceMoves['replace'],
|
||||
held: Held,
|
||||
) {
|
||||
function useCreated(ctx: LayerContext, replace: ReferenceMoves['replace']) {
|
||||
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)
|
||||
if (citing) citing(id)
|
||||
else setAdded((last) => ({ id, serial: (last?.serial ?? 0) + 1 }))
|
||||
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
|
||||
@@ -140,7 +155,7 @@ function useCreated(
|
||||
dispatch({ type: 'close_reference' })
|
||||
})
|
||||
},
|
||||
[replace, mark, dispatch, held],
|
||||
[replace, mark, dispatch],
|
||||
)
|
||||
return { created, added }
|
||||
}
|
||||
@@ -172,12 +187,17 @@ export function useReferenceMoves(
|
||||
trace: MoveTrace,
|
||||
view: NavigationState['reference'],
|
||||
): ReferenceMoves {
|
||||
const held = useRef<Held>({ opener: null, cite: null }).current
|
||||
const held = useRef<Held>({ opener: null, cite: null, initial: null }).current
|
||||
const creating = view !== null && 'create' in view
|
||||
// A Back that removes the creation dialog leaves no citing form to answer.
|
||||
useEffect(() => {
|
||||
if (!creating) held.cite = null
|
||||
if (!creating) forget(held)
|
||||
}, [creating, held])
|
||||
const drafting = useCallback(
|
||||
(): Drafting | null =>
|
||||
held.cite ? { initial: held.initial, cite: held.cite } : null,
|
||||
[held],
|
||||
)
|
||||
const opener = useCallback((): HTMLElement | null => {
|
||||
const element = held.opener
|
||||
return element?.isConnected && !element.closest('[hidden]') ? element : null
|
||||
@@ -186,8 +206,9 @@ export function useReferenceMoves(
|
||||
return {
|
||||
...useOpening(ctx, held),
|
||||
...closing,
|
||||
...useCreated(ctx, closing.replace, held),
|
||||
...useCreated(ctx, closing.replace),
|
||||
...useFilter(ctx, trace),
|
||||
opener,
|
||||
drafting,
|
||||
}
|
||||
}
|
||||
@@ -1237,6 +1237,10 @@ export const en: Dict = {
|
||||
'editor.citations.new_reference': 'New reference',
|
||||
'editor.citations.cite': 'Cite',
|
||||
'editor.citations.pending_choice': 'Reference chosen but not cited yet: choose « Cite » or go back to the empty choice.',
|
||||
'editor.citations.created_draft': 'New reference cited in the draft: {citation}. It will be saved with the citations.',
|
||||
'editor.citations.pending_removed': 'New reference removed: {citation}',
|
||||
'editor.citations.pending': 'New',
|
||||
'editor.citations.pending_kept': 'New reference not saved, still in the draft: {citation}',
|
||||
'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_count_family_one': '{count} reference cited by this family',
|
||||
|
||||
@@ -1268,6 +1268,10 @@ export const fr: Dict = {
|
||||
'editor.citations.new_reference': 'Nouvelle référence',
|
||||
'editor.citations.cite': 'Citer',
|
||||
'editor.citations.pending_choice': 'Référence choisie mais pas encore citée : choisissez « Citer » ou revenez au choix vide.',
|
||||
'editor.citations.created_draft': 'Nouvelle référence citée dans le brouillon : {citation}. Elle sera enregistrée avec les citations.',
|
||||
'editor.citations.pending_removed': 'Nouvelle référence retirée : {citation}',
|
||||
'editor.citations.pending': 'Nouvelle',
|
||||
'editor.citations.pending_kept': 'Nouvelle référence non enregistrée, toujours dans le brouillon : {citation}',
|
||||
'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_count_family_one': '{count} référence citée par cette famille',
|
||||
|
||||
@@ -1,12 +1,24 @@
|
||||
/** Rev 5 Task 12: the citations draft, held as additions and removals. */
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { Reference } from '@faunosteo/core-wasm/types'
|
||||
import {
|
||||
addId,
|
||||
applyEdits,
|
||||
citationCommands,
|
||||
NO_EDITS,
|
||||
putCreated,
|
||||
removeId,
|
||||
sameEdits,
|
||||
} from '@/editor/references/citationEdits'
|
||||
|
||||
const value = (id: string, citation: string): Reference => ({
|
||||
id,
|
||||
type: 'book',
|
||||
citation,
|
||||
doi: null,
|
||||
url: null,
|
||||
})
|
||||
|
||||
describe('citation edits', () => {
|
||||
it('applies removals and additions to the current list, each id once', () => {
|
||||
const edits = addId(removeId(NO_EDITS, 'a'), 'b')
|
||||
@@ -26,4 +38,40 @@ describe('citation edits', () => {
|
||||
const gone = removeId(NO_EDITS, 'a')
|
||||
expect(removeId(gone, 'a')).toBe(gone)
|
||||
})
|
||||
|
||||
it('a created reference joins the draft with its id; a second put replaces it', () => {
|
||||
const once = putCreated(NO_EDITS, value('ref-n', 'Neuf'))
|
||||
expect(once).toEqual({
|
||||
added: ['ref-n'],
|
||||
removed: [],
|
||||
created: [value('ref-n', 'Neuf')],
|
||||
})
|
||||
const twice = putCreated(once, value('ref-n', 'Neuf 2'))
|
||||
expect(twice.created).toEqual([value('ref-n', 'Neuf 2')])
|
||||
expect(twice.added).toEqual(['ref-n'])
|
||||
expect(sameEdits(once, twice)).toBe(false)
|
||||
})
|
||||
|
||||
it('removing a created id drops it entirely', () => {
|
||||
const edits = putCreated(addId(NO_EDITS, 'b'), value('ref-n', 'Neuf'))
|
||||
expect(removeId(edits, 'ref-n')).toEqual(addId(NO_EDITS, 'b'))
|
||||
})
|
||||
|
||||
it('the save: an insert per created reference under a minted id, then the update', () => {
|
||||
const edits = putCreated(removeId(NO_EDITS, 'a'), value('ref-n', 'Neuf'))
|
||||
const minted = ['ref-m']
|
||||
const commands = citationCommands(
|
||||
edits,
|
||||
['a', 'c'],
|
||||
(ids) => ({ op: 'remove', key: { kind: 'reference', id: ids.join() } }),
|
||||
() => minted.shift()!,
|
||||
)
|
||||
expect(commands).toEqual([
|
||||
{
|
||||
op: 'insert',
|
||||
element: { kind: 'reference', value: value('ref-m', 'Neuf') },
|
||||
},
|
||||
{ op: 'remove', key: { kind: 'reference', id: 'c,ref-m' } },
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -44,6 +44,17 @@ vi.mock('@faunosteo/supabase', async (orig) => ({
|
||||
submitSheetReview: vi.fn(),
|
||||
}))
|
||||
|
||||
/** Ids handed out before the real generator: a clash at the save (Rev 6). */
|
||||
const minted = vi.hoisted((): string[] => [])
|
||||
vi.mock('@/editor/ids', async (orig) => {
|
||||
const real = await orig<typeof import('@/editor/ids')>()
|
||||
return {
|
||||
...real,
|
||||
newElementId: (prefix: Parameters<typeof real.newElementId>[0]) =>
|
||||
minted.shift() ?? real.newElementId(prefix),
|
||||
}
|
||||
})
|
||||
|
||||
let navigate: NavigateFunction
|
||||
let location: Location
|
||||
const probe = (n: NavigateFunction, l: Location) => {
|
||||
@@ -59,6 +70,7 @@ beforeEach(() => {
|
||||
TAG = resolveSessionTag(USER)
|
||||
})
|
||||
afterEach(() => {
|
||||
minted.length = 0
|
||||
cleanup()
|
||||
resetStore()
|
||||
setWidth(1024)
|
||||
@@ -197,6 +209,24 @@ async function cite(user: User, id: string) {
|
||||
await user.click(button('Citer'))
|
||||
}
|
||||
|
||||
/** The reference dialog over the edit mode: type and citation, then « Ajouter la référence ». */
|
||||
async function createPending(user: User, citation: string) {
|
||||
await waitFor(() => expect(referenceDialog()).toBeDefined())
|
||||
await user.selectOptions(inReference().getByLabelText('Type'), 'book')
|
||||
await user.type(inReference().getByLabelText('Citation'), citation)
|
||||
await user.click(
|
||||
inReference().getByRole('button', { name: 'Ajouter la référence' }),
|
||||
)
|
||||
await waitFor(() => expect(referenceDialog()).toBeUndefined())
|
||||
}
|
||||
const pendingRow = () =>
|
||||
[...citations()!.querySelectorAll<HTMLElement>('[data-citation-row]')][2]
|
||||
const status = () =>
|
||||
citations()!.querySelector('[data-place="citations"] > [role="status"]')!
|
||||
.textContent
|
||||
const live = () =>
|
||||
document.querySelector('p.sr-only[aria-live="polite"]')!.textContent ?? ''
|
||||
|
||||
describe('the « Modifier » of the references dialog', () => {
|
||||
it('edit mode: no history entry, no « Tout afficher », no « Aller à »', async () => {
|
||||
const user = await mount()
|
||||
@@ -391,9 +421,6 @@ describe('« Citer » (Rev 6)', () => {
|
||||
})
|
||||
})
|
||||
|
||||
const live = () =>
|
||||
document.querySelector('p.sr-only[aria-live="polite"]')!.textContent ?? ''
|
||||
|
||||
describe('leaving the edit mode with changes', () => {
|
||||
it('an explicit « Abandonner » after ✕ closes the dialog without a word', async () => {
|
||||
const user = await mount()
|
||||
@@ -509,7 +536,7 @@ describe('the reference dialog over the edit mode', () => {
|
||||
expect(rows()).toEqual(['ref-a'])
|
||||
})
|
||||
|
||||
it('« Nouvelle référence » creates it and cites it in the draft only', async () => {
|
||||
it('« Nouvelle référence » cites it in the draft only; the library is unchanged', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await user.click(button('Nouvelle référence'))
|
||||
@@ -518,40 +545,163 @@ describe('the reference dialog over the edit mode', () => {
|
||||
'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 createPending(user, 'Neuf')
|
||||
expect(library()).not.toContain('Neuf')
|
||||
expect(rows()).toHaveLength(3)
|
||||
expect(rows().slice(0, 2)).toEqual(['ref-a', 'ref-c'])
|
||||
const row = pendingRow()
|
||||
expect(within(row).getByText('Neuf')).toBeVisible()
|
||||
expect(within(row).getByText('Nouvelle')).toBeVisible()
|
||||
expect(status()).toBe(
|
||||
'Nouvelle référence citée dans le brouillon : Neuf. ' +
|
||||
'Elle sera enregistrée avec les citations.',
|
||||
)
|
||||
await waitFor(() => expect(referenceDialog()).toBeUndefined())
|
||||
expect(library()).toContain('Neuf')
|
||||
expect(live()).not.toContain('sera enregistrée')
|
||||
expect(undos()).toBe(0)
|
||||
})
|
||||
|
||||
it('« Enregistrer » writes the reference and the citations as ONE undo step', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await user.click(button('Nouvelle référence'))
|
||||
await createPending(user, 'Neuf')
|
||||
await user.click(button('Enregistrer'))
|
||||
await waitFor(() => expect(button('Modifier')).toHaveFocus())
|
||||
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)
|
||||
expect(undos()).toBe(1)
|
||||
act(() => {
|
||||
store.getState().undoStep()
|
||||
})
|
||||
expect(library()).not.toContain('Neuf')
|
||||
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
|
||||
act(() => {
|
||||
store.getState().redoStep()
|
||||
})
|
||||
expect(library()).toContain('Neuf')
|
||||
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c', id])
|
||||
})
|
||||
|
||||
it('a reference created, then the draft abandoned, stays in the library uncited', async () => {
|
||||
it('created, then the draft abandoned: library unchanged, nothing said', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await user.click(button('Nouvelle référence'))
|
||||
await createPending(user, 'Neuf')
|
||||
await user.click(button('Annuler'))
|
||||
await user.click(button('Abandonner'))
|
||||
expect(library()).not.toContain('Neuf')
|
||||
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
|
||||
expect(undos()).toBe(0)
|
||||
await user.click(button('Fermer'))
|
||||
await waitFor(() => expect(citations()).toBeUndefined())
|
||||
await user.click(inFindingDialog().getByRole('button', { name: 'Fermer' }))
|
||||
await waitFor(() => expect(findingDialog()).toBeNull())
|
||||
await act(async () => undefined)
|
||||
expect(live()).not.toContain('sera enregistrée')
|
||||
})
|
||||
|
||||
it('a pending reference is modified, prefilled; nothing is written', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await user.click(button('Nouvelle référence'))
|
||||
await createPending(user, 'Neuf')
|
||||
const pendingId = rows()[2]
|
||||
await user.click(button(/^Modifier la référence Neuf/))
|
||||
await waitFor(() => expect(referenceDialog()).toBeDefined())
|
||||
expect(
|
||||
inReference().getByRole('heading', { name: 'Nouvelle référence' }),
|
||||
).toBeVisible()
|
||||
const citation = inReference().getByLabelText('Citation')
|
||||
expect(citation).toHaveValue('Neuf')
|
||||
await user.type(citation, ' 2')
|
||||
await user.click(inReference().getByRole('button', { name: 'Valider' }))
|
||||
await waitFor(() => expect(referenceDialog()).toBeUndefined())
|
||||
expect(rows()).toEqual(['ref-a', 'ref-c', pendingId])
|
||||
expect(within(pendingRow()).getByText('Neuf 2')).toBeVisible()
|
||||
expect(library()).not.toContain('Neuf 2')
|
||||
await user.click(button('Enregistrer'))
|
||||
expect(library().filter((c) => c.startsWith('Neuf'))).toEqual(['Neuf 2'])
|
||||
expect(undos()).toBe(1)
|
||||
})
|
||||
|
||||
it('« Retirer » drops a pending reference entirely and says so in the dialog', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await user.click(button('Nouvelle référence'))
|
||||
await createPending(user, 'Neuf')
|
||||
await removeRow(user, /Neuf/)
|
||||
expect(rows()).toEqual(['ref-a', 'ref-c'])
|
||||
expect(status()).toBe('Nouvelle référence retirée : Neuf')
|
||||
await user.click(button('Annuler'))
|
||||
await waitFor(() => expect(button('Modifier')).toHaveFocus())
|
||||
expect(library()).not.toContain('Neuf')
|
||||
expect(undos()).toBe(0)
|
||||
})
|
||||
|
||||
it('a double submit of the creation makes one pending row', 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')
|
||||
const form = referenceDialog()!.querySelector('form')!
|
||||
act(() => {
|
||||
fireEvent.submit(form)
|
||||
fireEvent.submit(form)
|
||||
})
|
||||
await waitFor(() => expect(referenceDialog()).toBeUndefined())
|
||||
expect(rows()).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('the creation is dry-run: a refusal shows in its form, nothing cited', 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')
|
||||
minted.push('ref-a')
|
||||
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(inReference().getByRole('alert')).toBeVisible()
|
||||
expect(referenceDialog()).toBeDefined()
|
||||
expect(rows()).toEqual(['ref-a', 'ref-c'])
|
||||
expect(undos()).toBe(0)
|
||||
})
|
||||
|
||||
it('a clashing id at the save is minted again once', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await user.click(button('Nouvelle référence'))
|
||||
await createPending(user, 'Neuf')
|
||||
minted.push('ref-a')
|
||||
await user.click(button('Enregistrer'))
|
||||
await waitFor(() => expect(button('Modifier')).toHaveFocus())
|
||||
const added = doc().references.find(
|
||||
(r: { citation: string }) => r.citation === 'Neuf',
|
||||
)
|
||||
expect(added.id).not.toBe('ref-a')
|
||||
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c', added.id])
|
||||
expect(undos()).toBe(1)
|
||||
})
|
||||
|
||||
it('a save refused twice keeps the draft and names the pending reference', async () => {
|
||||
const user = await mount()
|
||||
await editCitations(user)
|
||||
await user.click(button('Nouvelle référence'))
|
||||
await createPending(user, 'Neuf')
|
||||
minted.push('ref-a', 'ref-c')
|
||||
await user.click(button('Enregistrer'))
|
||||
const alert = inCitations().getByRole('alert')
|
||||
expect(alert).toHaveTextContent(/Neuf/)
|
||||
expect(rows()).toHaveLength(3)
|
||||
expect(library()).not.toContain('Neuf')
|
||||
expect(undos()).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('a finding draft and a references draft on the same element', () => {
|
||||
|
||||
@@ -152,55 +152,62 @@ describe('closeCitations', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('a creation started over the citations dialog', () => {
|
||||
it('hands its id to the form that started it; no « added » notice', async () => {
|
||||
describe('a creation started over the citations dialog (Rev 6: a draft creation)', () => {
|
||||
const pending = {
|
||||
id: 'ref-p',
|
||||
type: 'book',
|
||||
citation: 'Neuf',
|
||||
doi: null,
|
||||
url: null,
|
||||
} as const
|
||||
|
||||
it('holds its citing form and the pending value; created() never cites', async () => {
|
||||
cited()
|
||||
const cite = vi.fn()
|
||||
act(() => nav.references.start(null, cite))
|
||||
act(() => nav.references.start(null, cite, pending))
|
||||
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.references.drafting()).toEqual({ initial: pending, cite })
|
||||
act(() => nav.references.close(true))
|
||||
expect(nav.references.drafting()).toBeNull()
|
||||
expect(nav.state.reference).toBeNull()
|
||||
expect(nav.state.finding).toMatchObject({ citations: true })
|
||||
expect(cite).not.toHaveBeenCalled()
|
||||
expect(nav.references.added).toBeNull()
|
||||
})
|
||||
|
||||
it('a creation closed or replaced forgets its citing form', async () => {
|
||||
it('a new one has no initial value', () => {
|
||||
cited()
|
||||
const cite = vi.fn()
|
||||
act(() => nav.references.start(null, cite))
|
||||
act(() => nav.references.close(true))
|
||||
await act(async () => nav.references.created('ref-x'))
|
||||
expect(cite).not.toHaveBeenCalled()
|
||||
act(() => nav.references.start(null, cite))
|
||||
expect(nav.references.drafting()).toEqual({ initial: null, cite })
|
||||
})
|
||||
|
||||
it('a creation replaced forgets its citing form', () => {
|
||||
cited()
|
||||
act(() => nav.references.start(null, vi.fn(), pending))
|
||||
act(() => nav.references.replace(null))
|
||||
await act(async () => nav.references.created('ref-y'))
|
||||
expect(cite).not.toHaveBeenCalled()
|
||||
expect(nav.references.drafting()).toBeNull()
|
||||
})
|
||||
|
||||
it('a Back that removes the creation dialog forgets its citing form', async () => {
|
||||
it('a Back that removes the creation dialog forgets its citing form', () => {
|
||||
cited()
|
||||
const cite = vi.fn()
|
||||
act(() => nav.references.start(null, cite))
|
||||
act(() => nav.references.start(null, vi.fn(), pending))
|
||||
act(() => navigate(-1))
|
||||
expect(nav.state.reference).toBeNull()
|
||||
await act(async () => nav.references.created('ref-z'))
|
||||
expect(cite).not.toHaveBeenCalled()
|
||||
expect(nav.references.added).toMatchObject({ id: 'ref-z' })
|
||||
expect(nav.references.drafting()).toBeNull()
|
||||
})
|
||||
|
||||
it('a later creation from the library sets the notice, cites nothing', async () => {
|
||||
it('a creation from the library is no draft; created() sets the notice', async () => {
|
||||
cited()
|
||||
const cite = vi.fn()
|
||||
act(() => nav.references.start(null, cite))
|
||||
act(() => nav.references.start(null, vi.fn()))
|
||||
act(() => nav.references.close(true))
|
||||
act(() => nav.selectTab('references'))
|
||||
act(() => nav.references.start(null))
|
||||
expect(nav.references.drafting()).toBeNull()
|
||||
await act(async () => nav.references.created('ref-lib'))
|
||||
expect(cite).not.toHaveBeenCalled()
|
||||
expect(nav.references.added).toMatchObject({ id: 'ref-lib' })
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user