feat(app): editor store, undo, recovery copy and geometry accept rules
This commit is contained in:
1 parent
f7e7bf4ee1
commit
7f1d44065b
20 files changed
+2538
-5
No files matched your search
@@ -0,0 +1,44 @@
|
||||
import { fetchDrawing, type DrawingFetch } from '@/catalogue/catalogue'
|
||||
import { coreFailure, type CatalogueFailure } from '@/catalogue/failure'
|
||||
import type { CataloguePreview } from '@/catalogue/preview'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import type { DrawingEntry } from './editorTypes'
|
||||
|
||||
export interface Attached {
|
||||
held: DrawingEntry[]
|
||||
failures: Record<string, CatalogueFailure>
|
||||
}
|
||||
|
||||
/** Adds each downloaded drawing to the handle; a refusal becomes that drawing's state. */
|
||||
export function attachDrawings(
|
||||
preview: CataloguePreview,
|
||||
fetched: readonly DrawingFetch[],
|
||||
): Attached {
|
||||
const attached: Attached = { held: [], failures: {} }
|
||||
for (const item of fetched) {
|
||||
if (!item.ok) {
|
||||
attached.failures[item.assetId] = item.failure
|
||||
continue
|
||||
}
|
||||
const added = preview.addDrawing(item.drawing)
|
||||
if (added.ok) {
|
||||
attached.held.push({ asset_id: item.drawing.assetId, sha256: item.drawing.sha256 })
|
||||
} else {
|
||||
attached.failures[item.drawing.assetId] = coreFailure(added.kind)
|
||||
}
|
||||
}
|
||||
return attached
|
||||
}
|
||||
|
||||
|
||||
/** The listed drawings the handle lacks, each settled alone. */
|
||||
export async function fetchMissing(
|
||||
held: readonly DrawingEntry[],
|
||||
listed: readonly DrawingEntry[],
|
||||
): Promise<DrawingFetch[]> {
|
||||
const client = getSupabaseClient()
|
||||
const have = new Set(held.map((d) => d.asset_id))
|
||||
if (!client) return []
|
||||
const missing = listed.filter((d) => !have.has(d.asset_id))
|
||||
return Promise.all(missing.map((entry) => fetchDrawing(client, entry)))
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { CataloguePreview } from '@/catalogue/preview'
|
||||
import { emptyHistory } from './undo'
|
||||
import type { BlockKind, EditorData, EditorState } from './editorTypes'
|
||||
|
||||
export function initialData(): EditorData {
|
||||
return {
|
||||
session: 0,
|
||||
status: 'idle',
|
||||
failure: null,
|
||||
userId: null,
|
||||
versionId: null,
|
||||
sheetId: null,
|
||||
canEdit: true,
|
||||
preview: null,
|
||||
previewState: null,
|
||||
handleVersion: 0,
|
||||
documentText: '',
|
||||
savedText: '',
|
||||
savedRevision: 0,
|
||||
staleBase: false,
|
||||
unsaved: false,
|
||||
drawings: [],
|
||||
drawingFailures: {},
|
||||
...emptyHistory(),
|
||||
saving: false,
|
||||
submitting: false,
|
||||
reloading: false,
|
||||
saveFailure: null,
|
||||
conflict: null,
|
||||
recovery: 'none',
|
||||
offer: null,
|
||||
refusedKind: null,
|
||||
copyWritten: false,
|
||||
copyIssue: null,
|
||||
otherCopies: [],
|
||||
unusableCopy: false,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a document change cannot run now. A recovery offer, a refused or a restoring copy
|
||||
* block every change at the store level (keyboard shortcuts included).
|
||||
*/
|
||||
export function blockKind(state: EditorState): BlockKind | null {
|
||||
if (state.status !== 'ready' || state.preview === null) return 'not_ready'
|
||||
if (state.recovery !== 'none') return 'recovery.pending'
|
||||
if (!state.canEdit) return 'read_only'
|
||||
if (state.reloading) return 'busy'
|
||||
return null
|
||||
}
|
||||
|
||||
/** The handle of a state that accepts document changes, else the reason it does not. */
|
||||
export function editablePreview(state: EditorState): CataloguePreview | BlockKind {
|
||||
return blockKind(state) ?? state.preview ?? 'not_ready'
|
||||
}
|
||||
|
||||
/** The leave guard is armed while unsaved or while a recovery offer is not answered. */
|
||||
export function leaveGuardArmed(state: EditorData): boolean {
|
||||
return state.unsaved || state.recovery !== 'none'
|
||||
}
|
||||
|
||||
export const canUndo = (state: EditorData): boolean => state.undo.length > 0
|
||||
export const canRedo = (state: EditorData): boolean => state.redo.length > 0
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { EditCommand, PreviewState } from '@faunosteo/core-wasm/types'
|
||||
import type { Acceptance } from '@/catalogue/preview'
|
||||
import { applyEdit } from '../core/editOps'
|
||||
import { sameDocument } from '../core/sameDocument'
|
||||
import { editablePreview } from './editorBase'
|
||||
import type {
|
||||
AddedDrawing,
|
||||
BlockKind,
|
||||
CommitOutcome,
|
||||
EditorState,
|
||||
StoreApi,
|
||||
} from './editorTypes'
|
||||
import { recordCommit, stepBack, stepForward, type History } from './undo'
|
||||
|
||||
function blocked(kind: BlockKind): CommitOutcome<never> {
|
||||
return { ok: false, reason: 'blocked', kind }
|
||||
}
|
||||
|
||||
function historyOf(state: EditorState): History {
|
||||
return { undo: state.undo, redo: state.redo }
|
||||
}
|
||||
|
||||
/** One store update for an accepted replacement of the document. */
|
||||
function replacedPatch(
|
||||
state: EditorState,
|
||||
text: string,
|
||||
next: PreviewState,
|
||||
history: History,
|
||||
): Partial<EditorState> {
|
||||
return {
|
||||
documentText: text,
|
||||
previewState: next,
|
||||
handleVersion: state.handleVersion + 1,
|
||||
unsaved: !sameDocument(text, state.savedText),
|
||||
undo: history.undo,
|
||||
redo: history.redo,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `sheet.edit` → `replaceDocument` → `accept`: nothing is kept (no store change, no
|
||||
* `handleVersion` bump, so no copy write) unless the core and `accept` all agree.
|
||||
*/
|
||||
export function commit<R>(
|
||||
api: StoreApi,
|
||||
command: EditCommand,
|
||||
accept?: (state: PreviewState) => Acceptance<R>,
|
||||
): CommitOutcome<R> {
|
||||
const state = api.get()
|
||||
const preview = editablePreview(state)
|
||||
if (typeof preview === 'string') return blocked(preview)
|
||||
const edited = applyEdit(state.documentText, command)
|
||||
if (!edited.ok) return { ok: false, reason: 'core', failure: edited }
|
||||
const replaced = preview.replaceDocument(edited.value, accept)
|
||||
if (!replaced.ok) return replaced
|
||||
const history = recordCommit(historyOf(state), state.documentText)
|
||||
api.set(replacedPatch(state, edited.value, replaced.state, history))
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
export function stepHistory(api: StoreApi, direction: 'undo' | 'redo'): CommitOutcome {
|
||||
const state = api.get()
|
||||
const preview = editablePreview(state)
|
||||
if (typeof preview === 'string') return blocked(preview)
|
||||
const move = direction === 'undo' ? stepBack : stepForward
|
||||
const step = move(historyOf(state), state.documentText)
|
||||
if (!step) return blocked('empty')
|
||||
const replaced = preview.replaceDocument(step.text)
|
||||
if (!replaced.ok) return replaced
|
||||
api.set(replacedPatch(state, step.text, replaced.state, step.history))
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
/** A drawing the core accepted becomes part of the handle (and of the copy's list). */
|
||||
export function addDrawing(api: StoreApi, drawing: AddedDrawing): CommitOutcome {
|
||||
const state = api.get()
|
||||
const preview = editablePreview(state)
|
||||
if (typeof preview === 'string') return blocked(preview)
|
||||
const added = preview.addDrawing(drawing)
|
||||
if (!added.ok) return { ok: false, reason: 'core', failure: added }
|
||||
const next = preview.state()
|
||||
const entry = { asset_id: drawing.assetId, sha256: drawing.sha256 }
|
||||
const others = state.drawings.filter((d) => d.asset_id !== entry.asset_id)
|
||||
const failures = Object.fromEntries(
|
||||
Object.entries(state.drawingFailures).filter(([id]) => id !== entry.asset_id),
|
||||
)
|
||||
api.set({
|
||||
drawings: [...others, entry],
|
||||
drawingFailures: failures,
|
||||
handleVersion: state.handleVersion + 1,
|
||||
...(next.ok ? { previewState: next.value } : {}),
|
||||
})
|
||||
return { ok: true }
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
import type { PreviewState } from '@faunosteo/core-wasm/types'
|
||||
import type { FaunosteoClient } from '@faunosteo/supabase'
|
||||
import {
|
||||
readVersion,
|
||||
type DrawingFetch,
|
||||
type DraftAnswer,
|
||||
} from '@/catalogue/catalogue'
|
||||
import { coreFailure, type CatalogueFailure } from '@/catalogue/failure'
|
||||
import { CataloguePreview } from '@/catalogue/preview'
|
||||
import { coreRuntime } from '@/core/runtime'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { blockKind, initialData } from './editorBase'
|
||||
import type { Attached } from './drawings'
|
||||
import type {
|
||||
ActionOutcome,
|
||||
ConfirmOption,
|
||||
EditorState,
|
||||
StoreApi,
|
||||
} from './editorTypes'
|
||||
import { attachDrawings } from './drawings'
|
||||
import { detectRecovery } from './recoveryFlow'
|
||||
import { listOtherCopies, removeCopy } from './recovery'
|
||||
import { emptyHistory } from './undo'
|
||||
|
||||
interface Loaded {
|
||||
version: DraftAnswer
|
||||
text: string
|
||||
preview: CataloguePreview
|
||||
state: PreviewState
|
||||
attached: Attached
|
||||
}
|
||||
type LoadResult = { ok: true; loaded: Loaded } | { ok: false; failure: CatalogueFailure }
|
||||
|
||||
/**
|
||||
* A draft handle is built with NO drawing (a draft builds with its drawings missing); each
|
||||
* downloaded drawing is added after, so one bad drawing never blocks authoring.
|
||||
*/
|
||||
async function loadDraft(client: FaunosteoClient, versionId: string): Promise<LoadResult> {
|
||||
const read = await readVersion(client, versionId, { draft: true })
|
||||
if (!read.ok) return read
|
||||
if (!(await coreRuntime().ready())) return { ok: false, failure: 'core_unavailable' }
|
||||
const text = JSON.stringify(read.version.document)
|
||||
const input = {
|
||||
status: read.version.status,
|
||||
document: text,
|
||||
fingerprint: read.version.fingerprint ?? undefined,
|
||||
}
|
||||
const preview = new CataloguePreview(coreRuntime(), input, [])
|
||||
const attached = attachDrawings(preview, read.drawings)
|
||||
const state = preview.state()
|
||||
if (!state.ok) {
|
||||
preview.free()
|
||||
return { ok: false, failure: coreFailure(state.kind) }
|
||||
}
|
||||
const loaded = { version: read.version, text, preview, state: state.value, attached }
|
||||
return { ok: true, loaded }
|
||||
}
|
||||
|
||||
function readyPatch(state: EditorState, loaded: Loaded): Partial<EditorState> {
|
||||
const { version, text } = loaded
|
||||
const recovery = detectRecovery({
|
||||
userId: state.userId ?? '',
|
||||
versionId: state.versionId ?? '',
|
||||
canEdit: state.canEdit,
|
||||
savedText: text,
|
||||
savedRevision: version.revision,
|
||||
})
|
||||
return {
|
||||
status: 'ready',
|
||||
failure: null,
|
||||
sheetId: version.sheet_id,
|
||||
preview: loaded.preview,
|
||||
previewState: loaded.state,
|
||||
handleVersion: 1,
|
||||
documentText: text,
|
||||
savedText: text,
|
||||
savedRevision: version.revision,
|
||||
drawings: loaded.attached.held,
|
||||
drawingFailures: loaded.attached.failures,
|
||||
otherCopies: listOtherCopies(state.userId ?? '', state.versionId ?? ''),
|
||||
...recovery,
|
||||
}
|
||||
}
|
||||
|
||||
async function loadInto(api: StoreApi, session: number): Promise<void> {
|
||||
const client = getSupabaseClient()
|
||||
const versionId = api.get().versionId ?? ''
|
||||
const result: LoadResult = client
|
||||
? await loadDraft(client, versionId)
|
||||
: { ok: false, failure: 'unavailable' }
|
||||
if (api.get().session !== session) {
|
||||
if (result.ok) result.loaded.preview.free()
|
||||
return
|
||||
}
|
||||
api.set(
|
||||
result.ok
|
||||
? readyPatch(api.get(), result.loaded)
|
||||
: { status: 'failed', failure: result.failure },
|
||||
)
|
||||
}
|
||||
|
||||
export function open(
|
||||
api: StoreApi,
|
||||
versionId: string,
|
||||
userId: string,
|
||||
options?: { canEdit?: boolean },
|
||||
): number {
|
||||
const previous = api.get()
|
||||
previous.preview?.free()
|
||||
const session = previous.session + 1
|
||||
api.set({
|
||||
...initialData(),
|
||||
session,
|
||||
status: 'loading',
|
||||
userId,
|
||||
versionId,
|
||||
canEdit: options?.canEdit ?? true,
|
||||
})
|
||||
void loadInto(api, session)
|
||||
return session
|
||||
}
|
||||
|
||||
/** Invalidates the session (late answers are dropped) and frees its handle. */
|
||||
export function close(api: StoreApi): void {
|
||||
const state = api.get()
|
||||
state.preview?.free()
|
||||
api.set({ ...initialData(), session: state.session + 1 })
|
||||
}
|
||||
|
||||
function reloadPatch(state: EditorState, text: string, next: PreviewState, revision: number) {
|
||||
return {
|
||||
documentText: text,
|
||||
savedText: text,
|
||||
savedRevision: revision,
|
||||
staleBase: false,
|
||||
unsaved: false,
|
||||
previewState: next,
|
||||
handleVersion: state.handleVersion + 1,
|
||||
...emptyHistory(),
|
||||
saveFailure: null,
|
||||
conflict: null,
|
||||
copyWritten: false,
|
||||
copyIssue: null,
|
||||
reloading: false,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* « Recharger » (confirmed): the server draft's text and revision from one
|
||||
* `get_sheet_version`, the drawings the handle lacks downloaded and added, both stacks
|
||||
* cleared, the copy removed. A refusal leaves everything, the copy included, as it was.
|
||||
*/
|
||||
export async function reloadServerDraft(
|
||||
api: StoreApi,
|
||||
{ confirmed }: ConfirmOption,
|
||||
): Promise<ActionOutcome> {
|
||||
const state = api.get()
|
||||
const block = blockKind(state)
|
||||
if (block || !state.preview) return { ok: false, reason: 'blocked', kind: block ?? 'not_ready' }
|
||||
if (state.saving || state.submitting) return { ok: false, reason: 'blocked', kind: 'busy' }
|
||||
if (!confirmed) return { ok: false, reason: 'blocked', kind: 'confirmation_required' }
|
||||
const client = getSupabaseClient()
|
||||
if (!client) return { ok: false, reason: 'load', failure: 'unavailable' }
|
||||
api.set({ reloading: true })
|
||||
const have = new Set(state.drawings.map((d) => d.asset_id))
|
||||
const read = await readVersion(client, state.versionId ?? '', { draft: true, have })
|
||||
if (api.get().session !== state.session) {
|
||||
return { ok: false, reason: 'blocked', kind: 'session_changed' }
|
||||
}
|
||||
if (!read.ok) {
|
||||
api.set({ reloading: false })
|
||||
return { ok: false, reason: 'load', failure: read.failure }
|
||||
}
|
||||
return applyReload(api, state, state.preview, read)
|
||||
}
|
||||
|
||||
function applyReload(
|
||||
api: StoreApi,
|
||||
state: EditorState,
|
||||
preview: CataloguePreview,
|
||||
read: { version: DraftAnswer; revision: number; drawings: DrawingFetch[] },
|
||||
): ActionOutcome {
|
||||
const text = JSON.stringify(read.version.document)
|
||||
const replaced = preview.replaceDocument(text)
|
||||
if (!replaced.ok) {
|
||||
api.set({ reloading: false })
|
||||
return replaced.reason === 'core'
|
||||
? { ok: false, reason: 'core', failure: replaced.failure }
|
||||
: { ok: false, reason: 'blocked', kind: 'not_ready' }
|
||||
}
|
||||
const attached = attachDrawings(preview, read.drawings)
|
||||
const next = preview.state()
|
||||
removeCopy(state.userId ?? '', state.versionId ?? '')
|
||||
api.set({
|
||||
...reloadPatch(state, text, next.ok ? next.value : replaced.state, read.revision),
|
||||
drawings: [...state.drawings, ...attached.held],
|
||||
drawingFailures: { ...state.drawingFailures, ...attached.failures },
|
||||
})
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* « Annuler les modifications » (confirmed): back to the saved text; with `staleBase` the
|
||||
* server draft is reloaded instead (the saved text is an older revision's).
|
||||
*/
|
||||
export async function discardChanges(
|
||||
api: StoreApi,
|
||||
option: ConfirmOption,
|
||||
): Promise<ActionOutcome> {
|
||||
const state = api.get()
|
||||
const block = blockKind(state)
|
||||
if (block || !state.preview) return { ok: false, reason: 'blocked', kind: block ?? 'not_ready' }
|
||||
if (!option.confirmed) return { ok: false, reason: 'blocked', kind: 'confirmation_required' }
|
||||
if (state.staleBase) return reloadServerDraft(api, option)
|
||||
const replaced = state.preview.replaceDocument(state.savedText)
|
||||
if (!replaced.ok) {
|
||||
return replaced.reason === 'core'
|
||||
? { ok: false, reason: 'core', failure: replaced.failure }
|
||||
: { ok: false, reason: 'blocked', kind: 'not_ready' }
|
||||
}
|
||||
removeCopy(state.userId ?? '', state.versionId ?? '')
|
||||
api.set(reloadPatch(state, state.savedText, replaced.state, state.savedRevision))
|
||||
return { ok: true }
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import {
|
||||
SheetFailure,
|
||||
classifySheetError,
|
||||
getOfficialSheetAdmin,
|
||||
parseSaveAnswer,
|
||||
saveSheetDraft,
|
||||
submitSheetReview,
|
||||
type FaunosteoClient,
|
||||
type OfficialSheetAdmin,
|
||||
type SheetFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { sameDocument } from '../core/sameDocument'
|
||||
import { blockKind } from './editorBase'
|
||||
import type {
|
||||
BlockKind,
|
||||
Blocked,
|
||||
ConfirmOption,
|
||||
ConflictState,
|
||||
EditorState,
|
||||
SaveOutcome,
|
||||
ServerRefusal,
|
||||
StoreApi,
|
||||
SubmitOutcome,
|
||||
} from './editorTypes'
|
||||
import { removeCopy } from './recovery'
|
||||
|
||||
function blocked(kind: BlockKind): Blocked {
|
||||
return { ok: false, reason: 'blocked', kind }
|
||||
}
|
||||
|
||||
function requireClient(): FaunosteoClient {
|
||||
const client = getSupabaseClient()
|
||||
if (!client) throw new SheetFailure('unavailable')
|
||||
return client
|
||||
}
|
||||
|
||||
function server(error: unknown): ServerRefusal {
|
||||
return { ok: false, reason: 'server', kind: classifySheetError(error) }
|
||||
}
|
||||
|
||||
/** The page's view of the server draft after a `draft_conflict` (plan, C29). */
|
||||
function conflictFrom(admin: OfficialSheetAdmin, state: EditorState): ConflictState {
|
||||
const draft = admin.draft_version
|
||||
if (!draft || draft.version_id !== state.versionId) return { status: 'unknown' }
|
||||
const last = admin.draft_last_save
|
||||
if (!last || last.revision !== draft.revision) {
|
||||
return { status: 'known', revision: draft.revision, lastSave: null }
|
||||
}
|
||||
const byCaller = last.saved_by !== null && last.saved_by.user_id === state.userId
|
||||
const lastSave = { savedAt: last.saved_at, savedBy: last.saved_by, byCaller }
|
||||
return { status: 'known', revision: draft.revision, lastSave }
|
||||
}
|
||||
|
||||
/** Reads the conflict; a failed read or an unparsable answer is the `unknown` variant. */
|
||||
export async function readConflict(api: StoreApi, session: number): Promise<void> {
|
||||
const state = api.get()
|
||||
api.set({ conflict: { status: 'reading' } })
|
||||
let next: ConflictState
|
||||
try {
|
||||
const admin = await getOfficialSheetAdmin(requireClient(), state.sheetId ?? '')
|
||||
next = conflictFrom(admin, state)
|
||||
} catch {
|
||||
next = { status: 'unknown' }
|
||||
}
|
||||
if (api.get().session === session) api.set({ conflict: next })
|
||||
}
|
||||
|
||||
interface Attempt {
|
||||
session: number
|
||||
sentText: string
|
||||
expected: number
|
||||
}
|
||||
|
||||
function applySaved(api: StoreApi, attempt: Attempt, revision: number): SaveOutcome {
|
||||
const state = api.get()
|
||||
if (state.session !== attempt.session) return blocked('session_changed')
|
||||
const unsaved = !sameDocument(state.documentText, attempt.sentText)
|
||||
if (!unsaved) removeCopy(state.userId ?? '', state.versionId ?? '')
|
||||
api.set({
|
||||
saving: false,
|
||||
savedText: attempt.sentText,
|
||||
savedRevision: revision,
|
||||
staleBase: false,
|
||||
unsaved,
|
||||
conflict: null,
|
||||
saveFailure: null,
|
||||
...(unsaved ? {} : { copyWritten: false, copyIssue: null }),
|
||||
})
|
||||
return { ok: true, revision }
|
||||
}
|
||||
|
||||
async function failedSave(
|
||||
api: StoreApi,
|
||||
attempt: Attempt,
|
||||
error: unknown,
|
||||
): Promise<SaveOutcome> {
|
||||
if (api.get().session !== attempt.session) return blocked('session_changed')
|
||||
const kind: SheetFailureKind = classifySheetError(error)
|
||||
// Unchanged content: the saved pair is what was sent, at the revision it was sent against.
|
||||
if (kind === 'draft.unchanged') return applySaved(api, attempt, attempt.expected)
|
||||
api.set({ saving: false, saveFailure: kind })
|
||||
if (kind === 'draft_conflict') await readConflict(api, attempt.session)
|
||||
return { ok: false, reason: 'server', kind }
|
||||
}
|
||||
|
||||
function saveBlock(state: EditorState): BlockKind | null {
|
||||
if (state.saving || state.submitting) return 'busy'
|
||||
return blockKind(state)
|
||||
}
|
||||
|
||||
/** Sends `documentText` as of now; commits made while it is in flight stay unsaved. */
|
||||
async function saveWith(api: StoreApi, expected: number): Promise<SaveOutcome> {
|
||||
const state = api.get()
|
||||
const block = saveBlock(state)
|
||||
if (block) return blocked(block)
|
||||
const attempt = { session: state.session, sentText: state.documentText, expected }
|
||||
api.set({ saving: true, saveFailure: null })
|
||||
try {
|
||||
const args = {
|
||||
version_id: state.versionId ?? '',
|
||||
expected_revision: expected,
|
||||
document: JSON.parse(attempt.sentText),
|
||||
}
|
||||
const answer = parseSaveAnswer(await saveSheetDraft(requireClient(), args))
|
||||
return applySaved(api, attempt, answer.revision)
|
||||
} catch (error) {
|
||||
return failedSave(api, attempt, error)
|
||||
}
|
||||
}
|
||||
|
||||
export function save(api: StoreApi): Promise<SaveOutcome> {
|
||||
return saveWith(api, api.get().savedRevision)
|
||||
}
|
||||
|
||||
/** « Garder ma version » (confirmed): saves against N, the server decides at write time. */
|
||||
export async function keepMine(
|
||||
api: StoreApi,
|
||||
{ confirmed }: ConfirmOption,
|
||||
): Promise<SaveOutcome> {
|
||||
const { conflict } = api.get()
|
||||
if (conflict?.status !== 'known') return blocked('revision_unknown')
|
||||
if (!confirmed) return blocked('confirmation_required')
|
||||
return saveWith(api, conflict.revision)
|
||||
}
|
||||
|
||||
/** Never re-submits by itself: a `draft_conflict` opens the conflict read only. */
|
||||
export async function submit(api: StoreApi, note?: string): Promise<SubmitOutcome> {
|
||||
const state = api.get()
|
||||
const block = saveBlock(state)
|
||||
if (block) return blocked(block)
|
||||
if (state.staleBase) return blocked('stale_base')
|
||||
api.set({ submitting: true })
|
||||
try {
|
||||
const args = {
|
||||
version_id: state.versionId ?? '',
|
||||
expected_revision: state.savedRevision,
|
||||
...(note ? { note } : {}),
|
||||
}
|
||||
const reviewId = await submitSheetReview(requireClient(), args)
|
||||
if (api.get().session !== state.session) return blocked('session_changed')
|
||||
api.set({ submitting: false })
|
||||
return { ok: true, reviewId }
|
||||
} catch (error) {
|
||||
return failedSubmit(api, state.session, error)
|
||||
}
|
||||
}
|
||||
|
||||
async function failedSubmit(
|
||||
api: StoreApi,
|
||||
session: number,
|
||||
error: unknown,
|
||||
): Promise<SubmitOutcome> {
|
||||
if (api.get().session !== session) return blocked('session_changed')
|
||||
api.set({ submitting: false })
|
||||
const refusal = server(error)
|
||||
if (refusal.kind === 'draft_conflict') await readConflict(api, session)
|
||||
return refusal
|
||||
}
|
||||
|
||||
export async function retryConflictRead(api: StoreApi): Promise<void> {
|
||||
const { conflict, session } = api.get()
|
||||
if (conflict && conflict.status !== 'reading') await readConflict(api, session)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { create } from 'zustand'
|
||||
import { addDrawing, commit, stepHistory } from './editorEdit'
|
||||
import { initialData } from './editorBase'
|
||||
import { close, discardChanges, open, reloadServerDraft } from './editorLoad'
|
||||
import { keepMine, retryConflictRead, save, submit } from './editorSave'
|
||||
import type { EditorState, StoreApi } from './editorTypes'
|
||||
import {
|
||||
abandonOtherCopy,
|
||||
copyInputsChanged,
|
||||
ignoreCopy,
|
||||
restoreCopy,
|
||||
syncCopy,
|
||||
} from './recoveryFlow'
|
||||
|
||||
/**
|
||||
* The editor's store: one Zustand store, module-level, state and actions only. The rules
|
||||
* live in the modules beside it (edit, load, save and conflict, recovery, history); every
|
||||
* async continuation checks `session` before it writes (StrictMode runs open → close → open).
|
||||
*/
|
||||
export const useEditorStore = create<EditorState>()((set, get) => {
|
||||
const api: StoreApi = { get, set }
|
||||
return {
|
||||
...initialData(),
|
||||
open: (versionId, userId, options) => open(api, versionId, userId, options),
|
||||
close: () => close(api),
|
||||
setCanEdit: (canEdit) => set({ canEdit }),
|
||||
commit: (command, options) => commit(api, command, options?.accept),
|
||||
undoStep: () => stepHistory(api, 'undo'),
|
||||
redoStep: () => stepHistory(api, 'redo'),
|
||||
addDrawing: (drawing) => addDrawing(api, drawing),
|
||||
discardChanges: (option) => discardChanges(api, option),
|
||||
reloadServerDraft: (option) => reloadServerDraft(api, option),
|
||||
save: () => save(api),
|
||||
keepMine: (option) => keepMine(api, option),
|
||||
submit: (note) => submit(api, note),
|
||||
retryConflictRead: () => retryConflictRead(api),
|
||||
dismissConflict: () => set({ conflict: null }),
|
||||
restoreCopy: () => restoreCopy(api),
|
||||
ignoreCopy: (option) => ignoreCopy(api, option),
|
||||
abandonOtherCopy: (versionId, option) => abandonOtherCopy(api, versionId, option),
|
||||
retryCopyWrite: () => syncCopy(api),
|
||||
}
|
||||
})
|
||||
|
||||
const storeApi: StoreApi = {
|
||||
get: useEditorStore.getState,
|
||||
set: (patch) => useEditorStore.setState(patch),
|
||||
}
|
||||
|
||||
// The copy is written synchronously on each committed change while unsaved.
|
||||
useEditorStore.subscribe((state, previous) => {
|
||||
if (copyInputsChanged(state, previous)) syncCopy(storeApi)
|
||||
})
|
||||
|
||||
export { canRedo, canUndo, leaveGuardArmed } from './editorBase'
|
||||
@@ -0,0 +1,171 @@
|
||||
import type { CoreFailure } from '@faunosteo/core-wasm'
|
||||
import type { EditCommand, PreviewState } from '@faunosteo/core-wasm/types'
|
||||
import type { SheetAdminPerson, SheetFailureKind } from '@faunosteo/supabase'
|
||||
import type { CataloguePreview, Acceptance } from '@/catalogue/preview'
|
||||
import type { CatalogueFailure } from '@/catalogue/failure'
|
||||
import type { HistoryEntry } from './undo'
|
||||
import type { RecoveryCopy, StoredCopyInfo } from './recovery'
|
||||
|
||||
export type EditorStatus = 'idle' | 'loading' | 'ready' | 'failed'
|
||||
export type RecoveryMode = 'none' | 'pending' | 'restoring' | 'refused'
|
||||
|
||||
/** Why an action did not run, never text (the UI phrases it). */
|
||||
export type BlockKind =
|
||||
| 'recovery.pending'
|
||||
| 'not_ready'
|
||||
| 'read_only'
|
||||
| 'busy'
|
||||
| 'empty'
|
||||
| 'confirmation_required'
|
||||
| 'stale_base'
|
||||
| 'revision_unknown'
|
||||
| 'session_changed'
|
||||
|
||||
export interface Blocked {
|
||||
ok: false
|
||||
reason: 'blocked'
|
||||
kind: BlockKind
|
||||
}
|
||||
export interface CoreRefusal {
|
||||
ok: false
|
||||
reason: 'core'
|
||||
failure: CoreFailure
|
||||
}
|
||||
export interface Refused<R> {
|
||||
ok: false
|
||||
reason: 'refused'
|
||||
refusal: R
|
||||
}
|
||||
export interface ServerRefusal {
|
||||
ok: false
|
||||
reason: 'server'
|
||||
kind: SheetFailureKind
|
||||
}
|
||||
export interface LoadRefusal {
|
||||
ok: false
|
||||
reason: 'load'
|
||||
failure: CatalogueFailure
|
||||
}
|
||||
|
||||
export type CommitOutcome<R = never> = { ok: true } | Blocked | CoreRefusal | Refused<R>
|
||||
export type ActionOutcome = { ok: true } | Blocked | CoreRefusal | LoadRefusal
|
||||
export type SaveOutcome = { ok: true; revision: number } | Blocked | ServerRefusal
|
||||
export type SubmitOutcome = { ok: true; reviewId: string } | Blocked | ServerRefusal
|
||||
|
||||
/** A drawing the handle holds. */
|
||||
export interface DrawingEntry {
|
||||
asset_id: string
|
||||
sha256: string
|
||||
}
|
||||
|
||||
/** What the recovery notice shows while `recovery` is `pending`. */
|
||||
export interface RecoveryOffer {
|
||||
revision: number
|
||||
writtenAt: string
|
||||
sheetName: string
|
||||
/** The server revision this session opened on. */
|
||||
serverRevision: number
|
||||
copy: RecoveryCopy
|
||||
}
|
||||
|
||||
export interface ConflictLastSave {
|
||||
savedAt: string
|
||||
savedBy: SheetAdminPerson | null
|
||||
/** `saved_by` is the caller: the dialog says « une autre session de votre compte ». */
|
||||
byCaller: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* `known`: N from `draft_version.revision` of the edited version; `lastSave` only when
|
||||
* `draft_last_save.revision` = N. `unknown`: no « Garder ma version ».
|
||||
*/
|
||||
export type ConflictState =
|
||||
| { status: 'reading' }
|
||||
| { status: 'known'; revision: number; lastSave: ConflictLastSave | null }
|
||||
| { status: 'unknown' }
|
||||
|
||||
export type CopyIssue = 'cap' | 'quota'
|
||||
|
||||
export interface EditorData {
|
||||
/** Session token: bumped by `open` and `close`; every async continuation checks it. */
|
||||
session: number
|
||||
status: EditorStatus
|
||||
failure: CatalogueFailure | null
|
||||
userId: string | null
|
||||
versionId: string | null
|
||||
sheetId: string | null
|
||||
canEdit: boolean
|
||||
preview: CataloguePreview | null
|
||||
/** The last accepted state: the `before` of the next `accept`. */
|
||||
previewState: PreviewState | null
|
||||
/** Bumped by every accepted replacement and added drawing (canvas rebuild signal). */
|
||||
handleVersion: number
|
||||
documentText: string
|
||||
savedText: string
|
||||
savedRevision: number
|
||||
/** The edits started from a revision older than the server's (older-copy restore). */
|
||||
staleBase: boolean
|
||||
unsaved: boolean
|
||||
drawings: DrawingEntry[]
|
||||
drawingFailures: Record<string, CatalogueFailure>
|
||||
undo: HistoryEntry[]
|
||||
redo: HistoryEntry[]
|
||||
saving: boolean
|
||||
submitting: boolean
|
||||
reloading: boolean
|
||||
saveFailure: SheetFailureKind | null
|
||||
conflict: ConflictState | null
|
||||
recovery: RecoveryMode
|
||||
offer: RecoveryOffer | null
|
||||
/** Why `recovery` is `refused`: `unreadable` or the core's closed kind. */
|
||||
refusedKind: string | null
|
||||
/** The last write of the recovery copy succeeded and the copy holds the unsaved work. */
|
||||
copyWritten: boolean
|
||||
copyIssue: CopyIssue | null
|
||||
otherCopies: StoredCopyInfo[]
|
||||
/** A copy exists but this mode cannot use it (left untouched). */
|
||||
unusableCopy: boolean
|
||||
}
|
||||
|
||||
export interface ConfirmOption {
|
||||
confirmed: boolean
|
||||
}
|
||||
|
||||
export interface EditorActions {
|
||||
/** Starts a session and loads the version; returns its token at once. */
|
||||
open(versionId: string, userId: string, options?: { canEdit?: boolean }): number
|
||||
close(): void
|
||||
setCanEdit(canEdit: boolean): void
|
||||
commit<R = never>(
|
||||
command: EditCommand,
|
||||
options?: { accept?: (state: PreviewState) => Acceptance<R> },
|
||||
): CommitOutcome<R>
|
||||
undoStep(): CommitOutcome
|
||||
redoStep(): CommitOutcome
|
||||
addDrawing(drawing: AddedDrawing): CommitOutcome
|
||||
discardChanges(option: ConfirmOption): Promise<ActionOutcome>
|
||||
reloadServerDraft(option: ConfirmOption): Promise<ActionOutcome>
|
||||
save(): Promise<SaveOutcome>
|
||||
keepMine(option: ConfirmOption): Promise<SaveOutcome>
|
||||
submit(note?: string): Promise<SubmitOutcome>
|
||||
retryConflictRead(): Promise<void>
|
||||
dismissConflict(): void
|
||||
restoreCopy(): Promise<ActionOutcome>
|
||||
ignoreCopy(option: ConfirmOption): CommitOutcome
|
||||
abandonOtherCopy(versionId: string, option: ConfirmOption): CommitOutcome
|
||||
retryCopyWrite(): void
|
||||
}
|
||||
|
||||
export interface AddedDrawing {
|
||||
assetId: string
|
||||
sha256: string
|
||||
bytes: Uint8Array
|
||||
}
|
||||
|
||||
export type EditorState = EditorData & EditorActions
|
||||
|
||||
/** What the action modules need of the store (Zustand's `get` and `set`). */
|
||||
export interface StoreApi {
|
||||
get(): EditorState
|
||||
set(patch: Partial<EditorState>): void
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { z } from 'zod'
|
||||
import { writeOrRemove } from '@/state/persistence'
|
||||
|
||||
/**
|
||||
* The local recovery copy (plan « Save, conflict, recovery »): a TEMPORARY copy of the
|
||||
* unsaved draft in this tab's sessionStorage, never a server save. This module is the
|
||||
* storage layer only; when to write, offer or remove is the store's.
|
||||
*/
|
||||
|
||||
export const COPY_PREFIX = 'osteo:sheet-draft:'
|
||||
/** Copies of OTHER versions of the account kept beside the current one. */
|
||||
export const MAX_OTHER_COPIES = 2
|
||||
|
||||
const DocumentObject = z.custom<Record<string, unknown>>(
|
||||
(value) => typeof value === 'object' && value !== null && !Array.isArray(value),
|
||||
)
|
||||
|
||||
const CopySchema = z.object({
|
||||
v: z.literal(1),
|
||||
user_id: z.string(),
|
||||
version_id: z.string(),
|
||||
sheet_id: z.string(),
|
||||
sheet_name: z.string(),
|
||||
revision: z.number().int().nonnegative(),
|
||||
written_at: z.string(),
|
||||
document: DocumentObject,
|
||||
drawings: z.array(z.object({ asset_id: z.string(), sha256: z.string() })),
|
||||
})
|
||||
export type RecoveryCopy = z.infer<typeof CopySchema>
|
||||
|
||||
/** What a copy of another version shows in the cap notice (nulls for an unreadable one). */
|
||||
export interface StoredCopyInfo {
|
||||
versionId: string
|
||||
sheetName: string | null
|
||||
revision: number | null
|
||||
writtenAt: string | null
|
||||
}
|
||||
|
||||
export type StoredCopy =
|
||||
| { kind: 'none' }
|
||||
| { kind: 'unreadable' }
|
||||
| { kind: 'copy'; copy: RecoveryCopy }
|
||||
|
||||
export type WriteResult = 'written' | 'cap' | 'quota'
|
||||
|
||||
export function copyKey(userId: string, versionId: string): string {
|
||||
return `${COPY_PREFIX}${userId}:${versionId}`
|
||||
}
|
||||
|
||||
function storage(): Storage | null {
|
||||
try {
|
||||
return typeof sessionStorage === 'undefined' ? null : sessionStorage
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function parseCopy(raw: string, userId: string, versionId: string): RecoveryCopy | null {
|
||||
try {
|
||||
const parsed = CopySchema.safeParse(JSON.parse(raw))
|
||||
const matches = parsed.success && parsed.data.user_id === userId
|
||||
return matches && parsed.data.version_id === versionId ? parsed.data : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function readCopy(userId: string, versionId: string): StoredCopy {
|
||||
const raw = storage()?.getItem(copyKey(userId, versionId)) ?? null
|
||||
if (raw === null) return { kind: 'none' }
|
||||
const copy = parseCopy(raw, userId, versionId)
|
||||
return copy ? { kind: 'copy', copy } : { kind: 'unreadable' }
|
||||
}
|
||||
|
||||
export function copyExists(userId: string, versionId: string): boolean {
|
||||
return storage()?.getItem(copyKey(userId, versionId)) != null
|
||||
}
|
||||
|
||||
/** The document text of a copy, as the core will read it. */
|
||||
export function copyText(copy: RecoveryCopy): string {
|
||||
return JSON.stringify(copy.document)
|
||||
}
|
||||
|
||||
function keysOf(store: Storage, prefix: string): string[] {
|
||||
const keys: string[] = []
|
||||
for (let i = 0; i < store.length; i += 1) {
|
||||
const key = store.key(i)
|
||||
if (key?.startsWith(prefix)) keys.push(key)
|
||||
}
|
||||
return keys.sort()
|
||||
}
|
||||
|
||||
function infoOf(store: Storage, key: string, userId: string, versionId: string) {
|
||||
const copy = parseCopy(store.getItem(key) ?? '', userId, versionId)
|
||||
return {
|
||||
versionId,
|
||||
sheetName: copy?.sheet_name ?? null,
|
||||
revision: copy?.revision ?? null,
|
||||
writtenAt: copy?.written_at ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
/** The account's copies of other versions; another account's keys never match the prefix. */
|
||||
export function listOtherCopies(userId: string, versionId: string): StoredCopyInfo[] {
|
||||
const store = storage()
|
||||
if (!store) return []
|
||||
const prefix = `${COPY_PREFIX}${userId}:`
|
||||
return keysOf(store, prefix)
|
||||
.map((key) => ({ key, other: key.slice(prefix.length) }))
|
||||
.filter(({ other }) => other !== versionId)
|
||||
.map(({ key, other }) => infoOf(store, key, userId, other))
|
||||
}
|
||||
|
||||
/** Writes the copy unless the cap is reached (nothing is ever evicted) or storage refuses. */
|
||||
export function writeCopy(copy: RecoveryCopy): WriteResult {
|
||||
const others = listOtherCopies(copy.user_id, copy.version_id)
|
||||
const own = copyExists(copy.user_id, copy.version_id)
|
||||
if (!own && others.length >= MAX_OTHER_COPIES) return 'cap'
|
||||
const written = writeOrRemove(copyKey(copy.user_id, copy.version_id), copy)
|
||||
return written ? 'written' : 'quota'
|
||||
}
|
||||
|
||||
/** Only ever called on an explicit outcome (plan « Removal »). */
|
||||
export function removeCopy(userId: string, versionId: string): void {
|
||||
writeOrRemove(copyKey(userId, versionId), null)
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import { sameDocument } from '../core/sameDocument'
|
||||
import type { PreviewState } from '@faunosteo/core-wasm/types'
|
||||
import { attachDrawings, fetchMissing, type Attached } from './drawings'
|
||||
import type {
|
||||
ActionOutcome,
|
||||
CommitOutcome,
|
||||
ConfirmOption,
|
||||
EditorData,
|
||||
EditorState,
|
||||
RecoveryOffer,
|
||||
StoreApi,
|
||||
} from './editorTypes'
|
||||
import {
|
||||
copyExists,
|
||||
copyText,
|
||||
listOtherCopies,
|
||||
readCopy,
|
||||
removeCopy,
|
||||
writeCopy,
|
||||
type RecoveryCopy,
|
||||
} from './recovery'
|
||||
import { emptyHistory } from './undo'
|
||||
|
||||
export interface DetectInput {
|
||||
userId: string
|
||||
versionId: string
|
||||
canEdit: boolean
|
||||
savedText: string
|
||||
savedRevision: number
|
||||
}
|
||||
|
||||
type RecoveryPatch = Pick<EditorData, 'recovery' | 'offer' | 'refusedKind' | 'unusableCopy'>
|
||||
|
||||
const NO_RECOVERY: RecoveryPatch = {
|
||||
recovery: 'none',
|
||||
offer: null,
|
||||
refusedKind: null,
|
||||
unusableCopy: false,
|
||||
}
|
||||
|
||||
function offerOf(copy: RecoveryCopy, serverRevision: number): RecoveryOffer {
|
||||
return {
|
||||
revision: copy.revision,
|
||||
writtenAt: copy.written_at,
|
||||
sheetName: copy.sheet_name,
|
||||
serverRevision,
|
||||
copy,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What opening finds in this tab's storage. A mode that cannot save leaves the copy
|
||||
* untouched (never offered); an unreadable copy is refused and kept; a copy whose document
|
||||
* differs from the server's opens the blocking offer.
|
||||
*/
|
||||
export function detectRecovery(input: DetectInput): RecoveryPatch {
|
||||
const { userId, versionId } = input
|
||||
if (!input.canEdit) {
|
||||
return { ...NO_RECOVERY, unusableCopy: copyExists(userId, versionId) }
|
||||
}
|
||||
const stored = readCopy(userId, versionId)
|
||||
if (stored.kind === 'none') return NO_RECOVERY
|
||||
if (stored.kind === 'unreadable') {
|
||||
return { ...NO_RECOVERY, recovery: 'refused', refusedKind: 'unreadable' }
|
||||
}
|
||||
if (sameDocument(copyText(stored.copy), input.savedText)) return NO_RECOVERY
|
||||
const offer = offerOf(stored.copy, input.savedRevision)
|
||||
return { ...NO_RECOVERY, recovery: 'pending', offer }
|
||||
}
|
||||
|
||||
function sheetNameOf(state: EditorState): string {
|
||||
const name = state.previewState?.document.name
|
||||
return name?.fr.trim() || name?.en.trim() || state.versionId || ''
|
||||
}
|
||||
|
||||
function buildCopy(state: EditorState): RecoveryCopy {
|
||||
return {
|
||||
v: 1,
|
||||
user_id: state.userId ?? '',
|
||||
version_id: state.versionId ?? '',
|
||||
sheet_id: state.sheetId ?? '',
|
||||
sheet_name: sheetNameOf(state),
|
||||
revision: state.savedRevision,
|
||||
written_at: new Date().toISOString(),
|
||||
document: JSON.parse(state.documentText),
|
||||
drawings: state.drawings,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The copy subscription's body: writes while unsaved, never while an offer is pending
|
||||
* (or refused, or restoring), never removes (a copy outlives an undo back to the saved
|
||||
* content). The write flag and the issue (`cap`, `quota`) are kept in the store.
|
||||
*/
|
||||
export function syncCopy(api: StoreApi): void {
|
||||
const state = api.get()
|
||||
const live = state.status === 'ready' && state.canEdit
|
||||
if (!live || state.recovery !== 'none' || !state.unsaved) return
|
||||
const result = writeCopy(buildCopy(state))
|
||||
api.set({
|
||||
copyWritten: result === 'written',
|
||||
copyIssue: result === 'written' ? null : result,
|
||||
otherCopies: listOtherCopies(state.userId ?? '', state.versionId ?? ''),
|
||||
})
|
||||
}
|
||||
|
||||
export function copyInputsChanged(a: EditorState, b: EditorState): boolean {
|
||||
return (
|
||||
a.documentText !== b.documentText ||
|
||||
a.savedRevision !== b.savedRevision ||
|
||||
a.unsaved !== b.unsaved ||
|
||||
a.recovery !== b.recovery ||
|
||||
a.drawings !== b.drawings ||
|
||||
a.status !== b.status
|
||||
)
|
||||
}
|
||||
|
||||
function core(failure: { ok: false; kind: string }): ActionOutcome {
|
||||
return { ok: false, reason: 'core', failure }
|
||||
}
|
||||
|
||||
/** The copy's document goes through the core; the core's refusal keeps the copy, blocked. */
|
||||
export async function restoreCopy(api: StoreApi): Promise<ActionOutcome> {
|
||||
const state = api.get()
|
||||
const copy = state.offer?.copy
|
||||
if (state.recovery !== 'pending' || !copy || !state.preview) {
|
||||
return { ok: false, reason: 'blocked', kind: 'not_ready' }
|
||||
}
|
||||
api.set({ recovery: 'restoring' })
|
||||
const text = copyText(copy)
|
||||
const replaced = state.preview.replaceDocument(text)
|
||||
if (!replaced.ok) {
|
||||
const kind = replaced.reason === 'core' ? replaced.failure.kind : 'unknown'
|
||||
api.set({ recovery: 'refused', refusedKind: kind })
|
||||
return replaced.reason === 'core'
|
||||
? core(replaced.failure)
|
||||
: { ok: false, reason: 'blocked', kind: 'not_ready' }
|
||||
}
|
||||
return finishRestore(api, state, copy, await fetchMissing(state.drawings, copy.drawings))
|
||||
}
|
||||
|
||||
type Fetched = Awaited<ReturnType<typeof fetchMissing>>
|
||||
|
||||
/** ONE update, so the copy subscription never sees a mixed state. */
|
||||
function restoredPatch(
|
||||
now: EditorState,
|
||||
copy: RecoveryCopy,
|
||||
next: PreviewState,
|
||||
attached: Attached,
|
||||
): Partial<EditorState> {
|
||||
const text = copyText(copy)
|
||||
return {
|
||||
documentText: text,
|
||||
previewState: next,
|
||||
handleVersion: now.handleVersion + 1 + attached.held.length,
|
||||
drawings: [...now.drawings, ...attached.held],
|
||||
drawingFailures: { ...now.drawingFailures, ...attached.failures },
|
||||
savedRevision: copy.revision,
|
||||
staleBase: copy.revision < now.savedRevision,
|
||||
unsaved: !sameDocument(text, now.savedText),
|
||||
...emptyHistory(),
|
||||
...NO_RECOVERY,
|
||||
}
|
||||
}
|
||||
|
||||
function finishRestore(
|
||||
api: StoreApi,
|
||||
started: EditorState,
|
||||
copy: RecoveryCopy,
|
||||
fetched: Fetched,
|
||||
): ActionOutcome {
|
||||
const now = api.get()
|
||||
const preview = now.preview
|
||||
if (now.session !== started.session || !preview) {
|
||||
return { ok: false, reason: 'blocked', kind: 'session_changed' }
|
||||
}
|
||||
if (now.recovery !== 'restoring') {
|
||||
preview.replaceDocument(started.documentText)
|
||||
return { ok: false, reason: 'blocked', kind: 'recovery.pending' }
|
||||
}
|
||||
const attached = attachDrawings(preview, fetched)
|
||||
const next = preview.state()
|
||||
if (!next.ok) {
|
||||
preview.replaceDocument(started.documentText)
|
||||
api.set({ recovery: 'refused', refusedKind: next.kind })
|
||||
return core(next)
|
||||
}
|
||||
api.set(restoredPatch(now, copy, next.value, attached))
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
/** « Ignorer la copie » (confirmed): the one way out of pending and refused. */
|
||||
export function ignoreCopy(api: StoreApi, { confirmed }: ConfirmOption): CommitOutcome {
|
||||
const state = api.get()
|
||||
if (state.recovery !== 'pending' && state.recovery !== 'refused') {
|
||||
return { ok: false, reason: 'blocked', kind: 'not_ready' }
|
||||
}
|
||||
if (!confirmed) return { ok: false, reason: 'blocked', kind: 'confirmation_required' }
|
||||
const userId = state.userId ?? ''
|
||||
const versionId = state.versionId ?? ''
|
||||
removeCopy(userId, versionId)
|
||||
api.set({
|
||||
...NO_RECOVERY,
|
||||
copyWritten: false,
|
||||
copyIssue: null,
|
||||
otherCopies: listOtherCopies(userId, versionId),
|
||||
})
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
/** « Abandonner cette copie » (confirmed) of ANOTHER version, then the current copy is retried. */
|
||||
export function abandonOtherCopy(
|
||||
api: StoreApi,
|
||||
versionId: string,
|
||||
{ confirmed }: ConfirmOption,
|
||||
): CommitOutcome {
|
||||
const state = api.get()
|
||||
if (state.userId === null || versionId === state.versionId) {
|
||||
return { ok: false, reason: 'blocked', kind: 'not_ready' }
|
||||
}
|
||||
if (!confirmed) return { ok: false, reason: 'blocked', kind: 'confirmation_required' }
|
||||
removeCopy(state.userId, versionId)
|
||||
api.set({ otherCopies: listOtherCopies(state.userId, state.versionId ?? '') })
|
||||
syncCopy(api)
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* The editor's history: arrays of document texts, each entry's UTF-8 size measured once.
|
||||
* Pure functions over a value, so the store holds the arrays and replaces them whole.
|
||||
*/
|
||||
|
||||
/** Oldest undo entries are dropped while both stacks together exceed this many bytes. */
|
||||
export const HISTORY_LIMIT_BYTES = 8_388_608
|
||||
|
||||
export interface HistoryEntry {
|
||||
text: string
|
||||
bytes: number
|
||||
}
|
||||
|
||||
export interface History {
|
||||
undo: HistoryEntry[]
|
||||
redo: HistoryEntry[]
|
||||
}
|
||||
|
||||
export interface HistoryStep {
|
||||
history: History
|
||||
/** The document text to put back. */
|
||||
text: string
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder()
|
||||
|
||||
export function entryOf(text: string): HistoryEntry {
|
||||
return { text, bytes: encoder.encode(text).length }
|
||||
}
|
||||
|
||||
export function emptyHistory(): History {
|
||||
return { undo: [], redo: [] }
|
||||
}
|
||||
|
||||
function totalBytes(entries: readonly HistoryEntry[]): number {
|
||||
return entries.reduce((sum, entry) => sum + entry.bytes, 0)
|
||||
}
|
||||
|
||||
function bounded(history: History): History {
|
||||
let size = totalBytes(history.undo) + totalBytes(history.redo)
|
||||
let dropped = 0
|
||||
while (size > HISTORY_LIMIT_BYTES && dropped < history.undo.length) {
|
||||
size -= history.undo[dropped].bytes
|
||||
dropped += 1
|
||||
}
|
||||
return dropped === 0
|
||||
? history
|
||||
: { undo: history.undo.slice(dropped), redo: history.redo }
|
||||
}
|
||||
|
||||
/** A commit: the text it replaced becomes the newest undo entry, redo is cleared. */
|
||||
export function recordCommit(history: History, replacedText: string): History {
|
||||
return bounded({ undo: [...history.undo, entryOf(replacedText)], redo: [] })
|
||||
}
|
||||
|
||||
export function stepBack(history: History, currentText: string): HistoryStep | null {
|
||||
const target = history.undo[history.undo.length - 1]
|
||||
if (!target) return null
|
||||
const next = {
|
||||
undo: history.undo.slice(0, -1),
|
||||
redo: [...history.redo, entryOf(currentText)],
|
||||
}
|
||||
return { history: bounded(next), text: target.text }
|
||||
}
|
||||
|
||||
export function stepForward(history: History, currentText: string): HistoryStep | null {
|
||||
const target = history.redo[history.redo.length - 1]
|
||||
if (!target) return null
|
||||
const next = {
|
||||
undo: [...history.undo, entryOf(currentText)],
|
||||
redo: history.redo.slice(0, -1),
|
||||
}
|
||||
return { history: bounded(next), text: target.text }
|
||||
}
|
||||
Reference in new issue
Block a user