From 1bbf97e65b9d8b530d5d1360d00027e154ec0fe8 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 4 Nov 2026 13:34:02 +0100 Subject: [PATCH] fix(app): closed hash and canonical-form drawing messages, split crop and drawing views --- .../2026-11-03-v1-2-6-label-proposals.md | 7 + .../components/editor/views/CropEditor.tsx | 223 +++++++----------- .../components/editor/views/ViewDrawing.tsx | 168 ++++++++----- .../components/editor/views/useCropGroup.ts | 81 +++++++ apps/app/src/editor/drawingReason.ts | 27 +++ apps/app/src/editor/drawingStatus.ts | 31 ++- apps/app/src/editor/drawingUpload.ts | 22 +- apps/app/src/editor/frameRefusal.ts | 3 + apps/app/src/editor/issues.ts | 39 ++- apps/app/src/editor/uploadMessages.ts | 18 +- apps/app/src/editor/viewUpdate.ts | 20 +- apps/app/src/i18n/en.ts | 7 +- apps/app/src/i18n/fr.ts | 7 +- .../tests/unit/editor-drawing-upload.test.tsx | 46 +++- apps/app/tests/unit/editor-store.test.ts | 9 + .../app/tests/unit/editor-tabs-views.test.tsx | 27 ++- 16 files changed, 487 insertions(+), 248 deletions(-) create mode 100644 apps/app/src/components/editor/views/useCropGroup.ts create mode 100644 apps/app/src/editor/drawingReason.ts 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 90145b14..744819c5 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 @@ -245,6 +245,13 @@ Status: `plan wording` = quoted in the plan or the brief (EN proposed unless not | `editor.upload.reason.reserved_id` | identifiant réservé | reserved identifier | Reader reason | proposal | | `editor.upload.reason.root_visibility` | élément racine masqué | hidden root element | Reader reason | proposal | | `editor.upload.reason.other` | motif non reconnu | unrecognised reason | Reader reason, any other | proposal | +| `editor.views.drawing.not_canonical` | Illustration refusée : elle n'est pas sous la forme enregistrée. Choisissez de nouveau le fichier d'origine pour la remplacer. | Drawing refused: it is not in the stored form. Choose the original file again to replace it. | Drawing state, core holds it as rejected (not_canonical) | G fix, V1-2 §9.2/§9.3 item 6 | +| `editor.views.drawing.rejected_reason` | Illustration refusée ({reason}). | Drawing refused ({reason}). | Drawing state, rejected for a reader reason; raw core detail never shown | G fix | +| `editor.views.drawing.hash_mismatch` | Illustration refusée : le contenu du fichier ne correspond pas à son empreinte enregistrée. | Drawing refused: the file content does not match its recorded hash. | Drawing state, bytes failed the hash check at load | G fix, §9.3 item 3 | +| `editor.upload.err.svg_not_canonical` | Cette illustration n'est pas sous la forme enregistrée : elle est refusée. Choisissez de nouveau le fichier d'origine. | This drawing is not in the stored form: it is refused. Choose the original file again. | Upload: bytes outside the page's cleaning refused at attach | G fix | +| `editor.upload.reason.processing_instruction` | instruction de traitement interdite | processing instruction not allowed | Reason in `{reason}` | G fix | +| `editor.upload.reason.removal` | le fichier contient des éléments à retirer | the file contains elements to remove | Reason in `{reason}` | G fix | +Removed: `editor.views.drawing.detail` (raw core detail no longer shown). | `editor.cleaning.title` | Nettoyer cette illustration ? | Clean this drawing? | Cleaning dialog title | proposal | | `editor.cleaning.body` | Ce fichier contient des éléments qui ne sont pas conservés. L'aperçu montre le dessin tel qu'il sera enregistré. | This file contains elements that are not kept. The preview shows the drawing as it will be saved. | Cleaning dialog | proposal | | `editor.cleaning.preview` | Aperçu du dessin nettoyé | Preview of the cleaned drawing | Cleaning dialog preview accessible name | proposal | diff --git a/apps/app/src/components/editor/views/CropEditor.tsx b/apps/app/src/components/editor/views/CropEditor.tsx index 4a36caef..d2e60ef5 100644 --- a/apps/app/src/components/editor/views/CropEditor.tsx +++ b/apps/app/src/components/editor/views/CropEditor.tsx @@ -1,18 +1,17 @@ -import { useEffect, useRef, useState } from 'react' import type { ViewBox } from '@faunosteo/core-wasm/types' import ActionButton from '@/components/editor/fields/ActionButton' import DraftField from '@/components/editor/fields/DraftField' import ReadOnlyValue from '@/components/editor/fields/ReadOnlyValue' -import { - BOX_KEYS, - fieldsOf, - parseBox, - sameBox, - type BoxFields, -} from '@/editor/viewBox' -import { useViewUpdate } from '@/editor/useViewUpdate' +import { BOX_KEYS, fieldsOf } from '@/editor/viewBox' import { useT } from '@/i18n/useT' import CropCanvas from './CropCanvas' +import { useCropGroup, type CropGroup } from './useCropGroup' + +interface CropProps { + viewId: string + parentId: string + box: ViewBox | null +} /** * The four `view_box` fields as ONE group: leaving the group or Enter proposes all four @@ -20,141 +19,91 @@ import CropCanvas from './CropCanvas' * marked « non appliqué », with the refusal naming what it would break. */ export default function CropEditor({ - viewId, - parentId, - box, readOnly, -}: { - viewId: string - parentId: string - box: ViewBox | null - readOnly: boolean -}) { - const t = useT() - if (readOnly) { - const fields = fieldsOf(box) - return ( -
- {BOX_KEYS.map((key) => ( - - ))} -
- ) - } - return + ...props +}: CropProps & { readOnly: boolean }) { + return readOnly ? : } -type Gate = { state: 'applied' } | { state: 'refused' } - -function EditableCrop({ - viewId, - parentId, - box, -}: { - viewId: string - parentId: string - box: ViewBox | null -}) { +function CropValues({ viewId, box }: CropProps) { const t = useT() - const views = useViewUpdate() - const saved = fieldsOf(box) - const [draft, setDraft] = useState(saved) - const [seen, setSeen] = useState(saved) - const [gate, setGate] = useState({ state: 'applied' }) - // A new saved box (undo, reload, restore, an accepted apply) replaces what was typed. - if (BOX_KEYS.some((key) => seen[key] !== saved[key])) { - setSeen(saved) - setDraft(saved) - setGate({ state: 'applied' }) - } - const apply = (fields: BoxFields): void => { - const parsed = parseBox(fields) - if (!parsed.ok) { - views.reject('crop', `editor.views.crop.${parsed.reason}`) - setGate({ state: 'refused' }) - } else if (sameBox(parsed.box, box)) { - views.clear() - setGate({ state: 'applied' }) - } else { - const done = views.update('crop', viewId, { view_box: parsed.box }, true) - setGate({ state: done ? 'applied' : 'refused' }) - } - } - const latest = useRef({ draft, saved, apply }) - useEffect(() => { - latest.current = { draft, saved, apply } - }) - useEffect( - () => () => { - const pending = latest.current - if (BOX_KEYS.some((key) => pending.draft[key] !== pending.saved[key])) { - pending.apply(pending.draft) - } - }, - [], - ) - const shown = parseBox(draft) - const rectangle = shown.ok ? shown.box : box - const revert = () => { - setDraft(saved) - setGate({ state: 'applied' }) - views.clear() - } + const fields = fieldsOf(box) return ( +
+ {BOX_KEYS.map((key) => ( + + ))} +
+ ) +} + +function EditableCrop({ viewId, parentId, box }: CropProps) { + const group = useCropGroup(viewId, box) + return (
-
{ - if (!event.currentTarget.contains(event.relatedTarget)) apply(draft) - }} - onKeyDown={(event) => { - if ( - event.key === 'Enter' && - event.target instanceof HTMLInputElement - ) { - apply(draft) - } - }} + + +
+ ) +} + +function CropFields({ viewId, group }: { viewId: string; group: CropGroup }) { + const t = useT() + return ( +
{ + if (!event.currentTarget.contains(event.relatedTarget)) group.apply() + }} + onKeyDown={(event) => { + if (event.key === 'Enter' && event.target instanceof HTMLInputElement) { + group.apply() + } + }} + > +

+ {t('editor.views.crop.hint')} +

+
+ {BOX_KEYS.map((key) => ( + group.setField(key, value)} + /> + ))} +
+ {group.refused && } +
+ ) +} + +function CropRefusal({ group }: { group: CropGroup }) { + const t = useT() + const message = group.views.error('crop') + return ( +
+

+ {t('editor.views.crop.not_applied')} +

+ {message &&

{message}

} + -

- {t('editor.views.crop.hint')} -

-
- {BOX_KEYS.map((key) => ( - setDraft({ ...draft, [key]: value })} - /> - ))} -
- {gate.state === 'refused' && ( -
-

- {t('editor.views.crop.not_applied')} -

- {views.error('crop') &&

{views.error('crop')}

} - - {t('editor.views.crop.revert')} - -
- )} -
- + {t('editor.views.crop.revert')} +
) } diff --git a/apps/app/src/components/editor/views/ViewDrawing.tsx b/apps/app/src/components/editor/views/ViewDrawing.tsx index 87e2f2cc..3623000e 100644 --- a/apps/app/src/components/editor/views/ViewDrawing.tsx +++ b/apps/app/src/components/editor/views/ViewDrawing.tsx @@ -2,9 +2,13 @@ import { useRef, type ChangeEvent } from 'react' import type { SheetView } from '@faunosteo/core-wasm/types' import ActionButton from '@/components/editor/fields/ActionButton' import Notice from '@/components/ui/Notice' -import { drawingStatusOf, drawingStatusText } from '@/editor/drawingStatus' +import { + drawingStatusOf, + drawingStatusText, + type DrawingStatus, +} from '@/editor/drawingStatus' import { unmeasuredViews } from '@/editor/issues' -import { useDrawingUpload } from '@/editor/useDrawingUpload' +import { useDrawingUpload, type DrawingUpload } from '@/editor/useDrawingUpload' import { uploadErrorMessage } from '@/editor/uploadMessages' import { useSheetDocument } from '@/editor/sheetDocument' import { useEditorStore } from '@/editor/state/editorStore' @@ -14,9 +18,9 @@ import { useLocaleStore } from '@/state/localeStore' import CleaningDialog from './CleaningDialog' /** - * A view's drawing: its state with the core's detail, the hint when it is not usable, - * « Choisir une illustration » (check, clean, upload, attach) and, on a detail view that - * has its own drawing, the way back to the parent's. + * A view's drawing: its state, the hint when it is not usable, « Choisir une + * illustration » (check, clean, upload, attach) and, on a detail view that has its own + * drawing, the way back to the parent's. */ export default function ViewDrawing({ view, @@ -25,88 +29,73 @@ export default function ViewDrawing({ view: SheetView readOnly: boolean }) { - const t = useT() const state = useEditorStore((s) => s.previewState) const failures = useEditorStore((s) => s.drawingFailures) if (!state) return null const status = drawingStatusOf(view, state, failures) - const inherits = view.kind === 'detail' && status.kind === 'none' const unmeasured = unmeasuredViews(state).has(view.id) - const unusable = status.kind !== 'ok' && !inherits return (
+ + {!readOnly && ( + + )} +
+ ) +} + +function DrawingLines({ + view, + status, + unmeasured, + readOnly, +}: { + view: SheetView + status: DrawingStatus + unmeasured: boolean + readOnly: boolean +}) { + const t = useT() + const inherits = view.kind === 'detail' && status.kind === 'none' + const unusable = status.kind !== 'ok' && !inherits + const muted = 'text-sm text-[var(--color-ink-muted)]' + return ( + <>

{t('editor.views.drawing')}

-

+

{inherits ? t('editor.views.drawing.inherited') : drawingStatusText(t, status)}

{!readOnly && (unusable || unmeasured) && ( -

- {t('editor.views.drawing.hint')} -

+

{t('editor.views.drawing.hint')}

)} {unmeasured && ( -

- {t('editor.views.drawing.unmeasured')} -

+

{t('editor.views.drawing.unmeasured')}

)} - - + ) } function DrawingActions({ view, - readOnly, ownDrawing, }: { view: SheetView - readOnly: boolean ownDrawing: boolean }) { const t = useT() - const locale = useLocaleStore((s) => s.locale) - const doc = useSheetDocument() - const input = useRef(null) const upload = useDrawingUpload(view.id) const views = useViewUpdate() - const pick = (event: ChangeEvent) => { - const file = event.target.files?.[0] - event.target.value = '' - if (file) void upload.start(file) - } - const failure = - upload.ui.phase === 'failed' - ? uploadErrorMessage(t, upload.ui.error, { doc, locale }) - : null - if (readOnly) return null return ( <>
- - input.current?.click()} - > - {t('editor.views.drawing.choose')} - + {view.kind === 'detail' && ownDrawing && ( )}
- {upload.ui.phase === 'working' && ( - {t('editor.upload.working')} - )} - {upload.ui.phase === 'done' && ( - {t('editor.upload.done')} - )} - {failure && {failure}} + {views.error('drawing') && ( {views.error('drawing')} )} @@ -138,3 +121,64 @@ function DrawingActions({ ) } + +function FilePicker({ + viewId, + upload, +}: { + viewId: string + upload: DrawingUpload +}) { + const t = useT() + const input = useRef(null) + const pick = (event: ChangeEvent) => { + const file = event.target.files?.[0] + event.target.value = '' + if (file) void upload.start(file) + } + return ( + <> + + input.current?.click()} + > + {t('editor.views.drawing.choose')} + + + ) +} + +function UploadNotices({ upload }: { upload: DrawingUpload }) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const doc = useSheetDocument() + const { ui } = upload + const failure = + ui.phase === 'failed' + ? uploadErrorMessage(t, ui.error, { doc, locale }) + : null + return ( + <> + {ui.phase === 'working' && ( + {t('editor.upload.working')} + )} + {ui.phase === 'done' && ( + {t('editor.upload.done')} + )} + {failure && {failure}} + + ) +} diff --git a/apps/app/src/components/editor/views/useCropGroup.ts b/apps/app/src/components/editor/views/useCropGroup.ts new file mode 100644 index 00000000..24fdaa82 --- /dev/null +++ b/apps/app/src/components/editor/views/useCropGroup.ts @@ -0,0 +1,81 @@ +import { useEffect, useRef, useState } from 'react' +import type { ViewBox } from '@faunosteo/core-wasm/types' +import { + BOX_KEYS, + fieldsOf, + parseBox, + sameBox, + type BoxFields, +} from '@/editor/viewBox' +import { useViewUpdate, type ViewUpdateApi } from '@/editor/useViewUpdate' + +export interface CropGroup { + draft: BoxFields + refused: boolean + views: ViewUpdateApi + /** The rectangle to draw: the typed group when it parses, else the saved box. */ + rectangle: ViewBox | null + setField: (key: keyof BoxFields, value: string) => void + apply: () => void + revert: () => void +} + +const differs = (a: BoxFields, b: BoxFields) => + BOX_KEYS.some((key) => a[key] !== b[key]) + +/** + * The four `view_box` fields as one group: `apply` proposes all four together under the + * geometry check; a refused group stays typed and `refused`. A new saved box (undo, reload, + * restore, an accepted apply) replaces what was typed; unmounting applies a pending group. + */ +export function useCropGroup(viewId: string, box: ViewBox | null): CropGroup { + const views = useViewUpdate() + const saved = fieldsOf(box) + const [draft, setDraft] = useState(saved) + const [seen, setSeen] = useState(saved) + const [refused, setRefused] = useState(false) + if (differs(seen, saved)) { + setSeen(saved) + setDraft(saved) + setRefused(false) + } + const apply = (): void => { + const parsed = parseBox(draft) + if (!parsed.ok) { + views.reject('crop', `editor.views.crop.${parsed.reason}`) + setRefused(true) + } else if (sameBox(parsed.box, box)) { + views.clear() + setRefused(false) + } else { + const done = views.update('crop', viewId, { view_box: parsed.box }, true) + setRefused(!done) + } + } + const latest = useRef({ draft, saved, apply }) + useEffect(() => { + latest.current = { draft, saved, apply } + }) + useEffect( + () => () => { + if (differs(latest.current.draft, latest.current.saved)) { + latest.current.apply() + } + }, + [], + ) + const shown = parseBox(draft) + return { + draft, + refused, + views, + rectangle: shown.ok ? shown.box : box, + setField: (key, value) => setDraft({ ...draft, [key]: value }), + apply, + revert: () => { + setDraft(saved) + setRefused(false) + views.clear() + }, + } +} diff --git a/apps/app/src/editor/drawingReason.ts b/apps/app/src/editor/drawingReason.ts new file mode 100644 index 00000000..5568e315 --- /dev/null +++ b/apps/app/src/editor/drawingReason.ts @@ -0,0 +1,27 @@ +/** The reasons the reader gives for a refused file, each with a `editor.upload.reason.*`. */ +const READER_REASONS: ReadonlySet = new Set([ + 'malformed', + 'doctype', + 'not_svg', + 'too_many_elements', + 'too_deep', + 'too_many_uses', + 'too_complex', + 'reference_cycle', + 'dangling_reference', + 'reserved_id', + 'root_visibility', + 'processing_instruction', + 'removal', +]) + +/** + * A drawing the core refuses (`detail` of a `rejected` state, or a cleaning reason) as a + * closed key: `not_canonical` (valid but not in the stored form), a reader reason, `removal` + * (the file would lose elements) or `other`. The core's text itself is never shown. + */ +export function rejectionReason(detail: string | null): string { + if (detail === 'not_canonical') return detail + if (detail?.startsWith('removed')) return 'removal' + return detail && READER_REASONS.has(detail) ? detail : 'other' +} diff --git a/apps/app/src/editor/drawingStatus.ts b/apps/app/src/editor/drawingStatus.ts index 0fb9a30c..65f13775 100644 --- a/apps/app/src/editor/drawingStatus.ts +++ b/apps/app/src/editor/drawingStatus.ts @@ -1,12 +1,14 @@ import type { PreviewState, SheetView } from '@faunosteo/core-wasm/types' import type { CatalogueFailure } from '@/catalogue/failure' +import { rejectionReason } from './drawingReason' import { loadFailureMessage } from './messages' /** The state of the drawing a view names itself (not the one it inherits). */ export type DrawingStatus = | { kind: 'none' } | { kind: 'ok' } - | { kind: 'missing' | 'rejected'; detail: string | null } + | { kind: 'missing'; detail: null } + | { kind: 'rejected'; detail: string | null } | { kind: 'failed'; failure: CatalogueFailure } export function drawingStatusOf( @@ -18,7 +20,9 @@ export function drawingStatusOf( if (assetId === null) return { kind: 'none' } const held = state.drawings.find((drawing) => drawing.asset_id === assetId) if (held?.state === 'ok') return { kind: 'ok' } - if (held) return { kind: held.state, detail: held.detail } + if (held?.state === 'rejected') + return { kind: 'rejected', detail: held.detail } + // A drawing the handle refused at load is `missing` for the core: the failure says why. const failure = failures[assetId] return failure ? { kind: 'failed', failure } @@ -28,9 +32,22 @@ export function drawingStatusOf( type Translate = (key: string) => string export function drawingStatusText(t: Translate, status: DrawingStatus): string { - if (status.kind === 'failed') return loadFailureMessage(t, status.failure) - const label = t(`editor.views.drawing.${status.kind}`) - if (status.kind === 'ok' || status.kind === 'none' || !status.detail) - return label - return `${label} ${t('editor.views.drawing.detail').replace('{detail}', status.detail)}` + if (status.kind === 'failed') return failedText(t, status.failure) + if (status.kind === 'rejected') return rejectedText(t, status.detail) + return t(`editor.views.drawing.${status.kind}`) +} + +function failedText(t: Translate, failure: CatalogueFailure): string { + return failure === 'drawing_hash_mismatch' + ? t('editor.views.drawing.hash_mismatch') + : loadFailureMessage(t, failure) +} + +function rejectedText(t: Translate, detail: string | null): string { + const reason = rejectionReason(detail) + if (reason === 'not_canonical') return t('editor.views.drawing.not_canonical') + return t('editor.views.drawing.rejected_reason').replace( + '{reason}', + t(`editor.upload.reason.${reason}`), + ) } diff --git a/apps/app/src/editor/drawingUpload.ts b/apps/app/src/editor/drawingUpload.ts index b66600fe..0b6e51ee 100644 --- a/apps/app/src/editor/drawingUpload.ts +++ b/apps/app/src/editor/drawingUpload.ts @@ -13,6 +13,7 @@ import { fetchDrawing } from '@/catalogue/catalogue' import type { CatalogueFailure } from '@/catalogue/failure' import { getSupabaseClient } from '@/lib/supabase' import { cleanSvg } from './core/cleaning' +import { rejectionReason } from './drawingReason' import type { GeometryRefusal } from './issues' import { useEditorStore } from './state/editorStore' import { updateView } from './viewUpdate' @@ -22,7 +23,13 @@ export const MAX_DRAWING_BYTES = 2 * 1024 * 1024 /** Everything that can stop an upload, as closed codes (never text from a server). */ export type UploadError = - | { code: 'too_large' | 'svg_active_content' | 'object_conflict' } + | { + code: + | 'too_large' + | 'svg_active_content' + | 'object_conflict' + | 'svg_not_canonical' + } | { code: 'caps' | 'core' | 'blocked' | 'stale' } | { code: 'svg_rejected'; reason: string } | { code: 'sheet'; kind: SheetFailureKind } @@ -154,13 +161,20 @@ export async function downloadAndHold( return fail({ code: held.failure.kind === 'caps' ? 'caps' : 'core' }) } +/** A drawing the core holds as refused is a closed upload code, not a frame message. */ +function refusedAttach(refusal: GeometryRefusal): UploadError { + if (refusal.reason !== 'drawing_rejected') return { code: 'frame', refusal } + const reason = rejectionReason(refusal.drawingDetail ?? null) + return reason === 'not_canonical' + ? { code: 'svg_not_canonical' } + : { code: 'svg_rejected', reason } +} + /** The last step: the view takes the drawing, under the geometry check of a frame change. */ 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({ code: 'frame', refusal: outcome.refusal }) - } + if (outcome.reason === 'refused') return fail(refusedAttach(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 fab8bf54..a25bf19c 100644 --- a/apps/app/src/editor/frameRefusal.ts +++ b/apps/app/src/editor/frameRefusal.ts @@ -19,6 +19,9 @@ export function frameRefusalMessage( ids .map((id) => (doc ? elementLabel(doc, { kind, id }, locale) : id)) .join(', ') + if (refusal.reason === 'drawing_rejected') { + return t('editor.upload.err.svg_not_canonical') + } if (refusal.reason === 'view_unmeasured') { return t('editor.views.frame.view_unmeasured').replace( '{names}', diff --git a/apps/app/src/editor/issues.ts b/apps/app/src/editor/issues.ts index 44dd86b4..d1e7954e 100644 --- a/apps/app/src/editor/issues.ts +++ b/apps/app/src/editor/issues.ts @@ -28,20 +28,28 @@ export function geometryErrorsById( const index = GEOMETRY_PATH.exec(issue.path)?.[1] const annotation = state.document.annotations[Number(index)] if (index === undefined || !annotation) continue - const entry = { annotationId: annotation.id, code: issue.code, message: issue.message } + const entry = { + annotationId: annotation.id, + code: issue.code, + message: issue.message, + } byId.set(annotation.id, [...(byId.get(annotation.id) ?? []), entry]) } return byId } /** The asset a view draws: its own, else the first up its parent chain (cycle-safe). */ -function drawingAssetOf(views: readonly SheetView[], viewId: string): string | null { +function drawingAssetOf( + views: readonly SheetView[], + viewId: string, +): string | null { const seen = new Set() let view = views.find((candidate) => candidate.id === viewId) while (view && !seen.has(view.id)) { if (view.svg_asset_id) return view.svg_asset_id seen.add(view.id) - const parent: string | null = view.kind === 'detail' ? view.parent_view_id : null + const parent: string | null = + view.kind === 'detail' ? view.parent_view_id : null view = parent === null ? undefined : views.find((v) => v.id === parent) } return null @@ -75,6 +83,7 @@ export type GeometryRefusalReason = | 'changed_unmeasured' | 'newly_invalid' | 'view_unmeasured' + | 'drawing_rejected' /** What `geometryAccept` answers on a refusal: the annotations, issues and views at fault. */ export interface GeometryRefusal { @@ -82,6 +91,8 @@ export interface GeometryRefusal { annotationIds: string[] issues: GeometryIssue[] viewIds: string[] + /** The core's detail for a `drawing_rejected` refusal (mapped, never shown). */ + drawingDetail?: string } export interface GeometryAcceptInput { @@ -129,7 +140,8 @@ function frameFault( const newlyInvalid = [...geometryErrorsById(after)] .filter(([id]) => !errorsBefore.has(id)) .flatMap(([, issues]) => issues) - if (newlyInvalid.length > 0) return refusal('newly_invalid', { issues: newlyInvalid }) + if (newlyInvalid.length > 0) + return refusal('newly_invalid', { issues: newlyInvalid }) const unmeasuredBefore = unmeasuredViews(before) const knownBefore = new Set(before.document.views.map((v) => v.id)) const lost = [...unmeasuredViews(after)].filter( @@ -155,3 +167,22 @@ export function geometryAccept( changedFault(after, input.changedIds) ?? frameFault(input.before, after) ?? { accepted: true } } + +/** A new drawing the core holds as `rejected` is refused before any geometry is judged. */ +export function rejectedDrawingFault( + after: PreviewState, + assetId: string, +): Acceptance | null { + const held = after.drawings.find((drawing) => drawing.asset_id === assetId) + if (held?.state !== 'rejected') return null + return { + accepted: false, + refusal: { + reason: 'drawing_rejected', + annotationIds: [], + issues: [], + viewIds: [], + drawingDetail: held.detail ?? undefined, + }, + } +} diff --git a/apps/app/src/editor/uploadMessages.ts b/apps/app/src/editor/uploadMessages.ts index 965177cb..e94c45fe 100644 --- a/apps/app/src/editor/uploadMessages.ts +++ b/apps/app/src/editor/uploadMessages.ts @@ -2,26 +2,12 @@ import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types' import { failureMessage } from '@/admin/labels' import type { Locale } from '@/i18n/types' import { frameRefusalMessage } from './frameRefusal' +import { rejectionReason } from './drawingReason' import { loadFailureMessage } from './messages' import type { UploadError } from './drawingUpload' type Translate = (key: string) => string -/** The reasons the reader gives for a refused file, each with a `editor.upload.reason.*`. */ -const READER_REASONS: ReadonlySet = new Set([ - 'malformed', - 'doctype', - 'not_svg', - 'too_many_elements', - 'too_deep', - 'too_many_uses', - 'too_complex', - 'reference_cycle', - 'dangling_reference', - 'reserved_id', - 'root_visibility', -]) - /** Server kinds with their own upload wording; the others go through `failureMessage`. */ const UPLOAD_KINDS: ReadonlySet = new Set([ 'size_mismatch', @@ -39,7 +25,7 @@ export function uploadErrorMessage( case 'stale': return null case 'svg_rejected': { - const reason = READER_REASONS.has(error.reason) ? error.reason : 'other' + const reason = rejectionReason(error.reason) return t('editor.upload.err.svg_rejected').replace( '{reason}', t(`editor.upload.reason.${reason}`), diff --git a/apps/app/src/editor/viewUpdate.ts b/apps/app/src/editor/viewUpdate.ts index 3608d90f..5b3518e5 100644 --- a/apps/app/src/editor/viewUpdate.ts +++ b/apps/app/src/editor/viewUpdate.ts @@ -1,5 +1,13 @@ -import type { DetailView, SheetView } from '@faunosteo/core-wasm/types' -import { geometryAccept, type GeometryRefusal } from './issues' +import type { + DetailView, + PreviewState, + SheetView, +} from '@faunosteo/core-wasm/types' +import { + geometryAccept, + rejectedDrawingFault, + type GeometryRefusal, +} from './issues' import { useEditorStore } from './state/editorStore' import type { CommitOutcome } from './state/editorTypes' @@ -25,14 +33,16 @@ export function updateView( if (!before || !view) return { ok: false, reason: 'blocked', kind: 'not_ready' } 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) return store.commit( { op: 'update', key: { kind: 'view', id: viewId }, element: { kind: 'view', value }, }, - guarded - ? { accept: geometryAccept({ before, changedIds: [] }) } - : undefined, + guarded ? { accept } : undefined, ) } diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index c6add494..ef79d580 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -1346,7 +1346,9 @@ export const en: Dict = { 'editor.views.drawing.ok': 'Drawing valid', 'editor.views.drawing.missing': 'Drawing not found', 'editor.views.drawing.rejected': 'Drawing rejected', - 'editor.views.drawing.detail': 'Detail: {detail}', + 'editor.views.drawing.not_canonical': "Drawing refused: it is not in the stored form. Choose the original file again to replace it.", + 'editor.views.drawing.rejected_reason': "Drawing refused ({reason}).", + 'editor.views.drawing.hash_mismatch': "Drawing refused: the file content does not match its recorded hash.", 'editor.views.drawing.inherited': "Uses the parent view's drawing.", 'editor.views.drawing.hint': "Use « Choose a drawing » to add or replace this view's drawing.", 'editor.views.drawing.unmeasured': 'This view cannot be measured: add or fix its drawing before placing or moving elements.', @@ -1378,6 +1380,7 @@ export const en: Dict = { 'editor.upload.err.too_large': 'This file is larger than 2 MiB.', 'editor.upload.err.svg_active_content': 'This file contains active or external content (script, link, remote image): it is refused.', 'editor.upload.err.svg_rejected': 'This file is not a usable SVG drawing ({reason}).', + 'editor.upload.err.svg_not_canonical': "This drawing is not in the stored form: it is refused. Choose the original file again.", 'editor.upload.err.size_mismatch': 'The size of the file sent does not match the announced size. Try again.', 'editor.upload.err.upload_missing': 'The file did not reach the server. Try again.', 'editor.upload.err.upload.pending_other': 'Another account is sending this drawing. Try again in a moment.', @@ -1395,6 +1398,8 @@ export const en: Dict = { 'editor.upload.reason.dangling_reference': 'reference to a missing element', 'editor.upload.reason.reserved_id': 'reserved identifier', 'editor.upload.reason.root_visibility': 'hidden root element', + 'editor.upload.reason.processing_instruction': "processing instruction not allowed", + 'editor.upload.reason.removal': "the file contains elements to remove", 'editor.upload.reason.other': 'unrecognised reason', 'editor.cleaning.title': 'Clean this drawing?', 'editor.cleaning.body': 'This file contains elements that are not kept. The preview shows the drawing as it will be saved.', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index f11c40ab..bccbd0c5 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -1377,7 +1377,9 @@ export const fr: Dict = { 'editor.views.drawing.ok': 'Illustration valide', 'editor.views.drawing.missing': 'Illustration introuvable', 'editor.views.drawing.rejected': 'Illustration refusée', - 'editor.views.drawing.detail': 'Détail : {detail}', + 'editor.views.drawing.not_canonical': "Illustration refusée : elle n'est pas sous la forme enregistrée. Choisissez de nouveau le fichier d'origine pour la remplacer.", + 'editor.views.drawing.rejected_reason': "Illustration refusée ({reason}).", + 'editor.views.drawing.hash_mismatch': "Illustration refusée : le contenu du fichier ne correspond pas à son empreinte enregistrée.", 'editor.views.drawing.inherited': "Utilise l'illustration de la vue parente.", 'editor.views.drawing.hint': 'Utilisez « Choisir une illustration » pour ajouter ou remplacer le dessin de cette vue.', 'editor.views.drawing.unmeasured': "Cette vue n'est pas mesurable : ajoutez ou corrigez son illustration avant de placer ou de déplacer des éléments.", @@ -1409,6 +1411,7 @@ export const fr: Dict = { 'editor.upload.err.too_large': 'Ce fichier dépasse 2 Mio.', 'editor.upload.err.svg_active_content': 'Ce fichier contient du contenu actif ou externe (script, lien, image distante) : il est refusé.', 'editor.upload.err.svg_rejected': "Ce fichier n'est pas un dessin SVG utilisable ({reason}).", + 'editor.upload.err.svg_not_canonical': "Cette illustration n'est pas sous la forme enregistrée : elle est refusée. Choisissez de nouveau le fichier d'origine.", 'editor.upload.err.size_mismatch': 'La taille du fichier envoyé ne correspond pas à celle annoncée. Réessayez.', 'editor.upload.err.upload_missing': "Le fichier n'est pas arrivé sur le serveur. Réessayez.", 'editor.upload.err.upload.pending_other': "Ce dessin est en cours d'envoi par un autre compte. Réessayez dans quelques instants.", @@ -1426,6 +1429,8 @@ export const fr: Dict = { 'editor.upload.reason.dangling_reference': 'référence vers un élément absent', 'editor.upload.reason.reserved_id': 'identifiant réservé', 'editor.upload.reason.root_visibility': 'élément racine masqué', + 'editor.upload.reason.processing_instruction': "instruction de traitement interdite", + 'editor.upload.reason.removal': "le fichier contient des éléments à retirer", 'editor.upload.reason.other': 'motif non reconnu', 'editor.cleaning.title': 'Nettoyer cette illustration ?', 'editor.cleaning.body': "Ce fichier contient des éléments qui ne sont pas conservés. L'aperçu montre le dessin tel qu'il sera enregistré.", diff --git a/apps/app/tests/unit/editor-drawing-upload.test.tsx b/apps/app/tests/unit/editor-drawing-upload.test.tsx index d06be935..8078c3fb 100644 --- a/apps/app/tests/unit/editor-drawing-upload.test.tsx +++ b/apps/app/tests/unit/editor-drawing-upload.test.tsx @@ -12,7 +12,10 @@ import { SheetFailure } from '@faunosteo/supabase' import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types' import ViewsTab from '@/components/editor/tabs/ViewsTab' import { cleanSvg } from '@/editor/core/cleaning' -import { MAX_DRAWING_BYTES } from '@/editor/drawingUpload' +import { createHash } from 'node:crypto' +import { getDict } from '@/i18n' +import { uploadErrorMessage } from '@/editor/uploadMessages' +import { MAX_DRAWING_BYTES, attachToView } from '@/editor/drawingUpload' import { useLocaleStore } from '@/state/localeStore' import { ASSET } from '../helpers/editorFixtures' import { openReady, resetStore, sb, store } from '../helpers/editorHarness' @@ -139,13 +142,11 @@ describe('drawing upload flow', () => { expect( within(dialog).getByTestId('cleaning-preview').querySelector('svg'), ).not.toBeNull() - await userEvent - .setup() - .click( - within(dialog).getByRole('button', { - name: 'Nettoyer et utiliser cette version', - }), - ) + await userEvent.setup().click( + within(dialog).getByRole('button', { + name: 'Nettoyer et utiliser cette version', + }), + ) await waitFor(() => expect(mainAsset()).toBe(NEW_ASSET)) expect(sb.uploadSheetDrawing).toHaveBeenCalledTimes(1) }) @@ -255,6 +256,35 @@ describe('drawing upload flow', () => { expect(mainAsset()).toBe(ASSET) }) + it('a held drawing outside the stored form is refused at attach as svg_not_canonical', async () => { + const bytes = new TextEncoder().encode( + svg('0 0 200 100', ' '), + ) + const sha256 = createHash('sha256').update(bytes).digest('hex') + expect( + store.getState().addDrawing({ assetId: NEW_ASSET, sha256, bytes }).ok, + ).toBe(true) + expect(attachToView('view-main', NEW_ASSET)).toEqual({ + ok: false, + error: { code: 'svg_not_canonical' }, + }) + expect(mainAsset()).toBe(ASSET) + }) + + it('phrases svg_not_canonical and the new reader reasons', () => { + const t = (key: string) => getDict('fr')[key as never] as string + const context = { doc: null, locale: 'fr' as const } + expect( + uploadErrorMessage(t, { code: 'svg_not_canonical' }, context), + ).toMatch(/pas sous la forme enregistrée/) + const reason = (value: string) => + uploadErrorMessage(t, { code: 'svg_rejected', reason: value }, context) + expect(reason('processing_instruction')).toMatch( + /instruction de traitement/, + ) + expect(reason('removed