feat(app): editor views tab, drawing upload and cleaning, guarded crops

This commit is contained in:
bchanot committed 2026-11-04 13:02:30 +01:00
1 parent d163b2ce9a
commit 8343528be9
22 files changed
+2164 -4

No files matched your search

@@ -177,3 +177,80 @@ Status column: `ratified` = REVUE.md wording; `plan wording` = quoted in the pla
| `editor.vertebra.new` | Nouvelle région vertébrale | New vertebral region | Region creation form | proposal |
| `editor.vertebra.add` | Ajouter la région | Add the region | Region creation button | proposal |
| `editor.vertebra.required` | Renseignez le code et les noms français et anglais. | Fill in the code and the French and English names. | Region creation, missing field | proposal |
## Lot G (Vues et illustrations, upload, cleaning dialog)
Status: `plan wording` = quoted in the plan or the brief (EN proposed unless noted); `proposal` = new.
| Key | FR | EN | Where | Status |
|---|---|---|---|---|
| `editor.views.main_title` | Vue principale | Main view | Views tab, main view card | proposal |
| `editor.views.details_title` | Vues de détail | Detail views | Views tab, section title | proposal |
| `editor.views.empty` | Aucune vue de détail pour l'instant. | No detail view yet. | Views tab, empty list | proposal |
| `editor.views.name_fr` | Nom de la vue (FR) | View name (FR) | View field | proposal |
| `editor.views.name_en` | Nom de la vue (EN) | View name (EN) | View field | proposal |
| `editor.views.parent` | Vue parente | Parent view | Detail view field | proposal |
| `editor.views.drawing` | Illustration | Drawing | View drawing section title | plan wording |
| `editor.views.drawing.none` | Aucune illustration | No drawing | Drawing state | proposal |
| `editor.views.drawing.ok` | Illustration valide | Drawing valid | Drawing state | plan wording (state ok) |
| `editor.views.drawing.missing` | Illustration introuvable | Drawing not found | Drawing state | plan wording (state missing) |
| `editor.views.drawing.rejected` | Illustration refusée | Drawing rejected | Drawing state | plan wording (state rejected) |
| `editor.views.drawing.detail` | Détail : {detail} | Detail: {detail} | Drawing state, the core's detail | proposal |
| `editor.views.drawing.inherited` | Utilise l'illustration de la vue parente. | Uses the parent view's drawing. | Detail view without own drawing | proposal |
| `editor.views.drawing.hint` | Utilisez « Choisir une illustration » pour ajouter ou remplacer le dessin de cette vue. | Use « Choose a drawing » to add or replace this view's drawing. | Hint when the drawing is not usable (edit mode) | proposal |
| `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. | This view cannot be measured: add or fix its drawing before placing or moving elements. | Hint on an unmeasured view | proposal (adapted from the plan's Annotations hint) |
| `editor.views.drawing.choose` | Choisir une illustration | Choose a drawing | Button (brief wording) | brief wording FR; EN proposal |
| `editor.views.drawing.file` | Fichier d'illustration (SVG) | Drawing file (SVG) | File input accessible name | proposal |
| `editor.views.drawing.use_parent` | Utiliser l'illustration de la vue parente | Use the parent view's drawing | Detail view, removes its own drawing (frame change) | proposal |
| `editor.views.crop.title` | Recadrage | Crop | Detail view crop section | proposal |
| `editor.views.crop.toggle` | Modifier le recadrage | Edit the crop | Button, opens the crop fields and the parent canvas | proposal |
| `editor.views.crop.min_x` | Recadrage : x minimum | Crop: minimum x | Crop field (view_box.min_x) | proposal |
| `editor.views.crop.min_y` | Recadrage : y minimum | Crop: minimum y | Crop field (view_box.min_y) | proposal |
| `editor.views.crop.width` | Recadrage : largeur | Crop: width | Crop field (view_box.width) | proposal |
| `editor.views.crop.height` | Recadrage : hauteur | Crop: height | Crop field (view_box.height) | proposal |
| `editor.views.crop.hint` | Rectangle en unités du dessin parent. Quatre valeurs, ou aucune pour ne pas recadrer. Elles s'appliquent ensemble. | Rectangle in the parent drawing's units. Four values, or none for no crop. They apply together. | Crop group hint | proposal |
| `editor.views.crop.incomplete` | Indiquez les quatre valeurs du recadrage, ou aucune. | Fill in all four crop values, or none. | Crop group, a value missing | proposal |
| `editor.views.crop.number` | Les valeurs du recadrage sont des nombres. | The crop values are numbers. | Crop group, not a number | proposal |
| `editor.views.crop.not_applied` | Non appliqué | Not applied | Crop group refused (board wording « non appliqué ») | ratified FR (plan); EN proposal |
| `editor.views.crop.revert` | Revenir aux valeurs enregistrées | Revert to the saved values | Crop group refused | plan wording FR; EN proposal |
| `editor.views.crop.canvas` | Vue parente avec le rectangle de recadrage | Parent view with the crop rectangle | Crop canvas accessible name | proposal |
| `editor.views.crop.canvas_failed` | La vue parente ne peut pas être affichée. | The parent view cannot be displayed. | Crop canvas failure | proposal |
| `editor.views.new` | Nouvelle vue de détail | New detail view | Creation form | proposal |
| `editor.views.new_hint` | Saisissez le recadrage pour une vue recadrée ; laissez-le vide pour une vue qui aura sa propre illustration (à choisir une fois la vue ajoutée). | Fill in the crop for a cropped view; leave it empty for a view that will have its own drawing (chosen once the view is added). | Creation form hint | proposal |
| `editor.views.add` | Ajouter la vue | Add the view | Creation button | proposal |
| `editor.views.required` | Renseignez les noms français et anglais de la vue. | Fill in the French and English names of the view. | Creation, missing field | proposal |
| `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). | This frame change would put the geometry of these elements in error: {names}. Move them first (Annotations tab). | Refused frame change (crop, drawing, parent) | proposal |
| `editor.views.frame.view_unmeasured` | Ce changement rendrait non mesurable une vue qui porte des annotations : {names}. | This change would make a view that holds annotations unmeasurable: {names}. | Refused frame change | proposal |
| `editor.views.frame.kept` | L'illustration reste téléversée ; la vue garde son illustration précédente. | The drawing stays uploaded; the view keeps its previous drawing. | Refused attach after an upload | proposal |
| `editor.upload.working` | Vérification et envoi de l'illustration… | Checking and sending the drawing… | Upload in progress | proposal |
| `editor.upload.done` | L'illustration est ajoutée à la vue. | The drawing is added to the view. | Upload done | proposal |
| `editor.upload.err.too_large` | Ce fichier dépasse 2 Mio. | This file is larger than 2 MiB. | Upload refused | plan code too_large |
| `editor.upload.err.svg_active_content` | Ce fichier contient du contenu actif ou externe (script, lien, image distante) : il est refusé. | This file contains active or external content (script, link, remote image): it is refused. | Upload refused | plan code svg_active_content |
| `editor.upload.err.svg_rejected` | Ce fichier n'est pas un dessin SVG utilisable ({reason}). | This file is not a usable SVG drawing ({reason}). | Upload refused, with the reader's reason | plan code svg_rejected |
| `editor.upload.err.size_mismatch` | La taille du fichier envoyé ne correspond pas à celle annoncée. Réessayez. | The size of the file sent does not match the announced size. Try again. | Confirm refused | plan code size_mismatch |
| `editor.upload.err.upload_missing` | Le fichier n'est pas arrivé sur le serveur. Réessayez. | The file did not reach the server. Try again. | Confirm refused | plan code upload_missing |
| `editor.upload.err.upload.pending_other` | Ce dessin est en cours d'envoi par un autre compte. Réessayez dans quelques instants. | Another account is sending this drawing. Try again in a moment. | Policy refusal then confirm without object | plan code upload.pending_other |
| `editor.upload.err.object_conflict` | Un fichier différent existe déjà sous cette empreinte : l'illustration est refusée. | A different file already exists under this hash: the drawing is refused. | Downloaded object does not match its hash | plan code object_conflict |
| `editor.upload.err.caps` | Trop d'illustrations dans cette session d'édition (16 au plus). Enregistrez, puis rechargez le brouillon. | Too many drawings in this editing session (16 at most). Save, then reload the draft. | Core drawing cap | plan code caps |
| `editor.upload.err.core` | Le contrôle du document a refusé cette illustration. | The document check refused this drawing. | Core refusal | proposal |
| `editor.upload.reason.malformed` | fichier mal formé | malformed file | Reader reason | proposal |
| `editor.upload.reason.doctype` | déclaration DOCTYPE interdite | DOCTYPE declaration not allowed | Reader reason | proposal |
| `editor.upload.reason.not_svg` | ce n'est pas un SVG | not an SVG | Reader reason | proposal |
| `editor.upload.reason.too_many_elements` | trop d'éléments | too many elements | Reader reason | proposal |
| `editor.upload.reason.too_deep` | imbrication trop profonde | nesting too deep | Reader reason | proposal |
| `editor.upload.reason.too_many_uses` | trop de réutilisations (use) | too many reuses (use) | Reader reason | proposal |
| `editor.upload.reason.too_complex` | dessin trop complexe | drawing too complex | Reader reason | proposal |
| `editor.upload.reason.reference_cycle` | références circulaires | circular references | Reader reason | proposal |
| `editor.upload.reason.dangling_reference` | référence vers un élément absent | reference to a missing element | Reader reason | proposal |
| `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.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 |
| `editor.cleaning.preview_failed` | L'aperçu du dessin nettoyé ne peut pas être composé. | The preview of the cleaned drawing cannot be composed. | Cleaning dialog | proposal |
| `editor.cleaning.removed` | Éléments retirés : | Removed elements: | Cleaning dialog list | proposal |
| `editor.cleaning.active` | Contenu actif ou externe retiré : | Active or external content removed: | Cleaning dialog list | proposal |
| `editor.cleaning.style` | L'élément <style> a été retiré : les classes qu'il définissait s'afficheront sans style. | The <style> element was removed: the classes it defined will show unstyled. | Cleaning dialog | plan (style named) |
| `editor.cleaning.confirm` | Nettoyer et utiliser cette version | Clean and use this version | Cleaning dialog button | plan wording FR; EN proposal |
| `editor.cleaning.cancel` | Annuler | Cancel | Cleaning dialog button | plan wording FR; EN proposal |
@@ -1,14 +1,67 @@
import { useState } from 'react'
import DeleteDialog, {
type DeleteTarget,
} from '@/components/editor/DeleteDialog'
import DetailViewForm from '@/components/editor/views/DetailViewForm'
import DetailViewRow from '@/components/editor/views/DetailViewRow'
import MainViewCard from '@/components/editor/views/MainViewCard'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { EditorTabProps } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
/** Placeholder: Lot G replaces the body and keeps the props contract (`EditorTabProps`). */
export default function ViewsTab(_props: EditorTabProps) {
/**
* Vues et illustrations: the main view and its drawing, the detail views (parent, own
* drawing or crop), the upload of a drawing and the frame changes it brings.
*/
export default function ViewsTab({ readOnly }: EditorTabProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const doc = useSheetDocument()
const [deleting, setDeleting] = useState<DeleteTarget | null>(null)
const [cropOpen, setCropOpen] = useState<string | null>(null)
const views = doc?.views ?? []
const main = views.find((view) => view.kind === 'main')
const details = views.filter((view) => view.kind === 'detail')
return (
<section
data-testid="editor-tab-views"
aria-label={t('editor.tab.views')}
className="min-h-24"
/>
className="min-h-24 space-y-4"
>
{main?.kind === 'main' && (
<MainViewCard view={main} readOnly={readOnly} />
)}
<h3 className="text-base font-semibold">
{t('editor.views.details_title')}
</h3>
{doc && details.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.views.empty')}
</p>
)}
<ul className="space-y-3">
{details.map((view) => (
<DetailViewRow
key={view.id}
view={view}
views={views}
readOnly={readOnly}
cropOpen={cropOpen === view.id}
onToggleCrop={() =>
setCropOpen(cropOpen === view.id ? null : view.id)
}
onDelete={() =>
setDeleting({
key: { kind: 'view', id: view.id },
label: view.name[locale],
})
}
/>
))}
</ul>
{doc && !readOnly && <DetailViewForm views={views} />}
<DeleteDialog target={deleting} onClose={() => setDeleting(null)} />
</section>
)
}
@@ -0,0 +1,126 @@
import { useEffect, useRef, useState } from 'react'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import Notice from '@/components/ui/Notice'
import { buildView } from '@/components/catalogue/CatalogueCanvas'
import { composeCleaningPreview } from '@/editor/core/cleaning'
import type { Candidate } from '@/editor/drawingUpload'
import { useT } from '@/i18n/useT'
export interface CleaningDialogProps {
/** null = closed. */
candidate: Candidate | null
onConfirm: () => void
onCancel: () => void
}
/**
* The cleaned drawing the core composed from its own stored text (the uploaded file is
* never rendered), with what the cleaning removes, before the user accepts it.
*/
export default function CleaningDialog({
candidate,
onConfirm,
onCancel,
}: CleaningDialogProps) {
const t = useT()
return (
<Dialog
open={candidate !== null}
onClose={onCancel}
title={t('editor.cleaning.title')}
size="lg"
description={t('editor.cleaning.body')}
>
{candidate && (
<CleaningBody
candidate={candidate}
onConfirm={onConfirm}
onCancel={onCancel}
/>
)}
</Dialog>
)
}
/** Builds the throwaway preview once per candidate and frees it when the dialog closes. */
function useCleanedDrawing(candidate: Candidate) {
const host = useRef<HTMLDivElement | null>(null)
const [failed, setFailed] = useState(false)
useEffect(() => {
const composed = composeCleaningPreview({
stored: candidate.stored,
sha256: candidate.sha256,
})
const built = composed.ok
? buildView(composed.value.preview, composed.value.viewId)
: null
setFailed(!built?.ok)
if (built?.ok) host.current?.replaceChildren(built.svg)
return () => {
if (composed.ok) composed.value.preview.free()
}
}, [candidate])
return { host, failed }
}
function CleaningBody({
candidate,
onConfirm,
onCancel,
}: Omit<CleaningDialogProps, 'candidate'> & { candidate: Candidate }) {
const t = useT()
const { host, failed } = useCleanedDrawing(candidate)
return (
<div className="space-y-3">
<div
ref={host}
role="img"
aria-label={t('editor.cleaning.preview')}
data-testid="cleaning-preview"
className="aspect-[3/2] w-full overflow-hidden rounded-lg border border-[var(--color-border)] bg-white [&>svg]:block [&>svg]:h-full [&>svg]:w-full"
/>
{failed && (
<Notice tone="error">{t('editor.cleaning.preview_failed')}</Notice>
)}
<NameList title={t('editor.cleaning.active')} names={candidate.active} />
<NameList
title={t('editor.cleaning.removed')}
names={candidate.removed}
/>
{candidate.styleRemoved && (
<Notice tone="info">{t('editor.cleaning.style')}</Notice>
)}
<div className="flex flex-wrap justify-end gap-2">
<Button type="button" variant="ghost" onClick={onCancel}>
{t('editor.cleaning.cancel')}
</Button>
<Button type="button" disabled={failed} onClick={onConfirm}>
{t('editor.cleaning.confirm')}
</Button>
</div>
</div>
)
}
function NameList({
title,
names,
}: {
title: string
names: readonly string[]
}) {
if (names.length === 0) return null
return (
<div className="text-sm">
<p className="font-medium">{title}</p>
<ul className="mt-1 list-disc pl-5 text-[var(--color-ink-muted)]">
{names.map((name, index) => (
<li key={`${name}-${index}`}>
<code>{name}</code>
</li>
))}
</ul>
</div>
)
}
@@ -0,0 +1,84 @@
import { useEffect, useRef, useState } from 'react'
import type { ViewBox } from '@faunosteo/core-wasm/types'
import Notice from '@/components/ui/Notice'
import { buildView } from '@/components/catalogue/CatalogueCanvas'
import { useEditorStore } from '@/editor/state/editorStore'
import { useT } from '@/i18n/useT'
interface Frame {
viewBox: string
ratio: string
}
/**
* The parent view as the core composes it, with the crop rectangle over it. The overlay
* is page-drawn and holds numbers only (one rectangle in the composed root's own
* `viewBox`); it draws no annotation. It follows the handle, so an upload shows at once.
*/
export default function CropCanvas({
parentId,
box,
}: {
parentId: string
box: ViewBox | null
}) {
const t = useT()
const preview = useEditorStore((s) => s.preview)
const handleVersion = useEditorStore((s) => s.handleVersion)
const host = useRef<HTMLDivElement | null>(null)
const [frame, setFrame] = useState<Frame | 'failed' | null>(null)
useEffect(() => {
const element = host.current
if (!element || !preview) return
const built = buildView(preview, parentId)
element.replaceChildren(...(built.ok ? [built.svg] : []))
setFrame(
built.ok
? {
viewBox: built.svg.getAttribute('viewBox') ?? '0 0 100 100',
ratio:
built.svg.getAttribute('preserveAspectRatio') ?? 'xMidYMid meet',
}
: 'failed',
)
}, [preview, parentId, handleVersion])
return (
<div className="space-y-2">
<div
role="img"
aria-label={t('editor.views.crop.canvas')}
className="relative aspect-[4/3] w-full overflow-hidden rounded-lg border border-[var(--color-border)] bg-white"
>
<div
ref={host}
data-testid="crop-canvas-drawing"
className="h-full w-full [&>svg]:block [&>svg]:h-full [&>svg]:w-full"
/>
{frame !== null && frame !== 'failed' && box !== null && (
<svg
aria-hidden="true"
data-testid="crop-overlay"
viewBox={frame.viewBox}
preserveAspectRatio={frame.ratio}
className="pointer-events-none absolute inset-0 h-full w-full"
>
<rect
x={box.min_x}
y={box.min_y}
width={Math.max(box.width, 0)}
height={Math.max(box.height, 0)}
fill="none"
stroke="var(--color-accent)"
strokeWidth={2}
strokeDasharray="6 4"
vectorEffect="non-scaling-stroke"
/>
</svg>
)}
</div>
{frame === 'failed' && (
<Notice tone="error">{t('editor.views.crop.canvas_failed')}</Notice>
)}
</div>
)
}
@@ -0,0 +1,160 @@
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 { useT } from '@/i18n/useT'
import CropCanvas from './CropCanvas'
/**
* The four `view_box` fields as ONE group: leaving the group or Enter proposes all four
* together (a frame change under the geometry check). A refused group stays shown,
* 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} />
}
type Gate = { state: 'applied' } | { state: 'refused' }
function EditableCrop({
viewId,
parentId,
box,
}: {
viewId: string
parentId: string
box: ViewBox | null
}) {
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()
}
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)
}
}}
>
<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} />
</div>
)
}
@@ -0,0 +1,108 @@
import { useState } from 'react'
import type { SheetView } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import DraftField from '@/components/editor/fields/DraftField'
import FormField from '@/components/ui/FormField'
import Select from '@/components/ui/Select'
import { isBlank } from '@/editor/sheetDocument'
import { useEditCommand } from '@/editor/useEditCommand'
import { BOX_KEYS, fieldsOf, parseBox, type BoxFields } from '@/editor/viewBox'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
const EMPTY = { fr: '', en: '', parent: '', ...fieldsOf(null) }
/**
* Adds a detail view: names, parent, and the crop values when it is a crop (all four, or
* none for a view that will carry its own drawing, chosen once it exists).
*/
export default function DetailViewForm({
views,
}: {
views: readonly SheetView[]
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const edit = useEditCommand()
const [form, setForm] = useState(EMPTY)
const set = (patch: Partial<typeof EMPTY>) => setForm({ ...form, ...patch })
const parent =
form.parent || views.find((view) => view.kind === 'main')?.id || ''
const create = () => {
const box = parseBox(form as BoxFields)
if (isBlank(form.fr) || isBlank(form.en) || parent === '') {
return edit.reject('form', 'editor.views.required')
}
if (!box.ok) return edit.reject('form', `editor.views.crop.${box.reason}`)
const added = edit.runNew('form', 'view', (id) => ({
op: 'insert',
element: {
kind: 'view',
value: {
kind: 'detail',
id,
name: { fr: form.fr, en: form.en },
svg_asset_id: null,
view_box: box.box,
parent_view_id: parent,
},
},
}))
if (added) setForm(EMPTY)
return added
}
return (
<div className="space-y-2 rounded-lg border border-dashed border-[var(--color-border)] p-3">
<p className="text-sm font-medium">{t('editor.views.new')}</p>
<div className="grid gap-3 md:grid-cols-3">
<DraftField
id="view-new-fr"
label={t('editor.views.name_fr')}
value={form.fr}
onChange={(fr) => set({ fr })}
/>
<DraftField
id="view-new-en"
label={t('editor.views.name_en')}
value={form.en}
onChange={(en) => set({ en })}
/>
<FormField id="view-new-parent" label={t('editor.views.parent')}>
<Select
id="view-new-parent"
value={parent}
onChange={(e) => set({ parent: e.target.value })}
>
{views.map((view) => (
<option key={view.id} value={view.id}>
{view.name[locale]}
</option>
))}
</Select>
</FormField>
</div>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('editor.views.new_hint')}
</p>
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
{BOX_KEYS.map((key) => (
<DraftField
key={key}
id={`view-new-crop-${key}`}
label={t(`editor.views.crop.${key}`)}
value={form[key]}
onChange={(value) => set({ [key]: value })}
/>
))}
</div>
{edit.fieldError('form') && (
<p role="alert" className="text-sm text-[var(--color-danger-strong)]">
{edit.fieldError('form')}
</p>
)}
<ActionButton readOnly={false} variant="secondary" onClick={create}>
{t('editor.views.add')}
</ActionButton>
</div>
)
}
@@ -0,0 +1,90 @@
import type { DetailView, SheetView } from '@faunosteo/core-wasm/types'
import ActionButton from '@/components/editor/fields/ActionButton'
import SelectField from '@/components/editor/fields/SelectField'
import { useViewUpdate } from '@/editor/useViewUpdate'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import CropEditor from './CropEditor'
import ViewDrawing from './ViewDrawing'
import ViewNames from './ViewNames'
/** One detail view: names, parent, own drawing, crop (one crop canvas open at a time). */
export default function DetailViewRow({
view,
views,
readOnly,
cropOpen,
onToggleCrop,
onDelete,
}: {
view: DetailView
views: readonly SheetView[]
readOnly: boolean
cropOpen: boolean
onToggleCrop: () => void
onDelete: () => void
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const edit = useViewUpdate()
const parents = views
.filter((candidate) => candidate.id !== view.id)
.map((candidate) => ({
value: candidate.id,
label: candidate.name[locale],
}))
return (
<li
aria-label={view.name[locale]}
className="space-y-3 rounded-lg border border-[var(--color-border)] p-3"
>
<div className="grid gap-3 md:grid-cols-3">
<ViewNames view={view} readOnly={readOnly} views={edit} />
<SelectField
id={`view-${view.id}-parent`}
label={t('editor.views.parent')}
value={view.parent_view_id}
options={parents}
onCommit={(parent) =>
edit.update('parent', view.id, { parent_view_id: parent }, true)
}
readOnly={readOnly}
error={edit.error('parent')}
/>
</div>
<ViewDrawing view={view} readOnly={readOnly} />
<div className="space-y-2">
<div className="flex items-center justify-between gap-2">
<p className="text-sm font-medium">{t('editor.views.crop.title')}</p>
<ActionButton
readOnly={readOnly}
variant="secondary"
size="sm"
aria-expanded={cropOpen}
onClick={onToggleCrop}
>
{t('editor.views.crop.toggle')}
</ActionButton>
</div>
{(readOnly || cropOpen) && (
<CropEditor
viewId={view.id}
parentId={view.parent_view_id}
box={view.view_box}
readOnly={readOnly}
/>
)}
</div>
<div className="flex justify-end">
<ActionButton
readOnly={readOnly}
variant="danger"
size="sm"
onClick={onDelete}
>
{t('editor.action.delete')}
</ActionButton>
</div>
</li>
)
}
@@ -0,0 +1,31 @@
import type { MainView } from '@faunosteo/core-wasm/types'
import { useViewUpdate } from '@/editor/useViewUpdate'
import { useT } from '@/i18n/useT'
import ViewDrawing from './ViewDrawing'
import ViewNames from './ViewNames'
/** The main view: its names and its drawing (state, detail, « Choisir une illustration »). */
export default function MainViewCard({
view,
readOnly,
}: {
view: MainView
readOnly: boolean
}) {
const t = useT()
const views = useViewUpdate()
return (
<section
aria-labelledby="views-main-title"
className="space-y-3 rounded-lg border border-[var(--color-border)] p-3"
>
<h3 id="views-main-title" className="text-base font-semibold">
{t('editor.views.main_title')}
</h3>
<div className="grid gap-3 md:grid-cols-2">
<ViewNames view={view} readOnly={readOnly} views={views} />
</div>
<ViewDrawing view={view} readOnly={readOnly} />
</section>
)
}
@@ -0,0 +1,140 @@
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 { unmeasuredViews } from '@/editor/issues'
import { useDrawingUpload } from '@/editor/useDrawingUpload'
import { uploadErrorMessage } from '@/editor/uploadMessages'
import { useSheetDocument } from '@/editor/sheetDocument'
import { useEditorStore } from '@/editor/state/editorStore'
import { useViewUpdate } from '@/editor/useViewUpdate'
import { useT } from '@/i18n/useT'
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.
*/
export default function ViewDrawing({
view,
readOnly,
}: {
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`}>
<p className="text-sm font-medium">{t('editor.views.drawing')}</p>
<p className="text-sm text-[var(--color-ink-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>
)}
{unmeasured && (
<p className="text-sm text-[var(--color-ink-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>
{view.kind === 'detail' && ownDrawing && (
<ActionButton
readOnly={false}
variant="ghost"
size="sm"
onClick={() =>
views.update('drawing', view.id, { svg_asset_id: null }, true)
}
>
{t('editor.views.drawing.use_parent')}
</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>}
{views.error('drawing') && (
<Notice tone="error">{views.error('drawing')}</Notice>
)}
<CleaningDialog
candidate={upload.ui.phase === 'cleaning' ? upload.ui.candidate : null}
onConfirm={() => void upload.confirmCleaning()}
onCancel={upload.cancelCleaning}
/>
</>
)
}
@@ -0,0 +1,43 @@
import type { SheetView } from '@faunosteo/core-wasm/types'
import TextField from '@/components/editor/fields/TextField'
import { isBlank } from '@/editor/sheetDocument'
import type { ViewUpdateApi } from '@/editor/useViewUpdate'
import type { Locale } from '@/i18n/types'
import { useT } from '@/i18n/useT'
/** The two names of a view (required); each commits on blur or Enter. */
export default function ViewNames({
view,
readOnly,
views,
}: {
view: SheetView
readOnly: boolean
views: ViewUpdateApi
}) {
const t = useT()
const rename = (locale: Locale) => (value: string) =>
isBlank(value)
? views.reject(locale, 'editor.field.required')
: views.update(
locale,
view.id,
{ name: { ...view.name, [locale]: value } },
false,
)
return (
<>
{(['fr', 'en'] as const).map((locale) => (
<TextField
key={locale}
id={`view-${view.id}-name-${locale}`}
label={t(`editor.views.name_${locale}`)}
value={view.name[locale]}
onCommit={rename(locale)}
readOnly={readOnly}
error={views.error(locale)}
/>
))}
</>
)
}
+36
View File
@@ -0,0 +1,36 @@
import type { PreviewState, SheetView } from '@faunosteo/core-wasm/types'
import type { CatalogueFailure } from '@/catalogue/failure'
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: 'failed'; failure: CatalogueFailure }
export function drawingStatusOf(
view: SheetView,
state: PreviewState,
failures: Readonly<Record<string, CatalogueFailure>>,
): DrawingStatus {
const assetId = view.svg_asset_id
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 }
const failure = failures[assetId]
return failure
? { kind: 'failed', failure }
: { kind: 'missing', detail: null }
}
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)}`
}
+185
View File
@@ -0,0 +1,185 @@
import {
SheetFailure,
classifySheetError,
confirmSheetAssetUpload,
listSheetAssets,
registerSheetAsset,
uploadSheetDrawing,
type FaunosteoClient,
type SheetFailureKind,
} from '@faunosteo/supabase'
import type { SvgCleaning } from '@faunosteo/core-wasm/types'
import { fetchDrawing } from '@/catalogue/catalogue'
import type { CatalogueFailure } from '@/catalogue/failure'
import { getSupabaseClient } from '@/lib/supabase'
import { cleanSvg } from './core/cleaning'
import type { GeometryRefusal } from './issues'
import { useEditorStore } from './state/editorStore'
import { updateView } from './viewUpdate'
/** The size the upload path accepts (plan « Upload »); the core caps the rest. */
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: 'caps' | 'core' | 'blocked' | 'stale' }
| { code: 'svg_rejected'; reason: string }
| { code: 'sheet'; kind: SheetFailureKind }
| { code: 'catalogue'; failure: CatalogueFailure }
| { code: 'frame'; refusal: GeometryRefusal }
export type Step<T> = { ok: true; value: T } | { ok: false; error: UploadError }
const fail = (error: UploadError): { ok: false; error: UploadError } => ({
ok: false,
error,
})
const done = <T>(value: T): { ok: true; value: T } => ({ ok: true, value })
/** A file the core read: the text it stores, its hash and what it would remove. */
export interface Candidate {
fileName: string
outcome: 'clean' | 'cleanable'
stored: string
sha256: string
byteSize: number
removed: string[]
active: string[]
styleRemoved: boolean
}
function rejection(cleaning: SvgCleaning): UploadError {
if (cleaning.reason === 'too_large') return { code: 'too_large' }
if (cleaning.reason === 'svg_active_content')
return { code: 'svg_active_content' }
return { code: 'svg_rejected', reason: cleaning.reason ?? 'malformed' }
}
function candidateOf(fileName: string, cleaning: SvgCleaning): Step<Candidate> {
const { stored, sha256, byte_size: byteSize, outcome } = cleaning
if (outcome === 'rejected' || !stored || !sha256 || byteSize === null) {
return fail(rejection(cleaning))
}
return done({
fileName,
outcome,
stored,
sha256,
byteSize,
removed: cleaning.removed,
active: cleaning.active,
styleRemoved: cleaning.style_removed,
})
}
/** Size check before reading, then the core's `clean_svg` on the bytes. */
export async function checkFile(file: File): Promise<Step<Candidate>> {
if (file.size > MAX_DRAWING_BYTES) return fail({ code: 'too_large' })
const cleaned = cleanSvg(new Uint8Array(await file.arrayBuffer()))
return cleaned.ok
? candidateOf(file.name, cleaned.value)
: fail({ code: 'core' })
}
/** A pending row of another account: its object may already be there, so confirm once. */
async function confirmAfterRefusal(client: FaunosteoClient, assetId: string) {
try {
await confirmSheetAssetUpload(client, assetId)
} catch (error) {
if (classifySheetError(error) === 'upload_missing') {
throw new SheetFailure('upload.pending_other', error)
}
throw error
}
}
async function sendAndConfirm(
client: FaunosteoClient,
assetId: string,
drawing: Candidate,
): Promise<void> {
const bytes = new TextEncoder().encode(drawing.stored)
try {
await uploadSheetDrawing(client, drawing.sha256, bytes)
} catch (error) {
if (classifySheetError(error) !== 'upload.pending_other') throw error
return confirmAfterRefusal(client, assetId)
}
await confirmSheetAssetUpload(client, assetId)
}
/**
* Register, read the row back, upload when the row is still pending, confirm. A confirmed
* row (`uploaded_at` set) is neither uploaded nor confirmed again: the Storage policy
* would refuse the re-upload.
*/
export async function registerAndUpload(
sheetId: string,
drawing: Candidate,
): Promise<Step<string>> {
const client = getSupabaseClient()
if (!client) return fail({ code: 'sheet', kind: 'unavailable' })
try {
const assetId = await registerSheetAsset(client, {
sheet_id: sheetId,
sha256: drawing.sha256,
byte_size: drawing.byteSize,
file_name: drawing.fileName,
})
const rows = await listSheetAssets(client, sheetId)
const confirmed = rows.find((row) => row.id === assetId)?.uploaded_at
if (!confirmed) await sendAndConfirm(client, assetId, drawing)
return done(assetId)
} catch (error) {
return fail({ code: 'sheet', kind: classifySheetError(error) })
}
}
/** The stored object is downloaded (its hash checked by the core) and held by the handle. */
export async function downloadAndHold(
assetId: string,
sha256: string,
): Promise<Step<null>> {
const client = getSupabaseClient()
if (!client) return fail({ code: 'sheet', kind: 'unavailable' })
const fetched = await fetchDrawing(client, { asset_id: assetId, sha256 })
if (!fetched.ok) return fail({ code: 'catalogue', failure: fetched.failure })
const held = useEditorStore.getState().addDrawing(fetched.drawing)
if (held.ok) return done(null)
if (held.reason !== 'core') return fail({ code: 'blocked' })
if (held.failure.kind === 'drawing_hash_mismatch') {
return fail({ code: 'object_conflict' })
}
return fail({ code: held.failure.kind === 'caps' ? 'caps' : 'core' })
}
/** 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 })
}
return fail({ code: outcome.reason === 'blocked' ? 'blocked' : 'core' })
}
/**
* Register, upload, confirm, hold, attach. Every continuation checks the session token:
* a closed or reopened editor drops the rest (`stale`). A refusal at the last step leaves
* the drawing uploaded and held; the view keeps its previous drawing.
*/
export async function uploadDrawing(
drawing: Candidate,
viewId: string,
): Promise<Step<null>> {
const { session, sheetId } = useEditorStore.getState()
const live = () => useEditorStore.getState().session === session
if (!sheetId) return fail({ code: 'blocked' })
const stored = await registerAndUpload(sheetId, drawing)
if (!live()) return fail({ code: 'stale' })
if (!stored.ok) return stored
const held = await downloadAndHold(stored.value, drawing.sha256)
if (!live()) return fail({ code: 'stale' })
return held.ok ? attachToView(viewId, stored.value) : held
}
+32
View File
@@ -0,0 +1,32 @@
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import type { Locale } from '@/i18n/types'
import { elementLabel } from './sheetDocument'
import type { GeometryRefusal } from './issues'
type Translate = (key: string) => string
/**
* The words for a frame change the geometry check refused: the annotations (or views)
* the change would break, by name. Nothing here re-judges the geometry.
*/
export function frameRefusalMessage(
t: Translate,
refusal: GeometryRefusal,
doc: AnatomicalSheetDocument | null,
locale: Locale,
): string {
const named = (kind: 'annotation' | 'view', ids: readonly string[]) =>
ids
.map((id) => (doc ? elementLabel(doc, { kind, id }, locale) : id))
.join(', ')
if (refusal.reason === 'view_unmeasured') {
return t('editor.views.frame.view_unmeasured').replace(
'{names}',
named('view', refusal.viewIds),
)
}
return t('editor.views.frame.newly_invalid').replace(
'{names}',
named('annotation', refusal.annotationIds),
)
}
+64
View File
@@ -0,0 +1,64 @@
import type { AnatomicalSheetDocument } from '@faunosteo/core-wasm/types'
import { failureMessage } from '@/admin/labels'
import type { Locale } from '@/i18n/types'
import { frameRefusalMessage } from './frameRefusal'
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',
'upload_missing',
'upload.pending_other',
])
/** The words for an upload that stopped; `null` for a dropped (stale) continuation. */
export function uploadErrorMessage(
t: Translate,
error: UploadError,
context: { doc: AnatomicalSheetDocument | null; locale: Locale },
): string | null {
switch (error.code) {
case 'stale':
return null
case 'svg_rejected': {
const reason = READER_REASONS.has(error.reason) ? error.reason : 'other'
return t('editor.upload.err.svg_rejected').replace(
'{reason}',
t(`editor.upload.reason.${reason}`),
)
}
case 'sheet':
return UPLOAD_KINDS.has(error.kind)
? t(`editor.upload.err.${error.kind}`)
: failureMessage(t, error.kind)
case 'catalogue':
return loadFailureMessage(t, error.failure)
case 'frame': {
const { doc, locale } = context
const refused = frameRefusalMessage(t, error.refusal, doc, locale)
return `${refused} ${t('editor.views.frame.kept')}`
}
case 'blocked':
return t('editor.refusal.blocked')
default:
return t(`editor.upload.err.${error.code}`)
}
}
+53
View File
@@ -0,0 +1,53 @@
import { useState } from 'react'
import {
checkFile,
uploadDrawing,
type Candidate,
type Step,
type UploadError,
} from './drawingUpload'
export type UploadUi =
| { phase: 'idle' }
| { phase: 'working' }
| { phase: 'cleaning'; candidate: Candidate }
| { phase: 'failed'; error: UploadError }
| { phase: 'done' }
export interface DrawingUpload {
ui: UploadUi
/** A picked file: checked, then sent (clean) or offered for cleaning (cleanable). */
start: (file: File) => Promise<void>
/** « Nettoyer et utiliser cette version ». */
confirmCleaning: () => Promise<void>
cancelCleaning: () => void
}
/** The upload of one view's drawing as a small state machine for its section. */
export function useDrawingUpload(viewId: string): DrawingUpload {
const [ui, setUi] = useState<UploadUi>({ phase: 'idle' })
const settle = (result: Step<unknown>) => {
if (result.ok) setUi({ phase: 'done' })
else if (result.error.code === 'stale') setUi({ phase: 'idle' })
else setUi({ phase: 'failed', error: result.error })
}
const send = async (candidate: Candidate) => {
setUi({ phase: 'working' })
settle(await uploadDrawing(candidate, viewId))
}
const start = async (file: File) => {
setUi({ phase: 'working' })
const checked = await checkFile(file)
if (!checked.ok) return settle(checked)
if (checked.value.outcome === 'clean') return send(checked.value)
setUi({ phase: 'cleaning', candidate: checked.value })
}
return {
ui,
start,
confirmCleaning: async () => {
if (ui.phase === 'cleaning') await send(ui.candidate)
},
cancelCleaning: () => setUi({ phase: 'idle' }),
}
}
+54
View File
@@ -0,0 +1,54 @@
import { useState } from 'react'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import { frameRefusalMessage } from './frameRefusal'
import { refusalMessage } from './refusal'
import { useSheetDocument } from './sheetDocument'
import { updateView, type ViewPatch } from './viewUpdate'
export interface ViewUpdateApi {
/** The refusal phrased for `field`, to show next to its control. */
error: (field: string) => string | undefined
/** One view `update`; `guarded` = a frame change under the geometry check. */
update: (
field: string,
viewId: string,
patch: ViewPatch,
guarded: boolean,
) => boolean
/** A refusal that never reached the core (a required field left blank). */
reject: (field: string, messageKey: string) => false
clear: () => void
}
/** The write path of the views panel: commit once, keep the refusal next to the control. */
export function useViewUpdate(): ViewUpdateApi {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const doc = useSheetDocument()
const [failure, setFailure] = useState<{
field: string
message: string
} | null>(null)
return {
error: (field) => (failure?.field === field ? failure.message : undefined),
update: (field, viewId, patch, guarded) => {
const outcome = updateView(viewId, patch, guarded)
if (outcome.ok) {
setFailure(null)
return true
}
const message =
outcome.reason === 'refused'
? frameRefusalMessage(t, outcome.refusal, doc, locale)
: refusalMessage(t, outcome)
setFailure({ field, message })
return false
},
reject: (field, messageKey) => {
setFailure({ field, message: t(messageKey) })
return false
},
clear: () => setFailure(null),
}
}
+46
View File
@@ -0,0 +1,46 @@
import type { ViewBox } from '@faunosteo/core-wasm/types'
/** The four crop fields as typed: numbers stay text until the group is applied. */
export interface BoxFields {
min_x: string
min_y: string
width: string
height: string
}
export const BOX_KEYS = ['min_x', 'min_y', 'width', 'height'] as const
export type BoxParse =
| { ok: true; box: ViewBox | null }
| { ok: false; reason: 'incomplete' | 'number' }
/** The stored numbers exactly as JSON prints them (no display rounding). */
export function fieldsOf(box: ViewBox | null): BoxFields {
return {
min_x: box === null ? '' : String(box.min_x),
min_y: box === null ? '' : String(box.min_y),
width: box === null ? '' : String(box.width),
height: box === null ? '' : String(box.height),
}
}
/**
* Input shape only: four numbers, or four blanks for "no crop". Whether the rectangle is
* acceptable (size, frame, annotations) is the core's answer.
*/
export function parseBox(fields: BoxFields): BoxParse {
const texts = BOX_KEYS.map((key) => fields[key].trim())
if (texts.every((text) => text === '')) return { ok: true, box: null }
if (texts.some((text) => text === ''))
return { ok: false, reason: 'incomplete' }
const [min_x, min_y, width, height] = texts.map(Number)
if (![min_x, min_y, width, height].every(Number.isFinite)) {
return { ok: false, reason: 'number' }
}
return { ok: true, box: { min_x, min_y, width, height } }
}
export function sameBox(a: ViewBox | null, b: ViewBox | null): boolean {
if (a === null || b === null) return a === b
return BOX_KEYS.every((key) => a[key] === b[key])
}
+38
View File
@@ -0,0 +1,38 @@
import type { DetailView, SheetView } from '@faunosteo/core-wasm/types'
import { geometryAccept, type GeometryRefusal } from './issues'
import { useEditorStore } from './state/editorStore'
import type { CommitOutcome } from './state/editorTypes'
export type ViewPatch = Partial<
Pick<DetailView, 'name' | 'svg_asset_id' | 'view_box' | 'parent_view_id'>
>
/**
* 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.
*/
export function updateView(
viewId: string,
patch: ViewPatch,
guarded: boolean,
): CommitOutcome<GeometryRefusal> {
const store = useEditorStore.getState()
const before = store.previewState
const view = before?.document.views.find(
(candidate) => candidate.id === viewId,
)
if (!before || !view)
return { ok: false, reason: 'blocked', kind: 'not_ready' }
const value = { ...view, ...patch } as SheetView
return store.commit(
{
op: 'update',
key: { kind: 'view', id: viewId },
element: { kind: 'view', value },
},
guarded
? { accept: geometryAccept({ before, changedIds: [] }) }
: undefined,
)
}
+70
View File
@@ -1335,4 +1335,74 @@ export const en: Dict = {
'editor.vertebra.new': 'New vertebral region',
'editor.vertebra.add': 'Add the region',
'editor.vertebra.required': 'Fill in the code and the French and English names.',
'editor.views.main_title': 'Main view',
'editor.views.details_title': 'Detail views',
'editor.views.empty': 'No detail view yet.',
'editor.views.name_fr': 'View name (FR)',
'editor.views.name_en': 'View name (EN)',
'editor.views.parent': 'Parent view',
'editor.views.drawing': 'Drawing',
'editor.views.drawing.none': 'No drawing',
'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.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.',
'editor.views.drawing.choose': 'Choose a drawing',
'editor.views.drawing.file': 'Drawing file (SVG)',
'editor.views.drawing.use_parent': "Use the parent view's drawing",
'editor.views.crop.title': 'Crop',
'editor.views.crop.toggle': 'Edit the crop',
'editor.views.crop.min_x': 'Crop: minimum x',
'editor.views.crop.min_y': 'Crop: minimum y',
'editor.views.crop.width': 'Crop: width',
'editor.views.crop.height': 'Crop: height',
'editor.views.crop.hint': "Rectangle in the parent drawing's units. Four values, or none for no crop. They apply together.",
'editor.views.crop.incomplete': 'Fill in all four crop values, or none.',
'editor.views.crop.number': 'The crop values are numbers.',
'editor.views.crop.not_applied': 'Not applied',
'editor.views.crop.revert': 'Revert to the saved values',
'editor.views.crop.canvas': 'Parent view with the crop rectangle',
'editor.views.crop.canvas_failed': 'The parent view cannot be displayed.',
'editor.views.new': 'New detail view',
'editor.views.new_hint': 'Fill in the crop for a cropped view; leave it empty for a view that will have its own drawing (chosen once the view is added).',
'editor.views.add': 'Add the view',
'editor.views.required': 'Fill in the French and English names of the view.',
'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.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.',
'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.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.',
'editor.upload.err.object_conflict': 'A different file already exists under this hash: the drawing is refused.',
'editor.upload.err.caps': 'Too many drawings in this editing session (16 at most). Save, then reload the draft.',
'editor.upload.err.core': 'The document check refused this drawing.',
'editor.upload.reason.malformed': 'malformed file',
'editor.upload.reason.doctype': 'DOCTYPE declaration not allowed',
'editor.upload.reason.not_svg': 'not an SVG',
'editor.upload.reason.too_many_elements': 'too many elements',
'editor.upload.reason.too_deep': 'nesting too deep',
'editor.upload.reason.too_many_uses': 'too many reuses (use)',
'editor.upload.reason.too_complex': 'drawing too complex',
'editor.upload.reason.reference_cycle': 'circular references',
'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.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.',
'editor.cleaning.preview': 'Preview of the cleaned drawing',
'editor.cleaning.preview_failed': 'The preview of the cleaned drawing cannot be composed.',
'editor.cleaning.removed': 'Removed elements:',
'editor.cleaning.active': 'Active or external content removed:',
'editor.cleaning.style': 'The <style> element was removed: the classes it defined will show unstyled.',
'editor.cleaning.confirm': 'Clean and use this version',
'editor.cleaning.cancel': 'Cancel',
}
+70
View File
@@ -1366,4 +1366,74 @@ export const fr: Dict = {
'editor.vertebra.new': 'Nouvelle région vertébrale',
'editor.vertebra.add': 'Ajouter la région',
'editor.vertebra.required': 'Renseignez le code et les noms français et anglais.',
'editor.views.main_title': 'Vue principale',
'editor.views.details_title': 'Vues de détail',
'editor.views.empty': "Aucune vue de détail pour l'instant.",
'editor.views.name_fr': 'Nom de la vue (FR)',
'editor.views.name_en': 'Nom de la vue (EN)',
'editor.views.parent': 'Vue parente',
'editor.views.drawing': 'Illustration',
'editor.views.drawing.none': 'Aucune illustration',
'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.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.",
'editor.views.drawing.choose': 'Choisir une illustration',
'editor.views.drawing.file': "Fichier d'illustration (SVG)",
'editor.views.drawing.use_parent': "Utiliser l'illustration de la vue parente",
'editor.views.crop.title': 'Recadrage',
'editor.views.crop.toggle': 'Modifier le recadrage',
'editor.views.crop.min_x': 'Recadrage : x minimum',
'editor.views.crop.min_y': 'Recadrage : y minimum',
'editor.views.crop.width': 'Recadrage : largeur',
'editor.views.crop.height': 'Recadrage : hauteur',
'editor.views.crop.hint': "Rectangle en unités du dessin parent. Quatre valeurs, ou aucune pour ne pas recadrer. Elles s'appliquent ensemble.",
'editor.views.crop.incomplete': 'Indiquez les quatre valeurs du recadrage, ou aucune.',
'editor.views.crop.number': 'Les valeurs du recadrage sont des nombres.',
'editor.views.crop.not_applied': 'Non appliqué',
'editor.views.crop.revert': 'Revenir aux valeurs enregistrées',
'editor.views.crop.canvas': 'Vue parente avec le rectangle de recadrage',
'editor.views.crop.canvas_failed': 'La vue parente ne peut pas être affichée.',
'editor.views.new': 'Nouvelle vue de détail',
'editor.views.new_hint': 'Saisissez le recadrage pour une vue recadrée ; laissez-le vide pour une vue qui aura sa propre illustration (à choisir une fois la vue ajoutée).',
'editor.views.add': 'Ajouter la vue',
'editor.views.required': 'Renseignez les noms français et anglais de la vue.',
'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.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.',
'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.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.",
'editor.upload.err.object_conflict': "Un fichier différent existe déjà sous cette empreinte : l'illustration est refusée.",
'editor.upload.err.caps': "Trop d'illustrations dans cette session d'édition (16 au plus). Enregistrez, puis rechargez le brouillon.",
'editor.upload.err.core': 'Le contrôle du document a refusé cette illustration.',
'editor.upload.reason.malformed': 'fichier mal formé',
'editor.upload.reason.doctype': 'déclaration DOCTYPE interdite',
'editor.upload.reason.not_svg': "ce n'est pas un SVG",
'editor.upload.reason.too_many_elements': "trop d'éléments",
'editor.upload.reason.too_deep': 'imbrication trop profonde',
'editor.upload.reason.too_many_uses': 'trop de réutilisations (use)',
'editor.upload.reason.too_complex': 'dessin trop complexe',
'editor.upload.reason.reference_cycle': 'références circulaires',
'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.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é.",
'editor.cleaning.preview': 'Aperçu du dessin nettoyé',
'editor.cleaning.preview_failed': "L'aperçu du dessin nettoyé ne peut pas être composé.",
'editor.cleaning.removed': 'Éléments retirés :',
'editor.cleaning.active': 'Contenu actif ou externe retiré :',
'editor.cleaning.style': "L'élément <style> a été retiré : les classes qu'il définissait s'afficheront sans style.",
'editor.cleaning.confirm': 'Nettoyer et utiliser cette version',
'editor.cleaning.cancel': 'Annuler',
}
@@ -0,0 +1,268 @@
/** Lot G: the upload flow of a drawing (check, clean, register, upload, confirm, attach). */
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 { 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 { useLocaleStore } from '@/state/localeStore'
import { ASSET } from '../helpers/editorFixtures'
import { openReady, resetStore, sb, store } from '../helpers/editorHarness'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
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 doc = (): AnatomicalSheetDocument =>
JSON.parse(store.getState().documentText)
const mainAsset = () => doc().views[0].svg_asset_id
const svg = (viewBox: string, inner = '<rect width="4" height="4"/>') =>
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}">${inner}</svg>`
/** The stored form the core would keep for a file, as the server would serve it. */
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, uploadedAt: string | null = null) {
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: uploadedAt,
},
])
sb.uploadSheetDrawing.mockResolvedValue('uploaded')
sb.confirmSheetAssetUpload.mockResolvedValue(NEW_ASSET)
const fresh = (hash: string) =>
hash === stored.sha256 ? stored.bytes : undefined
sb.downloadSheetDrawing.mockImplementation(
async (_c, hash) => fresh(hash) ?? (await baseBytes()),
)
return stored
}
async function baseBytes() {
const { svgBytes } = await import('../helpers/editorFixtures')
return svgBytes().bytes
}
async function pick(text: string, name = 'dessin.svg') {
const user = userEvent.setup()
const input = screen.getByTestId('view-view-main-file') as HTMLInputElement
await user.upload(input, new File([text], name, { type: 'image/svg+xml' }))
return user
}
beforeEach(async () => {
useLocaleStore.setState({ locale: 'fr' })
await openReady()
render(<ViewsTab {...props} />)
})
afterEach(() => {
cleanup()
resetStore()
})
describe('drawing upload flow', () => {
it('a clean file goes register, upload, confirm, hold, attach with no dialog', async () => {
const stored = serverGets(svg('0 0 200 100'))
await pick(svg('0 0 200 100'))
await waitFor(() => expect(mainAsset()).toBe(NEW_ASSET))
expect(screen.queryByRole('dialog')).toBeNull()
expect(sb.registerSheetAsset).toHaveBeenCalledWith(
{},
{
sheet_id: 'sheet-1',
sha256: stored.sha256,
byte_size: stored.byte_size,
file_name: 'dessin.svg',
},
)
expect(sb.uploadSheetDrawing).toHaveBeenCalledWith(
{},
stored.sha256,
stored.bytes,
)
expect(sb.confirmSheetAssetUpload).toHaveBeenCalledWith({}, NEW_ASSET)
expect(store.getState().drawings.map((d) => d.asset_id)).toContain(
NEW_ASSET,
)
expect(
await screen.findByText("L'illustration est ajoutée à la vue."),
).toBeTruthy()
})
it('a cleanable file shows the dialog with the core-composed drawing, then uploads on accept', async () => {
const dirty = svg(
'0 0 200 100',
'<style>.a{fill:red}</style><rect class="a" width="4" height="4"/>',
)
serverGets(dirty)
await pick(dirty)
const dialog = await screen.findByRole('dialog')
expect(sb.registerSheetAsset).not.toHaveBeenCalled()
expect(
within(dialog).getByText(/L'élément <style> a été retiré/),
).toBeTruthy()
expect(within(dialog).getByText('style')).toBeTruthy()
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 waitFor(() => expect(mainAsset()).toBe(NEW_ASSET))
expect(sb.uploadSheetDrawing).toHaveBeenCalledTimes(1)
})
it('cancelling the cleaning dialog sends nothing', async () => {
const dirty = svg(
'0 0 200 100',
'<style>.a{fill:red}</style><rect class="a" width="4" height="4"/>',
)
serverGets(dirty)
const user = await pick(dirty)
const dialog = await screen.findByRole('dialog')
await user.click(within(dialog).getByRole('button', { name: 'Annuler' }))
expect(sb.registerSheetAsset).not.toHaveBeenCalled()
expect(mainAsset()).toBe(ASSET)
})
it('a rejected file shows its reason and nothing else happens', async () => {
await pick(
'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>',
)
expect(await screen.findByText(/contenu actif ou externe/)).toBeTruthy()
await pick('pas un svg')
expect(
await screen.findByText(/n'est pas un dessin SVG utilisable/),
).toBeTruthy()
expect(sb.registerSheetAsset).not.toHaveBeenCalled()
expect(screen.queryByRole('dialog')).toBeNull()
})
it('a file over 2 MiB is refused before it is read', async () => {
const user = userEvent.setup()
const big = new File([new Uint8Array(MAX_DRAWING_BYTES + 1)], 'big.svg', {
type: 'image/svg+xml',
})
await user.upload(
screen.getByTestId('view-view-main-file') as HTMLInputElement,
big,
)
expect(await screen.findByText('Ce fichier dépasse 2 Mio.')).toBeTruthy()
expect(sb.registerSheetAsset).not.toHaveBeenCalled()
})
it('an object already present is confirmed without a second upload', async () => {
serverGets(svg('0 0 200 100'))
sb.uploadSheetDrawing.mockResolvedValue('present')
await pick(svg('0 0 200 100'))
await waitFor(() => expect(mainAsset()).toBe(NEW_ASSET))
expect(sb.confirmSheetAssetUpload).toHaveBeenCalledTimes(1)
})
it('a confirmed row is neither uploaded nor confirmed again', async () => {
serverGets(svg('0 0 200 100'), '2026-11-04T10:00:00Z')
await pick(svg('0 0 200 100'))
await waitFor(() => expect(mainAsset()).toBe(NEW_ASSET))
expect(sb.uploadSheetDrawing).not.toHaveBeenCalled()
expect(sb.confirmSheetAssetUpload).not.toHaveBeenCalled()
})
it('a policy refusal then a confirm that finds the object goes on', async () => {
serverGets(svg('0 0 200 100'))
sb.uploadSheetDrawing.mockRejectedValue(
new SheetFailure('upload.pending_other'),
)
await pick(svg('0 0 200 100'))
await waitFor(() => expect(mainAsset()).toBe(NEW_ASSET))
expect(sb.confirmSheetAssetUpload).toHaveBeenCalledTimes(1)
})
it('a policy refusal then upload_missing is upload.pending_other, view unchanged', async () => {
serverGets(svg('0 0 200 100'))
sb.uploadSheetDrawing.mockRejectedValue(
new SheetFailure('upload.pending_other'),
)
sb.confirmSheetAssetUpload.mockRejectedValue(
new SheetFailure('upload_missing'),
)
await pick(svg('0 0 200 100'))
expect(
await screen.findByText(/en cours d'envoi par un autre compte/),
).toBeTruthy()
expect(mainAsset()).toBe(ASSET)
expect(store.getState().drawings.map((d) => d.asset_id)).not.toContain(
NEW_ASSET,
)
})
it('server kinds are phrased, size_mismatch with its own wording', async () => {
serverGets(svg('0 0 200 100'))
sb.confirmSheetAssetUpload.mockRejectedValue(
new SheetFailure('size_mismatch'),
)
await pick(svg('0 0 200 100'))
expect(
await screen.findByText(/ne correspond pas à celle annoncée/),
).toBeTruthy()
expect(mainAsset()).toBe(ASSET)
})
it('a downloaded object that does not match its hash is an object conflict', async () => {
serverGets(svg('0 0 200 100'))
sb.downloadSheetDrawing.mockResolvedValue(new TextEncoder().encode('autre'))
await pick(svg('0 0 200 100'))
expect(
await screen.findByText(/Un fichier différent existe déjà/),
).toBeTruthy()
expect(mainAsset()).toBe(ASSET)
})
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'))
expect(await screen.findByText(/géométrie de : N\./)).toBeTruthy()
expect(screen.getByText(/L'illustration reste téléversée/)).toBeTruthy()
expect(mainAsset()).toBe(ASSET)
expect(store.getState().drawings.map((d) => d.asset_id)).toContain(
NEW_ASSET,
)
})
})
@@ -0,0 +1,332 @@
/** Lot G: Vues et illustrations (states, detail views, crop group under the frame check). */
import { createHash } from 'node:crypto'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type {
AnatomicalSheetDocument,
NewElement,
} from '@faunosteo/core-wasm/types'
import ViewsTab from '@/components/editor/tabs/ViewsTab'
import { useLocaleStore } from '@/state/localeStore'
import { ASSET, emptyText, insert, point } from '../helpers/editorFixtures'
import {
baseText,
openReady,
resetStore,
sb,
store,
versionAnswer,
} from '../helpers/editorHarness'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
getSheetVersion: vi.fn(),
downloadSheetDrawing: vi.fn(),
saveSheetDraft: vi.fn(),
getOfficialSheetAdmin: vi.fn(),
submitSheetReview: vi.fn(),
}))
const props = { readOnly: false, onSelectTab: vi.fn(), reloadSheet: vi.fn() }
const doc = (): AnatomicalSheetDocument =>
JSON.parse(store.getState().documentText)
const detail = (
viewBox: object | null = { min_x: 0, min_y: 0, width: 100, height: 100 },
) =>
({
kind: 'view',
value: {
kind: 'detail',
id: 'view-d',
name: { fr: 'Détail', en: 'Detail' },
svg_asset_id: null,
view_box: viewBox,
parent_view_id: 'view-main',
},
}) as NewElement
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
})
async function openCrop(text: string) {
await openReady({ text })
const user = userEvent.setup()
render(<ViewsTab {...props} />)
await user.click(
screen.getByRole('button', { name: 'Modifier le recadrage' }),
)
return user
}
const CROP_IDS: Record<string, string> = {
'x minimum': 'min_x',
'y minimum': 'min_y',
largeur: 'width',
hauteur: 'height',
}
const cropField = (name: string) =>
document.getElementById(
`view-view-d-crop-${CROP_IDS[name]}`,
) as HTMLInputElement
describe('Vues et illustrations: drawing states', () => {
it('a valid main drawing shows its state and no hint', async () => {
await openReady()
render(<ViewsTab {...props} />)
expect(screen.getByText('Illustration valide')).toBeTruthy()
expect(
screen.queryByText(/Utilisez « Choisir une illustration »/),
).toBeNull()
})
it('a main view without drawing shows the hint pointing at the button', async () => {
await openReady({ text: emptyText() })
render(<ViewsTab {...props} />)
expect(screen.getByText('Aucune illustration')).toBeTruthy()
expect(
screen.getByText(/Utilisez « Choisir une illustration »/),
).toBeTruthy()
expect(screen.getByText(/n'est pas mesurable/)).toBeTruthy()
expect(
screen.getByRole('button', { name: 'Choisir une illustration' }),
).toBeTruthy()
})
it('a drawing the handle lacks reads as not found', async () => {
store.getState().close()
sb.getSheetVersion.mockResolvedValue(
versionAnswer(baseText(), 3, false) as never,
)
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 introuvable/)).toBeTruthy()
expect(
screen.getByText(/Utilisez « Choisir une illustration »/),
).toBeTruthy()
})
it('a rejected drawing shows the core 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>',
)
const sha256 = createHash('sha256').update(bytes).digest('hex')
store.getState().close()
sb.getSheetVersion.mockResolvedValue({
...versionAnswer(baseText(), 3, false),
drawings: [{ asset_id: ASSET, sha256 }],
} as never)
sb.downloadSheetDrawing.mockResolvedValue(bytes)
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()
})
it('read-only shows states as text and no action', async () => {
await openReady({ text: insert(baseText(), detail()) })
render(<ViewsTab {...props} readOnly />)
expect(screen.getByText('Illustration valide')).toBeTruthy()
expect(screen.queryByRole('button')).toBeNull()
expect(screen.queryByRole('textbox')).toBeNull()
})
})
describe('Vues et illustrations: detail views', () => {
it('adds a detail view with names and a crop, in one insert', async () => {
await openReady()
const user = userEvent.setup()
render(<ViewsTab {...props} />)
await user.click(screen.getByRole('button', { name: 'Ajouter la vue' }))
expect(screen.getByRole('alert')).toHaveTextContent('Renseignez les noms')
await user.type(document.getElementById('view-new-fr')!, 'Tête')
await user.type(document.getElementById('view-new-en')!, 'Head')
await user.type(document.getElementById('view-new-crop-min_x')!, '10')
await user.click(screen.getByRole('button', { name: 'Ajouter la vue' }))
expect(screen.getByRole('alert')).toHaveTextContent('quatre valeurs')
expect(doc().views).toHaveLength(1)
for (const [key, value] of [
['min_y', '20'],
['width', '30'],
['height', '40'],
]) {
await user.type(document.getElementById(`view-new-crop-${key}`)!, value)
}
await user.click(screen.getByRole('button', { name: 'Ajouter la vue' }))
expect(doc().views).toHaveLength(2)
expect(doc().views[1]).toMatchObject({
kind: 'detail',
name: { fr: 'Tête', en: 'Head' },
parent_view_id: 'view-main',
svg_asset_id: null,
view_box: { min_x: 10, min_y: 20, width: 30, height: 40 },
})
expect(doc().views[1].id).toMatch(/^view-[a-z2-7]{10}$/)
})
it('renames on blur and refuses a blank name locally', async () => {
await openReady({ text: insert(baseText(), detail()) })
const user = userEvent.setup()
render(<ViewsTab {...props} />)
const name = document.getElementById('view-view-d-name-en')!
await user.clear(name)
await user.type(name, 'Lower leg')
await user.tab()
expect(doc().views[1].name).toEqual({ fr: 'Détail', en: 'Lower leg' })
await user.clear(document.getElementById('view-view-d-name-fr')!)
await user.tab()
expect(screen.getByText('Ce champ est obligatoire.')).toBeTruthy()
expect(doc().views[1].name.fr).toBe('Détail')
})
it('deleting a view that holds an annotation lists the dependents', async () => {
const text = insert(
insert(baseText(), detail()),
point('anno-d', 50, 50, 5, 'view-d'),
)
await openReady({ text })
const user = userEvent.setup()
render(<ViewsTab {...props} />)
await user.click(screen.getByRole('button', { name: 'Supprimer' }))
const dialog = await screen.findByRole('dialog')
expect(within(dialog).getByText(/ne peut pas être supprimé/)).toBeTruthy()
expect(doc().views).toHaveLength(2)
})
})
describe('Vues et illustrations: crop group under the frame check', () => {
it('refuses a crop that pushes a point out and keeps the typed values', async () => {
const text = insert(
insert(baseText(), detail()),
point('anno-d', 50, 50, 5, 'view-d'),
)
const user = await openCrop(text)
const before = store.getState().documentText
await user.clear(cropField('x minimum'))
await user.type(cropField('x minimum'), '60{Enter}')
const alert = screen.getByRole('alert')
expect(alert).toHaveTextContent('Non appliqué')
expect(alert).toHaveTextContent(/géométrie de : N/)
expect(store.getState().documentText).toBe(before)
expect(store.getState().undo).toHaveLength(0)
expect(cropField('x minimum')).toHaveValue('60')
await user.click(
screen.getByRole('button', { name: 'Revenir aux valeurs enregistrées' }),
)
expect(cropField('x minimum')).toHaveValue('0')
expect(screen.queryByText('Non appliqué')).toBeNull()
})
it('applies the four fields as one group when they fit', async () => {
const text = insert(
insert(baseText(), detail()),
point('anno-d', 50, 50, 5, 'view-d'),
)
const user = await openCrop(text)
await user.clear(cropField('x minimum'))
await user.type(cropField('x minimum'), '20')
await user.clear(cropField('largeur'))
await user.type(cropField('largeur'), '60{Enter}')
expect(doc().views[1]).toMatchObject({
view_box: { min_x: 20, width: 60, height: 100 },
})
expect(screen.queryByText('Non appliqué')).toBeNull()
})
it('accepts a crop change when only an already invalid point is affected', async () => {
const text = insert(
insert(baseText(), detail()),
point('anno-bad', 150, 50, 5, 'view-d'),
)
const user = await openCrop(text)
expect(
store
.getState()
.previewState?.report.issues.some((i) => i.path.endsWith('.geometry')),
).toBe(true)
await user.clear(cropField('largeur'))
await user.type(cropField('largeur'), '90{Enter}')
expect(doc().views[1]).toMatchObject({ view_box: { width: 90 } })
expect(screen.queryByText('Non appliqué')).toBeNull()
})
it('refuses a crop span the core cannot measure while the view holds annotations', async () => {
const text = insert(
insert(baseText(), detail()),
point('anno-d', 50, 50, 5, 'view-d'),
)
const user = await openCrop(text)
await user.clear(cropField('largeur'))
await user.type(cropField('largeur'), '0.5')
await user.clear(cropField('hauteur'))
await user.type(cropField('hauteur'), '0.5{Enter}')
expect(screen.getByRole('alert')).toHaveTextContent('Non appliqué')
expect(screen.getByRole('alert')).toHaveTextContent(
/non mesurable|géométrie de/,
)
expect(doc().views[1]).toMatchObject({ view_box: { width: 100 } })
})
it('a partial group is not applied and says so; an unchanged number commits nothing', async () => {
const user = await openCrop(insert(baseText(), detail()))
await user.clear(cropField('hauteur'))
await user.type(cropField('hauteur'), '{Enter}')
expect(screen.getByRole('alert')).toHaveTextContent(
'Indiquez les quatre valeurs',
)
await user.click(
screen.getByRole('button', { name: 'Revenir aux valeurs enregistrées' }),
)
await user.clear(cropField('largeur'))
await user.type(cropField('largeur'), '100.0{Enter}')
expect(store.getState().undo).toHaveLength(0)
expect(screen.queryByText('Non appliqué')).toBeNull()
})
it('draws the crop rectangle over the parent canvas, numbers only', async () => {
await openCrop(
insert(
baseText(),
detail({ min_x: 10, min_y: 20, width: 30, height: 40 }),
),
)
const rect = screen.getByTestId('crop-overlay').querySelector('rect')!
expect(rect.getAttribute('x')).toBe('10')
expect(rect.getAttribute('height')).toBe('40')
expect(
screen.getByTestId('crop-canvas-drawing').querySelector('svg'),
).not.toBeNull()
})
it('a parent change commits through the frame check', async () => {
const text = insert(insert(baseText(), detail()), detail2())
await openReady({ text })
const user = userEvent.setup()
render(<ViewsTab {...props} />)
await user.selectOptions(
document.getElementById('view-view-d-parent')!,
'view-e',
)
expect(doc().views[1]).toMatchObject({ parent_view_id: 'view-e' })
})
})
function detail2(): NewElement {
return {
kind: 'view',
value: {
kind: 'detail',
id: 'view-e',
name: { fr: 'Autre', en: 'Other' },
svg_asset_id: null,
view_box: { min_x: 0, min_y: 0, width: 50, height: 50 },
parent_view_id: 'view-main',
},
}
}