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

@@ -114,9 +114,8 @@ function useFormTitle(pending: PendingFinding): string {
const t = useT()
const doc = useSheetDocument()
const locale = useLocaleStore((s) => s.locale)
if (pending.kind !== 'category' || !doc || !pending.parent) {
return t(`editor.findings.new.${pending.kind}`)
}
if (pending.kind !== 'category') return t(`editor.findings.new.${pending.kind}`)
if (!doc || !pending.parent) return t('editor.findings.add_category')
const zone = elementLabel(
doc,
{ kind: 'zone', id: pending.parent.zoneId },
@@ -0,0 +1,196 @@
import { useState } from 'react'
import type { Annotation, Geometry } from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import GeometryGroup from '@/components/editor/annotations/GeometryGroup'
import { annotationName } from '@/components/editor/annotations/AnnotationList'
import { isEditable } from '@/editor/annotations/geometryEdit'
import { usePlural } from '@/editor/plural'
import {
applyRepair,
blockedIds,
initialGeometries,
listedAnnotations,
polygonReplacement,
type RepairOffer,
type RepairResult,
} from '@/editor/repair'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
export interface RepairDialogProps {
/** The refused attach to repair; null keeps the dialog closed. */
offer: RepairOffer | null
onApplied: () => void
onCancel: () => void
}
/**
* The temporary form of an attach refused for annotations outside the new frame (owner
* decision 7). Values are proposals in the new frame; nothing reaches the document before
* « Attacher et appliquer », which sends ONE batch the core judges on its end state.
*/
export default function RepairDialog({ offer, ...actions }: RepairDialogProps) {
const t = useT()
const plural = usePlural()
const count = offer ? new Set(offer.refusal.annotationIds).size : 0
return (
<Dialog
open={offer !== null}
onClose={actions.onCancel}
title={t('editor.views.repair.title')}
description={offer && plural('editor.views.repair.body', count)}
size="lg"
>
{offer && <RepairForm offer={offer} {...actions} />}
</Dialog>
)
}
/** The temporary state of the form: proposals, typed edits and the last refusal. */
function useRepairState(offer: RepairOffer, onApplied: () => void) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const doc = useSheetDocument()
const [annotations] = useState(() =>
doc ? listedAnnotations(offer, doc) : [],
)
const [geometries, setGeometries] = useState(() =>
initialGeometries(offer, annotations),
)
const [result, setResult] = useState<RepairResult | null>(null)
const apply = () => {
const applied = applyRepair(offer, geometries, { t, locale })
if (applied.ok) onApplied()
else setResult(applied)
}
const change = (id: string, geometry: Geometry) =>
setGeometries((current) => ({ ...current, [id]: geometry }))
return { annotations, geometries, result, apply, change }
}
function RepairForm({
offer,
onApplied,
onCancel,
}: Omit<RepairDialogProps, 'offer'> & { offer: RepairOffer }) {
const t = useT()
const state = useRepairState(offer, onApplied)
const refused = state.result && !state.result.ok ? state.result : null
return (
<div className="mt-4 space-y-4">
<ul className="space-y-4">
{state.annotations.map((annotation) => (
<RepairRow
key={annotation.id}
annotation={annotation}
geometry={state.geometries[annotation.id]}
offer={offer}
messages={refused?.byAnnotation[annotation.id]}
onChange={(geometry) => state.change(annotation.id, geometry)}
/>
))}
</ul>
{refused && <Refusal general={refused.general} />}
<div className="flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={onCancel}>
{t('editor.views.repair.cancel')}
</Button>
<Button
type="button"
disabled={blockedIds(state.geometries).length > 0}
onClick={state.apply}
>
{t('editor.views.repair.apply')}
</Button>
</div>
</div>
)
}
function Refusal({ general }: { general: string | null }) {
const t = useT()
return (
<div
role="alert"
className="space-y-1 text-sm text-[var(--color-danger-strong)]"
>
<p className="font-medium">{t('editor.views.repair.refused')}</p>
{general && <p>{general}</p>}
</div>
)
}
interface RowProps {
annotation: Annotation
geometry: Geometry | undefined
offer: RepairOffer
messages: string[] | undefined
onChange: (geometry: Geometry) => void
}
function RepairRow({
annotation,
geometry,
offer,
messages,
onChange,
}: RowProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const doc = useSheetDocument()
const name = annotationName(annotation, doc?.views ?? [], locale)
const title = t('editor.views.repair.row')
.replace('{kind}', t(`editor.annotations.kind.${annotation.kind}`))
.replace('{name}', name)
return (
<li
data-testid={`repair-${annotation.id}`}
className="space-y-2 rounded-lg border border-[var(--color-border)] p-3"
>
<h4 className="text-sm font-semibold">{title}</h4>
{geometry && isEditable(geometry) ? (
<GeometryGroup
idPrefix={`repair-${annotation.id}`}
geometry={geometry}
locked={false}
onApply={(next) => {
onChange(next)
return { ok: true }
}}
/>
) : (
<PathBlock
onConvert={() =>
onChange(polygonReplacement(offer.frames[annotation.view_id]))
}
/>
)}
{messages && messages.length > 0 && (
<ul
role="alert"
className="list-disc pl-5 text-sm text-[var(--color-danger-strong)]"
>
{messages.map((message) => (
<li key={message}>{message}</li>
))}
</ul>
)}
</li>
)
}
function PathBlock({ onConvert }: { onConvert: () => void }) {
const t = useT()
return (
<div className="space-y-2">
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.views.repair.path_blocked')}
</p>
<Button type="button" variant="secondary" size="sm" onClick={onConvert}>
{t('editor.annotations.replace_polygon')}
</Button>
</div>
)
}
@@ -17,6 +17,7 @@ import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import CleaningDialog from './CleaningDialog'
import ParentDrawingDialog from './ParentDrawingDialog'
import RepairDialog from './RepairDialog'
/**
* A view's drawing: its state, the hint when it is not usable, « Choisir une
@@ -127,6 +128,11 @@ function DrawingActions({
onConfirm={() => void upload.confirmCleaning()}
onCancel={upload.cancelCleaning}
/>
<RepairDialog
offer={upload.ui.phase === 'repair' ? upload.ui.offer : null}
onApplied={upload.finishRepair}
onCancel={upload.cancelRepair}
/>
</>
)
}
@@ -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',
+9
View File
@@ -1389,6 +1389,15 @@ export const en: Dict = {
'editor.views.frame.newly_invalid': 'This frame change would put the geometry of these elements in error: {names}. Move them first (Annotations tab).',
'editor.views.frame.view_unmeasured': 'This change would make a view that holds annotations unmeasurable: {names}.',
'editor.views.frame.kept': 'The drawing stays uploaded; the view keeps its previous drawing.',
'editor.views.frame.newly_invalid_repairable': 'These elements fall outside the new frame: {names}. Choose the drawing again to repair them as you attach it.',
'editor.views.repair.title': 'Repair the annotations outside the new frame',
'editor.views.repair.body_one': '{count} annotation falls outside the new frame of this drawing. The proposed values are computed in that frame. Nothing is applied before "Attach and apply": the drawing and the new values are then applied together, and a single Undo restores them together.',
'editor.views.repair.body_other': '{count} annotations fall outside the new frame of this drawing. The proposed values are computed in that frame. Nothing is applied before "Attach and apply": the drawing and the new values are then applied together, and a single Undo restores them together.',
'editor.views.repair.row': '{kind} "{name}"',
'editor.views.repair.path_blocked': 'This path has no coordinates to correct here. Replace it with a polygon to be able to attach the drawing.',
'editor.views.repair.refused': 'Nothing was applied: the document check refuses these values.',
'editor.views.repair.apply': 'Attach and apply',
'editor.views.repair.cancel': 'Cancel',
'editor.upload.working': 'Checking and sending the drawing…',
'editor.upload.done': 'The drawing is added to the view.',
'editor.upload.err.too_large': 'This file is larger than 2 MiB.',
+9
View File
@@ -1420,6 +1420,15 @@ export const fr: Dict = {
'editor.views.frame.newly_invalid': "Ce changement de cadre mettrait en erreur la géométrie de : {names}. Déplacez d'abord ces éléments (onglet Annotations).",
'editor.views.frame.view_unmeasured': 'Ce changement rendrait non mesurable une vue qui porte des annotations : {names}.',
'editor.views.frame.kept': "L'illustration reste téléversée ; la vue garde son illustration précédente.",
'editor.views.frame.newly_invalid_repairable': "Ces éléments sortent du nouveau cadre : {names}. Choisissez de nouveau l'illustration pour les réparer en l'attachant.",
'editor.views.repair.title': 'Réparer les annotations hors du nouveau cadre',
'editor.views.repair.body_one': "{count} annotation sort du nouveau cadre de cette illustration. Les valeurs proposées sont calculées dans ce cadre. Rien n'est appliqué avant « Attacher et appliquer » : l'illustration et les nouvelles valeurs sont alors appliquées ensemble, et un seul Annuler les restaure ensemble.",
'editor.views.repair.body_other': "{count} annotations sortent du nouveau cadre de cette illustration. Les valeurs proposées sont calculées dans ce cadre. Rien n'est appliqué avant « Attacher et appliquer » : l'illustration et les nouvelles valeurs sont alors appliquées ensemble, et un seul Annuler les restaure ensemble.",
'editor.views.repair.row': '{kind} « {name} »',
'editor.views.repair.path_blocked': "Ce tracé n'a pas de coordonnées à corriger ici. Remplacez-le par un polygone pour pouvoir attacher l'illustration.",
'editor.views.repair.refused': "Rien n'a été appliqué : le contrôle du document refuse ces valeurs.",
'editor.views.repair.apply': 'Attacher et appliquer',
'editor.views.repair.cancel': 'Annuler',
'editor.upload.working': "Vérification et envoi de l'illustration…",
'editor.upload.done': "L'illustration est ajoutée à la vue.",
'editor.upload.err.too_large': 'Ce fichier dépasse 2 Mio.',