feat(app): administration screens and anatomical catalogue (V1-2.5 G, H, I)
Administration page (board 10), species, rights, official sheets list with filters, creation from the core's empty document, overview with the working-copy action; catalogue list (search by sheet name), sheet and version pages through PreviewSheet with zoom and pan. App 650, typecheck, lint, build green.
This commit is contained in:
1 parent
9f7824dc08
commit
0176b3184d
42 files changed
+6438
-39
No files matched your search
@@ -0,0 +1,130 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
SheetFailure,
|
||||
downloadSheetDrawing,
|
||||
getSheetVersion,
|
||||
listOfficialCatalog,
|
||||
type FaunosteoClient,
|
||||
} from '@faunosteo/supabase'
|
||||
import type { PreviewState } from '@faunosteo/core-wasm/types'
|
||||
import { coreRuntime } from '@/core/runtime'
|
||||
import { coreFailure, serverFailure, type CatalogueFailure } from './failure'
|
||||
import { CataloguePreview, type PreviewDrawing } from './preview'
|
||||
|
||||
/**
|
||||
* The catalogue's reads (contract §10, §11.1): the list of published sheets and
|
||||
* one published or deprecated version loaded into the core. The answers are
|
||||
* checked against their shape only (a different one is `unavailable`); the
|
||||
* document and the drawings are the core's to judge.
|
||||
*/
|
||||
|
||||
const LocalizedSchema = z.object({ fr: z.string(), en: z.string() })
|
||||
|
||||
const CatalogEntrySchema = z.object({
|
||||
sheet_id: z.string(),
|
||||
species_id: z.string(),
|
||||
slug: z.string(),
|
||||
name: LocalizedSchema,
|
||||
version_number: z.number(),
|
||||
version_id: z.string(),
|
||||
})
|
||||
export type CatalogEntry = z.infer<typeof CatalogEntrySchema>
|
||||
|
||||
const VersionAnswerSchema = z.object({
|
||||
sheet_id: z.string(),
|
||||
version_id: z.string(),
|
||||
version_number: z.number(),
|
||||
status: z.enum(['draft', 'published', 'deprecated']),
|
||||
species_id: z.string(),
|
||||
document: z.unknown(),
|
||||
fingerprint: z.string().nullable(),
|
||||
drawings: z.array(z.object({ asset_id: z.string(), sha256: z.string() })),
|
||||
})
|
||||
export type VersionAnswer = z.infer<typeof VersionAnswerSchema>
|
||||
|
||||
function parsed<T>(schema: z.ZodType<T>, data: unknown): T {
|
||||
const result = schema.safeParse(data)
|
||||
if (!result.success) throw new SheetFailure('unavailable', result.error)
|
||||
return result.data
|
||||
}
|
||||
|
||||
/** The current published version of every listed sheet (`list_official_catalog`). */
|
||||
export async function fetchCatalog(client: FaunosteoClient): Promise<CatalogEntry[]> {
|
||||
return parsed(z.array(CatalogEntrySchema), await listOfficialCatalog(client))
|
||||
}
|
||||
|
||||
export type VersionLoad =
|
||||
| {
|
||||
ok: true
|
||||
version: VersionAnswer
|
||||
preview: CataloguePreview
|
||||
state: PreviewState
|
||||
}
|
||||
| { ok: false; failure: CatalogueFailure }
|
||||
|
||||
async function downloadDrawings(
|
||||
client: FaunosteoClient,
|
||||
version: VersionAnswer,
|
||||
): Promise<PreviewDrawing[]> {
|
||||
return Promise.all(
|
||||
version.drawings.map(async (drawing) => ({
|
||||
assetId: drawing.asset_id,
|
||||
sha256: drawing.sha256,
|
||||
bytes: await downloadSheetDrawing(client, drawing.sha256),
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
type VersionRead =
|
||||
| { ok: true; version: VersionAnswer; drawings: PreviewDrawing[] }
|
||||
| { ok: false; failure: CatalogueFailure }
|
||||
|
||||
async function readVersion(
|
||||
client: FaunosteoClient,
|
||||
versionId: string,
|
||||
): Promise<VersionRead> {
|
||||
let version: VersionAnswer
|
||||
try {
|
||||
version = parsed(VersionAnswerSchema, await getSheetVersion(client, versionId))
|
||||
} catch (error) {
|
||||
return { ok: false, failure: serverFailure(error) }
|
||||
}
|
||||
// The catalogue reads published and deprecated versions only (§11.1).
|
||||
if (version.status === 'draft') return { ok: false, failure: 'denied' }
|
||||
try {
|
||||
return { ok: true, version, drawings: await downloadDrawings(client, version) }
|
||||
} catch (error) {
|
||||
// The version answered: a drawing it names that Storage does not give is missing.
|
||||
const failure = serverFailure(error)
|
||||
return { ok: false, failure: failure === 'denied' ? 'drawing_missing' : failure }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One version through `get_sheet_version`, its drawings downloaded under RLS
|
||||
* and the whole handed to `PreviewSheet`, which checks hashes, fingerprint and
|
||||
* caps. Unknown and refused ids are the same `denied`. The caller frees the
|
||||
* preview.
|
||||
*/
|
||||
export async function loadVersion(
|
||||
client: FaunosteoClient,
|
||||
versionId: string,
|
||||
): Promise<VersionLoad> {
|
||||
const read = await readVersion(client, versionId)
|
||||
if (!read.ok) return read
|
||||
const { version, drawings } = read
|
||||
if (!(await coreRuntime().ready())) return { ok: false, failure: 'core_unavailable' }
|
||||
const preview = new CataloguePreview(
|
||||
coreRuntime(),
|
||||
{
|
||||
status: version.status,
|
||||
document: JSON.stringify(version.document),
|
||||
fingerprint: version.fingerprint ?? undefined,
|
||||
},
|
||||
drawings,
|
||||
)
|
||||
const state = preview.state()
|
||||
if (state.ok) return { ok: true, version, preview, state: state.value }
|
||||
preview.free()
|
||||
return { ok: false, failure: coreFailure(state.kind) }
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { classifySheetError, type SheetFailureKind } from '@faunosteo/supabase'
|
||||
|
||||
/**
|
||||
* What a catalogue page can meet (contract §10, closed kinds), each phrased by
|
||||
* `catalogue.failure.<kind>` except `denied` (« Accès non autorisé ») and
|
||||
* `core_unavailable` (the core notice with its retry). `denied` folds the
|
||||
* server's refusal and an unknown id into one answer (§5.3).
|
||||
*/
|
||||
export type CatalogueFailure =
|
||||
| 'denied'
|
||||
| 'network'
|
||||
| 'session_expired'
|
||||
| 'rate_limited'
|
||||
| 'unavailable'
|
||||
| 'drawing_missing'
|
||||
| 'drawing_hash_mismatch'
|
||||
| 'fingerprint_mismatch'
|
||||
| 'invalid_document'
|
||||
| 'caps'
|
||||
| 'core_unavailable'
|
||||
|
||||
const DENIED: ReadonlySet<SheetFailureKind> = new Set([
|
||||
'rights.catalog',
|
||||
'not_found',
|
||||
'forbidden',
|
||||
'authentication_required',
|
||||
])
|
||||
|
||||
const PASSED_THROUGH: ReadonlySet<SheetFailureKind> = new Set([
|
||||
'network',
|
||||
'session_expired',
|
||||
'rate_limited',
|
||||
])
|
||||
|
||||
/** A server or network answer of the access layer, folded for the page. */
|
||||
export function serverFailure(error: unknown): CatalogueFailure {
|
||||
const kind = classifySheetError(error)
|
||||
if (DENIED.has(kind)) return 'denied'
|
||||
if (PASSED_THROUGH.has(kind)) return kind as CatalogueFailure
|
||||
return 'unavailable'
|
||||
}
|
||||
|
||||
const CORE_REFUSALS: ReadonlySet<string> = new Set([
|
||||
'drawing_missing',
|
||||
'drawing_hash_mismatch',
|
||||
'fingerprint_mismatch',
|
||||
'invalid_document',
|
||||
'caps',
|
||||
])
|
||||
|
||||
/**
|
||||
* A refusal of the core's `PreviewBuilder` (`<kind>: <detail>`), or a runtime
|
||||
* failure: the engine kinds ask for a retry, anything else unreadable is the
|
||||
* document's fault (`invalid_shape`, `invalid_json`).
|
||||
*/
|
||||
export function coreFailure(kind: string): CatalogueFailure {
|
||||
if (CORE_REFUSALS.has(kind)) return kind as CatalogueFailure
|
||||
if (kind === 'core_unavailable' || kind === 'internal') return 'core_unavailable'
|
||||
return 'invalid_document'
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Display framing of the catalogue canvas (board 03): a CSS scale and
|
||||
* translation of the inserted drawing, never a change to the drawing. At
|
||||
* scale 1 the drawing fills the box with its whole frame visible (the
|
||||
* composer's `xMidYMid meet`); zooming keeps the point under the finger or
|
||||
* the box centre in place, and panning never uncovers the box.
|
||||
*/
|
||||
export interface Framing {
|
||||
scale: number
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
export interface Box {
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export const FIT: Framing = { scale: 1, x: 0, y: 0 }
|
||||
export const MAX_SCALE = 6
|
||||
/** One press of − or +. */
|
||||
export const ZOOM_STEP = 1.5
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(max, Math.max(min, value))
|
||||
}
|
||||
|
||||
/** The translation that keeps the scaled drawing over the whole box. */
|
||||
function contained(framing: Framing, box: Box): Framing {
|
||||
const { scale } = framing
|
||||
return {
|
||||
scale,
|
||||
x: clamp(framing.x, box.width * (1 - scale), 0),
|
||||
y: clamp(framing.y, box.height * (1 - scale), 0),
|
||||
}
|
||||
}
|
||||
|
||||
/** Scales by `factor` around a point of the box (its centre by default). */
|
||||
export function zoomBy(
|
||||
framing: Framing,
|
||||
factor: number,
|
||||
box: Box,
|
||||
at = { x: box.width / 2, y: box.height / 2 },
|
||||
): Framing {
|
||||
const scale = clamp(framing.scale * factor, 1, MAX_SCALE)
|
||||
const ratio = scale / framing.scale
|
||||
return contained(
|
||||
{
|
||||
scale,
|
||||
x: at.x - (at.x - framing.x) * ratio,
|
||||
y: at.y - (at.y - framing.y) * ratio,
|
||||
},
|
||||
box,
|
||||
)
|
||||
}
|
||||
|
||||
export function panBy(framing: Framing, dx: number, dy: number, box: Box): Framing {
|
||||
return contained({ ...framing, x: framing.x + dx, y: framing.y + dy }, box)
|
||||
}
|
||||
|
||||
export function transformOf(framing: Framing): string {
|
||||
return `translate(${framing.x}px, ${framing.y}px) scale(${framing.scale})`
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import {
|
||||
CORE_UNAVAILABLE,
|
||||
closedRefusal,
|
||||
parseOutcome,
|
||||
type CoreOutcome,
|
||||
type CoreRuntime,
|
||||
type GluePreviewSheet,
|
||||
} from '@faunosteo/core-wasm'
|
||||
import type {
|
||||
CanvasView,
|
||||
PreviewInput,
|
||||
PreviewState,
|
||||
} from '@faunosteo/core-wasm/types'
|
||||
|
||||
/** One stored drawing as the page downloaded it: untrusted bytes the core hashes and reads. */
|
||||
export interface PreviewDrawing {
|
||||
assetId: string
|
||||
sha256: string
|
||||
bytes: Uint8Array
|
||||
}
|
||||
|
||||
/**
|
||||
* A stored version loaded into the core (`PreviewSheet`, RUST.md §12): the
|
||||
* core checks each drawing's sha256 against its row, the fingerprint, the caps
|
||||
* and every drawing through its SVG reader, then answers `preview.state` and
|
||||
* `view.canvas`. Like `SheetSession`, the handle belongs to one instance of
|
||||
* the module: after a trap and a recovery it is rebuilt from the kept input,
|
||||
* a handle of a dropped instance is never called. `free` releases it when the
|
||||
* page leaves.
|
||||
*/
|
||||
export class CataloguePreview {
|
||||
private handle: GluePreviewSheet | null = null
|
||||
private handleGeneration = -1
|
||||
private freed = false
|
||||
|
||||
constructor(
|
||||
private readonly runtime: CoreRuntime,
|
||||
private readonly input: PreviewInput,
|
||||
private readonly drawings: readonly PreviewDrawing[],
|
||||
) {}
|
||||
|
||||
/** The first call builds the handle: the builder's refusals come back as closed kinds. */
|
||||
state(): CoreOutcome<PreviewState> {
|
||||
return this.call<PreviewState>('preview.state', {})
|
||||
}
|
||||
|
||||
/** The composed view (drawing framed, annotation layer, ids scoped per view). */
|
||||
canvas(viewId: string): CoreOutcome<string> {
|
||||
const view = this.call<CanvasView>('view.canvas', { viewId })
|
||||
return view.ok ? { ok: true, value: view.value.svg } : view
|
||||
}
|
||||
|
||||
/** After this, every call answers `core_unavailable`: a page that left never rebuilds. */
|
||||
free(): void {
|
||||
this.freed = true
|
||||
const handle = this.handle
|
||||
this.handle = null
|
||||
if (!handle || this.handleGeneration !== this.runtime.generation) return
|
||||
try {
|
||||
handle.free()
|
||||
} catch {
|
||||
// Freeing never decides anything; a dead instance keeps its memory.
|
||||
}
|
||||
}
|
||||
|
||||
private call<T>(op: string, input: unknown): CoreOutcome<T> {
|
||||
const handle = this.current()
|
||||
if (!handle.ok) return handle
|
||||
return this.runtime.invoke(() =>
|
||||
parseOutcome<T>(handle.value.call(op, JSON.stringify(input))),
|
||||
)
|
||||
}
|
||||
|
||||
private current(): CoreOutcome<GluePreviewSheet> {
|
||||
if (this.freed) return CORE_UNAVAILABLE
|
||||
if (this.handle && this.handleGeneration === this.runtime.generation) {
|
||||
return { ok: true, value: this.handle }
|
||||
}
|
||||
this.handle = null
|
||||
return this.runtime.invoke<GluePreviewSheet>((glue) => {
|
||||
const builder = new glue.PreviewBuilder()
|
||||
for (const drawing of this.drawings) {
|
||||
// `false` past the handle's bounds: the build then refuses with `caps`.
|
||||
builder.add_drawing(drawing.assetId, drawing.sha256, drawing.bytes)
|
||||
}
|
||||
try {
|
||||
this.handle = builder.build(JSON.stringify(this.input))
|
||||
} catch (error) {
|
||||
// Only the module's closed refusal is a refused version; anything else poisons.
|
||||
const refusal = closedRefusal(error)
|
||||
if (refusal === null) throw error
|
||||
const [kind, ...detail] = refusal.split(': ')
|
||||
return { ok: false, kind, detail: detail.join(': ') }
|
||||
}
|
||||
this.handleGeneration = this.runtime.generation
|
||||
return { ok: true, value: this.handle }
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { listSheetVersions } from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { loadVersion, type CatalogEntry } from './catalogue'
|
||||
|
||||
export interface CardDetails {
|
||||
publishedAt: string | null
|
||||
viewCount: number
|
||||
zoneCount: number
|
||||
/** Blob URL of the core's composed main view, shown as an image; null when it cannot be drawn. */
|
||||
thumbnail: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* What a catalogue card adds to the list answer: the publication date, the
|
||||
* counts the core read from the document, and a thumbnail of the main view.
|
||||
* Loaded per card once the list is shown (one version and its drawings each);
|
||||
* the core handle is freed as soon as the canvas is composed. Any failure
|
||||
* leaves the card with its name and its link only.
|
||||
*/
|
||||
export function useCardDetails(entry: CatalogEntry): CardDetails | null {
|
||||
const [details, setDetails] = useState<CardDetails | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
let thumbnail: string | null = null
|
||||
const client = getSupabaseClient()
|
||||
if (!client) return
|
||||
void Promise.all([
|
||||
listSheetVersions(client, entry.sheet_id).catch(() => []),
|
||||
loadVersion(client, entry.version_id),
|
||||
]).then(([versions, load]) => {
|
||||
if (!load.ok) return
|
||||
const { state, preview } = load
|
||||
const main = state.index ? preview.canvas(state.index.main_view_id) : null
|
||||
preview.free()
|
||||
if (!live) return
|
||||
if (main?.ok) {
|
||||
thumbnail = URL.createObjectURL(new Blob([main.value], { type: 'image/svg+xml' }))
|
||||
}
|
||||
setDetails({
|
||||
publishedAt:
|
||||
versions.find((v) => v.id === entry.version_id)?.published_at ?? null,
|
||||
viewCount: state.document.views.length,
|
||||
zoneCount: state.document.finding_zones.length,
|
||||
thumbnail,
|
||||
})
|
||||
})
|
||||
return () => {
|
||||
live = false
|
||||
if (thumbnail) URL.revokeObjectURL(thumbnail)
|
||||
}
|
||||
}, [entry.sheet_id, entry.version_id])
|
||||
|
||||
return details
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { fetchSpeciesLabels, type SpeciesLabel } from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { fetchCatalog, type CatalogEntry } from './catalogue'
|
||||
import { serverFailure, type CatalogueFailure } from './failure'
|
||||
|
||||
export type CatalogueState =
|
||||
| { status: 'loading' }
|
||||
| { status: 'ready'; entries: CatalogEntry[]; species: SpeciesLabel[] }
|
||||
| { status: 'error'; failure: CatalogueFailure }
|
||||
|
||||
/** Species names are display only: a failed read leaves the ids as names. */
|
||||
async function speciesLabels(
|
||||
client: NonNullable<ReturnType<typeof getSupabaseClient>>,
|
||||
): Promise<SpeciesLabel[]> {
|
||||
try {
|
||||
return await fetchSpeciesLabels(client)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** The published catalogue and the species names, read once per visit (retry reads again). */
|
||||
export function useCatalogue() {
|
||||
const [state, setState] = useState<CatalogueState>({ status: 'loading' })
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
const client = getSupabaseClient()
|
||||
setState({ status: 'loading' })
|
||||
if (!client) {
|
||||
setState({ status: 'error', failure: 'unavailable' })
|
||||
return
|
||||
}
|
||||
Promise.all([fetchCatalog(client), speciesLabels(client)])
|
||||
.then(([entries, species]) => {
|
||||
if (live) setState({ status: 'ready', entries, species })
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (live) setState({ status: 'error', failure: serverFailure(error) })
|
||||
})
|
||||
return () => {
|
||||
live = false
|
||||
}
|
||||
}, [attempt])
|
||||
|
||||
const retry = useCallback(() => setAttempt((n) => n + 1), [])
|
||||
return { state, retry }
|
||||
}
|
||||
|
||||
/** Lower case without accents, so « epaule » finds « Épaule ». */
|
||||
function folded(text: string): string {
|
||||
return text.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase()
|
||||
}
|
||||
|
||||
/** Search by sheet name only, French or English (BDR-095), then the species chip. */
|
||||
export function filterCatalog(
|
||||
entries: readonly CatalogEntry[],
|
||||
query: string,
|
||||
speciesId: string | null,
|
||||
): CatalogEntry[] {
|
||||
const term = folded(query.trim())
|
||||
return entries.filter(
|
||||
(entry) =>
|
||||
(speciesId === null || entry.species_id === speciesId) &&
|
||||
(term === '' ||
|
||||
folded(entry.name.fr).includes(term) ||
|
||||
folded(entry.name.en).includes(term)),
|
||||
)
|
||||
}
|
||||
|
||||
/** The species that have a listed sheet, in the reference order, unknown ids last. */
|
||||
export function catalogSpecies(
|
||||
entries: readonly CatalogEntry[],
|
||||
labels: readonly SpeciesLabel[],
|
||||
): string[] {
|
||||
const present = new Set(entries.map((entry) => entry.species_id))
|
||||
const known = labels.map((label) => label.id).filter((id) => present.has(id))
|
||||
return [...known, ...[...present].filter((id) => !known.includes(id))]
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type KeyboardEvent,
|
||||
type PointerEvent,
|
||||
type RefObject,
|
||||
} from 'react'
|
||||
import { FIT, ZOOM_STEP, panBy, zoomBy, type Box, type Framing } from './framing'
|
||||
|
||||
/** Movement past which a press is a drag, not a click on a zone. */
|
||||
const DRAG_THRESHOLD = 4
|
||||
const KEY_PAN = 40
|
||||
|
||||
type Point = { x: number; y: number }
|
||||
|
||||
function boxOf(element: HTMLElement | null): Box & { left: number; top: number } {
|
||||
const rect = element?.getBoundingClientRect()
|
||||
return {
|
||||
width: rect?.width ?? 0,
|
||||
height: rect?.height ?? 0,
|
||||
left: rect?.left ?? 0,
|
||||
top: rect?.top ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
function distance(a: Point, b: Point): number {
|
||||
return Math.hypot(a.x - b.x, a.y - b.y)
|
||||
}
|
||||
|
||||
/**
|
||||
* Zoom and pan of the canvas box: buttons, a drag with one pointer, a pinch
|
||||
* with two, the wheel (pans when zoomed; with Ctrl, as a trackpad pinch
|
||||
* sends it, zooms at the cursor) and the keyboard on the focused box (arrows,
|
||||
* + and −, 0 fits). `reset` comes back to the whole drawing. A press that
|
||||
* moved is not a click: `swallowClick` says so once.
|
||||
*/
|
||||
export function useFraming(viewport: RefObject<HTMLElement | null>, resetKey: string) {
|
||||
const [framing, setFraming] = useState<Framing>(FIT)
|
||||
const pointers = useRef(new Map<number, Point>())
|
||||
const moved = useRef(0)
|
||||
const dragged = useRef(false)
|
||||
// The wheel listener reads the scale without re-subscribing on every change.
|
||||
const scale = useRef(FIT.scale)
|
||||
|
||||
useEffect(() => setFraming(FIT), [resetKey])
|
||||
useEffect(() => {
|
||||
scale.current = framing.scale
|
||||
}, [framing.scale])
|
||||
|
||||
const zoom = useCallback(
|
||||
(factor: number, at?: Point) =>
|
||||
setFraming((f) => zoomBy(f, factor, boxOf(viewport.current), at)),
|
||||
[viewport],
|
||||
)
|
||||
const pan = useCallback(
|
||||
(dx: number, dy: number) =>
|
||||
setFraming((f) => panBy(f, dx, dy, boxOf(viewport.current))),
|
||||
[viewport],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const element = viewport.current
|
||||
if (!element) return
|
||||
const onWheel = (event: WheelEvent) => {
|
||||
const box = boxOf(element)
|
||||
if (event.ctrlKey) {
|
||||
event.preventDefault()
|
||||
const at = { x: event.clientX - box.left, y: event.clientY - box.top }
|
||||
zoom(event.deltaY < 0 ? 1.1 : 1 / 1.1, at)
|
||||
return
|
||||
}
|
||||
// Unzoomed, the wheel scrolls the page as usual.
|
||||
if (scale.current === 1) return
|
||||
event.preventDefault()
|
||||
setFraming((f) => panBy(f, -event.deltaX, -event.deltaY, box))
|
||||
}
|
||||
element.addEventListener('wheel', onWheel, { passive: false })
|
||||
return () => element.removeEventListener('wheel', onWheel)
|
||||
}, [viewport, zoom])
|
||||
|
||||
const onPointerDown = useCallback((event: PointerEvent) => {
|
||||
pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY })
|
||||
if (pointers.current.size === 1) {
|
||||
moved.current = 0
|
||||
dragged.current = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
const onPointerMove = useCallback(
|
||||
(event: PointerEvent) => {
|
||||
const before = pointers.current.get(event.pointerId)
|
||||
if (!before) return
|
||||
const now = { x: event.clientX, y: event.clientY }
|
||||
const others = [...pointers.current].filter(([id]) => id !== event.pointerId)
|
||||
pointers.current.set(event.pointerId, now)
|
||||
moved.current += distance(before, now)
|
||||
if (moved.current > DRAG_THRESHOLD) dragged.current = true
|
||||
if (others.length === 1) {
|
||||
const other = others[0][1]
|
||||
const box = boxOf(viewport.current)
|
||||
const at = { x: (now.x + other.x) / 2 - box.left, y: (now.y + other.y) / 2 - box.top }
|
||||
const factor = distance(now, other) / Math.max(distance(before, other), 1)
|
||||
zoom(factor, at)
|
||||
} else if (others.length === 0 && dragged.current) {
|
||||
event.currentTarget.setPointerCapture?.(event.pointerId)
|
||||
pan(now.x - before.x, now.y - before.y)
|
||||
}
|
||||
},
|
||||
[viewport, zoom, pan],
|
||||
)
|
||||
|
||||
const onPointerUp = useCallback((event: PointerEvent) => {
|
||||
pointers.current.delete(event.pointerId)
|
||||
}, [])
|
||||
|
||||
const onKeyDown = useCallback(
|
||||
(event: KeyboardEvent) => {
|
||||
const keys: Record<string, () => void> = {
|
||||
ArrowLeft: () => pan(KEY_PAN, 0),
|
||||
ArrowRight: () => pan(-KEY_PAN, 0),
|
||||
ArrowUp: () => pan(0, KEY_PAN),
|
||||
ArrowDown: () => pan(0, -KEY_PAN),
|
||||
'+': () => zoom(ZOOM_STEP),
|
||||
'=': () => zoom(ZOOM_STEP),
|
||||
'-': () => zoom(1 / ZOOM_STEP),
|
||||
'0': () => setFraming(FIT),
|
||||
}
|
||||
const action = keys[event.key]
|
||||
if (!action) return
|
||||
event.preventDefault()
|
||||
action()
|
||||
},
|
||||
[pan, zoom],
|
||||
)
|
||||
|
||||
/** True once after a press that moved: the click that ends a drag selects nothing. */
|
||||
const swallowClick = useCallback(() => {
|
||||
const was = dragged.current
|
||||
dragged.current = false
|
||||
return was
|
||||
}, [])
|
||||
|
||||
return {
|
||||
framing,
|
||||
zoomIn: () => zoom(ZOOM_STEP),
|
||||
zoomOut: () => zoom(1 / ZOOM_STEP),
|
||||
reset: () => setFraming(FIT),
|
||||
swallowClick,
|
||||
handlers: {
|
||||
onPointerDown,
|
||||
onPointerMove,
|
||||
onPointerUp,
|
||||
onPointerCancel: onPointerUp,
|
||||
onKeyDown,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { listSheetVersions, type CatalogVersionItem } from '@faunosteo/supabase'
|
||||
import type { PreviewState } from '@faunosteo/core-wasm/types'
|
||||
import { coreRuntime } from '@/core/runtime'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { loadVersion, type VersionAnswer } from './catalogue'
|
||||
import { serverFailure, type CatalogueFailure } from './failure'
|
||||
import type { CataloguePreview } from './preview'
|
||||
|
||||
export type SheetVersionState =
|
||||
| { status: 'loading' }
|
||||
| {
|
||||
status: 'ready'
|
||||
versions: CatalogVersionItem[]
|
||||
version: VersionAnswer
|
||||
preview: CataloguePreview
|
||||
state: PreviewState
|
||||
}
|
||||
| { status: 'error'; failure: CatalogueFailure }
|
||||
|
||||
/**
|
||||
* The version a sheet page shows: `number` names it, otherwise the newest
|
||||
* published one (the sheet's current version), else the newest at all (a
|
||||
* sheet whose versions were all retired stays readable by id, §6.9). The
|
||||
* list comes newest first under the reader policy; an unknown sheet, an
|
||||
* unreadable one and a missing number are the same `denied`.
|
||||
*/
|
||||
function pickVersion(
|
||||
versions: readonly CatalogVersionItem[],
|
||||
number: number | null,
|
||||
): CatalogVersionItem | undefined {
|
||||
if (number !== null) return versions.find((v) => v.version_number === number)
|
||||
return versions.find((v) => v.status === 'published') ?? versions[0]
|
||||
}
|
||||
|
||||
async function resolve(sheetId: string, number: number | null) {
|
||||
const client = getSupabaseClient()
|
||||
if (!client) return { ok: false as const, failure: 'unavailable' as const }
|
||||
let versions: CatalogVersionItem[]
|
||||
try {
|
||||
versions = await listSheetVersions(client, sheetId)
|
||||
} catch (error) {
|
||||
return { ok: false as const, failure: serverFailure(error) }
|
||||
}
|
||||
const picked = pickVersion(versions, number)
|
||||
if (!picked) return { ok: false as const, failure: 'denied' as const }
|
||||
const load = await loadVersion(client, picked.id)
|
||||
return load.ok ? { ...load, versions } : load
|
||||
}
|
||||
|
||||
/** Loads the page's version into the core; the handle is freed when the page leaves or changes. */
|
||||
export function useSheetVersion(sheetId: string, number: number | null) {
|
||||
const [state, setState] = useState<SheetVersionState>({ status: 'loading' })
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
let preview: CataloguePreview | null = null
|
||||
setState({ status: 'loading' })
|
||||
void resolve(sheetId, number).then((load) => {
|
||||
if (!load.ok) {
|
||||
if (live) setState({ status: 'error', failure: load.failure })
|
||||
return
|
||||
}
|
||||
if (!live) {
|
||||
load.preview.free()
|
||||
return
|
||||
}
|
||||
preview = load.preview
|
||||
setState({
|
||||
status: 'ready',
|
||||
versions: load.versions,
|
||||
version: load.version,
|
||||
preview: load.preview,
|
||||
state: load.state,
|
||||
})
|
||||
})
|
||||
return () => {
|
||||
live = false
|
||||
preview?.free()
|
||||
}
|
||||
}, [sheetId, number, attempt])
|
||||
|
||||
// The core may need a restart before the version is loaded again.
|
||||
const retry = useCallback(() => {
|
||||
void coreRuntime()
|
||||
.retry()
|
||||
.finally(() => setAttempt((n) => n + 1))
|
||||
}, [])
|
||||
return { state, retry }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { useT } from '@/i18n/useT'
|
||||
|
||||
type Translate = ReturnType<typeof useT>
|
||||
|
||||
/** « Version 3 · publiée le 28/10/2026 », the date in the page's language. */
|
||||
export function versionText(
|
||||
number: number,
|
||||
publishedAt: string | null,
|
||||
locale: string,
|
||||
t: Translate,
|
||||
): string {
|
||||
if (!publishedAt) return t('catalogue.version').replace('{number}', String(number))
|
||||
return t('catalogue.version_published')
|
||||
.replace('{number}', String(number))
|
||||
.replace('{date}', new Date(publishedAt).toLocaleDateString(locale))
|
||||
}
|
||||
Reference in new issue
Block a user