fix(app): closed hash and canonical-form drawing messages, split crop and drawing views

This commit is contained in:
bchanot committed 2026-11-04 13:34:02 +01:00
1 parent 7bf1404946
commit 1bbf97e65b
16 files changed
+487 -248

No files matched your search

@@ -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 |
@@ -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 (
<div className="grid gap-3 sm:grid-cols-4">
{BOX_KEYS.map((key) => (
<ReadOnlyValue
key={key}
id={`view-${viewId}-crop-${key}`}
label={t(`editor.views.crop.${key}`)}
value={fields[key]}
/>
))}
</div>
)
}
return <EditableCrop viewId={viewId} parentId={parentId} box={box} />
...props
}: CropProps & { readOnly: boolean }) {
return readOnly ? <CropValues {...props} /> : <EditableCrop {...props} />
}
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<BoxFields>(saved)
const [seen, setSeen] = useState<BoxFields>(saved)
const [gate, setGate] = useState<Gate>({ 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 (
<div className="grid gap-3 sm:grid-cols-4">
{BOX_KEYS.map((key) => (
<ReadOnlyValue
key={key}
id={`view-${viewId}-crop-${key}`}
label={t(`editor.views.crop.${key}`)}
value={fields[key]}
/>
))}
</div>
)
}
function EditableCrop({ viewId, parentId, box }: CropProps) {
const group = useCropGroup(viewId, box)
return (
<div className="grid gap-4 md:grid-cols-2">
<div
role="group"
aria-label={t('editor.views.crop.title')}
className="space-y-3"
onBlur={(event) => {
if (!event.currentTarget.contains(event.relatedTarget)) apply(draft)
}}
onKeyDown={(event) => {
if (
event.key === 'Enter' &&
event.target instanceof HTMLInputElement
) {
apply(draft)
}
}}
<CropFields viewId={viewId} group={group} />
<CropCanvas parentId={parentId} box={group.rectangle} />
</div>
)
}
function CropFields({ viewId, group }: { viewId: string; group: CropGroup }) {
const t = useT()
return (
<div
role="group"
aria-label={t('editor.views.crop.title')}
className="space-y-3"
onBlur={(event) => {
if (!event.currentTarget.contains(event.relatedTarget)) group.apply()
}}
onKeyDown={(event) => {
if (event.key === 'Enter' && event.target instanceof HTMLInputElement) {
group.apply()
}
}}
>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.views.crop.hint')}
</p>
<div className="grid grid-cols-2 gap-3">
{BOX_KEYS.map((key) => (
<DraftField
key={key}
id={`view-${viewId}-crop-${key}`}
label={t(`editor.views.crop.${key}`)}
value={group.draft[key]}
onChange={(value) => group.setField(key, value)}
/>
))}
</div>
{group.refused && <CropRefusal group={group} />}
</div>
)
}
function CropRefusal({ group }: { group: CropGroup }) {
const t = useT()
const message = group.views.error('crop')
return (
<div role="alert" className="space-y-2 text-sm">
<p className="font-medium text-[var(--color-danger-strong)]">
{t('editor.views.crop.not_applied')}
</p>
{message && <p>{message}</p>}
<ActionButton
readOnly={false}
variant="ghost"
size="sm"
onClick={group.revert}
>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.views.crop.hint')}
</p>
<div className="grid grid-cols-2 gap-3">
{BOX_KEYS.map((key) => (
<DraftField
key={key}
id={`view-${viewId}-crop-${key}`}
label={t(`editor.views.crop.${key}`)}
value={draft[key]}
onChange={(value) => setDraft({ ...draft, [key]: value })}
/>
))}
</div>
{gate.state === 'refused' && (
<div role="alert" className="space-y-2 text-sm">
<p className="font-medium text-[var(--color-danger-strong)]">
{t('editor.views.crop.not_applied')}
</p>
{views.error('crop') && <p>{views.error('crop')}</p>}
<ActionButton
readOnly={false}
variant="ghost"
size="sm"
onClick={revert}
>
{t('editor.views.crop.revert')}
</ActionButton>
</div>
)}
</div>
<CropCanvas parentId={parentId} box={rectangle} />
{t('editor.views.crop.revert')}
</ActionButton>
</div>
)
}
@@ -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 (
<div className="space-y-2" data-testid={`view-${view.id}-drawing`}>
<DrawingLines
view={view}
status={status}
unmeasured={unmeasured}
readOnly={readOnly}
/>
{!readOnly && (
<DrawingActions view={view} ownDrawing={status.kind !== 'none'} />
)}
</div>
)
}
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 (
<>
<p className="text-sm font-medium">{t('editor.views.drawing')}</p>
<p className="text-sm text-[var(--color-ink-muted)]">
<p className={muted}>
{inherits
? t('editor.views.drawing.inherited')
: drawingStatusText(t, status)}
</p>
{!readOnly && (unusable || unmeasured) && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.views.drawing.hint')}
</p>
<p className={muted}>{t('editor.views.drawing.hint')}</p>
)}
{unmeasured && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.views.drawing.unmeasured')}
</p>
<p className={muted}>{t('editor.views.drawing.unmeasured')}</p>
)}
<DrawingActions
view={view}
readOnly={readOnly}
ownDrawing={status.kind !== 'none'}
/>
</div>
</>
)
}
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<HTMLInputElement | null>(null)
const upload = useDrawingUpload(view.id)
const views = useViewUpdate()
const pick = (event: ChangeEvent<HTMLInputElement>) => {
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 (
<>
<div className="flex flex-wrap items-center gap-2">
<input
ref={input}
type="file"
accept=".svg,image/svg+xml"
className="sr-only"
tabIndex={-1}
aria-label={t('editor.views.drawing.file')}
data-testid={`view-${view.id}-file`}
onChange={pick}
/>
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
disabled={upload.ui.phase === 'working'}
onClick={() => input.current?.click()}
>
{t('editor.views.drawing.choose')}
</ActionButton>
<FilePicker viewId={view.id} upload={upload} />
{view.kind === 'detail' && ownDrawing && (
<ActionButton
readOnly={false}
@@ -120,13 +109,7 @@ function DrawingActions({
</ActionButton>
)}
</div>
{upload.ui.phase === 'working' && (
<Notice tone="info">{t('editor.upload.working')}</Notice>
)}
{upload.ui.phase === 'done' && (
<Notice tone="success">{t('editor.upload.done')}</Notice>
)}
{failure && <Notice tone="error">{failure}</Notice>}
<UploadNotices upload={upload} />
{views.error('drawing') && (
<Notice tone="error">{views.error('drawing')}</Notice>
)}
@@ -138,3 +121,64 @@ function DrawingActions({
</>
)
}
function FilePicker({
viewId,
upload,
}: {
viewId: string
upload: DrawingUpload
}) {
const t = useT()
const input = useRef<HTMLInputElement | null>(null)
const pick = (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
event.target.value = ''
if (file) void upload.start(file)
}
return (
<>
<input
ref={input}
type="file"
accept=".svg,image/svg+xml"
className="sr-only"
tabIndex={-1}
aria-label={t('editor.views.drawing.file')}
data-testid={`view-${viewId}-file`}
onChange={pick}
/>
<ActionButton
readOnly={false}
variant="secondary"
size="sm"
disabled={upload.ui.phase === 'working'}
onClick={() => input.current?.click()}
>
{t('editor.views.drawing.choose')}
</ActionButton>
</>
)
}
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' && (
<Notice tone="info">{t('editor.upload.working')}</Notice>
)}
{ui.phase === 'done' && (
<Notice tone="success">{t('editor.upload.done')}</Notice>
)}
{failure && <Notice tone="error">{failure}</Notice>}
</>
)
}
@@ -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<BoxFields>(saved)
const [seen, setSeen] = useState<BoxFields>(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()
},
}
}
+27
View File
@@ -0,0 +1,27 @@
/** The reasons the reader gives for a refused file, each with a `editor.upload.reason.*`. */
const READER_REASONS: ReadonlySet<string> = 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'
}
+24 -7
View File
@@ -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}`),
)
}
+18 -4
View File
@@ -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<null> {
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' })
}
+3
View File
@@ -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}',
+35 -4
View File
@@ -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<string>()
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<GeometryRefusal> | 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,
},
}
}
+2 -16
View File
@@ -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<string> = 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<string> = 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}`),
+15 -5
View File
@@ -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,
)
}
+6 -1
View File
@@ -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.',
+6 -1
View File
@@ -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é.",
@@ -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', ' <rect width="4" height="4"/>'),
)
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 <script>')).toMatch(/éléments à retirer/)
})
it('a refused frame change leaves the drawing uploaded and held, the view unchanged', async () => {
serverGets(svg('0 0 20 20'))
await pick(svg('0 0 20 20'))
+9
View File
@@ -51,6 +51,15 @@ describe('open and sessions', () => {
expect(store.getState().previewState?.drawings[0]).toMatchObject({ state: 'missing' })
})
it('records a drawing whose bytes fail the hash check at load', async () => {
serverHas(baseText(), 3)
sb.downloadSheetDrawing.mockResolvedValue(new TextEncoder().encode('<svg/>'))
store.getState().open(VERSION, USER)
await vi.waitFor(() => expect(store.getState().status).toBe('ready'))
expect(store.getState().drawingFailures[ASSET]).toBe('drawing_hash_mismatch')
expect(store.getState().drawings).toEqual([])
})
it('drops a late load after close and frees the preview it built', async () => {
const late = deferred<unknown>()
sb.getSheetVersion.mockReturnValue(late.promise as never)
+24 -3
View File
@@ -111,7 +111,7 @@ describe('Vues et illustrations: drawing states', () => {
).toBeTruthy()
})
it('a rejected drawing shows the core detail', async () => {
it('a rejected drawing shows the closed not-canonical message, no raw detail', async () => {
const bytes = new TextEncoder().encode(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"> <rect width="4" height="4"/></svg>',
)
@@ -125,8 +125,29 @@ describe('Vues et illustrations: drawing states', () => {
store.getState().open('ver-1', 'user-1', { canEdit: true })
await vi.waitFor(() => expect(store.getState().status).toBe('ready'))
render(<ViewsTab {...props} />)
expect(screen.getByText(/Illustration refusée/)).toBeTruthy()
expect(screen.getByText(/Détail : not_canonical/)).toBeTruthy()
expect(
screen.getByText(
/Illustration refusée : elle n'est pas sous la forme enregistrée/,
),
).toBeTruthy()
expect(screen.queryByText(/not_canonical/)).toBeNull()
})
it('bytes that fail the hash check at load show their own message, not « introuvable »', async () => {
store.getState().close()
sb.getSheetVersion.mockResolvedValue(
versionAnswer(baseText(), 3, true) as never,
)
sb.downloadSheetDrawing.mockResolvedValue(
new TextEncoder().encode('<svg/>'),
)
store.getState().open('ver-1', 'user-1', { canEdit: true })
await vi.waitFor(() => expect(store.getState().status).toBe('ready'))
render(<ViewsTab {...props} />)
expect(
screen.getByText(/ne correspond pas à son empreinte enregistrée/),
).toBeTruthy()
expect(screen.queryByText(/introuvable/)).toBeNull()
})
it('read-only shows states as text and no action', async () => {