fix(editor): Task 8 round 2, cascade closes the sheet
This commit is contained in:
1 parent
579d8afff4
commit
791fc03a0d
7 files changed
+205
-10
No files matched your search
@@ -13,6 +13,7 @@ import {
|
||||
openTab,
|
||||
referenceDialog,
|
||||
seedDraft,
|
||||
showCitations,
|
||||
standardShape,
|
||||
startReference,
|
||||
} from '../support/editor'
|
||||
@@ -162,4 +163,48 @@ test.describe('leaving the editor by a history jump', () => {
|
||||
await reopenDraft(page)
|
||||
await expect(page.getByText(leftNotice)).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('a dirty reference over the sheet of a dirty finding: both ask in turn', async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
test.setTimeout(150_000)
|
||||
const sheetId = await open(page)
|
||||
await openFinding(page, dict, 'Constat A')
|
||||
const finding = findingDialog(page)
|
||||
await finding
|
||||
.getByRole('button', { name: dict['editor.findings.edit'], exact: true })
|
||||
.click()
|
||||
const name = finding.getByLabel(dict['editor.general.name_fr'])
|
||||
await name.fill('Constat brouillon')
|
||||
await showCitations(page)
|
||||
const panel = page.getByTestId('editor-citations-panel')
|
||||
await panel.locator('button[aria-controls][id$="-header"]').first().click()
|
||||
await panel
|
||||
.getByRole('button', { name: dict['editor.references.edit'] })
|
||||
.click()
|
||||
const form = referenceDialog(page)
|
||||
await form.getByLabel(dict['editor.reference.citation']).fill('Brouillon')
|
||||
await expect(page.locator('dialog[open]')).toHaveCount(3)
|
||||
|
||||
await jumpToOverview(context, page, sheetId)
|
||||
await expect(form.getByText(confirmText)).toBeVisible()
|
||||
await form
|
||||
.getByRole('button', { name: dict['editor.findings.discard'] })
|
||||
.click()
|
||||
await expect(page.locator('dialog[open]')).toHaveCount(1)
|
||||
await expect(finding.getByText(confirmText)).toBeVisible()
|
||||
const keep = finding.getByRole('button', {
|
||||
name: dict['editor.findings.keep_typing'],
|
||||
})
|
||||
await expect(keep).toBeFocused()
|
||||
expect(new URL(page.url()).pathname).toBe(draftPath(sheetId))
|
||||
await finding
|
||||
.getByRole('button', { name: dict['editor.findings.discard'] })
|
||||
.click()
|
||||
await expect(page).toHaveURL(
|
||||
(url) => url.pathname === overviewPath(sheetId),
|
||||
)
|
||||
expect(await leftFlags(page)).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -141,7 +141,7 @@ function useOwner(sheetId: string, tag: string): HistoryOwner {
|
||||
* or one under a tag already rotated (a sign-out): nobody would read that flag.
|
||||
*/
|
||||
function useUnflagged(nav: EditorNavigation, tag: string) {
|
||||
const confirmed = useLeaveConfirm(nav.guards)
|
||||
const confirmed = useLeaveConfirm(nav)
|
||||
return useCallback(
|
||||
() => confirmed() || useSessionTagStore.getState().held?.tag !== tag,
|
||||
[confirmed, tag],
|
||||
|
||||
@@ -10,6 +10,42 @@ import { useT } from '@/i18n/useT'
|
||||
const BOX =
|
||||
'space-y-2 rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-strong)] p-3'
|
||||
|
||||
/** True when no open dialog lies over `host`: each open one is `host` or holds it. */
|
||||
const onTop = (host: Element) =>
|
||||
[...document.querySelectorAll('dialog[open]')].every(
|
||||
(dialog) => dialog === host || dialog.contains(host),
|
||||
)
|
||||
|
||||
/**
|
||||
* Focuses `target` once its dialog is on top: at once, or, when dialogs over it are
|
||||
* closing (a history jump that asks layer after layer, criterion 23), after the last one
|
||||
* has gone and restored its own focus (two microtasks after the DOM change; Chromium
|
||||
* fires `close` only once the dialog has left the DOM, so the DOM is what is watched).
|
||||
* Answers a cancel.
|
||||
*/
|
||||
function focusWhenOnTop(target: HTMLElement): () => void {
|
||||
const host = target.closest('dialog')
|
||||
if (!host || onTop(host)) {
|
||||
target.focus()
|
||||
return () => undefined
|
||||
}
|
||||
const watcher = new MutationObserver(() =>
|
||||
queueMicrotask(() =>
|
||||
queueMicrotask(() => {
|
||||
if (!onTop(host)) return
|
||||
watcher.disconnect()
|
||||
target.focus()
|
||||
}),
|
||||
),
|
||||
)
|
||||
watcher.observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
attributeFilter: ['open'],
|
||||
})
|
||||
return () => watcher.disconnect()
|
||||
}
|
||||
|
||||
export default function DiscardConfirm({
|
||||
onKeepTyping,
|
||||
onDiscard,
|
||||
@@ -19,7 +55,10 @@ export default function DiscardConfirm({
|
||||
}) {
|
||||
const t = useT()
|
||||
const keep = useRef<HTMLButtonElement>(null)
|
||||
useEffect(() => keep.current?.focus(), [])
|
||||
useEffect(() => {
|
||||
const button = keep.current
|
||||
return button ? focusWhenOnTop(button) : undefined
|
||||
}, [])
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
|
||||
@@ -132,5 +132,9 @@ export function startSessionTagSync(): () => void {
|
||||
*/
|
||||
export function useSessionTag(): string | null {
|
||||
const user = useAuthStore((s) => s.user?.id ?? null)
|
||||
// shortcut: resolved during the render (it may set the tag store, write sessionStorage
|
||||
// and clear old flags). Safe while it stays idempotent per account and nothing
|
||||
// subscribes to `useSessionTagStore` (no update-while-rendering). Upgrade path: resolve
|
||||
// at sign-in in `startSessionTagSync` only, and read the held tag here.
|
||||
return useMemo(() => (user ? resolveSessionTag(user) : null), [user])
|
||||
}
|
||||
@@ -1,7 +1,12 @@
|
||||
import { useCallback, useEffect, useRef } from 'react'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { topDirtyLayer } from '../leftDraft'
|
||||
import type { Guards, LayerExit, LayerName } from '../useEditorNavigation'
|
||||
import type {
|
||||
EditorNavigation,
|
||||
Guards,
|
||||
LayerExit,
|
||||
LayerName,
|
||||
} from '../useEditorNavigation'
|
||||
|
||||
/** The part of a Navigation API `navigate` event this guard reads (not in the DOM types). */
|
||||
interface NavigateEventLike extends Event {
|
||||
@@ -35,6 +40,8 @@ function leavesEditor(event: NavigateEventLike, path: string): boolean {
|
||||
|
||||
interface Watch {
|
||||
guards: Guards
|
||||
/** Closes the citations sheet, which may lie between two asking dialogs. */
|
||||
closeSheet: () => void
|
||||
path: string
|
||||
/** The key of the jump the user confirmed: it passes, and leaves no flag. */
|
||||
passing: { current: string | null }
|
||||
@@ -63,18 +70,21 @@ function jumpTo({ api, key, watch }: Jump, keep: () => void): void {
|
||||
|
||||
/**
|
||||
* `layer` asks « Abandonner les modifications ? » and holds the jump. Its « Abandonner »
|
||||
* closes it and the next dirty layer under it asks in turn; the last one lets the jump go.
|
||||
* Any « Continuer la saisie » drops the jump.
|
||||
* 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.
|
||||
*/
|
||||
function askLeave(jump: Jump, layer: LayerName): void {
|
||||
const { guards } = jump.watch
|
||||
const { guards, closeSheet } = jump.watch
|
||||
guards.ask(layer, false)
|
||||
guards.holdLeave({
|
||||
layer,
|
||||
go: (exit: LayerExit) => {
|
||||
const next = topDirtyLayer(guards, layer)
|
||||
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)
|
||||
},
|
||||
})
|
||||
@@ -101,18 +111,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(guards: Guards): () => boolean {
|
||||
export default function useLeaveConfirm(
|
||||
nav: Pick<EditorNavigation, 'guards' | 'closeCitations'>,
|
||||
): () => boolean {
|
||||
const { pathname } = useLocation()
|
||||
const passing = useRef<string | null>(null)
|
||||
const path = useRef(pathname).current
|
||||
const { guards, closeCitations } = nav
|
||||
useEffect(() => {
|
||||
const api = navigationApi()
|
||||
if (!api) return
|
||||
const watch: Watch = { guards, path, passing }
|
||||
const closeSheet = () => void closeCitations()
|
||||
const watch: Watch = { guards, closeSheet, path, passing }
|
||||
const listener = (event: Event) =>
|
||||
onNavigate(api, event as NavigateEventLike, watch)
|
||||
api.addEventListener('navigate', listener)
|
||||
return () => api.removeEventListener('navigate', listener)
|
||||
}, [guards, path])
|
||||
}, [guards, closeCitations, path])
|
||||
return useCallback(() => passing.current !== null, [])
|
||||
}
|
||||
@@ -42,7 +42,7 @@ function Asking(props: {
|
||||
|
||||
function Editor() {
|
||||
const nav = useEditorNavigation('findings')
|
||||
useLeaveConfirm(nav.guards)
|
||||
useLeaveConfirm(nav)
|
||||
return (
|
||||
<>
|
||||
<Layer guards={nav.guards} layer="finding" />
|
||||
|
||||
@@ -559,3 +559,96 @@ describe('final review: the creation dialog fades out as a creation (M-9)', () =
|
||||
expect(titles).not.toContain('Modifier la référence')
|
||||
})
|
||||
})
|
||||
|
||||
/** The Navigation API as the leave guard reads it: `navigate` events and `traverseTo`. */
|
||||
class NavigationStub extends EventTarget {
|
||||
traverseTo = vi.fn((key: string) => {
|
||||
void key
|
||||
return { committed: Promise.resolve(), finished: Promise.resolve() }
|
||||
})
|
||||
}
|
||||
|
||||
describe('a jump with the reference over the sheet of a dirty finding (criterion 23)', () => {
|
||||
let api: NavigationStub
|
||||
beforeEach(() => {
|
||||
api = new NavigationStub()
|
||||
Object.defineProperty(window, 'navigation', {
|
||||
value: api,
|
||||
configurable: true,
|
||||
})
|
||||
})
|
||||
afterEach(() => {
|
||||
Reflect.deleteProperty(window, 'navigation')
|
||||
})
|
||||
|
||||
const sheet = () =>
|
||||
[...dialogs()].find((d) => d.querySelector('[data-place="citations"]'))
|
||||
const question = 'Abandonner les modifications ?'
|
||||
/** The reference dialog: the finding's edit form is a draft form too. */
|
||||
const refForm = () =>
|
||||
[...dialogs()].find((d) => d.querySelector('#reference-form-citation')) as
|
||||
| HTMLElement
|
||||
| undefined
|
||||
const inForm = () => within(refForm()!)
|
||||
|
||||
function jump() {
|
||||
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)
|
||||
})
|
||||
return event
|
||||
}
|
||||
|
||||
/** Node A in edit with a typed name, its sheet open, Barone in edit with a typed citation. */
|
||||
async function stacked(user: User) {
|
||||
await user.click(screen.getByRole('tab', { name: 'Constats' }))
|
||||
await openFinding(user, /Node A/)
|
||||
const finding = within(findingDialog()!)
|
||||
await user.click(finding.getByRole('button', { name: 'Modifier' }))
|
||||
await user.type(finding.getByLabelText('Nom (FR)'), ' bis')
|
||||
await user.click(finding.getByRole('button', { name: '2 références' }))
|
||||
await waitFor(() => expect(sheet()).toBeDefined())
|
||||
const inSheet = within(sheet() as HTMLElement)
|
||||
const head = inSheet.getByRole('button', { name: /^Barone/ })
|
||||
if (head.getAttribute('aria-expanded') === 'false') await user.click(head)
|
||||
const tile = head.closest('li')!
|
||||
await user.click(within(tile).getByRole('button', { name: 'Modifier' }))
|
||||
await waitFor(() => expect(refForm()).toBeDefined())
|
||||
await user.type(inForm().getByLabelText('Citation'), ' x')
|
||||
}
|
||||
|
||||
it('the finding asks next with the sheet closed, focused; the jump goes after it', async () => {
|
||||
const user = await mount()
|
||||
await stacked(user)
|
||||
expect(jump().defaultPrevented).toBe(true)
|
||||
expect(inForm().getByText(question)).toBeVisible()
|
||||
await user.click(inForm().getByRole('button', { name: 'Abandonner' }))
|
||||
await waitFor(() => expect(refForm()).toBeUndefined())
|
||||
await waitFor(() => expect(sheet()).toBeUndefined())
|
||||
const finding = within(findingDialog()!)
|
||||
expect(finding.getByText(question)).toBeVisible()
|
||||
const keep = finding.getByRole('button', { name: 'Continuer la saisie' })
|
||||
await waitFor(() => expect(keep).toHaveFocus())
|
||||
expect(api.traverseTo).not.toHaveBeenCalled()
|
||||
await user.click(finding.getByRole('button', { name: 'Abandonner' }))
|
||||
expect(api.traverseTo).toHaveBeenCalledWith('list')
|
||||
})
|
||||
|
||||
it('« Continuer la saisie » there keeps the finding draft and drops the jump', async () => {
|
||||
const user = await mount()
|
||||
await stacked(user)
|
||||
jump()
|
||||
await user.click(inForm().getByRole('button', { name: 'Abandonner' }))
|
||||
await waitFor(() => expect(sheet()).toBeUndefined())
|
||||
const finding = within(findingDialog()!)
|
||||
await user.click(
|
||||
finding.getByRole('button', { name: 'Continuer la saisie' }),
|
||||
)
|
||||
expect(finding.getByLabelText('Nom (FR)')).toHaveValue('Node A bis')
|
||||
expect(api.traverseTo).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user