feat(editor): session tag in history, confirm before leaving

This commit is contained in:
bchanot committed 2026-11-14 14:47:43 +01:00
1 parent 4018344ffc
commit 07bebbc855
19 files changed
+844 -76

No files matched your search

@@ -0,0 +1,163 @@
import { fr } from '@/i18n/fr'
import type { BrowserContext, Page, TestInfo } from '@playwright/test'
import { stepUpAdmin } from '../support/admin'
import { expect, test } from '../support/browser'
import { dropLateReplays, routeToSandbox } from '../support/sandbox'
import { signIn } from '../support/shell'
import {
draftPath,
draftTitle,
editorActor,
findingDialog,
openFinding,
openTab,
referenceDialog,
seedDraft,
standardShape,
startReference,
} from '../support/editor'
// R2 UX finish, task 8 (criteria 22, 23): a jump of several entries in the browser's
// history (the history menu) that leaves the editor while a dialog holds changes asks
// « Abandonner les modifications ? » before anything is lost. Chromium's Navigation API
// lets the page cancel it; the jump is the history menu's own (CDP
// Page.navigateToHistoryEntry: page.goBack() waits for a commit that never comes once
// cancelled). The entries carry a session tag, never the account id.
const dict = fr
const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
const overviewPath = (sheetId: string) => `/app/admin/sheets/${sheetId}`
const confirmText = dict['editor.findings.discard_ask']
const leftNotice = dict['editor.leave.draft_dropped']
/**
* The overview, then the draft through its link: one document, so the jump back to the
* overview is a same-document traversal the page can cancel.
*/
async function open(page: Page) {
const actor = await editorActor('fr')
const seed = await seedDraft(actor, { shape: standardShape })
await signIn(page, actor.account, dict)
await page.goto('/app/admin')
await stepUpAdmin(page, dict, actor.secret)
await page.goto(overviewPath(seed.sheetId))
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. */
async function jumpToOverview(
context: BrowserContext,
page: Page,
sheetId: string,
) {
const cdp = await context.newCDPSession(page)
const { entries, currentIndex } = await cdp.send('Page.getNavigationHistory')
const target = entries
.slice(0, currentIndex)
.filter((e) => new URL(e.url).pathname === overviewPath(sheetId))
.pop()
if (!target) throw new Error('no overview entry in the history')
expect(currentIndex - entries.indexOf(target)).toBeGreaterThan(1)
await cdp.send('Page.navigateToHistoryEntry', { entryId: target.id })
await cdp.detach()
}
const leftFlags = (page: Page) =>
page.evaluate(
() =>
Object.keys(sessionStorage).filter((k) =>
k.startsWith('faunosteo:editor:left-draft:'),
).length,
)
test.describe('leaving the editor by a history jump', () => {
test.use({ locale: 'fr-FR', actionTimeout: 15_000 })
test.beforeEach(async ({ context }, info) => {
test.skip(isPhone(info), 'editing needs 1 024 px') // floor-guard: allow C16 editing needs >= 1024 px; the guard is the same at every width
await routeToSandbox(context)
})
test.afterEach(async ({ context }) => {
await dropLateReplays(context)
})
test('a dirty finding dialog asks first, then keeps it or goes', async ({
page,
context,
}) => {
test.setTimeout(150_000)
const sheetId = await open(page)
await openFinding(page, dict, 'Dysfonction A')
const dialog = findingDialog(page)
await dialog
.getByRole('button', { name: dict['editor.findings.edit'], exact: true })
.click()
const name = dialog.getByLabel(dict['editor.general.name_fr'])
await name.fill('Dysfonction brouillon')
const entry = await page.evaluate(() => history.state?.usr?.editorEntry)
expect(entry?.tag).toMatch(/^[0-9a-f]{32}$/)
expect(Object.keys(entry ?? {})).not.toContain('userId')
await jumpToOverview(context, page, sheetId)
await expect(dialog.getByText(confirmText)).toBeVisible()
expect(new URL(page.url()).pathname).toBe(draftPath(sheetId))
await dialog
.getByRole('button', { name: dict['editor.findings.keep_typing'] })
.click()
await expect(name).toHaveValue('Dysfonction brouillon')
expect(new URL(page.url()).pathname).toBe(draftPath(sheetId))
await jumpToOverview(context, page, sheetId)
await expect(dialog.getByText(confirmText)).toBeVisible()
await dialog
.getByRole('button', { name: dict['editor.findings.discard'] })
.click()
await expect(page).toHaveURL(
(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 expect(page.getByText(leftNotice)).toHaveCount(0)
})
test('a dirty reference dialog asks the same before the jump goes', async ({
page,
context,
}) => {
test.setTimeout(150_000)
const sheetId = await open(page)
await openTab(page, dict, 'references')
await startReference(page, dict)
const form = referenceDialog(page)
await form.locator('#reference-form-type').selectOption('manual')
await form.locator('#reference-form-citation').fill('Brouillon')
await jumpToOverview(context, page, sheetId)
await expect(form.getByText(confirmText)).toBeVisible()
expect(new URL(page.url()).pathname).toBe(draftPath(sheetId))
await form
.getByRole('button', { name: dict['editor.findings.keep_typing'] })
.click()
await expect(form.locator('#reference-form-citation')).toHaveValue(
'Brouillon',
)
await jumpToOverview(context, page, sheetId)
await form
.getByRole('button', { name: dict['editor.findings.discard'] })
.click()
await expect(page).toHaveURL(
(url) => url.pathname === overviewPath(sheetId),
)
expect(await leftFlags(page)).toBe(0)
})
})
+7 -1
View File
@@ -1,15 +1,21 @@
import { useEffect, type ReactNode } from 'react'
import { useAuthStore } from '@/state/authStore'
import { startLocaleSync } from '@/services/localeSync'
import { startSessionTagSync } from '@/editor/history/sessionTag'
/** Starts the session subscription and the locale sync for the app lifetime. */
/**
* Starts the session subscription, the locale sync and the editor's session tag (rotated
* on sign-out) for the app lifetime.
*/
export function AuthProvider({ children }: { children: ReactNode }) {
useEffect(() => {
const stopAuth = useAuthStore.getState().start()
const stopSync = startLocaleSync()
const stopTag = startSessionTagSync()
return () => {
stopAuth()
stopSync()
stopTag()
}
}, [])
return <>{children}</>
@@ -1,4 +1,10 @@
import { useEffect, useMemo, useState, type ReactNode } from 'react'
import {
useCallback,
useEffect,
useMemo,
useState,
type ReactNode,
} from 'react'
import { useLocation } from 'react-router-dom'
import type { OfficialSheetAdmin } from '@faunosteo/supabase'
import Notice from '@/components/ui/Notice'
@@ -13,6 +19,8 @@ import {
type HistoryOwner,
} from '@/editor/history/entry'
import useEditorHistory from '@/editor/history/useEditorHistory'
import useLeaveConfirm from '@/editor/history/useLeaveConfirm'
import { useSessionTag, useSessionTagStore } from '@/editor/history/sessionTag'
import { useLeftDraft } from '@/editor/leftDraft'
import { citationsOfView, defaultView } from '@/editor/navigation'
import { findingLayerOf, referenceLayerOf } from '@/editor/findingLayer'
@@ -23,7 +31,6 @@ import {
} from '@/editor/useEditorNavigation'
import type { TabTier } from '@/editor/useViewport'
import { useT } from '@/i18n/useT'
import { useAuthStore } from '@/state/authStore'
import ConflictDialog from './ConflictDialog'
import CopyIssueNotice from './CopyIssueNotice'
import DraftHeader from './DraftHeader'
@@ -124,10 +131,21 @@ function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
)
}
/** The sheet and the account the history entries of this editor belong to. */
function useOwner(sheetId: string): HistoryOwner {
const userId = useAuthStore((s) => s.user?.id ?? '')
return useMemo(() => ({ sheetId, userId }), [sheetId, userId])
/** The sheet and the session tag the history entries of this editor belong to. */
function useOwner(sheetId: string, tag: string): HistoryOwner {
return useMemo(() => ({ sheetId, tag }), [sheetId, tag])
}
/**
* A leave that leaves no left-draft flag: one the user confirmed before a history jump,
* 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)
return useCallback(
() => confirmed() || useSessionTagStore.getState().held?.tag !== tag,
[confirmed, tag],
)
}
/** A reload or a reopened entry shows the view the history kept, never a layer. */
@@ -154,18 +172,19 @@ function useShowRestored(nav: EditorNavigation) {
}
/**
* The navigation of this sheet for this account: the first tab known at mount
* (`initialTab`), the view a kept entry holds, the browser history in step with it, and
* whether the last editor left a dirty dialog behind.
* The navigation of this sheet under this session tag: the first tab known at mount
* (`initialTab`), the view a kept entry holds, the browser history in step with it, the
* confirmation before a history jump leaves with a dirty dialog, and whether the last
* editor left a dirty dialog behind.
*/
function useWorkspaceNavigation(sheetId: string, tier: TabTier) {
function useWorkspaceNavigation(sheetId: string, tier: TabTier, tag: string) {
const previewState = useEditorStore((s) => s.previewState)
const tab = previewState ? initialTab(previewState, tier) : 'annotations'
const owner = useOwner(sheetId)
const owner = useOwner(sheetId, tag)
const nav = useEditorNavigation(tab, useRestoredView(owner))
useEditorHistory(nav, owner, defaultView(tab))
useShowRestored(nav)
return { nav, left: useLeftDraft(nav, owner) }
return { nav, left: useLeftDraft(nav, owner, useUnflagged(nav, tag)) }
}
/** The last editor of this sheet was left with a dirty dialog: said once. */
@@ -180,9 +199,13 @@ function LeftDraftNotice({ shown }: { shown: boolean }) {
* panel and the shown place. Owns the navigation state, so the first tab is known at
* mount and later edits never move the user off their tab.
*/
export default function EditorWorkspace(props: Props) {
function Workspace(props: Props & { tag: string }) {
const { sheet, mode, readOnly } = props
const { nav, left } = useWorkspaceNavigation(sheet.sheet_id, props.tier)
const { nav, left } = useWorkspaceNavigation(
sheet.sheet_id,
props.tier,
props.tag,
)
return (
<EditingState readOnly={readOnly} mode={mode}>
<div className="space-y-4" data-editor-workspace>
@@ -214,3 +237,12 @@ export default function EditorWorkspace(props: Props) {
</EditingState>
)
}
/**
* 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.
*/
export default function EditorWorkspace(props: Props) {
const tag = useSessionTag()
return tag ? <Workspace key={tag} {...props} tag={tag} /> : null
}
@@ -183,7 +183,7 @@ export default function FindingCreateForm(props: FindingCreateFormProps) {
submitLabel={t('editor.findings.create')}
onCancel={() => props.onClose(props.readOnly)}
onKeepTyping={form.guard.keepTyping}
onDiscard={() => props.onClose(true)}
onDiscard={form.guard.discard(() => props.onClose(true))}
/>
</form>
)
@@ -259,7 +259,7 @@ export default function FindingEditForm(props: FindingEditFormProps) {
submitLabel={t('editor.findings.save')}
onCancel={form.cancel}
onKeepTyping={guard.keepTyping}
onDiscard={discard}
onDiscard={guard.discard(discard)}
/>
</form>
)
@@ -13,6 +13,8 @@ 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.
*/
export function useDirtyGuard(
guards: Guards,
@@ -37,7 +39,12 @@ export function useDirtyGuard(
return {
confirming,
askToLeave: () => setConfirming('form'),
keepTyping: () => setConfirming(null),
keepTyping: () => {
guards.holdLeave(null)
setConfirming(null)
},
/** « Abandonner »: the held leave when there is one, else `close`. */
discard: (close: () => void) => () => (guards.takeLeave() ?? close)(),
}
}
@@ -239,7 +239,7 @@ export default function ReferenceForm(props: ReferenceFormProps) {
: props.onClose(props.readOnly)
}
onKeepTyping={guard.keepTyping}
onDiscard={() => props.onClose(true)}
onDiscard={guard.discard(() => props.onClose(true))}
/>
</form>
)
+17 -13
View File
@@ -11,8 +11,9 @@ import { EDITOR_TABS, type EditorTabId } from '../tabs'
/**
* What one browser history entry of the editor holds (R2F-1): the view, the view below
* it (the place a Back returns to), and whose editor wrote it. Navigation only: never
* typed text, a search term or a draft.
* it (the place a Back returns to), and whose editor wrote it: the sheet and the session
* tag (criterion 22), a random label bound to the signed-in account, never its id.
* Navigation only: never typed text, a search term or a draft.
*/
export interface HistoryEntry {
/** Keys the scroll map: one per entry written, kept by a replace. */
@@ -20,13 +21,13 @@ export interface HistoryEntry {
view: EditorView
below: EditorView | null
sheetId: string
userId: string
tag: string
}
/** The sheet and the account an entry may be restored for. */
/** The sheet and the session tag an entry may be restored for. */
export interface HistoryOwner {
sheetId: string
userId: string
tag: string
}
/** The key of the entry inside the router's `location.state`. */
@@ -129,11 +130,14 @@ export function withoutForms(view: EditorView): EditorView {
return sanitizeView(view, false) ?? view
}
/** The entry's id and owner, each a string within the cap, or null. */
/**
* The entry's id and owner, each a string within the cap, or null. An entry of the older
* shape (an account id, no tag) has no owner: it reads as foreign.
*/
function idsOf(raw: Record<string, unknown>) {
const { id, sheetId, userId } = raw
const valid = isId(id) && isId(sheetId) && isId(userId)
return valid ? { id, sheetId, userId } : null
const { id, sheetId, tag } = raw
const valid = isId(id) && isId(sheetId) && isId(tag)
return valid ? { id, sheetId, tag } : null
}
/** The entry `state` (a `location.state`) carries, or null when it carries none. */
@@ -147,15 +151,15 @@ export function readEntry(state: unknown): HistoryEntry | null {
return { ...ids, view, below }
}
/** An entry restores only for the sheet and the account that wrote it. */
/** An entry restores only for the sheet and the session tag that wrote it. */
export function ownedEntry(
state: unknown,
owner: HistoryOwner,
): HistoryEntry | null {
const entry = readEntry(state)
// An empty id is no owner: nobody signed in, no sheet known.
if (!owner.sheetId || !owner.userId) return null
const mine = entry?.sheetId === owner.sheetId && entry.userId === owner.userId
// An empty id is no owner: no tag known yet (fail closed), no sheet known.
if (!owner.sheetId || !owner.tag) return null
const mine = entry?.sheetId === owner.sheetId && entry.tag === owner.tag
return mine ? entry : null
}
+128
View File
@@ -0,0 +1,128 @@
import { useEffect } from 'react'
import { create } from 'zustand'
import { useAuthStore } from '@/state/authStore'
import { clearLeftDrafts } 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.
*/
const STORAGE_KEY = 'faunosteo:editor:session-tag'
const TAG_PATTERN = /^[0-9a-f]{32}$/
const DIGEST_PATTERN = /^[0-9a-f]{64}$/
interface TagRecord {
tag: string
/** The SHA-256 digest (hex) of the account id; empty when none could be made. */
account: string
}
/** The tag in memory, with the account it was resolved for (never written anywhere). */
interface HeldTag extends TagRecord {
user: string
}
/** The tag this page holds: the in-memory copy, and what the editor waits for. */
export const useSessionTagStore = create<{ held: HeldTag | null }>(() => ({
held: null,
}))
const hex = (bytes: Uint8Array) =>
Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')
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
}
}
function isTagRecord(raw: unknown): raw is TagRecord {
if (typeof raw !== 'object' || raw === null) return false
const { tag, account } = raw as Record<string, unknown>
return (
typeof tag === 'string' &&
TAG_PATTERN.test(tag) &&
typeof account === 'string' &&
DIGEST_PATTERN.test(account)
)
}
function readStored(): TagRecord | null {
try {
const raw: unknown = JSON.parse(sessionStorage.getItem(STORAGE_KEY) ?? '0')
return isTagRecord(raw) ? raw : null
} catch {
return null
}
}
function writeStored(record: TagRecord | null): void {
try {
if (record) sessionStorage.setItem(STORAGE_KEY, JSON.stringify(record))
else sessionStorage.removeItem(STORAGE_KEY)
} catch {
// The tag stays in memory only.
}
}
/** Old tags go with the flags left under them. */
function retire(...records: (TagRecord | null)[]): void {
for (const record of records) if (record) clearLeftDrafts(record.tag)
}
function hold(next: HeldTag): string {
useSessionTagStore.setState({ held: next })
if (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.
const held = useSessionTagStore.getState().held
if (held?.user === user) return held.tag
const kept = account ? readStored() : null
if (kept && kept.account === account) return hold({ ...kept, user })
retire(kept, held)
return hold({ tag: randomTag(), account: account ?? '', user })
}
/** Sign-out: the tag goes, with its flags; the next sign-in draws a new one. */
export function forgetSessionTag(): void {
retire(readStored(), useSessionTagStore.getState().held)
writeStored(null)
useSessionTagStore.setState({ held: null })
}
/** Follows the signed-in account for the app's lifetime; returns the unsubscribe. */
export function startSessionTagSync(): () => void {
return useAuthStore.subscribe((state, previous) => {
const user = state.user?.id
if (user === previous.user?.id) return
if (user) void resolveSessionTag(user)
else forgetSessionTag()
})
}
/** The session tag of the signed-in account, or null until it is known (fail closed). */
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
}
@@ -0,0 +1,91 @@
import { useCallback, useEffect, useRef } from 'react'
import { useLocation } from 'react-router-dom'
import { topDirtyLayer } from '../leftDraft'
import type { Guards } from '../useEditorNavigation'
/** The part of a Navigation API `navigate` event this guard reads (not in the DOM types). */
interface NavigateEventLike extends Event {
readonly navigationType: string
readonly destination: {
readonly url: string
readonly key: string
readonly sameDocument: boolean
}
}
interface NavigationLike extends EventTarget {
traverseTo: (key: string) => {
committed: Promise<unknown>
finished: Promise<unknown>
}
}
/** The Navigation API where the browser offers it (Chromium), else null. */
function navigationApi(): NavigationLike | null {
const api = (window as { navigation?: NavigationLike }).navigation
return api && typeof api.traverseTo === 'function' ? api : null
}
/** A jump through this document's history to a page other than the editor. */
function leavesEditor(event: NavigateEventLike, path: string): boolean {
const { navigationType, destination } = event
if (navigationType !== 'traverse' || !destination?.sameDocument) return false
return new URL(destination.url).pathname !== path
}
interface Watch {
guards: Guards
path: string
/** The key of the jump the user confirmed: it passes, and leaves no flag. */
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 {
watch.passing.current = key
const failed = () => {
watch.passing.current = null
}
const { committed, finished } = api.traverseTo(key)
committed.catch(failed)
finished.catch(failed)
}
/**
* 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 ».
*/
function onNavigate(api: NavigationLike, event: NavigateEventLike, w: Watch) {
if (!leavesEditor(event, w.path)) return
const { key } = event.destination
if (w.passing.current === key || !event.cancelable) return
const layer = topDirtyLayer(w.guards)
if (!layer) return
event.preventDefault()
w.guards.ask(layer, false)
w.guards.holdLeave(() => jumpTo(api, key, w))
}
/**
* 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
* 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 {
const { pathname } = useLocation()
const passing = useRef<string | null>(null)
const path = useRef(pathname).current
useEffect(() => {
const api = navigationApi()
if (!api) return
const watch: Watch = { guards, path, passing }
const listener = (event: Event) =>
onNavigate(api, event as NavigateEventLike, watch)
api.addEventListener('navigate', listener)
return () => api.removeEventListener('navigate', listener)
}, [guards, path])
return useCallback(() => passing.current !== null, [])
}
+49 -17
View File
@@ -1,21 +1,26 @@
import { useEffect, useRef, useState } from 'react'
import type { HistoryOwner } from './history/entry'
import type { NavigationState } from './navigation'
import type { EditorNavigation, LayerName } from './useEditorNavigation'
import type { EditorNavigation, Guards, LayerName } from './useEditorNavigation'
/**
* A dirty dialog lost when the editor goes (a Back of several entries, BDR-078: a Back
* cannot be refused, and a draft is never stored). One flag in this tab's sessionStorage
* says so to the next mount of the same sheet for the same account (criterion 17).
* A dirty dialog lost when the editor goes (a Back of several entries the browser does
* not let the page cancel, BDR-078; a draft is never stored). One flag in this tab's
* sessionStorage says so to the next mount of the same sheet under the same session tag
* (criteria 17, 22).
*/
const PREFIX = 'faunosteo:editor:left-draft:'
export const leftDraftKey = ({ sheetId, userId }: HistoryOwner) =>
`${PREFIX}${sheetId}:${userId}`
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']
/** 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
function storage(): Storage | null {
try {
return typeof sessionStorage === 'undefined' ? null : sessionStorage
@@ -37,11 +42,17 @@ function elementOf(state: NavigationState, layer: LayerName): unknown {
return 'key' in finding ? finding.key : finding.create.parent
}
/** Called as the editor goes: a layer whose form holds changes leaves the flag. */
function flagIfDirty(owner: HistoryOwner, nav: EditorNavigation): void {
if (!owner.sheetId || !owner.userId) return
// A forced ask has no side effect: a dirty form answers with its note.
const layer = LAYERS_TOP_DOWN.find((l) => nav.guards.ask(l, true).note)
/**
* Called as the editor goes: a layer whose form holds changes leaves the flag, unless
* the leave is one that leaves none (`confirmed`: see `useLeftDraft`).
*/
function flagIfDirty(
owner: HistoryOwner,
nav: EditorNavigation,
confirmed: boolean,
): void {
if (!owner.sheetId || !owner.tag || confirmed) return
const layer = topDirtyLayer(nav.guards)
if (!layer) return
const flag = { kind: layer, key: elementOf(nav.state, layer) }
try {
@@ -68,21 +79,42 @@ function clearFlag(owner: HistoryOwner): void {
}
}
/** Clears the flags of every sheet left under `tag` (a tag rotated, criterion 22). */
export function clearLeftDrafts(tag: string): void {
try {
const store = storage()
if (!store || !tag) return
const keys = Array.from({ length: store.length }, (_, i) => store.key(i))
const mine = keys.filter(
(k) => k?.startsWith(PREFIX) && k.endsWith(`:${tag}`),
)
for (const key of mine) if (key) store.removeItem(key)
} catch {
// A blocked storage holds no flag to clear.
}
}
/**
* Whether the last editor of this sheet and account left with a dirty dialog: shown once,
* then cleared. The editor's own cleanup runs before its dialogs' (a deleted tree is
* cleaned up from its root), so their guards still answer when it flags.
* 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
* tree is cleaned up from its root), so their guards still answer when it flags.
* `confirmed` tells a leave that leaves no flag: one the user confirmed (« Abandonner »
* before a history jump), or one under a session tag already rotated.
*/
export function useLeftDraft(
nav: EditorNavigation,
owner: HistoryOwner,
confirmed: () => boolean,
): boolean {
const latest = useRef(nav)
latest.current = nav
const latest = useRef({ nav, confirmed })
latest.current = { nav, confirmed }
const [left] = useState(() => readFlag(owner))
useEffect(() => {
clearFlag(owner)
return () => flagIfDirty(owner, latest.current)
return () => {
const { nav: last, confirmed: asked } = latest.current
flagIfDirty(owner, last, asked())
}
}, [owner])
return left
}
+34 -3
View File
@@ -64,6 +64,13 @@ export interface Guards {
ask: (layer: LayerName, forced: boolean) => LeaveAnswer
/** 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.
*/
holdLeave: (leave: (() => void) | null) => void
/** The held leave, taken once; null when none is held. */
takeLeave: () => (() => void) | null
}
/**
@@ -189,16 +196,40 @@ function useLiveRegion() {
return { live, announce }
}
/** The leave a layer's « Abandonner » would carry out, held while it asks. */
function useHeldLeave() {
const held = useRef<(() => void) | null>(null)
return useMemo(
() => ({
holdLeave: (leave: (() => void) | null) => {
held.current = leave
},
takeLeave: () => {
const leave = held.current
held.current = null
return leave
},
}),
[],
)
}
/** The guards of the open layers, keyed by layer so a re-registration keeps its place. */
function useGuards(): Guards {
const guards = useRef(new Map<LayerName, CanLeave>()).current
const leave = useHeldLeave()
return useMemo(() => {
const ask = (layer: LayerName, forced: boolean): LeaveAnswer =>
guards.get(layer)?.(forced) ?? { allowed: true }
const ask = (layer: LayerName, forced: boolean): LeaveAnswer => {
// A user ask is a new question: a leave held before it is no longer what is asked.
if (!forced) leave.holdLeave(null)
return guards.get(layer)?.(forced) ?? { allowed: true }
}
return {
...leave,
register: (layer, guard) => {
if (guard) guards.set(layer, guard)
else guards.delete(layer)
if (!guard) leave.holdLeave(null)
},
ask,
askAll: (forced) => {
@@ -208,7 +239,7 @@ function useGuards(): Guards {
return { allowed: answers.every((a) => a.allowed), note }
},
}
}, [guards])
}, [guards, leave])
}
function useMoveTrace() {
+2
View File
@@ -45,6 +45,8 @@ export const testLayer: FindingLayer = {
register: () => undefined,
ask: () => ({ allowed: true }),
askAll: () => ({ allowed: true }),
holdLeave: () => undefined,
takeLeave: () => null,
},
open: () => undefined,
start: () => undefined,
@@ -11,6 +11,10 @@ import {
import userEvent from '@testing-library/user-event'
import type { Location, NavigateFunction } from 'react-router-dom'
import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry'
import {
forgetSessionTag,
resolveSessionTag,
} from '@/editor/history/sessionTag'
import { useCitationDraft } from '@/editor/findings/citationDraft'
import { useLocaleStore } from '@/state/localeStore'
import { edit, insert } from '../helpers/editorFixtures'
@@ -51,7 +55,12 @@ const written = () =>
(location.state as Record<string, HistoryEntry> | null)?.[ENTRY_KEY]
const back = () => act(async () => navigate(-1))
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
/** The session tag of USER in this tab: entries and flags carry it (criterion 22). */
let TAG: string
beforeEach(async () => {
useLocaleStore.setState({ locale: 'fr' })
TAG = await resolveSessionTag(USER)
})
afterEach(() => {
cleanup()
resetStore()
@@ -485,7 +494,7 @@ describe('read-only flip and the gone rule', () => {
view,
below: null,
sheetId: SHEET,
userId: USER,
tag: TAG,
},
}
mountDraft({ probe, entries: [{ pathname: path, state }] })
@@ -515,7 +524,7 @@ describe('read-only flip and the gone rule', () => {
view,
below: null,
sheetId: SHEET,
userId: USER,
tag: TAG,
},
}
mountDraft({ probe, entries: [{ pathname: path, state }] })
@@ -586,7 +595,7 @@ describe('final review: the zone of a new category is part of the draft (criteri
})
describe('final review: leaving the editor with a dirty dialog (criterion 17)', () => {
const flagKey = `faunosteo:editor:left-draft:${SHEET}:${USER}`
const flagKey = () => `faunosteo:editor:left-draft:${SHEET}:${TAG}`
const notice =
"Une saisie non enregistrée a été abandonnée en quittant l'éditeur"
@@ -596,7 +605,7 @@ describe('final review: leaving the editor with a dirty dialog (criterion 17)',
await modify(user)
await user.type(nameField(), ' bis')
cleanup()
const flag = sessionStorage.getItem(flagKey)
const flag = sessionStorage.getItem(flagKey())
expect(flag).not.toBeNull()
expect(flag).not.toContain('bis')
expect(JSON.parse(flag!)).toEqual({
@@ -605,17 +614,133 @@ describe('final review: leaving the editor with a dirty dialog (criterion 17)',
})
await mount()
expect(screen.getByText(notice)).toBeVisible()
expect(sessionStorage.getItem(flagKey)).toBeNull()
expect(sessionStorage.getItem(flagKey())).toBeNull()
cleanup()
await mount()
expect(screen.queryByText(notice)).toBeNull()
})
it('a sign-out leaves no flag under the tag it rotated', async () => {
const user = await mount()
await openFinding(user, /Node A/)
await modify(user)
await user.type(nameField(), ' bis')
act(() => forgetSessionTag())
await waitFor(() => expect(findingDialog()).toBeNull())
const flags = Object.keys(sessionStorage).filter((k) =>
k.startsWith('faunosteo:editor:left-draft:'),
)
expect(flags).toEqual([])
})
it('a clean dialog leaves no flag', async () => {
const user = await mount()
await openFinding(user, /Node A/)
cleanup()
expect(sessionStorage.getItem(flagKey)).toBeNull()
expect(sessionStorage.getItem(flagKey())).toBeNull()
})
})
/** The Navigation API as the 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 of several entries out of the editor (criterion 23)', () => {
const flagKey = () => `faunosteo:editor:left-draft:${SHEET}:${TAG}`
const notice =
"Une saisie non enregistrée a été abandonnée en quittant l'éditeur"
let api: NavigationStub
beforeEach(() => {
api = new NavigationStub()
Object.defineProperty(window, 'navigation', {
value: api,
configurable: true,
})
})
afterEach(() => {
Reflect.deleteProperty(window, 'navigation')
})
/** A history jump to `pathname`, as Chromium dispatches it before it commits. */
function traverse(pathname: string, key: string, cancelable = 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 },
})
act(() => {
api.dispatchEvent(event)
})
return event
}
async function dirtyDialog() {
const user = await mount()
await openFinding(user, /Node A/)
await modify(user)
await user.type(nameField(), ' bis')
return user
}
it('is cancelled and asks first; « Continuer la saisie » keeps the draft', async () => {
const user = await dirtyDialog()
const jump = traverse('/app/admin/sheets', 'list')
expect(jump.defaultPrevented).toBe(true)
expect(inDialog().getByText('Abandonner les modifications ?')).toBeVisible()
await user.click(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
)
expect(nameField()).toHaveValue('Node A bis')
expect(api.traverseTo).not.toHaveBeenCalled()
expect(sessionStorage.getItem(flagKey())).toBeNull()
})
it('« Abandonner » goes to the destination, with no notice afterwards', async () => {
const user = await dirtyDialog()
traverse('/app/admin/sheets', 'list')
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
expect(api.traverseTo).toHaveBeenCalledWith('list')
expect(traverse('/app/admin/sheets', 'list').defaultPrevented).toBe(false)
cleanup()
expect(sessionStorage.getItem(flagKey())).toBeNull()
await mount()
expect(screen.queryByText(notice)).toBeNull()
})
it('« Abandonner » after « Continuer la saisie » closes the dialog only', async () => {
const user = await dirtyDialog()
traverse('/app/admin/sheets', 'list')
await user.click(
inDialog().getByRole('button', { name: 'Continuer la saisie' }),
)
await user.click(inDialog().getByRole('button', { name: 'Annuler' }))
await user.click(inDialog().getByRole('button', { name: 'Abandonner' }))
expect(api.traverseTo).not.toHaveBeenCalled()
expect(findingDialog()).not.toBeNull()
})
it('a jump that cannot be cancelled keeps the notice after the fact', async () => {
await dirtyDialog()
expect(traverse('/app/admin/sheets', 'list', false).defaultPrevented).toBe(
false,
)
expect(screen.queryByText('Abandonner les modifications ?')).toBeNull()
cleanup()
expect(sessionStorage.getItem(flagKey())).not.toBeNull()
})
it('a traversal inside the editor, or a clean dialog, is left alone', async () => {
const user = await mount()
await openFinding(user, /Node A/)
expect(traverse('/app/admin/sheets', 'list').defaultPrevented).toBe(false)
await modify(user)
await user.type(nameField(), ' bis')
expect(traverse(path, 'inside').defaultPrevented).toBe(false)
expect(screen.queryByText('Abandonner les modifications ?')).toBeNull()
})
})
@@ -844,6 +844,8 @@ describe('the category form zone line (N1 review, C46)', () => {
register: vi.fn(),
ask: () => ({ allowed: true }),
askAll: () => ({ allowed: true }),
holdLeave: () => undefined,
takeLeave: () => null,
}}
onCreated={vi.fn()}
onClose={vi.fn()}
@@ -29,7 +29,7 @@ const entry = (patch: Partial<HistoryEntry> = {}): HistoryEntry => ({
view: view('general'),
below: null,
sheetId: 'S',
userId: 'U',
tag: 'T',
...patch,
})
const stateOf = (value: unknown) => ({ [ENTRY_KEY]: value })
@@ -145,19 +145,34 @@ describe('readEntry and ownership', () => {
expect(readEntry(stateOf({ ...entry(), view: 'x' }))).toBeNull()
})
it('restores only for the sheet and the account that wrote it', () => {
const mine = { sheetId: 'S', userId: 'U' }
it('restores only for the sheet and the session tag that wrote it', () => {
const mine = { sheetId: 'S', tag: 'T' }
expect(ownedEntry(stateOf(entry()), mine)).not.toBeNull()
expect(ownedEntry(stateOf(entry()), { ...mine, sheetId: 'T' })).toBeNull()
expect(ownedEntry(stateOf(entry()), { ...mine, userId: 'V' })).toBeNull()
expect(ownedEntry(stateOf(entry()), { ...mine, sheetId: 'X' })).toBeNull()
expect(ownedEntry(stateOf(entry()), { ...mine, tag: 'V' })).toBeNull()
})
it('refuses an owner without a sheet or an account', () => {
const blank = entry({ sheetId: '', userId: '' })
expect(ownedEntry(stateOf(blank), { sheetId: '', userId: '' })).toBeNull()
expect(
ownedEntry(stateOf(entry()), { sheetId: 'S', userId: '' }),
).toBeNull()
it('refuses an owner without a sheet or a tag: no tag yet restores nothing', () => {
const blank = entry({ sheetId: '', tag: '' })
expect(ownedEntry(stateOf(blank), { sheetId: '', tag: '' })).toBeNull()
expect(ownedEntry(stateOf(entry()), { sheetId: 'S', tag: '' })).toBeNull()
})
it('reads an entry of the older shape (an account id, no tag) as foreign', () => {
const { id, view, below, sheetId } = entry()
const older = { id, view, below, sheetId, userId: 'T' }
expect(readEntry(stateOf(older))).toBeNull()
expect(ownedEntry(stateOf(older), { sheetId: 'S', tag: 'T' })).toBeNull()
})
it('never writes an account id in the entry', () => {
expect(Object.keys(readEntry(stateOf(entry()))!).sort()).toEqual([
'below',
'id',
'sheetId',
'tag',
'view',
])
})
it('keeps only navigation: nothing typed survives the read', () => {
@@ -362,11 +377,11 @@ describe('final review: read-back values are capped', () => {
const onFindings = (key: ElementKey) =>
view('findings', { finding: { key, citations: false } })
it('drops an entry whose id, sheet or account is over 128 characters', () => {
it('drops an entry whose id, sheet or tag is over 128 characters', () => {
expect(readEntry(stateOf(entry({ id: atCap })))).not.toBeNull()
expect(readEntry(stateOf(entry({ id: long })))).toBeNull()
expect(readEntry(stateOf(entry({ sheetId: long })))).toBeNull()
expect(readEntry(stateOf(entry({ userId: long })))).toBeNull()
expect(readEntry(stateOf(entry({ tag: long })))).toBeNull()
})
it('drops a key with an over-long id or a path deeper than the tree allows', () => {
@@ -29,7 +29,7 @@ import { useLocaleStore } from '@/state/localeStore'
afterEach(cleanup)
const owner = { sheetId: 'S', userId: 'U' }
const owner = { sheetId: 'S', tag: 'T' }
const finding: ElementKey = {
kind: 'finding',
zone_id: 'zone',
+21 -3
View File
@@ -10,6 +10,7 @@ import {
import userEvent from '@testing-library/user-event'
import type { Location, NavigateFunction } from 'react-router-dom'
import { ENTRY_KEY, type HistoryEntry } from '@/editor/history/entry'
import { resolveSessionTag } from '@/editor/history/sessionTag'
import { defaultView } from '@/editor/navigation'
import { useLocaleStore } from '@/state/localeStore'
import { emptyText } from '../helpers/editorFixtures'
@@ -48,12 +49,15 @@ const foreign = (patch: Partial<HistoryEntry>) => ({
view: defaultView('findings'),
below: null,
sheetId: SHEET,
userId: USER,
tag: TAG,
...patch,
},
})
beforeEach(() => {
/** The session tag of USER in this tab (criterion 22). */
let TAG: string
beforeEach(async () => {
TAG = await resolveSessionTag(USER)
useLocaleStore.setState({ locale: 'fr' })
serverHas(emptyText(), 3, false)
})
@@ -75,7 +79,7 @@ describe('mount', () => {
expect(written()?.view.tab).toBe(tabs[selected()])
expect(written()).toMatchObject({
sheetId: SHEET,
userId: USER,
tag: TAG,
below: null,
})
})
@@ -110,6 +114,20 @@ describe('mount', () => {
expect(selected()).not.toBe('Constats')
expect(written()?.id).not.toBe('old')
})
it('an entry of another session tag, or of the older shape, is foreign', async () => {
const older = foreign({}) as Record<string, Record<string, unknown>>
older[ENTRY_KEY] = { ...older[ENTRY_KEY], tag: undefined, userId: USER }
for (const state of [foreign({ tag: '0'.repeat(32) }), older]) {
mountDraft({ probe, entries: [{ pathname: path, state }] })
await ready()
await waitFor(() => expect(written()?.tag).toBe(TAG))
expect(selected()).not.toBe('Constats')
expect(written()?.id).not.toBe('old')
expect(JSON.stringify(written())).not.toContain(USER)
cleanup()
}
})
})
describe('tab and section moves', () => {
@@ -0,0 +1,112 @@
/** Criterion 22: the session tag the history entries and the left-draft flag carry. */
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
forgetSessionTag,
resolveSessionTag,
startSessionTagSync,
useSessionTagStore,
} from '@/editor/history/sessionTag'
import { leftDraftKey } from '@/editor/leftDraft'
import { useAuthStore } from '@/state/authStore'
const STORAGE_KEY = 'faunosteo:editor:session-tag'
const stored = () =>
JSON.parse(sessionStorage.getItem(STORAGE_KEY) ?? 'null') as {
tag: string
account: string
} | null
/** A new page load of this tab: the memory goes, the tab's storage stays. */
const reload = () => useSessionTagStore.setState({ held: null })
afterEach(() => {
vi.restoreAllMocks()
reload()
sessionStorage.clear()
useAuthStore.setState({ user: null })
})
describe('resolveSessionTag', () => {
it('draws a 128-bit hex tag, stored with the account digest, 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(sessionStorage.getItem(STORAGE_KEY)).not.toContain('account-a')
})
it('reuses the tag for the same account, after a reload too', async () => {
const tag = await resolveSessionTag('account-a')
expect(await resolveSessionTag('account-a')).toBe(tag)
reload()
expect(await resolveSessionTag('account-a')).toBe(tag)
})
it('rotates on another account and clears the flags of the old tag', async () => {
const old = await resolveSessionTag('account-a')
const flag = leftDraftKey({ sheetId: 'S', tag: old })
sessionStorage.setItem(flag, '{}')
reload()
const tag = await resolveSessionTag('account-b')
expect(tag).not.toBe(old)
expect(sessionStorage.getItem(flag)).toBeNull()
reload()
expect(await resolveSessionTag('account-a')).not.toBe(old)
})
it('keeps the tag in memory when the storage refuses: a reload restores nothing', async () => {
vi.spyOn(sessionStorage, 'getItem').mockImplementation(() => {
throw new Error('blocked')
})
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
throw new Error('blocked')
})
const tag = await resolveSessionTag('account-a')
expect(tag).toMatch(/^[0-9a-f]{32}$/)
expect(await resolveSessionTag('account-a')).toBe(tag)
reload()
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('reads a tampered record as none', async () => {
sessionStorage.setItem(STORAGE_KEY, '{"tag":"x","account":"y"}')
const tag = await resolveSessionTag('account-a')
expect(tag).toMatch(/^[0-9a-f]{32}$/)
expect(stored()?.tag).toBe(tag)
})
})
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')
const flag = leftDraftKey({ sheetId: 'S', tag: old })
sessionStorage.setItem(flag, '{}')
forgetSessionTag()
expect(stored()).toBeNull()
expect(sessionStorage.getItem(flag)).toBeNull()
expect(await resolveSessionTag('account-a')).not.toBe(old)
})
it('follows the account: a sign-out forgets, a sign-in resolves', async () => {
const stop = startSessionTagSync()
useAuthStore.setState({ user: { id: 'account-a' } as never })
await vi.waitFor(() =>
expect(useSessionTagStore.getState().held?.tag).toMatch(/^[0-9a-f]{32}$/),
)
const old = useSessionTagStore.getState().held!.tag
useAuthStore.setState({ user: null })
expect(useSessionTagStore.getState().held).toBeNull()
expect(stored()).toBeNull()
stop()
expect(await resolveSessionTag('account-a')).not.toBe(old)
})
})