feat(app): editor views tab, drawing upload and cleaning, guarded crops
This commit is contained in:
1 parent
d163b2ce9a
commit
8343528be9
22 files changed
+2164
-4
No files matched your search
@@ -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)}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -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)}`
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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),
|
||||
)
|
||||
}
|
||||
@@ -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}`)
|
||||
}
|
||||
}
|
||||
@@ -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' }),
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
@@ -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])
|
||||
}
|
||||
@@ -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,
|
||||
)
|
||||
}
|
||||
@@ -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',
|
||||
}
|
||||
@@ -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',
|
||||
}
|
||||
Reference in new issue
Block a user