fix(editor): citation notices, literal citation text, local limits

This commit is contained in:
bchanot committed 2026-11-15 20:50:48 +01:00
1 parent c93787c947
commit 3e94f732c7
5 files changed
+138 -47

No files matched your search

@@ -80,7 +80,7 @@ function EditBody({ citedBy, mode, props, onNotice }: BodyProps) {
} }
/** The view mode: the cited references, then « Modifier » (edit tier only). */ /** The view mode: the cited references, then « Modifier » (edit tier only). */
function ViewBody({ citedBy, mode, props }: BodyProps) { function ViewBody({ citedBy, mode, props }: Omit<BodyProps, 'onNotice'>) {
const t = useT() const t = useT()
const readOnly = useEditorReadOnly() const readOnly = useEditorReadOnly()
return ( return (
@@ -117,6 +117,9 @@ function useNotice(editing: boolean) {
const waiting = useRef('') const waiting = useRef('')
const place = useRef<HTMLElement>(null) const place = useRef<HTMLElement>(null)
if (!editing && notice !== '') setNotice('') if (!editing && notice !== '') setNotice('')
useEffect(() => {
if (!editing) waiting.current = ''
}, [editing])
useEffect(() => { useEffect(() => {
const section = place.current const section = place.current
const back = () => { const back = () => {
@@ -154,7 +157,7 @@ function Body(body: Omit<BodyProps, 'onNotice'>) {
{mode.editing ? ( {mode.editing ? (
<EditBody {...body} onNotice={line.say} /> <EditBody {...body} onNotice={line.say} />
) : ( ) : (
<ViewBody {...body} onNotice={line.say} /> <ViewBody {...body} />
)} )}
<p role="status" className="text-sm text-[var(--color-ink-muted)]"> <p role="status" className="text-sm text-[var(--color-ink-muted)]">
{line.notice || (mode.saved ? t('editor.findings.saved') : '')} {line.notice || (mode.saved ? t('editor.findings.saved') : '')}
@@ -21,7 +21,6 @@ import { useSheetDocument } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand' import { useEditCommand } from '@/editor/useEditCommand'
import type { Guards } from '@/editor/useEditorNavigation' import type { Guards } from '@/editor/useEditorNavigation'
import type { ReferenceMoves } from '@/editor/useReferenceMoves' import type { ReferenceMoves } from '@/editor/useReferenceMoves'
import type { Locale } from '@/i18n/types'
import { useT } from '@/i18n/useT' import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore' import { useLocaleStore } from '@/state/localeStore'
import CitationsDraftList, { 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]) 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's batch: the created references' inserts under fresh ids, then the `update`. */ /** The save's batch: the created references' inserts under fresh ids, then the `update`. */
function saveCommands( function saveCommands(
@@ -76,16 +74,14 @@ function saveCommands(
* A refused save with references made in the draft: the line names them, still pending, * A refused save with references made in the draft: the line names them, still pending,
* as a list of the interface's locale. * as a list of the interface's locale.
*/ */
function savedError( function useSavedError(error: string | undefined, draft: CitationEdits) {
t: Translate, const t = useT()
locale: Locale, const locale = useLocaleStore((s) => s.locale)
error: string | undefined,
draft: CitationEdits,
) {
if (!error || draft.created.length === 0) return error if (!error || draft.created.length === 0) return error
const list = new Intl.ListFormat(locale, { type: 'conjunction' }) const list = new Intl.ListFormat(locale, { type: 'conjunction' })
const citations = list.format(draft.created.map((r) => r.citation)) 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). * 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 locale = useLocaleStore((s) => s.locale)
const { item, ids } = useCurrent(props.citedBy) const { item, ids } = useCurrent(props.citedBy)
const edit = useEditCommand() const edit = useEditCommand()
const error = useSavedError(edit.fieldError('save'), form.draft)
const save = () => { const save = () => {
if (!item) { if (!item) {
const gone = isFamilyKey(props.citedBy) const gone = isFamilyKey(props.citedBy)
@@ -111,7 +106,7 @@ function useCitationsSave(props: CitationsEditFormProps, form: Draft) {
return { return {
shown: applyEdits(ids, form.draft), shown: applyEdits(ids, form.draft),
save, save,
error: savedError(t, locale, edit.fieldError('save'), form.draft), error,
} }
} }
@@ -139,7 +134,10 @@ function useCreation(props: CitationsEditFormProps, form: Draft) {
const key = replaced const key = replaced
? 'editor.citations.pending_updated' ? 'editor.citations.pending_updated'
: 'editor.citations.created_draft' : '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) => return (opener: HTMLElement, initial?: Reference) =>
props.references.start(opener, cite, initial) props.references.start(opener, cite, initial)
@@ -157,12 +155,21 @@ function useRowMoves(props: CitationsEditFormProps, form: Draft) {
if (pending) create(opener, pending) if (pending) create(opener, pending)
else props.references.open(id, opener) 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) => { remove: (id: string) => {
const pending = pendingOf(id) const pending = pendingOf(id)
form.set(removeId(form.draft, id)) form.set(removeId(form.draft, id))
if (!pending) return
const text = t('editor.citations.pending_removed') 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} 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={form.rows.add}
onRemove={form.rows.remove} onRemove={form.rows.remove}
onEditReference={form.rows.editReference} onEditReference={form.rows.editReference}
onNew={(opener) => form.rows.create(opener)} onNew={form.rows.startNew}
/> />
{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)]">
@@ -104,11 +104,21 @@ function useOnSaved(
return (id: string, citation: string) => { return (id: string, citation: string) => {
if (!creating || layer.drafting()) 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)) const added = t('editor.references.added')
layer.announce(added.replace('{citation}', () => citation))
layer.created(id) 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 * 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
@@ -125,8 +135,7 @@ 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 input = useFormInput(layer, shown.edited)
const reference = drafting ? drafting.initial : shown.edited
useGoneRule(layer) useGoneRule(layer)
return ( return (
<Dialog <Dialog
@@ -138,12 +147,12 @@ export default function ReferenceDialog({
onClose={() => (layer.close() ? undefined : 'kept')} onClose={() => (layer.close() ? undefined : 'kept')}
> >
<ReferenceForm <ReferenceForm
key={reference?.id ?? 'new'} key={input.reference?.id ?? 'new'}
reference={reference} reference={input.reference}
readOnly={readOnly} readOnly={readOnly}
guards={layer.guards} guards={layer.guards}
onSaved={onSaved} onSaved={onSaved}
onValue={drafting?.cite} onValue={input.onValue}
onClose={(forced) => layer.close(forced)} onClose={(forced) => layer.close(forced)}
/> />
</Dialog> </Dialog>
+30 -22
View File
@@ -41,50 +41,58 @@ const isClash = (outcome: CommitOutcome) =>
outcome.reason === 'core' && outcome.reason === 'core' &&
outcome.failure.kind === 'duplicate_key' outcome.failure.kind === 'duplicate_key'
/** The write path of an editor panel: commit once, keep the refusal next to the control. */ type Settle = (field: string, outcome: CommitOutcome) => boolean
export function useEditCommand(): EditCommandApi {
const t = useT()
const [error, setError] = useState<FieldError | null>(null)
const attempt = (command: EditCommand) => const attempt = (command: EditCommand) =>
useEditorStore.getState().commit(command) useEditorStore.getState().commit(command)
const run = (field: string, command: EditCommand): boolean => function insertNew(
settle(field, attempt(command)) settle: Settle,
field: string,
const settle = (field: string, outcome: CommitOutcome): boolean => { prefix: IdPrefix,
setError(outcome.ok ? null : { field, message: refusalMessage(t, outcome) }) build: (id: string) => EditCommand,
return outcome.ok ): boolean {
}
const runNew: EditCommandApi['runNew'] = (field, prefix, build) => {
let outcome = attempt(build(newElementId(prefix))) let outcome = attempt(build(newElementId(prefix)))
if (isClash(outcome)) outcome = attempt(build(newElementId(prefix))) if (isClash(outcome)) outcome = attempt(build(newElementId(prefix)))
return settle(field, outcome) return settle(field, outcome)
} }
const runBatch: EditCommandApi['runBatch'] = (field, build) => { function commitBatch(
settle: Settle,
field: string,
build: () => readonly EditCommand[],
): boolean {
const store = useEditorStore.getState() const store = useEditorStore.getState()
let outcome = store.commitBatch(build()) let outcome = store.commitBatch(build())
if (isClash(outcome)) outcome = store.commitBatch(build()) if (isClash(outcome)) outcome = store.commitBatch(build())
return settle(field, outcome) return settle(field, outcome)
} }
const check: EditCommandApi['check'] = (field, command) => { function dryRun(settle: Settle, field: string, command: EditCommand): boolean {
const text = useEditorStore.getState().documentText const text = useEditorStore.getState().documentText
const edited = applyEdit(text, command) const edited = applyEdit(text, command)
const outcome: CommitOutcome = edited.ok const outcome: CommitOutcome = edited.ok
? { ok: true } ? { ok: true }
: { ok: false, reason: 'core', failure: edited } : { ok: false, reason: 'core', failure: edited }
return settle(field, outcome) 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<FieldError | null>(null)
const settle: Settle = (field, outcome) => {
setError(outcome.ok ? null : { field, message: refusalMessage(t, outcome) })
return outcome.ok
} }
return { return {
fieldError: (field) => (error?.field === field ? error.message : undefined), fieldError: (field) => (error?.field === field ? error.message : undefined),
run, run: (field, command) => settle(field, attempt(command)),
runNew, runNew: (field, prefix, build) => insertNew(settle, field, prefix, build),
runBatch, runBatch: (field, build) => commitBatch(settle, field, build),
check, check: (field, command) => dryRun(settle, field, command),
reject: (field, messageKey) => { reject: (field, messageKey) => {
setError({ field, message: t(messageKey) }) setError({ field, message: t(messageKey) })
return false return false
@@ -583,9 +583,11 @@ describe('the reference dialog over the edit mode', () => {
const row = pendingRow() const row = pendingRow()
expect(within(row).getByText('Neuf')).toBeVisible() expect(within(row).getByText('Neuf')).toBeVisible()
expect(within(row).getByText('Nouvelle')).toBeVisible() expect(within(row).getByText('Nouvelle')).toBeVisible()
await waitFor(() =>
expect(status()).toBe( expect(status()).toBe(
'Nouvelle référence citée dans le brouillon : Neuf. ' + 'Nouvelle référence citée dans le brouillon : Neuf. ' +
'Elle sera enregistrée avec les citations.', 'Elle sera enregistrée avec les citations.',
),
) )
expect(live()).not.toContain('sera enregistrée') expect(live()).not.toContain('sera enregistrée')
expect(undos()).toBe(0) expect(undos()).toBe(0)
@@ -775,6 +777,68 @@ describe('the reference dialog over the edit mode', () => {
observer.disconnect() observer.disconnect()
expect(seen.filter((text) => text !== '')).toEqual([]) 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', () => { describe('a save of the edit form when its element is unreadable', () => {