fix(editor): ask only the layers a Back removes, clear the sheet first

This commit is contained in:
bchanot committed 2026-11-14 18:47:24 +01:00
1 parent 526aecb40e
commit 2ad720b34e
5 files changed
+193 -30

No files matched your search

+54 -14
View File
@@ -10,12 +10,14 @@ import {
landAfterModalsClosed,
} from '@/components/ui/afterModalsClosed'
import { focusActiveTab } from '../focusRequest'
import { LAYERS_TOP_DOWN } from '../leftDraft'
import { sameView, type EditorView } from '../navigation'
import {
headingOf,
shownPlace,
useMoveText,
type EditorNavigation,
type LayerName,
type MoveTrace,
} from '../useEditorNavigation'
import {
@@ -209,19 +211,52 @@ function sameLayers(a: EditorView, b: EditorView): boolean {
)
}
/** The finding dialog a view shows, without its sheet: the sheet is no form. */
function dialogOf({ finding }: EditorView): unknown {
return finding && 'key' in finding ? { key: finding.key } : finding
}
/**
* A POP the page must not follow: a modal that is no layer is open (its place-scoped
* state is not in the history), or a dirty layer would be removed. Either way the layers
* are asked, so a dirty form shows its own confirmation.
* The layers holding a form that a POP from `from` to `to` takes away, top down: the
* citations sheet alone is no such layer, so a Back that only closes it asks nothing.
*/
function popRefused(ctx: PopContext, entry: HistoryEntry | null): boolean {
const { nav, view, defaultView } = ctx
function leavingLayers(from: EditorView, to: EditorView): LayerName[] {
const same = (a: unknown, b: unknown) =>
JSON.stringify(a) === JSON.stringify(b)
const reference = from.reference && !same(from.reference, to.reference)
const finding = from.finding && !same(dialogOf(from), dialogOf(to))
return LAYERS_TOP_DOWN.filter((l) =>
l === 'reference' ? reference : finding,
)
}
/**
* Whether a POP must not be followed, and which layer refused it: a modal that is no
* layer is open (its place-scoped state is not in the history, every layer is asked), or
* a dirty layer would be removed. Only the layers the POP removes are asked, top down, so
* a dirty form shows its own confirmation and a layer the POP keeps is never asked.
*/
function refusal(
ctx: PopContext,
entry: HistoryEntry | null,
): LayerName | 'modal' | null {
const { nav, view } = ctx
if (document.querySelector('dialog[open]:not([data-layer])')) {
nav.guards.askAll(false)
return true
return 'modal'
}
if (sameLayers(entry?.view ?? defaultView, view)) return false
return !nav.guards.askAll(false).allowed
const leaving = leavingLayers(view, entry?.view ?? ctx.defaultView)
const answers = leaving.map((layer) => nav.guards.ask(layer, false).allowed)
const index = answers.indexOf(false)
return index < 0 ? null : leaving[index]
}
/** The view under the finding dialog's sheet: what lies over it is clean, it goes. */
function bareFinding(view: EditorView): EditorView {
const { finding } = view
const shown =
finding && 'key' in finding ? { ...finding, citations: false } : finding
return { ...view, finding: shown, reference: null }
}
interface PopContext {
@@ -244,14 +279,19 @@ function landOnForeign(ctx: PopContext): Landing | null {
}
/**
* Something the history does not carry is on screen: the view stays, the pre-POP view is
* pushed again above the entry landed on.
* A POP refused (see `refusal`): the view stays, pushed again above the entry landed on.
* When the finding dialog refused, the clean sheet and reference dialog over it close
* first, so its question is not hidden under them. True when refused.
*/
function refusePop(ctx: PopContext, landed: HistoryEntry | null): null {
function refusePop(ctx: PopContext, landed: HistoryEntry | null): boolean {
const refused = refusal(ctx, landed)
if (!refused) return false
const { book, writer, view } = ctx
if (landed) adopt(book, landed)
writer.push(view)
return null
const kept = refused === 'finding' ? bareFinding(view) : view
if (!sameView(kept, view)) ctx.nav.restoreView(kept)
writer.push(kept)
return true
}
/** A `back()` this adapter asked for is expected: reads and clears the flag. */
@@ -269,7 +309,7 @@ function landOn(ctx: PopContext, state: unknown): Landing | null {
if (book.entry) book.scrolls.set(book.entry.id, window.scrollY)
const expected = takePendingBack(book)
const entry = ownedEntry(state, ctx.owner)
if (!expected && popRefused(ctx, entry)) return refusePop(ctx, entry)
if (!expected && refusePop(ctx, entry)) return null
if (!entry) return landOnForeign(ctx)
adopt(book, entry)
if (sameView(entry.view, view)) return null
+31 -12
View File
@@ -40,8 +40,11 @@ function leavesEditor(event: NavigateEventLike, path: string): boolean {
interface Watch {
guards: Guards
/** Closes the citations sheet, which may lie between two asking dialogs. */
closeSheet: () => void
/**
* Closes the citations sheet and a reference dialog over it: they lie over the finding
* dialog, so its question would be hidden under them.
*/
clearAbove: () => void
path: string
/** The key of the jump the user confirmed: it passes, and leaves no flag. */
passing: { current: string | null }
@@ -72,10 +75,12 @@ function jumpTo({ api, key, watch }: Jump, keep: () => void): void {
* `layer` asks « Abandonner les modifications ? » and holds the jump. Its « Abandonner »
* closes it, with the citations sheet it may have been opened from (so the next question
* is not hidden under the sheet), and the next dirty layer under it asks in turn; the
* last one lets the jump go. Any « Continuer la saisie » drops the jump.
* last one lets the jump go. Any « Continuer la saisie » drops the jump. The finding
* dialog asks once the layers over it are closed (they are clean: it is the top dirty one).
*/
function askLeave(jump: Jump, layer: LayerName): void {
const { guards, closeSheet } = jump.watch
const { guards, clearAbove } = jump.watch
if (layer === 'finding') clearAbove()
guards.ask(layer, false)
guards.holdLeave({
layer,
@@ -84,7 +89,6 @@ function askLeave(jump: Jump, layer: LayerName): void {
if (!next) return jumpTo(jump, exit.keep)
// One commit closes both: the history writes one replace, never a Back racing it.
exit.close()
closeSheet()
askLeave(jump, next)
},
})
@@ -104,6 +108,21 @@ function onNavigate(api: NavigationLike, event: NavigateEventLike, w: Watch) {
askLeave({ api, key, watch: w }, layer)
}
type LeaveNav = Pick<
EditorNavigation,
'guards' | 'state' | 'closeCitations' | 'references'
>
/** Closes the sheet and the reference dialog of the navigation `latest` holds, if open. */
function clearerOf(latest: { current: LeaveNav }): () => void {
return () => {
const { state, closeCitations, references } = latest.current
const { finding } = state
if (finding && 'key' in finding && finding.citations) closeCitations()
if (state.reference) references.close(true)
}
}
/**
* Confirmation before a history jump of several entries leaves the editor with a dirty
* dialog (criterion 23): where the Navigation API can cancel it, the jump waits for each
@@ -111,22 +130,22 @@ function onNavigate(api: NavigationLike, event: NavigateEventLike, w: Watch) {
* cancel) the left-draft notice says it afterwards. Traversals inside the editor keep the
* history adapter's refusal path. Returns whether the user confirmed a leave.
*/
export default function useLeaveConfirm(
nav: Pick<EditorNavigation, 'guards' | 'closeCitations'>,
): () => boolean {
export default function useLeaveConfirm(nav: LeaveNav): () => boolean {
const { pathname } = useLocation()
const passing = useRef<string | null>(null)
const path = useRef(pathname).current
const { guards, closeCitations } = nav
const latest = useRef(nav)
latest.current = nav
const { guards } = nav
useEffect(() => {
const api = navigationApi()
if (!api) return
const closeSheet = () => void closeCitations()
const watch: Watch = { guards, closeSheet, path, passing }
const clearAbove = clearerOf(latest)
const watch: Watch = { guards, clearAbove, path, passing }
const listener = (event: Event) =>
onNavigate(api, event as NavigateEventLike, watch)
api.addEventListener('navigate', listener)
return () => api.removeEventListener('navigate', listener)
}, [guards, closeCitations, path])
}, [guards, path])
return useCallback(() => passing.current !== null, [])
}
+1 -1
View File
@@ -15,7 +15,7 @@ export const leftDraftKey = ({ sheetId, tag }: HistoryOwner) =>
`${PREFIX}${sheetId}:${tag}`
/** The top layer first: the dialog the user was typing in when they left. */
const LAYERS_TOP_DOWN: readonly LayerName[] = ['reference', 'finding']
export const LAYERS_TOP_DOWN: readonly LayerName[] = ['reference', 'finding']
/**
* The top layer whose form holds changes, or the first one under `below`; a forced ask
@@ -979,3 +979,94 @@ describe('citing references lives in the edit form (owner item 1)', () => {
).toBeVisible()
})
})
describe('the citations sheet over a dirty edit form (final review rev 4, item 1)', () => {
const question = 'Abandonner les modifications ?'
const dialogs = () => [...document.querySelectorAll('dialog[open]')]
const refForm = () =>
dialogs().find((d) => d.querySelector('#reference-form-citation'))
let api: NavigationStub
beforeEach(() => {
api = new NavigationStub()
Object.defineProperty(window, 'navigation', {
value: api,
configurable: true,
})
})
afterEach(() => {
Reflect.deleteProperty(window, 'navigation')
})
/** Node A in edit with Beta cited in the draft, its sheet open over the form. */
async function sheetOverDirtyForm() {
const user = await mount(1280, citingText())
await openFinding(user, /Node A/)
await modify(user)
await cite(user, 'Beta')
await user.click(inDialog().getByRole('button', { name: '2 références' }))
await waitFor(() => expect(panelOpen()).not.toBeNull())
await waitFor(() =>
expect(written()?.view.finding).toMatchObject({ citations: true }),
)
return user
}
const draftKept = () =>
expect(
inDialog().getByRole('button', { name: '2 références' }),
).toBeVisible()
it('a Back closes the clean sheet and asks nothing', async () => {
await sheetOverDirtyForm()
await back()
await waitFor(() => expect(panelOpen()).toBeNull())
expect(screen.queryByText(question)).toBeNull()
expect(written()?.view.finding).toMatchObject({ citations: false })
draftKept()
})
it('a Back from a clean reference dialog over the sheet closes it only', async () => {
const user = await sheetOverDirtyForm()
const sheet = within(panelOpen()!)
const head = sheet.getByRole('button', { name: /^Alpha/ })
if (head.getAttribute('aria-expanded') === 'false') await user.click(head)
const tile = within(head.closest('li')!)
await user.click(tile.getByRole('button', { name: 'Modifier' }))
await waitFor(() => expect(refForm()).toBeDefined())
await back()
await waitFor(() => expect(refForm()).toBeUndefined())
expect(panelOpen()).not.toBeNull()
expect(screen.queryByText(question)).toBeNull()
})
it('a jump of two entries inside the editor closes the sheet, then the form asks', async () => {
await sheetOverDirtyForm()
await act(async () => navigate(-2))
await waitFor(() => expect(panelOpen()).toBeNull())
expect(inDialog().getByText(question)).toBeVisible()
await waitFor(() =>
expect(findingDialog()!.contains(document.activeElement)).toBe(true),
)
expect(written()?.view.finding).toMatchObject({ citations: false })
draftKept()
})
it('a jump out of the editor closes the sheet, then the form asks in view', async () => {
await sheetOverDirtyForm()
const url = new URL('/app/admin/sheets', window.location.origin).href
const event = Object.assign(new Event('navigate', { cancelable: true }), {
navigationType: 'traverse',
destination: { url, key: 'list', sameDocument: true },
})
act(() => {
api.dispatchEvent(event)
})
expect(event.defaultPrevented).toBe(true)
await waitFor(() => expect(panelOpen()).toBeNull())
expect(inDialog().getByText(question)).toBeVisible()
await waitFor(() =>
expect(findingDialog()!.contains(document.activeElement)).toBe(true),
)
draftKept()
})
})
@@ -109,13 +109,26 @@ describe('a Back over the finding layers', () => {
it('a dirty layer keeps the page where it is: asked, the view pushed again', async () => {
const guard = vi.fn(() => ({ allowed: false }))
await openSheet(guard)
// The sheet is no form: the Back that closes it alone asks nothing (rev 4, item 1).
act(() => navigate(-1))
expect(guard).not.toHaveBeenCalled()
expect(layer()).toMatchObject({ citations: false })
const before = entry().id
act(() => navigate(-1))
expect(guard).toHaveBeenCalledWith(false)
expect(layer()).toMatchObject({ citations: true })
expect(layer()).toMatchObject({ citations: false })
expect(entry().id).not.toBe(before)
expect(entry().view.finding).toMatchObject({ citations: true })
expect(entry().below?.finding).toMatchObject({ citations: false })
expect(entry().view.finding).toMatchObject({ citations: false })
expect(entry().below?.finding).toBeNull()
})
it('a jump that removes a dirty dialog under the sheet closes the sheet, then asks', async () => {
const guard = vi.fn(() => ({ allowed: false }))
await openSheet(guard)
act(() => navigate(-2))
expect(guard).toHaveBeenCalledWith(false)
expect(layer()).toMatchObject({ citations: false })
expect(entry().view.finding).toMatchObject({ citations: false })
})
it('a modal that is no layer refuses the Back too', async () => {