fix(editor): never drop a refused draft silently on a read-only flip

Drop slot is tile-local state; the edit view cleanup reports every pending
field (FIELDS order) only when some are pending. The tile shows a warning
note and says it once in the live region; it ends on toggle, Terminer or a
newer drop. LeaveGuard returns all refused fields (forced panel close names
them all). Pin follows editingKey through read-only; reset re-pins it.
Read-only toggle ends edit and collapses. Flip focus goes to the tile header.

R-24 mapping:
- view test "keeps its index ... read-only (M3)": renamed, same assertion
- view test "is suspended in read-only ...": rewritten as "stays pinned in
  read-only" (pin kept, tile still shown after a search); toggle test added
- reset test extended: tile in edit stays pinned through the reset
- new editor-references-flip.test.tsx covers (a)-(g); (h) is a stated limit
This commit is contained in:
bchanot committed 2026-11-13 11:11:51 +01:00
1 parent 52aac41472
commit 3303530717
15 files changed
+543 -94

No files matched your search

@@ -443,6 +443,44 @@ test.describe('reference tiles, search, sort and add', () => {
libraryRoot(page).getByLabel(dict['editor.reference.citation']),
).toBeVisible()
})
test('a refused draft is never dropped silently by a read-only flip', async ({
page,
}) => {
test.setTimeout(150_000)
await open(page)
await openTab(page, dict, 'references')
const bar = toolbar(page)
await headers(page).nth(REF_DOI).click()
const tile = libraryRoot(page)
.locator('button[id$="-ref-doi-header"]')
.locator('xpath=ancestor::li[1]')
await tile
.getByRole('button', { name: dict['editor.references.edit'] })
.click()
await bar.search.fill('libre')
const url = tile.getByLabel(dict['editor.reference.url'])
await url.fill('exemple.org')
const note = dict['editor.references.draft_dropped'].replace(
'{field}',
dict['editor.reference.url'],
)
const size = page.viewportSize() ?? { width: 1280, height: 900 }
await page.setViewportSize({ width: 800, height: size.height })
await expect(tile.getByText(note)).toBeVisible()
await expect(page.locator('p.sr-only[aria-live="polite"]')).toHaveText(note)
await expect(url).toHaveCount(0)
await page.setViewportSize(size)
await expect(tile.getByText(note)).toBeVisible()
await expect(url).toHaveValue(`https://doi.org/${DOI}`)
await tile
.getByRole('button', {
name: dict['editor.references.done'],
exact: true,
})
.click()
await expect(tile.getByText(note)).toHaveCount(0)
})
})
test.describe('reference tiles, read-only at 375 px', () => {
@@ -163,7 +163,7 @@ function EntryTile({
readOnly={readOnly}
movable={false}
on={{
toggle: () => tiles.toggle(key),
toggle: () => tiles.toggle(key, readOnly),
edit: () => void tiles.startEdit(key),
done: tiles.finish,
goTo: (target) => navigate(targetOfKey(target)),
@@ -1,7 +1,8 @@
import { useRef, type RefObject } from 'react'
import { useContext, useEffect, useRef, useState, type RefObject } from 'react'
import type { ElementKey, Reference } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import Icon from '@/components/ui/Icon'
import { AnnounceContext } from '@/editor/focusRequest'
import { usePlural } from '@/editor/plural'
import type { CiterItem } from '@/editor/references/citations'
import { useT } from '@/i18n/useT'
@@ -9,7 +10,7 @@ import CitersList from './CitersList'
import ReferenceEditor from './ReferenceEditor'
import ReferenceFacts from './ReferenceFacts'
import type { ReferenceHost } from './referenceTypes'
import { useDropNote, type Field, type LeaveGuard } from './useReferenceEdit'
import { useDroppedText, type Field, type LeaveGuard } from './useReferenceEdit'
/** What a tile asks of the library that owns its state. */
export interface TileHandlers {
@@ -71,10 +72,12 @@ function TileHeader({
base,
props,
headerRef,
onToggle,
}: {
base: string
props: TileProps
headerRef: RefObject<HTMLButtonElement | null>
onToggle: () => void
}) {
const t = useT()
const plural = usePlural()
@@ -87,9 +90,10 @@ function TileHeader({
type="button"
id={`${base}-header`}
data-focus-key={key}
data-tile-header
aria-expanded={open || editing}
aria-controls={`${base}-body`}
onClick={props.on.toggle}
onClick={onToggle}
className={`grid min-h-11 w-full grid-cols-[1.25rem_1fr] items-start gap-x-3 gap-y-1 rounded-lg p-3 text-left ${META_COLUMN[props.host]} ${BUTTON_RING}`}
>
<Icon
@@ -216,6 +220,40 @@ function TileActions({ props }: { props: TileProps }) {
)
}
/**
* The refused drafts a read-only flip dropped, as the tile keeps them: said once in the
* polite live region, shown by the tile until its next action. An edit view that ends on
* purpose (« Terminer », another tile's « Modifier ») ends the note; a flip does not.
*/
function useDroppedDrafts(editing: boolean, readOnly: boolean) {
const droppedText = useDroppedText()
const announce = useContext(AnnounceContext)
const [dropped, setDropped] = useState<readonly Field[] | null>(null)
const [wasEditing, setWasEditing] = useState(editing)
if (wasEditing !== editing) {
setWasEditing(editing)
if (wasEditing && !readOnly) setDropped(null)
}
const said = useRef<readonly Field[] | null>(null)
useEffect(() => {
if (dropped === null || said.current === dropped) return
said.current = dropped
announce(droppedText(dropped))
})
return [dropped, setDropped] as const
}
/** « Saisie non appliquée : … »: plain text, the live region says it once elsewhere. */
function DroppedNote({ fields }: { fields: readonly Field[] }) {
const droppedText = useDroppedText()
return (
<p className="flex items-start gap-2 rounded-md bg-amber-50 p-2 text-sm text-amber-800">
<Icon name="alert" size={16} className="mt-0.5 shrink-0" />
{droppedText(fields)}
</p>
)
}
/**
* One reference as a collapsible tile (boards 23, 24): closed, open (facts, citers,
* actions), or in edit (fields, citers, « Terminer »). Read-only: the facts and the
@@ -226,14 +264,25 @@ export default function ReferenceTile(props: TileProps) {
const t = useT()
const base = tileBase(host, position, reference)
const headerRef = useRef<HTMLButtonElement>(null)
const dropped = useRef<Field | null>(null)
useDropNote(props.readOnly, dropped)
const [dropped, setDropped] = useDroppedDrafts(editing, props.readOnly)
const done = () => {
if (on.done()) headerRef.current?.focus()
}
const toggle = () => {
setDropped(null)
on.toggle()
}
return (
<li className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)]">
<TileHeader base={base} props={props} headerRef={headerRef} />
<li
data-reference-tile
className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)]"
>
<TileHeader
base={base}
props={props}
headerRef={headerRef}
onToggle={toggle}
/>
{(open || editing) && (
<div
id={`${base}-body`}
@@ -246,7 +295,7 @@ export default function ReferenceTile(props: TileProps) {
hooks={{
registerLeave: on.registerLeave,
takeFocus: on.takeFocus,
dropped,
onDrop: setDropped,
}}
/>
) : (
@@ -257,6 +306,7 @@ export default function ReferenceTile(props: TileProps) {
current={props.panel?.current}
onGoTo={on.goTo}
/>
{dropped && <DroppedNote fields={dropped} />}
{editing ? (
<ActionButton
readOnly={false}
@@ -50,7 +50,7 @@ export default function ReferenceTiles(props: Props) {
readOnly={props.readOnly}
movable={props.movable}
on={{
toggle: () => tiles.toggle(key),
toggle: () => tiles.toggle(key, props.readOnly),
edit: () => props.onEdit(position),
done: tiles.finish,
remove: () => props.onDelete(reference),
@@ -7,7 +7,7 @@ import { citationEntries, findingPath } from '@/editor/references/panel'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import type { CanLeave } from '@/editor/useEditorNavigation'
import { useT } from '@/i18n/useT'
import { useDroppedText } from './useReferenceEdit'
import { tileKeys, useTileState } from './useTileState'
export interface PanelHooks {
@@ -45,18 +45,13 @@ function useLeaveCheck(
tiles: ReturnType<typeof useTileState>,
register: PanelHooks['registerCanLeave'],
) {
const t = useT()
const droppedText = useDroppedText()
useEffect(() => {
register((forced) => {
const refused = tiles.leave()
if (refused === null) return { allowed: true }
if (refused.length === 0) return { allowed: true }
if (!forced) return { allowed: false }
const field = t(`editor.reference.${refused}`)
const note = t('editor.references.draft_dropped').replace(
'{field}',
() => field,
)
return { allowed: true, note }
return { allowed: true, note: droppedText(refused) }
})
return () => register(null)
})
@@ -1,13 +1,5 @@
import {
useContext,
useEffect,
useLayoutEffect,
useRef,
useState,
type RefObject,
} from 'react'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import type { Reference, ReferenceType } from '@faunosteo/core-wasm/types'
import { AnnounceContext } from '@/editor/focusRequest'
import { isBlank, nullable } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import { useT } from '@/i18n/useT'
@@ -18,17 +10,18 @@ export type Field = (typeof FIELDS)[number]
type Drafts = Record<Field, string>
/**
* What the guard calls on a leave: null when every pending field was applied, else the
* field that refused (its draft stays, the field is focused).
* What the guard calls on a leave: every pending field is tried; the fields that refused
* (their drafts stay, the first one is focused), empty when all were applied.
*/
export type LeaveGuard = () => Field | null
export type LeaveGuard = () => Field[]
/** What the tile hands its edit view (the library owns the state). */
export interface EditHooks {
registerLeave: (guard: LeaveGuard | null) => void
/** True once per « Modifier »: the mount focuses Citation, a remount never does. */
takeFocus: () => boolean
dropped: RefObject<Field | null>
/** The view unmounted with these refused drafts; stable (it runs from a cleanup). */
onDrop: (fields: readonly Field[]) => void
}
const committedOf = (reference: Reference): Drafts => ({
@@ -62,12 +55,12 @@ function useDrafts(reference: Reference) {
return [drafts, setDraft] as const
}
/** The first field whose draft differs from `reference`, null when none does. */
const pendingField = (reference: Reference, drafts: Drafts) =>
FIELDS.find(
/** The fields whose draft differs from `reference`, in `FIELDS` order. */
const pendingFields = (reference: Reference, drafts: Drafts) =>
FIELDS.filter(
(field) =>
normalized(field, drafts[field]) !== committedOf(reference)[field],
) ?? null
)
/**
* The reference as the document holds it now, and the drafts as typed. A blur right after
@@ -109,14 +102,14 @@ function useWriter(reference: Reference, drafts: Drafts) {
return { edit, applied, typed, update, apply, pending }
}
/** The view's three effects: its guard, the focus ticket and the dropped-draft slot. */
/** The view's three effects: its guard, the focus ticket and the dropped-draft report. */
function useEditLifecycle(
base: string,
hooks: EditHooks,
leave: LeaveGuard,
writer: Pick<ReturnType<typeof useWriter>, 'applied' | 'typed'>,
) {
const { registerLeave, takeFocus, dropped } = hooks
const { registerLeave, takeFocus, onDrop } = hooks
const { applied, typed } = writer
useEffect(() => {
registerLeave(leave)
@@ -125,21 +118,23 @@ function useEditLifecycle(
useEffect(() => {
if (takeFocus()) document.getElementById(`${base}-citation`)?.focus()
}, [base, takeFocus])
// Never clears a report (a StrictMode remount runs this cleanup with nothing pending).
useLayoutEffect(
() => () => {
dropped.current = pendingField(applied.current, typed.current)
const pending = pendingFields(applied.current, typed.current)
if (pending.length > 0) onDrop(pending)
},
[applied, typed, dropped],
[applied, typed, onDrop],
)
}
/**
* The write path of one reference's edit view. A field applies to the draft when it
* loses the focus (`commitField`); `leave` re-applies every field whose text differs from
* the document, stops at the first refusal, shows it and focuses that field (P22, P22').
* the document, shows each refusal and focuses the first refused field (P22, P22').
* `base` is the DOM id prefix of the tile; `registerLeave` hands `leave` to the library.
* `takeFocus` says whether this mount is a user's « Modifier » (it focuses Citation) and
* `dropped` receives the field of a refused draft the view is unmounted with (M1).
* `onDrop` receives the fields of the refused drafts the view is unmounted with (M1).
*/
export function useReferenceEdit(
reference: Reference,
@@ -150,12 +145,11 @@ export function useReferenceEdit(
const writer = useWriter(reference, drafts)
const { edit, applied, apply, pending } = writer
const leave: LeaveGuard = () => {
for (const field of FIELDS.filter(pending)) {
if (apply(field)) continue
document.getElementById(`${base}-${field}`)?.focus()
return field
const refused = FIELDS.filter(pending).filter((field) => !apply(field))
if (refused.length > 0) {
document.getElementById(`${base}-${refused[0]}`)?.focus()
}
return null
return refused
}
useEditLifecycle(base, hooks, leave, writer)
return {
@@ -168,22 +162,13 @@ export function useReferenceEdit(
}
}
/**
* A read-only flip unmounts the edit view of the tile in edit: a refused draft it held
* (left in `dropped` by the view) is lost, so the live region says which field (M1).
*/
export function useDropNote(
readOnly: boolean,
dropped: RefObject<Field | null>,
) {
/** « Saisie non appliquée : Citation, Adresse web (URL) »: the words for dropped drafts. */
export function useDroppedText(): (fields: readonly Field[]) => string {
const t = useT()
const announce = useContext(AnnounceContext)
useEffect(() => {
if (!readOnly || dropped.current === null) return
const field = t(`editor.reference.${dropped.current}`)
dropped.current = null
announce(
t('editor.references.draft_dropped').replace('{field}', () => field),
return (fields) => {
const names = fields.map((field) => t(`editor.reference.${field}`))
return t('editor.references.draft_dropped').replace('{field}', () =>
names.join(', '),
)
}, [readOnly, dropped, t, announce])
}
}
@@ -14,7 +14,7 @@ import { useReferenceView } from './useReferenceView'
const NO_CITERS = new Map<string, never[]>()
/** The document's references with the tab's tile state and display order. */
export function useReferenceLibrary(readOnly: boolean, resetSignal: number) {
export function useReferenceLibrary(resetSignal: number) {
const doc = useSheetDocument()
const all: readonly Reference[] = doc?.references ?? []
const keys = tileKeys(all)
@@ -23,7 +23,6 @@ export function useReferenceLibrary(readOnly: boolean, resetSignal: number) {
const shown = useReferenceView(
{ all, keys, citers },
tiles.editingKey,
readOnly,
resetSignal,
)
return { loaded: doc !== null, all, keys, tiles, citers, shown }
@@ -30,28 +30,32 @@ interface Shown {
* afficher ») empties the search and the sort once per bump; the tab stays mounted (A2).
* The tile that entered edit is pinned at the index it was shown at, whatever the search
* or the sort, and stays pinned after « Terminer » until the next search or sort change,
* so the tile the user just edited never vanishes under their focus (P23, I1). While
* read-only the pin is suspended and its index kept (M3). `editingKey` is the tile in
* edit, if any.
* so the tile the user just edited never vanishes under their focus (P23, I1). A
* read-only flip keeps the pin: the tile in edit stays shown across it, with its note.
* `editingKey` is the tile in edit, if any.
*/
export function useReferenceView(
{ all, keys, citers }: Shown,
editingKey: string | null,
readOnly: boolean,
resetSignal: number,
) {
const locale = useLocaleStore((state) => state.locale)
const [view, setView] = useState(INITIAL)
const [seen, setSeen] = useState(resetSignal)
const [pinned, setPinned] = useState<Pinned | null>(null)
// The reset view is the sheet order: the tile in edit sits at its own position.
const pinEdited = (): Pinned | null =>
editingKey === null
? null
: { key: editingKey, index: Math.max(0, keys.indexOf(editingKey)) }
if (seen !== resetSignal) {
setSeen(resetSignal)
setView(INITIAL)
setPinned(null)
setPinned(pinEdited())
}
const pinAt = pinned === null ? -1 : keys.indexOf(pinned.key)
const pin =
!readOnly && pinned !== null && pinAt >= 0 && !isSheetView(view)
pinned !== null && pinAt >= 0 && !isSheetView(view)
? { position: pinAt, index: pinned.index }
: null
const context = {
@@ -66,9 +70,7 @@ export function useReferenceView(
// A new search or sort: the tile in edit stays where it is shown, any other pin ends.
const pinAfterChange = (): Pinned | null => {
if (pinned === null || pinned.key !== editingKey) return null
return readOnly
? pinned
: { key: pinned.key, index: pinAtShown(pinned.key) }
return { key: pinned.key, index: pinAtShown(pinned.key) }
}
return {
view,
@@ -80,7 +82,7 @@ export function useReferenceView(
},
reset: () => {
setView(INITIAL)
setPinned(null)
setPinned(pinEdited())
},
/** The tile `key` enters edit: remember where it is shown. */
markEdited: (key: string) => setPinned({ key, index: pinAtShown(key) }),
@@ -35,16 +35,20 @@ export function useTileState(keys: readonly string[] | null) {
// The tile a « Modifier » just opened: its edit view focuses Citation once, a remount
// after a read-only interval does not (M1).
const focusTicket = useRef<string | null>(null)
/** Applies the tile in edit; the field that refused, null when nothing is left to apply. */
const leave = (): Field | null => guard.current?.() ?? null
/** Applies the tile in edit; the fields that refused, none when nothing is left to apply. */
const leave = (): Field[] => guard.current?.() ?? []
const open = (key: string) => setOpenKeys((prev) => new Set(prev).add(key))
const finish = () => {
if (leave() !== null) return false
if (leave().length > 0) return false
setEditingKey(null)
return true
}
const toggle = (key: string) => {
if (editingKey === key) return void finish()
// Read-only, the edit view is gone: a toggle ends the edit state and collapses.
const toggle = (key: string, readOnly = false) => {
if (editingKey === key) {
if (!readOnly) return void finish()
setEditingKey(null)
}
setOpenKeys((prev) => {
const next = new Set(prev)
if (!next.delete(key)) next.add(key)
@@ -52,7 +56,7 @@ export function useTileState(keys: readonly string[] | null) {
})
}
const startEdit = (key: string) => {
if (editingKey !== null && editingKey !== key && leave() !== null)
if (editingKey !== null && editingKey !== key && leave().length > 0)
return false
focusTicket.current = key
setEditingKey(key)
@@ -36,7 +36,7 @@ type Props = Pick<EditorPlaceProps, 'readOnly' | 'navigate' | 'focus'> & {
*/
function Library({ readOnly, navigate, focus, resetSignal }: Props) {
const t = useT()
const lib = useReferenceLibrary(readOnly, resetSignal)
const lib = useReferenceLibrary(resetSignal)
const searchRef = useRef<HTMLInputElement>(null)
const act = useReferenceActions(lib, focus, searchRef)
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
+17 -4
View File
@@ -162,16 +162,29 @@ export function heldElement(): HTMLElement | null {
: null
}
/** The disclosure button of the reference tile that holds `element`, if any. */
export function tileHeaderOf(element: HTMLElement | null): HTMLElement | null {
const tile = element?.closest('[data-reference-tile]')
return tile?.querySelector<HTMLElement>('[data-tile-header]') ?? null
}
/**
* After the render that hides parts: `held` (taken before) that left the page or sits in a
* hidden part hands its focus to the shown tab; one still shown gets its focus back when
* the commit blurred it (never `body`), and the tab takes it if the element refuses.
* hidden part hands its focus to `home` (the header of the tile it was in) when that is
* still shown, else to the shown tab; one still shown gets its focus back when the commit
* blurred it (never `body`), and the tab takes it if the element refuses.
*/
export function refocusIfHidden(held: HTMLElement | null): void {
export function refocusIfHidden(
held: HTMLElement | null,
home: HTMLElement | null = null,
): void {
if (!held) return
const gone = !held.isConnected || held.closest('[hidden]')
if (!gone && document.activeElement !== held) held.focus()
if (gone || document.activeElement !== held) focusActiveTab()
if (!gone && document.activeElement === held) return
const homeShown = home?.isConnected && !home.closest('[hidden]')
if (homeShown) home.focus()
if (!homeShown || document.activeElement !== home) focusActiveTab()
}
/**
+10 -2
View File
@@ -1,5 +1,10 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { commitFocusedField, heldElement, refocusIfHidden } from './focusRequest'
import {
commitFocusedField,
heldElement,
refocusIfHidden,
tileHeaderOf,
} from './focusRequest'
import { MIN_EDIT_WIDTH } from './mode'
/** The tab lists of board 05: all, the five of 640 px and over, the two below. */
@@ -22,6 +27,7 @@ export function useTabTier(): TabTier {
const [tier, setTier] = useState<TabTier>(() => tierOf(window.innerWidth))
const previous = useRef(tier)
const held = useRef<HTMLElement | null>(null)
const home = useRef<HTMLElement | null>(null)
useEffect(() => {
const update = () => {
const next = tierOf(window.innerWidth)
@@ -29,6 +35,7 @@ export function useTabTier(): TabTier {
// after the hide would be too late, a hidden field keeps no focus event.
if (crossesEditWidth(previous.current, next)) {
held.current = heldElement()
home.current = tileHeaderOf(held.current)
commitFocusedField()
}
previous.current = next
@@ -40,8 +47,9 @@ export function useTabTier(): TabTier {
}, [])
// The new tier is rendered: a focus left in a hidden part goes to the shown tab.
useLayoutEffect(() => {
refocusIfHidden(held.current)
refocusIfHidden(held.current, home.current)
held.current = null
home.current = null
}, [tier])
return tier
}
+6 -2
View File
@@ -1,3 +1,4 @@
import { StrictMode } from 'react'
import { render } from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import {
@@ -89,6 +90,8 @@ export interface MountOptions {
answer?: Record<string, unknown>
/** The admin read is refused with this closed kind. */
adminFailure?: SheetFailureKind
/** Renders inside <StrictMode>: effects run twice on mount, as in development. */
strict?: boolean
}
/** Mounts the draft route as an editor with the admin role, at a wide screen, by default. */
@@ -111,7 +114,7 @@ export function mountDraft(options: MountOptions = {}) {
(options.answer ?? adminAnswer()) as never,
)
}
return render(
const page = (
<MemoryRouter initialEntries={[`/app/admin/sheets/${SHEET}/draft`]}>
<Routes>
<Route
@@ -123,6 +126,7 @@ export function mountDraft(options: MountOptions = {}) {
element={<p>overview page</p>}
/>
</Routes>
</MemoryRouter>,
</MemoryRouter>
)
return render(options.strict ? <StrictMode>{page}</StrictMode> : page)
}
@@ -0,0 +1,331 @@
/** C1: a read-only flip never drops a draft silently, writes nothing, and keeps the tile. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
import {
baseText,
resetStore,
serverHas,
store,
} from '../helpers/editorHarness'
import { mountDraft, setWidth } from '../helpers/editorRoute'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
getSheetVersion: vi.fn(),
downloadSheetDrawing: vi.fn(),
saveSheetDraft: vi.fn(),
getOfficialSheetAdmin: vi.fn(),
submitSheetReview: vi.fn(),
}))
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
setWidth(1024)
})
const name = (n: string) => ({ fr: n, en: n })
const ref = (id: string, citation: string, url = '') =>
({
kind: 'reference',
value: { id, type: 'book', citation, url: url || null, doi: null },
}) as const
/** Three references (ref-b has a URL) and Node A citing ref-a and ref-b. */
function sheetText(): string {
let text = baseText()
text = insert(text, ref('ref-a', 'Barone, Ostéologie'))
text = insert(text, ref('ref-b', 'Denoix', 'https://exemple.org/Épaule'))
text = insert(text, ref('ref-c', 'Code rural'))
text = insert(text, {
kind: 'zone',
value: { id: 'zone-a', name: name('Zone A'), categories: [] },
})
text = edit(text, {
op: 'insert',
parent: { kind: 'zone', id: 'zone-a' },
element: {
kind: 'finding_category',
value: {
id: 'fcat-a',
kind: 'dysfunction',
name: name('Cat A'),
description: {},
reference_ids: [],
review_status: 'to_confirm',
children: [],
},
},
})
return edit(text, {
op: 'insert',
parent: { kind: 'finding', zone_id: 'zone-a', path: ['fcat-a'] },
element: {
kind: 'finding_node',
value: {
id: 'fnode-a',
name: name('Node A'),
description: {},
requires_vet_referral: false,
reference_ids: ['ref-a', 'ref-b'],
review_status: 'to_confirm',
children: [],
},
},
})
}
type User = ReturnType<typeof userEvent.setup>
const NOTE = 'Saisie non appliquée'
const live = () => document.querySelector('p.sr-only[aria-live="polite"]')!
const doc = () => JSON.parse(store.getState().documentText)
const history = () => ({
undo: store.getState().undo.length,
redo: store.getState().redo.length,
})
const cross = (width: number) =>
act(() => {
setWidth(width)
window.dispatchEvent(new Event('resize'))
})
const flush = () => act(async () => undefined)
/** Counts the live region's updates that carry the drop note. */
function watchNotes() {
const seen: string[] = []
const observer = new MutationObserver(() => {
if (live().textContent?.includes(NOTE)) seen.push(live().textContent!)
})
observer.observe(live(), {
childList: true,
characterData: true,
subtree: true,
})
return { seen, stop: () => observer.disconnect() }
}
async function mount(width = 1280) {
serverHas(sheetText(), 3)
const user = userEvent.setup()
mountDraft({ width, strict: true })
await screen.findByRole('heading', { level: 1, name: 'Brouillon, version 4' })
return user
}
const tabPanel = () => screen.getByRole('tabpanel', { name: 'Références' })
const header = (id: string, host = 'tab') =>
document.querySelector<HTMLElement>(
`button[id^="${host}-reference-"][id$="-${id}-header"]`,
)!
const tile = (id: string, host = 'tab') => header(id, host).closest('li')!
const field = (id: string, name: string, host = 'tab') =>
document.querySelector<HTMLInputElement>(
`#${host}-reference-${id === 'ref-a' ? 0 : id === 'ref-b' ? 1 : 2}-${id}-${name}`,
)!
/** « Références », the tile open and in edit; the focus on its Citation field. */
async function editTile(user: User, id: string, label: RegExp) {
await user.click(screen.getByRole('tab', { name: 'Références' }))
await user.click(within(tabPanel()).getByRole('button', { name: label }))
await user.click(within(tile(id)).getByRole('button', { name: 'Modifier' }))
}
/** Types a schemeless URL (refused) in the focused-then-kept URL field of `id`. */
async function typeBadUrl(user: User, id: string) {
const url = field(id, 'url')
await user.clear(url)
await user.type(url, 'exemple.org')
return url
}
describe('a read-only flip with a refused draft (tab tile)', () => {
it('shows the note in the tile, says it once, writes nothing, keeps the focus on the tile', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await typeBadUrl(user, 'ref-b')
const before = { references: doc().references, ...history() }
const watch = watchNotes()
cross(800)
expect(
within(tile('ref-b')).getByText(`${NOTE} : Adresse web (URL)`),
).toBeVisible()
expect(within(tile('ref-b')).queryByRole('textbox')).toBeNull()
expect(
within(tile('ref-b')).getByText('https://exemple.org/Épaule'),
).toBeVisible()
await flush()
expect(watch.seen).toHaveLength(1)
expect(live().textContent).toBe(`${NOTE} : Adresse web (URL)`)
expect({ references: doc().references, ...history() }).toEqual(before)
expect(document.activeElement).toBe(header('ref-b'))
watch.stop()
})
it('keeps the note across the flip back, URL field on the document value; Terminer removes it', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await typeBadUrl(user, 'ref-b')
cross(800)
cross(1280)
const item = tile('ref-b')
expect(within(item).getByText(`${NOTE} : Adresse web (URL)`)).toBeVisible()
expect(field('ref-b', 'url')).toHaveValue('https://exemple.org/Épaule')
expect(history()).toEqual({ undo: 0, redo: 0 })
await user.click(within(item).getByRole('button', { name: 'Terminer' }))
expect(within(item).queryByText(new RegExp(NOTE))).toBeNull()
})
it('the read-only toggle ends the edit state, collapses and clears the note', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await typeBadUrl(user, 'ref-b')
cross(800)
await user.click(header('ref-b'))
expect(header('ref-b')).toHaveAttribute('aria-expanded', 'false')
expect(within(tile('ref-b')).queryByText(new RegExp(NOTE))).toBeNull()
cross(1280)
expect(header('ref-b')).toHaveAttribute('aria-expanded', 'false')
expect(within(tile('ref-b')).queryByRole('textbox')).toBeNull()
})
it('names both refused fields, in field order', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await user.clear(field('ref-b', 'citation'))
await typeBadUrl(user, 'ref-b')
cross(800)
expect(
within(tile('ref-b')).getByText(`${NOTE} : Citation, Adresse web (URL)`),
).toBeVisible()
expect(doc().references[1].citation).toBe('Denoix')
})
it('keeps the tile in edit shown when the search does not match it', async () => {
const user = await mount()
await editTile(user, 'ref-b', /^Denoix/)
await user.type(
within(tabPanel()).getByRole('searchbox', {
name: 'Rechercher une référence',
}),
'rural',
)
expect(header('ref-b')).not.toBeNull()
await typeBadUrl(user, 'ref-b')
cross(800)
expect(
within(tile('ref-b')).getByText(`${NOTE} : Adresse web (URL)`),
).toBeVisible()
expect(header('ref-c')).not.toBeNull()
})
})
describe('a read-only flip without a refused draft', () => {
it('adds exactly the typed change when a valid draft has the focus, nothing on the way back', async () => {
const user = await mount()
await editTile(user, 'ref-a', /^Barone/)
const citation = field('ref-a', 'citation')
await user.clear(citation)
await user.type(citation, 'Neuf')
const watch = watchNotes()
cross(800)
expect(history()).toEqual({ undo: 1, redo: 0 })
expect(doc().references[0].citation).toBe('Neuf')
expect(within(tile('ref-a')).queryByText(new RegExp(NOTE))).toBeNull()
expect(document.activeElement).toBe(header('ref-a'))
cross(1280)
await flush()
expect(history()).toEqual({ undo: 1, redo: 0 })
expect(watch.seen).toHaveLength(0)
watch.stop()
})
it('writes nothing, says nothing and shows no note when nothing is pending', async () => {
const user = await mount()
await editTile(user, 'ref-a', /^Barone/)
const watch = watchNotes()
cross(800)
cross(1280)
await flush()
expect(history()).toEqual({ undo: 0, redo: 0 })
expect(watch.seen).toHaveLength(0)
expect(screen.queryByText(new RegExp(NOTE))).toBeNull()
watch.stop()
})
})
describe('a read-only flip in the citations panel', () => {
async function openPanel(user: User) {
await user.click(screen.getByRole('tab', { name: 'Constats' }))
await user.click(screen.getByRole('treeitem', { name: /Cat A/ }))
await user.keyboard('{ArrowRight}')
await user.click(screen.getByRole('treeitem', { name: /Node A/ }))
await user.click(
within(screen.getByRole('tabpanel', { name: 'Constats' })).getByRole(
'button',
{ name: '2 références' },
),
)
await waitFor(() =>
expect(document.activeElement).toBe(
screen.getByRole('heading', { name: 'Références citées' }),
),
)
const panel = screen.getByTestId('editor-citations-panel')
await user.click(within(panel).getByRole('button', { name: /^Denoix/ }))
await user.click(within(panel).getByRole('button', { name: 'Modifier' }))
return panel
}
it('shows the note in the panel tile, says it once, focuses the tile header', async () => {
const user = await mount()
await openPanel(user)
await typeBadUrlIn(user)
const watch = watchNotes()
cross(800)
const item = tile('ref-b', 'panel')
expect(within(item).getByText(`${NOTE} : Adresse web (URL)`)).toBeVisible()
await flush()
expect(watch.seen).toHaveLength(1)
expect(document.activeElement).toBe(header('ref-b', 'panel'))
expect(history()).toEqual({ undo: 0, redo: 0 })
watch.stop()
})
it('a forced close names every refused field and says it once', async () => {
const user = await mount()
await openPanel(user)
await user.clear(field('ref-b', 'citation', 'panel'))
await typeBadUrlIn(user)
const watch = watchNotes()
act(() => {
store.getState().commit({
op: 'remove',
key: {
kind: 'finding',
zone_id: 'zone-a',
path: ['fcat-a', 'fnode-a'],
},
})
})
await waitFor(() =>
expect(screen.queryByTestId('editor-citations-panel')).toBeNull(),
)
expect(watch.seen).toHaveLength(1)
expect(live().textContent).toContain(
`${NOTE} : Citation, Adresse web (URL)`,
)
watch.stop()
})
})
async function typeBadUrlIn(user: User) {
const url = field('ref-b', 'url', 'panel')
await user.clear(url)
await user.type(url, 'exemple.org')
}
@@ -356,7 +356,7 @@ describe('the tile in edit is pinned (P23)', () => {
expect(document.activeElement).toBe(header('r1'))
})
it('keeps its index across a search or sort change made while read-only (M3)', async () => {
it('keeps the tile in edit at its index across a sort change made while read-only (M3)', async () => {
const { user, view } = await mount()
await user.selectOptions(sortBox(), 'citation')
await startEdit(user, 'r3')
@@ -367,15 +367,32 @@ describe('the tile in edit is pinned (P23)', () => {
expect(order()).toEqual(['r2', 'r3', 'r1', 'r5', 'r4'])
})
it('is suspended in read-only: the tile renders its read view', async () => {
it('stays pinned in read-only: the read view of the tile, still shown after a search', async () => {
const { user, view } = await mount()
await startEdit(user, 'r1')
await user.selectOptions(sortBox(), 'citation')
view.rerender(lib(true))
expect(screen.queryByLabelText('Citation')).toBeNull()
expect(order()).toEqual(['r5', 'r3', 'r4', 'r2', 'r1'])
expect(order()).toEqual(['r1', 'r5', 'r3', 'r4', 'r2'])
await user.type(search(), 'alpha')
expect(order()).toEqual(['r5'])
expect(order()).toEqual(['r1', 'r5'])
view.rerender(lib(false))
expect(order()).toEqual(['r1', 'r5'])
expect(
within(header('r1').closest('li')!).getByLabelText('Citation'),
).toBeVisible()
})
it('a read-only toggle ends the edit state and collapses the tile', async () => {
const { user, view } = await mount()
await startEdit(user, 'r1')
view.rerender(lib(true))
expect(header('r1')).toHaveAttribute('aria-expanded', 'true')
await user.click(header('r1'))
expect(header('r1')).toHaveAttribute('aria-expanded', 'false')
view.rerender(lib(false))
expect(header('r1')).toHaveAttribute('aria-expanded', 'false')
expect(screen.queryByLabelText('Citation')).toBeNull()
})
})
@@ -494,6 +511,9 @@ describe('the reset path (« Tout afficher »)', () => {
expect(order()).toHaveLength(5)
expect(header('r2')).toHaveAttribute('aria-expanded', 'true')
expect(within(item).getByLabelText('Citation')).toBeInTheDocument()
// The tile in edit stays pinned through the reset: a new search does not hide it.
await user.type(search(), 'alpha')
expect(order()).toEqual(['r1', 'r5'])
})
})