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
+152 -61

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). */
function ViewBody({ citedBy, mode, props }: BodyProps) {
function ViewBody({ citedBy, mode, props }: Omit<BodyProps, 'onNotice'>) {
const t = useT()
const readOnly = useEditorReadOnly()
return (
@@ -117,6 +117,9 @@ function useNotice(editing: boolean) {
const waiting = useRef('')
const place = useRef<HTMLElement>(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<BodyProps, 'onNotice'>) {
{mode.editing ? (
<EditBody {...body} onNotice={line.say} />
) : (
<ViewBody {...body} onNotice={line.say} />
<ViewBody {...body} />
)}
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{line.notice || (mode.saved ? t('editor.findings.saved') : '')}
@@ -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<typeof useFormDraft<CitationEdits>>
type Translate = ReturnType<typeof useT>
/** 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 && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
@@ -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 (
<Dialog
@@ -138,12 +147,12 @@ export default function ReferenceDialog({
onClose={() => (layer.close() ? undefined : 'kept')}
>
<ReferenceForm
key={reference?.id ?? 'new'}
reference={reference}
key={input.reference?.id ?? 'new'}
reference={input.reference}
readOnly={readOnly}
guards={layer.guards}
onSaved={onSaved}
onValue={drafting?.cite}
onValue={input.onValue}
onClose={(forced) => layer.close(forced)}
/>
</Dialog>
+41 -33
View File
@@ -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<FieldError | null>(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
@@ -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', () => {