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
@@ -62,6 +62,35 @@ export type VersionLoad =
|
||||
}
|
||||
| { ok: false; failure: CatalogueFailure }
|
||||
|
||||
/** One drawing as `downloadSheetDrawing` settled it: bytes, or the closed failure. */
|
||||
export type DrawingFetch =
|
||||
| { ok: true; drawing: PreviewDrawing }
|
||||
| { ok: false; assetId: string; sha256: string; failure: CatalogueFailure }
|
||||
|
||||
type DrawingEntry = VersionAnswer['drawings'][number]
|
||||
|
||||
/** Never rejects: a drawing Storage does not give is missing, the version answered. */
|
||||
export async function fetchDrawing(
|
||||
client: FaunosteoClient,
|
||||
entry: DrawingEntry,
|
||||
): Promise<DrawingFetch> {
|
||||
try {
|
||||
const bytes = await downloadSheetDrawing(client, entry.sha256)
|
||||
return {
|
||||
ok: true,
|
||||
drawing: { assetId: entry.asset_id, sha256: entry.sha256, bytes },
|
||||
}
|
||||
} catch (error) {
|
||||
const failure = serverFailure(error)
|
||||
return {
|
||||
ok: false,
|
||||
assetId: entry.asset_id,
|
||||
sha256: entry.sha256,
|
||||
failure: failure === 'denied' ? 'drawing_missing' : failure,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadDrawings(
|
||||
client: FaunosteoClient,
|
||||
version: VersionAnswer,
|
||||
@@ -79,16 +108,75 @@ type VersionRead =
|
||||
| { ok: true; version: VersionAnswer; drawings: PreviewDrawing[] }
|
||||
| { ok: false; failure: CatalogueFailure }
|
||||
|
||||
async function readVersion(
|
||||
const DraftAnswerSchema = VersionAnswerSchema.extend({
|
||||
revision: z.number().int().nonnegative(),
|
||||
})
|
||||
export type DraftAnswer = z.infer<typeof DraftAnswerSchema>
|
||||
|
||||
/** The editor's read: any status, the revision of the same answer, settled drawings. */
|
||||
export type DraftRead =
|
||||
| {
|
||||
ok: true
|
||||
version: DraftAnswer
|
||||
revision: number
|
||||
drawings: DrawingFetch[]
|
||||
}
|
||||
| { ok: false; failure: CatalogueFailure }
|
||||
|
||||
export interface DraftReadOptions {
|
||||
draft: true
|
||||
/** Asset ids the caller already holds: not downloaded again. */
|
||||
have?: ReadonlySet<string>
|
||||
}
|
||||
|
||||
async function readAnswer<T>(
|
||||
client: FaunosteoClient,
|
||||
versionId: string,
|
||||
): Promise<VersionRead> {
|
||||
let version: VersionAnswer
|
||||
schema: z.ZodType<T>,
|
||||
): Promise<{ ok: true; version: T } | { ok: false; failure: CatalogueFailure }> {
|
||||
try {
|
||||
version = parsed(VersionAnswerSchema, await getSheetVersion(client, versionId))
|
||||
return { ok: true, version: parsed(schema, await getSheetVersion(client, versionId)) }
|
||||
} catch (error) {
|
||||
return { ok: false, failure: serverFailure(error) }
|
||||
}
|
||||
}
|
||||
|
||||
async function readDraft(
|
||||
client: FaunosteoClient,
|
||||
versionId: string,
|
||||
have: ReadonlySet<string>,
|
||||
): Promise<DraftRead> {
|
||||
const answer = await readAnswer(client, versionId, DraftAnswerSchema)
|
||||
if (!answer.ok) return answer
|
||||
const { version } = answer
|
||||
const wanted = version.drawings.filter((entry) => !have.has(entry.asset_id))
|
||||
const drawings = await Promise.all(wanted.map((e) => fetchDrawing(client, e)))
|
||||
return { ok: true, version, revision: version.revision, drawings }
|
||||
}
|
||||
|
||||
/**
|
||||
* One version as the server gave it. Catalogue mode: published and deprecated only, every
|
||||
* drawing or none. Draft mode (the editor): any status, `revision` from the same answer,
|
||||
* each drawing settled alone so one bad drawing never blocks authoring.
|
||||
*/
|
||||
export async function readVersion(
|
||||
client: FaunosteoClient,
|
||||
versionId: string,
|
||||
): Promise<VersionRead>
|
||||
export async function readVersion(
|
||||
client: FaunosteoClient,
|
||||
versionId: string,
|
||||
options: DraftReadOptions,
|
||||
): Promise<DraftRead>
|
||||
export async function readVersion(
|
||||
client: FaunosteoClient,
|
||||
versionId: string,
|
||||
options?: DraftReadOptions,
|
||||
): Promise<VersionRead | DraftRead> {
|
||||
if (options) return readDraft(client, versionId, options.have ?? new Set())
|
||||
const answer = await readAnswer(client, versionId, VersionAnswerSchema)
|
||||
if (!answer.ok) return answer
|
||||
const { version } = answer
|
||||
// The catalogue reads published and deprecated versions only (§11.1).
|
||||
if (version.status === 'draft') return { ok: false, failure: 'denied' }
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import type { PreviewState, SheetView } from '@faunosteo/core-wasm/types'
|
||||
import type { Acceptance } from '@/catalogue/preview'
|
||||
|
||||
/**
|
||||
* Pure readers over ONE `PreviewState`: the issue paths are indexes into the document of
|
||||
* the same state, so an insert, a delete or a reorder never mismaps an issue. The codes
|
||||
* and paths are the core's report strings (crates/core/src/domain/sheet/report.rs); the
|
||||
* rules they signal stay the core's.
|
||||
*/
|
||||
|
||||
const GEOMETRY_PATH = /^annotations\[(\d+)\]\.geometry$/
|
||||
const VIEW_PATH = /^views\[(\d+)\]$/
|
||||
const NO_FRAME = 'view.frame.unknown'
|
||||
|
||||
export interface GeometryIssue {
|
||||
annotationId: string
|
||||
code: string
|
||||
message: string
|
||||
}
|
||||
|
||||
/** The Error issues at exactly `annotations[i].geometry`, by annotation id. */
|
||||
export function geometryErrorsById(
|
||||
state: PreviewState,
|
||||
): Map<string, GeometryIssue[]> {
|
||||
const byId = new Map<string, GeometryIssue[]>()
|
||||
for (const issue of state.report.issues) {
|
||||
if (issue.severity !== 'error') continue
|
||||
const index = GEOMETRY_PATH.exec(issue.path)?.[1]
|
||||
const annotation = state.document.annotations[Number(index)]
|
||||
if (index === undefined || !annotation) continue
|
||||
const entry = { annotationId: annotation.id, code: issue.code, message: issue.message }
|
||||
byId.set(annotation.id, [...(byId.get(annotation.id) ?? []), entry])
|
||||
}
|
||||
return byId
|
||||
}
|
||||
|
||||
/** The asset a view draws: its own, else the first up its parent chain (cycle-safe). */
|
||||
function drawingAssetOf(views: readonly SheetView[], viewId: string): string | null {
|
||||
const seen = new Set<string>()
|
||||
let view = views.find((candidate) => candidate.id === viewId)
|
||||
while (view && !seen.has(view.id)) {
|
||||
if (view.svg_asset_id) return view.svg_asset_id
|
||||
seen.add(view.id)
|
||||
const parent: string | null = view.kind === 'detail' ? view.parent_view_id : null
|
||||
view = parent === null ? undefined : views.find((v) => v.id === parent)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* The views the core does not measure: no drawing held for them, a drawing that is not
|
||||
* `ok`, or an Error `view.frame.unknown`. The core stays silent about their annotations.
|
||||
*/
|
||||
export function unmeasuredViews(state: PreviewState): Set<string> {
|
||||
const { views } = state.document
|
||||
const frameless = new Set<string>()
|
||||
for (const issue of state.report.issues) {
|
||||
const index = VIEW_PATH.exec(issue.path)?.[1]
|
||||
const view = views[Number(index)]
|
||||
if (issue.severity === 'error' && issue.code === NO_FRAME && view) {
|
||||
frameless.add(view.id)
|
||||
}
|
||||
}
|
||||
const drawn = new Map(state.drawings.map((d) => [d.asset_id, d.state]))
|
||||
const unmeasured = new Set(frameless)
|
||||
for (const view of views) {
|
||||
const asset = drawingAssetOf(views, view.id)
|
||||
if (asset === null || drawn.get(asset) !== 'ok') unmeasured.add(view.id)
|
||||
}
|
||||
return unmeasured
|
||||
}
|
||||
|
||||
export type GeometryRefusalReason =
|
||||
| 'changed_invalid'
|
||||
| 'changed_unmeasured'
|
||||
| 'newly_invalid'
|
||||
| 'view_unmeasured'
|
||||
|
||||
/** What `geometryAccept` answers on a refusal: the annotations, issues and views at fault. */
|
||||
export interface GeometryRefusal {
|
||||
reason: GeometryRefusalReason
|
||||
annotationIds: string[]
|
||||
issues: GeometryIssue[]
|
||||
viewIds: string[]
|
||||
}
|
||||
|
||||
export interface GeometryAcceptInput {
|
||||
/** The last accepted state the store holds. */
|
||||
before: PreviewState
|
||||
/** The annotations the commit creates or changes (empty for a frame change). */
|
||||
changedIds: readonly string[]
|
||||
}
|
||||
|
||||
function refusal(
|
||||
reason: GeometryRefusalReason,
|
||||
parts: Partial<Omit<GeometryRefusal, 'reason'>>,
|
||||
): Acceptance<GeometryRefusal> {
|
||||
const issues = parts.issues ?? []
|
||||
const annotationIds = parts.annotationIds ?? issues.map((i) => i.annotationId)
|
||||
return {
|
||||
accepted: false,
|
||||
refusal: { reason, annotationIds, issues, viewIds: parts.viewIds ?? [] },
|
||||
}
|
||||
}
|
||||
|
||||
function changedFault(
|
||||
after: PreviewState,
|
||||
changedIds: readonly string[],
|
||||
): Acceptance<GeometryRefusal> | null {
|
||||
const errors = geometryErrorsById(after)
|
||||
const invalid = changedIds.flatMap((id) => errors.get(id) ?? [])
|
||||
if (invalid.length > 0) return refusal('changed_invalid', { issues: invalid })
|
||||
const unmeasured = unmeasuredViews(after)
|
||||
const onUnmeasured = after.document.annotations.filter(
|
||||
(a) => changedIds.includes(a.id) && unmeasured.has(a.view_id),
|
||||
)
|
||||
if (onUnmeasured.length === 0) return null
|
||||
return refusal('changed_unmeasured', {
|
||||
annotationIds: onUnmeasured.map((a) => a.id),
|
||||
viewIds: [...new Set(onUnmeasured.map((a) => a.view_id))],
|
||||
})
|
||||
}
|
||||
|
||||
function frameFault(
|
||||
before: PreviewState,
|
||||
after: PreviewState,
|
||||
): Acceptance<GeometryRefusal> | null {
|
||||
const errorsBefore = geometryErrorsById(before)
|
||||
const newlyInvalid = [...geometryErrorsById(after)]
|
||||
.filter(([id]) => !errorsBefore.has(id))
|
||||
.flatMap(([, issues]) => issues)
|
||||
if (newlyInvalid.length > 0) return refusal('newly_invalid', { issues: newlyInvalid })
|
||||
const unmeasuredBefore = unmeasuredViews(before)
|
||||
const knownBefore = new Set(before.document.views.map((v) => v.id))
|
||||
const lost = [...unmeasuredViews(after)].filter(
|
||||
(id) =>
|
||||
knownBefore.has(id) &&
|
||||
!unmeasuredBefore.has(id) &&
|
||||
after.document.annotations.some((a) => a.view_id === id),
|
||||
)
|
||||
return lost.length > 0 ? refusal('view_unmeasured', { viewIds: lost }) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* The `accept` of a geometry commit (plan « Geometry errors », « Frame changes »): refuses
|
||||
* when a changed annotation carries a geometry error or sits on an unmeasured view after
|
||||
* it, when an annotation without geometry error before has one after, or when a measured
|
||||
* view holding annotations becomes unmeasured. An annotation invalid before and after, and
|
||||
* not changed, never blocks.
|
||||
*/
|
||||
export function geometryAccept(
|
||||
input: GeometryAcceptInput,
|
||||
): (after: PreviewState) => Acceptance<GeometryRefusal> {
|
||||
return (after) =>
|
||||
changedFault(after, input.changedIds) ??
|
||||
frameFault(input.before, after) ?? { accepted: true }
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -40,7 +40,7 @@ function storage(): Storage | null {
|
||||
}
|
||||
|
||||
/** A refused write (quota) leaves the previous value in place, as the Storage API does. */
|
||||
function writeOrRemove(key: string, value: unknown): boolean {
|
||||
export function writeOrRemove(key: string, value: unknown): boolean {
|
||||
const store = storage()
|
||||
if (!store) return false
|
||||
if (value === null) {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { Annotation, EditCommand, NewElement } from '@faunosteo/core-wasm/types'
|
||||
import { emptySheetDocument } from '@/core/sheetDocumentOps'
|
||||
import { cleanSvg } from '@/editor/core/cleaning'
|
||||
import { applyEdit } from '@/editor/core/editOps'
|
||||
|
||||
export const ASSET = '11111111-1111-4111-8111-111111111111'
|
||||
const NAME = { fr: 'N', en: 'N' }
|
||||
|
||||
export function svgBytes(viewBox = '0 0 100 100'): {
|
||||
bytes: Uint8Array
|
||||
sha256: string
|
||||
} {
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}"><rect width="4" height="4"/></svg>`
|
||||
const cleaned = cleanSvg(new TextEncoder().encode(svg))
|
||||
if (!cleaned.ok || !cleaned.value.stored || !cleaned.value.sha256) {
|
||||
throw new Error('uncleanable drawing')
|
||||
}
|
||||
return { bytes: new TextEncoder().encode(cleaned.value.stored), sha256: cleaned.value.sha256 }
|
||||
}
|
||||
|
||||
export function edit(text: string, command: EditCommand): string {
|
||||
const result = applyEdit(text, command)
|
||||
if (!result.ok) throw new Error(`${result.kind} ${result.detail ?? ''}`)
|
||||
return result.value
|
||||
}
|
||||
|
||||
export function insert(text: string, element: NewElement): string {
|
||||
return edit(text, { op: 'insert', element })
|
||||
}
|
||||
|
||||
export function emptyText(name = 'Fiche'): string {
|
||||
const empty = emptySheetDocument({ speciesId: 'equine', name: { fr: name, en: name } })
|
||||
if (!empty.ok) throw new Error(empty.kind)
|
||||
return JSON.stringify(empty.value)
|
||||
}
|
||||
|
||||
export function point(id: string, cx: number, cy: number, r: number, viewId = 'view-main') {
|
||||
const value: Annotation = {
|
||||
id,
|
||||
view_id: viewId,
|
||||
category_id: 'cat-a',
|
||||
laterality: 'unpaired',
|
||||
geometry: { type: 'circle', cx, cy, r },
|
||||
review_status: 'to_confirm',
|
||||
color: null,
|
||||
name: NAME,
|
||||
finding_zone_id: null,
|
||||
vertebral_region_code: null,
|
||||
kind: 'point',
|
||||
}
|
||||
return { kind: 'annotation', value } satisfies NewElement
|
||||
}
|
||||
|
||||
/** An empty sheet whose main view draws ASSET and with one category `cat-a`. */
|
||||
export function drawnText(): string {
|
||||
const withCategory = insert(emptyText(), {
|
||||
kind: 'category',
|
||||
value: { id: 'cat-a', name: NAME, color: null },
|
||||
})
|
||||
const document = JSON.parse(withCategory)
|
||||
const main = document.views.find((v: { id: string }) => v.id === 'view-main')
|
||||
return edit(withCategory, {
|
||||
op: 'update',
|
||||
key: { kind: 'view', id: 'view-main' },
|
||||
element: { kind: 'view', value: { ...main, svg_asset_id: ASSET } },
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { expect, vi } from 'vitest'
|
||||
import type { EditCommand } from '@faunosteo/core-wasm/types'
|
||||
import * as supabase from '@faunosteo/supabase'
|
||||
import { useEditorStore } from '@/editor/state/editorStore'
|
||||
import { ASSET, drawnText, insert, point, svgBytes } from './editorFixtures'
|
||||
|
||||
/**
|
||||
* The store harness. The calling test file declares the two module mocks (hoisted):
|
||||
* vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
|
||||
* vi.mock('@faunosteo/supabase', async (orig) => ({ ...(await orig()), getSheetVersion: vi.fn(),
|
||||
* downloadSheetDrawing: vi.fn(), saveSheetDraft: vi.fn(), getOfficialSheetAdmin: vi.fn(),
|
||||
* submitSheetReview: vi.fn() }))
|
||||
*/
|
||||
export const USER = 'user-1'
|
||||
export const VERSION = 'ver-1'
|
||||
export const SHEET = 'sheet-1'
|
||||
|
||||
export const sb = vi.mocked(supabase)
|
||||
export const store = useEditorStore
|
||||
|
||||
export function baseText(): string {
|
||||
return insert(drawnText(), point('anno-a', 50, 50, 5))
|
||||
}
|
||||
|
||||
export function versionAnswer(text: string, revision: number, withDrawing = true) {
|
||||
const drawings = withDrawing ? [{ asset_id: ASSET, sha256: svgBytes().sha256 }] : []
|
||||
return {
|
||||
sheet_id: SHEET,
|
||||
version_id: VERSION,
|
||||
version_number: 1,
|
||||
status: 'draft',
|
||||
species_id: 'equine',
|
||||
document: JSON.parse(text),
|
||||
fingerprint: null,
|
||||
revision,
|
||||
drawings,
|
||||
}
|
||||
}
|
||||
|
||||
export function serverHas(text: string, revision: number, withDrawing = true): void {
|
||||
sb.getSheetVersion.mockResolvedValue(versionAnswer(text, revision, withDrawing) as never)
|
||||
sb.downloadSheetDrawing.mockResolvedValue(svgBytes().bytes)
|
||||
}
|
||||
|
||||
export async function openReady(
|
||||
options: { text?: string; revision?: number; canEdit?: boolean } = {},
|
||||
): Promise<number> {
|
||||
serverHas(options.text ?? baseText(), options.revision ?? 3)
|
||||
const token = store.getState().open(VERSION, USER, { canEdit: options.canEdit ?? true })
|
||||
await vi.waitFor(() => expect(store.getState().status).not.toBe('loading'))
|
||||
return token
|
||||
}
|
||||
|
||||
export function resetStore(): void {
|
||||
store.getState().close()
|
||||
sessionStorage.clear()
|
||||
vi.restoreAllMocks()
|
||||
vi.resetAllMocks()
|
||||
}
|
||||
|
||||
/** Moves anno-a to (x, 50): a valid, always different, document. */
|
||||
export function moveCommand(x: number): EditCommand {
|
||||
return {
|
||||
op: 'update',
|
||||
key: { kind: 'annotation', id: 'anno-a' },
|
||||
element: point('anno-a', x, 50, 5),
|
||||
}
|
||||
}
|
||||
|
||||
export function commitMove(x: number) {
|
||||
return store.getState().commit(moveCommand(x))
|
||||
}
|
||||
|
||||
export const copyKeyOf = (version = VERSION, user = USER) =>
|
||||
`osteo:sheet-draft:${user}:${version}`
|
||||
|
||||
export function storedCopy(version = VERSION, user = USER) {
|
||||
const raw = sessionStorage.getItem(copyKeyOf(version, user))
|
||||
return raw === null ? null : JSON.parse(raw)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/** Lot D: `readVersion` draft mode (ruling R1) beside the unchanged catalogue path. */
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { SheetFailure, type FaunosteoClient } from '@faunosteo/supabase'
|
||||
import * as supabase from '@faunosteo/supabase'
|
||||
import { readVersion } from '@/catalogue/catalogue'
|
||||
|
||||
vi.mock('@faunosteo/supabase', async (orig) => ({
|
||||
...(await orig<typeof import('@faunosteo/supabase')>()),
|
||||
getSheetVersion: vi.fn(),
|
||||
downloadSheetDrawing: vi.fn(),
|
||||
}))
|
||||
|
||||
const sb = vi.mocked(supabase)
|
||||
const client = {} as FaunosteoClient
|
||||
const HASH_A = 'a'.repeat(64)
|
||||
const HASH_B = 'b'.repeat(64)
|
||||
|
||||
function answer(over: Record<string, unknown> = {}) {
|
||||
return {
|
||||
sheet_id: 's', version_id: 'v', version_number: 1, status: 'draft', species_id: 'equine',
|
||||
document: { any: 'thing' }, fingerprint: null, revision: 4,
|
||||
drawings: [{ asset_id: 'one', sha256: HASH_A }, { asset_id: 'two', sha256: HASH_B }],
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
describe('readVersion draft mode', () => {
|
||||
it('accepts a draft, returns its revision and settles each drawing alone', async () => {
|
||||
sb.getSheetVersion.mockResolvedValue(answer() as never)
|
||||
sb.downloadSheetDrawing.mockImplementation(async (_c, sha) => {
|
||||
if (sha === HASH_B) throw new SheetFailure('not_found')
|
||||
return new Uint8Array([1])
|
||||
})
|
||||
const read = await readVersion(client, 'v', { draft: true })
|
||||
expect(read).toMatchObject({ ok: true, revision: 4 })
|
||||
if (!read.ok) return
|
||||
expect(read.drawings[0]).toMatchObject({ ok: true, drawing: { assetId: 'one' } })
|
||||
expect(read.drawings[1]).toEqual({ ok: false, assetId: 'two', sha256: HASH_B, failure: 'drawing_missing' })
|
||||
})
|
||||
|
||||
it('skips the drawings the caller holds', async () => {
|
||||
sb.getSheetVersion.mockResolvedValue(answer() as never)
|
||||
sb.downloadSheetDrawing.mockClear()
|
||||
sb.downloadSheetDrawing.mockResolvedValue(new Uint8Array([1]))
|
||||
const read = await readVersion(client, 'v', { draft: true, have: new Set(['one']) })
|
||||
expect(read.ok && read.drawings.map((d) => d.ok && d.drawing.assetId)).toEqual(['two'])
|
||||
})
|
||||
|
||||
it('needs the revision: an answer without it is unavailable', async () => {
|
||||
sb.getSheetVersion.mockResolvedValue(answer({ revision: undefined }) as never)
|
||||
expect(await readVersion(client, 'v', { draft: true })).toEqual({ ok: false, failure: 'unavailable' })
|
||||
})
|
||||
|
||||
it('maps a server refusal like the catalogue does', async () => {
|
||||
sb.getSheetVersion.mockRejectedValue(new SheetFailure('not_found'))
|
||||
expect(await readVersion(client, 'v', { draft: true })).toEqual({ ok: false, failure: 'denied' })
|
||||
})
|
||||
|
||||
it('leaves the catalogue path all-or-nothing and draft-refusing', async () => {
|
||||
sb.getSheetVersion.mockResolvedValue(answer() as never)
|
||||
expect(await readVersion(client, 'v')).toEqual({ ok: false, failure: 'denied' })
|
||||
sb.getSheetVersion.mockResolvedValue(answer({ status: 'published' }) as never)
|
||||
sb.downloadSheetDrawing.mockRejectedValue(new SheetFailure('not_found'))
|
||||
expect(await readVersion(client, 'v')).toEqual({ ok: false, failure: 'drawing_missing' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Lot D: geometry errors and the geometry `accept`, read from ONE `PreviewState` and proved
|
||||
* through the real `replaceDocument` rollback on the Node core.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { PreviewState } from '@faunosteo/core-wasm/types'
|
||||
import { CataloguePreview } from '@/catalogue/preview'
|
||||
import { coreRuntime } from '@/core/runtime'
|
||||
import {
|
||||
geometryAccept,
|
||||
geometryErrorsById,
|
||||
unmeasuredViews,
|
||||
type GeometryRefusal,
|
||||
} from '@/editor/issues'
|
||||
import { ASSET, drawnText, edit, insert, point, svgBytes } from '../helpers/editorFixtures'
|
||||
|
||||
function draft(text: string, viewBox = '0 0 100 100') {
|
||||
const drawing = svgBytes(viewBox)
|
||||
const preview = new CataloguePreview(coreRuntime(), { status: 'draft', document: text }, [
|
||||
{ assetId: ASSET, sha256: drawing.sha256, bytes: drawing.bytes },
|
||||
])
|
||||
const state = preview.state()
|
||||
if (!state.ok) throw new Error(state.kind)
|
||||
return { preview, state: state.value }
|
||||
}
|
||||
|
||||
function moved(text: string, id: string, cx: number, cy: number, r: number) {
|
||||
return edit(text, { op: 'update', key: { kind: 'annotation', id }, element: point(id, cx, cy, r) })
|
||||
}
|
||||
|
||||
function refusalOf(outcome: ReturnType<CataloguePreview['replaceDocument']>) {
|
||||
if (outcome.ok || outcome.reason !== 'refused') throw new Error('not refused')
|
||||
return outcome.refusal as GeometryRefusal
|
||||
}
|
||||
|
||||
const valid = () => insert(drawnText(), point('anno-a', 50, 50, 5))
|
||||
|
||||
describe('geometryErrorsById', () => {
|
||||
it('maps the issue index to the id after an insert before the annotation', () => {
|
||||
const text = insert(valid(), point('anno-b', 1, 1, 5))
|
||||
expect([...geometryErrorsById(draft(text).state).keys()]).toEqual(['anno-b'])
|
||||
const shifted = edit(text, {
|
||||
op: 'insert',
|
||||
element: point('anno-c', 60, 60, 5),
|
||||
position: 0,
|
||||
})
|
||||
const { state } = draft(shifted)
|
||||
expect(state.report.issues.some((i) => i.path === 'annotations[2].geometry')).toBe(true)
|
||||
expect([...geometryErrorsById(state).keys()]).toEqual(['anno-b'])
|
||||
})
|
||||
|
||||
it('ignores an Error that is not at annotations[i].geometry', () => {
|
||||
const { state } = draft(valid())
|
||||
const faked: PreviewState = {
|
||||
...state,
|
||||
report: {
|
||||
...state.report,
|
||||
issues: [
|
||||
{ code: 'x.y', severity: 'error', path: 'annotations[0].name_fr', message: 'm' },
|
||||
{ code: 'annotation.geometry.out_of_frame', severity: 'warning', path: 'annotations[0].geometry', message: 'm' },
|
||||
],
|
||||
},
|
||||
}
|
||||
expect(geometryErrorsById(faked).size).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('unmeasuredViews', () => {
|
||||
it('measures a view through its own drawing or the one it crops', () => {
|
||||
const detail = insert(drawnText(), {
|
||||
kind: 'view',
|
||||
value: {
|
||||
kind: 'detail', id: 'view-det', name: { fr: 'D', en: 'D' },
|
||||
svg_asset_id: null, view_box: { min_x: 0, min_y: 0, width: 50, height: 50 },
|
||||
parent_view_id: 'view-main',
|
||||
},
|
||||
})
|
||||
expect(unmeasuredViews(draft(detail).state).size).toBe(0)
|
||||
})
|
||||
|
||||
it('counts a missing drawing and a frame-less view as unmeasured', () => {
|
||||
const { state } = draft(drawnText())
|
||||
const without = { ...state, drawings: [] }
|
||||
expect([...unmeasuredViews(without)]).toEqual(['view-main'])
|
||||
const frameless: PreviewState = {
|
||||
...state,
|
||||
report: {
|
||||
...state.report,
|
||||
issues: [{ code: 'view.frame.unknown', severity: 'error', path: 'views[0]', message: 'm' }],
|
||||
},
|
||||
}
|
||||
expect([...unmeasuredViews(frameless)]).toEqual(['view-main'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('geometryAccept through replaceDocument', () => {
|
||||
it('refuses a valid point moved out of the frame and keeps the previous text', () => {
|
||||
const text = valid()
|
||||
const { preview, state } = draft(text)
|
||||
const accept = geometryAccept({ before: state, changedIds: ['anno-a'] })
|
||||
const outcome = preview.replaceDocument(moved(text, 'anno-a', 1, 1, 5), accept)
|
||||
expect(refusalOf(outcome)).toMatchObject({
|
||||
reason: 'changed_invalid',
|
||||
annotationIds: ['anno-a'],
|
||||
issues: [{ code: 'annotation.geometry.out_of_frame' }],
|
||||
})
|
||||
expect(preview.document).toBe(text)
|
||||
})
|
||||
|
||||
it('refuses a typed radius the core reports too_small', () => {
|
||||
const big = '0 0 5000 5000'
|
||||
const text = insert(drawnText(), point('anno-a', 2500, 2500, 400))
|
||||
const { preview, state } = draft(text, big)
|
||||
expect(geometryErrorsById(state).size).toBe(0)
|
||||
const accept = geometryAccept({ before: state, changedIds: ['anno-a'] })
|
||||
const outcome = preview.replaceDocument(moved(text, 'anno-a', 2500, 2500, 1), accept)
|
||||
expect(refusalOf(outcome).issues[0].code).toBe('annotation.geometry.too_small')
|
||||
})
|
||||
|
||||
it('repairs an inherited out-of-frame point only with a coherent set', () => {
|
||||
const text = insert(drawnText(), point('anno-a', 150, 150, 5))
|
||||
const { preview, state } = draft(text)
|
||||
expect(geometryErrorsById(state).has('anno-a')).toBe(true)
|
||||
const accept = geometryAccept({ before: state, changedIds: ['anno-a'] })
|
||||
const half = preview.replaceDocument(moved(text, 'anno-a', 50, 150, 5), accept)
|
||||
expect(refusalOf(half).reason).toBe('changed_invalid')
|
||||
const whole = preview.replaceDocument(moved(text, 'anno-a', 50, 50, 5), accept)
|
||||
expect(whole.ok).toBe(true)
|
||||
})
|
||||
|
||||
it('never blocks a commit on an unrelated annotation already invalid', () => {
|
||||
const text = insert(valid(), point('anno-b', 1, 1, 5))
|
||||
const { preview, state } = draft(text)
|
||||
const accept = geometryAccept({ before: state, changedIds: ['anno-a'] })
|
||||
expect(preview.replaceDocument(moved(text, 'anno-a', 40, 40, 5), accept).ok).toBe(true)
|
||||
})
|
||||
|
||||
it('refuses a view_box that invalidates a valid point', () => {
|
||||
const text = valid()
|
||||
const { preview, state } = draft(text)
|
||||
const main = state.document.views[0]
|
||||
const next = edit(text, {
|
||||
op: 'update',
|
||||
key: { kind: 'view', id: 'view-main' },
|
||||
element: { kind: 'view', value: { ...main, view_box: { min_x: 0, min_y: 0, width: 40, height: 40 } } },
|
||||
})
|
||||
const outcome = preview.replaceDocument(next, geometryAccept({ before: state, changedIds: [] }))
|
||||
expect(refusalOf(outcome)).toMatchObject({ reason: 'newly_invalid', annotationIds: ['anno-a'] })
|
||||
})
|
||||
|
||||
it('accepts a view_box that only touches an already invalid point', () => {
|
||||
const text = insert(drawnText(), point('anno-a', 150, 50, 5))
|
||||
const { preview, state } = draft(text)
|
||||
const main = state.document.views[0]
|
||||
const next = edit(text, {
|
||||
op: 'update',
|
||||
key: { kind: 'view', id: 'view-main' },
|
||||
element: { kind: 'view', value: { ...main, view_box: { min_x: 0, min_y: 0, width: 90, height: 90 } } },
|
||||
})
|
||||
const outcome = preview.replaceDocument(next, geometryAccept({ before: state, changedIds: [] }))
|
||||
expect(outcome.ok).toBe(true)
|
||||
})
|
||||
|
||||
it('refuses a frame change that leaves a view with annotations unmeasured', () => {
|
||||
const text = valid()
|
||||
const { preview, state } = draft(text)
|
||||
const main = state.document.views[0]
|
||||
const next = edit(text, {
|
||||
op: 'update',
|
||||
key: { kind: 'view', id: 'view-main' },
|
||||
element: { kind: 'view', value: { ...main, svg_asset_id: '22222222-2222-4222-8222-222222222222' } },
|
||||
})
|
||||
const outcome = preview.replaceDocument(next, geometryAccept({ before: state, changedIds: [] }))
|
||||
expect(refusalOf(outcome)).toMatchObject({ reason: 'view_unmeasured', viewIds: ['view-main'] })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,265 @@
|
||||
/** Lot D: the local recovery copy (offer, restore, ignore, cap, quota) on the Node core. */
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { SheetFailure } from '@faunosteo/supabase'
|
||||
import { leaveGuardArmed } from '@/editor/state/editorStore'
|
||||
import {
|
||||
SHEET, USER, VERSION, baseText, commitMove, copyKeyOf, openReady, resetStore, sb, serverHas,
|
||||
storedCopy, store,
|
||||
} from '../helpers/editorHarness'
|
||||
import { ASSET, svgBytes } from '../helpers/editorFixtures'
|
||||
|
||||
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
|
||||
vi.mock('@faunosteo/supabase', async (orig) => ({
|
||||
...(await orig<typeof import('@faunosteo/supabase')>()),
|
||||
getSheetVersion: vi.fn(),
|
||||
downloadSheetDrawing: vi.fn(),
|
||||
saveSheetDraft: vi.fn(),
|
||||
getOfficialSheetAdmin: vi.fn(),
|
||||
submitSheetReview: vi.fn(),
|
||||
}))
|
||||
|
||||
afterEach(resetStore)
|
||||
|
||||
/** The text of the server document with anno-a moved: what a copy would hold. */
|
||||
function movedText(x: number): string {
|
||||
return JSON.stringify(
|
||||
JSON.parse(baseText(), (key, value) => (key === 'cx' ? x : value)),
|
||||
)
|
||||
}
|
||||
|
||||
function seed(text: string, revision: number, over: Record<string, unknown> = {}, version = VERSION, user = USER) {
|
||||
sessionStorage.setItem(
|
||||
copyKeyOf(version, user),
|
||||
JSON.stringify({
|
||||
v: 1, user_id: user, version_id: version, sheet_id: SHEET, sheet_name: 'Fiche',
|
||||
revision, written_at: '2026-11-03T10:00:00Z', document: JSON.parse(text), drawings: [], ...over,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
describe('writing the copy', () => {
|
||||
it('writes synchronously on a committed change while unsaved, with the base revision', async () => {
|
||||
await openReady({ revision: 3 })
|
||||
expect(storedCopy()).toBeNull()
|
||||
commitMove(40)
|
||||
expect(storedCopy()).toMatchObject({
|
||||
v: 1, user_id: USER, version_id: VERSION, sheet_id: SHEET, sheet_name: 'Fiche', revision: 3,
|
||||
document: JSON.parse(store.getState().documentText),
|
||||
drawings: [{ asset_id: ASSET }],
|
||||
})
|
||||
expect(store.getState()).toMatchObject({ copyWritten: true, copyIssue: null })
|
||||
expect(leaveGuardArmed(store.getState())).toBe(true)
|
||||
})
|
||||
|
||||
it('leaves the copy untouched in a mode that cannot save', async () => {
|
||||
seed(movedText(10), 3)
|
||||
const raw = sessionStorage.getItem(copyKeyOf())
|
||||
await openReady({ canEdit: false })
|
||||
expect(store.getState()).toMatchObject({ recovery: 'none', offer: null, unusableCopy: true })
|
||||
expect(sessionStorage.getItem(copyKeyOf())).toBe(raw)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the blocking offer', () => {
|
||||
it('refuses every change and never writes or removes the copy while pending', async () => {
|
||||
seed(movedText(10), 3)
|
||||
const raw = sessionStorage.getItem(copyKeyOf())
|
||||
await openReady({ revision: 3 })
|
||||
const state = store.getState()
|
||||
expect(state).toMatchObject({ recovery: 'pending', offer: { revision: 3, serverRevision: 3 } })
|
||||
expect(leaveGuardArmed(state)).toBe(true)
|
||||
const blocked = { ok: false, reason: 'blocked', kind: 'recovery.pending' }
|
||||
expect(commitMove(40)).toMatchObject(blocked)
|
||||
expect(state.undoStep()).toMatchObject(blocked)
|
||||
expect(state.redoStep()).toMatchObject(blocked)
|
||||
expect(await state.save()).toMatchObject(blocked)
|
||||
expect(await state.submit()).toMatchObject(blocked)
|
||||
expect(await state.discardChanges({ confirmed: true })).toMatchObject(blocked)
|
||||
expect(await state.reloadServerDraft({ confirmed: true })).toMatchObject(blocked)
|
||||
expect(sb.saveSheetDraft).not.toHaveBeenCalled()
|
||||
expect(sessionStorage.getItem(copyKeyOf())).toBe(raw)
|
||||
expect(state.documentText).toBe(state.savedText)
|
||||
})
|
||||
|
||||
it('offers nothing for a copy equal to the server document, whatever the key order', async () => {
|
||||
seed(baseText(), 3)
|
||||
await openReady()
|
||||
expect(store.getState().recovery).toBe('none')
|
||||
})
|
||||
|
||||
it('needs a confirmation to ignore, then removes the copy and resumes from the server', async () => {
|
||||
seed(movedText(10), 3)
|
||||
await openReady()
|
||||
expect(store.getState().ignoreCopy({ confirmed: false })).toMatchObject({ kind: 'confirmation_required' })
|
||||
expect(storedCopy()).not.toBeNull()
|
||||
expect(store.getState().ignoreCopy({ confirmed: true })).toEqual({ ok: true })
|
||||
expect(storedCopy()).toBeNull()
|
||||
expect(store.getState()).toMatchObject({ recovery: 'none', offer: null })
|
||||
expect(commitMove(40)).toEqual({ ok: true })
|
||||
})
|
||||
})
|
||||
|
||||
describe('restore', () => {
|
||||
it('applies the copy in one store update and rewrites it on its base revision', async () => {
|
||||
seed(movedText(10), 3)
|
||||
await openReady({ revision: 3 })
|
||||
const seen: Array<{ recovery: string; text: string }> = []
|
||||
const stop = store.subscribe((s) => seen.push({ recovery: s.recovery, text: s.documentText }))
|
||||
expect(await store.getState().restoreCopy()).toEqual({ ok: true })
|
||||
stop()
|
||||
const state = store.getState()
|
||||
expect(state.documentText).toBe(movedText(10))
|
||||
expect(state).toMatchObject({ savedRevision: 3, staleBase: false, unsaved: true, recovery: 'none' })
|
||||
expect(state.savedText).toBe(JSON.stringify(JSON.parse(baseText())))
|
||||
expect(seen.filter((s) => s.recovery === 'none').every((s) => s.text === movedText(10))).toBe(true)
|
||||
expect(storedCopy()).toMatchObject({ revision: 3, document: JSON.parse(movedText(10)) })
|
||||
expect(state.previewState?.document.annotations[0]).toMatchObject({ geometry: { cx: 10 } })
|
||||
})
|
||||
|
||||
it('downloads and adds the copy drawings the page lacks', async () => {
|
||||
serverHas(baseText(), 3, false)
|
||||
sb.downloadSheetDrawing.mockResolvedValue(svgBytes().bytes)
|
||||
seed(movedText(10), 3, { drawings: [{ asset_id: ASSET, sha256: svgBytes().sha256 }] })
|
||||
store.getState().open(VERSION, USER)
|
||||
await vi.waitFor(() => expect(store.getState().status).toBe('ready'))
|
||||
expect(store.getState().previewState?.drawings[0]).toMatchObject({ state: 'missing' })
|
||||
await store.getState().restoreCopy()
|
||||
expect(store.getState().previewState?.drawings[0]).toMatchObject({ state: 'ok' })
|
||||
expect(store.getState().drawings).toEqual([expect.objectContaining({ asset_id: ASSET })])
|
||||
})
|
||||
|
||||
it('keeps the base revision R of an older copy, sets staleBase and meets the conflict', async () => {
|
||||
seed(movedText(10), 2)
|
||||
await openReady({ revision: 5 })
|
||||
expect(store.getState().offer).toMatchObject({ revision: 2, serverRevision: 5 })
|
||||
await store.getState().restoreCopy()
|
||||
expect(store.getState()).toMatchObject({ savedRevision: 2, staleBase: true, unsaved: true })
|
||||
commitMove(30)
|
||||
expect(storedCopy()).toMatchObject({ revision: 2 })
|
||||
expect(await store.getState().submit()).toMatchObject({ ok: false, kind: 'stale_base' })
|
||||
sb.saveSheetDraft.mockRejectedValue(new SheetFailure('draft_conflict'))
|
||||
sb.getOfficialSheetAdmin.mockResolvedValue({
|
||||
draft_version: { version_id: VERSION, version_number: 1, revision: 5 },
|
||||
draft_last_save: null,
|
||||
} as never)
|
||||
await store.getState().save()
|
||||
expect(sb.saveSheetDraft).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ expected_revision: 2 }))
|
||||
expect(store.getState().conflict).toMatchObject({ status: 'known', revision: 5 })
|
||||
})
|
||||
|
||||
it('takes the reload path for « Annuler les modifications » under staleBase', async () => {
|
||||
seed(movedText(10), 2)
|
||||
await openReady({ revision: 5 })
|
||||
await store.getState().restoreCopy()
|
||||
serverHas(baseText(), 6)
|
||||
expect(await store.getState().discardChanges({ confirmed: true })).toEqual({ ok: true })
|
||||
expect(store.getState()).toMatchObject({ savedRevision: 6, staleBase: false, unsaved: false })
|
||||
expect(store.getState().documentText).toBe(store.getState().savedText)
|
||||
expect(storedCopy()).toBeNull()
|
||||
})
|
||||
|
||||
it('reports a copy the core refuses, keeps it, blocks editing until ignored', async () => {
|
||||
sessionStorage.setItem(
|
||||
copyKeyOf(),
|
||||
JSON.stringify({
|
||||
v: 1, user_id: USER, version_id: VERSION, sheet_id: SHEET, sheet_name: 'X',
|
||||
revision: 3, written_at: 'T', document: { not: 'a document' }, drawings: [],
|
||||
}),
|
||||
)
|
||||
const raw = sessionStorage.getItem(copyKeyOf())
|
||||
await openReady()
|
||||
const outcome = await store.getState().restoreCopy()
|
||||
expect(outcome).toMatchObject({ ok: false, reason: 'core' })
|
||||
const state = store.getState()
|
||||
expect(state.recovery).toBe('refused')
|
||||
expect(state.refusedKind).toEqual(expect.any(String))
|
||||
expect(state.documentText).toBe(state.savedText)
|
||||
expect(commitMove(40)).toMatchObject({ kind: 'recovery.pending' })
|
||||
expect(await state.restoreCopy()).toMatchObject({ ok: false })
|
||||
expect(sessionStorage.getItem(copyKeyOf())).toBe(raw)
|
||||
expect(store.getState().ignoreCopy({ confirmed: true })).toEqual({ ok: true })
|
||||
expect(commitMove(40)).toEqual({ ok: true })
|
||||
})
|
||||
})
|
||||
|
||||
describe('an unreadable copy', () => {
|
||||
it.each([
|
||||
['malformed JSON', () => 'not json{'],
|
||||
['an unknown version', () => JSON.stringify({ v: 2 })],
|
||||
['another user in the key', () =>
|
||||
JSON.stringify({ v: 1, user_id: 'x', version_id: VERSION, sheet_id: SHEET, sheet_name: '', revision: 1, written_at: 'T', document: {}, drawings: [] })],
|
||||
])('is refused and kept byte for byte (%s)', async (_label, raw) => {
|
||||
sessionStorage.setItem(copyKeyOf(), raw())
|
||||
await openReady()
|
||||
expect(store.getState()).toMatchObject({ recovery: 'refused', refusedKind: 'unreadable' })
|
||||
expect(commitMove(40)).toMatchObject({ kind: 'recovery.pending' })
|
||||
expect(sessionStorage.getItem(copyKeyOf())).toBe(raw())
|
||||
expect(leaveGuardArmed(store.getState())).toBe(true)
|
||||
expect(store.getState().ignoreCopy({ confirmed: false })).toMatchObject({ kind: 'confirmation_required' })
|
||||
expect(store.getState().ignoreCopy({ confirmed: true })).toEqual({ ok: true })
|
||||
expect(storedCopy()).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('cap, quota and other accounts', () => {
|
||||
const other = (n: number) => `ver-other-${n}`
|
||||
|
||||
it('refuses a third version, keeps both others, retries after an explicit abandonment', async () => {
|
||||
seed(baseText(), 1, {}, other(1))
|
||||
seed(baseText(), 2, { sheet_name: 'Autre' }, other(2))
|
||||
await openReady()
|
||||
commitMove(40)
|
||||
expect(store.getState()).toMatchObject({ copyWritten: false, copyIssue: 'cap' })
|
||||
expect(storedCopy()).toBeNull()
|
||||
expect(store.getState().otherCopies.map((c) => [c.versionId, c.revision])).toEqual([
|
||||
[other(1), 1], [other(2), 2],
|
||||
])
|
||||
expect(store.getState().abandonOtherCopy(other(1), { confirmed: false })).toMatchObject({ kind: 'confirmation_required' })
|
||||
expect(storedCopy(other(1))).not.toBeNull()
|
||||
expect(store.getState().abandonOtherCopy(other(1), { confirmed: true })).toEqual({ ok: true })
|
||||
expect(storedCopy(other(1))).toBeNull()
|
||||
expect(storedCopy(other(2))).not.toBeNull()
|
||||
expect(storedCopy()).not.toBeNull()
|
||||
expect(store.getState()).toMatchObject({ copyWritten: true, copyIssue: null })
|
||||
})
|
||||
|
||||
it('reports a full storage and keeps the work in the document', async () => {
|
||||
await openReady()
|
||||
const spy = vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
|
||||
throw new DOMException('full', 'QuotaExceededError')
|
||||
})
|
||||
commitMove(40)
|
||||
expect(store.getState()).toMatchObject({ copyWritten: false, copyIssue: 'quota', unsaved: true })
|
||||
spy.mockRestore()
|
||||
store.getState().retryCopyWrite()
|
||||
expect(store.getState()).toMatchObject({ copyWritten: true, copyIssue: null })
|
||||
})
|
||||
|
||||
it('never lists, counts, offers or removes the copies of another account', async () => {
|
||||
seed(movedText(10), 3, {}, VERSION, 'user-2')
|
||||
seed(baseText(), 1, {}, other(1), 'user-2')
|
||||
seed(baseText(), 1, {}, other(2), 'user-2')
|
||||
seed(baseText(), 1, {}, other(3), 'user-2')
|
||||
await openReady()
|
||||
expect(store.getState()).toMatchObject({ recovery: 'none', otherCopies: [] })
|
||||
commitMove(40)
|
||||
expect(store.getState()).toMatchObject({ copyWritten: true, copyIssue: null })
|
||||
expect(store.getState().abandonOtherCopy(other(1), { confirmed: true })).toEqual({ ok: true })
|
||||
for (const version of [VERSION, other(1), other(2), other(3)]) {
|
||||
expect(storedCopy(version, 'user-2')).not.toBeNull()
|
||||
}
|
||||
})
|
||||
|
||||
it('removes the copy only on the explicit outcomes', async () => {
|
||||
await openReady()
|
||||
commitMove(40)
|
||||
store.getState().undoStep()
|
||||
store.getState().redoStep()
|
||||
sb.saveSheetDraft.mockRejectedValue(new SheetFailure('draft.frozen'))
|
||||
await store.getState().save()
|
||||
expect(storedCopy()).not.toBeNull()
|
||||
sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never)
|
||||
await store.getState().save()
|
||||
expect(storedCopy()).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,334 @@
|
||||
/** Lot D: the editor store on the Node core, Supabase accessors mocked at the module boundary. */
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { SheetFailure } from '@faunosteo/supabase'
|
||||
import { leaveGuardArmed, canRedo, canUndo } from '@/editor/state/editorStore'
|
||||
import {
|
||||
USER, VERSION, baseText, commitMove, moveCommand, openReady, resetStore, sb, serverHas,
|
||||
storedCopy, store,
|
||||
} from '../helpers/editorHarness'
|
||||
import { ASSET } from '../helpers/editorFixtures'
|
||||
|
||||
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
|
||||
vi.mock('@faunosteo/supabase', async (orig) => ({
|
||||
...(await orig<typeof import('@faunosteo/supabase')>()),
|
||||
getSheetVersion: vi.fn(),
|
||||
downloadSheetDrawing: vi.fn(),
|
||||
saveSheetDraft: vi.fn(),
|
||||
getOfficialSheetAdmin: vi.fn(),
|
||||
submitSheetReview: vi.fn(),
|
||||
}))
|
||||
|
||||
afterEach(resetStore)
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
let reject!: (error: unknown) => void
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res
|
||||
reject = rej
|
||||
})
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
describe('open and sessions', () => {
|
||||
it('loads the draft with its revision and drawings from one read', async () => {
|
||||
await openReady({ revision: 3 })
|
||||
const state = store.getState()
|
||||
expect(state).toMatchObject({ status: 'ready', savedRevision: 3, unsaved: false, recovery: 'none' })
|
||||
expect(state.documentText).toBe(state.savedText)
|
||||
expect(state.drawings).toEqual([expect.objectContaining({ asset_id: ASSET })])
|
||||
expect(state.previewState?.drawings[0]).toMatchObject({ state: 'ok' })
|
||||
expect(state.handleVersion).toBe(1)
|
||||
})
|
||||
|
||||
it('does not fail the load on a drawing that cannot be downloaded', async () => {
|
||||
sb.downloadSheetDrawing.mockRejectedValue(new SheetFailure('not_found'))
|
||||
serverHas(baseText(), 3)
|
||||
sb.downloadSheetDrawing.mockRejectedValue(new SheetFailure('not_found'))
|
||||
store.getState().open(VERSION, USER)
|
||||
await vi.waitFor(() => expect(store.getState().status).toBe('ready'))
|
||||
expect(store.getState().drawingFailures[ASSET]).toBe('drawing_missing')
|
||||
expect(store.getState().previewState?.drawings[0]).toMatchObject({ state: 'missing' })
|
||||
})
|
||||
|
||||
it('drops a late load after close and frees the preview it built', async () => {
|
||||
const late = deferred<unknown>()
|
||||
sb.getSheetVersion.mockReturnValue(late.promise as never)
|
||||
store.getState().open(VERSION, USER)
|
||||
store.getState().close()
|
||||
late.resolve({})
|
||||
await Promise.resolve()
|
||||
expect(store.getState()).toMatchObject({ status: 'idle', preview: null })
|
||||
})
|
||||
|
||||
it('lets the second open of a StrictMode double mount win over the first', async () => {
|
||||
const first = deferred<unknown>()
|
||||
sb.getSheetVersion.mockReturnValueOnce(first.promise as never)
|
||||
const one = store.getState().open(VERSION, USER)
|
||||
store.getState().close()
|
||||
serverHas(baseText(), 7)
|
||||
const two = store.getState().open(VERSION, USER)
|
||||
expect(two).toBeGreaterThan(one)
|
||||
await vi.waitFor(() => expect(store.getState().status).toBe('ready'))
|
||||
first.resolve({ sheet_id: 'x' })
|
||||
await Promise.resolve()
|
||||
expect(store.getState().savedRevision).toBe(7)
|
||||
})
|
||||
|
||||
it('drops a save answer that lands after close', async () => {
|
||||
await openReady()
|
||||
commitMove(40)
|
||||
const answer = deferred<unknown>()
|
||||
sb.saveSheetDraft.mockReturnValue(answer.promise as never)
|
||||
const saving = store.getState().save()
|
||||
store.getState().close()
|
||||
answer.resolve({ revision: 4 })
|
||||
expect(await saving).toMatchObject({ ok: false, reason: 'blocked', kind: 'session_changed' })
|
||||
expect(store.getState()).toMatchObject({ status: 'idle', savedRevision: 0 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('commit, undo, redo', () => {
|
||||
it('commits in one store update', async () => {
|
||||
await openReady()
|
||||
const before = store.getState()
|
||||
expect(commitMove(40)).toEqual({ ok: true })
|
||||
const after = store.getState()
|
||||
expect(after.documentText).not.toBe(before.documentText)
|
||||
expect(after).toMatchObject({ unsaved: true, handleVersion: before.handleVersion + 1 })
|
||||
expect(after.undo).toHaveLength(1)
|
||||
expect(after.previewState).not.toBe(before.previewState)
|
||||
})
|
||||
|
||||
it('keeps nothing on a core refusal or an accept refusal', async () => {
|
||||
await openReady()
|
||||
const before = store.getState()
|
||||
const missing = store.getState().commit({ op: 'remove', key: { kind: 'annotation', id: 'nope' } })
|
||||
expect(missing).toMatchObject({ ok: false, reason: 'core' })
|
||||
const refused = store.getState().commit(moveCommand(40), {
|
||||
accept: () => ({ accepted: false, refusal: 'no' as const }),
|
||||
})
|
||||
expect(refused).toEqual({ ok: false, reason: 'refused', refusal: 'no' })
|
||||
const after = store.getState()
|
||||
expect(after.documentText).toBe(before.documentText)
|
||||
expect(after.handleVersion).toBe(before.handleVersion)
|
||||
expect(after.undo).toHaveLength(0)
|
||||
expect(storedCopy()).toBeNull()
|
||||
expect(after.preview?.document).toBe(before.documentText)
|
||||
})
|
||||
|
||||
it('undoes, redoes, and clears redo on a new commit', async () => {
|
||||
await openReady()
|
||||
const saved = store.getState().documentText
|
||||
commitMove(40)
|
||||
commitMove(30)
|
||||
expect(store.getState().undoStep()).toEqual({ ok: true })
|
||||
expect(canRedo(store.getState())).toBe(true)
|
||||
expect(store.getState().redoStep()).toEqual({ ok: true })
|
||||
store.getState().undoStep()
|
||||
commitMove(20)
|
||||
expect(canRedo(store.getState())).toBe(false)
|
||||
expect(store.getState().undo).toHaveLength(2)
|
||||
store.getState().undoStep()
|
||||
store.getState().undoStep()
|
||||
expect(store.getState().documentText).toBe(saved)
|
||||
expect(store.getState().unsaved).toBe(false)
|
||||
expect(canUndo(store.getState())).toBe(false)
|
||||
expect(store.getState().undoStep()).toMatchObject({ ok: false, kind: 'empty' })
|
||||
})
|
||||
|
||||
it('keeps the copy when undo returns to the saved content', async () => {
|
||||
await openReady()
|
||||
commitMove(40)
|
||||
const written = storedCopy()
|
||||
store.getState().undoStep()
|
||||
expect(store.getState().unsaved).toBe(false)
|
||||
expect(storedCopy()).toEqual(written)
|
||||
})
|
||||
|
||||
it('refuses every change in a read-only mode', async () => {
|
||||
await openReady({ canEdit: false })
|
||||
expect(commitMove(40)).toMatchObject({ ok: false, kind: 'read_only' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('save', () => {
|
||||
it('saves against the saved revision and removes the copy', async () => {
|
||||
await openReady({ revision: 3 })
|
||||
commitMove(40)
|
||||
expect(storedCopy()).not.toBeNull()
|
||||
sb.saveSheetDraft.mockResolvedValue({ revision: 4 } as never)
|
||||
const sent = store.getState().documentText
|
||||
expect(await store.getState().save()).toEqual({ ok: true, revision: 4 })
|
||||
expect(sb.saveSheetDraft).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({ version_id: VERSION, expected_revision: 3 }),
|
||||
)
|
||||
expect(store.getState()).toMatchObject({ savedRevision: 4, savedText: sent, unsaved: false })
|
||||
expect(storedCopy()).toBeNull()
|
||||
expect(leaveGuardArmed(store.getState())).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps the sent text and rewrites the copy on the new revision for commits in flight', async () => {
|
||||
await openReady({ revision: 3 })
|
||||
commitMove(40)
|
||||
const sent = store.getState().documentText
|
||||
const answer = deferred<unknown>()
|
||||
sb.saveSheetDraft.mockReturnValue(answer.promise as never)
|
||||
const saving = store.getState().save()
|
||||
commitMove(30)
|
||||
const latest = store.getState().documentText
|
||||
answer.resolve({ revision: 4 })
|
||||
await saving
|
||||
expect(store.getState()).toMatchObject({ savedText: sent, savedRevision: 4, unsaved: true })
|
||||
expect(storedCopy()).toMatchObject({ revision: 4, document: JSON.parse(latest) })
|
||||
})
|
||||
|
||||
it('treats draft.unchanged as saved at the revision sent', async () => {
|
||||
await openReady({ revision: 3 })
|
||||
commitMove(40)
|
||||
sb.saveSheetDraft.mockRejectedValue(new SheetFailure('draft.unchanged'))
|
||||
const sent = store.getState().documentText
|
||||
expect(await store.getState().save()).toEqual({ ok: true, revision: 3 })
|
||||
expect(store.getState()).toMatchObject({ savedText: sent, savedRevision: 3, unsaved: false })
|
||||
expect(storedCopy()).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the document and the copy on any other server kind', async () => {
|
||||
await openReady()
|
||||
commitMove(40)
|
||||
sb.saveSheetDraft.mockRejectedValue(new SheetFailure('draft.frozen'))
|
||||
expect(await store.getState().save()).toEqual({ ok: false, reason: 'server', kind: 'draft.frozen' })
|
||||
expect(store.getState()).toMatchObject({ unsaved: true, saveFailure: 'draft.frozen', saving: false })
|
||||
expect(storedCopy()).not.toBeNull()
|
||||
})
|
||||
|
||||
it('refuses a second save while one is in flight', async () => {
|
||||
await openReady()
|
||||
commitMove(40)
|
||||
sb.saveSheetDraft.mockReturnValue(deferred<unknown>().promise as never)
|
||||
void store.getState().save()
|
||||
expect(await store.getState().save()).toMatchObject({ ok: false, kind: 'busy' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('conflict', () => {
|
||||
async function conflicted(admin: unknown | 'fail', revision = 5) {
|
||||
await openReady({ revision: 3 })
|
||||
commitMove(40)
|
||||
sb.saveSheetDraft.mockRejectedValue(new SheetFailure('draft_conflict'))
|
||||
if (admin === 'fail') sb.getOfficialSheetAdmin.mockRejectedValue(new SheetFailure('network'))
|
||||
else sb.getOfficialSheetAdmin.mockResolvedValue(admin as never)
|
||||
const outcome = await store.getState().save()
|
||||
expect(outcome).toMatchObject({ ok: false, kind: 'draft_conflict' })
|
||||
return revision
|
||||
}
|
||||
|
||||
const adminWith = (over: Record<string, unknown>) => ({
|
||||
draft_version: { version_id: VERSION, version_number: 1, revision: 5 },
|
||||
draft_last_save: null,
|
||||
...over,
|
||||
})
|
||||
|
||||
it('takes N from draft_version and the author only when draft_last_save matches N', async () => {
|
||||
const person = { user_id: 'other', display_name: 'Marie' }
|
||||
await conflicted(adminWith({ draft_last_save: { revision: 5, saved_at: 'T', saved_by: person } }))
|
||||
expect(store.getState().conflict).toEqual({
|
||||
status: 'known',
|
||||
revision: 5,
|
||||
lastSave: { savedAt: 'T', savedBy: person, byCaller: false },
|
||||
})
|
||||
})
|
||||
|
||||
it('omits the author when draft_last_save is for another revision, flags the caller', async () => {
|
||||
await conflicted(adminWith({ draft_last_save: { revision: 4, saved_at: 'T', saved_by: null } }))
|
||||
expect(store.getState().conflict).toEqual({ status: 'known', revision: 5, lastSave: null })
|
||||
const me = { user_id: USER, display_name: 'Moi' }
|
||||
sb.getOfficialSheetAdmin.mockResolvedValue(
|
||||
adminWith({ draft_last_save: { revision: 5, saved_at: 'T', saved_by: me } }) as never,
|
||||
)
|
||||
await store.getState().retryConflictRead()
|
||||
expect(store.getState().conflict).toMatchObject({ lastSave: { byCaller: true } })
|
||||
})
|
||||
|
||||
it('is unknown on a failed read, another version or no draft_version, and refuses keepMine', async () => {
|
||||
await conflicted('fail')
|
||||
expect(store.getState().conflict).toEqual({ status: 'unknown' })
|
||||
expect(await store.getState().keepMine({ confirmed: true })).toMatchObject({ kind: 'revision_unknown' })
|
||||
sb.getOfficialSheetAdmin.mockResolvedValue(
|
||||
adminWith({ draft_version: { version_id: 'other', version_number: 1, revision: 9 } }) as never,
|
||||
)
|
||||
await store.getState().retryConflictRead()
|
||||
expect(store.getState().conflict).toEqual({ status: 'unknown' })
|
||||
sb.getOfficialSheetAdmin.mockResolvedValue(adminWith({ draft_version: null }) as never)
|
||||
await store.getState().retryConflictRead()
|
||||
expect(store.getState().conflict).toEqual({ status: 'unknown' })
|
||||
})
|
||||
|
||||
it('keeps my version only after confirmation, against N', async () => {
|
||||
await conflicted(adminWith({}))
|
||||
sb.saveSheetDraft.mockClear()
|
||||
expect(await store.getState().keepMine({ confirmed: false })).toMatchObject({ kind: 'confirmation_required' })
|
||||
expect(sb.saveSheetDraft).not.toHaveBeenCalled()
|
||||
sb.saveSheetDraft.mockResolvedValue({ revision: 6 } as never)
|
||||
expect(await store.getState().keepMine({ confirmed: true })).toEqual({ ok: true, revision: 6 })
|
||||
expect(sb.saveSheetDraft).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({ expected_revision: 5 }),
|
||||
)
|
||||
expect(store.getState()).toMatchObject({ savedRevision: 6, unsaved: false, conflict: null })
|
||||
})
|
||||
|
||||
it('re-reads on a new conflict and never writes by itself', async () => {
|
||||
await conflicted(adminWith({}))
|
||||
sb.saveSheetDraft.mockClear()
|
||||
sb.saveSheetDraft.mockRejectedValue(new SheetFailure('draft_conflict'))
|
||||
sb.getOfficialSheetAdmin.mockResolvedValue(
|
||||
adminWith({ draft_version: { version_id: VERSION, version_number: 1, revision: 8 } }) as never,
|
||||
)
|
||||
await store.getState().keepMine({ confirmed: true })
|
||||
expect(sb.saveSheetDraft).toHaveBeenCalledTimes(1)
|
||||
expect(store.getState().conflict).toMatchObject({ status: 'known', revision: 8 })
|
||||
store.getState().dismissConflict()
|
||||
expect(store.getState()).toMatchObject({ conflict: null, unsaved: true, savedRevision: 3 })
|
||||
})
|
||||
|
||||
it('reloads the server draft after confirmation: stacks cleared, copy removed', async () => {
|
||||
await conflicted(adminWith({}))
|
||||
const server = baseText().replace('"Fiche"', '"Serveur"')
|
||||
serverHas(server, 5)
|
||||
expect(await store.getState().reloadServerDraft({ confirmed: false })).toMatchObject({ kind: 'confirmation_required' })
|
||||
expect(storedCopy()).not.toBeNull()
|
||||
expect(await store.getState().reloadServerDraft({ confirmed: true })).toEqual({ ok: true })
|
||||
expect(store.getState()).toMatchObject({
|
||||
savedRevision: 5, unsaved: false, conflict: null, undo: [], redo: [], staleBase: false,
|
||||
})
|
||||
expect(store.getState().documentText).toBe(JSON.stringify(JSON.parse(server)))
|
||||
expect(storedCopy()).toBeNull()
|
||||
expect(sb.downloadSheetDrawing).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('discard and submit', () => {
|
||||
it('discards back to the saved text after confirmation, clears stacks, removes the copy', async () => {
|
||||
await openReady()
|
||||
const saved = store.getState().savedText
|
||||
commitMove(40)
|
||||
expect(await store.getState().discardChanges({ confirmed: false })).toMatchObject({ kind: 'confirmation_required' })
|
||||
expect(await store.getState().discardChanges({ confirmed: true })).toEqual({ ok: true })
|
||||
expect(store.getState()).toMatchObject({ documentText: saved, unsaved: false, undo: [], redo: [] })
|
||||
expect(storedCopy()).toBeNull()
|
||||
})
|
||||
|
||||
it('submits the saved revision and never re-submits on a conflict', async () => {
|
||||
await openReady({ revision: 3 })
|
||||
sb.submitSheetReview.mockResolvedValue('review-1' as never)
|
||||
expect(await store.getState().submit()).toEqual({ ok: true, reviewId: 'review-1' })
|
||||
expect(sb.submitSheetReview).toHaveBeenCalledWith(expect.anything(), { version_id: VERSION, expected_revision: 3 })
|
||||
sb.submitSheetReview.mockRejectedValue(new SheetFailure('draft_conflict'))
|
||||
sb.getOfficialSheetAdmin.mockRejectedValue(new SheetFailure('network'))
|
||||
expect(await store.getState().submit()).toMatchObject({ kind: 'draft_conflict' })
|
||||
expect(sb.submitSheetReview).toHaveBeenCalledTimes(2)
|
||||
expect(store.getState().conflict).toEqual({ status: 'unknown' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,38 @@
|
||||
/** Lot D: the history's byte bound and its steps. */
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
HISTORY_LIMIT_BYTES, emptyHistory, entryOf, recordCommit, stepBack, stepForward,
|
||||
} from '@/editor/state/undo'
|
||||
|
||||
const chunk = (bytes: number, tag: string) => tag + 'x'.repeat(bytes - tag.length)
|
||||
|
||||
describe('history', () => {
|
||||
it('measures the UTF-8 size of each entry once', () => {
|
||||
expect(entryOf('é').bytes).toBe(2)
|
||||
})
|
||||
|
||||
it('drops the oldest undo entries while both stacks exceed the bound', () => {
|
||||
const third = Math.floor(HISTORY_LIMIT_BYTES / 3) + 1
|
||||
let history = emptyHistory()
|
||||
for (const tag of ['a', 'b', 'c', 'd']) history = recordCommit(history, chunk(third, tag))
|
||||
expect(history.undo.map((e) => e.text[0])).toEqual(['c', 'd'])
|
||||
const total = history.undo.reduce((sum, e) => sum + e.bytes, 0)
|
||||
expect(total).toBeLessThanOrEqual(HISTORY_LIMIT_BYTES)
|
||||
})
|
||||
|
||||
it('counts the redo stack in the bound and clears it on a commit', () => {
|
||||
const half = Math.floor(HISTORY_LIMIT_BYTES / 2)
|
||||
let history = recordCommit(recordCommit(emptyHistory(), chunk(half, 'a')), chunk(half, 'b'))
|
||||
const back = stepBack(history, chunk(half, 'c'))
|
||||
expect(back?.text[0]).toBe('b')
|
||||
history = back!.history
|
||||
expect(history.redo).toHaveLength(1)
|
||||
expect(stepForward(history, 'now')?.text[0]).toBe('c')
|
||||
expect(recordCommit(history, 'z').redo).toEqual([])
|
||||
})
|
||||
|
||||
it('answers null with nothing to step to', () => {
|
||||
expect(stepBack(emptyHistory(), 'x')).toBeNull()
|
||||
expect(stepForward(emptyHistory(), 'x')).toBeNull()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user