fix(editor): Task 8 round 1, sync tag, cascaded leave ask
This commit is contained in:
1 parent
07bebbc855
commit
579d8afff4
10 files changed
+358
-82
No files matched your search
@@ -42,13 +42,18 @@ async function open(page: Page) {
|
|||||||
await page.goto('/app/admin')
|
await page.goto('/app/admin')
|
||||||
await stepUpAdmin(page, dict, actor.secret)
|
await stepUpAdmin(page, dict, actor.secret)
|
||||||
await page.goto(overviewPath(seed.sheetId))
|
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
|
await page
|
||||||
.getByRole('link', { name: dict['admin.overview.open_draft'] })
|
.getByRole('link', { name: dict['admin.overview.open_draft'] })
|
||||||
.click()
|
.click()
|
||||||
await expect(
|
await expect(
|
||||||
page.getByRole('heading', { level: 1, name: draftTitle(dict) }),
|
page.getByRole('heading', { level: 1, name: draftTitle(dict) }),
|
||||||
).toBeVisible()
|
).toBeVisible()
|
||||||
return seed.sheetId
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The history menu's jump to the last entry of the overview, several entries back. */
|
/** 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),
|
(url) => url.pathname === overviewPath(sheetId),
|
||||||
)
|
)
|
||||||
expect(await leftFlags(page)).toBe(0)
|
expect(await leftFlags(page)).toBe(0)
|
||||||
await page
|
await reopenDraft(page)
|
||||||
.getByRole('link', { name: dict['admin.overview.open_draft'] })
|
|
||||||
.click()
|
|
||||||
await expect(
|
|
||||||
page.getByRole('heading', { level: 1, name: draftTitle(dict) }),
|
|
||||||
).toBeVisible()
|
|
||||||
await expect(page.getByText(leftNotice)).toHaveCount(0)
|
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),
|
(url) => url.pathname === overviewPath(sheetId),
|
||||||
)
|
)
|
||||||
expect(await leftFlags(page)).toBe(0)
|
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
|
* The editor of the signed-in account's session tag (criterion 22), resolved at once;
|
||||||
* known nothing is restored or written (fail closed); another tag is another editor.
|
* nobody signed in, no editor. Another tag is another editor.
|
||||||
*/
|
*/
|
||||||
export default function EditorWorkspace(props: Props) {
|
export default function EditorWorkspace(props: Props) {
|
||||||
const tag = useSessionTag()
|
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
|
* forced close (the element vanished) goes ahead and says the draft was dropped
|
||||||
* (BDR-115); a form with nothing typed says nothing.
|
* (BDR-115); a form with nothing typed says nothing.
|
||||||
* `askToLeave` is the form's own « Annuler ». The browser's unload is guarded too.
|
* `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
|
* A history jump out of the editor held for this question (criterion 23) is what
|
||||||
* what `discard` carries out; « Continuer la saisie » drops it.
|
* `discard` carries on (the next dirty layer asks, or the jump goes); « Continuer la
|
||||||
|
* saisie » drops it.
|
||||||
*/
|
*/
|
||||||
export function useDirtyGuard(
|
export function useDirtyGuard(
|
||||||
guards: Guards,
|
guards: Guards,
|
||||||
@@ -43,8 +44,12 @@ export function useDirtyGuard(
|
|||||||
guards.holdLeave(null)
|
guards.holdLeave(null)
|
||||||
setConfirming(null)
|
setConfirming(null)
|
||||||
},
|
},
|
||||||
/** « Abandonner »: the held leave when there is one, else `close`. */
|
/** « Abandonner »: the leave held for this layer when there is one, else `close`. */
|
||||||
discard: (close: () => void) => () => (guards.takeLeave() ?? 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 { create } from 'zustand'
|
||||||
import { useAuthStore } from '@/state/authStore'
|
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
|
* 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
|
* 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
|
* tab's sessionStorage with a fingerprint of the account id, reused only for the account
|
||||||
* account whose digest it holds, and rotated on sign-out and on any other account (the
|
* whose fingerprint it holds, and rotated on sign-out and on any other account (the flags
|
||||||
* flags of the old tag cleared). A storage that refuses, or no digest (an insecure
|
* of the old tag cleared). Resolved at once, on any origin (http included). A storage
|
||||||
* origin), keeps it in memory only: a reload then restores nothing.
|
* that refuses keeps it in memory only: a reload then restores nothing.
|
||||||
*/
|
*/
|
||||||
const STORAGE_KEY = 'faunosteo:editor:session-tag'
|
const STORAGE_KEY = 'faunosteo:editor:session-tag'
|
||||||
const TAG_PATTERN = /^[0-9a-f]{32}$/
|
const TAG_PATTERN = /^[0-9a-f]{32}$/
|
||||||
const DIGEST_PATTERN = /^[0-9a-f]{64}$/
|
const FINGERPRINT_PATTERN = /^[0-9a-f]{16}$/
|
||||||
|
|
||||||
interface TagRecord {
|
interface TagRecord {
|
||||||
tag: string
|
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
|
account: string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,14 +36,21 @@ const hex = (bytes: Uint8Array) =>
|
|||||||
|
|
||||||
const randomTag = () => hex(crypto.getRandomValues(new Uint8Array(16)))
|
const randomTag = () => hex(crypto.getRandomValues(new Uint8Array(16)))
|
||||||
|
|
||||||
/** The digest of the account id, or null where the browser offers none. */
|
const FNV_OFFSET = 0xcbf29ce484222325n
|
||||||
async function digestOf(user: string): Promise<string | null> {
|
const FNV_PRIME = 0x100000001b3n
|
||||||
try {
|
const MASK_64 = 0xffffffffffffffffn
|
||||||
const data = new TextEncoder().encode(user)
|
|
||||||
return hex(new Uint8Array(await crypto.subtle.digest('SHA-256', data)))
|
/**
|
||||||
} catch {
|
* FNV-1a 64 of the account id, hex. An equality check binding the tag to one account,
|
||||||
return null
|
* 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 {
|
function isTagRecord(raw: unknown): raw is TagRecord {
|
||||||
@@ -53,7 +60,7 @@ function isTagRecord(raw: unknown): raw is TagRecord {
|
|||||||
typeof tag === 'string' &&
|
typeof tag === 'string' &&
|
||||||
TAG_PATTERN.test(tag) &&
|
TAG_PATTERN.test(tag) &&
|
||||||
typeof account === 'string' &&
|
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 {
|
function hold(next: HeldTag): string {
|
||||||
useSessionTagStore.setState({ held: next })
|
useSessionTagStore.setState({ held: next })
|
||||||
if (next.account) writeStored({ tag: next.tag, account: next.account })
|
writeStored({ tag: next.tag, account: next.account })
|
||||||
return next.tag
|
return next.tag
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The tag of `user` in this tab: the kept one when its digest matches, else a new one. */
|
/** The tag of `user` in this tab: the kept one when its fingerprint matches, else a new one. */
|
||||||
export async function resolveSessionTag(user: string): Promise<string> {
|
export function resolveSessionTag(user: string): 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.
|
|
||||||
const held = useSessionTagStore.getState().held
|
const held = useSessionTagStore.getState().held
|
||||||
if (held?.user === user) return held.tag
|
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 })
|
if (kept && kept.account === account) return hold({ ...kept, user })
|
||||||
retire(kept, held)
|
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. */
|
/** 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 })
|
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 {
|
export function startSessionTagSync(): () => void {
|
||||||
|
sweepAccountFlags()
|
||||||
return useAuthStore.subscribe((state, previous) => {
|
return useAuthStore.subscribe((state, previous) => {
|
||||||
const user = state.user?.id
|
const user = state.user?.id
|
||||||
if (user === previous.user?.id) return
|
if (user === previous.user?.id) return
|
||||||
if (user) void resolveSessionTag(user)
|
if (user) resolveSessionTag(user)
|
||||||
else forgetSessionTag()
|
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 {
|
export function useSessionTag(): string | null {
|
||||||
const user = useAuthStore((s) => s.user?.id ?? null)
|
const user = useAuthStore((s) => s.user?.id ?? null)
|
||||||
const held = useSessionTagStore((s) => s.held)
|
return useMemo(() => (user ? resolveSessionTag(user) : null), [user])
|
||||||
useEffect(() => {
|
|
||||||
if (user) void resolveSessionTag(user)
|
|
||||||
}, [user])
|
|
||||||
return user && held?.user === user ? held.tag : null
|
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useCallback, useEffect, useRef } from 'react'
|
import { useCallback, useEffect, useRef } from 'react'
|
||||||
import { useLocation } from 'react-router-dom'
|
import { useLocation } from 'react-router-dom'
|
||||||
import { topDirtyLayer } from '../leftDraft'
|
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). */
|
/** The part of a Navigation API `navigate` event this guard reads (not in the DOM types). */
|
||||||
interface NavigateEventLike extends Event {
|
interface NavigateEventLike extends Event {
|
||||||
@@ -40,21 +40,49 @@ interface Watch {
|
|||||||
passing: { current: string | null }
|
passing: { current: string | null }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** « Abandonner » after a held jump: the same jump, let through this time. */
|
interface Jump {
|
||||||
function jumpTo(api: NavigationLike, key: string, watch: Watch): void {
|
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
|
watch.passing.current = key
|
||||||
const failed = () => {
|
const failed = () => {
|
||||||
watch.passing.current = null
|
watch.passing.current = null
|
||||||
|
keep()
|
||||||
}
|
}
|
||||||
const { committed, finished } = api.traverseTo(key)
|
const { committed, finished } = api.traverseTo(key)
|
||||||
committed.catch(failed)
|
committed.catch(() => undefined)
|
||||||
finished.catch(failed)
|
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
|
* 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 ? »
|
* lets the page cancel it; the dirty dialogs ask, top down, before it goes.
|
||||||
* and holds the jump for its « Abandonner ».
|
|
||||||
*/
|
*/
|
||||||
function onNavigate(api: NavigationLike, event: NavigateEventLike, w: Watch) {
|
function onNavigate(api: NavigationLike, event: NavigateEventLike, w: Watch) {
|
||||||
if (!leavesEditor(event, w.path)) return
|
if (!leavesEditor(event, w.path)) return
|
||||||
@@ -63,14 +91,13 @@ function onNavigate(api: NavigationLike, event: NavigateEventLike, w: Watch) {
|
|||||||
const layer = topDirtyLayer(w.guards)
|
const layer = topDirtyLayer(w.guards)
|
||||||
if (!layer) return
|
if (!layer) return
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
w.guards.ask(layer, false)
|
askLeave({ api, key, watch: w }, layer)
|
||||||
w.guards.holdLeave(() => jumpTo(api, key, w))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Confirmation before a history jump of several entries leaves the editor with a dirty
|
* 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 (criterion 23): where the Navigation API can cancel it, the jump waits for each
|
||||||
* dialog's own question; elsewhere (no API, a jump the browser will not let the page
|
* 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
|
* 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.
|
* 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. */
|
/** The top layer first: the dialog the user was typing in when they left. */
|
||||||
const LAYERS_TOP_DOWN: readonly LayerName[] = ['reference', 'finding']
|
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 =>
|
* The top layer whose form holds changes, or the first one under `below`; a forced ask
|
||||||
LAYERS_TOP_DOWN.find((l) => guards.ask(l, true).note) ?? null
|
* 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 {
|
function storage(): Storage | null {
|
||||||
try {
|
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:
|
* 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
|
* 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. */
|
/** The layers asked top down; one refusal refuses, and each one still shows its own. */
|
||||||
askAll: (forced: boolean) => LeaveAnswer
|
askAll: (forced: boolean) => LeaveAnswer
|
||||||
/**
|
/**
|
||||||
* A leave of the editor held while the top dirty layer asks (criterion 23): its
|
* A leave of the editor held while a dirty layer asks (criterion 23): that layer's
|
||||||
* « Abandonner » runs it. Any later user ask, or a layer going, drops it.
|
* « Abandonner » carries it on. Any later user ask, or the asking layer going, drops it.
|
||||||
*/
|
*/
|
||||||
holdLeave: (leave: (() => void) | null) => void
|
holdLeave: (leave: HeldLeave | null) => void
|
||||||
/** The held leave, taken once; null when none is held. */
|
/** The leave held for `layer`, taken once; null when none is held for it. */
|
||||||
takeLeave: () => (() => void) | null
|
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. */
|
/** The leave a layer's « Abandonner » would carry out, held while it asks. */
|
||||||
function useHeldLeave() {
|
function useHeldLeave() {
|
||||||
const held = useRef<(() => void) | null>(null)
|
const held = useRef<HeldLeave | null>(null)
|
||||||
return useMemo(
|
return useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
holdLeave: (leave: (() => void) | null) => {
|
holdLeave: (leave: HeldLeave | null) => {
|
||||||
held.current = leave
|
held.current = leave
|
||||||
},
|
},
|
||||||
takeLeave: () => {
|
takeLeave: (layer: LayerName) => {
|
||||||
const leave = held.current
|
const leave = held.current?.layer === layer ? held.current : null
|
||||||
held.current = null
|
if (leave) held.current = null
|
||||||
return leave
|
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 guards.get(layer)?.(forced) ?? { allowed: true }
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
...leave,
|
holdLeave: leave.holdLeave,
|
||||||
|
takeLeave: leave.takeLeave,
|
||||||
register: (layer, guard) => {
|
register: (layer, guard) => {
|
||||||
if (guard) guards.set(layer, guard)
|
if (guard) guards.set(layer, guard)
|
||||||
else guards.delete(layer)
|
else guards.delete(layer)
|
||||||
if (!guard) leave.holdLeave(null)
|
if (!guard) leave.dropFor(layer)
|
||||||
},
|
},
|
||||||
ask,
|
ask,
|
||||||
askAll: (forced) => {
|
askAll: (forced) => {
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import {
|
|||||||
resolveSessionTag,
|
resolveSessionTag,
|
||||||
} from '@/editor/history/sessionTag'
|
} from '@/editor/history/sessionTag'
|
||||||
import { useCitationDraft } from '@/editor/findings/citationDraft'
|
import { useCitationDraft } from '@/editor/findings/citationDraft'
|
||||||
|
import { useAuthStore } from '@/state/authStore'
|
||||||
import { useLocaleStore } from '@/state/localeStore'
|
import { useLocaleStore } from '@/state/localeStore'
|
||||||
import { edit, insert } from '../helpers/editorFixtures'
|
import { edit, insert } from '../helpers/editorFixtures'
|
||||||
import { defaultView } from '@/editor/navigation'
|
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 openFinding(user, /Node A/)
|
||||||
await modify(user)
|
await modify(user)
|
||||||
await user.type(nameField(), ' bis')
|
await user.type(nameField(), ' bis')
|
||||||
act(() => forgetSessionTag())
|
act(() => {
|
||||||
|
forgetSessionTag()
|
||||||
|
useAuthStore.setState({ user: null })
|
||||||
|
})
|
||||||
await waitFor(() => expect(findingDialog()).toBeNull())
|
await waitFor(() => expect(findingDialog()).toBeNull())
|
||||||
const flags = Object.keys(sessionStorage).filter((k) =>
|
const flags = Object.keys(sessionStorage).filter((k) =>
|
||||||
k.startsWith('faunosteo:editor:left-draft:'),
|
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. */
|
/** 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 url = new URL(pathname, window.location.origin).href
|
||||||
const event = Object.assign(new Event('navigate', { cancelable }), {
|
const event = Object.assign(new Event('navigate', { cancelable }), {
|
||||||
navigationType: 'traverse',
|
navigationType: 'traverse',
|
||||||
destination: { url, key, sameDocument: true },
|
destination: { url, key, sameDocument },
|
||||||
})
|
})
|
||||||
act(() => {
|
act(() => {
|
||||||
api.dispatchEvent(event)
|
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()
|
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 () => {
|
it('a traversal inside the editor, or a clean dialog, is left alone', async () => {
|
||||||
const user = await mount()
|
const user = await mount()
|
||||||
await openFinding(user, /Node A/)
|
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', () => {
|
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')
|
const tag = await resolveSessionTag('account-a')
|
||||||
expect(tag).toMatch(/^[0-9a-f]{32}$/)
|
expect(tag).toMatch(/^[0-9a-f]{32}$/)
|
||||||
const record = stored()
|
const record = stored()
|
||||||
expect(record?.tag).toBe(tag)
|
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')
|
expect(sessionStorage.getItem(STORAGE_KEY)).not.toContain('account-a')
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -69,12 +69,27 @@ describe('resolveSessionTag', () => {
|
|||||||
expect(await resolveSessionTag('account-a')).not.toBe(tag)
|
expect(await resolveSessionTag('account-a')).not.toBe(tag)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('keeps the tag in memory when no digest is available', async () => {
|
it('works without crypto.subtle (http): kept on reload, rotated per account', () => {
|
||||||
vi.spyOn(crypto.subtle, 'digest').mockRejectedValue(new Error('insecure'))
|
const subtle = Object.getOwnPropertyDescriptor(crypto, 'subtle')
|
||||||
const tag = await resolveSessionTag('account-a')
|
Object.defineProperty(crypto, 'subtle', {
|
||||||
|
value: undefined,
|
||||||
|
configurable: true,
|
||||||
|
})
|
||||||
|
try {
|
||||||
|
const tag = resolveSessionTag('account-a')
|
||||||
expect(tag).toMatch(/^[0-9a-f]{32}$/)
|
expect(tag).toMatch(/^[0-9a-f]{32}$/)
|
||||||
expect(stored()).toBeNull()
|
expect(sessionStorage.getItem(STORAGE_KEY)).not.toContain('account-a')
|
||||||
expect(await resolveSessionTag('account-a')).toBe(tag)
|
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 () => {
|
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', () => {
|
describe('forgetSessionTag and the sign-out', () => {
|
||||||
it('rotates the tag of the same account and clears its flags', async () => {
|
it('rotates the tag of the same account and clears its flags', async () => {
|
||||||
const old = await resolveSessionTag('account-a')
|
const old = await resolveSessionTag('account-a')
|
||||||
|
|||||||
Reference in new issue
Block a user