320 lines
11 KiB
TypeScript
320 lines
11 KiB
TypeScript
import type {
|
|
Annotation,
|
|
EditCommand,
|
|
Geometry,
|
|
Point,
|
|
PreviewState,
|
|
SheetView,
|
|
} from '@faunosteo/core-wasm/types'
|
|
import type { Acceptance, CataloguePreview } 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 { elementLabel } from './sheetDocument'
|
|
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: `preview` must hold it. */
|
|
function candidateFrame(
|
|
preview: CataloguePreview | null,
|
|
viewId: string,
|
|
): Frame | null {
|
|
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[],
|
|
preview: CataloguePreview | null,
|
|
): 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(preview, 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
|
|
// Inside `accept` the store's preview handle holds the candidate document (not yet kept).
|
|
const { preview } = useEditorStore.getState()
|
|
const frames = framesOfListed(before, after, refusal.annotationIds, preview)
|
|
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 order is free: the core's `update_annotation`
|
|
* keeps the current status and sets `to_confirm` on any change, so both orders end in the
|
|
* same text, and only that end text is judged.
|
|
*/
|
|
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: {} }
|
|
}
|
|
|
|
const UNMEASURED: ReadonlySet<string> = new Set([
|
|
'view_unmeasured',
|
|
'changed_unmeasured',
|
|
])
|
|
|
|
function namesOf(ids: readonly string[], { locale }: CommitContext): string {
|
|
const doc = useEditorStore.getState().previewState?.document
|
|
const label = (id: string) =>
|
|
doc ? elementLabel(doc, { kind: 'annotation', id }, locale) : id
|
|
return [...new Set(ids)].map(label).join(', ')
|
|
}
|
|
|
|
/** Words that fit the dialog: none of them sends the user to a tab behind it. */
|
|
function dialogMessage(
|
|
outcome: Exclude<CommitOutcome<GeometryRefusal>, { ok: true }>,
|
|
context: CommitContext,
|
|
): string | null {
|
|
const refusal = outcome.reason === 'refused' ? outcome.refusal : null
|
|
if (refusal?.reason === 'newly_invalid') {
|
|
return context
|
|
.t('editor.views.repair.more_outside')
|
|
.replace('{names}', namesOf(refusal.annotationIds, context))
|
|
}
|
|
if (refusal && UNMEASURED.has(refusal.reason)) {
|
|
return context.t('editor.views.repair.not_measurable')
|
|
}
|
|
return describeOutcome(outcome, context).messages[0] ?? null
|
|
}
|
|
|
|
export function refusedResult(
|
|
outcome: Exclude<CommitOutcome<GeometryRefusal>, { ok: true }>,
|
|
context: CommitContext,
|
|
): RepairResult {
|
|
const refusal = outcome.reason === 'refused' ? outcome.refusal : null
|
|
if (refusal?.reason === 'changed_invalid') {
|
|
return { ok: false, general: null, byAnnotation: issueMessages(refusal) }
|
|
}
|
|
const general = dialogMessage(outcome, context)
|
|
return { ok: false, general, 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)
|
|
}
|
|
|
|
/** The commands and the repaired ids, or null when the view is gone. */
|
|
function repairBatch(
|
|
offer: RepairOffer,
|
|
before: PreviewState,
|
|
geometries: Record<string, Geometry>,
|
|
) {
|
|
const view = before.document.views.find((v) => v.id === offer.viewId)
|
|
if (!view) return null
|
|
const repairs = listedAnnotations(offer, before.document).map(
|
|
(annotation) => ({
|
|
annotation,
|
|
geometry: geometries[annotation.id] ?? (annotation.geometry as Geometry),
|
|
}),
|
|
)
|
|
return {
|
|
commands: repairCommands(view, offer.assetId, repairs),
|
|
ids: repairs.map((r) => r.annotation.id),
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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 batch =
|
|
before && store.session === offer.session
|
|
? repairBatch(offer, before, geometries)
|
|
: null
|
|
if (!before || !batch) return blockedResult(context)
|
|
const accept = repairAccept(before, offer.assetId, batch.ids)
|
|
const outcome = store.commitBatch(batch.commands, { accept })
|
|
return outcome.ok ? { ok: true } : refusedResult(outcome, context)
|
|
}
|