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

+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() {