From 3e94f732c76a14d6852bfe1c5ec6d485e6999455 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 15 Nov 2026 20:50:48 +0100 Subject: [PATCH] fix(editor): citation notices, literal citation text, local limits --- .../editor/references/CitationsDialog.tsx | 7 +- .../editor/references/CitationsEditForm.tsx | 41 +++++----- .../editor/references/ReferenceDialog.tsx | 21 ++++-- apps/app/src/editor/useEditCommand.ts | 74 ++++++++++--------- .../tests/unit/editor-citations-edit.test.tsx | 70 +++++++++++++++++- 5 files changed, 152 insertions(+), 61 deletions(-) diff --git a/apps/app/src/components/editor/references/CitationsDialog.tsx b/apps/app/src/components/editor/references/CitationsDialog.tsx index 668016fc..a048f88a 100644 --- a/apps/app/src/components/editor/references/CitationsDialog.tsx +++ b/apps/app/src/components/editor/references/CitationsDialog.tsx @@ -80,7 +80,7 @@ function EditBody({ citedBy, mode, props, onNotice }: BodyProps) { } /** The view mode: the cited references, then « Modifier » (edit tier only). */ -function ViewBody({ citedBy, mode, props }: BodyProps) { +function ViewBody({ citedBy, mode, props }: Omit) { const t = useT() const readOnly = useEditorReadOnly() return ( @@ -117,6 +117,9 @@ function useNotice(editing: boolean) { const waiting = useRef('') const place = useRef(null) if (!editing && notice !== '') setNotice('') + useEffect(() => { + if (!editing) waiting.current = '' + }, [editing]) useEffect(() => { const section = place.current const back = () => { @@ -154,7 +157,7 @@ function Body(body: Omit) { {mode.editing ? ( ) : ( - + )}

{line.notice || (mode.saved ? t('editor.findings.saved') : '')} diff --git a/apps/app/src/components/editor/references/CitationsEditForm.tsx b/apps/app/src/components/editor/references/CitationsEditForm.tsx index ff37dd27..e7568c2d 100644 --- a/apps/app/src/components/editor/references/CitationsEditForm.tsx +++ b/apps/app/src/components/editor/references/CitationsEditForm.tsx @@ -21,7 +21,6 @@ import { useSheetDocument } from '@/editor/sheetDocument' import { useEditCommand } from '@/editor/useEditCommand' import type { Guards } from '@/editor/useEditorNavigation' import type { ReferenceMoves } from '@/editor/useReferenceMoves' -import type { Locale } from '@/i18n/types' import { useT } from '@/i18n/useT' import { useLocaleStore } from '@/state/localeStore' import CitationsDraftList, { @@ -57,7 +56,6 @@ const sameIds = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((id, at) => id === b[at]) type Draft = ReturnType> -type Translate = ReturnType /** The save's batch: the created references' inserts under fresh ids, then the `update`. */ function saveCommands( @@ -76,16 +74,14 @@ function saveCommands( * A refused save with references made in the draft: the line names them, still pending, * as a list of the interface's locale. */ -function savedError( - t: Translate, - locale: Locale, - error: string | undefined, - draft: CitationEdits, -) { +function useSavedError(error: string | undefined, draft: CitationEdits) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) if (!error || draft.created.length === 0) return error const list = new Intl.ListFormat(locale, { type: 'conjunction' }) const citations = list.format(draft.created.map((r) => r.citation)) - return `${error} ${t('editor.citations.pending_kept').replace('{citation}', citations)}` + const kept = t('editor.citations.pending_kept') + return `${error} ${kept.replace('{citation}', () => citations)}` } /** @@ -93,10 +89,9 @@ function savedError( * step), none when nothing changed; refused, the draft stays (an element gone too). */ function useCitationsSave(props: CitationsEditFormProps, form: Draft) { - const t = useT() - const locale = useLocaleStore((s) => s.locale) const { item, ids } = useCurrent(props.citedBy) const edit = useEditCommand() + const error = useSavedError(edit.fieldError('save'), form.draft) const save = () => { if (!item) { const gone = isFamilyKey(props.citedBy) @@ -111,7 +106,7 @@ function useCitationsSave(props: CitationsEditFormProps, form: Draft) { return { shown: applyEdits(ids, form.draft), save, - error: savedError(t, locale, edit.fieldError('save'), form.draft), + error, } } @@ -139,7 +134,10 @@ function useCreation(props: CitationsEditFormProps, form: Draft) { const key = replaced ? 'editor.citations.pending_updated' : 'editor.citations.created_draft' - props.onNotice(t(key).replace('{citation}', value.citation), true) + props.onNotice( + t(key).replace('{citation}', () => value.citation), + true, + ) } return (opener: HTMLElement, initial?: Reference) => props.references.start(opener, cite, initial) @@ -157,12 +155,21 @@ function useRowMoves(props: CitationsEditFormProps, form: Draft) { if (pending) create(opener, pending) else props.references.open(id, opener) }, + add: (id: string) => { + props.onNotice('') + form.set(addId(form.draft, id)) + }, + startNew: (opener: HTMLElement) => { + props.onNotice('') + create(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)) + props.onNotice( + pending ? text.replace('{citation}', () => pending.citation) : '', + ) }, } } @@ -245,10 +252,10 @@ export default function CitationsEditForm(props: CitationsEditFormProps) { pending={form.draft.created} readOnly={props.readOnly} choice={form.choice} - onAdd={(id) => form.set(addId(form.draft, id))} + onAdd={form.rows.add} onRemove={form.rows.remove} onEditReference={form.rows.editReference} - onNew={(opener) => form.rows.create(opener)} + onNew={form.rows.startNew} /> {form.error && (

diff --git a/apps/app/src/components/editor/references/ReferenceDialog.tsx b/apps/app/src/components/editor/references/ReferenceDialog.tsx index 9945fa60..22fc25d3 100644 --- a/apps/app/src/components/editor/references/ReferenceDialog.tsx +++ b/apps/app/src/components/editor/references/ReferenceDialog.tsx @@ -104,11 +104,21 @@ function useOnSaved( return (id: string, citation: string) => { if (!creating || layer.drafting()) return void layer.close(true) handOver(id) - layer.announce(t('editor.references.added').replace('{citation}', citation)) + const added = t('editor.references.added') + layer.announce(added.replace('{citation}', () => citation)) layer.created(id) } } +/** What the form shows: a draft creation's prefill and hand-over, else the edited one. */ +function useFormInput(layer: ReferenceLayer, edited: Reference | null) { + const drafting = layer.drafting() + return { + reference: drafting ? drafting.initial : edited, + onValue: drafting?.cite, + } +} + /** * 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 @@ -125,8 +135,7 @@ 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 + const input = useFormInput(layer, shown.edited) useGoneRule(layer) return (

(layer.close() ? undefined : 'kept')} > layer.close(forced)} /> diff --git a/apps/app/src/editor/useEditCommand.ts b/apps/app/src/editor/useEditCommand.ts index 2f629f98..b2bf0713 100644 --- a/apps/app/src/editor/useEditCommand.ts +++ b/apps/app/src/editor/useEditCommand.ts @@ -41,50 +41,58 @@ const isClash = (outcome: CommitOutcome) => outcome.reason === 'core' && outcome.failure.kind === 'duplicate_key' +type Settle = (field: string, outcome: CommitOutcome) => boolean + +const attempt = (command: EditCommand) => + useEditorStore.getState().commit(command) + +function insertNew( + settle: Settle, + field: string, + prefix: IdPrefix, + build: (id: string) => EditCommand, +): boolean { + let outcome = attempt(build(newElementId(prefix))) + if (isClash(outcome)) outcome = attempt(build(newElementId(prefix))) + return settle(field, outcome) +} + +function commitBatch( + settle: Settle, + field: string, + build: () => readonly EditCommand[], +): boolean { + const store = useEditorStore.getState() + let outcome = store.commitBatch(build()) + if (isClash(outcome)) outcome = store.commitBatch(build()) + return settle(field, outcome) +} + +function dryRun(settle: Settle, field: string, command: EditCommand): boolean { + 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) +} + /** The write path of an editor panel: commit once, keep the refusal next to the control. */ export function useEditCommand(): EditCommandApi { const t = useT() const [error, setError] = useState(null) - const attempt = (command: EditCommand) => - useEditorStore.getState().commit(command) - - const run = (field: string, command: EditCommand): boolean => - settle(field, attempt(command)) - - const settle = (field: string, outcome: CommitOutcome): boolean => { + const settle: Settle = (field, outcome) => { 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))) - 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, + run: (field, command) => settle(field, attempt(command)), + runNew: (field, prefix, build) => insertNew(settle, field, prefix, build), + runBatch: (field, build) => commitBatch(settle, field, build), + check: (field, command) => dryRun(settle, field, command), reject: (field, messageKey) => { setError({ field, message: t(messageKey) }) return false diff --git a/apps/app/tests/unit/editor-citations-edit.test.tsx b/apps/app/tests/unit/editor-citations-edit.test.tsx index 5447b1ec..3e63fd68 100644 --- a/apps/app/tests/unit/editor-citations-edit.test.tsx +++ b/apps/app/tests/unit/editor-citations-edit.test.tsx @@ -583,9 +583,11 @@ describe('the reference dialog over the edit mode', () => { 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(status()).toBe( + 'Nouvelle référence citée dans le brouillon : Neuf. ' + + 'Elle sera enregistrée avec les citations.', + ), ) expect(live()).not.toContain('sera enregistrée') expect(undos()).toBe(0) @@ -775,6 +777,68 @@ describe('the reference dialog over the edit mode', () => { observer.disconnect() expect(seen.filter((text) => text !== '')).toEqual([]) }) + + it('a notice still waiting when the edit mode ends is dropped, not shown later', 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') + // The focus never comes back into the dialog: the notice keeps waiting. + const focus = vi + .spyOn(HTMLElement.prototype, 'focus') + .mockImplementation(() => undefined) + await user.click( + inReference().getByRole('button', { name: 'Ajouter la référence' }), + ) + await waitFor(() => expect(referenceDialog()).toBeUndefined()) + expect(status()).toBe('') + fireEvent.click(button('Enregistrer')) + await waitFor(() => expect(button('Modifier')).toBeVisible()) + focus.mockRestore() + fireEvent.click(button('Modifier')) + await waitFor(() => + expect( + document.activeElement?.closest('form[data-draft-form]'), + ).not.toBeNull(), + ) + expect(status()).not.toContain('Nouvelle référence') + }) + + it('the draft notice goes with the next draft action: cite, remove, new', async () => { + const user = await mount() + await editCitations(user) + await user.click(button('Nouvelle référence')) + await createPending(user, 'Neuf') + await waitFor(() => expect(status()).toContain('Neuf')) + await cite(user, 'ref-b') + expect(status()).toBe('') + await user.click(button('Nouvelle référence')) + await createPending(user, 'Vieux') + await waitFor(() => expect(status()).toContain('Vieux')) + await removeRow(user, /Code rural/) + expect(status()).toBe('') + await user.click(button('Nouvelle référence')) + await waitFor(() => expect(referenceDialog()).toBeDefined()) + expect(status()).toBe('') + }) + + it('a citation holding « $& » reaches every notice as typed', async () => { + const user = await mount() + await editCitations(user) + await user.click(button('Nouvelle référence')) + await createPending(user, 'A$&B') + await waitFor(() => expect(status()).toContain('A$&B')) + expect(status()).not.toContain('{citation}') + minted.push('ref-a', 'ref-c') + await user.click(button('Enregistrer')) + expect(inCitations().getByRole('alert')).toHaveTextContent('A$&B') + expect(inCitations().getByRole('alert')).not.toHaveTextContent('{citation}') + await removeRow(user, /A\$&B/) + expect(status()).toContain('A$&B') + expect(status()).not.toContain('{citation}') + }) }) describe('a save of the edit form when its element is unreadable', () => {