fix(editor): a sign-out with a dirty dialog is said at the next sign-in
This commit is contained in:
1 parent
7ecaf1998e
commit
28e298ac56
4 files changed
+178
-53
No files matched your search
@@ -1,10 +1,4 @@
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react'
|
||||
import { 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'
|
||||
@@ -21,7 +15,7 @@ import {
|
||||
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 { useLeftDraft, type LeaveFacts } from '@/editor/leftDraft'
|
||||
import { citationsOfView, defaultView } from '@/editor/navigation'
|
||||
import { findingLayerOf, referenceLayerOf } from '@/editor/findingLayer'
|
||||
import { initialTab } from '@/editor/tabs'
|
||||
@@ -31,6 +25,7 @@ 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'
|
||||
@@ -131,20 +126,35 @@ function Places({ nav, readOnly, reloadSheet }: PlacesProps) {
|
||||
)
|
||||
}
|
||||
|
||||
/** The signed-in account's session tag, and its id (kept in memory only). */
|
||||
interface Who {
|
||||
tag: string
|
||||
account: string
|
||||
}
|
||||
|
||||
/** 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.
|
||||
* How this editor leaves, for its left-draft flag: a leave the user confirmed before a
|
||||
* history jump leaves none; one under a tag already rotated (a sign-out, a session
|
||||
* ending) leaves it keyed by the account, so its next sign-in in this tab is told.
|
||||
*/
|
||||
function useUnflagged(nav: EditorNavigation, tag: string) {
|
||||
function useLeaveFacts(
|
||||
nav: EditorNavigation,
|
||||
tag: string,
|
||||
account: string,
|
||||
): LeaveFacts {
|
||||
const confirmed = useLeaveConfirm(nav)
|
||||
return useCallback(
|
||||
() => confirmed() || useSessionTagStore.getState().held?.tag !== tag,
|
||||
[confirmed, tag],
|
||||
return useMemo(
|
||||
() => ({
|
||||
confirmed,
|
||||
rotated: () => useSessionTagStore.getState().held?.tag !== tag,
|
||||
account,
|
||||
}),
|
||||
[confirmed, tag, account],
|
||||
)
|
||||
}
|
||||
|
||||
@@ -177,14 +187,15 @@ function useShowRestored(nav: EditorNavigation) {
|
||||
* 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, tag: string) {
|
||||
function useWorkspaceNavigation(sheetId: string, tier: TabTier, who: Who) {
|
||||
const previewState = useEditorStore((s) => s.previewState)
|
||||
const tab = previewState ? initialTab(previewState, tier) : 'annotations'
|
||||
const owner = useOwner(sheetId, tag)
|
||||
const owner = useOwner(sheetId, who.tag)
|
||||
const nav = useEditorNavigation(tab, useRestoredView(owner))
|
||||
useEditorHistory(nav, owner, defaultView(tab))
|
||||
useShowRestored(nav)
|
||||
return { nav, left: useLeftDraft(nav, owner, useUnflagged(nav, tag)) }
|
||||
const leave = useLeaveFacts(nav, who.tag, who.account)
|
||||
return { nav, left: useLeftDraft(nav, owner, leave) }
|
||||
}
|
||||
|
||||
/** The last editor of this sheet was left with a dirty dialog: said once. */
|
||||
@@ -199,12 +210,12 @@ 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.
|
||||
*/
|
||||
function Workspace(props: Props & { tag: string }) {
|
||||
function Workspace(props: Props & Who) {
|
||||
const { sheet, mode, readOnly } = props
|
||||
const { nav, left } = useWorkspaceNavigation(
|
||||
sheet.sheet_id,
|
||||
props.tier,
|
||||
props.tag,
|
||||
props,
|
||||
)
|
||||
return (
|
||||
<EditingState readOnly={readOnly} mode={mode}>
|
||||
@@ -244,5 +255,7 @@ function Workspace(props: Props & { tag: string }) {
|
||||
*/
|
||||
export default function EditorWorkspace(props: Props) {
|
||||
const tag = useSessionTag()
|
||||
return tag ? <Workspace key={tag} {...props} tag={tag} /> : null
|
||||
const account = useAuthStore((s) => s.user?.id ?? null)
|
||||
if (!tag || !account) return null
|
||||
return <Workspace key={tag} {...props} tag={tag} account={account} />
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { HistoryOwner } from './history/entry'
|
||||
import { fingerprintOf, randomHex } from './history/fingerprint'
|
||||
import type { NavigationState } from './navigation'
|
||||
import type { EditorNavigation, Guards, LayerName } from './useEditorNavigation'
|
||||
|
||||
@@ -7,10 +8,18 @@ import type { EditorNavigation, Guards, LayerName } from './useEditorNavigation'
|
||||
* 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).
|
||||
* (criteria 17, 22). A sign-out, or a session ending, rotates the tag first: the flag is
|
||||
* then keyed by the account, salted (see `ACCOUNT_PREFIX`).
|
||||
*/
|
||||
const PREFIX = 'faunosteo:editor:left-draft:'
|
||||
|
||||
/**
|
||||
* Flags left as the tag rotated, keyed by sheet and by a fingerprint of the account
|
||||
* salted with a random value stored in the record: the same account's next sign-in in
|
||||
* this tab recomputes the key, another account never matches, and no raw id is stored.
|
||||
*/
|
||||
const ACCOUNT_PREFIX = 'faunosteo:editor:left-draft-account:'
|
||||
|
||||
export const leftDraftKey = ({ sheetId, tag }: HistoryOwner) =>
|
||||
`${PREFIX}${sheetId}:${tag}`
|
||||
|
||||
@@ -51,19 +60,22 @@ 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, 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
|
||||
/** What a flag holds: the layer and the element it showed, never any text. */
|
||||
interface Flag {
|
||||
kind: LayerName
|
||||
key: unknown
|
||||
}
|
||||
|
||||
/** The flag of the top dirty layer, or null when no form holds changes. */
|
||||
function dirtyFlag(nav: EditorNavigation): Flag | null {
|
||||
const layer = topDirtyLayer(nav.guards)
|
||||
if (!layer) return
|
||||
const flag = { kind: layer, key: elementOf(nav.state, layer) }
|
||||
return layer && { kind: layer, key: elementOf(nav.state, layer) }
|
||||
}
|
||||
|
||||
/** Called as the editor goes under its tag: a dirty layer leaves the tag's flag. */
|
||||
function flagIfDirty(owner: HistoryOwner, nav: EditorNavigation): void {
|
||||
const flag = owner.sheetId && owner.tag ? dirtyFlag(nav) : null
|
||||
if (!flag) return
|
||||
try {
|
||||
storage()?.setItem(leftDraftKey(owner), JSON.stringify(flag))
|
||||
} catch {
|
||||
@@ -71,6 +83,70 @@ function flagIfDirty(
|
||||
}
|
||||
}
|
||||
|
||||
const accountKey = (sheetId: string, account: string, salt: string) =>
|
||||
`${ACCOUNT_PREFIX}${sheetId}:${fingerprintOf(`${salt}:${account}`)}`
|
||||
|
||||
/** The salt a stored account flag holds, or null when the record is no such flag. */
|
||||
function saltOf(raw: string | null): string | null {
|
||||
try {
|
||||
const record: unknown = JSON.parse(raw ?? 'null')
|
||||
const salt = (record as { salt?: unknown } | null)?.salt
|
||||
return typeof salt === 'string' ? salt : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** The keys of the account flags of `sheetId` that belong to `account`. */
|
||||
function accountFlags(store: Storage, sheetId: string, account: string) {
|
||||
const keys = Array.from({ length: store.length }, (_, i) => store.key(i))
|
||||
return keys.filter((key): key is string => {
|
||||
if (!key?.startsWith(`${ACCOUNT_PREFIX}${sheetId}:`)) return false
|
||||
const salt = saltOf(store.getItem(key))
|
||||
return salt !== null && key === accountKey(sheetId, account, salt)
|
||||
})
|
||||
}
|
||||
|
||||
/** Removes the account's flags of `sheetId`; true when there was one. */
|
||||
function takeAccountFlags(sheetId: string, account: string): boolean {
|
||||
try {
|
||||
const store = storage()
|
||||
const mine = store ? accountFlags(store, sheetId, account) : []
|
||||
for (const key of mine) store?.removeItem(key)
|
||||
return mine.length > 0
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** Called as the editor goes after its tag rotated: one flag, keyed by the account. */
|
||||
function flagForAccount(
|
||||
sheetId: string,
|
||||
account: string,
|
||||
nav: EditorNavigation,
|
||||
) {
|
||||
const flag = sheetId && account ? dirtyFlag(nav) : null
|
||||
if (!flag) return
|
||||
takeAccountFlags(sheetId, account)
|
||||
const salt = randomHex(16)
|
||||
try {
|
||||
const record = JSON.stringify({ salt, ...flag })
|
||||
storage()?.setItem(accountKey(sheetId, account, salt), record)
|
||||
} catch {
|
||||
// A full or blocked storage: the leave goes unsaid.
|
||||
}
|
||||
}
|
||||
|
||||
/** True when an account flag of `sheetId` is there; read once per mount. */
|
||||
function hasAccountFlag(sheetId: string, account: string): boolean {
|
||||
try {
|
||||
const store = storage()
|
||||
return !!store && accountFlags(store, sheetId, account).length > 0
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** True when the flag is there; read once per mount. */
|
||||
function readFlag(owner: HistoryOwner): boolean {
|
||||
try {
|
||||
@@ -121,27 +197,48 @@ export function sweepAccountFlags(): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** How the editor leaves, as its cleanup reads it. */
|
||||
export interface LeaveFacts {
|
||||
/** A leave the user confirmed (« Abandonner » before a history jump): no flag. */
|
||||
confirmed: () => boolean
|
||||
/** The tag was rotated (a sign-out, a session ending, another account). */
|
||||
rotated: () => boolean
|
||||
/** The account the tag was resolved for: kept in memory, stored salted only. */
|
||||
account: string
|
||||
}
|
||||
|
||||
/** The flag the editor leaves as it goes, by how it leaves (`LeaveFacts`). */
|
||||
function flagOnLeave(
|
||||
owner: HistoryOwner,
|
||||
nav: EditorNavigation,
|
||||
leave: LeaveFacts,
|
||||
) {
|
||||
if (leave.confirmed()) return
|
||||
if (leave.rotated()) flagForAccount(owner.sheetId, leave.account, nav)
|
||||
else flagIfDirty(owner, nav)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Whether the last editor of this sheet under this session tag, or of this account
|
||||
* before its tag rotated, 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.
|
||||
*/
|
||||
export function useLeftDraft(
|
||||
nav: EditorNavigation,
|
||||
owner: HistoryOwner,
|
||||
confirmed: () => boolean,
|
||||
leave: LeaveFacts,
|
||||
): boolean {
|
||||
const latest = useRef({ nav, confirmed })
|
||||
latest.current = { nav, confirmed }
|
||||
const [left] = useState(() => readFlag(owner))
|
||||
const latest = useRef({ nav, leave })
|
||||
latest.current = { nav, leave }
|
||||
const { account } = leave
|
||||
const [left] = useState(
|
||||
() => readFlag(owner) || hasAccountFlag(owner.sheetId, account),
|
||||
)
|
||||
useEffect(() => {
|
||||
clearFlag(owner)
|
||||
return () => {
|
||||
const { nav: last, confirmed: asked } = latest.current
|
||||
flagIfDirty(owner, last, asked())
|
||||
}
|
||||
}, [owner])
|
||||
takeAccountFlags(owner.sheetId, account)
|
||||
return () => flagOnLeave(owner, latest.current.nav, latest.current.leave)
|
||||
}, [owner, account])
|
||||
return left
|
||||
}
|
||||
@@ -105,6 +105,8 @@ export interface MountOptions {
|
||||
entries?: InitialEntry[]
|
||||
/** Called on every render with the router's navigate and location: Back, Forward, state. */
|
||||
probe?: (navigate: NavigateFunction, location: Location) => void
|
||||
/** The signed-in account's id (default: USER). */
|
||||
user?: string
|
||||
}
|
||||
|
||||
/** Hands the router to a test: MemoryRouter listens to no popstate, a test calls navigate(-1). */
|
||||
@@ -119,7 +121,7 @@ export function mountDraft(options: MountOptions = {}) {
|
||||
useLocaleStore.setState({ locale: 'fr' })
|
||||
useLeaveGuardStore.setState({ armed: false })
|
||||
useAuthStore.setState({
|
||||
user: { id: USER } as never,
|
||||
user: { id: options.user ?? USER } as never,
|
||||
catalogGrants: options.grants ?? [grant('sheet_editor')],
|
||||
catalogGrantsStatus: options.grantsStatus ?? 'ready',
|
||||
roles: options.roles ?? ['admin'],
|
||||
|
||||
@@ -621,7 +621,7 @@ describe('final review: leaving the editor with a dirty dialog (criterion 17)',
|
||||
expect(screen.queryByText(notice)).toBeNull()
|
||||
})
|
||||
|
||||
it('a sign-out leaves no flag under the tag it rotated', async () => {
|
||||
it('a sign-out with a dirty dialog is said once to the same account, never to another', async () => {
|
||||
const user = await mount()
|
||||
await openFinding(user, /Node A/)
|
||||
await modify(user)
|
||||
@@ -631,10 +631,23 @@ describe('final review: leaving the editor with a dirty dialog (criterion 17)',
|
||||
useAuthStore.setState({ user: null })
|
||||
})
|
||||
await waitFor(() => expect(findingDialog()).toBeNull())
|
||||
const flags = Object.keys(sessionStorage).filter((k) =>
|
||||
k.startsWith('faunosteo:editor:left-draft:'),
|
||||
)
|
||||
expect(flags).toEqual([])
|
||||
const values = Object.keys(sessionStorage).map((k) => k + sessionStorage[k])
|
||||
expect(values.join()).not.toContain('bis')
|
||||
expect(values.join()).not.toContain(USER)
|
||||
cleanup()
|
||||
serverHas(sheetText(), 3)
|
||||
mountDraft({ width: 1280, probe, user: 'user-2' })
|
||||
await screen.findByRole('heading', {
|
||||
level: 1,
|
||||
name: 'Brouillon, version 4',
|
||||
})
|
||||
expect(screen.queryByText(notice)).toBeNull()
|
||||
cleanup()
|
||||
await mount()
|
||||
expect(screen.getByText(notice)).toBeVisible()
|
||||
cleanup()
|
||||
await mount()
|
||||
expect(screen.queryByText(notice)).toBeNull()
|
||||
})
|
||||
|
||||
it('a clean dialog leaves no flag', async () => {
|
||||
|
||||
Reference in new issue
Block a user