fix(editor): Task 8 round 1, sync tag, cascaded leave ask
This commit is contained in:
1 parent
07bebbc855
commit
579d8afff4
10 files changed
+359
-83
No files matched your search
@@ -42,13 +42,18 @@ async function open(page: Page) {
|
||||
await page.goto('/app/admin')
|
||||
await stepUpAdmin(page, dict, actor.secret)
|
||||
await page.goto(overviewPath(seed.sheetId))
|
||||
await reopenDraft(page)
|
||||
return seed.sheetId
|
||||
}
|
||||
|
||||
/** From the overview, the draft through its link (same document). */
|
||||
async function reopenDraft(page: Page) {
|
||||
await page
|
||||
.getByRole('link', { name: dict['admin.overview.open_draft'] })
|
||||
.click()
|
||||
await expect(
|
||||
page.getByRole('heading', { level: 1, name: draftTitle(dict) }),
|
||||
).toBeVisible()
|
||||
return seed.sheetId
|
||||
}
|
||||
|
||||
/** The history menu's jump to the last entry of the overview, several entries back. */
|
||||
@@ -122,12 +127,7 @@ test.describe('leaving the editor by a history jump', () => {
|
||||
(url) => url.pathname === overviewPath(sheetId),
|
||||
)
|
||||
expect(await leftFlags(page)).toBe(0)
|
||||
await page
|
||||
.getByRole('link', { name: dict['admin.overview.open_draft'] })
|
||||
.click()
|
||||
await expect(
|
||||
page.getByRole('heading', { level: 1, name: draftTitle(dict) }),
|
||||
).toBeVisible()
|
||||
await reopenDraft(page)
|
||||
await expect(page.getByText(leftNotice)).toHaveCount(0)
|
||||
})
|
||||
|
||||
@@ -159,5 +159,7 @@ test.describe('leaving the editor by a history jump', () => {
|
||||
(url) => url.pathname === overviewPath(sheetId),
|
||||
)
|
||||
expect(await leftFlags(page)).toBe(0)
|
||||
await reopenDraft(page)
|
||||
await expect(page.getByText(leftNotice)).toHaveCount(0)
|
||||
})
|
||||
})
|
||||
@@ -239,8 +239,8 @@ function Workspace(props: Props & { tag: string }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The editor of the signed-in account's session tag (criterion 22). Until the tag is
|
||||
* known nothing is restored or written (fail closed); another tag is another editor.
|
||||
* The editor of the signed-in account's session tag (criterion 22), resolved at once;
|
||||
* nobody signed in, no editor. Another tag is another editor.
|
||||
*/
|
||||
export default function EditorWorkspace(props: Props) {
|
||||
const tag = useSessionTag()
|
||||
|
||||
@@ -13,8 +13,9 @@ export type DiscardTarget = 'form' | 'dialog'
|
||||
* forced close (the element vanished) goes ahead and says the draft was dropped
|
||||
* (BDR-115); a form with nothing typed says nothing.
|
||||
* `askToLeave` is the form's own « Annuler ». The browser's unload is guarded too.
|
||||
* A history jump out of the editor that was held for this question (criterion 23) is
|
||||
* what `discard` carries out; « Continuer la saisie » drops it.
|
||||
* A history jump out of the editor held for this question (criterion 23) is what
|
||||
* `discard` carries on (the next dirty layer asks, or the jump goes); « Continuer la
|
||||
* saisie » drops it.
|
||||
*/
|
||||
export function useDirtyGuard(
|
||||
guards: Guards,
|
||||
@@ -43,8 +44,12 @@ export function useDirtyGuard(
|
||||
guards.holdLeave(null)
|
||||
setConfirming(null)
|
||||
},
|
||||
/** « Abandonner »: the held leave when there is one, else `close`. */
|
||||
discard: (close: () => void) => () => (guards.takeLeave() ?? close)(),
|
||||
/** « Abandonner »: the leave held for this layer when there is one, else `close`. */
|
||||
discard: (close: () => void) => () => {
|
||||
const leave = guards.takeLeave(layer)
|
||||
if (leave) leave({ close, keep: () => setConfirming(null) })
|
||||
else close()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useMemo } from 'react'
|
||||
import { create } from 'zustand'
|
||||
import { useAuthStore } from '@/state/authStore'
|
||||
import { clearLeftDrafts } from '../leftDraft'
|
||||
import { clearLeftDrafts, sweepAccountFlags } from '../leftDraft'
|
||||
|
||||
/**
|
||||
* The session tag (criterion 22, owner 2026-11-14): a random 128-bit label the history
|
||||
* entries and the left-draft flag carry instead of the account id. It is kept in this
|
||||
* tab's sessionStorage with the SHA-256 digest of the account id, reused only for the
|
||||
* account whose digest it holds, and rotated on sign-out and on any other account (the
|
||||
* flags of the old tag cleared). A storage that refuses, or no digest (an insecure
|
||||
* origin), keeps it in memory only: a reload then restores nothing.
|
||||
* tab's sessionStorage with a fingerprint of the account id, reused only for the account
|
||||
* whose fingerprint it holds, and rotated on sign-out and on any other account (the flags
|
||||
* of the old tag cleared). Resolved at once, on any origin (http included). A storage
|
||||
* that refuses keeps it in memory only: a reload then restores nothing.
|
||||
*/
|
||||
const STORAGE_KEY = 'faunosteo:editor:session-tag'
|
||||
const TAG_PATTERN = /^[0-9a-f]{32}$/
|
||||
const DIGEST_PATTERN = /^[0-9a-f]{64}$/
|
||||
const FINGERPRINT_PATTERN = /^[0-9a-f]{16}$/
|
||||
|
||||
interface TagRecord {
|
||||
tag: string
|
||||
/** The SHA-256 digest (hex) of the account id; empty when none could be made. */
|
||||
/** The fingerprint of the account id (`fingerprintOf`). */
|
||||
account: string
|
||||
}
|
||||
|
||||
@@ -36,14 +36,21 @@ const hex = (bytes: Uint8Array) =>
|
||||
|
||||
const randomTag = () => hex(crypto.getRandomValues(new Uint8Array(16)))
|
||||
|
||||
/** The digest of the account id, or null where the browser offers none. */
|
||||
async function digestOf(user: string): Promise<string | null> {
|
||||
try {
|
||||
const data = new TextEncoder().encode(user)
|
||||
return hex(new Uint8Array(await crypto.subtle.digest('SHA-256', data)))
|
||||
} catch {
|
||||
return null
|
||||
const FNV_OFFSET = 0xcbf29ce484222325n
|
||||
const FNV_PRIME = 0x100000001b3n
|
||||
const MASK_64 = 0xffffffffffffffffn
|
||||
|
||||
/**
|
||||
* FNV-1a 64 of the account id, hex. An equality check binding the tag to one account,
|
||||
* not a secret: it keeps the raw id out of storage, and needs no secure context
|
||||
* (`crypto.subtle` is absent on an http origin such as the LAN trial).
|
||||
*/
|
||||
function fingerprintOf(user: string): string {
|
||||
let hash = FNV_OFFSET
|
||||
for (const byte of new TextEncoder().encode(user)) {
|
||||
hash = ((hash ^ BigInt(byte)) * FNV_PRIME) & MASK_64
|
||||
}
|
||||
return hash.toString(16).padStart(16, '0')
|
||||
}
|
||||
|
||||
function isTagRecord(raw: unknown): raw is TagRecord {
|
||||
@@ -53,7 +60,7 @@ function isTagRecord(raw: unknown): raw is TagRecord {
|
||||
typeof tag === 'string' &&
|
||||
TAG_PATTERN.test(tag) &&
|
||||
typeof account === 'string' &&
|
||||
DIGEST_PATTERN.test(account)
|
||||
FINGERPRINT_PATTERN.test(account)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -82,22 +89,19 @@ function retire(...records: (TagRecord | null)[]): void {
|
||||
|
||||
function hold(next: HeldTag): string {
|
||||
useSessionTagStore.setState({ held: next })
|
||||
if (next.account) writeStored({ tag: next.tag, account: next.account })
|
||||
writeStored({ tag: next.tag, account: next.account })
|
||||
return next.tag
|
||||
}
|
||||
|
||||
/** The tag of `user` in this tab: the kept one when its digest matches, else a new one. */
|
||||
export async function resolveSessionTag(user: string): Promise<string> {
|
||||
const known = useSessionTagStore.getState().held
|
||||
if (known?.user === user) return known.tag
|
||||
const account = await digestOf(user)
|
||||
// Another resolve may have finished while the digest was made.
|
||||
/** The tag of `user` in this tab: the kept one when its fingerprint matches, else a new one. */
|
||||
export function resolveSessionTag(user: string): string {
|
||||
const held = useSessionTagStore.getState().held
|
||||
if (held?.user === user) return held.tag
|
||||
const kept = account ? readStored() : null
|
||||
const account = fingerprintOf(user)
|
||||
const kept = readStored()
|
||||
if (kept && kept.account === account) return hold({ ...kept, user })
|
||||
retire(kept, held)
|
||||
return hold({ tag: randomTag(), account: account ?? '', user })
|
||||
return hold({ tag: randomTag(), account, user })
|
||||
}
|
||||
|
||||
/** Sign-out: the tag goes, with its flags; the next sign-in draws a new one. */
|
||||
@@ -107,22 +111,26 @@ export function forgetSessionTag(): void {
|
||||
useSessionTagStore.setState({ held: null })
|
||||
}
|
||||
|
||||
/** Follows the signed-in account for the app's lifetime; returns the unsubscribe. */
|
||||
/**
|
||||
* Follows the signed-in account for the app's lifetime; returns the unsubscribe. On start,
|
||||
* flags of the older shape (keyed by an account id) are swept from the tab.
|
||||
*/
|
||||
export function startSessionTagSync(): () => void {
|
||||
sweepAccountFlags()
|
||||
return useAuthStore.subscribe((state, previous) => {
|
||||
const user = state.user?.id
|
||||
if (user === previous.user?.id) return
|
||||
if (user) void resolveSessionTag(user)
|
||||
if (user) resolveSessionTag(user)
|
||||
else forgetSessionTag()
|
||||
})
|
||||
}
|
||||
|
||||
/** The session tag of the signed-in account, or null until it is known (fail closed). */
|
||||
/**
|
||||
* The session tag of the signed-in account, resolved at once; null when nobody is signed
|
||||
* in. Nothing renders under this hook's store, so resolving during the render updates no
|
||||
* other component.
|
||||
*/
|
||||
export function useSessionTag(): string | null {
|
||||
const user = useAuthStore((s) => s.user?.id ?? null)
|
||||
const held = useSessionTagStore((s) => s.held)
|
||||
useEffect(() => {
|
||||
if (user) void resolveSessionTag(user)
|
||||
}, [user])
|
||||
return user && held?.user === user ? held.tag : null
|
||||
return useMemo(() => (user ? resolveSessionTag(user) : null), [user])
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useRef } from 'react'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { topDirtyLayer } from '../leftDraft'
|
||||
import type { Guards } from '../useEditorNavigation'
|
||||
import type { 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 {
|
||||
@@ -40,21 +40,49 @@ interface Watch {
|
||||
passing: { current: string | null }
|
||||
}
|
||||
|
||||
/** « Abandonner » after a held jump: the same jump, let through this time. */
|
||||
function jumpTo(api: NavigationLike, key: string, watch: Watch): void {
|
||||
interface Jump {
|
||||
api: NavigationLike
|
||||
key: string
|
||||
watch: Watch
|
||||
}
|
||||
|
||||
/**
|
||||
* The last « Abandonner »: the same jump, let through this time. A jump that fails closes
|
||||
* the question and keeps the draft (`keep`).
|
||||
*/
|
||||
function jumpTo({ api, key, watch }: Jump, keep: () => void): void {
|
||||
watch.passing.current = key
|
||||
const failed = () => {
|
||||
watch.passing.current = null
|
||||
keep()
|
||||
}
|
||||
const { committed, finished } = api.traverseTo(key)
|
||||
committed.catch(failed)
|
||||
committed.catch(() => undefined)
|
||||
finished.catch(failed)
|
||||
}
|
||||
|
||||
/**
|
||||
* `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.
|
||||
*/
|
||||
function askLeave(jump: Jump, layer: LayerName): void {
|
||||
const { guards } = jump.watch
|
||||
guards.ask(layer, false)
|
||||
guards.holdLeave({
|
||||
layer,
|
||||
go: (exit: LayerExit) => {
|
||||
const next = topDirtyLayer(guards, layer)
|
||||
if (!next) return jumpTo(jump, exit.keep)
|
||||
exit.close()
|
||||
askLeave(jump, next)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* A jump out of the editor while a dialog holds changes is cancelled when the browser
|
||||
* lets the page cancel it; the top dirty dialog asks « Abandonner les modifications ? »
|
||||
* and holds the jump for its « Abandonner ».
|
||||
* lets the page cancel it; the dirty dialogs ask, top down, before it goes.
|
||||
*/
|
||||
function onNavigate(api: NavigationLike, event: NavigateEventLike, w: Watch) {
|
||||
if (!leavesEditor(event, w.path)) return
|
||||
@@ -63,14 +91,13 @@ function onNavigate(api: NavigationLike, event: NavigateEventLike, w: Watch) {
|
||||
const layer = topDirtyLayer(w.guards)
|
||||
if (!layer) return
|
||||
event.preventDefault()
|
||||
w.guards.ask(layer, false)
|
||||
w.guards.holdLeave(() => jumpTo(api, key, w))
|
||||
askLeave({ api, key, watch: w }, layer)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 the
|
||||
* dialog's own question; elsewhere (no API, a jump the browser will not let the page
|
||||
* dialog (criterion 23): where the Navigation API can cancel it, the jump waits for each
|
||||
* dirty dialog's own question; elsewhere (no API, a jump the browser will not let the page
|
||||
* 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.
|
||||
*/
|
||||
|
||||
@@ -17,9 +17,18 @@ export const leftDraftKey = ({ sheetId, tag }: HistoryOwner) =>
|
||||
/** The top layer first: the dialog the user was typing in when they left. */
|
||||
const LAYERS_TOP_DOWN: readonly LayerName[] = ['reference', 'finding']
|
||||
|
||||
/** The top layer whose form holds changes; a forced ask has no side effect. */
|
||||
export const topDirtyLayer = (guards: Guards): LayerName | null =>
|
||||
LAYERS_TOP_DOWN.find((l) => guards.ask(l, true).note) ?? null
|
||||
/**
|
||||
* The top layer whose form holds changes, or the first one under `below`; a forced ask
|
||||
* has no side effect.
|
||||
*/
|
||||
export function topDirtyLayer(
|
||||
guards: Guards,
|
||||
below: LayerName | null = null,
|
||||
): LayerName | null {
|
||||
const from = below ? LAYERS_TOP_DOWN.indexOf(below) + 1 : 0
|
||||
const layers = LAYERS_TOP_DOWN.slice(from)
|
||||
return layers.find((l) => guards.ask(l, true).note) ?? null
|
||||
}
|
||||
|
||||
function storage(): Storage | null {
|
||||
try {
|
||||
@@ -94,6 +103,24 @@ export function clearLeftDrafts(tag: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
const TAG_SUFFIX = /:[0-9a-f]{32}$/
|
||||
|
||||
/**
|
||||
* Removes the flags of the older shape, keyed by an account id (criterion 22): no raw
|
||||
* account id stays in the tab's storage.
|
||||
*/
|
||||
export function sweepAccountFlags(): void {
|
||||
try {
|
||||
const store = storage()
|
||||
if (!store) return
|
||||
const keys = Array.from({ length: store.length }, (_, i) => store.key(i))
|
||||
const old = keys.filter((k) => k?.startsWith(PREFIX) && !TAG_SUFFIX.test(k))
|
||||
for (const key of old) if (key) store.removeItem(key)
|
||||
} catch {
|
||||
// A blocked storage holds no flag to sweep.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the last editor of this sheet under this session tag left with a dirty dialog:
|
||||
* shown once, then cleared. The editor's own cleanup runs before its dialogs' (a deleted
|
||||
|
||||
@@ -65,12 +65,24 @@ export interface Guards {
|
||||
/** The layers asked top down; one refusal refuses, and each one still shows its own. */
|
||||
askAll: (forced: boolean) => LeaveAnswer
|
||||
/**
|
||||
* A leave of the editor held while the top dirty layer asks (criterion 23): its
|
||||
* « Abandonner » runs it. Any later user ask, or a layer going, drops it.
|
||||
* A leave of the editor held while a dirty layer asks (criterion 23): that layer's
|
||||
* « Abandonner » carries it on. Any later user ask, or the asking layer going, drops it.
|
||||
*/
|
||||
holdLeave: (leave: (() => void) | null) => void
|
||||
/** The held leave, taken once; null when none is held. */
|
||||
takeLeave: () => (() => void) | null
|
||||
holdLeave: (leave: HeldLeave | null) => void
|
||||
/** The leave held for `layer`, taken once; null when none is held for it. */
|
||||
takeLeave: (layer: LayerName) => HeldLeave['go'] | null
|
||||
}
|
||||
|
||||
/** What a held leave may do with the layer that asked: close it, or keep it as it is. */
|
||||
export interface LayerExit {
|
||||
close: () => void
|
||||
keep: () => void
|
||||
}
|
||||
|
||||
/** A leave held for the layer asking about it. */
|
||||
export interface HeldLeave {
|
||||
layer: LayerName
|
||||
go: (exit: LayerExit) => void
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -198,16 +210,20 @@ function useLiveRegion() {
|
||||
|
||||
/** The leave a layer's « Abandonner » would carry out, held while it asks. */
|
||||
function useHeldLeave() {
|
||||
const held = useRef<(() => void) | null>(null)
|
||||
const held = useRef<HeldLeave | null>(null)
|
||||
return useMemo(
|
||||
() => ({
|
||||
holdLeave: (leave: (() => void) | null) => {
|
||||
holdLeave: (leave: HeldLeave | null) => {
|
||||
held.current = leave
|
||||
},
|
||||
takeLeave: () => {
|
||||
const leave = held.current
|
||||
held.current = null
|
||||
return leave
|
||||
takeLeave: (layer: LayerName) => {
|
||||
const leave = held.current?.layer === layer ? held.current : null
|
||||
if (leave) held.current = null
|
||||
return leave?.go ?? null
|
||||
},
|
||||
/** The asking layer went: its leave goes with it. */
|
||||
dropFor: (layer: LayerName) => {
|
||||
if (held.current?.layer === layer) held.current = null
|
||||
},
|
||||
}),
|
||||
[],
|
||||
@@ -225,11 +241,12 @@ function useGuards(): Guards {
|
||||
return guards.get(layer)?.(forced) ?? { allowed: true }
|
||||
}
|
||||
return {
|
||||
...leave,
|
||||
holdLeave: leave.holdLeave,
|
||||
takeLeave: leave.takeLeave,
|
||||
register: (layer, guard) => {
|
||||
if (guard) guards.set(layer, guard)
|
||||
else guards.delete(layer)
|
||||
if (!guard) leave.holdLeave(null)
|
||||
if (!guard) leave.dropFor(layer)
|
||||
},
|
||||
ask,
|
||||
askAll: (forced) => {
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
resolveSessionTag,
|
||||
} from '@/editor/history/sessionTag'
|
||||
import { useCitationDraft } from '@/editor/findings/citationDraft'
|
||||
import { useAuthStore } from '@/state/authStore'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { edit, insert } from '../helpers/editorFixtures'
|
||||
import { defaultView } from '@/editor/navigation'
|
||||
@@ -625,7 +626,10 @@ describe('final review: leaving the editor with a dirty dialog (criterion 17)',
|
||||
await openFinding(user, /Node A/)
|
||||
await modify(user)
|
||||
await user.type(nameField(), ' bis')
|
||||
act(() => forgetSessionTag())
|
||||
act(() => {
|
||||
forgetSessionTag()
|
||||
useAuthStore.setState({ user: null })
|
||||
})
|
||||
await waitFor(() => expect(findingDialog()).toBeNull())
|
||||
const flags = Object.keys(sessionStorage).filter((k) =>
|
||||
k.startsWith('faunosteo:editor:left-draft:'),
|
||||
@@ -666,11 +670,16 @@ describe('a jump of several entries out of the editor (criterion 23)', () => {
|
||||
})
|
||||
|
||||
/** A history jump to `pathname`, as Chromium dispatches it before it commits. */
|
||||
function traverse(pathname: string, key: string, cancelable = true) {
|
||||
function traverse(
|
||||
pathname: string,
|
||||
key: string,
|
||||
cancelable = true,
|
||||
sameDocument = true,
|
||||
) {
|
||||
const url = new URL(pathname, window.location.origin).href
|
||||
const event = Object.assign(new Event('navigate', { cancelable }), {
|
||||
navigationType: 'traverse',
|
||||
destination: { url, key, sameDocument: true },
|
||||
destination: { url, key, sameDocument },
|
||||
})
|
||||
act(() => {
|
||||
api.dispatchEvent(event)
|
||||
@@ -733,6 +742,33 @@ describe('a jump of several entries out of the editor (criterion 23)', () => {
|
||||
expect(sessionStorage.getItem(flagKey())).not.toBeNull()
|
||||
})
|
||||
|
||||
it('a failed jump closes the question and keeps the draft', async () => {
|
||||
const user = await dirtyDialog()
|
||||
api.traverseTo.mockImplementation(() => ({
|
||||
committed: Promise.reject(new Error('gone')),
|
||||
finished: Promise.reject(new Error('gone')),
|
||||
}))
|
||||
traverse('/app/admin/sheets', 'list')
|
||||
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByText('Abandonner les modifications ?')).toBeNull(),
|
||||
)
|
||||
expect(nameField()).toHaveValue('Node A bis')
|
||||
cleanup()
|
||||
expect(sessionStorage.getItem(flagKey())).not.toBeNull()
|
||||
})
|
||||
|
||||
it('a jump to another sheet is a leave; another document is not cancelled', async () => {
|
||||
await dirtyDialog()
|
||||
const other = '/app/admin/sheets/other-sheet/draft'
|
||||
expect(traverse('/app/admin', 'admin', true, false).defaultPrevented).toBe(
|
||||
false,
|
||||
)
|
||||
expect(screen.queryByText('Abandonner les modifications ?')).toBeNull()
|
||||
expect(traverse(other, 'other').defaultPrevented).toBe(true)
|
||||
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
|
||||
})
|
||||
|
||||
it('a traversal inside the editor, or a clean dialog, is left alone', async () => {
|
||||
const user = await mount()
|
||||
await openFinding(user, /Node A/)
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
/** Criterion 23: a history jump out of the editor asks every dirty layer, top down. */
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import DiscardConfirm from '@/components/editor/findings/DiscardConfirm'
|
||||
import { useDirtyGuard } from '@/components/editor/findings/useDirtyGuard'
|
||||
import useLeaveConfirm from '@/editor/history/useLeaveConfirm'
|
||||
import {
|
||||
useEditorNavigation,
|
||||
type Guards,
|
||||
type LayerName,
|
||||
} from '@/editor/useEditorNavigation'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
const path = '/app/admin/sheets/S/draft'
|
||||
|
||||
/** A dirty layer: its question and buttons once asked, gone once closed. */
|
||||
function Layer({ guards, layer }: { guards: Guards; layer: LayerName }) {
|
||||
const [open, setOpen] = useState(true)
|
||||
return open ? <Asking guards={guards} layer={layer} close={setOpen} /> : null
|
||||
}
|
||||
|
||||
function Asking(props: {
|
||||
guards: Guards
|
||||
layer: LayerName
|
||||
close: (open: boolean) => void
|
||||
}) {
|
||||
const guard = useDirtyGuard(props.guards, true, props.layer)
|
||||
return (
|
||||
<section data-testid={props.layer}>
|
||||
{guard.confirming && (
|
||||
<DiscardConfirm
|
||||
onKeepTyping={guard.keepTyping}
|
||||
onDiscard={guard.discard(() => props.close(false))}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function Editor() {
|
||||
const nav = useEditorNavigation('findings')
|
||||
useLeaveConfirm(nav.guards)
|
||||
return (
|
||||
<>
|
||||
<Layer guards={nav.guards} layer="finding" />
|
||||
<Layer guards={nav.guards} layer="reference" />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
class NavigationStub extends EventTarget {
|
||||
traverseTo = vi.fn((key: string) => {
|
||||
void key
|
||||
return { committed: Promise.resolve(), finished: Promise.resolve() }
|
||||
})
|
||||
}
|
||||
|
||||
let api: NavigationStub
|
||||
beforeEach(() => {
|
||||
useLocaleStore.setState({ locale: 'fr' })
|
||||
api = new NavigationStub()
|
||||
Object.defineProperty(window, 'navigation', {
|
||||
value: api,
|
||||
configurable: true,
|
||||
})
|
||||
render(
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<Editor />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
Reflect.deleteProperty(window, 'navigation')
|
||||
})
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
const layer = (name: LayerName) => screen.queryByTestId(name)
|
||||
const button = (name: LayerName, label: string) =>
|
||||
within(layer(name)!).getByRole('button', { name: label })
|
||||
|
||||
describe('a reference dialog over a finding dialog, both dirty', () => {
|
||||
it('asks the reference, then the finding, then the jump goes', async () => {
|
||||
const user = userEvent.setup()
|
||||
expect(jump().defaultPrevented).toBe(true)
|
||||
expect(within(layer('finding')!).queryByRole('group')).toBeNull()
|
||||
await user.click(button('reference', 'Abandonner'))
|
||||
expect(layer('reference')).toBeNull()
|
||||
expect(api.traverseTo).not.toHaveBeenCalled()
|
||||
await user.click(button('finding', 'Abandonner'))
|
||||
expect(api.traverseTo).toHaveBeenCalledTimes(1)
|
||||
expect(api.traverseTo).toHaveBeenCalledWith('list')
|
||||
})
|
||||
|
||||
it('« Continuer la saisie » on the second keeps the finding, no jump', async () => {
|
||||
const user = userEvent.setup()
|
||||
jump()
|
||||
await user.click(button('reference', 'Abandonner'))
|
||||
await user.click(button('finding', 'Continuer la saisie'))
|
||||
expect(layer('finding')).not.toBeNull()
|
||||
expect(within(layer('finding')!).queryByRole('group')).toBeNull()
|
||||
expect(api.traverseTo).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('« Continuer la saisie » on the first question keeps every draft', async () => {
|
||||
const user = userEvent.setup()
|
||||
jump()
|
||||
await user.click(button('reference', 'Continuer la saisie'))
|
||||
expect(layer('reference')).not.toBeNull()
|
||||
expect(layer('finding')).not.toBeNull()
|
||||
expect(api.traverseTo).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -27,12 +27,12 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('resolveSessionTag', () => {
|
||||
it('draws a 128-bit hex tag, stored with the account digest, never the id', async () => {
|
||||
it('draws a 128-bit hex tag, stored with the account fingerprint, never the id', async () => {
|
||||
const tag = await resolveSessionTag('account-a')
|
||||
expect(tag).toMatch(/^[0-9a-f]{32}$/)
|
||||
const record = stored()
|
||||
expect(record?.tag).toBe(tag)
|
||||
expect(record?.account).toMatch(/^[0-9a-f]{64}$/)
|
||||
expect(record?.account).toMatch(/^[0-9a-f]{16}$/)
|
||||
expect(sessionStorage.getItem(STORAGE_KEY)).not.toContain('account-a')
|
||||
})
|
||||
|
||||
@@ -69,12 +69,27 @@ describe('resolveSessionTag', () => {
|
||||
expect(await resolveSessionTag('account-a')).not.toBe(tag)
|
||||
})
|
||||
|
||||
it('keeps the tag in memory when no digest is available', async () => {
|
||||
vi.spyOn(crypto.subtle, 'digest').mockRejectedValue(new Error('insecure'))
|
||||
const tag = await resolveSessionTag('account-a')
|
||||
expect(tag).toMatch(/^[0-9a-f]{32}$/)
|
||||
expect(stored()).toBeNull()
|
||||
expect(await resolveSessionTag('account-a')).toBe(tag)
|
||||
it('works without crypto.subtle (http): kept on reload, rotated per account', () => {
|
||||
const subtle = Object.getOwnPropertyDescriptor(crypto, 'subtle')
|
||||
Object.defineProperty(crypto, 'subtle', {
|
||||
value: undefined,
|
||||
configurable: true,
|
||||
})
|
||||
try {
|
||||
const tag = resolveSessionTag('account-a')
|
||||
expect(tag).toMatch(/^[0-9a-f]{32}$/)
|
||||
expect(sessionStorage.getItem(STORAGE_KEY)).not.toContain('account-a')
|
||||
reload()
|
||||
expect(resolveSessionTag('account-a')).toBe(tag)
|
||||
reload()
|
||||
expect(resolveSessionTag('account-b')).not.toBe(tag)
|
||||
} finally {
|
||||
if (subtle) Object.defineProperty(crypto, 'subtle', subtle)
|
||||
}
|
||||
})
|
||||
|
||||
it('resolves at once: no wait before the first render', () => {
|
||||
expect(typeof resolveSessionTag('account-a')).toBe('string')
|
||||
})
|
||||
|
||||
it('reads a tampered record as none', async () => {
|
||||
@@ -85,6 +100,18 @@ describe('resolveSessionTag', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('the sweep of flags keyed by an account id (older shape)', () => {
|
||||
it('removes them on start and keeps the flags of a tag', () => {
|
||||
const older = 'faunosteo:editor:left-draft:S:account-a'
|
||||
const mine = leftDraftKey({ sheetId: 'S', tag: 'a'.repeat(32) })
|
||||
sessionStorage.setItem(older, '{}')
|
||||
sessionStorage.setItem(mine, '{}')
|
||||
startSessionTagSync()()
|
||||
expect(sessionStorage.getItem(older)).toBeNull()
|
||||
expect(sessionStorage.getItem(mine)).not.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('forgetSessionTag and the sign-out', () => {
|
||||
it('rotates the tag of the same account and clears its flags', async () => {
|
||||
const old = await resolveSessionTag('account-a')
|
||||
|
||||
Reference in new issue
Block a user