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
+661
-152
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'])
|
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 ({
|
/** « Nouvelle référence » over the edit mode, typed, then « Ajouter la référence ». */
|
||||||
page,
|
async function createPending(page: Page) {
|
||||||
}) => {
|
|
||||||
test.setTimeout(150_000)
|
|
||||||
const { seed } = await open(page)
|
|
||||||
await editCitations(page)
|
|
||||||
const create = inDialog(page, dict['editor.citations.new_reference'])
|
const create = inDialog(page, dict['editor.citations.new_reference'])
|
||||||
await create.click()
|
await create.click()
|
||||||
const form = referenceDialog(page)
|
const form = referenceDialog(page)
|
||||||
await expect(form).toBeVisible()
|
await expect(form).toBeVisible()
|
||||||
await expect(page.locator('dialog[open]')).toHaveCount(3)
|
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-type').selectOption('manual')
|
||||||
await form.locator('#reference-form-citation').fill('Source nouvelle')
|
await form.locator('#reference-form-citation').fill('Source nouvelle')
|
||||||
await form
|
await form
|
||||||
@@ -605,14 +604,54 @@ test.describe('references dialog, edit mode', () => {
|
|||||||
await expect(create).toBeFocused()
|
await expect(create).toBeFocused()
|
||||||
await expect(draftRows(page)).toHaveCount(4)
|
await expect(draftRows(page)).toHaveCount(4)
|
||||||
await expect(draftRows(page).last()).toContainText('Source nouvelle')
|
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 inDialog(page, dict['editor.findings.save']).click()
|
||||||
await expect(editButton(page)).toBeFocused()
|
await expect(editButton(page)).toBeFocused()
|
||||||
await closeCitations(page, dict)
|
await closeCitations(page, dict)
|
||||||
await closeFinding(page, dict)
|
await closeFinding(page, dict)
|
||||||
await saveDraft(page, dict, seed.revision + 1)
|
await saveDraft(page, dict, seed.revision + 1)
|
||||||
const saved = await serverDocument<Record<string, unknown>>(seed.draftId)
|
let saved = await serverDocument<Record<string, unknown>>(seed.draftId)
|
||||||
const refs = saved.references as { id: string; citation: string }[]
|
const added = (saved.references as { id: string; citation: string }[]).find(
|
||||||
const added = refs.find((ref) => ref.citation === 'Source nouvelle')
|
(ref) => ref.citation === 'Source nouvelle',
|
||||||
|
)
|
||||||
expect(added).toBeDefined()
|
expect(added).toBeDefined()
|
||||||
expect(nodeOf(saved).reference_ids).toEqual([
|
expect(nodeOf(saved).reference_ids).toEqual([
|
||||||
'ref-a',
|
'ref-a',
|
||||||
@@ -620,6 +659,16 @@ test.describe('references dialog, edit mode', () => {
|
|||||||
'ref-c',
|
'ref-c',
|
||||||
added!.id,
|
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
|
citedBy: ElementKey
|
||||||
mode: Mode
|
mode: Mode
|
||||||
props: CitationsDialogProps
|
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. */
|
/** 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 doc = useSheetDocument()
|
||||||
const readOnly = useEditorReadOnly()
|
const readOnly = useEditorReadOnly()
|
||||||
return (
|
return (
|
||||||
@@ -70,6 +72,7 @@ function EditBody({ citedBy, mode, props }: BodyProps) {
|
|||||||
guards={props.guards}
|
guards={props.guards}
|
||||||
references={props.references}
|
references={props.references}
|
||||||
onDone={mode.done}
|
onDone={mode.done}
|
||||||
|
onNotice={onNotice}
|
||||||
onDiscardClose={() => props.onClose(true, true)}
|
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 t = useT()
|
||||||
const { mode } = body
|
const { mode } = body
|
||||||
|
const [notice, setNotice] = useState('')
|
||||||
|
if (!mode.editing && notice !== '') setNotice('')
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
id="editor-citations-panel"
|
id="editor-citations-panel"
|
||||||
@@ -114,9 +122,13 @@ function Body(body: BodyProps) {
|
|||||||
aria-labelledby={CITATIONS_TITLE_ID}
|
aria-labelledby={CITATIONS_TITLE_ID}
|
||||||
className="space-y-3"
|
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)]">
|
<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>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { useEffect, useRef } from 'react'
|
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 Button from '@/components/ui/Button'
|
||||||
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
|
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
|
||||||
import Select from '@/components/ui/Select'
|
import Select from '@/components/ui/Select'
|
||||||
@@ -20,11 +22,13 @@ export interface CiteChoice {
|
|||||||
export interface DraftListProps {
|
export interface DraftListProps {
|
||||||
/** The draft's cited ids, in the order they will be saved. */
|
/** The draft's cited ids, in the order they will be saved. */
|
||||||
ids: readonly string[]
|
ids: readonly string[]
|
||||||
|
/** The references made in the draft (Rev 6): written only by « Enregistrer ». */
|
||||||
|
pending: readonly Reference[]
|
||||||
readOnly: boolean
|
readOnly: boolean
|
||||||
choice: CiteChoice
|
choice: CiteChoice
|
||||||
onAdd: (id: string) => void
|
onAdd: (id: string) => void
|
||||||
onRemove: (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
|
onEditReference: (id: string, opener: HTMLElement) => void
|
||||||
/** « Nouvelle référence »: the creation dialog over this one. */
|
/** « Nouvelle référence »: the creation dialog over this one. */
|
||||||
onNew: (opener: HTMLElement) => void
|
onNew: (opener: HTMLElement) => void
|
||||||
@@ -72,15 +76,28 @@ interface RowProps {
|
|||||||
onRemove: () => void
|
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) {
|
function DraftRow({ id, props, onRemove }: RowProps) {
|
||||||
const t = useT()
|
const t = useT()
|
||||||
const doc = useSheetDocument()
|
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}`
|
const shown = citation ?? `${t('editor.references.missing')} ${id}`
|
||||||
return (
|
return (
|
||||||
<li data-citation-row={id} className="flex flex-wrap items-center gap-2">
|
<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 && (
|
{citation !== undefined && (
|
||||||
<Button
|
<Button
|
||||||
type="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
|
* 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.
|
* Nothing is written before « Enregistrer ». Read only: every control off.
|
||||||
*/
|
*/
|
||||||
export default function CitationsDraftList(props: DraftListProps) {
|
export default function CitationsDraftList(props: DraftListProps) {
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
import { useEffect, useRef, useState } from 'react'
|
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 { FormActions } from '@/components/editor/findings/DiscardConfirm'
|
||||||
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
|
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
|
||||||
import { useFormDraft } from '@/components/editor/findings/useDirtyGuard'
|
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 {
|
import {
|
||||||
addId,
|
addId,
|
||||||
applyEdits,
|
applyEdits,
|
||||||
|
citationCommands,
|
||||||
NO_EDITS,
|
NO_EDITS,
|
||||||
|
putCreated,
|
||||||
removeId,
|
removeId,
|
||||||
sameEdits,
|
sameEdits,
|
||||||
type CitationEdits,
|
type CitationEdits,
|
||||||
@@ -31,6 +35,8 @@ export interface CitationsEditFormProps {
|
|||||||
references: Pick<ReferenceMoves, 'open' | 'start'>
|
references: Pick<ReferenceMoves, 'open' | 'start'>
|
||||||
/** Back to the view mode; `saved` is true when a command was written. */
|
/** Back to the view mode; `saved` is true when a command was written. */
|
||||||
onDone: (saved: boolean) => void
|
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. */
|
/** « Abandonner » after a close request: the draft goes, so does the dialog. */
|
||||||
onDiscardClose: () => void
|
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])
|
a.length === b.length && a.every((id, at) => id === b[at])
|
||||||
|
|
||||||
type Draft = ReturnType<typeof useFormDraft<CitationEdits>>
|
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) {
|
function useCitationsSave(props: CitationsEditFormProps, form: Draft) {
|
||||||
|
const t = useT()
|
||||||
const { item, ids } = useCurrent(props.citedBy)
|
const { item, ids } = useCurrent(props.citedBy)
|
||||||
const edit = useEditCommand()
|
const edit = useEditCommand()
|
||||||
const save = () => {
|
const save = () => {
|
||||||
const next = applyEdits(ids, form.draft)
|
if (!item) {
|
||||||
if (!item || sameIds(next, ids)) return props.onDone(false)
|
const gone = isFamilyKey(props.citedBy)
|
||||||
const element = patchElement(item, { reference_ids: next })
|
? 'editor.findings.gone_family'
|
||||||
const command = { op: 'update', key: item.key, element } as const
|
: 'editor.findings.gone'
|
||||||
if (edit.run('save', command)) props.onDone(true)
|
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 {
|
return {
|
||||||
shown: applyEdits(ids, form.draft),
|
shown: applyEdits(ids, form.draft),
|
||||||
save,
|
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,
|
* « Nouvelle référence », or « Modifier la référence » of a pending one (Rev 6): the
|
||||||
* only while this form is still there (an abandoned draft cites nothing).
|
* 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) {
|
function useCreation(props: CitationsEditFormProps, form: Draft) {
|
||||||
|
const t = useT()
|
||||||
const latest = useRef(form)
|
const latest = useRef(form)
|
||||||
latest.current = form
|
latest.current = form
|
||||||
const alive = useRef(true)
|
const alive = useRef(true)
|
||||||
@@ -79,11 +120,37 @@ function useCreation(props: CitationsEditFormProps, form: Draft) {
|
|||||||
alive.current = false
|
alive.current = false
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
return (opener: HTMLElement) =>
|
const cite = (value: Reference) => {
|
||||||
props.references.start(opener, (id) => {
|
if (!alive.current) return
|
||||||
const now = latest.current
|
const now = latest.current
|
||||||
if (alive.current) now.set(addId(now.draft, id))
|
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) {
|
function useCitationsForm(props: CitationsEditFormProps) {
|
||||||
const form = useFormDraft(NO_EDITS, props.guards, sameEdits, 'citations')
|
const form = useFormDraft(NO_EDITS, props.guards, sameEdits, 'citations')
|
||||||
const saving = useCitationsSave(props, form)
|
const saving = useCitationsSave(props, form)
|
||||||
@@ -125,16 +192,17 @@ function useCitationsForm(props: CitationsEditFormProps) {
|
|||||||
choice,
|
choice,
|
||||||
cancel,
|
cancel,
|
||||||
submit,
|
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
|
* 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
|
* reference made in the draft, Rev 6), one batch on « Enregistrer » (the new references
|
||||||
* while a choice in the select waits for « Citer », Rev 6), nothing on
|
* and the `update`, one undo step; none when nothing changed; refused while a choice in
|
||||||
* « Annuler » or a close. The draft's layer is `citations`: a dirty one is asked before a
|
* the select waits for « Citer »), nothing on « Annuler » or a close. The draft's layer
|
||||||
* close, a Back or a leave. Read only: the draft stays, only « Abandonner » is left.
|
* 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) {
|
export default function CitationsEditForm(props: CitationsEditFormProps) {
|
||||||
const t = useT()
|
const t = useT()
|
||||||
@@ -157,12 +225,13 @@ export default function CitationsEditForm(props: CitationsEditFormProps) {
|
|||||||
{props.readOnly && <ReadOnlyNotice />}
|
{props.readOnly && <ReadOnlyNotice />}
|
||||||
<CitationsDraftList
|
<CitationsDraftList
|
||||||
ids={form.shown}
|
ids={form.shown}
|
||||||
|
pending={form.draft.created}
|
||||||
readOnly={props.readOnly}
|
readOnly={props.readOnly}
|
||||||
choice={form.choice}
|
choice={form.choice}
|
||||||
onAdd={(id) => form.set(addId(form.draft, id))}
|
onAdd={(id) => form.set(addId(form.draft, id))}
|
||||||
onRemove={(id) => form.set(removeId(form.draft, id))}
|
onRemove={form.rows.remove}
|
||||||
onEditReference={props.references.open}
|
onEditReference={form.rows.editReference}
|
||||||
onNew={form.create}
|
onNew={(opener) => form.rows.create(opener)}
|
||||||
/>
|
/>
|
||||||
{form.error && (
|
{form.error && (
|
||||||
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
|
<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 }
|
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(
|
function useOnSaved(
|
||||||
layer: ReferenceLayer,
|
layer: ReferenceLayer,
|
||||||
creating: boolean,
|
creating: boolean,
|
||||||
@@ -98,7 +101,7 @@ function useOnSaved(
|
|||||||
) {
|
) {
|
||||||
const t = useT()
|
const t = useT()
|
||||||
return (id: string, citation: string) => {
|
return (id: string, citation: string) => {
|
||||||
if (!creating) return void layer.close(true)
|
if (!creating || layer.drafting()) return void layer.close(true)
|
||||||
handOver(id)
|
handOver(id)
|
||||||
layer.announce(t('editor.references.added').replace('{citation}', citation))
|
layer.announce(t('editor.references.added').replace('{citation}', citation))
|
||||||
layer.created(id)
|
layer.created(id)
|
||||||
@@ -108,8 +111,10 @@ function useOnSaved(
|
|||||||
/**
|
/**
|
||||||
* The reference dialog (R2F-5): one `Dialog` over the References tab or the references
|
* 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
|
* 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
|
* a new one. Over the edit mode it is a draft creation (Rev 6): titled « Nouvelle
|
||||||
* place, so it is never a native modal inside a hidden one.
|
* 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({
|
export default function ReferenceDialog({
|
||||||
layer,
|
layer,
|
||||||
@@ -119,6 +124,8 @@ export default function ReferenceDialog({
|
|||||||
const shown = useShownReference(layer, creation.handed)
|
const shown = useShownReference(layer, creation.handed)
|
||||||
const returnFocus = useReturnTarget(layer)
|
const returnFocus = useReturnTarget(layer)
|
||||||
const onSaved = useOnSaved(layer, shown.creating, creation.handOver)
|
const onSaved = useOnSaved(layer, shown.creating, creation.handOver)
|
||||||
|
const drafting = layer.drafting()
|
||||||
|
const reference = drafting ? drafting.initial : shown.edited
|
||||||
useGoneRule(layer)
|
useGoneRule(layer)
|
||||||
return (
|
return (
|
||||||
<Dialog
|
<Dialog
|
||||||
@@ -130,11 +137,12 @@ export default function ReferenceDialog({
|
|||||||
onClose={() => (layer.close() ? undefined : 'kept')}
|
onClose={() => (layer.close() ? undefined : 'kept')}
|
||||||
>
|
>
|
||||||
<ReferenceForm
|
<ReferenceForm
|
||||||
key={shown.edited?.id ?? 'new'}
|
key={reference?.id ?? 'new'}
|
||||||
reference={shown.edited}
|
reference={reference}
|
||||||
readOnly={readOnly}
|
readOnly={readOnly}
|
||||||
guards={layer.guards}
|
guards={layer.guards}
|
||||||
onSaved={onSaved}
|
onSaved={onSaved}
|
||||||
|
onValue={drafting?.cite}
|
||||||
onClose={(forced) => layer.close(forced)}
|
onClose={(forced) => layer.close(forced)}
|
||||||
/>
|
/>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import SelectField from '@/components/editor/fields/SelectField'
|
|||||||
import { FormActions } from '@/components/editor/findings/DiscardConfirm'
|
import { FormActions } from '@/components/editor/findings/DiscardConfirm'
|
||||||
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
|
import ReadOnlyNotice from '@/components/editor/findings/ReadOnlyNotice'
|
||||||
import { useFormDraft } from '@/components/editor/findings/useDirtyGuard'
|
import { useFormDraft } from '@/components/editor/findings/useDirtyGuard'
|
||||||
|
import { newElementId } from '@/editor/ids'
|
||||||
import { webHref } from '@/editor/references/safeLink'
|
import { webHref } from '@/editor/references/safeLink'
|
||||||
import { isBlank, nullable } from '@/editor/sheetDocument'
|
import { isBlank, nullable } from '@/editor/sheetDocument'
|
||||||
import { useEditCommand } from '@/editor/useEditCommand'
|
import { useEditCommand } from '@/editor/useEditCommand'
|
||||||
@@ -77,22 +78,27 @@ export interface ReferenceFormProps {
|
|||||||
reference: Reference | null
|
reference: Reference | null
|
||||||
readOnly: boolean
|
readOnly: boolean
|
||||||
guards: Guards
|
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
|
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. */
|
/** Nothing was written (pristine save, « Annuler », « Abandonner »); forced drops a draft. */
|
||||||
onClose: (forced: boolean) => void
|
onClose: (forced: boolean) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
type Form = ReturnType<typeof useFormDraft<Draft>>
|
type Form = ReturnType<typeof useFormDraft<Draft>>
|
||||||
|
|
||||||
/**
|
type EditApi = ReturnType<typeof useEditCommand>
|
||||||
* 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.
|
/** The one command of a library save: an `update`, or an `insert` under a new id. */
|
||||||
*/
|
function writeCommand(
|
||||||
function useWrite(reference: Reference | null, draft: Draft) {
|
edit: EditApi,
|
||||||
const edit = useEditCommand()
|
reference: Reference | null,
|
||||||
const saved = useRef(false)
|
draft: Draft,
|
||||||
const run = (): string | null => {
|
): string | null {
|
||||||
if (reference) {
|
if (reference) {
|
||||||
const element = { kind: 'reference', value: valueOf(draft, reference.id) }
|
const element = { kind: 'reference', value: valueOf(draft, reference.id) }
|
||||||
const key = { kind: 'reference', id: reference.id }
|
const key = { kind: 'reference', id: reference.id }
|
||||||
@@ -106,7 +112,37 @@ function useWrite(reference: Reference | null, draft: Draft) {
|
|||||||
return { op: 'insert', element } as EditCommand
|
return { op: 'insert', element } as EditCommand
|
||||||
})
|
})
|
||||||
return added ? id : null
|
return added ? id : null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 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 =>
|
||||||
|
props.onValue
|
||||||
|
? offerValue(edit, props, draft, props.onValue)
|
||||||
|
: writeCommand(edit, props.reference, draft)
|
||||||
const write = (): string | null => {
|
const write = (): string | null => {
|
||||||
const id = saved.current ? null : run()
|
const id = saved.current ? null : run()
|
||||||
saved.current = saved.current || id !== null
|
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. */
|
/** The save: refused on its field, nothing written when unchanged, else one command. */
|
||||||
function useReferenceSave(props: ReferenceFormProps, form: Form) {
|
function useReferenceSave(props: ReferenceFormProps, form: Form) {
|
||||||
const { edit, write } = useWrite(props.reference, form.draft)
|
const { edit, write } = useWrite(props, form.draft)
|
||||||
const save = () => {
|
const save = () => {
|
||||||
const refusal = refusalOf(form.draft, props.reference === null)
|
const refusal = refusalOf(form.draft, props.reference === null)
|
||||||
if (refusal) {
|
if (refusal) {
|
||||||
@@ -201,15 +237,21 @@ function FormFields({
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* A reference edited or created in the reference dialog (R2F-5): a local draft, one
|
* 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
|
* command on « Enregistrer » (none when nothing changed; in a draft creation, none at all:
|
||||||
* or a move. When the editor turns read-only the draft stays, its fields read-only, and
|
* the value goes to the citing form), nothing on « Annuler », a close or a move. When
|
||||||
* only « Abandonner » is left.
|
* the editor turns read-only the draft stays, its fields read-only, and only
|
||||||
|
* « Abandonner » is left.
|
||||||
*/
|
*/
|
||||||
export default function ReferenceForm(props: ReferenceFormProps) {
|
export default function ReferenceForm(props: ReferenceFormProps) {
|
||||||
const t = useT()
|
const t = useT()
|
||||||
const form = useReferenceForm(props)
|
const form = useReferenceForm(props)
|
||||||
const { guard } = form
|
const { guard } = form
|
||||||
const creating = props.reference === null
|
const submitLabel =
|
||||||
|
props.reference === null
|
||||||
|
? 'editor.reference.add'
|
||||||
|
: props.onValue
|
||||||
|
? 'common.confirm'
|
||||||
|
: 'editor.findings.save'
|
||||||
return (
|
return (
|
||||||
<form
|
<form
|
||||||
data-draft-form
|
data-draft-form
|
||||||
@@ -230,9 +272,7 @@ export default function ReferenceForm(props: ReferenceFormProps) {
|
|||||||
<FormActions
|
<FormActions
|
||||||
confirming={guard.confirming}
|
confirming={guard.confirming}
|
||||||
readOnly={props.readOnly}
|
readOnly={props.readOnly}
|
||||||
submitLabel={t(
|
submitLabel={t(submitLabel)}
|
||||||
creating ? 'editor.reference.add' : 'editor.findings.save',
|
|
||||||
)}
|
|
||||||
onCancel={() =>
|
onCancel={() =>
|
||||||
form.dirty && !props.readOnly
|
form.dirty && !props.readOnly
|
||||||
? guard.askToLeave()
|
? 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,
|
* 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
|
* 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.
|
* 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 {
|
export interface CitationEdits {
|
||||||
added: readonly string[]
|
added: readonly string[]
|
||||||
removed: 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) =>
|
export const sameEdits = (a: CitationEdits, b: CitationEdits) =>
|
||||||
JSON.stringify(a) === JSON.stringify(b)
|
JSON.stringify(a) === JSON.stringify(b)
|
||||||
@@ -31,11 +36,53 @@ export function addId(edits: CitationEdits, id: string): CitationEdits {
|
|||||||
return { ...edits, added: [...edits.added, id] }
|
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 {
|
export function removeId(edits: CitationEdits, id: string): CitationEdits {
|
||||||
if (edits.added.includes(id)) {
|
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
|
if (edits.removed.includes(id)) return edits
|
||||||
return { ...edits, removed: [...edits.removed, id] }
|
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 { unmeasuredViews } from './issues'
|
||||||
import type { TabTier } from './useViewport'
|
import type { TabTier } from './useViewport'
|
||||||
import type { Guards } from './useEditorNavigation'
|
import type { Guards } from './useEditorNavigation'
|
||||||
import type { AddedReference } from './useReferenceMoves'
|
import type { AddedReference, ReferenceMoves } from './useReferenceMoves'
|
||||||
|
|
||||||
export const EDITOR_TABS = [
|
export const EDITOR_TABS = [
|
||||||
'general',
|
'general',
|
||||||
@@ -64,7 +64,9 @@ export interface ReferenceLayer {
|
|||||||
filter: ElementKey | null
|
filter: ElementKey | null
|
||||||
guards: Guards
|
guards: Guards
|
||||||
open: (id: string, opener?: HTMLElement | null) => void
|
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
|
close: (forced?: boolean) => boolean
|
||||||
replace: (id: string | null, text?: string) => void
|
replace: (id: string | null, text?: string) => void
|
||||||
created: (id: string) => void
|
created: (id: string) => void
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import type { EditCommand } from '@faunosteo/core-wasm/types'
|
import type { EditCommand } from '@faunosteo/core-wasm/types'
|
||||||
|
import type { CommitOutcome } from './state/editorTypes'
|
||||||
import { useT } from '@/i18n/useT'
|
import { useT } from '@/i18n/useT'
|
||||||
|
import { applyEdit } from './core/editOps'
|
||||||
import { newElementId, type IdPrefix } from './ids'
|
import { newElementId, type IdPrefix } from './ids'
|
||||||
import { refusalMessage } from './refusal'
|
import { refusalMessage } from './refusal'
|
||||||
import { useEditorStore } from './state/editorStore'
|
import { useEditorStore } from './state/editorStore'
|
||||||
@@ -21,11 +23,24 @@ export interface EditCommandApi {
|
|||||||
prefix: IdPrefix,
|
prefix: IdPrefix,
|
||||||
build: (id: string) => EditCommand,
|
build: (id: string) => EditCommand,
|
||||||
) => boolean
|
) => 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). */
|
/** A refusal that never reached the core (a required field left blank). */
|
||||||
reject: (field: string, messageKey: string) => false
|
reject: (field: string, messageKey: string) => false
|
||||||
clear: () => void
|
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. */
|
/** The write path of an editor panel: commit once, keep the refusal next to the control. */
|
||||||
export function useEditCommand(): EditCommandApi {
|
export function useEditCommand(): EditCommandApi {
|
||||||
const t = useT()
|
const t = useT()
|
||||||
@@ -34,27 +49,42 @@ export function useEditCommand(): EditCommandApi {
|
|||||||
const attempt = (command: EditCommand) =>
|
const attempt = (command: EditCommand) =>
|
||||||
useEditorStore.getState().commit(command)
|
useEditorStore.getState().commit(command)
|
||||||
|
|
||||||
const run = (field: string, command: EditCommand): boolean => {
|
const run = (field: string, command: EditCommand): boolean =>
|
||||||
const outcome = attempt(command)
|
settle(field, attempt(command))
|
||||||
|
|
||||||
|
const settle = (field: string, outcome: CommitOutcome): boolean => {
|
||||||
setError(outcome.ok ? null : { field, message: refusalMessage(t, outcome) })
|
setError(outcome.ok ? null : { field, message: refusalMessage(t, outcome) })
|
||||||
return outcome.ok
|
return outcome.ok
|
||||||
}
|
}
|
||||||
|
|
||||||
const runNew: EditCommandApi['runNew'] = (field, prefix, build) => {
|
const runNew: EditCommandApi['runNew'] = (field, prefix, build) => {
|
||||||
let outcome = attempt(build(newElementId(prefix)))
|
let outcome = attempt(build(newElementId(prefix)))
|
||||||
const clash =
|
if (isClash(outcome)) outcome = attempt(build(newElementId(prefix)))
|
||||||
!outcome.ok &&
|
return settle(field, outcome)
|
||||||
outcome.reason === 'core' &&
|
}
|
||||||
outcome.failure.kind === 'duplicate_key'
|
|
||||||
if (clash) outcome = attempt(build(newElementId(prefix)))
|
const runBatch: EditCommandApi['runBatch'] = (field, build) => {
|
||||||
setError(outcome.ok ? null : { field, message: refusalMessage(t, outcome) })
|
const store = useEditorStore.getState()
|
||||||
return outcome.ok
|
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 {
|
return {
|
||||||
fieldError: (field) => (error?.field === field ? error.message : undefined),
|
fieldError: (field) => (error?.field === field ? error.message : undefined),
|
||||||
run,
|
run,
|
||||||
runNew,
|
runNew,
|
||||||
|
runBatch,
|
||||||
|
check,
|
||||||
reject: (field, messageKey) => {
|
reject: (field, messageKey) => {
|
||||||
setError({ field, message: t(messageKey) })
|
setError({ field, message: t(messageKey) })
|
||||||
return false
|
return false
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
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 { NavigationState } from './navigation'
|
||||||
import type { LayerContext, MoveTrace } from './useEditorNavigation'
|
import type { LayerContext, MoveTrace } from './useEditorNavigation'
|
||||||
|
|
||||||
@@ -11,8 +11,17 @@ export interface AddedReference {
|
|||||||
|
|
||||||
type Opener = HTMLElement | null | undefined
|
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. */
|
/** What the reference dialog (R2F-5) and the References tab's filter (R2F-6) do to the view. */
|
||||||
export interface ReferenceMoves {
|
export interface ReferenceMoves {
|
||||||
@@ -20,10 +29,12 @@ export interface ReferenceMoves {
|
|||||||
open: (id: string, opener?: Opener) => void
|
open: (id: string, opener?: Opener) => void
|
||||||
/**
|
/**
|
||||||
* The creation dialog, over the References tab or the citations dialog. `cite` is the
|
* 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
|
* citations edit form that started it (Rev 6): the dialog writes nothing and hands the
|
||||||
* library shows no « added » notice for it.
|
* 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). */
|
/** A user close; false when the form refused it (a dirty draft asks first). */
|
||||||
close: (forced?: boolean) => boolean
|
close: (forced?: boolean) => boolean
|
||||||
/**
|
/**
|
||||||
@@ -32,7 +43,10 @@ export interface ReferenceMoves {
|
|||||||
* said once the dialogs are closed.
|
* said once the dialogs are closed.
|
||||||
*/
|
*/
|
||||||
replace: (id: string | null, text?: string) => void
|
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
|
created: (id: string) => void
|
||||||
added: AddedReference | null
|
added: AddedReference | null
|
||||||
/** The element that opened the dialog, while it is still on the page. */
|
/** 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
|
* What the open dialog was started from: its opener, and for a draft creation the citing
|
||||||
* (forgotten once the dialog closes or is replaced).
|
* form and the pending value (both forgotten once the dialog closes or is replaced).
|
||||||
*/
|
*/
|
||||||
interface Held {
|
interface Held {
|
||||||
opener: Opener
|
opener: Opener
|
||||||
cite: CiteCreated | null
|
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. */
|
/** 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(
|
const open = useCallback(
|
||||||
(id: string, opener?: Opener) => {
|
(id: string, opener?: Opener) => {
|
||||||
held.opener = opener
|
held.opener = opener
|
||||||
held.cite = null
|
forget(held)
|
||||||
mark()
|
mark()
|
||||||
dispatch({ type: 'open_reference', id })
|
dispatch({ type: 'open_reference', id })
|
||||||
},
|
},
|
||||||
[dispatch, mark, held],
|
[dispatch, mark, held],
|
||||||
)
|
)
|
||||||
const start = useCallback(
|
const start = useCallback(
|
||||||
(opener?: Opener, cite?: CiteCreated) => {
|
(opener?: Opener, cite?: CiteCreated, initial?: Reference) => {
|
||||||
held.opener = opener
|
held.opener = opener
|
||||||
held.cite = cite ?? null
|
held.cite = cite ?? null
|
||||||
|
held.initial = cite ? (initial ?? null) : null
|
||||||
mark()
|
mark()
|
||||||
dispatch({ type: 'create_reference' })
|
dispatch({ type: 'create_reference' })
|
||||||
},
|
},
|
||||||
@@ -80,7 +102,7 @@ function useClose({ dispatch, guards, mark }: LayerContext, held: Held) {
|
|||||||
return useCallback(
|
return useCallback(
|
||||||
(forced = false) => {
|
(forced = false) => {
|
||||||
if (!guards.ask('reference', forced).allowed) return false
|
if (!guards.ask('reference', forced).allowed) return false
|
||||||
held.cite = null
|
forget(held)
|
||||||
mark()
|
mark()
|
||||||
dispatch({ type: 'close_reference' })
|
dispatch({ type: 'close_reference' })
|
||||||
return true
|
return true
|
||||||
@@ -94,7 +116,7 @@ function useReplace(ctx: LayerContext, held: Held) {
|
|||||||
const { dispatch, announce, guards, mark } = ctx
|
const { dispatch, announce, guards, mark } = ctx
|
||||||
return useCallback(
|
return useCallback(
|
||||||
(id: string | null, text?: string) => {
|
(id: string | null, text?: string) => {
|
||||||
held.cite = null
|
forget(held)
|
||||||
const note = text ? guards.ask('reference', true).note : undefined
|
const note = text ? guards.ask('reference', true).note : undefined
|
||||||
if (text) announce(note ? `${note}. ${text}` : text)
|
if (text) announce(note ? `${note}. ${text}` : text)
|
||||||
mark(true)
|
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
|
* A library creation that succeeded: its entry becomes the reference's own, then it
|
||||||
* citing form that started it takes the id (no notice); else the library says it.
|
* closes, and the library says it. A draft creation never comes here (it writes nothing).
|
||||||
*/
|
*/
|
||||||
function useCreated(
|
function useCreated(ctx: LayerContext, replace: ReferenceMoves['replace']) {
|
||||||
ctx: LayerContext,
|
|
||||||
replace: ReferenceMoves['replace'],
|
|
||||||
held: Held,
|
|
||||||
) {
|
|
||||||
const { dispatch, mark } = ctx
|
const { dispatch, mark } = ctx
|
||||||
const [added, setAdded] = useState<AddedReference | null>(null)
|
const [added, setAdded] = useState<AddedReference | null>(null)
|
||||||
const created = useCallback(
|
const created = useCallback(
|
||||||
(id: string) => {
|
(id: string) => {
|
||||||
const citing = held.cite
|
|
||||||
held.cite = null
|
|
||||||
replace(id)
|
replace(id)
|
||||||
if (citing) citing(id)
|
setAdded((last) => ({ id, serial: (last?.serial ?? 0) + 1 }))
|
||||||
else setAdded((last) => ({ id, serial: (last?.serial ?? 0) + 1 }))
|
|
||||||
// Precondition: the caller is a discrete event (the form's submit). React then
|
// 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
|
// 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
|
// 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' })
|
dispatch({ type: 'close_reference' })
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
[replace, mark, dispatch, held],
|
[replace, mark, dispatch],
|
||||||
)
|
)
|
||||||
return { created, added }
|
return { created, added }
|
||||||
}
|
}
|
||||||
@@ -172,12 +187,17 @@ export function useReferenceMoves(
|
|||||||
trace: MoveTrace,
|
trace: MoveTrace,
|
||||||
view: NavigationState['reference'],
|
view: NavigationState['reference'],
|
||||||
): ReferenceMoves {
|
): 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
|
const creating = view !== null && 'create' in view
|
||||||
// A Back that removes the creation dialog leaves no citing form to answer.
|
// A Back that removes the creation dialog leaves no citing form to answer.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!creating) held.cite = null
|
if (!creating) forget(held)
|
||||||
}, [creating, held])
|
}, [creating, held])
|
||||||
|
const drafting = useCallback(
|
||||||
|
(): Drafting | null =>
|
||||||
|
held.cite ? { initial: held.initial, cite: held.cite } : null,
|
||||||
|
[held],
|
||||||
|
)
|
||||||
const opener = useCallback((): HTMLElement | null => {
|
const opener = useCallback((): HTMLElement | null => {
|
||||||
const element = held.opener
|
const element = held.opener
|
||||||
return element?.isConnected && !element.closest('[hidden]') ? element : null
|
return element?.isConnected && !element.closest('[hidden]') ? element : null
|
||||||
@@ -186,8 +206,9 @@ export function useReferenceMoves(
|
|||||||
return {
|
return {
|
||||||
...useOpening(ctx, held),
|
...useOpening(ctx, held),
|
||||||
...closing,
|
...closing,
|
||||||
...useCreated(ctx, closing.replace, held),
|
...useCreated(ctx, closing.replace),
|
||||||
...useFilter(ctx, trace),
|
...useFilter(ctx, trace),
|
||||||
opener,
|
opener,
|
||||||
|
drafting,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1237,6 +1237,10 @@ export const en: Dict = {
|
|||||||
'editor.citations.new_reference': 'New reference',
|
'editor.citations.new_reference': 'New reference',
|
||||||
'editor.citations.cite': 'Cite',
|
'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.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_one': '{count} reference cited by this finding',
|
||||||
'editor.references.panel_count_other': '{count} references 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',
|
'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.new_reference': 'Nouvelle référence',
|
||||||
'editor.citations.cite': 'Citer',
|
'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.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_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_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',
|
'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. */
|
/** Rev 5 Task 12: the citations draft, held as additions and removals. */
|
||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import type { Reference } from '@faunosteo/core-wasm/types'
|
||||||
import {
|
import {
|
||||||
addId,
|
addId,
|
||||||
applyEdits,
|
applyEdits,
|
||||||
|
citationCommands,
|
||||||
NO_EDITS,
|
NO_EDITS,
|
||||||
|
putCreated,
|
||||||
removeId,
|
removeId,
|
||||||
|
sameEdits,
|
||||||
} from '@/editor/references/citationEdits'
|
} from '@/editor/references/citationEdits'
|
||||||
|
|
||||||
|
const value = (id: string, citation: string): Reference => ({
|
||||||
|
id,
|
||||||
|
type: 'book',
|
||||||
|
citation,
|
||||||
|
doi: null,
|
||||||
|
url: null,
|
||||||
|
})
|
||||||
|
|
||||||
describe('citation edits', () => {
|
describe('citation edits', () => {
|
||||||
it('applies removals and additions to the current list, each id once', () => {
|
it('applies removals and additions to the current list, each id once', () => {
|
||||||
const edits = addId(removeId(NO_EDITS, 'a'), 'b')
|
const edits = addId(removeId(NO_EDITS, 'a'), 'b')
|
||||||
@@ -26,4 +38,40 @@ describe('citation edits', () => {
|
|||||||
const gone = removeId(NO_EDITS, 'a')
|
const gone = removeId(NO_EDITS, 'a')
|
||||||
expect(removeId(gone, 'a')).toBe(gone)
|
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(),
|
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 navigate: NavigateFunction
|
||||||
let location: Location
|
let location: Location
|
||||||
const probe = (n: NavigateFunction, l: Location) => {
|
const probe = (n: NavigateFunction, l: Location) => {
|
||||||
@@ -59,6 +70,7 @@ beforeEach(() => {
|
|||||||
TAG = resolveSessionTag(USER)
|
TAG = resolveSessionTag(USER)
|
||||||
})
|
})
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
|
minted.length = 0
|
||||||
cleanup()
|
cleanup()
|
||||||
resetStore()
|
resetStore()
|
||||||
setWidth(1024)
|
setWidth(1024)
|
||||||
@@ -197,6 +209,24 @@ async function cite(user: User, id: string) {
|
|||||||
await user.click(button('Citer'))
|
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', () => {
|
describe('the « Modifier » of the references dialog', () => {
|
||||||
it('edit mode: no history entry, no « Tout afficher », no « Aller à »', async () => {
|
it('edit mode: no history entry, no « Tout afficher », no « Aller à »', async () => {
|
||||||
const user = await mount()
|
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', () => {
|
describe('leaving the edit mode with changes', () => {
|
||||||
it('an explicit « Abandonner » after ✕ closes the dialog without a word', async () => {
|
it('an explicit « Abandonner » after ✕ closes the dialog without a word', async () => {
|
||||||
const user = await mount()
|
const user = await mount()
|
||||||
@@ -509,7 +536,7 @@ describe('the reference dialog over the edit mode', () => {
|
|||||||
expect(rows()).toEqual(['ref-a'])
|
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()
|
const user = await mount()
|
||||||
await editCitations(user)
|
await editCitations(user)
|
||||||
await user.click(button('Nouvelle référence'))
|
await user.click(button('Nouvelle référence'))
|
||||||
@@ -518,40 +545,163 @@ describe('the reference dialog over the edit mode', () => {
|
|||||||
'aria-selected',
|
'aria-selected',
|
||||||
'true',
|
'true',
|
||||||
)
|
)
|
||||||
await user.selectOptions(inReference().getByLabelText('Type'), 'book')
|
await createPending(user, 'Neuf')
|
||||||
await user.type(inReference().getByLabelText('Citation'), 'Neuf')
|
expect(library()).not.toContain('Neuf')
|
||||||
await user.click(
|
expect(rows()).toHaveLength(3)
|
||||||
inReference().getByRole('button', { name: 'Ajouter la référence' }),
|
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(live()).not.toContain('sera enregistrée')
|
||||||
expect(library()).toContain('Neuf')
|
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(
|
const id = doc().references.find(
|
||||||
(r: { citation: string }) => r.citation === 'Neuf',
|
(r: { citation: string }) => r.citation === 'Neuf',
|
||||||
).id
|
).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(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()
|
const user = await mount()
|
||||||
await editCitations(user)
|
await editCitations(user)
|
||||||
await user.click(button('Nouvelle référence'))
|
await user.click(button('Nouvelle référence'))
|
||||||
await waitFor(() => expect(referenceDialog()).toBeDefined())
|
await waitFor(() => expect(referenceDialog()).toBeDefined())
|
||||||
await user.selectOptions(inReference().getByLabelText('Type'), 'book')
|
await user.selectOptions(inReference().getByLabelText('Type'), 'book')
|
||||||
await user.type(inReference().getByLabelText('Citation'), 'Neuf')
|
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(
|
await user.click(
|
||||||
inReference().getByRole('button', { name: 'Ajouter la référence' }),
|
inReference().getByRole('button', { name: 'Ajouter la référence' }),
|
||||||
)
|
)
|
||||||
await waitFor(() => expect(referenceDialog()).toBeUndefined())
|
expect(inReference().getByRole('alert')).toBeVisible()
|
||||||
await user.click(button('Annuler'))
|
expect(referenceDialog()).toBeDefined()
|
||||||
await user.click(button('Abandonner'))
|
expect(rows()).toEqual(['ref-a', 'ref-c'])
|
||||||
expect(library()).toContain('Neuf')
|
expect(undos()).toBe(0)
|
||||||
expect(nodeA().reference_ids).toEqual(['ref-a', 'ref-c'])
|
})
|
||||||
|
|
||||||
|
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)
|
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', () => {
|
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', () => {
|
describe('a creation started over the citations dialog (Rev 6: a draft creation)', () => {
|
||||||
it('hands its id to the form that started it; no « added » notice', async () => {
|
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()
|
cited()
|
||||||
const cite = vi.fn()
|
const cite = vi.fn()
|
||||||
act(() => nav.references.start(null, cite))
|
act(() => nav.references.start(null, cite, pending))
|
||||||
expect(nav.state).toMatchObject({
|
expect(nav.state).toMatchObject({
|
||||||
tab: 'findings',
|
tab: 'findings',
|
||||||
reference: { create: true },
|
reference: { create: true },
|
||||||
})
|
})
|
||||||
await act(async () => nav.references.created('ref-new'))
|
expect(nav.references.drafting()).toEqual({ initial: pending, cite })
|
||||||
expect(cite).toHaveBeenCalledWith('ref-new')
|
act(() => nav.references.close(true))
|
||||||
expect(nav.references.added).toBeNull()
|
expect(nav.references.drafting()).toBeNull()
|
||||||
expect(nav.state.reference).toBeNull()
|
expect(nav.state.reference).toBeNull()
|
||||||
expect(nav.state.finding).toMatchObject({ citations: true })
|
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()
|
cited()
|
||||||
const cite = vi.fn()
|
const cite = vi.fn()
|
||||||
act(() => nav.references.start(null, cite))
|
act(() => nav.references.start(null, cite))
|
||||||
act(() => nav.references.close(true))
|
expect(nav.references.drafting()).toEqual({ initial: null, cite })
|
||||||
await act(async () => nav.references.created('ref-x'))
|
})
|
||||||
expect(cite).not.toHaveBeenCalled()
|
|
||||||
act(() => nav.references.start(null, cite))
|
it('a creation replaced forgets its citing form', () => {
|
||||||
|
cited()
|
||||||
|
act(() => nav.references.start(null, vi.fn(), pending))
|
||||||
act(() => nav.references.replace(null))
|
act(() => nav.references.replace(null))
|
||||||
await act(async () => nav.references.created('ref-y'))
|
expect(nav.references.drafting()).toBeNull()
|
||||||
expect(cite).not.toHaveBeenCalled()
|
|
||||||
})
|
})
|
||||||
|
|
||||||
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()
|
cited()
|
||||||
const cite = vi.fn()
|
act(() => nav.references.start(null, vi.fn(), pending))
|
||||||
act(() => nav.references.start(null, cite))
|
|
||||||
act(() => navigate(-1))
|
act(() => navigate(-1))
|
||||||
expect(nav.state.reference).toBeNull()
|
expect(nav.state.reference).toBeNull()
|
||||||
await act(async () => nav.references.created('ref-z'))
|
expect(nav.references.drafting()).toBeNull()
|
||||||
expect(cite).not.toHaveBeenCalled()
|
|
||||||
expect(nav.references.added).toMatchObject({ id: 'ref-z' })
|
|
||||||
})
|
})
|
||||||
|
|
||||||
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()
|
cited()
|
||||||
const cite = vi.fn()
|
act(() => nav.references.start(null, vi.fn()))
|
||||||
act(() => nav.references.start(null, cite))
|
|
||||||
act(() => nav.references.close(true))
|
act(() => nav.references.close(true))
|
||||||
act(() => nav.selectTab('references'))
|
act(() => nav.selectTab('references'))
|
||||||
act(() => nav.references.start(null))
|
act(() => nav.references.start(null))
|
||||||
|
expect(nav.references.drafting()).toBeNull()
|
||||||
await act(async () => nav.references.created('ref-lib'))
|
await act(async () => nav.references.created('ref-lib'))
|
||||||
expect(cite).not.toHaveBeenCalled()
|
|
||||||
expect(nav.references.added).toMatchObject({ id: 'ref-lib' })
|
expect(nav.references.added).toMatchObject({ id: 'ref-lib' })
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
Reference in new issue
Block a user