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
@@ -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,
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user