diff --git a/.claude/audits/2026-11-03-v1-2-6-label-proposals.md b/.claude/audits/2026-11-03-v1-2-6-label-proposals.md index 356269a2..f160690f 100644 --- a/.claude/audits/2026-11-03-v1-2-6-label-proposals.md +++ b/.claude/audits/2026-11-03-v1-2-6-label-proposals.md @@ -508,3 +508,17 @@ Shown by a voluntary sign-out only when the editor holds unsaved changes, a reco | `shell.sign_out_loss_body` | Des modifications non enregistrées ou des copies locales de cet onglet seraient perdues. Les enregistrer sur le serveur avant de vous déconnecter les conserve. | Unsaved changes or the local copies held in this tab would be lost. Saving them to the server before signing out keeps them. | New: names what is lost and the way to keep it | | `shell.sign_out_loss_cancel` | Annuler | Cancel | New: keeps the session and the copies | | `shell.sign_out_loss_confirm` | Se déconnecter quand même | Sign out anyway | New: purges this account's copies, then signs out | + +## Lot N3 (owner decision 7, ruling R23: repair on attach to an unmeasured view, C41) + +Shown when a drawing attached to a view that was unmeasured would put the geometry of its annotations out of the new frame. Plural keys use `_one` / `_other`. + +| Key | FR | EN | Old wording and why | +|---|---|---|---| +| `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. | These elements fall outside the new frame: {names}. Choose the drawing again to repair them as you attach it. | New: shown after « Annuler » in the repair dialog. `editor.views.frame.newly_invalid` (« Déplacez d'abord ces éléments (onglet Annotations) ») stays for a measured view (C33); on an unmeasured view that tab is locked (C32) | +| `editor.views.repair.title` | Réparer les annotations hors du nouveau cadre | Repair the annotations outside the new frame | New: dialog title | +| `editor.views.repair.body_one` / `_other` | {count} annotation sort / {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. | {count} annotation falls / {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. | New: names the proposal, the atomic apply and the single undo | +| `editor.views.repair.row` | {kind} « {name} » | {kind} "{name}" | New: heading of one annotation row | +| `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. | This path has no coordinates to correct here. Replace it with a polygon to be able to attach the drawing. | New: a path cannot be edited numerically; the existing « Remplacer par un polygone » converts it inside the form | +| `editor.views.repair.refused` | Rien n'a été appliqué : le contrôle du document refuse ces valeurs. | Nothing was applied: the document check refuses these values. | New: the core refused the end state; the core's messages follow per annotation | +| `editor.views.repair.apply` / `cancel` | Attacher et appliquer / Annuler | Attach and apply / Cancel | New: dialog buttons (« Attacher et appliquer » is the owner's wording) | diff --git a/apps/app/e2e/shell/editor-geometry.spec.ts b/apps/app/e2e/shell/editor-geometry.spec.ts index 7001830a..6b6f8fa6 100644 --- a/apps/app/e2e/shell/editor-geometry.spec.ts +++ b/apps/app/e2e/shell/editor-geometry.spec.ts @@ -9,7 +9,9 @@ import { geometryField, openEditor, pointOf, + saveDraft, seedDraft, + serverDocument, selectTab, shapeWith, standardShape, @@ -221,6 +223,97 @@ test.describe('editor geometry (adversarial)', () => { await expect(width).toHaveValue('300') }) + test('attaching a drawing to an unmeasured view repairs the annotations outside its frame', async ({ + page, + requests, + }) => { + const zone = { + ...pointOf('out-zone', 'main', { cx: 0, cy: 0, r: 1 }, 'Zone hors cadre'), + kind: 'zone', + geometry: { + type: 'polygon', + points: [ + [10, 10], + [400, 10], + [400, 400], + ], + }, + } + const point = pointOf( + 'out-point', + 'main', + { cx: 500, cy: 400, r: 20 }, + 'Point hors cadre', + ) + const actor = await editorActor('fr') + requests.forbid(actor.account.email, actor.account.password) + const seed = await seedDraft(actor, { + drawing: null, + shape: (document) => { + standardShape(document) + const views = document.views as { id: string }[] + document.views = views.filter((view) => view.id === 'main') + document.annotations = [point, zone] + }, + }) + await openEditor(page, dict, actor, seed.sheetId) + await selectTab(page, dict, 'views') + await page.getByTestId('view-main-file').setInputFiles({ + name: 'petit.svg', + mimeType: 'image/svg+xml', + buffer: Buffer.from( + '' + + '', + ), + }) + const dialog = page.getByRole('dialog', { + name: dict['editor.views.repair.title'], + }) + await expect(dialog).toBeVisible() + const row = dialog.getByTestId('repair-out-point') + await expect( + row.getByLabel(dict['editor.annotations.geometry.cx']), + ).toHaveValue('85') + await expectAccessible(page, 'the repair dialog') + + // A value the core refuses: nothing applied, the typed value kept. + const cx = row.getByLabel(dict['editor.annotations.geometry.cx']) + await cx.fill('900') + await cx.press('Enter') + await dialog + .getByRole('button', { name: dict['editor.views.repair.apply'] }) + .click() + await expect( + dialog.getByText(dict['editor.views.repair.refused']), + ).toBeVisible() + await expect(cx).toHaveValue('900') + + await cx.fill('60') + await cx.press('Enter') + await dialog + .getByRole('button', { name: dict['editor.views.repair.apply'] }) + .click() + await expect(dialog).toBeHidden() + await expect(page.getByText(dict['editor.upload.done'])).toBeVisible() + + await saveDraft(page, dict, seed.revision + 1) + const saved = await serverDocument<{ + views: { id: string; svg_asset_id: string | null }[] + annotations: { id: string; geometry: Record }[] + }>(seed.draftId) + expect(saved.views[0].svg_asset_id).not.toBeNull() + const byId = Object.fromEntries(saved.annotations.map((a) => [a.id, a])) + expect(byId['out-point'].geometry).toMatchObject({ type: 'circle', cx: 60 }) + expect(byId['out-zone'].geometry).toEqual({ + type: 'polygon', + points: [ + [10, 10], + [100, 10], + [100, 100], + ], + }) + }) + test('an unmeasured view: drawing tools and add buttons disabled, the hint shown', async ({ page, requests, diff --git a/apps/app/src/components/editor/findings/FindingCreateForm.tsx b/apps/app/src/components/editor/findings/FindingCreateForm.tsx index 06270b6f..bbc2f33b 100644 --- a/apps/app/src/components/editor/findings/FindingCreateForm.tsx +++ b/apps/app/src/components/editor/findings/FindingCreateForm.tsx @@ -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 }, diff --git a/apps/app/src/components/editor/views/RepairDialog.tsx b/apps/app/src/components/editor/views/RepairDialog.tsx new file mode 100644 index 00000000..493340d6 --- /dev/null +++ b/apps/app/src/components/editor/views/RepairDialog.tsx @@ -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 ( + + {offer && } + + ) +} + +/** 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(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 & { offer: RepairOffer }) { + const t = useT() + const state = useRepairState(offer, onApplied) + const refused = state.result && !state.result.ok ? state.result : null + return ( +
+
    + {state.annotations.map((annotation) => ( + state.change(annotation.id, geometry)} + /> + ))} +
+ {refused && } +
+ + +
+
+ ) +} + +function Refusal({ general }: { general: string | null }) { + const t = useT() + return ( +
+

{t('editor.views.repair.refused')}

+ {general &&

{general}

} +
+ ) +} + +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 ( +
  • +

    {title}

    + {geometry && isEditable(geometry) ? ( + { + onChange(next) + return { ok: true } + }} + /> + ) : ( + + onChange(polygonReplacement(offer.frames[annotation.view_id])) + } + /> + )} + {messages && messages.length > 0 && ( +
      + {messages.map((message) => ( +
    • {message}
    • + ))} +
    + )} +
  • + ) +} + +function PathBlock({ onConvert }: { onConvert: () => void }) { + const t = useT() + return ( +
    +

    + {t('editor.views.repair.path_blocked')} +

    + +
    + ) +} diff --git a/apps/app/src/components/editor/views/ViewDrawing.tsx b/apps/app/src/components/editor/views/ViewDrawing.tsx index 3d161d3d..c7ac73b0 100644 --- a/apps/app/src/components/editor/views/ViewDrawing.tsx +++ b/apps/app/src/components/editor/views/ViewDrawing.tsx @@ -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} /> + ) } diff --git a/apps/app/src/editor/annotations/annotationCommit.ts b/apps/app/src/editor/annotations/annotationCommit.ts index f79d739f..b4cc7033 100644 --- a/apps/app/src/editor/annotations/annotationCommit.ts +++ b/apps/app/src/editor/annotations/annotationCommit.ts @@ -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, { ok: true }>, { t, locale }: CommitContext, -): CommitResult { +): Extract { 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`. */ diff --git a/apps/app/src/editor/core/editOps.ts b/apps/app/src/editor/core/editOps.ts index cb1dfc06..f52264d0 100644 --- a/apps/app/src/editor/core/editOps.ts +++ b/apps/app/src/editor/core/editOps.ts @@ -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 { + 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, diff --git a/apps/app/src/editor/drawingUpload.ts b/apps/app/src/editor/drawingUpload.ts index 152cf095..90032b5c 100644 --- a/apps/app/src/editor/drawingUpload.ts +++ b/apps/app/src/editor/drawingUpload.ts @@ -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 = { 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 { 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' }) } diff --git a/apps/app/src/editor/frameRefusal.ts b/apps/app/src/editor/frameRefusal.ts index 11817e8c..69b5dce9 100644 --- a/apps/app/src/editor/frameRefusal.ts +++ b/apps/app/src/editor/frameRefusal.ts @@ -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), ) diff --git a/apps/app/src/editor/issues.ts b/apps/app/src/editor/issues.ts index d1e7954e..65abdd3c 100644 --- a/apps/app/src/editor/issues.ts +++ b/apps/app/src/editor/issues.ts @@ -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 } export interface GeometryAcceptInput { diff --git a/apps/app/src/editor/repair.ts b/apps/app/src/editor/repair.ts new file mode 100644 index 00000000..81e70a33 --- /dev/null +++ b/apps/app/src/editor/repair.ts @@ -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 + 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 { + const proposals: Record = {} + 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[] { + 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 | null { + const viewIds = after.document.annotations + .filter((annotation) => ids.includes(annotation.id)) + .map((annotation) => annotation.view_id) + const unmeasured = unmeasuredViews(before) + const frames: Record = {} + 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, + before: PreviewState, + after: PreviewState, +): Acceptance { + 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 + } + +function issueMessages(refusal: GeometryRefusal) { + const byAnnotation: Record = {} + 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, { 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, + 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) +} diff --git a/apps/app/src/editor/state/editorEdit.ts b/apps/app/src/editor/state/editorEdit.ts index f49076d6..12d99b71 100644 --- a/apps/app/src/editor/state/editorEdit.ts +++ b/apps/app/src/editor/state/editorEdit.ts @@ -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( +export function commitBatch( api: StoreApi, - command: EditCommand, + commands: readonly EditCommand[], accept?: (state: PreviewState) => Acceptance, ): CommitOutcome { 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( return { ok: true } } +export function commit( + api: StoreApi, + command: EditCommand, + accept?: (state: PreviewState) => Acceptance, +): CommitOutcome { + return commitBatch(api, [command], accept) +} + export function stepHistory(api: StoreApi, direction: 'undo' | 'redo'): CommitOutcome { const state = api.get() const preview = editablePreview(state) diff --git a/apps/app/src/editor/state/editorStore.ts b/apps/app/src/editor/state/editorStore.ts index 9254c861..a1e3218b 100644 --- a/apps/app/src/editor/state/editorStore.ts +++ b/apps/app/src/editor/state/editorStore.ts @@ -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()((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), diff --git a/apps/app/src/editor/state/editorTypes.ts b/apps/app/src/editor/state/editorTypes.ts index 461d3a2a..f5f9c8e9 100644 --- a/apps/app/src/editor/state/editorTypes.ts +++ b/apps/app/src/editor/state/editorTypes.ts @@ -141,6 +141,11 @@ export interface EditorActions { command: EditCommand, options?: { accept?: (state: PreviewState) => Acceptance }, ): CommitOutcome + /** Ordered commands on a scratch text, committed once on the end state (one undo entry). */ + commitBatch( + commands: readonly EditCommand[], + options?: { accept?: (state: PreviewState) => Acceptance }, + ): CommitOutcome undoStep(): CommitOutcome redoStep(): CommitOutcome addDrawing(drawing: AddedDrawing): CommitOutcome diff --git a/apps/app/src/editor/uploadMessages.ts b/apps/app/src/editor/uploadMessages.ts index e94c45fe..c0358dff 100644 --- a/apps/app/src/editor/uploadMessages.ts +++ b/apps/app/src/editor/uploadMessages.ts @@ -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) diff --git a/apps/app/src/editor/useDrawingUpload.ts b/apps/app/src/editor/useDrawingUpload.ts index b6e14055..bf07d641 100644 --- a/apps/app/src/editor/useDrawingUpload.ts +++ b/apps/app/src/editor/useDrawingUpload.ts @@ -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 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) => { 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 } }) + }, } } diff --git a/apps/app/src/editor/viewUpdate.ts b/apps/app/src/editor/viewUpdate.ts index 5b3518e5..b75bb286 100644 --- a/apps/app/src/editor/viewUpdate.ts +++ b/apps/app/src/editor/viewUpdate.ts @@ -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', diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index 8b474eda..93e577c0 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -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.', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 13ec37cd..eede90fd 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -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.', diff --git a/apps/app/tests/unit/editor-batch.test.ts b/apps/app/tests/unit/editor-batch.test.ts new file mode 100644 index 00000000..2c286f6a --- /dev/null +++ b/apps/app/tests/unit/editor-batch.test.ts @@ -0,0 +1,157 @@ +/** Lot N3: one atomic batch of edit commands (R23), on the Node core. */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { EditCommand } from '@faunosteo/core-wasm/types' +import { + ASSET, + emptyText, + insert, + point, + svgBytes, +} from '../helpers/editorFixtures' +import { + openReady, + resetStore, + serverHas, + storedCopy, + store, +} from '../helpers/editorHarness' + +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(), +})) + +afterEach(resetStore) + +/** An unmeasured main view (no drawing) holding one point at (500, 400). */ +function unmeasuredText(): string { + const withCategory = insert(emptyText(), { + kind: 'category', + value: { id: 'cat-a', name: { fr: 'N', en: 'N' }, color: null }, + }) + return insert(withCategory, point('anno-a', 500, 400, 5)) +} + +async function openUnmeasured() { + await openReady({ text: unmeasuredText() }) + serverHas(unmeasuredText(), 3, false) + const drawing = svgBytes('0 0 100 100') + const held = store + .getState() + .addDrawing({ + assetId: ASSET, + sha256: drawing.sha256, + bytes: drawing.bytes, + }) + expect(held).toEqual({ ok: true }) +} + +const doc = () => JSON.parse(store.getState().documentText) + +const attachCommand = (): EditCommand => ({ + op: 'update', + key: { kind: 'view', id: 'view-main' }, + element: { + kind: 'view', + value: { ...doc().views[0], svg_asset_id: ASSET }, + }, +}) +const moved = (cx: number): EditCommand => ({ + op: 'update', + key: { kind: 'annotation', id: 'anno-a' }, + element: point('anno-a', cx, 50, 5), +}) + +describe('commitBatch', () => { + it('applies the commands in order and commits once: one undo entry, one copy write', async () => { + await openUnmeasured() + const before = store.getState() + const outcome = store.getState().commitBatch([attachCommand(), moved(50)]) + expect(outcome).toEqual({ ok: true }) + const after = store.getState() + expect(doc().views[0].svg_asset_id).toBe(ASSET) + expect(doc().annotations[0].geometry.cx).toBe(50) + expect(after.undo).toHaveLength(1) + expect(after.handleVersion).toBe(before.handleVersion + 1) + expect(storedCopy()).not.toBeNull() + }) + + it('restores both the view and the geometry with one undo', async () => { + await openUnmeasured() + const text = store.getState().documentText + store.getState().commitBatch([attachCommand(), moved(50)]) + expect(store.getState().undoStep()).toEqual({ ok: true }) + expect(store.getState().documentText).toBe(text) + }) + + it('keeps nothing when one command is refused by sheet.edit', async () => { + await openUnmeasured() + const before = store.getState() + const missing: EditCommand = { + op: 'remove', + key: { kind: 'annotation', id: 'nope' }, + } + const outcome = store.getState().commitBatch([attachCommand(), missing]) + expect(outcome).toMatchObject({ ok: false, reason: 'core' }) + const after = store.getState() + expect(after.documentText).toBe(before.documentText) + expect(after.handleVersion).toBe(before.handleVersion) + expect(after.undo).toHaveLength(0) + expect(storedCopy()).toBeNull() + }) + + it('keeps nothing when accept refuses the end state', async () => { + await openUnmeasured() + const before = store.getState() + const outcome = store.getState().commitBatch([attachCommand(), moved(50)], { + accept: () => ({ accepted: false, refusal: 'no' as const }), + }) + expect(outcome).toEqual({ ok: false, reason: 'refused', refusal: 'no' }) + const after = store.getState() + expect(after.documentText).toBe(before.documentText) + expect(after.undo).toHaveLength(0) + expect(after.preview?.document).toBe(before.documentText) + }) + + it('hands accept the END state only, never an intermediate one', async () => { + await openUnmeasured() + const accept = vi.fn(() => ({ accepted: true as const })) + store.getState().commitBatch([attachCommand(), moved(50)], { accept }) + expect(accept).toHaveBeenCalledTimes(1) + const [state] = accept.mock.calls[0] as unknown as [ + { document: { annotations: { geometry: { cx: number } }[] } }, + ] + expect(state.document.annotations[0].geometry.cx).toBe(50) + }) + + it('is blocked while a recovery offer is pending and when read-only', async () => { + await openUnmeasured() + store.setState({ recovery: 'pending' }) + expect(store.getState().commitBatch([attachCommand()])).toMatchObject({ + ok: false, + reason: 'blocked', + kind: 'recovery.pending', + }) + store.setState({ recovery: 'none', canEdit: false }) + expect(store.getState().commitBatch([attachCommand()])).toMatchObject({ + ok: false, + reason: 'blocked', + kind: 'read_only', + }) + expect(store.getState().undo).toHaveLength(0) + }) + + it('refuses an empty batch without touching the document', async () => { + await openUnmeasured() + expect(store.getState().commitBatch([])).toMatchObject({ + ok: false, + reason: 'blocked', + kind: 'empty', + }) + }) +}) diff --git a/apps/app/tests/unit/editor-findings.test.tsx b/apps/app/tests/unit/editor-findings.test.tsx index 1bc29cb7..ef33a26c 100644 --- a/apps/app/tests/unit/editor-findings.test.tsx +++ b/apps/app/tests/unit/editor-findings.test.tsx @@ -6,6 +6,7 @@ import type { AnatomicalSheetDocument, FindingNode, } from '@faunosteo/core-wasm/types' +import FindingCreateForm from '@/components/editor/findings/FindingCreateForm' import FindingsTab from '@/components/editor/tabs/FindingsTab' import { buildItems, keyMove, visibleItems } from '@/editor/findings/tree' import { useLocaleStore } from '@/state/localeStore' @@ -527,3 +528,36 @@ describe('Constats tab', () => { expect(items()[0]).toHaveFocus() }) }) + +describe('the category form title (N1 review)', () => { + const parentOf = (id: string) => { + const found = buildItems(doc()).find((item) => item.id.includes(`"${id}"`) && item.path.at(-1) === id || item.zoneId === id && item.kind === 'zone') + if (!found) throw new Error(`no ${id}`) + return found + } + const title = (parent: ReturnType | null) => { + render( + , + ) + return document.querySelector('p.font-medium')?.textContent + } + + it.each(['zone-a', 'fcat-a', 'node-a'])( + 'names the zone when the parent is %s', + async (id) => { + await openReady({ text: treeText() }) + expect(title(parentOf(id))).toBe( + 'Nouvelle catégorie dans la zone « Zone A »', + ) + }, + ) + + it('falls back to an existing label, never a missing key, without a parent', async () => { + await openReady({ text: treeText() }) + expect(title(null)).toBe('Ajouter une catégorie') + }) +}) diff --git a/apps/app/tests/unit/editor-repair.test.tsx b/apps/app/tests/unit/editor-repair.test.tsx new file mode 100644 index 00000000..1d6ae9d5 --- /dev/null +++ b/apps/app/tests/unit/editor-repair.test.tsx @@ -0,0 +1,393 @@ +/** Lot N3: repair on attach to an unmeasured view (owner decision 7, R23). */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + cleanup, + render, + screen, + waitFor, + within, +} from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import type { + AnatomicalSheetDocument, + Annotation, + Geometry, +} from '@faunosteo/core-wasm/types' +import ViewsTab from '@/components/editor/tabs/ViewsTab' +import { cleanSvg } from '@/editor/core/cleaning' +import { attachToView } from '@/editor/drawingUpload' +import { + applyRepair, + polygonReplacement, + proposeGeometry, +} from '@/editor/repair' +import { useLocaleStore } from '@/state/localeStore' +import { getDict } from '@/i18n' +import { emptyText, insert, point, svgBytes } from '../helpers/editorFixtures' +import { openReady, resetStore, sb, store } from '../helpers/editorHarness' + +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(), + registerSheetAsset: vi.fn(), + listSheetAssets: vi.fn(), + uploadSheetDrawing: vi.fn(), + confirmSheetAssetUpload: vi.fn(), +})) + +const props = { readOnly: false, onSelectTab: vi.fn(), reloadSheet: vi.fn() } +const NEW_ASSET = '22222222-2222-4222-8222-222222222222' +const t = (key: string) => getDict('fr')[key as never] as string +const doc = (): AnatomicalSheetDocument => + JSON.parse(store.getState().documentText) +const annotation = (id: string) => + doc().annotations.find((a) => a.id === id) as Annotation + +const zone = (id: string, points: [number, number][]) => ({ + kind: 'annotation' as const, + value: { + ...(point(id, 0, 0, 1).value as Annotation), + kind: 'zone' as const, + geometry: { type: 'polygon' as const, points }, + } as Annotation, +}) + +/** An unmeasured main view with a point and a zone far outside a 100 x 100 frame. */ +function unmeasuredText(extra?: ReturnType['value'][]): string { + let text = insert(emptyText(), { + kind: 'category', + value: { id: 'cat-a', name: { fr: 'N', en: 'N' }, color: null }, + }) + text = insert(text, point('anno-a', 500, 400, 5)) + text = insert( + text, + zone('anno-z', [ + [10, 10], + [400, 10], + [400, 400], + ]), + ) + for (const value of extra ?? []) + text = insert(text, { kind: 'annotation', value }) + return text +} + +async function holdNewDrawing(viewBox = '0 0 100 100') { + const drawing = svgBytes(viewBox) + const held = store.getState().addDrawing({ + assetId: NEW_ASSET, + sha256: drawing.sha256, + bytes: drawing.bytes, + }) + expect(held).toEqual({ ok: true }) +} + +beforeEach(() => useLocaleStore.setState({ locale: 'fr' })) +afterEach(() => { + cleanup() + resetStore() +}) + +describe('proposals (UI arithmetic in the new frame)', () => { + const frame = { x: 0, y: 0, w: 100, h: 100 } + + it('moves a point into the frame with the creation arithmetic', () => { + const proposed = proposeGeometry(frame, { + type: 'circle', + cx: 500, + cy: 400, + r: 5, + }) + expect(proposed).toEqual({ type: 'circle', cx: 85, cy: 85, r: 15 }) + }) + + it('clamps each vertex of a polygon and leaves vertices inside as they are', () => { + const proposed = proposeGeometry(frame, { + type: 'polygon', + points: [ + [10.5, 20], + [400, 50], + [30, -8], + ], + }) + expect(proposed).toEqual({ + type: 'polygon', + points: [ + [10.5, 20], + [100, 50], + [30, 0], + ], + }) + }) + + it('leaves a path to the conversion, which offers a triangle in the frame', () => { + const path: Geometry = { type: 'path', d: 'M 1 1 L 5 5 Z' } + expect(proposeGeometry(frame, path)).toBe(path) + expect(polygonReplacement(frame)).toMatchObject({ + type: 'polygon', + points: expect.arrayContaining([expect.any(Array)]), + }) + }) +}) + +describe('the attach refusal on an unmeasured view', () => { + it('turns into a repair offer with the new frame, the document untouched', async () => { + await openReady({ text: unmeasuredText() }) + await holdNewDrawing() + const before = store.getState().documentText + const step = attachToView('view-main', NEW_ASSET) + expect(step).toMatchObject({ ok: false, error: { code: 'repair' } }) + if (step.ok || step.error.code !== 'repair') throw new Error('no offer') + expect(step.error.offer.frames['view-main']).toEqual({ + x: 0, + y: 0, + w: 100, + h: 100, + }) + expect(step.error.offer.refusal.annotationIds.sort()).toEqual([ + 'anno-a', + 'anno-z', + ]) + expect(store.getState().documentText).toBe(before) + }) + + it('keeps the plain refusal on a measured view (C33)', async () => { + await openReady() + await holdNewDrawing('0 0 20 20') + const step = attachToView('view-main', NEW_ASSET) + expect(step).toMatchObject({ ok: false, error: { code: 'frame' } }) + }) +}) + +describe('applyRepair', () => { + const context = { t, locale: 'fr' as const } + const offerOf = () => { + const step = attachToView('view-main', NEW_ASSET) + if (step.ok || step.error.code !== 'repair') throw new Error('no offer') + return step.error.offer + } + const proposals = (offer: ReturnType) => ({ + 'anno-a': proposeGeometry( + offer.frames['view-main'], + annotation('anno-a').geometry as Geometry, + ), + 'anno-z': proposeGeometry( + offer.frames['view-main'], + annotation('anno-z').geometry as Geometry, + ), + }) + + it('commits the drawing and the repaired geometry as one undo entry', async () => { + await openReady({ text: unmeasuredText() }) + await holdNewDrawing() + const text = store.getState().documentText + const offer = offerOf() + expect(applyRepair(offer, proposals(offer), context)).toEqual({ ok: true }) + expect(doc().views[0]).toMatchObject({ svg_asset_id: NEW_ASSET }) + expect(annotation('anno-a').geometry).toEqual({ + type: 'circle', + cx: 85, + cy: 85, + r: 15, + }) + expect(annotation('anno-a').review_status).toBe('to_confirm') + expect(store.getState().undo).toHaveLength(1) + store.getState().undoStep() + expect(store.getState().documentText).toBe(text) + }) + + it('keeps nothing and speaks per annotation when the core refuses the values', async () => { + await openReady({ text: unmeasuredText() }) + await holdNewDrawing() + const before = store.getState().documentText + const offer = offerOf() + const result = applyRepair( + offer, + { + ...proposals(offer), + 'anno-a': { type: 'circle', cx: 500, cy: 400, r: 5 }, + }, + context, + ) + expect(result).toMatchObject({ ok: false, general: null }) + if (result.ok) return + expect(Object.keys(result.byAnnotation)).toEqual(['anno-a']) + expect(result.byAnnotation['anno-a'].length).toBeGreaterThan(0) + expect(store.getState().documentText).toBe(before) + expect(store.getState().undo).toHaveLength(0) + }) + + it('is blocked while a recovery offer is pending', async () => { + await openReady({ text: unmeasuredText() }) + await holdNewDrawing() + const offer = offerOf() + store.setState({ recovery: 'pending' }) + const result = applyRepair(offer, proposals(offer), context) + expect(result).toMatchObject({ ok: false }) + expect(doc().views[0].svg_asset_id).toBeNull() + }) + + it('is refused for an offer of another session', async () => { + await openReady({ text: unmeasuredText() }) + await holdNewDrawing() + const offer = { ...offerOf(), session: -1 } + expect(applyRepair(offer, proposals(offer), context)).toMatchObject({ + ok: false, + }) + expect(doc().views[0].svg_asset_id).toBeNull() + }) +}) + +function storedOf(text: string) { + const cleaned = cleanSvg(new TextEncoder().encode(text)) + if (!cleaned.ok || !cleaned.value.stored || !cleaned.value.sha256) + throw new Error('bad') + return { + ...cleaned.value, + bytes: new TextEncoder().encode(cleaned.value.stored), + } +} + +function serverGets(text: string) { + const stored = storedOf(text) + sb.registerSheetAsset.mockResolvedValue(NEW_ASSET) + sb.listSheetAssets.mockResolvedValue([ + { + id: NEW_ASSET, + sha256: stored.sha256!, + byte_size: stored.byte_size!, + uploaded_at: null, + }, + ]) + sb.uploadSheetDrawing.mockResolvedValue('uploaded') + sb.confirmSheetAssetUpload.mockResolvedValue(NEW_ASSET) + sb.downloadSheetDrawing.mockImplementation(async (_c, hash) => + hash === stored.sha256 ? stored.bytes : svgBytes().bytes, + ) +} + +const SVG = + '' + +async function pickAndOpenDialog(text = unmeasuredText()) { + await openReady({ text }) + serverGets(SVG) + render() + const user = userEvent.setup() + const input = screen.getByTestId('view-view-main-file') as HTMLInputElement + await user.upload(input, new File([SVG], 'd.svg', { type: 'image/svg+xml' })) + const dialog = await screen.findByRole('dialog', { + name: t('editor.views.repair.title'), + }) + return { user, dialog } +} + +describe('the repair dialog', () => { + it('lists the annotations with proposals; typing and nothing else applies nothing', async () => { + const { user, dialog } = await pickAndOpenDialog() + const before = store.getState().documentText + expect( + within(dialog).getByText( + '2 annotations sortent du nouveau cadre de cette illustration.', + { exact: false }, + ), + ).toBeTruthy() + const row = within(dialog).getByTestId('repair-anno-a') + expect(within(row).getByLabelText('Centre x')).toHaveValue('85') + expect(within(row).getByLabelText('Centre y')).toHaveValue('85') + await user.clear(within(row).getByLabelText('Centre x')) + await user.type(within(row).getByLabelText('Centre x'), '60') + expect(store.getState().documentText).toBe(before) + expect(store.getState().undo).toHaveLength(0) + }) + + it('applies one batch: drawing and values together, the dialog closes', async () => { + const { user, dialog } = await pickAndOpenDialog() + await user.click( + within(dialog).getByRole('button', { + name: t('editor.views.repair.apply'), + }), + ) + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + expect(doc().views[0].svg_asset_id).toBe(NEW_ASSET) + expect(annotation('anno-a').geometry).toEqual({ + type: 'circle', + cx: 85, + cy: 85, + r: 15, + }) + expect(store.getState().undo).toHaveLength(1) + }) + + it('keeps the typed values and the document when the core refuses', async () => { + const { user, dialog } = await pickAndOpenDialog() + const before = store.getState().documentText + const row = within(dialog).getByTestId('repair-anno-a') + const cx = within(row).getByLabelText('Centre x') + await user.clear(cx) + await user.type(cx, '900') + await user.click( + within(dialog).getByRole('button', { + name: t('editor.views.repair.apply'), + }), + ) + expect( + await within(dialog).findByText(t('editor.views.repair.refused')), + ).toBeTruthy() + expect(within(row).getByLabelText('Centre x')).toHaveValue('900') + expect(within(row).getByRole('alert')).toBeTruthy() + expect(store.getState().documentText).toBe(before) + expect(screen.getByRole('dialog')).toBeTruthy() + }) + + it('cancels with the document unchanged and the drawing kept, saying how to repair', async () => { + const { user, dialog } = await pickAndOpenDialog() + const before = store.getState().documentText + await user.click( + within(dialog).getByRole('button', { + name: t('editor.views.repair.cancel'), + }), + ) + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + expect(store.getState().documentText).toBe(before) + expect(store.getState().drawings.map((d) => d.asset_id)).toContain( + NEW_ASSET, + ) + expect(screen.getByText(/sortent du nouveau cadre/)).toBeTruthy() + expect(screen.getByText(/L'illustration reste téléversée/)).toBeTruthy() + expect(screen.queryByText(/Déplacez d'abord/)).toBeNull() + }) + + it('blocks a path until it is replaced by a polygon, inside the same form', async () => { + const pathValue = { + ...(point('anno-p', 0, 0, 1).value as Annotation), + kind: 'zone' as const, + geometry: { type: 'path' as const, d: 'M 300 300 L 400 300 L 350 400 Z' }, + } as Annotation + const { user, dialog } = await pickAndOpenDialog( + unmeasuredText([pathValue]), + ) + const apply = within(dialog).getByRole('button', { + name: t('editor.views.repair.apply'), + }) + expect(apply).toBeDisabled() + const row = within(dialog).getByTestId('repair-anno-p') + expect( + within(row).getByText(t('editor.views.repair.path_blocked')), + ).toBeTruthy() + await user.click( + within(row).getByRole('button', { + name: t('editor.annotations.replace_polygon'), + }), + ) + expect(apply).toBeEnabled() + await user.click(apply) + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + expect(annotation('anno-p').geometry).toMatchObject({ type: 'polygon' }) + }) +})