feat(editor): repair out-of-frame annotations when attaching a drawing

This commit is contained in:
bchanot committed 2026-11-04 20:10:07 +01:00
1 parent 4ab85adeb0
commit 3776a33b79
22 files changed
+1277 -19

No files matched your search

@@ -23,10 +23,11 @@ export interface CommitContext {
locale: Locale
}
function describe(
/** The words for a geometry commit that was not kept. */
export function describeOutcome(
outcome: Exclude<CommitOutcome<GeometryRefusal>, { ok: true }>,
{ t, locale }: CommitContext,
): CommitResult {
): Extract<CommitResult, { ok: false }> {
if (outcome.reason !== 'refused') {
const duplicate =
outcome.reason === 'core' && outcome.failure.kind === 'duplicate_key'
@@ -67,7 +68,7 @@ function commitGeometry(
}
const accept = geometryAccept({ before, changedIds: [annotationId] })
const outcome = store.commit(command, { accept })
return outcome.ok ? { ok: true } : describe(outcome, context)
return outcome.ok ? { ok: true } : describeOutcome(outcome, context)
}
/** Inserts a new annotation under a fresh id; one regeneration on `duplicate_key`. */
+17
View File
@@ -25,6 +25,23 @@ export function applyEdit(
: outcome
}
/**
* Commands applied in order on a scratch text, each on the previous result. The first
* refusal ends the run and is the answer; nothing outside the returned text changes.
*/
export function applyEdits(
text: string,
commands: readonly EditCommand[],
): CoreOutcome<string> {
let current = text
for (const command of commands) {
const edited = applyEdit(current, command)
if (!edited.ok) return edited
current = edited.value
}
return { ok: true, value: current }
}
/** What refers to the element `key` (removal and rename warnings). */
export function dependentsOf(
text: string,
+12 -2
View File
@@ -16,6 +16,7 @@ import { cleanSvg } from './core/cleaning'
import { rejectionReason } from './drawingReason'
import type { GeometryRefusal } from './issues'
import { useEditorStore } from './state/editorStore'
import { repairOffer, type RepairOffer } from './repair'
import { updateView } from './viewUpdate'
/** The size the upload path accepts (plan « Upload »); the core caps the rest. */
@@ -35,6 +36,7 @@ export type UploadError =
| { code: 'sheet'; kind: SheetFailureKind }
| { code: 'catalogue'; failure: CatalogueFailure }
| { code: 'frame'; refusal: GeometryRefusal }
| { code: 'repair'; offer: RepairOffer }
export type Step<T> = { ok: true; value: T } | { ok: false; error: UploadError }
@@ -164,7 +166,13 @@ export async function downloadAndHold(
}
/** A drawing the core holds as refused is a closed upload code, not a frame message. */
function refusedAttach(refusal: GeometryRefusal): UploadError {
function refusedAttach(
viewId: string,
assetId: string,
refusal: GeometryRefusal,
): UploadError {
const offer = repairOffer(viewId, assetId, refusal)
if (offer) return { code: 'repair', offer }
if (refusal.reason !== 'drawing_rejected') return { code: 'frame', refusal }
const reason = rejectionReason(refusal.drawingDetail ?? null)
return reason === 'not_canonical'
@@ -176,7 +184,9 @@ function refusedAttach(refusal: GeometryRefusal): UploadError {
export function attachToView(viewId: string, assetId: string): Step<null> {
const outcome = updateView(viewId, { svg_asset_id: assetId }, true)
if (outcome.ok) return done(null)
if (outcome.reason === 'refused') return fail(refusedAttach(outcome.refusal))
if (outcome.reason === 'refused') {
return fail(refusedAttach(viewId, assetId, outcome.refusal))
}
return fail({ code: outcome.reason === 'blocked' ? 'blocked' : 'core' })
}
+4 -1
View File
@@ -39,7 +39,10 @@ export function frameRefusalMessage(
named('view', refusal.viewIds),
)
}
return t('editor.views.frame.newly_invalid').replace(
const key = refusal.repairFrames
? 'editor.views.frame.newly_invalid_repairable'
: 'editor.views.frame.newly_invalid'
return t(key).replace(
'{names}',
named('annotation', refusal.annotationIds),
)
+6
View File
@@ -1,5 +1,6 @@
import type { PreviewState, SheetView } from '@faunosteo/core-wasm/types'
import type { Acceptance } from '@/catalogue/preview'
import type { Frame } from './annotations/frame'
/**
* Pure readers over ONE `PreviewState`: the issue paths are indexes into the document of
@@ -93,6 +94,11 @@ export interface GeometryRefusal {
viewIds: string[]
/** The core's detail for a `drawing_rejected` refusal (mapped, never shown). */
drawingDetail?: string
/**
* `newly_invalid` on views that were unmeasured before: the composed frame each of them
* gets, which makes the refusal repairable (Lot N3). Absent for a measured view (C33).
*/
repairFrames?: Record<string, Frame>
}
export interface GeometryAcceptInput {
+275
View File
@@ -0,0 +1,275 @@
import type {
Annotation,
EditCommand,
Geometry,
Point,
PreviewState,
SheetView,
} from '@faunosteo/core-wasm/types'
import type { Acceptance } from '@/catalogue/preview'
import { buildView } from '@/components/catalogue/CatalogueCanvas'
import {
describeOutcome,
type CommitContext,
} from './annotations/annotationCommit'
import { isEditable } from './annotations/geometryEdit'
import {
centreTriangle,
correctedCircle,
parseFrame,
type Frame,
} from './annotations/frame'
import {
geometryAccept,
rejectedDrawingFault,
unmeasuredViews,
type GeometryRefusal,
} from './issues'
import { useEditorStore } from './state/editorStore'
import type { CommitOutcome } from './state/editorTypes'
/**
* Repair on attach (owner decision 7, ruling R23). Attaching a drawing to an unmeasured
* view whose annotations fall outside the new frame is offered a temporary form instead
* of a dead end. The page only PROPOSES values (UI arithmetic over the frame); the core
* decides on the end state of one batch, so nothing here copies a geometry rule.
*/
/** What the dialog needs: the view, the held drawing and the new frame of each view. */
export interface RepairOffer {
/** The editor session that made the offer: another session never applies it. */
session: number
viewId: string
assetId: string
/** The composed frame of every view holding a listed annotation, in the candidate. */
frames: Record<string, Frame>
refusal: GeometryRefusal
}
const clamp = (value: number, low: number, high: number): number =>
Math.min(Math.max(value, low), high)
function clampedVertex(frame: Frame, [x, y]: Point): Point {
return [
clamp(x, frame.x, frame.x + frame.w),
clamp(y, frame.y, frame.y + frame.h),
]
}
/**
* A proposal in the new frame: a point goes through the creation arithmetic (candidate
* C), a polygon gets each vertex clamped into the frame. A path has no numbers to move:
* it is returned as it is, and the user converts it.
*/
export function proposeGeometry(frame: Frame, geometry: Geometry): Geometry {
if (geometry.type === 'circle') {
const at = { x: geometry.cx, y: geometry.cy }
return { type: 'circle', ...correctedCircle(frame, at) }
}
if (geometry.type === 'polygon') {
const points = geometry.points.map((p) => clampedVertex(frame, p))
return { type: 'polygon', points }
}
return geometry
}
/** « Remplacer par un polygone » inside the temporary form: a triangle to edit. */
export function polygonReplacement(frame: Frame): Geometry {
return { type: 'polygon', points: centreTriangle(frame) }
}
/** The annotations the refusal lists, in document order. */
export function listedAnnotations(
offer: RepairOffer,
doc: { annotations: readonly Annotation[] },
): Annotation[] {
const ids = new Set(offer.refusal.annotationIds)
return doc.annotations.filter((annotation) => ids.has(annotation.id))
}
export function initialGeometries(
offer: RepairOffer,
annotations: readonly Annotation[],
): Record<string, Geometry> {
const proposals: Record<string, Geometry> = {}
for (const annotation of annotations) {
const frame = offer.frames[annotation.view_id]
if (annotation.geometry && frame) {
proposals[annotation.id] = proposeGeometry(frame, annotation.geometry)
}
}
return proposals
}
/** Attaching stays blocked while a listed annotation still has numbers the page cannot edit. */
export function blockedIds(geometries: Record<string, Geometry>): string[] {
return Object.entries(geometries)
.filter(([, geometry]) => !isEditable(geometry))
.map(([id]) => id)
}
/** The frame of `viewId` as the CANDIDATE document composes it (read inside `accept`). */
function candidateFrame(viewId: string): Frame | null {
const preview = useEditorStore.getState().preview
const built = preview ? buildView(preview, viewId) : null
return built?.ok ? parseFrame(built.svg.getAttribute('viewBox')) : null
}
function framesOfListed(
before: PreviewState,
after: PreviewState,
ids: readonly string[],
): Record<string, Frame> | null {
const viewIds = after.document.annotations
.filter((annotation) => ids.includes(annotation.id))
.map((annotation) => annotation.view_id)
const unmeasured = unmeasuredViews(before)
const frames: Record<string, Frame> = {}
for (const viewId of new Set(viewIds)) {
const frame = unmeasured.has(viewId) ? candidateFrame(viewId) : null
if (!frame) return null
frames[viewId] = frame
}
return frames
}
/**
* Marks a `newly_invalid` refusal as repairable when every listed annotation sits on a
* view that was unmeasured before: the refusal then carries the new frames. A measured
* view keeps its refusal as it is (C33).
*/
export function markRepairable(
verdict: Acceptance<GeometryRefusal>,
before: PreviewState,
after: PreviewState,
): Acceptance<GeometryRefusal> {
if (verdict.accepted || verdict.refusal.reason !== 'newly_invalid') {
return verdict
}
const { refusal } = verdict
const frames = framesOfListed(before, after, refusal.annotationIds)
return frames
? { accepted: false, refusal: { ...refusal, repairFrames: frames } }
: verdict
}
/** The offer an attach refusal opens, or null when the refusal is not repairable. */
export function repairOffer(
viewId: string,
assetId: string,
refusal: GeometryRefusal,
): RepairOffer | null {
if (refusal.reason !== 'newly_invalid' || !refusal.repairFrames) return null
const { session } = useEditorStore.getState()
return { session, viewId, assetId, frames: refusal.repairFrames, refusal }
}
function updateAnnotation(
annotation: Annotation,
geometry: Geometry,
): EditCommand {
return {
op: 'update',
key: { kind: 'annotation', id: annotation.id },
element: { kind: 'annotation', value: { ...annotation, geometry } },
}
}
/**
* The geometries first, the view last: the core then turns the redrawn view's annotations
* `to_confirm` itself, after the page's copies of them were written. Only the end text is
* judged, so the order of the intermediate texts is free.
*/
export function repairCommands(
view: SheetView,
assetId: string,
repairs: readonly { annotation: Annotation; geometry: Geometry }[],
): EditCommand[] {
const attach: EditCommand = {
op: 'update',
key: { kind: 'view', id: view.id },
element: { kind: 'view', value: { ...view, svg_asset_id: assetId } },
}
return [
...repairs.map((r) => updateAnnotation(r.annotation, r.geometry)),
attach,
]
}
/** « Attacher et appliquer » refused: the words, in general and per annotation. */
export type RepairResult =
| { ok: true }
| {
ok: false
general: string | null
byAnnotation: Record<string, string[]>
}
function issueMessages(refusal: GeometryRefusal) {
const byAnnotation: Record<string, string[]> = {}
for (const issue of refusal.issues) {
const known = byAnnotation[issue.annotationId] ?? []
if (!known.includes(issue.message)) known.push(issue.message)
byAnnotation[issue.annotationId] = known
}
return byAnnotation
}
function blockedResult(context: CommitContext): RepairResult {
const general = context.t('editor.refusal.blocked')
return { ok: false, general, byAnnotation: {} }
}
function refusedResult(
outcome: Exclude<CommitOutcome<GeometryRefusal>, { ok: true }>,
context: CommitContext,
): RepairResult {
if (
outcome.reason === 'refused' &&
outcome.refusal.reason === 'changed_invalid'
) {
return {
ok: false,
general: null,
byAnnotation: issueMessages(outcome.refusal),
}
}
const [general] = describeOutcome(outcome, context).messages
return { ok: false, general: general ?? null, byAnnotation: {} }
}
/** The end-state verdict: a refused drawing first, then the geometry of the repaired ids. */
function repairAccept(before: PreviewState, assetId: string, ids: string[]) {
const geometry = geometryAccept({ before, changedIds: ids })
return (after: PreviewState) =>
rejectedDrawingFault(after, assetId) ?? geometry(after)
}
/**
* ONE batch: the listed annotations take the typed geometries and the view takes the
* drawing, judged by the core on the end state (`geometryAccept` on the repaired ids).
* Accepted: one commit, one undo entry. Refused: nothing kept.
*/
export function applyRepair(
offer: RepairOffer,
geometries: Record<string, Geometry>,
context: CommitContext,
): RepairResult {
const store = useEditorStore.getState()
const before = store.previewState
const view = before?.document.views.find((v) => v.id === offer.viewId)
if (!before || !view || store.session !== offer.session) {
return blockedResult(context)
}
const repairs = listedAnnotations(offer, before.document).map(
(annotation) => ({
annotation,
geometry: geometries[annotation.id] ?? (annotation.geometry as Geometry),
}),
)
const ids = repairs.map((r) => r.annotation.id)
const accept = repairAccept(before, offer.assetId, ids)
const commands = repairCommands(view, offer.assetId, repairs)
const outcome = store.commitBatch(commands, { accept })
return outcome.ok ? { ok: true } : refusedResult(outcome, context)
}
+16 -6
View File
@@ -1,6 +1,6 @@
import type { EditCommand, PreviewState } from '@faunosteo/core-wasm/types'
import type { Acceptance } from '@/catalogue/preview'
import { applyEdit } from '../core/editOps'
import { applyEdits } from '../core/editOps'
import { sameDocument } from '../core/sameDocument'
import { editablePreview } from './editorBase'
import type {
@@ -38,18 +38,20 @@ function replacedPatch(
}
/**
* `sheet.edit` → `replaceDocument` → `accept`: nothing is kept (no store change, no
* `handleVersion` bump, so no copy write) unless the core and `accept` all agree.
* `sheet.edit` (one command, or an ordered batch on a scratch text) → `replaceDocument` →
* `accept`: nothing is kept (no store change, no `handleVersion` bump, so no copy write,
* no undo entry) unless the core and `accept` all agree on the END text.
*/
export function commit<R>(
export function commitBatch<R>(
api: StoreApi,
command: EditCommand,
commands: readonly 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 (commands.length === 0) return blocked('empty')
const edited = applyEdits(state.documentText, commands)
if (!edited.ok) return { ok: false, reason: 'core', failure: edited }
const replaced = preview.replaceDocument(edited.value, accept)
if (!replaced.ok) return replaced
@@ -58,6 +60,14 @@ export function commit<R>(
return { ok: true }
}
export function commit<R>(
api: StoreApi,
command: EditCommand,
accept?: (state: PreviewState) => Acceptance<R>,
): CommitOutcome<R> {
return commitBatch(api, [command], accept)
}
export function stepHistory(api: StoreApi, direction: 'undo' | 'redo'): CommitOutcome {
const state = api.get()
const preview = editablePreview(state)
+2 -1
View File
@@ -1,5 +1,5 @@
import { create } from 'zustand'
import { addDrawing, commit, stepHistory } from './editorEdit'
import { addDrawing, commit, commitBatch, stepHistory } from './editorEdit'
import { initialData } from './editorBase'
import { close, discardChanges, open, reloadServerDraft } from './editorLoad'
import { keepMine, retryConflictRead, save, submit } from './editorSave'
@@ -26,6 +26,7 @@ export const useEditorStore = create<EditorState>()((set, get) => {
close: () => close(api),
setCanEdit: (canEdit) => setCanEdit(api, canEdit),
commit: (command, options) => commit(api, command, options?.accept),
commitBatch: (commands, options) => commitBatch(api, commands, options?.accept),
undoStep: () => stepHistory(api, 'undo'),
redoStep: () => stepHistory(api, 'redo'),
addDrawing: (drawing) => addDrawing(api, drawing),
+5
View File
@@ -141,6 +141,11 @@ export interface EditorActions {
command: EditCommand,
options?: { accept?: (state: PreviewState) => Acceptance<R> },
): CommitOutcome<R>
/** Ordered commands on a scratch text, committed once on the end state (one undo entry). */
commitBatch<R = never>(
commands: readonly EditCommand[],
options?: { accept?: (state: PreviewState) => Acceptance<R> },
): CommitOutcome<R>
undoStep(): CommitOutcome
redoStep(): CommitOutcome
addDrawing(drawing: AddedDrawing): CommitOutcome
+1
View File
@@ -23,6 +23,7 @@ export function uploadErrorMessage(
): string | null {
switch (error.code) {
case 'stale':
case 'repair':
return null
case 'svg_rejected': {
const reason = rejectionReason(error.reason)
+14
View File
@@ -6,11 +6,13 @@ import {
type Step,
type UploadError,
} from './drawingUpload'
import type { RepairOffer } from './repair'
export type UploadUi =
| { phase: 'idle' }
| { phase: 'working' }
| { phase: 'cleaning'; candidate: Candidate }
| { phase: 'repair'; offer: RepairOffer }
| { phase: 'failed'; error: UploadError }
| { phase: 'done' }
@@ -21,6 +23,10 @@ export interface DrawingUpload {
/** « Nettoyer et utiliser cette version ». */
confirmCleaning: () => Promise<void>
cancelCleaning: () => void
/** The repair dialog applied: the drawing is attached with the repaired annotations. */
finishRepair: () => void
/** « Annuler »: the document stays as it is, the drawing stays uploaded and held. */
cancelRepair: () => void
}
/** The upload of one view's drawing as a small state machine for its section. */
@@ -29,6 +35,8 @@ export function useDrawingUpload(viewId: string): DrawingUpload {
const settle = (result: Step<unknown>) => {
if (result.ok) setUi({ phase: 'done' })
else if (result.error.code === 'stale') setUi({ phase: 'idle' })
else if (result.error.code === 'repair')
setUi({ phase: 'repair', offer: result.error.offer })
else setUi({ phase: 'failed', error: result.error })
}
const send = async (candidate: Candidate) => {
@@ -49,5 +57,11 @@ export function useDrawingUpload(viewId: string): DrawingUpload {
if (ui.phase === 'cleaning') await send(ui.candidate)
},
cancelCleaning: () => setUi({ phase: 'idle' }),
finishRepair: () => setUi({ phase: 'done' }),
cancelRepair: () => {
if (ui.phase !== 'repair') return
const { refusal } = ui.offer
setUi({ phase: 'failed', error: { code: 'frame', refusal } })
},
}
}
+8 -3
View File
@@ -8,6 +8,7 @@ import {
rejectedDrawingFault,
type GeometryRefusal,
} from './issues'
import { markRepairable } from './repair'
import { useEditorStore } from './state/editorStore'
import type { CommitOutcome } from './state/editorTypes'
@@ -18,7 +19,8 @@ export type ViewPatch = Partial<
/**
* One `update` of a view through the store. A frame change (drawing, crop, parent) is
* `guarded`: the core's geometry verdict decides through `geometryAccept`, so no annotation
* gets a geometry error it did not have and no measured view becomes unmeasured.
* gets a geometry error it did not have and no measured view becomes unmeasured. A new
* drawing refused for annotations of a view that was unmeasured comes back repairable.
*/
export function updateView(
viewId: string,
@@ -35,8 +37,11 @@ export function updateView(
const value = { ...view, ...patch } as SheetView
const geometry = geometryAccept({ before, changedIds: [] })
const newAsset = patch.svg_asset_id
const accept = (after: PreviewState) =>
(newAsset ? rejectedDrawingFault(after, newAsset) : null) ?? geometry(after)
const accept = (after: PreviewState) => {
const rejected = newAsset ? rejectedDrawingFault(after, newAsset) : null
const verdict = rejected ?? geometry(after)
return newAsset ? markRepairable(verdict, before, after) : verdict
}
return store.commit(
{
op: 'update',