chore(workspace): move the app to apps/app under a pnpm workspace (step 2)
144 files moved with git mv (pure renames). Root package.json delegates dev/typecheck/test:run/lint/build to the packages; Node 24 LTS and pnpm 10.13.1 pinned (.nvmrc, .node-version, engines, packageManager, root devDependency, engine-strict). Dockerfile builds @faunosteo/app on node:24-alpine and copies apps/app/dist; nginx and runtime config unchanged. CI workflow for Gitea Actions. packages/ reserved (README only). Docs synced: WORKSPACE.md, CLAUDE.md, README, DEPLOY, CHANGELOG, plan. 271/271 tests, typecheck, lint, build green from the root.
This commit is contained in:
1 parent
c8d48ab4cc
commit
8673475293
164 files changed
+348
-128
No files matched your search
@@ -0,0 +1,19 @@
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
|
||||
import type { Bone } from './types'
|
||||
|
||||
/**
|
||||
* Resolves the user-facing label for an anatomical zone given the active
|
||||
* locale. Falls back to the opposite language when the requested one is
|
||||
* missing (some SVG hitboxes carry only `data-anno-name-fr`), then to the
|
||||
* provided fallback (typically the raw boneId) so the UI never renders
|
||||
* an empty label.
|
||||
*/
|
||||
export function boneLabel(
|
||||
bone: Bone | undefined,
|
||||
locale: Locale,
|
||||
fallback: string,
|
||||
): string {
|
||||
if (!bone) return fallback
|
||||
return pickLocaleLabel(bone.fr, bone.en, locale, fallback)
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { SvgConventionError } from './types'
|
||||
import type { Bone, BoneCategory } from './types'
|
||||
|
||||
/**
|
||||
* Validates that an annotated SVG element carries the two attributes the
|
||||
* application needs to wire it up: a stable id (`data-anno-id`) and a
|
||||
* category bucket (`data-anno-category`). Labels (`data-anno-name-fr/en`)
|
||||
* and the popup trigger (`data-anno-opens-detail`) are optional and
|
||||
* checked only at use-site.
|
||||
*
|
||||
* The category value itself is opaque to the application — any non-empty
|
||||
* string is accepted. New SVGs are free to introduce new categories
|
||||
* without touching this parser.
|
||||
*/
|
||||
function validateBoneElement(el: Element): void {
|
||||
const boneId = el.getAttribute('data-anno-id') ?? ''
|
||||
if (!boneId) {
|
||||
throw new SvgConventionError(
|
||||
'Element with missing data-anno-id',
|
||||
boneId,
|
||||
'data-anno-id',
|
||||
)
|
||||
}
|
||||
const cat = el.getAttribute('data-anno-category') ?? ''
|
||||
if (!cat) {
|
||||
throw new SvgConventionError(
|
||||
`Element data-anno-id="${boneId}" missing attribute data-anno-category`,
|
||||
boneId,
|
||||
'data-anno-category',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an SVG document and returns a map of `data-anno-id` → Bone.
|
||||
*
|
||||
* Every element carrying `data-anno-id` is collected. Multiple elements
|
||||
* may share the same id (e.g. hitbox + visible layer); they all end up
|
||||
* grouped under the same Bone with all elements in `els`.
|
||||
*
|
||||
* Throws `SvgConventionError` only on the two required attributes
|
||||
* (`data-anno-id`, `data-anno-category`). Labels are optional.
|
||||
*/
|
||||
export function parseSvgBones(svgRoot: SVGSVGElement): Map<string, Bone> {
|
||||
const map = new Map<string, Bone>()
|
||||
const all = svgRoot.querySelectorAll<Element>('[data-anno-id]')
|
||||
all.forEach((el) => {
|
||||
validateBoneElement(el)
|
||||
const id = el.getAttribute('data-anno-id') as string
|
||||
const fr = el.getAttribute('data-anno-name-fr') ?? ''
|
||||
const en = el.getAttribute('data-anno-name-en') ?? ''
|
||||
const category = el.getAttribute('data-anno-category') as BoneCategory
|
||||
const opensDetail =
|
||||
el.getAttribute('data-anno-opens-detail') ?? undefined
|
||||
const special = el.getAttribute('data-anno-special') ?? undefined
|
||||
const lateral = (el.getAttribute('data-anno-lateral') ?? undefined) as
|
||||
| 'bilateral'
|
||||
| 'unpaired'
|
||||
| undefined
|
||||
|
||||
const existing = map.get(id)
|
||||
if (existing) {
|
||||
existing.els.push(el)
|
||||
if (opensDetail && !existing.opensDetail) {
|
||||
existing.opensDetail = opensDetail
|
||||
}
|
||||
if (special && !existing.special) {
|
||||
existing.special = special
|
||||
}
|
||||
if (lateral && !existing.lateral) {
|
||||
existing.lateral = lateral
|
||||
}
|
||||
if (!existing.fr && fr) existing.fr = fr
|
||||
if (!existing.en && en) existing.en = en
|
||||
} else {
|
||||
map.set(id, {
|
||||
id,
|
||||
fr,
|
||||
en,
|
||||
category,
|
||||
opensDetail,
|
||||
special,
|
||||
lateral,
|
||||
els: [el],
|
||||
})
|
||||
}
|
||||
})
|
||||
return map
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks up from `event.target` to find the nearest element carrying
|
||||
* `data-anno-id`. Returns null when the click did not land on an
|
||||
* annotated element.
|
||||
*/
|
||||
export function getBoneIdFromEvent(event: Event): string | null {
|
||||
return getAnnotatedElement(event)?.getAttribute('data-anno-id') || null
|
||||
}
|
||||
|
||||
export function getAnnotatedElement(event: Event): Element | null {
|
||||
let node = event.target as Element | null
|
||||
while (node && node.nodeType === 1) {
|
||||
if (node.hasAttribute('data-anno-id')) return node
|
||||
node = node.parentElement
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export async function loadSvg(publicPath: string): Promise<SVGSVGElement> {
|
||||
const resp = await fetch(publicPath)
|
||||
if (!resp.ok) {
|
||||
throw new Error(`Failed to load SVG ${publicPath}: HTTP ${resp.status}`)
|
||||
}
|
||||
const text = await resp.text()
|
||||
const doc = new DOMParser().parseFromString(text, 'image/svg+xml')
|
||||
const parseErr = doc.querySelector('parsererror')
|
||||
if (parseErr) {
|
||||
throw new Error(`Invalid SVG at ${publicPath}: ${parseErr.textContent}`)
|
||||
}
|
||||
const root = doc.documentElement
|
||||
if (root.tagName.toLowerCase() !== 'svg') {
|
||||
throw new Error(`Root element of ${publicPath} is not <svg>`)
|
||||
}
|
||||
return root as unknown as SVGSVGElement
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* `data-anno-category` is a free-form string supplied by the SVG.
|
||||
*
|
||||
* The application never branches on category values — it treats every
|
||||
* annotation the same way. Categories are kept around because they're
|
||||
* useful for grouping and future filtering, but no code path here may
|
||||
* rely on a closed set.
|
||||
*/
|
||||
export type BoneCategory = string
|
||||
|
||||
/**
|
||||
* Logical annotation as parsed from an SVG. All DOM elements sharing the
|
||||
* same `data-anno-id` are grouped into one Bone. `id` is the persisted
|
||||
* identifier surfaced in the report JSON contract
|
||||
* (`ObservationZone.boneId`); keep it stable across SVG renames.
|
||||
*/
|
||||
export interface Bone {
|
||||
id: string
|
||||
/** French label from data-anno-name-fr — may be empty for opens-detail-only triggers */
|
||||
fr: string
|
||||
/** English label from data-anno-name-en — may be empty */
|
||||
en: string
|
||||
/** Raw value from data-anno-category — opaque to the application */
|
||||
category: BoneCategory
|
||||
/** Detail popup id from data-anno-opens-detail, if present */
|
||||
opensDetail?: string
|
||||
/**
|
||||
* Free-form behavior hint from `data-anno-special`.
|
||||
*
|
||||
* Known values consumed by the application:
|
||||
* - `vertebral-precision`: clicking the zone opens VertebraPicker.
|
||||
*
|
||||
* Opaque to the parser; new values are accepted without code changes.
|
||||
*/
|
||||
special?: string
|
||||
/** Laterality hint from data-anno-lateral — bilateral or unpaired */
|
||||
lateral?: 'bilateral' | 'unpaired'
|
||||
/** All DOM elements carrying this annotation (used for colorization) */
|
||||
els: Element[]
|
||||
}
|
||||
|
||||
/** Visual state applied to SVG elements (active-observation highlight). */
|
||||
export type BoneState = 'current' | 'default'
|
||||
|
||||
/** Error thrown when SVG violates the convention. */
|
||||
export class SvgConventionError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly boneId: string,
|
||||
public readonly missingAttribute: string,
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'SvgConventionError'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { BrowserRouter, Routes, Route, useLocation } from 'react-router-dom'
|
||||
import { ConfigProvider } from './providers/ConfigProvider'
|
||||
import Footer from '@/components/brand/Footer'
|
||||
import HomeRoute from './routes/HomeRoute'
|
||||
import NewReportRoute from './routes/NewReportRoute'
|
||||
import EditorRoute from './routes/EditorRoute'
|
||||
import SvgEditorRoute from './routes/SvgEditorRoute'
|
||||
import EditorsRoute from './routes/EditorsRoute'
|
||||
import NotFoundRoute from './routes/NotFoundRoute'
|
||||
|
||||
function AppShell() {
|
||||
const hideFooter = useLocation().pathname === '/svg-editor'
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col">
|
||||
<main className="flex-1 flex flex-col">
|
||||
<Routes>
|
||||
<Route path="/" element={<HomeRoute />} />
|
||||
<Route path="/new" element={<NewReportRoute />} />
|
||||
<Route path="/editor" element={<EditorRoute />} />
|
||||
<Route path="/svg-editor" element={<SvgEditorRoute />} />
|
||||
<Route path="/editors" element={<EditorsRoute />} />
|
||||
<Route path="*" element={<NotFoundRoute />} />
|
||||
</Routes>
|
||||
</main>
|
||||
{!hideFooter && <Footer />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<ConfigProvider>
|
||||
<BrowserRouter>
|
||||
<AppShell />
|
||||
</BrowserRouter>
|
||||
</ConfigProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { createContext, useContext, type ReactNode } from 'react'
|
||||
import { appConfig, type AppConfig } from '@/config/env'
|
||||
|
||||
const ConfigContext = createContext<AppConfig>(appConfig)
|
||||
|
||||
export function ConfigProvider({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<ConfigContext.Provider value={appConfig}>
|
||||
{children}
|
||||
</ConfigContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
/** Returns the resolved app config. Never returns undefined. */
|
||||
export function useConfig(): AppConfig {
|
||||
return useContext(ConfigContext)
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
|
||||
import DetailModal from '@/components/canvas/DetailModal'
|
||||
import ObservationList from '@/components/observation/ObservationList'
|
||||
import VertebraPicker from '@/components/observation/VertebraPicker'
|
||||
import { regionFromLabel } from '@/lib/spineZones'
|
||||
import LateralityPicker from '@/components/observation/LateralityPicker'
|
||||
import type { LateralSide } from '@/domain/schema/observation'
|
||||
import ConclusionPanel from '@/components/report/ConclusionPanel'
|
||||
import ReportHeader from '@/components/report/ReportHeader'
|
||||
import PractitionerForm from '@/components/report/PractitionerForm'
|
||||
import AnimalForm from '@/components/report/AnimalForm'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { writeCachedPractitioner } from '@/state/practitionerCache'
|
||||
import { getSpecies } from '@/domain/species/registry'
|
||||
import { loadSvg } from '@/anatomy/svgLoader'
|
||||
import { parseSvgBones } from '@/anatomy/svgConvention'
|
||||
import { collectSpineVertebrae, syncSpineZones } from '@/lib/spineZones'
|
||||
import type { Bone, BoneState } from '@/anatomy/types'
|
||||
import type { Observation, ObservationZone } from '@/domain/schema/observation'
|
||||
import type { Report } from '@/domain/schema/report'
|
||||
import type { SpeciesFindings } from '@/domain/schema/findings'
|
||||
import type { Practitioner } from '@/domain/schema/practitioner'
|
||||
import type { Animal, Owner } from '@/domain/schema/animal'
|
||||
import { exportReportToPdf } from '@/pdf/export'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { boneLabel } from '@/anatomy/labels'
|
||||
|
||||
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
|
||||
|
||||
/** Merges newly parsed bones into the accumulated map without overwriting. */
|
||||
function mergeBones(prev: Map<string, Bone>, parsed: Map<string, Bone>) {
|
||||
const merged = new Map(prev)
|
||||
parsed.forEach((b, id) => {
|
||||
if (!merged.has(id)) merged.set(id, b)
|
||||
})
|
||||
return merged
|
||||
}
|
||||
|
||||
export default function EditorRoute() {
|
||||
const navigate = useNavigate()
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const report = useReportStore((s) => s.report)
|
||||
const activeIndex = useReportStore((s) => s.activeObservationIndex)
|
||||
const addObservation = useReportStore((s) => s.addObservation)
|
||||
const updateObservation = useReportStore((s) => s.updateObservation)
|
||||
const removeObservation = useReportStore((s) => s.removeObservation)
|
||||
const moveObservationUp = useReportStore((s) => s.moveObservationUp)
|
||||
const moveObservationDown = useReportStore((s) => s.moveObservationDown)
|
||||
const setActiveObservation = useReportStore((s) => s.setActiveObservation)
|
||||
const setConclusion = useReportStore((s) => s.setConclusion)
|
||||
const setRecommendations = useReportStore((s) => s.setRecommendations)
|
||||
const setNextAppointment = useReportStore((s) => s.setNextAppointment)
|
||||
const setPractitioner = useReportStore((s) => s.setPractitioner)
|
||||
const setAnimal = useReportStore((s) => s.setAnimal)
|
||||
const setOwner = useReportStore((s) => s.setOwner)
|
||||
|
||||
const [bones, setBones] = useState<Map<string, Bone>>(new Map())
|
||||
const [detailBones, setDetailBones] = useState<Map<string, Bone>>(new Map())
|
||||
const [findings, setFindings] = useState<SpeciesFindings | null>(null)
|
||||
const [disclaimer, setDisclaimer] = useState<string | null>(null)
|
||||
const [detail, setDetail] = useState<{
|
||||
id: string
|
||||
src: string
|
||||
title: string
|
||||
} | null>(null)
|
||||
const [vertebraTarget, setVertebraTarget] = useState<number | null>(null)
|
||||
const [lateralTarget, setLateralTarget] = useState<{
|
||||
boneId: string
|
||||
detailSourceId?: string
|
||||
} | null>(null)
|
||||
const [exporting, setExporting] = useState(false)
|
||||
const [editOpen, setEditOpen] = useState(false)
|
||||
const [editDraft, setEditDraft] = useState<{
|
||||
practitioner: Practitioner
|
||||
animal: Animal
|
||||
owner: Owner
|
||||
} | null>(null)
|
||||
|
||||
function openEditInfos() {
|
||||
if (!report) return
|
||||
setEditDraft({
|
||||
practitioner: report.practitioner,
|
||||
animal: report.animal,
|
||||
owner: report.owner,
|
||||
})
|
||||
setEditOpen(true)
|
||||
}
|
||||
|
||||
function closeEditInfos() {
|
||||
setEditOpen(false)
|
||||
setEditDraft(null)
|
||||
}
|
||||
|
||||
function saveEditInfos() {
|
||||
if (!editDraft) return closeEditInfos()
|
||||
const name = editDraft.practitioner.name.trim()
|
||||
const animalName = editDraft.animal.name.trim()
|
||||
const ownerName = editDraft.owner.name.trim()
|
||||
if (!name || !animalName || !ownerName) return
|
||||
setPractitioner(editDraft.practitioner)
|
||||
setAnimal(editDraft.animal)
|
||||
setOwner(editDraft.owner)
|
||||
writeCachedPractitioner(editDraft.practitioner)
|
||||
closeEditInfos()
|
||||
}
|
||||
|
||||
function acknowledgeDisclaimer() {
|
||||
if (typeof sessionStorage !== 'undefined') {
|
||||
sessionStorage.setItem(DISCLAIMER_FLAG, '1')
|
||||
}
|
||||
setDisclaimer(null)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!report) navigate('/')
|
||||
}, [report, navigate])
|
||||
|
||||
useEffect(() => {
|
||||
window.scrollTo({ top: 0, left: 0, behavior: 'auto' })
|
||||
}, [])
|
||||
|
||||
const species = useMemo(
|
||||
() => (report ? getSpecies(report.animal.speciesId) : undefined),
|
||||
[report],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!species) return
|
||||
loadSvg(species.mainSvg).then((root) => setBones(parseSvgBones(root)))
|
||||
species.findings().then((m) => setFindings(m.default))
|
||||
|
||||
// Eagerly preload every detail SVG so observation zones imported
|
||||
// from a PDF (which can carry detail-popup boneIds without the user
|
||||
// ever re-opening the popup) resolve their labels and findings
|
||||
// pickers immediately on mount. Each fetch is independent — a 404
|
||||
// on one detail asset must not prevent the others from loading.
|
||||
Object.values(species.details).forEach((path) => {
|
||||
loadSvg(path)
|
||||
.then((root) => {
|
||||
const parsed = parseSvgBones(root)
|
||||
setDetailBones((prev) => mergeBones(prev, parsed))
|
||||
})
|
||||
.catch((err) => {
|
||||
console.warn(`EditorRoute: failed to preload detail SVG ${path}`, err)
|
||||
})
|
||||
})
|
||||
}, [species])
|
||||
|
||||
useEffect(() => {
|
||||
if (!findings) return
|
||||
if (typeof sessionStorage === 'undefined') return
|
||||
if (sessionStorage.getItem(DISCLAIMER_FLAG)) return
|
||||
setDisclaimer(findings.scope_disclaimer)
|
||||
}, [findings])
|
||||
|
||||
useEffect(() => {
|
||||
if (!detail) return
|
||||
let cancelled = false
|
||||
loadSvg(detail.src).then((root) => {
|
||||
if (cancelled) return
|
||||
const parsed = parseSvgBones(root)
|
||||
setDetailBones((prev) => mergeBones(prev, parsed))
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [detail])
|
||||
|
||||
const allBones = useMemo(() => {
|
||||
const m = new Map(bones)
|
||||
detailBones.forEach((b, id) => {
|
||||
if (!m.has(id)) m.set(id, b)
|
||||
})
|
||||
return m
|
||||
}, [bones, detailBones])
|
||||
|
||||
const activeObs =
|
||||
activeIndex >= 0 ? report?.observations[activeIndex] : undefined
|
||||
|
||||
const boneStates = useMemo<Map<string, BoneState>>(() => {
|
||||
const map = new Map<string, BoneState>()
|
||||
if (!report || activeIndex < 0) return map
|
||||
const active = report.observations[activeIndex]
|
||||
if (!active) return map
|
||||
active.zones.forEach((z) => {
|
||||
map.set(z.boneId, 'current')
|
||||
})
|
||||
return map
|
||||
}, [report, activeIndex])
|
||||
|
||||
function onToggleCard(index: number) {
|
||||
setActiveObservation(activeIndex === index ? -1 : index)
|
||||
}
|
||||
|
||||
/** Opens the detail-popup modal for a bone that carries data-anno-opens-detail. */
|
||||
function handleDetailOpen(bone: Bone, detailId: string, detailSrc: string) {
|
||||
setDetail({
|
||||
id: detailId,
|
||||
src: detailSrc,
|
||||
title: boneLabel(bone, locale, detailId),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* No expanded observation — auto-expand the most recent one (or the
|
||||
* first if no rows yet) so the click lands somewhere. Defers the actual
|
||||
* zone add to the next render where activeObs is set.
|
||||
*/
|
||||
function activateFallbackObservation(report: Report) {
|
||||
const fallbackIndex =
|
||||
report.observations.length > 0 ? report.observations.length - 1 : -1
|
||||
if (fallbackIndex < 0) return
|
||||
setActiveObservation(fallbackIndex)
|
||||
}
|
||||
|
||||
/**
|
||||
* Spine-zone behavior: always open VertebraPicker on click. Adds the
|
||||
* zone if missing; never toggles it off here (use the ✕ button).
|
||||
*/
|
||||
function handleSpineZone(
|
||||
activeObs: Observation,
|
||||
boneId: string,
|
||||
detailSourceId: string | undefined,
|
||||
existingIndex: number,
|
||||
) {
|
||||
let targetIndex = existingIndex
|
||||
if (existingIndex < 0) {
|
||||
const newZone: ObservationZone = {
|
||||
boneId,
|
||||
...(detailSourceId ? { detailSourceId } : {}),
|
||||
}
|
||||
const nextZones = [...activeObs.zones, newZone]
|
||||
targetIndex = nextZones.length - 1
|
||||
updateObservation(activeIndex, { ...activeObs, zones: nextZones })
|
||||
}
|
||||
setVertebraTarget(targetIndex)
|
||||
}
|
||||
|
||||
/** Bilateral zone: adding a side, or clearing both once left+right are set. */
|
||||
function handleBilateralZone(
|
||||
activeObs: Observation,
|
||||
boneId: string,
|
||||
detailSourceId: string | undefined,
|
||||
) {
|
||||
const sidesPresent = activeObs.zones
|
||||
.filter(
|
||||
(z) => z.boneId === boneId && z.detailSourceId === detailSourceId,
|
||||
)
|
||||
.map((z) => z.side)
|
||||
.filter(Boolean) as LateralSide[]
|
||||
|
||||
if (sidesPresent.includes('left') && sidesPresent.includes('right')) {
|
||||
const nextZones = activeObs.zones.filter(
|
||||
(z) => !(z.boneId === boneId && z.detailSourceId === detailSourceId),
|
||||
)
|
||||
updateObservation(activeIndex, { ...activeObs, zones: nextZones })
|
||||
return
|
||||
}
|
||||
|
||||
setLateralTarget({
|
||||
boneId,
|
||||
...(detailSourceId ? { detailSourceId } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
/** Plain zone: toggles it on the active observation. */
|
||||
function toggleZone(
|
||||
activeObs: Observation,
|
||||
boneId: string,
|
||||
detailSourceId: string | undefined,
|
||||
existingIndex: number,
|
||||
) {
|
||||
const newZone: ObservationZone = {
|
||||
boneId,
|
||||
...(detailSourceId ? { detailSourceId } : {}),
|
||||
}
|
||||
const nextZones =
|
||||
existingIndex >= 0
|
||||
? activeObs.zones.filter((_, k) => k !== existingIndex)
|
||||
: [...activeObs.zones, newZone]
|
||||
updateObservation(activeIndex, { ...activeObs, zones: nextZones })
|
||||
}
|
||||
|
||||
function onZoneClick(boneId: string, detailSourceId?: string) {
|
||||
if (!report) return
|
||||
const bone = bones.get(boneId) ?? detailBones.get(boneId)
|
||||
if (!bone) return
|
||||
|
||||
if (bone.opensDetail && species?.details[bone.opensDetail]) {
|
||||
handleDetailOpen(bone, bone.opensDetail, species.details[bone.opensDetail])
|
||||
return
|
||||
}
|
||||
|
||||
if (!activeObs || activeIndex < 0) {
|
||||
activateFallbackObservation(report)
|
||||
return
|
||||
}
|
||||
|
||||
const matches = (z: ObservationZone) =>
|
||||
z.boneId === boneId && z.detailSourceId === detailSourceId
|
||||
const existingIndex = activeObs.zones.findIndex(matches)
|
||||
|
||||
if (bone.special === 'vertebral-precision') {
|
||||
handleSpineZone(activeObs, boneId, detailSourceId, existingIndex)
|
||||
return
|
||||
}
|
||||
|
||||
if (bone.lateral === 'bilateral') {
|
||||
handleBilateralZone(activeObs, boneId, detailSourceId)
|
||||
return
|
||||
}
|
||||
|
||||
toggleZone(activeObs, boneId, detailSourceId, existingIndex)
|
||||
}
|
||||
|
||||
async function onExport() {
|
||||
if (!report) return
|
||||
setExporting(true)
|
||||
try {
|
||||
const bytes = await exportReportToPdf(report, { locale })
|
||||
const blob = new Blob([bytes as BlobPart], { type: 'application/pdf' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `bilan-${report.animal.name}-${report.date}.pdf`
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
} catch (err) {
|
||||
console.error('PDF export failed', err)
|
||||
window.alert(t('editor.export_failed'))
|
||||
} finally {
|
||||
setExporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!report || !species) return null
|
||||
|
||||
return (
|
||||
<main className="min-h-screen flex flex-col">
|
||||
<ReportHeader report={report} onEditInfos={openEditInfos} />
|
||||
<div className="flex-1 grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-4 sm:gap-6 p-4 sm:p-6">
|
||||
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden max-h-[55vh] lg:max-h-none">
|
||||
<AnatomyCanvas
|
||||
src={species.mainSvg}
|
||||
boneStates={boneStates}
|
||||
onZoneClick={(id) => onZoneClick(id)}
|
||||
/>
|
||||
</section>
|
||||
<section className="space-y-4 sm:space-y-6">
|
||||
<ObservationList
|
||||
observations={report.observations}
|
||||
activeIndex={activeIndex}
|
||||
onToggle={onToggleCard}
|
||||
onAdd={addObservation}
|
||||
onDelete={removeObservation}
|
||||
onMoveUp={moveObservationUp}
|
||||
onMoveDown={moveObservationDown}
|
||||
bones={allBones}
|
||||
findings={findings}
|
||||
onChange={(i, next: Observation) => updateObservation(i, next)}
|
||||
onOpenVertebraPicker={(_i, zoneIndex) =>
|
||||
setVertebraTarget(zoneIndex)
|
||||
}
|
||||
onRemoveZone={(i, zoneIndex) => {
|
||||
const obs = report.observations[i]
|
||||
if (!obs) return
|
||||
const zones = obs.zones.filter((_, k) => k !== zoneIndex)
|
||||
updateObservation(i, { ...obs, zones })
|
||||
}}
|
||||
/>
|
||||
<ConclusionPanel
|
||||
conclusion={report.conclusion}
|
||||
recommendations={report.recommendations}
|
||||
nextAppointment={report.nextAppointment}
|
||||
onChangeConclusion={setConclusion}
|
||||
onChangeRecommendations={setRecommendations}
|
||||
onChangeNextAppointment={setNextAppointment}
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={onExport} disabled={exporting}>
|
||||
{exporting ? t('editor.exporting') : t('editor.export')}
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{detail && (
|
||||
<DetailModal
|
||||
open
|
||||
onClose={() => setDetail(null)}
|
||||
detailSrc={detail.src}
|
||||
detailId={detail.id}
|
||||
title={`${t('editor.detail_title_prefix')}${detail.title}`}
|
||||
boneStates={boneStates}
|
||||
onZoneClick={(id, did) => onZoneClick(id, did)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{editDraft && (
|
||||
<Dialog
|
||||
open={editOpen}
|
||||
onClose={closeEditInfos}
|
||||
title={t('editor.edit_dialog_title')}
|
||||
size="lg"
|
||||
>
|
||||
<div className="space-y-8">
|
||||
<PractitionerForm
|
||||
value={editDraft.practitioner}
|
||||
onChange={(next) =>
|
||||
setEditDraft((d) => (d ? { ...d, practitioner: next } : d))
|
||||
}
|
||||
/>
|
||||
<AnimalForm
|
||||
animal={editDraft.animal}
|
||||
owner={editDraft.owner}
|
||||
onChangeAnimal={(next) =>
|
||||
setEditDraft((d) => (d ? { ...d, animal: next } : d))
|
||||
}
|
||||
onChangeOwner={(next) =>
|
||||
setEditDraft((d) => (d ? { ...d, owner: next } : d))
|
||||
}
|
||||
/>
|
||||
<div className="flex gap-3 justify-end pt-2 border-t border-[var(--color-border)]">
|
||||
<Button variant="ghost" onClick={closeEditInfos}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={saveEditInfos}
|
||||
disabled={
|
||||
!editDraft.practitioner.name.trim() ||
|
||||
!editDraft.animal.name.trim() ||
|
||||
!editDraft.owner.name.trim()
|
||||
}
|
||||
>
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
)}
|
||||
|
||||
{disclaimer && (
|
||||
<Dialog
|
||||
open
|
||||
onClose={acknowledgeDisclaimer}
|
||||
title={t('editor.disclaimer_title')}
|
||||
size="md"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-[var(--color-ink)]">{disclaimer}</p>
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={acknowledgeDisclaimer}>{t('common.understood')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
)}
|
||||
|
||||
{vertebraTarget !== null &&
|
||||
activeObs &&
|
||||
activeObs.zones[vertebraTarget] && (
|
||||
<VertebraPicker
|
||||
open
|
||||
onClose={() => setVertebraTarget(null)}
|
||||
onConfirm={(vertebrae) => {
|
||||
const fresh =
|
||||
useReportStore.getState().report?.observations[activeIndex]
|
||||
if (!fresh?.zones[vertebraTarget]) {
|
||||
setVertebraTarget(null)
|
||||
return
|
||||
}
|
||||
// Picker edits every region at once: reconcile all spine zones —
|
||||
// spawn newly picked regions, prune emptied ones, keep the rest.
|
||||
const next = syncSpineZones(fresh.zones, vertebrae, bones)
|
||||
updateObservation(activeIndex, { ...fresh, zones: next })
|
||||
setVertebraTarget(null)
|
||||
}}
|
||||
initial={collectSpineVertebrae(
|
||||
activeObs.zones,
|
||||
bones,
|
||||
activeObs.zones[vertebraTarget].boneId,
|
||||
)}
|
||||
formula={species.vertebralFormula}
|
||||
title={`${t('vertebra.title_prefix')}${boneLabel(
|
||||
bones.get(activeObs.zones[vertebraTarget].boneId),
|
||||
locale,
|
||||
'',
|
||||
)}`}
|
||||
initialRegion={(() => {
|
||||
const b = bones.get(activeObs.zones[vertebraTarget].boneId)
|
||||
return regionFromLabel(b?.fr ?? '') ?? regionFromLabel(b?.en ?? '')
|
||||
})()}
|
||||
/>
|
||||
)}
|
||||
|
||||
{lateralTarget && activeObs && (
|
||||
<LateralityPicker
|
||||
open
|
||||
onClose={() => setLateralTarget(null)}
|
||||
title={boneLabel(
|
||||
allBones.get(lateralTarget.boneId),
|
||||
locale,
|
||||
lateralTarget.boneId,
|
||||
)}
|
||||
existingSides={
|
||||
activeObs.zones
|
||||
.filter(
|
||||
(z) =>
|
||||
z.boneId === lateralTarget.boneId &&
|
||||
z.detailSourceId === lateralTarget.detailSourceId &&
|
||||
z.side,
|
||||
)
|
||||
.map((z) => z.side!) as LateralSide[]
|
||||
}
|
||||
onSelect={(sides) => {
|
||||
const fresh =
|
||||
useReportStore.getState().report?.observations[activeIndex]
|
||||
if (!fresh) {
|
||||
setLateralTarget(null)
|
||||
return
|
||||
}
|
||||
const newSideZones = sides
|
||||
.filter(
|
||||
(side) =>
|
||||
!fresh.zones.some(
|
||||
(z) =>
|
||||
z.boneId === lateralTarget.boneId &&
|
||||
z.detailSourceId === lateralTarget.detailSourceId &&
|
||||
z.side === side,
|
||||
),
|
||||
)
|
||||
.map((side) => ({
|
||||
boneId: lateralTarget.boneId,
|
||||
...(lateralTarget.detailSourceId
|
||||
? { detailSourceId: lateralTarget.detailSourceId }
|
||||
: {}),
|
||||
side,
|
||||
}))
|
||||
const nextZones = [...fresh.zones, ...newSideZones]
|
||||
updateObservation(activeIndex, { ...fresh, zones: nextZones })
|
||||
setLateralTarget(null)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Link } from 'react-router-dom'
|
||||
import AppHeader from '@/components/brand/AppHeader'
|
||||
import Card from '@/components/ui/Card'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export default function EditorsRoute() {
|
||||
const t = useT()
|
||||
|
||||
return (
|
||||
<main className="flex-1 flex flex-col">
|
||||
<AppHeader />
|
||||
<section className="flex-1 grid place-items-center px-4 sm:px-6">
|
||||
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
|
||||
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
|
||||
<h2 className="font-serif text-xl sm:text-2xl">{t('editors.svg.title')}</h2>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editors.svg.description')}
|
||||
</p>
|
||||
<Link
|
||||
to="/svg-editor"
|
||||
className="inline-block rounded-lg bg-[var(--color-accent)] px-5 py-2 text-sm font-medium text-white hover:bg-[var(--color-accent-strong)] transition-colors"
|
||||
>
|
||||
{t('editors.svg.cta')}
|
||||
</Link>
|
||||
</Card>
|
||||
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
|
||||
<h2 className="font-serif text-xl sm:text-2xl">{t('editors.pathology.title')}</h2>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('editors.pathology.description')}
|
||||
</p>
|
||||
<a
|
||||
href="/pathology-editor.html"
|
||||
className="inline-block rounded-lg bg-[var(--color-accent)] px-5 py-2 text-sm font-medium text-white hover:bg-[var(--color-accent-strong)] transition-colors"
|
||||
>
|
||||
{t('editors.pathology.cta')}
|
||||
</a>
|
||||
</Card>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useRef, useState } from 'react'
|
||||
import AppHeader from '@/components/brand/AppHeader'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Card from '@/components/ui/Card'
|
||||
import { importReportFromPdf, ImportError } from '@/pdf/import'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export default function HomeRoute() {
|
||||
const navigate = useNavigate()
|
||||
const fileRef = useRef<HTMLInputElement | null>(null)
|
||||
const hydrate = useReportStore((s) => s.hydrateReport)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const t = useT()
|
||||
|
||||
async function onPickFile(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0]
|
||||
if (!file) return
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
const bytes = new Uint8Array(await file.arrayBuffer())
|
||||
const report = await importReportFromPdf(bytes)
|
||||
hydrate(report)
|
||||
navigate('/editor')
|
||||
} catch (err) {
|
||||
if (err instanceof ImportError) {
|
||||
if (err.kind === 'incompatible_version') {
|
||||
setError(
|
||||
t('home.import.error_incompatible_version').replace(
|
||||
'{version}',
|
||||
String(err.foundVersion ?? '?'),
|
||||
),
|
||||
)
|
||||
} else if (err.kind === 'invalid_pdf') {
|
||||
setError(t('home.import.error_invalid_pdf'))
|
||||
} else {
|
||||
setError(t('home.import.error_no_attachment'))
|
||||
}
|
||||
} else {
|
||||
setError(t('home.import.error_generic'))
|
||||
}
|
||||
} finally {
|
||||
setBusy(false)
|
||||
if (fileRef.current) fileRef.current.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex-1 flex flex-col">
|
||||
<AppHeader />
|
||||
<section className="flex-1 grid place-items-center px-4 sm:px-6">
|
||||
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
|
||||
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
|
||||
<h2 className="font-serif text-xl sm:text-2xl">{t('home.new_report.title')}</h2>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">{t('home.new_report.description')}</p>
|
||||
<Button onClick={() => navigate('/new')} size="lg">{t('home.new_report.cta')}</Button>
|
||||
</Card>
|
||||
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
|
||||
<h2 className="font-serif text-xl sm:text-2xl">{t('home.import.title')}</h2>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">{t('home.import.description')}</p>
|
||||
<input ref={fileRef} type="file" accept="application/pdf,.pdf" className="hidden" onChange={onPickFile} />
|
||||
<Button variant="secondary" size="lg" onClick={() => fileRef.current?.click()} disabled={busy}>
|
||||
{busy ? t('home.import.loading') : t('home.import.cta')}
|
||||
</Button>
|
||||
{error && <p className="text-sm text-red-700">{error}</p>}
|
||||
</Card>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import PractitionerForm from '@/components/report/PractitionerForm'
|
||||
import AnimalForm from '@/components/report/AnimalForm'
|
||||
import AppHeader from '@/components/brand/AppHeader'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Label from '@/components/ui/Label'
|
||||
import { todayIso } from '@/lib/dates'
|
||||
import { readCachedPractitioner, writeCachedPractitioner } from '@/state/practitionerCache'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export default function NewReportRoute() {
|
||||
const navigate = useNavigate()
|
||||
const initReport = useReportStore((s) => s.initReport)
|
||||
const t = useT()
|
||||
|
||||
const [practitioner, setPractitioner] = useState({ name: '' })
|
||||
const [animal, setAnimal] = useState({ speciesId: 'equine', name: '' })
|
||||
const [owner, setOwner] = useState({ name: '' })
|
||||
const [date, setDate] = useState(todayIso())
|
||||
|
||||
useEffect(() => {
|
||||
const cached = readCachedPractitioner()
|
||||
if (cached) setPractitioner(cached)
|
||||
}, [])
|
||||
|
||||
const canSubmit = practitioner.name.trim() && animal.name.trim() && owner.name.trim()
|
||||
|
||||
function submit() {
|
||||
if (!canSubmit) return
|
||||
writeCachedPractitioner(practitioner)
|
||||
initReport({
|
||||
date,
|
||||
practitioner,
|
||||
animal,
|
||||
owner,
|
||||
observations: [],
|
||||
conclusion: '',
|
||||
recommendations: '',
|
||||
})
|
||||
navigate('/editor')
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="min-h-screen">
|
||||
<AppHeader />
|
||||
<div className="max-w-3xl mx-auto px-4 sm:px-6 py-6 sm:py-8 space-y-6 sm:space-y-8">
|
||||
<h1 className="font-serif text-2xl sm:text-3xl">{t('new_report.title')}</h1>
|
||||
<div>
|
||||
<Label htmlFor="date">{t('new_report.date_label')}</Label>
|
||||
<Input id="date" type="date" value={date} onChange={(e) => setDate(e.target.value)} />
|
||||
</div>
|
||||
<PractitionerForm value={practitioner} onChange={setPractitioner} />
|
||||
<AnimalForm animal={animal} owner={owner} onChangeAnimal={setAnimal} onChangeOwner={setOwner} />
|
||||
<div className="flex gap-3 justify-end">
|
||||
<Button variant="ghost" onClick={() => navigate('/')}>{t('common.cancel')}</Button>
|
||||
<Button disabled={!canSubmit} onClick={submit}>{t('new_report.submit')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import Button from '@/components/ui/Button'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export default function NotFoundRoute() {
|
||||
const navigate = useNavigate()
|
||||
const t = useT()
|
||||
return (
|
||||
<main className="min-h-screen grid place-items-center">
|
||||
<div className="text-center space-y-4">
|
||||
<h1 className="font-serif text-4xl">{t('not_found.title')}</h1>
|
||||
<p className="text-[var(--color-ink-muted)]">{t('not_found.description')}</p>
|
||||
<Button onClick={() => navigate('/')}>{t('common.back_to_home')}</Button>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,34 @@
|
||||
import { Link } from 'react-router-dom'
|
||||
import Brand from './Brand'
|
||||
import LanguageSwitcher from './LanguageSwitcher'
|
||||
import { useConfig } from '@/app/providers/ConfigProvider'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
interface AppHeaderProps {
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
export default function AppHeader({ children }: AppHeaderProps) {
|
||||
const cfg = useConfig()
|
||||
const t = useT()
|
||||
return (
|
||||
<header className="px-3 sm:px-6 py-2 sm:py-3 border-b border-[var(--color-border)] flex items-center justify-between bg-[var(--color-surface)]">
|
||||
<div className="flex items-center gap-3">
|
||||
<Link
|
||||
to="/"
|
||||
aria-label={t('common.home')}
|
||||
className="rounded-md px-1 py-0.5 hover:opacity-80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
|
||||
>
|
||||
<Brand size="lg" />
|
||||
</Link>
|
||||
<span className="text-sm text-[var(--color-ink-muted)] hidden sm:inline">
|
||||
{cfg.tagline}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 sm:gap-4">
|
||||
{children}
|
||||
<LanguageSwitcher />
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useConfig } from '@/app/providers/ConfigProvider'
|
||||
|
||||
const HEIGHT = { sm: 'h-7', md: 'h-9', lg: 'h-11' } as const
|
||||
|
||||
export default function Brand({ size = 'md' }: { size?: 'sm' | 'md' | 'lg' }) {
|
||||
const { brandName } = useConfig()
|
||||
return (
|
||||
<img
|
||||
src="/logo-horizontal.svg"
|
||||
alt={brandName}
|
||||
className={`${HEIGHT[size]} w-auto`}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Link } from 'react-router-dom'
|
||||
import { useConfig } from '@/app/providers/ConfigProvider'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export default function Footer() {
|
||||
const cfg = useConfig()
|
||||
const t = useT()
|
||||
const year = new Date().getFullYear()
|
||||
return (
|
||||
<footer className="mt-8 sm:mt-12 border-t border-neutral-200 bg-neutral-50 py-4 sm:py-6 text-center text-xs sm:text-sm text-neutral-600">
|
||||
<p className="mb-3">
|
||||
© {year} {cfg.footerName}. {t('footer.all_rights_reserved')}{' '}
|
||||
<span className="text-neutral-300">·</span>{' '}
|
||||
<Link
|
||||
to="/editors"
|
||||
className="text-[var(--color-accent)] hover:text-[var(--color-accent-strong)] transition-colors"
|
||||
>
|
||||
{t('footer.editors')}
|
||||
</Link>
|
||||
</p>
|
||||
<div className="flex flex-wrap items-center justify-center gap-2 sm:gap-4">
|
||||
<span className="flex items-center gap-2">
|
||||
<span>{t('footer.powered_by')}</span>
|
||||
<a
|
||||
href="https://zenquality.fr"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label="ZenQuality"
|
||||
className="inline-flex items-center"
|
||||
>
|
||||
<img
|
||||
src="https://zenquality.fr/assets/logo-horizontal-1024.png"
|
||||
alt="ZenQuality"
|
||||
className="h-6 w-auto"
|
||||
loading="lazy"
|
||||
/>
|
||||
</a>
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span>{t('footer.in_partnership')}</span>
|
||||
<a
|
||||
href="https://www.instagram.com/paws.iin.harmony"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-[var(--color-accent)] hover:text-[var(--color-accent-strong)] transition-colors font-medium"
|
||||
>
|
||||
<img
|
||||
src="/Paws_in_harmony.svg"
|
||||
alt="Paws in Harmony"
|
||||
className="h-6 w-auto inline-block align-middle"
|
||||
/>
|
||||
</a>
|
||||
</span>
|
||||
</div>
|
||||
</footer>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
|
||||
const ITEMS: { value: Locale; labelKey: string; ariaKey: string }[] = [
|
||||
{ value: 'fr', labelKey: 'lang.fr', ariaKey: 'lang.switch_to_fr' },
|
||||
{ value: 'en', labelKey: 'lang.en', ariaKey: 'lang.switch_to_en' },
|
||||
]
|
||||
|
||||
export default function LanguageSwitcher() {
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const setLocale = useLocaleStore((s) => s.setLocale)
|
||||
const t = useT()
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
aria-label={t('lang.group_label')}
|
||||
className="inline-flex rounded-full border border-[var(--color-border)] overflow-hidden text-xs font-medium"
|
||||
>
|
||||
{ITEMS.map((item) => {
|
||||
const active = locale === item.value
|
||||
return (
|
||||
<button
|
||||
key={item.value}
|
||||
type="button"
|
||||
aria-label={t(item.ariaKey)}
|
||||
aria-pressed={active}
|
||||
onClick={() => setLocale(item.value)}
|
||||
className={[
|
||||
'px-2.5 py-1 transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]',
|
||||
active
|
||||
? 'bg-[var(--color-accent)] text-white'
|
||||
: 'text-[var(--color-ink)] hover:bg-[var(--color-surface-strong)]',
|
||||
].join(' ')}
|
||||
>
|
||||
{t(item.labelKey)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { loadSvg } from '@/anatomy/svgLoader'
|
||||
import {
|
||||
getBoneIdFromEvent,
|
||||
getAnnotatedElement,
|
||||
} from '@/anatomy/svgConvention'
|
||||
import type { BoneState } from '@/anatomy/types'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
|
||||
|
||||
export interface AnatomyCanvasProps {
|
||||
src: string
|
||||
boneStates: Map<string, BoneState>
|
||||
onZoneClick: (boneId: string) => void
|
||||
className?: string
|
||||
}
|
||||
|
||||
export default function AnatomyCanvas({
|
||||
src,
|
||||
boneStates,
|
||||
onZoneClick,
|
||||
className = '',
|
||||
}: AnatomyCanvasProps) {
|
||||
const wrapperRef = useRef<HTMLDivElement | null>(null)
|
||||
const svgRef = useRef<HTMLDivElement | null>(null)
|
||||
const tooltipRef = useRef<HTMLDivElement | null>(null)
|
||||
const [loadedSrc, setLoadedSrc] = useState<string | null>(null)
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
const c = svgRef.current
|
||||
if (!c) return
|
||||
c.replaceChildren()
|
||||
setLoadedSrc(null)
|
||||
loadSvg(src).then((root) => {
|
||||
if (cancelled || !c) return
|
||||
c.appendChild(root)
|
||||
setLoadedSrc(src)
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, [src])
|
||||
|
||||
useEffect(() => {
|
||||
const c = svgRef.current
|
||||
if (!c) return
|
||||
const onClick = (e: Event) => {
|
||||
const id = getBoneIdFromEvent(e)
|
||||
if (id) onZoneClick(id)
|
||||
}
|
||||
c.addEventListener('click', onClick)
|
||||
return () => c.removeEventListener('click', onClick)
|
||||
}, [onZoneClick])
|
||||
|
||||
useEffect(() => {
|
||||
const c = svgRef.current
|
||||
if (!c || loadedSrc !== src) return
|
||||
const all = c.querySelectorAll<Element>('[data-anno-id]')
|
||||
all.forEach((el) => {
|
||||
const id = el.getAttribute('data-anno-id') as string
|
||||
const state = boneStates.get(id)
|
||||
if (state && state !== 'default') el.setAttribute('data-state', state)
|
||||
else el.removeAttribute('data-state')
|
||||
})
|
||||
}, [boneStates, loadedSrc, src])
|
||||
|
||||
const showTooltip = useCallback(
|
||||
(el: Element, x: number, y: number) => {
|
||||
const tip = tooltipRef.current
|
||||
if (!tip) return
|
||||
const fr = el.getAttribute('data-anno-name-fr') ?? ''
|
||||
const en = el.getAttribute('data-anno-name-en') ?? ''
|
||||
const label = pickLocaleLabel(fr, en, locale)
|
||||
if (!label) { tip.style.opacity = '0'; return }
|
||||
tip.textContent = label
|
||||
tip.style.opacity = '1'
|
||||
tip.style.left = `${x + 12}px`
|
||||
tip.style.top = `${y - 8}px`
|
||||
},
|
||||
[locale],
|
||||
)
|
||||
|
||||
const hideTooltip = useCallback(() => {
|
||||
const tip = tooltipRef.current
|
||||
if (tip) tip.style.opacity = '0'
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const c = svgRef.current
|
||||
if (!c || loadedSrc !== src) return
|
||||
const onMove = (e: MouseEvent) => {
|
||||
const el = getAnnotatedElement(e)
|
||||
if (el && !el.hasAttribute('data-anno-opens-detail')) {
|
||||
const w = wrapperRef.current
|
||||
if (!w) return
|
||||
const rect = w.getBoundingClientRect()
|
||||
showTooltip(el, e.clientX - rect.left, e.clientY - rect.top)
|
||||
} else {
|
||||
hideTooltip()
|
||||
}
|
||||
}
|
||||
const onLeave = () => hideTooltip()
|
||||
c.addEventListener('mousemove', onMove)
|
||||
c.addEventListener('mouseleave', onLeave)
|
||||
return () => {
|
||||
c.removeEventListener('mousemove', onMove)
|
||||
c.removeEventListener('mouseleave', onLeave)
|
||||
}
|
||||
}, [loadedSrc, src, showTooltip, hideTooltip])
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="anatomy-canvas"
|
||||
ref={wrapperRef}
|
||||
className={`svg-canvas relative w-full h-full ${className}`}
|
||||
>
|
||||
<div ref={svgRef} className="w-full h-full [&>svg]:max-w-full [&>svg]:max-h-full [&>svg]:mx-auto" />
|
||||
<div
|
||||
ref={tooltipRef}
|
||||
className="zone-tooltip"
|
||||
style={{ opacity: 0 }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import AnatomyCanvas from './AnatomyCanvas'
|
||||
import type { BoneState } from '@/anatomy/types'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface DetailModalProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
detailSrc: string
|
||||
detailId: string
|
||||
title: string
|
||||
boneStates: Map<string, BoneState>
|
||||
onZoneClick: (boneId: string, detailId: string) => void
|
||||
}
|
||||
|
||||
export default function DetailModal({
|
||||
open,
|
||||
onClose,
|
||||
detailSrc,
|
||||
detailId,
|
||||
title,
|
||||
boneStates,
|
||||
onZoneClick,
|
||||
}: DetailModalProps) {
|
||||
const t = useT()
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} title={title} size="xl">
|
||||
<div className="aspect-[4/3] w-full">
|
||||
<AnatomyCanvas
|
||||
src={detailSrc}
|
||||
boneStates={boneStates}
|
||||
onZoneClick={(id) => onZoneClick(id, detailId)}
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-4 text-sm text-[var(--color-ink-muted)]">
|
||||
{t('detail.click_to_add')}
|
||||
</p>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { motion } from 'motion/react'
|
||||
import type {
|
||||
FindingNode,
|
||||
ZoneFindings,
|
||||
} from '@/domain/schema/findings'
|
||||
import type { Finding, LateralSide } from '@/domain/schema/observation'
|
||||
import Button from '@/components/ui/Button'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
const levelVariants = {
|
||||
enter: (dir: 1 | -1) => ({ opacity: 0, x: dir * 32 }),
|
||||
center: { opacity: 1, x: 0 },
|
||||
}
|
||||
|
||||
export interface FindingsTreePickerProps {
|
||||
zoneId: string
|
||||
tree: ZoneFindings
|
||||
side?: LateralSide
|
||||
selected: Finding[]
|
||||
onChange: (next: Finding[]) => void
|
||||
}
|
||||
|
||||
function isLeaf(node: FindingNode): boolean {
|
||||
return !node.children || node.children.length === 0
|
||||
}
|
||||
|
||||
function samePath(a: string[], b: string[]): boolean {
|
||||
if (a.length !== b.length) return false
|
||||
for (let i = 0; i < a.length; i += 1) {
|
||||
if (a[i] !== b[i]) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function pathStartsWith(full: string[], prefix: string[]): boolean {
|
||||
if (full.length < prefix.length) return false
|
||||
for (let i = 0; i < prefix.length; i += 1) {
|
||||
if (full[i] !== prefix[i]) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function findNode(
|
||||
categories: FindingNode[],
|
||||
path: string[],
|
||||
): FindingNode | undefined {
|
||||
let nodes: FindingNode[] = categories
|
||||
let node: FindingNode | undefined
|
||||
for (const segment of path) {
|
||||
node = nodes.find((n) => n.id === segment)
|
||||
if (!node) return undefined
|
||||
nodes = node.children ?? []
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
export default function FindingsTreePicker({
|
||||
zoneId,
|
||||
tree,
|
||||
side,
|
||||
selected,
|
||||
onChange,
|
||||
}: FindingsTreePickerProps) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const nameOf = (node: { name_fr: string; name_en: string }) =>
|
||||
locale === 'en' ? node.name_en : node.name_fr
|
||||
const descOf = (node: { description_fr?: string; description_en?: string }) =>
|
||||
locale === 'en' ? node.description_en : node.description_fr
|
||||
|
||||
const [path, setPath] = useState<string[]>([])
|
||||
const [direction, setDirection] = useState<1 | -1>(1)
|
||||
|
||||
function goInto(nodePath: string[]) {
|
||||
setDirection(1)
|
||||
setPath(nodePath)
|
||||
}
|
||||
function goBack() {
|
||||
setDirection(-1)
|
||||
setPath(path.slice(0, -1))
|
||||
}
|
||||
function goToDepth(depth: number) {
|
||||
setDirection(depth >= path.length ? 1 : -1)
|
||||
setPath(path.slice(0, depth))
|
||||
}
|
||||
|
||||
const currentNodes = useMemo<FindingNode[]>(() => {
|
||||
if (path.length === 0) return tree.categories
|
||||
const node = findNode(tree.categories, path)
|
||||
return node?.children ?? []
|
||||
}, [tree, path])
|
||||
|
||||
const focusedNode = useMemo(
|
||||
() => (path.length === 0 ? undefined : findNode(tree.categories, path)),
|
||||
[tree, path],
|
||||
)
|
||||
|
||||
const breadcrumb = useMemo<{ label: string; depth: number }[]>(() => {
|
||||
const pick = (z: { name_fr: string; name_en: string }) =>
|
||||
locale === 'en' ? z.name_en : z.name_fr
|
||||
const crumbs: { label: string; depth: number }[] = [
|
||||
{ label: pick(tree), depth: 0 },
|
||||
]
|
||||
let nodes: FindingNode[] = tree.categories
|
||||
path.forEach((seg, i) => {
|
||||
const n = nodes.find((x) => x.id === seg)
|
||||
if (n) {
|
||||
crumbs.push({ label: pick(n), depth: i + 1 })
|
||||
nodes = n.children ?? []
|
||||
}
|
||||
})
|
||||
return crumbs
|
||||
}, [tree, path, locale])
|
||||
|
||||
function matchesSide(f: Finding): boolean {
|
||||
return f.zoneId === zoneId && f.side === side
|
||||
}
|
||||
|
||||
function isLeafSelected(leafPath: string[]): boolean {
|
||||
return selected.some(
|
||||
(f) => matchesSide(f) && samePath(f.path, leafPath),
|
||||
)
|
||||
}
|
||||
|
||||
function countSelectedUnder(nodePath: string[]): number {
|
||||
let n = 0
|
||||
for (const f of selected) {
|
||||
if (!matchesSide(f)) continue
|
||||
if (!pathStartsWith(f.path, nodePath)) continue
|
||||
n += 1
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
function toggleLeaf(leafPath: string[], leaf: FindingNode) {
|
||||
if (isLeafSelected(leafPath)) {
|
||||
onChange(
|
||||
selected.filter(
|
||||
(f) => !(matchesSide(f) && samePath(f.path, leafPath)),
|
||||
),
|
||||
)
|
||||
return
|
||||
}
|
||||
const next: Finding = {
|
||||
zoneId,
|
||||
path: leafPath,
|
||||
labelFrSnapshot: leaf.name_fr,
|
||||
labelEnSnapshot: leaf.name_en,
|
||||
}
|
||||
if (leaf.requires_vet_referral) next.requiresVetReferral = true
|
||||
if (side) next.side = side
|
||||
onChange([...selected, next])
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-wrap items-center gap-1 text-xs text-[var(--color-ink-muted)]">
|
||||
{breadcrumb.map((c, i) => {
|
||||
const isLast = i === breadcrumb.length - 1
|
||||
return (
|
||||
<span key={`${c.label}-${i}`} className="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => goToDepth(c.depth)}
|
||||
disabled={isLast}
|
||||
className={
|
||||
isLast
|
||||
? 'text-[var(--color-ink)] font-medium'
|
||||
: 'underline text-[var(--color-accent-strong)]'
|
||||
}
|
||||
>
|
||||
{c.label}
|
||||
</button>
|
||||
{!isLast && <span aria-hidden="true">›</span>}
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{focusedNode && descOf(focusedNode) && (
|
||||
<p className="text-xs italic text-[var(--color-ink-muted)]">
|
||||
{descOf(focusedNode)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{path.length > 0 && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={goBack}
|
||||
aria-label={t('findings.back_to_parent')}
|
||||
>
|
||||
{t('findings.back')}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<motion.ul
|
||||
key={path.join('/') || '__root__'}
|
||||
custom={direction}
|
||||
variants={levelVariants}
|
||||
initial="enter"
|
||||
animate="center"
|
||||
transition={{ duration: 0.22, ease: 'easeOut' }}
|
||||
style={{ willChange: 'transform, opacity' }}
|
||||
className="space-y-1.5 max-h-64 overflow-auto pr-1"
|
||||
>
|
||||
{currentNodes.length === 0 ? (
|
||||
<li className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('findings.no_options')}
|
||||
</li>
|
||||
) : (
|
||||
currentNodes.map((node) => {
|
||||
const nodePath = [...path, node.id]
|
||||
if (isLeaf(node)) {
|
||||
const checked = isLeafSelected(nodePath)
|
||||
const nodeLabel = nameOf(node)
|
||||
const nodeDesc = descOf(node)
|
||||
return (
|
||||
<li key={node.id}>
|
||||
<label className="flex items-start gap-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={() => toggleLeaf(nodePath, node)}
|
||||
className="mt-1 accent-[var(--color-accent)]"
|
||||
aria-label={nodeLabel}
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-[var(--color-ink)]">
|
||||
{nodeLabel}
|
||||
</span>
|
||||
{node.requires_vet_referral && (
|
||||
<span
|
||||
title={t('findings.vet_referral')}
|
||||
aria-label={t('findings.vet_referral')}
|
||||
className="text-[var(--color-danger)]"
|
||||
>
|
||||
⚠
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{nodeDesc && (
|
||||
<div className="text-xs text-[var(--color-ink-muted)]">
|
||||
{nodeDesc}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</label>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
const selectedCount = countSelectedUnder(nodePath)
|
||||
const nodeLabel = nameOf(node)
|
||||
const selectedAria = `${selectedCount} ${
|
||||
selectedCount > 1
|
||||
? t('findings.selected_plural')
|
||||
: t('findings.selected_singular')
|
||||
}`
|
||||
return (
|
||||
<li key={node.id}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => goInto(nodePath)}
|
||||
className="flex items-center justify-between w-full text-left text-sm px-2 py-1.5 rounded hover:bg-[var(--color-surface-strong)] text-[var(--color-ink)]"
|
||||
aria-label={`${t('findings.open')} ${nodeLabel}`}
|
||||
>
|
||||
<span className="flex items-center gap-2">
|
||||
<span>{nodeLabel}</span>
|
||||
{selectedCount > 0 && (
|
||||
<span
|
||||
aria-label={selectedAria}
|
||||
className="inline-flex items-center justify-center min-w-[20px] h-[20px] px-1.5 rounded-full text-[11px] font-semibold bg-[var(--color-accent)] text-white"
|
||||
>
|
||||
{selectedCount}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span aria-hidden="true" className="text-[var(--color-ink-muted)]">
|
||||
›
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</motion.ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useState } from 'react'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Badge from '@/components/ui/Badge'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface FreeTextFindingInputProps {
|
||||
items: string[]
|
||||
onChange: (next: string[]) => void
|
||||
}
|
||||
|
||||
export default function FreeTextFindingInput({
|
||||
items,
|
||||
onChange,
|
||||
}: FreeTextFindingInputProps) {
|
||||
const [v, setV] = useState('')
|
||||
const t = useT()
|
||||
|
||||
function add() {
|
||||
const trimmed = v.trim()
|
||||
if (!trimmed) return
|
||||
onChange([...items, trimmed])
|
||||
setV('')
|
||||
}
|
||||
|
||||
function remove(i: number) {
|
||||
onChange(items.filter((_, k) => k !== i))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={v}
|
||||
onChange={(e) => setV(e.target.value)}
|
||||
placeholder={t('observation.free_placeholder')}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
add()
|
||||
}
|
||||
}}
|
||||
aria-label={t('observation.free_aria')}
|
||||
/>
|
||||
<Button onClick={add} variant="secondary">
|
||||
{t('common.add')}
|
||||
</Button>
|
||||
</div>
|
||||
{items.length > 0 && (
|
||||
<ul className="flex flex-wrap gap-2">
|
||||
{items.map((it, i) => (
|
||||
<li key={`${it}-${i}`}>
|
||||
<Badge tone="accent" className="gap-1">
|
||||
{it}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`${t('observation.remove_zone')} ${it}`}
|
||||
onClick={() => remove(i)}
|
||||
className="ml-1 text-[var(--color-accent-strong)] hover:text-[var(--color-danger)]"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</Badge>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import Button from '@/components/ui/Button'
|
||||
import type { LateralSide } from '@/domain/schema/observation'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface LateralityPickerProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onSelect: (sides: LateralSide[]) => void
|
||||
title: string
|
||||
existingSides: LateralSide[]
|
||||
}
|
||||
|
||||
export default function LateralityPicker({
|
||||
open,
|
||||
onClose,
|
||||
onSelect,
|
||||
title,
|
||||
existingSides,
|
||||
}: LateralityPickerProps) {
|
||||
const t = useT()
|
||||
const hasLeft = existingSides.includes('left')
|
||||
const hasRight = existingSides.includes('right')
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} title={title} size="sm">
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('lateral.which_side')}
|
||||
</p>
|
||||
<div className="flex gap-3 justify-center">
|
||||
<Button
|
||||
variant={hasLeft ? 'ghost' : 'primary'}
|
||||
disabled={hasLeft}
|
||||
onClick={() => onSelect(['left'])}
|
||||
>
|
||||
{t('lateral.left')}
|
||||
</Button>
|
||||
<Button
|
||||
variant={hasRight ? 'ghost' : 'primary'}
|
||||
disabled={hasRight}
|
||||
onClick={() => onSelect(['right'])}
|
||||
>
|
||||
{t('lateral.right')}
|
||||
</Button>
|
||||
<Button
|
||||
variant={hasLeft && hasRight ? 'ghost' : 'primary'}
|
||||
disabled={hasLeft && hasRight}
|
||||
onClick={() => {
|
||||
const sides: LateralSide[] = []
|
||||
if (!hasLeft) sides.push('left')
|
||||
if (!hasRight) sides.push('right')
|
||||
onSelect(sides)
|
||||
}}
|
||||
>
|
||||
{t('lateral.both')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import type {
|
||||
Observation,
|
||||
ObservationZone,
|
||||
Vertebra,
|
||||
LateralSide,
|
||||
} from '@/domain/schema/observation'
|
||||
import type {
|
||||
SpeciesFindings,
|
||||
ZoneFindings,
|
||||
} from '@/domain/schema/findings'
|
||||
import type { Bone } from '@/anatomy/types'
|
||||
import { matchZoneFindings } from '@/lib/zoneMatch'
|
||||
import { AnimatePresence, motion } from 'motion/react'
|
||||
import Card from '@/components/ui/Card'
|
||||
import Badge from '@/components/ui/Badge'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Label from '@/components/ui/Label'
|
||||
import Textarea from '@/components/ui/Textarea'
|
||||
import FindingsTreePicker from './FindingsTreePicker'
|
||||
import FreeTextFindingInput from './FreeTextFindingInput'
|
||||
import SeveritySelector from './SeveritySelector'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { boneLabel } from '@/anatomy/labels'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
|
||||
export interface ObservationCardProps {
|
||||
observation: Observation
|
||||
index: number
|
||||
expanded: boolean
|
||||
onToggle: () => void
|
||||
onDelete: () => void
|
||||
onMoveUp: () => void
|
||||
onMoveDown: () => void
|
||||
canMoveUp: boolean
|
||||
canMoveDown: boolean
|
||||
// Editor body props (used only when expanded)
|
||||
bones: Map<string, Bone>
|
||||
findings: SpeciesFindings | null
|
||||
onChange: (next: Observation) => void
|
||||
onOpenVertebraPicker: (zoneIndex: number) => void
|
||||
onRemoveZone: (zoneIndex: number) => void
|
||||
}
|
||||
|
||||
function describeZone(
|
||||
z: ObservationZone,
|
||||
bones: Map<string, Bone>,
|
||||
locale: Locale,
|
||||
t: (key: string) => string,
|
||||
): string {
|
||||
const label = boneLabel(bones.get(z.boneId), locale, z.boneId)
|
||||
if (z.vertebrae?.length) {
|
||||
const vs = z.vertebrae
|
||||
.map((v: Vertebra) => `${v.region}${v.index}`)
|
||||
.join(', ')
|
||||
return `${label} (${vs})`
|
||||
}
|
||||
if (z.side) {
|
||||
const sideLabel = t(
|
||||
z.side === 'left' ? 'lateral.left_short' : 'lateral.right_short',
|
||||
)
|
||||
return `${label} (${sideLabel})`
|
||||
}
|
||||
return label
|
||||
}
|
||||
|
||||
export default function ObservationCard({
|
||||
observation,
|
||||
index,
|
||||
expanded,
|
||||
onToggle,
|
||||
onDelete,
|
||||
onMoveUp,
|
||||
onMoveDown,
|
||||
canMoveUp,
|
||||
canMoveDown,
|
||||
bones,
|
||||
findings,
|
||||
onChange,
|
||||
onOpenVertebraPicker,
|
||||
onRemoveZone,
|
||||
}: ObservationCardProps) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const nameOf = (z: { name_fr: string; name_en: string }) =>
|
||||
locale === 'en' ? z.name_en : z.name_fr
|
||||
|
||||
// Per-zone picker accordion — only one tree picker open at a time,
|
||||
// matching the observation-card accordion semantics. Closed by default
|
||||
// so the card stays compact when first expanded.
|
||||
const [expandedZoneId, setExpandedZoneId] = useState<string | null>(null)
|
||||
|
||||
const zoneCount = observation.zones.length
|
||||
const findingCount =
|
||||
observation.findings.length + observation.freeTextFindings.length
|
||||
|
||||
const zoneCountLabel =
|
||||
zoneCount > 1
|
||||
? t('observation.zone_label_plural')
|
||||
: t('observation.zone_label_singular')
|
||||
const findingCountLabel =
|
||||
findingCount > 1
|
||||
? t('observation.finding_label_plural')
|
||||
: t('observation.finding_label_singular')
|
||||
|
||||
function onHeaderKey(event: React.KeyboardEvent<HTMLDivElement>) {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
onToggle()
|
||||
}
|
||||
}
|
||||
|
||||
function stop(fn: () => void) {
|
||||
return (event: React.MouseEvent) => {
|
||||
event.stopPropagation()
|
||||
fn()
|
||||
}
|
||||
}
|
||||
|
||||
const zonesArray = useMemo(
|
||||
() => (findings ? Object.values(findings.zones) : []),
|
||||
[findings],
|
||||
)
|
||||
|
||||
const zonesWithTree = useMemo(() => {
|
||||
if (zonesArray.length === 0)
|
||||
return [] as { tree: ZoneFindings; side?: LateralSide }[]
|
||||
const seen = new Set<string>()
|
||||
const out: { tree: ZoneFindings; side?: LateralSide }[] = []
|
||||
for (const z of observation.zones) {
|
||||
const bone = bones.get(z.boneId)
|
||||
if (!bone) continue
|
||||
const tree = matchZoneFindings(
|
||||
{ fr: bone.fr, en: bone.en },
|
||||
zonesArray,
|
||||
)
|
||||
if (!tree) continue
|
||||
const key = z.side ? `${tree.id}:${z.side}` : tree.id
|
||||
if (seen.has(key)) continue
|
||||
seen.add(key)
|
||||
out.push({ tree, side: z.side })
|
||||
}
|
||||
return out
|
||||
}, [observation.zones, bones, zonesArray])
|
||||
|
||||
return (
|
||||
<Card
|
||||
className={[
|
||||
'transition',
|
||||
expanded
|
||||
? 'ring-2 ring-[var(--color-accent)]'
|
||||
: 'hover:bg-[var(--color-surface-strong)]',
|
||||
].join(' ')}
|
||||
>
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-expanded={expanded}
|
||||
aria-label={`${expanded ? t('observation.collapse_aria') : t('observation.expand_aria')} ${index + 1}`}
|
||||
onClick={onToggle}
|
||||
onKeyDown={onHeaderKey}
|
||||
className="flex items-start justify-between gap-3 p-4 cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/40 rounded-2xl"
|
||||
>
|
||||
<div className="flex-1 min-h-[60px] text-left">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Badge tone="neutral">{t('observation.badge_n')}{index + 1}</Badge>
|
||||
{observation.severity && (
|
||||
<Badge
|
||||
tone={
|
||||
observation.severity === 'sévère'
|
||||
? 'danger'
|
||||
: observation.severity === 'modérée'
|
||||
? 'warn'
|
||||
: 'neutral'
|
||||
}
|
||||
>
|
||||
{t(`severity.${observation.severity}`)}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-sm text-[var(--color-ink-muted)]">
|
||||
{zoneCount} {zoneCountLabel} · {findingCount} {findingCountLabel}
|
||||
</div>
|
||||
{!expanded && observation.comment && (
|
||||
<p className="mt-2 text-sm line-clamp-2 text-[var(--color-ink)]">
|
||||
{observation.comment}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className="flex items-start gap-1"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={!canMoveUp}
|
||||
onClick={stop(onMoveUp)}
|
||||
aria-label={t('common.move_up')}
|
||||
>
|
||||
↑
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={!canMoveDown}
|
||||
onClick={stop(onMoveDown)}
|
||||
aria-label={t('common.move_down')}
|
||||
>
|
||||
↓
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={stop(onDelete)}
|
||||
aria-label={t('common.delete')}
|
||||
>
|
||||
🗑
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={stop(onToggle)}
|
||||
aria-label={expanded ? t('common.collapse') : t('common.expand')}
|
||||
>
|
||||
{expanded ? '▲' : '▼'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AnimatePresence initial={false}>
|
||||
{expanded && (
|
||||
<motion.div
|
||||
key="body"
|
||||
initial={{ height: 0, opacity: 0 }}
|
||||
animate={{ height: 'auto', opacity: 1 }}
|
||||
exit={{ height: 0, opacity: 0 }}
|
||||
transition={{ duration: 0.18, ease: 'easeOut' }}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
<div className="px-4 pb-4 pt-2 border-t border-[var(--color-border)] space-y-6">
|
||||
<section>
|
||||
<Label>{t('observation.zones_label')}</Label>
|
||||
{observation.zones.length === 0 ? (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('observation.zones_empty')}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="flex flex-wrap gap-2">
|
||||
{observation.zones.map((z, i) => {
|
||||
const b = bones.get(z.boneId)
|
||||
const supportsVertebrae =
|
||||
b?.special === 'vertebral-precision'
|
||||
return (
|
||||
<li key={`${z.boneId}-${i}`}>
|
||||
<Badge tone="accent" className="gap-2">
|
||||
{describeZone(z, bones, locale, t)}
|
||||
{supportsVertebrae && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onOpenVertebraPicker(i)}
|
||||
className="underline text-xs text-[var(--color-accent-strong)]"
|
||||
title={t('observation.vertebrae_button_title')}
|
||||
>
|
||||
{t('observation.vertebrae_button')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`${t('observation.remove_zone')} ${boneLabel(b, locale, z.boneId)}`}
|
||||
onClick={() => onRemoveZone(i)}
|
||||
className="ml-1 text-[var(--color-accent-strong)]"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</Badge>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<Label>{t('observation.findings_catalog_label')}</Label>
|
||||
{zonesWithTree.length === 0 ? (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{observation.zones.length === 0
|
||||
? t('observation.findings_pick_zone_first')
|
||||
: t('observation.findings_no_catalog')}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{zonesWithTree.map(({ tree, side }) => {
|
||||
const pickerKey = side
|
||||
? `${tree.id}:${side}`
|
||||
: tree.id
|
||||
const expanded = expandedZoneId === pickerKey
|
||||
const selectedCount = observation.findings.filter(
|
||||
(f) =>
|
||||
f.zoneId === tree.id && f.side === side,
|
||||
).length
|
||||
const selectedAria = `${selectedCount} ${
|
||||
selectedCount > 1
|
||||
? t('findings.selected_plural')
|
||||
: t('findings.selected_singular')
|
||||
}`
|
||||
return (
|
||||
<li
|
||||
key={pickerKey}
|
||||
className={[
|
||||
'rounded-xl border bg-[var(--color-surface)] transition',
|
||||
expanded
|
||||
? 'border-[var(--color-accent)] ring-1 ring-[var(--color-accent)]'
|
||||
: 'border-[var(--color-border)]',
|
||||
].join(' ')}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setExpandedZoneId(expanded ? null : pickerKey)
|
||||
}
|
||||
aria-expanded={expanded}
|
||||
aria-controls={`findings-zone-${pickerKey}`}
|
||||
className="w-full flex items-center justify-between gap-2 px-3 py-2 text-left rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/40"
|
||||
>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-[var(--color-ink)]">
|
||||
{nameOf(tree)}
|
||||
{side && ` (${t(side === 'left' ? 'lateral.left' : 'lateral.right')})`}
|
||||
</span>
|
||||
{selectedCount > 0 && (
|
||||
<span
|
||||
aria-label={selectedAria}
|
||||
className="inline-flex items-center justify-center min-w-[20px] h-[20px] px-1.5 rounded-full text-[11px] font-semibold bg-[var(--color-accent)] text-white"
|
||||
>
|
||||
{selectedCount}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="text-[var(--color-ink-muted)]"
|
||||
>
|
||||
{expanded ? '▲' : '▼'}
|
||||
</span>
|
||||
</button>
|
||||
<AnimatePresence initial={false}>
|
||||
{expanded && (
|
||||
<motion.div
|
||||
key="picker-body"
|
||||
id={`findings-zone-${pickerKey}`}
|
||||
initial={{ height: 0, opacity: 0 }}
|
||||
animate={{ height: 'auto', opacity: 1 }}
|
||||
exit={{ height: 0, opacity: 0 }}
|
||||
transition={{ duration: 0.18, ease: 'easeOut' }}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
<div className="px-3 pb-3 pt-1 border-t border-[var(--color-border)]">
|
||||
<FindingsTreePicker
|
||||
zoneId={tree.id}
|
||||
tree={tree}
|
||||
side={side}
|
||||
selected={observation.findings}
|
||||
onChange={(next) =>
|
||||
onChange({ ...observation, findings: next })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<Label>{t('observation.findings_free_label')}</Label>
|
||||
<FreeTextFindingInput
|
||||
items={observation.freeTextFindings}
|
||||
onChange={(items) =>
|
||||
onChange({ ...observation, freeTextFindings: items })
|
||||
}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<Label>{t('observation.severity_label')}</Label>
|
||||
<SeveritySelector
|
||||
value={observation.severity}
|
||||
onChange={(s) => onChange({ ...observation, severity: s })}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<Label htmlFor={`obs-comment-${observation.id}`}>
|
||||
{t('observation.comment_label')}
|
||||
</Label>
|
||||
<Textarea
|
||||
id={`obs-comment-${observation.id}`}
|
||||
value={observation.comment}
|
||||
onChange={(e) =>
|
||||
onChange({ ...observation, comment: e.target.value })
|
||||
}
|
||||
placeholder={t('observation.comment_placeholder')}
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { Observation } from '@/domain/schema/observation'
|
||||
import type { SpeciesFindings } from '@/domain/schema/findings'
|
||||
import type { Bone } from '@/anatomy/types'
|
||||
import ObservationCard from './ObservationCard'
|
||||
import Button from '@/components/ui/Button'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface ObservationListProps {
|
||||
observations: Observation[]
|
||||
activeIndex: number
|
||||
onToggle: (i: number) => void
|
||||
onAdd: () => void
|
||||
onDelete: (i: number) => void
|
||||
onMoveUp: (i: number) => void
|
||||
onMoveDown: (i: number) => void
|
||||
// Editor body props forwarded to each card
|
||||
bones: Map<string, Bone>
|
||||
findings: SpeciesFindings | null
|
||||
onChange: (i: number, next: Observation) => void
|
||||
onOpenVertebraPicker: (i: number, zoneIndex: number) => void
|
||||
onRemoveZone: (i: number, zoneIndex: number) => void
|
||||
}
|
||||
|
||||
export default function ObservationList({
|
||||
observations,
|
||||
activeIndex,
|
||||
onToggle,
|
||||
onAdd,
|
||||
onDelete,
|
||||
onMoveUp,
|
||||
onMoveDown,
|
||||
bones,
|
||||
findings,
|
||||
onChange,
|
||||
onOpenVertebraPicker,
|
||||
onRemoveZone,
|
||||
}: ObservationListProps) {
|
||||
const t = useT()
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="font-serif text-lg sm:text-xl text-[var(--color-ink)]">
|
||||
{t('observation.section_title')}
|
||||
</h2>
|
||||
<Button size="sm" onClick={onAdd}>
|
||||
{t('observation.add')}
|
||||
</Button>
|
||||
</div>
|
||||
{observations.length === 0 ? (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('observation.empty')}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{observations.map((obs, i) => (
|
||||
<li key={obs.id}>
|
||||
<ObservationCard
|
||||
observation={obs}
|
||||
index={i}
|
||||
expanded={i === activeIndex}
|
||||
onToggle={() => onToggle(i)}
|
||||
onDelete={() => onDelete(i)}
|
||||
onMoveUp={() => onMoveUp(i)}
|
||||
onMoveDown={() => onMoveDown(i)}
|
||||
canMoveUp={i > 0}
|
||||
canMoveDown={i < observations.length - 1}
|
||||
bones={bones}
|
||||
findings={findings}
|
||||
onChange={(next) => onChange(i, next)}
|
||||
onOpenVertebraPicker={(zoneIndex) =>
|
||||
onOpenVertebraPicker(i, zoneIndex)
|
||||
}
|
||||
onRemoveZone={(zoneIndex) => onRemoveZone(i, zoneIndex)}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { Severity } from '@/domain/schema/observation'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface SeveritySelectorProps {
|
||||
value: Severity | undefined
|
||||
onChange: (s: Severity | undefined) => void
|
||||
}
|
||||
|
||||
const SEVERITIES: Severity[] = ['légère', 'modérée', 'sévère']
|
||||
const COLORS: Record<Severity, string> = {
|
||||
'légère': 'border-[var(--severity-mild)] text-[var(--severity-mild)]',
|
||||
'modérée': 'border-[var(--severity-moderate)] text-[var(--severity-moderate)]',
|
||||
'sévère': 'border-[var(--severity-severe)] text-[var(--severity-severe)]',
|
||||
}
|
||||
|
||||
export default function SeveritySelector({ value, onChange }: SeveritySelectorProps) {
|
||||
const t = useT()
|
||||
return (
|
||||
<div role="radiogroup" aria-label={t('severity.aria')} className="flex gap-2">
|
||||
{SEVERITIES.map((s) => (
|
||||
<button
|
||||
key={s}
|
||||
role="radio"
|
||||
aria-checked={value === s}
|
||||
onClick={() => onChange(value === s ? undefined : s)}
|
||||
className={[
|
||||
'rounded-full border px-3 py-1.5 text-sm font-medium capitalize',
|
||||
value === s
|
||||
? `bg-white ${COLORS[s]}`
|
||||
: 'border-[var(--color-border)] text-[var(--color-ink-muted)]',
|
||||
].join(' ')}
|
||||
>
|
||||
{t(`severity.${s}`)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useState } from 'react'
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Chip from '@/components/ui/Chip'
|
||||
import type { Vertebra, VertebralRegion } from '@/domain/schema/observation'
|
||||
import type { VertebralFormula } from '@/domain/species/types'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
const REGIONS: VertebralRegion[] = ['C', 'T', 'L', 'S', 'Cd']
|
||||
const REGION_KEY: Record<VertebralRegion, string> = {
|
||||
C: 'vertebra.region.C',
|
||||
T: 'vertebra.region.T',
|
||||
L: 'vertebra.region.L',
|
||||
S: 'vertebra.region.S',
|
||||
Cd: 'vertebra.region.Cd',
|
||||
}
|
||||
|
||||
export interface VertebraPickerProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onConfirm: (vertebrae: Vertebra[]) => void
|
||||
initial: Vertebra[]
|
||||
formula: VertebralFormula
|
||||
title: string
|
||||
/** Tab to open on. Takes priority so a click always lands on its own zone. */
|
||||
initialRegion?: VertebralRegion
|
||||
}
|
||||
|
||||
export default function VertebraPicker({
|
||||
open,
|
||||
onClose,
|
||||
onConfirm,
|
||||
initial,
|
||||
formula,
|
||||
title,
|
||||
initialRegion,
|
||||
}: VertebraPickerProps) {
|
||||
const t = useT()
|
||||
const [selected, setSelected] = useState<Vertebra[]>(initial)
|
||||
const [activeRegion, setActiveRegion] = useState<VertebralRegion>(
|
||||
() => initialRegion ?? initial[0]?.region ?? 'C',
|
||||
)
|
||||
|
||||
const has = (r: VertebralRegion, i: number) =>
|
||||
selected.some((v) => v.region === r && v.index === i)
|
||||
|
||||
const toggle = (r: VertebralRegion, i: number) => {
|
||||
setSelected((cur) =>
|
||||
has(r, i)
|
||||
? cur.filter((v) => !(v.region === r && v.index === i))
|
||||
: [...cur, { region: r, index: i }],
|
||||
)
|
||||
}
|
||||
|
||||
const all = (r: VertebralRegion, count: number) => {
|
||||
setSelected((cur) => {
|
||||
const rest = cur.filter((v) => v.region !== r)
|
||||
return [...rest, ...Array.from({ length: count }, (_, k) => ({ region: r, index: k + 1 }))]
|
||||
})
|
||||
}
|
||||
|
||||
const none = (r: VertebralRegion) =>
|
||||
setSelected((cur) => cur.filter((v) => v.region !== r))
|
||||
|
||||
const count = formula[activeRegion]
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} title={title} size="lg">
|
||||
<div role="tablist" className="flex flex-wrap gap-2 mb-4">
|
||||
{REGIONS.map((r) => (
|
||||
<button
|
||||
key={r}
|
||||
role="tab"
|
||||
aria-selected={activeRegion === r}
|
||||
onClick={() => setActiveRegion(r)}
|
||||
className={[
|
||||
'rounded-full px-4 py-2.5 sm:py-1.5 text-sm font-medium border min-h-[2.75rem]',
|
||||
activeRegion === r
|
||||
? 'bg-[var(--color-accent)] text-white border-[var(--color-accent)]'
|
||||
: 'bg-white text-[var(--color-ink)] border-[var(--color-border)]',
|
||||
].join(' ')}
|
||||
>
|
||||
{t(REGION_KEY[r])}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2 mb-4 max-h-64 overflow-auto">
|
||||
{Array.from({ length: count }, (_, k) => k + 1).map((i) => (
|
||||
<Chip
|
||||
key={i}
|
||||
active={has(activeRegion, i)}
|
||||
onClick={() => toggle(activeRegion, i)}
|
||||
>
|
||||
{activeRegion}{i}
|
||||
</Chip>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 mb-6">
|
||||
<Button variant="ghost" size="sm" onClick={() => all(activeRegion, count)}>
|
||||
{t('vertebra.check_all')}
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => none(activeRegion)}>
|
||||
{t('vertebra.uncheck_all')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="ghost" onClick={onClose}>{t('common.cancel')}</Button>
|
||||
<Button onClick={() => onConfirm(selected)}>{t('common.confirm')}</Button>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { Animal, Owner } from '@/domain/schema/animal'
|
||||
import Label from '@/components/ui/Label'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Select from '@/components/ui/Select'
|
||||
import { getAllSpecies, speciesLabel } from '@/domain/species/registry'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
export interface AnimalFormProps {
|
||||
animal: Animal
|
||||
owner: Owner
|
||||
onChangeAnimal: (next: Animal) => void
|
||||
onChangeOwner: (next: Owner) => void
|
||||
}
|
||||
|
||||
export default function AnimalForm({ animal, owner, onChangeAnimal, onChangeOwner }: AnimalFormProps) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const species = getAllSpecies()
|
||||
const setA = (patch: Partial<Animal>) => onChangeAnimal({ ...animal, ...patch })
|
||||
return (
|
||||
<fieldset className="space-y-3">
|
||||
<legend className="font-serif text-xl mb-2 text-[var(--color-ink)]">
|
||||
{t('form.animal.legend')}
|
||||
</legend>
|
||||
<div>
|
||||
<Label htmlFor="an-species">{t('form.animal.species')}</Label>
|
||||
<Select
|
||||
id="an-species"
|
||||
value={animal.speciesId}
|
||||
onChange={(e) => setA({ speciesId: e.target.value })}
|
||||
>
|
||||
{species.map((s) => (
|
||||
<option key={s.id} value={s.id}>{speciesLabel(s, locale)}</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="an-name">{t('form.animal.name')}</Label>
|
||||
<Input id="an-name" required value={animal.name} onChange={(e) => setA({ name: e.target.value })} />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="an-breed">{t('form.animal.breed')}</Label>
|
||||
<Input id="an-breed" value={animal.breed ?? ''} onChange={(e) => setA({ breed: e.target.value || undefined })} />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="an-age">{t('form.animal.age')}</Label>
|
||||
<Input id="an-age" value={animal.age ?? ''} onChange={(e) => setA({ age: e.target.value || undefined })} />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="own-name">{t('form.owner.name')}</Label>
|
||||
<Input id="own-name" required value={owner.name} onChange={(e) => onChangeOwner({ name: e.target.value })} />
|
||||
</div>
|
||||
</fieldset>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { Report } from '@/domain/schema/report'
|
||||
import Label from '@/components/ui/Label'
|
||||
import Textarea from '@/components/ui/Textarea'
|
||||
import NextAppointmentPicker from './NextAppointmentPicker'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface ConclusionPanelProps {
|
||||
conclusion: string
|
||||
recommendations: string
|
||||
nextAppointment: Report['nextAppointment']
|
||||
onChangeConclusion: (s: string) => void
|
||||
onChangeRecommendations: (s: string) => void
|
||||
onChangeNextAppointment: (n: Report['nextAppointment']) => void
|
||||
}
|
||||
|
||||
export default function ConclusionPanel({
|
||||
conclusion,
|
||||
recommendations,
|
||||
nextAppointment,
|
||||
onChangeConclusion,
|
||||
onChangeRecommendations,
|
||||
onChangeNextAppointment,
|
||||
}: ConclusionPanelProps) {
|
||||
const t = useT()
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<h2 className="font-serif text-lg sm:text-xl text-[var(--color-ink)]">
|
||||
{t('conclusion.section_title')}
|
||||
</h2>
|
||||
<div>
|
||||
<Label htmlFor="conclusion">{t('conclusion.conclusion')}</Label>
|
||||
<Textarea id="conclusion" value={conclusion} onChange={(e) => onChangeConclusion(e.target.value)} />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="recommendations">{t('conclusion.recommendations')}</Label>
|
||||
<Textarea id="recommendations" value={recommendations} onChange={(e) => onChangeRecommendations(e.target.value)} />
|
||||
</div>
|
||||
<NextAppointmentPicker value={nextAppointment} onChange={onChangeNextAppointment} />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { Report } from '@/domain/schema/report'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Label from '@/components/ui/Label'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface NextAppointmentPickerProps {
|
||||
value: Report['nextAppointment']
|
||||
onChange: (next: Report['nextAppointment']) => void
|
||||
}
|
||||
|
||||
export default function NextAppointmentPicker({
|
||||
value,
|
||||
onChange,
|
||||
}: NextAppointmentPickerProps) {
|
||||
const t = useT()
|
||||
const kind = value?.kind
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label>{t('conclusion.next_appointment')}</Label>
|
||||
<div className="flex gap-2 mb-2">
|
||||
<label className="text-sm flex items-center gap-1">
|
||||
<input
|
||||
type="radio"
|
||||
checked={kind === 'date'}
|
||||
onChange={() => onChange({ kind: 'date', date: '' })}
|
||||
/>
|
||||
{t('conclusion.next_kind_date')}
|
||||
</label>
|
||||
<label className="text-sm flex items-center gap-1">
|
||||
<input
|
||||
type="radio"
|
||||
checked={kind === 'period'}
|
||||
onChange={() => onChange({ kind: 'period', text: '' })}
|
||||
/>
|
||||
{t('conclusion.next_kind_period')}
|
||||
</label>
|
||||
<label className="text-sm flex items-center gap-1">
|
||||
<input
|
||||
type="radio"
|
||||
checked={value === undefined}
|
||||
onChange={() => onChange(undefined)}
|
||||
/>
|
||||
{t('conclusion.next_kind_none')}
|
||||
</label>
|
||||
</div>
|
||||
{value?.kind === 'date' && (
|
||||
<Input
|
||||
type="date"
|
||||
value={value.date}
|
||||
onChange={(e) => onChange({ kind: 'date', date: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
{value?.kind === 'period' && (
|
||||
<Input
|
||||
value={value.text}
|
||||
placeholder={t('conclusion.next_period_placeholder')}
|
||||
onChange={(e) => onChange({ kind: 'period', text: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { Practitioner } from '@/domain/schema/practitioner'
|
||||
import Label from '@/components/ui/Label'
|
||||
import Input from '@/components/ui/Input'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface PractitionerFormProps {
|
||||
value: Practitioner
|
||||
onChange: (next: Practitioner) => void
|
||||
}
|
||||
|
||||
export default function PractitionerForm({ value, onChange }: PractitionerFormProps) {
|
||||
const t = useT()
|
||||
const set = (patch: Partial<Practitioner>) => onChange({ ...value, ...patch })
|
||||
return (
|
||||
<fieldset className="space-y-3">
|
||||
<legend className="font-serif text-xl mb-2 text-[var(--color-ink)]">
|
||||
{t('form.practitioner.legend')}
|
||||
</legend>
|
||||
<div>
|
||||
<Label htmlFor="prac-name">{t('form.practitioner.name')}</Label>
|
||||
<Input id="prac-name" required value={value.name} onChange={(e) => set({ name: e.target.value })} />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="prac-cabinet">{t('form.practitioner.cabinet')}</Label>
|
||||
<Input id="prac-cabinet" value={value.cabinet ?? ''} onChange={(e) => set({ cabinet: e.target.value || undefined })} />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="prac-contact">{t('form.practitioner.contact')}</Label>
|
||||
<Input id="prac-contact" value={value.contact ?? ''} onChange={(e) => set({ contact: e.target.value || undefined })} />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="prac-siret">{t('form.practitioner.siret')}</Label>
|
||||
<Input id="prac-siret" value={value.siret ?? ''} onChange={(e) => set({ siret: e.target.value || undefined })} />
|
||||
</div>
|
||||
</fieldset>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { Report } from '@/domain/schema/report'
|
||||
import AppHeader from '@/components/brand/AppHeader'
|
||||
import Button from '@/components/ui/Button'
|
||||
import { formatDate } from '@/lib/dates'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
export interface ReportHeaderProps {
|
||||
report: Report
|
||||
onEditInfos?: () => void
|
||||
}
|
||||
|
||||
export default function ReportHeader({ report, onEditInfos }: ReportHeaderProps) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
return (
|
||||
<AppHeader>
|
||||
<div className="text-xs sm:text-sm text-right text-[var(--color-ink-muted)]">
|
||||
<div className="text-[var(--color-ink)] font-medium truncate max-w-[10rem] sm:max-w-none">
|
||||
{report.animal.name} · {report.owner.name}
|
||||
</div>
|
||||
<div className="hidden sm:block">{formatDate(report.date, locale)}</div>
|
||||
</div>
|
||||
{onEditInfos && (
|
||||
<Button variant="secondary" size="sm" onClick={onEditInfos}>
|
||||
{t('editor.edit_infos')}
|
||||
</Button>
|
||||
)}
|
||||
</AppHeader>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
export default function Badge({
|
||||
children,
|
||||
tone = 'neutral',
|
||||
className = '',
|
||||
}: {
|
||||
children: ReactNode
|
||||
tone?: 'neutral' | 'accent' | 'warn' | 'danger'
|
||||
className?: string
|
||||
}) {
|
||||
const map = {
|
||||
neutral: 'bg-[var(--color-surface-strong)] text-[var(--color-ink)]',
|
||||
accent: 'bg-[var(--color-accent)]/10 text-[var(--color-accent-strong)]',
|
||||
warn: 'bg-amber-50 text-amber-700',
|
||||
danger: 'bg-red-50 text-red-700',
|
||||
} as const
|
||||
return (
|
||||
<span
|
||||
className={`inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium ${map[tone]} ${className}`}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { ButtonHTMLAttributes, ReactNode } from 'react'
|
||||
|
||||
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: 'primary' | 'secondary' | 'ghost' | 'danger'
|
||||
size?: 'sm' | 'md' | 'lg'
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
const VARIANTS: Record<NonNullable<ButtonProps['variant']>, string> = {
|
||||
primary:
|
||||
'bg-[var(--color-accent)] text-white hover:bg-[var(--color-accent-strong)] focus-visible:ring-[var(--color-accent)]',
|
||||
secondary:
|
||||
'bg-[var(--color-surface)] text-[var(--color-ink)] border border-[var(--color-border)] hover:bg-[var(--color-surface-strong)]',
|
||||
ghost:
|
||||
'bg-transparent text-[var(--color-ink)] hover:bg-[var(--color-surface)]',
|
||||
danger:
|
||||
'bg-[var(--color-danger)] text-white hover:bg-[var(--color-danger-strong)]',
|
||||
}
|
||||
|
||||
const SIZES: Record<NonNullable<ButtonProps['size']>, string> = {
|
||||
sm: 'h-9 px-3 text-sm rounded-md',
|
||||
md: 'h-10 px-4 text-sm sm:text-base rounded-lg',
|
||||
lg: 'h-12 px-5 sm:px-6 text-base rounded-lg',
|
||||
}
|
||||
|
||||
export default function Button({
|
||||
variant = 'primary',
|
||||
size = 'md',
|
||||
className = '',
|
||||
children,
|
||||
...rest
|
||||
}: ButtonProps) {
|
||||
return (
|
||||
<button
|
||||
className={[
|
||||
'inline-flex items-center justify-center font-medium transition disabled:opacity-50 disabled:cursor-not-allowed focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2',
|
||||
VARIANTS[variant],
|
||||
SIZES[size],
|
||||
className,
|
||||
].join(' ')}
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
export interface CardProps {
|
||||
children: ReactNode
|
||||
className?: string
|
||||
as?: 'div' | 'section' | 'article'
|
||||
}
|
||||
|
||||
export default function Card({ children, className = '', as: Tag = 'div' }: CardProps) {
|
||||
return (
|
||||
<Tag
|
||||
className={[
|
||||
'rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)] shadow-sm',
|
||||
className,
|
||||
].join(' ')}
|
||||
>
|
||||
{children}
|
||||
</Tag>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { ButtonHTMLAttributes, ReactNode } from 'react'
|
||||
|
||||
export default function Chip({
|
||||
active = false,
|
||||
children,
|
||||
className = '',
|
||||
...rest
|
||||
}: ButtonHTMLAttributes<HTMLButtonElement> & { active?: boolean; children: ReactNode }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={active}
|
||||
className={[
|
||||
'inline-flex items-center justify-center min-w-[40px] h-10 px-3 rounded-full border text-sm font-medium transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/30',
|
||||
active
|
||||
? 'bg-[var(--color-accent)] text-white border-[var(--color-accent)]'
|
||||
: 'bg-white text-[var(--color-ink)] border-[var(--color-border)] hover:bg-[var(--color-surface)]',
|
||||
className,
|
||||
].join(' ')}
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useEffect, type ReactNode } from 'react'
|
||||
import { AnimatePresence, motion } from 'motion/react'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface DialogProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
title: string
|
||||
children: ReactNode
|
||||
size?: 'sm' | 'md' | 'lg' | 'xl'
|
||||
}
|
||||
|
||||
const SIZE: Record<NonNullable<DialogProps['size']>, string> = {
|
||||
sm: 'max-w-sm',
|
||||
md: 'max-w-md',
|
||||
lg: 'max-w-2xl',
|
||||
xl: 'max-w-4xl',
|
||||
}
|
||||
|
||||
export default function Dialog({ open, onClose, title, children, size = 'md' }: DialogProps) {
|
||||
const t = useT()
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [open, onClose])
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{open && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4">
|
||||
<motion.div
|
||||
data-testid="dialog-backdrop"
|
||||
className="absolute inset-0 bg-black/40"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
onClick={onClose}
|
||||
/>
|
||||
<motion.div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={title}
|
||||
initial={{ opacity: 0, scale: 0.96 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.96 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
className={`relative w-full ${SIZE[size]} max-h-[85vh] overflow-y-auto rounded-2xl bg-[var(--color-surface)] shadow-xl`}
|
||||
>
|
||||
<header className="flex items-center justify-between px-4 sm:px-6 py-3 sm:py-4 border-b border-[var(--color-border)]">
|
||||
<h2 className="text-lg font-semibold text-[var(--color-ink)]">{title}</h2>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.close')}
|
||||
onClick={onClose}
|
||||
className="rounded-md p-1 text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)]"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</header>
|
||||
<div className="px-4 sm:px-6 py-3 sm:py-4">{children}</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { forwardRef, type InputHTMLAttributes } from 'react'
|
||||
|
||||
const Input = forwardRef<HTMLInputElement, InputHTMLAttributes<HTMLInputElement>>(
|
||||
({ className = '', ...rest }, ref) => (
|
||||
<input
|
||||
ref={ref}
|
||||
className={[
|
||||
'h-10 w-full rounded-lg border border-[var(--color-border)] bg-white px-3 text-base text-[var(--color-ink)] placeholder:text-[var(--color-ink-muted)] focus-visible:border-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/30',
|
||||
className,
|
||||
].join(' ')}
|
||||
{...rest}
|
||||
/>
|
||||
),
|
||||
)
|
||||
Input.displayName = 'Input'
|
||||
export default Input
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { LabelHTMLAttributes, ReactNode } from 'react'
|
||||
|
||||
export default function Label({
|
||||
children,
|
||||
className = '',
|
||||
...rest
|
||||
}: LabelHTMLAttributes<HTMLLabelElement> & { children: ReactNode }) {
|
||||
return (
|
||||
<label
|
||||
className={[
|
||||
'block text-sm font-medium text-[var(--color-ink)] mb-1',
|
||||
className,
|
||||
].join(' ')}
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
</label>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { forwardRef, type SelectHTMLAttributes } from 'react'
|
||||
|
||||
const Select = forwardRef<HTMLSelectElement, SelectHTMLAttributes<HTMLSelectElement>>(
|
||||
({ className = '', children, ...rest }, ref) => (
|
||||
<select
|
||||
ref={ref}
|
||||
className={[
|
||||
'h-10 w-full rounded-lg border border-[var(--color-border)] bg-white px-3 text-base text-[var(--color-ink)] focus-visible:border-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/30',
|
||||
className,
|
||||
].join(' ')}
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
</select>
|
||||
),
|
||||
)
|
||||
Select.displayName = 'Select'
|
||||
export default Select
|
||||
@@ -0,0 +1,16 @@
|
||||
import { forwardRef, type TextareaHTMLAttributes } from 'react'
|
||||
|
||||
const Textarea = forwardRef<HTMLTextAreaElement, TextareaHTMLAttributes<HTMLTextAreaElement>>(
|
||||
({ className = '', ...rest }, ref) => (
|
||||
<textarea
|
||||
ref={ref}
|
||||
className={[
|
||||
'w-full min-h-[96px] rounded-lg border border-[var(--color-border)] bg-white p-3 text-base text-[var(--color-ink)] placeholder:text-[var(--color-ink-muted)] focus-visible:border-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/30',
|
||||
className,
|
||||
].join(' ')}
|
||||
{...rest}
|
||||
/>
|
||||
),
|
||||
)
|
||||
Textarea.displayName = 'Textarea'
|
||||
export default Textarea
|
||||
@@ -0,0 +1,52 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
/**
|
||||
* Runtime application config.
|
||||
* Resolution order:
|
||||
* 1. window.__APP_CONFIG__ (injected by docker/entrypoint.sh)
|
||||
* 2. import.meta.env.VITE_APP_* (build-time Vite defines)
|
||||
* 3. Hard-coded defaults
|
||||
*/
|
||||
export interface AppConfig {
|
||||
siteName: string
|
||||
brandName: string
|
||||
footerName: string
|
||||
tagline: string
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__APP_CONFIG__?: Partial<AppConfig>
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULTS: AppConfig = {
|
||||
siteName: 'Faunosteo',
|
||||
brandName: 'Faunosteo',
|
||||
footerName: 'Faunosteo',
|
||||
tagline: 'Outils pour ostéopathes animaliers',
|
||||
}
|
||||
|
||||
function resolveConfig(): AppConfig {
|
||||
const runtime = typeof window !== 'undefined' ? window.__APP_CONFIG__ : {}
|
||||
return {
|
||||
siteName:
|
||||
runtime?.siteName ??
|
||||
import.meta.env.VITE_APP_SITE_NAME ??
|
||||
DEFAULTS.siteName,
|
||||
brandName:
|
||||
runtime?.brandName ??
|
||||
import.meta.env.VITE_APP_BRAND_NAME ??
|
||||
DEFAULTS.brandName,
|
||||
footerName:
|
||||
runtime?.footerName ??
|
||||
import.meta.env.VITE_APP_FOOTER_NAME ??
|
||||
DEFAULTS.footerName,
|
||||
tagline:
|
||||
runtime?.tagline ??
|
||||
import.meta.env.VITE_APP_TAGLINE ??
|
||||
DEFAULTS.tagline,
|
||||
}
|
||||
}
|
||||
|
||||
export const appConfig: AppConfig = resolveConfig()
|
||||
@@ -0,0 +1,17 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const AnimalSchema = z.object({
|
||||
/** Must match a registered species id (e.g. 'equine') */
|
||||
speciesId: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
breed: z.string().optional(),
|
||||
age: z.string().optional(),
|
||||
})
|
||||
|
||||
export type Animal = z.infer<typeof AnimalSchema>
|
||||
|
||||
export const OwnerSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
})
|
||||
|
||||
export type Owner = z.infer<typeof OwnerSchema>
|
||||
@@ -0,0 +1,67 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
/**
|
||||
* Schema for the species findings tree.
|
||||
*
|
||||
* Source of truth for what a practitioner can attach to an observation:
|
||||
* a hierarchical tree of dysfunctions/observations per anatomical zone,
|
||||
* authored by the domain expert in JSON and parsed at boot.
|
||||
*
|
||||
* Field names match the JSON authoring contract (snake_case).
|
||||
* Recursive children are typed via z.lazy + an explicit ZodType annotation
|
||||
* so TS can resolve the self-reference.
|
||||
*/
|
||||
|
||||
export const SourceRefSchema = z.object({
|
||||
type: z.enum(['manual', 'journal', 'database', 'web']),
|
||||
citation: z.string().min(1),
|
||||
url: z.string().url().optional(),
|
||||
})
|
||||
|
||||
export type SourceRef = z.infer<typeof SourceRefSchema>
|
||||
|
||||
export interface FindingNode {
|
||||
id: string
|
||||
name_fr: string
|
||||
name_en: string
|
||||
description_fr?: string
|
||||
description_en?: string
|
||||
requires_vet_referral?: boolean
|
||||
sources?: SourceRef[]
|
||||
children?: FindingNode[]
|
||||
}
|
||||
|
||||
export const FindingNodeSchema: z.ZodType<FindingNode> = z.lazy(() =>
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
name_fr: z.string().min(1),
|
||||
name_en: z.string().min(1),
|
||||
description_fr: z.string().optional(),
|
||||
description_en: z.string().optional(),
|
||||
requires_vet_referral: z.boolean().optional(),
|
||||
sources: z.array(SourceRefSchema).optional(),
|
||||
children: z.array(FindingNodeSchema).optional(),
|
||||
}),
|
||||
)
|
||||
|
||||
export const ZoneFindingsSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
name_fr: z.string().min(1),
|
||||
name_en: z.string().min(1),
|
||||
categories: z.array(FindingNodeSchema),
|
||||
})
|
||||
|
||||
export type ZoneFindings = z.infer<typeof ZoneFindingsSchema>
|
||||
|
||||
export const SpeciesFindingsSchema = z.object({
|
||||
schema_version: z.string().min(1),
|
||||
scope_disclaimer: z.string().min(1),
|
||||
species: z.object({
|
||||
id: z.string().min(1),
|
||||
name_fr: z.string().min(1),
|
||||
name_en: z.string().min(1),
|
||||
}),
|
||||
zones: z.record(z.string(), ZoneFindingsSchema),
|
||||
})
|
||||
|
||||
export type SpeciesFindings = z.infer<typeof SpeciesFindingsSchema>
|
||||
@@ -0,0 +1,61 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const SeveritySchema = z.enum(['légère', 'modérée', 'sévère'])
|
||||
|
||||
export type Severity = z.infer<typeof SeveritySchema>
|
||||
|
||||
export const VertebralRegionSchema = z.enum(['C', 'T', 'L', 'S', 'Cd'])
|
||||
|
||||
export type VertebralRegion = z.infer<typeof VertebralRegionSchema>
|
||||
|
||||
export const VertebraSchema = z.object({
|
||||
region: VertebralRegionSchema,
|
||||
index: z.number().int().positive(),
|
||||
})
|
||||
|
||||
export type Vertebra = z.infer<typeof VertebraSchema>
|
||||
|
||||
export const LateralSideSchema = z.enum(['left', 'right'])
|
||||
export type LateralSide = z.infer<typeof LateralSideSchema>
|
||||
|
||||
export const ObservationZoneSchema = z.object({
|
||||
/** Must match data-anno-id attribute on the SVG element */
|
||||
boneId: z.string().min(1),
|
||||
/** Set when zone originates from a detail popup SVG */
|
||||
detailSourceId: z.string().optional(),
|
||||
/** Set when boneId is a spine-zone; replaces the block semantically */
|
||||
vertebrae: z.array(VertebraSchema).optional(),
|
||||
/** Set for bilateral zones to distinguish left from right */
|
||||
side: LateralSideSchema.optional(),
|
||||
})
|
||||
|
||||
export type ObservationZone = z.infer<typeof ObservationZoneSchema>
|
||||
|
||||
/**
|
||||
* A selected leaf from the species findings tree. The path is anchored at the
|
||||
* zone root (categories array), e.g. ['sphenoid-dysfunctions', 'physiological',
|
||||
* 'flexion']. Labels are snapshotted at selection time so previously exported
|
||||
* reports remain readable if the catalog is later edited.
|
||||
*/
|
||||
export const FindingSchema = z.object({
|
||||
zoneId: z.string().min(1),
|
||||
path: z.array(z.string().min(1)).min(1),
|
||||
labelFrSnapshot: z.string().min(1),
|
||||
labelEnSnapshot: z.string().min(1),
|
||||
requiresVetReferral: z.boolean().optional(),
|
||||
side: LateralSideSchema.optional(),
|
||||
})
|
||||
|
||||
export type Finding = z.infer<typeof FindingSchema>
|
||||
|
||||
export const ObservationSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
zones: z.array(ObservationZoneSchema),
|
||||
findings: z.array(FindingSchema),
|
||||
/** Free-text additions when the tree does not cover a finding */
|
||||
freeTextFindings: z.array(z.string()),
|
||||
severity: SeveritySchema.optional(),
|
||||
comment: z.string(),
|
||||
})
|
||||
|
||||
export type Observation = z.infer<typeof ObservationSchema>
|
||||
@@ -0,0 +1,11 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const PractitionerSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
cabinet: z.string().optional(),
|
||||
contact: z.string().optional(),
|
||||
/** SIRET — 14-digit French business identifier */
|
||||
siret: z.string().optional(),
|
||||
})
|
||||
|
||||
export type Practitioner = z.infer<typeof PractitionerSchema>
|
||||
@@ -0,0 +1,33 @@
|
||||
import { z } from 'zod'
|
||||
import { PractitionerSchema } from './practitioner'
|
||||
import { AnimalSchema, OwnerSchema } from './animal'
|
||||
import { ObservationSchema } from './observation'
|
||||
|
||||
const NextAppointmentSchema = z.discriminatedUnion('kind', [
|
||||
z.object({ kind: z.literal('date'), date: z.string() }),
|
||||
z.object({ kind: z.literal('period'), text: z.string() }),
|
||||
])
|
||||
|
||||
export type NextAppointment = z.infer<typeof NextAppointmentSchema>
|
||||
|
||||
export const ReportSchema = z.object({
|
||||
/**
|
||||
* Schema version. v2 introduced the hierarchical findings tree
|
||||
* (replacing the flat pathology list). Bump on breaking changes.
|
||||
*/
|
||||
version: z.literal(2),
|
||||
id: z.string().min(1),
|
||||
/** ISO timestamp of report creation */
|
||||
createdAt: z.string(),
|
||||
/** ISO date of clinical encounter */
|
||||
date: z.string(),
|
||||
practitioner: PractitionerSchema,
|
||||
animal: AnimalSchema,
|
||||
owner: OwnerSchema,
|
||||
observations: z.array(ObservationSchema),
|
||||
conclusion: z.string(),
|
||||
recommendations: z.string(),
|
||||
nextAppointment: NextAppointmentSchema.optional(),
|
||||
})
|
||||
|
||||
export type Report = z.infer<typeof ReportSchema>
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { SpeciesManifest } from '@/domain/species/types'
|
||||
import { EQUINE_VERTEBRAL_FORMULA } from './vertebrae'
|
||||
|
||||
const equine: SpeciesManifest = {
|
||||
id: 'equine',
|
||||
labelFr: 'Cheval',
|
||||
labelEn: 'Horse',
|
||||
mainSvg: '/species/equine/Horse.svg',
|
||||
details: {
|
||||
head: '/species/equine/Horse_head.svg',
|
||||
},
|
||||
vertebralFormula: EQUINE_VERTEBRAL_FORMULA,
|
||||
findings: () => import('./pathologies'),
|
||||
}
|
||||
|
||||
// Default export is the convention picked up by the registry's
|
||||
// import.meta.glob() auto-discovery.
|
||||
export default equine
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,13 @@
|
||||
import {
|
||||
SpeciesFindingsSchema,
|
||||
type SpeciesFindings,
|
||||
} from '@/domain/schema/findings'
|
||||
import data from './pathologies.json'
|
||||
|
||||
/**
|
||||
* Equine findings tree. Authored as JSON, parsed via Zod at boot so any
|
||||
* malformed data crashes loudly instead of corrupting an observation later.
|
||||
*/
|
||||
const EQUINE_FINDINGS: SpeciesFindings = SpeciesFindingsSchema.parse(data)
|
||||
|
||||
export default EQUINE_FINDINGS
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { VertebralFormula } from '@/domain/species/types'
|
||||
|
||||
/**
|
||||
* Vertebral formula for the horse (Equus caballus).
|
||||
* Cd count capped at 18 for the picker — actual count varies 15–21.
|
||||
*/
|
||||
export const EQUINE_VERTEBRAL_FORMULA: VertebralFormula = {
|
||||
C: 7,
|
||||
T: 18,
|
||||
L: 6,
|
||||
S: 5,
|
||||
Cd: 18,
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { SpeciesManifest } from './types'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
|
||||
/**
|
||||
* Auto-discovers every species manifest in `src/domain/species/*\/index.ts`
|
||||
* via Vite's `import.meta.glob`. Each manifest module must default-export
|
||||
* its `SpeciesManifest`. Drop a new folder with a conforming `index.ts`
|
||||
* (and its `vertebrae.ts` + `pathologies.ts` siblings) and the species
|
||||
* shows up everywhere — the AnimalForm dropdown, the editor canvas,
|
||||
* the PDF export — without any registry edit.
|
||||
*
|
||||
* `eager: true` resolves modules synchronously at build time so the
|
||||
* registry is a plain object literal in the bundled output (no async
|
||||
* loading required to enumerate species).
|
||||
*/
|
||||
const modules = import.meta.glob<{ default: SpeciesManifest }>(
|
||||
'./*/index.ts',
|
||||
{ eager: true },
|
||||
)
|
||||
|
||||
function buildRegistry(): Record<string, SpeciesManifest> {
|
||||
const reg: Record<string, SpeciesManifest> = {}
|
||||
for (const [path, mod] of Object.entries(modules)) {
|
||||
const manifest = mod.default
|
||||
if (!manifest || typeof manifest.id !== 'string' || !manifest.id) {
|
||||
console.warn(`Species manifest at ${path} has no valid default export — skipping.`)
|
||||
continue
|
||||
}
|
||||
if (reg[manifest.id]) {
|
||||
console.warn(
|
||||
`Duplicate species id "${manifest.id}" — keeping the first one (from ${path} ignored).`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
reg[manifest.id] = manifest
|
||||
}
|
||||
return reg
|
||||
}
|
||||
|
||||
const SPECIES_REGISTRY: Record<string, SpeciesManifest> = buildRegistry()
|
||||
|
||||
/** Returns a species manifest by id, or undefined if not registered. */
|
||||
export function getSpecies(id: string): SpeciesManifest | undefined {
|
||||
return SPECIES_REGISTRY[id]
|
||||
}
|
||||
|
||||
/** Returns all registered species manifests, sorted alphabetically by labelFr. */
|
||||
export function getAllSpecies(): SpeciesManifest[] {
|
||||
return Object.values(SPECIES_REGISTRY).sort((a, b) =>
|
||||
a.labelFr.localeCompare(b.labelFr, 'fr'),
|
||||
)
|
||||
}
|
||||
|
||||
/** Display label of a species for the given locale. */
|
||||
export function speciesLabel(s: SpeciesManifest, locale: Locale): string {
|
||||
return locale === 'en' ? s.labelEn : s.labelFr
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { SpeciesFindings } from '@/domain/schema/findings'
|
||||
|
||||
/** Vertebral formula defines segment counts for a species. */
|
||||
export interface VertebralFormula {
|
||||
C: number
|
||||
T: number
|
||||
L: number
|
||||
S: number
|
||||
Cd: number
|
||||
}
|
||||
|
||||
/** Lazy import returning a module with a default export of SpeciesFindings. */
|
||||
export type FindingsLoader = () => Promise<{ default: SpeciesFindings }>
|
||||
|
||||
/** Species manifest — one per registered species. */
|
||||
export interface SpeciesManifest {
|
||||
id: string
|
||||
/** Display name in French */
|
||||
labelFr: string
|
||||
/** Display name in English */
|
||||
labelEn: string
|
||||
/** Absolute public path to the main anatomy SVG */
|
||||
mainSvg: string
|
||||
/**
|
||||
* Map of detail popup id → absolute public path to detail SVG.
|
||||
* Keys match data-anno-opens-detail attribute values in the main SVG.
|
||||
*/
|
||||
details: Record<string, string>
|
||||
vertebralFormula: VertebralFormula
|
||||
/** Lazy-loaded findings tree (zones + categories + leaves) for this species */
|
||||
findings: FindingsLoader
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import type { Dict } from './types'
|
||||
|
||||
export const en: Dict = {
|
||||
'common.cancel': 'Cancel',
|
||||
'common.close': 'Close',
|
||||
'common.save': 'Save',
|
||||
'common.confirm': 'Confirm',
|
||||
'common.delete': 'Delete',
|
||||
'common.add': 'Add',
|
||||
'common.home': 'Home',
|
||||
'common.understood': 'Got it',
|
||||
'common.collapse': 'Collapse',
|
||||
'common.expand': 'Expand',
|
||||
'common.move_up': 'Move up',
|
||||
'common.move_down': 'Move down',
|
||||
'common.back_to_home': 'Back to home',
|
||||
|
||||
'home.new_report.title': 'New report',
|
||||
'home.new_report.description': 'Start a new osteopathic report for an animal.',
|
||||
'home.new_report.cta': 'Start',
|
||||
'home.import.title': 'Import a PDF',
|
||||
'home.import.description': 'Reopen a previous report generated by this app to follow up.',
|
||||
'home.import.cta': 'Choose a PDF',
|
||||
'home.import.loading': 'Reading…',
|
||||
'home.import.error_generic': 'Failed to read the PDF.',
|
||||
'home.import.error_invalid_pdf': 'This file is not a readable PDF.',
|
||||
'home.import.error_no_attachment':
|
||||
'This PDF was not generated by Faunosteo (no data detected).',
|
||||
'home.import.error_incompatible_version':
|
||||
'This PDF uses format v{version}, incompatible with the current version (v2). Re-export the report from a recent version of the app.',
|
||||
|
||||
// footer
|
||||
'footer.all_rights_reserved': 'All rights reserved.',
|
||||
'footer.powered_by': 'Powered by',
|
||||
'footer.editors': 'Editors',
|
||||
'footer.in_partnership': 'In partnership with',
|
||||
|
||||
// editors page
|
||||
'editors.svg.title': 'SVG Editor',
|
||||
'editors.svg.description':
|
||||
'Annotate an anatomical SVG file: add clickable zones, categories, and FR/EN labels.',
|
||||
'editors.svg.cta': 'Open',
|
||||
'editors.pathology.title': 'Pathology Editor',
|
||||
'editors.pathology.description':
|
||||
'Create and edit the pathology catalog (JSON tree) for a species.',
|
||||
'editors.pathology.cta': 'Open',
|
||||
|
||||
'not_found.title': 'Page not found',
|
||||
'not_found.description': 'The requested path does not exist.',
|
||||
|
||||
'new_report.title': 'New report',
|
||||
'new_report.date_label': 'Report date',
|
||||
'new_report.submit': 'Start the report',
|
||||
|
||||
'editor.export': 'Export as PDF',
|
||||
'editor.exporting': 'Generating…',
|
||||
'editor.export_failed': 'PDF generation failed. Retry or contact support.',
|
||||
'editor.edit_infos': 'Edit info',
|
||||
'editor.edit_dialog_title': 'Edit information',
|
||||
'editor.disclaimer_title': 'Legal scope of animal osteopathy',
|
||||
'editor.detail_title_prefix': 'Detail — ',
|
||||
|
||||
'detail.click_to_add': 'Click the zones to add them to the current observation.',
|
||||
|
||||
'observation.section_title': 'Observations',
|
||||
'observation.add': '+ New observation',
|
||||
'observation.empty': 'No observation. Click "+ New observation" then on the zones in the diagram.',
|
||||
'observation.badge_n': 'Observation #',
|
||||
'observation.zone_label_singular': 'zone',
|
||||
'observation.zone_label_plural': 'zones',
|
||||
'observation.finding_label_singular': 'finding',
|
||||
'observation.finding_label_plural': 'findings',
|
||||
'observation.zones_label': 'Selected zones',
|
||||
'observation.zones_empty': 'Click on the zones in the diagram to add them to this observation.',
|
||||
'observation.findings_catalog_label': 'Findings (catalog)',
|
||||
'observation.findings_pick_zone_first': 'Pick a zone to access the catalog.',
|
||||
'observation.findings_no_catalog':
|
||||
'No catalog available for these zones. Use the free text below.',
|
||||
'observation.findings_free_label': 'Findings (free text)',
|
||||
'observation.free_placeholder': 'Additional observation (free text)',
|
||||
'observation.free_aria': 'Free observation',
|
||||
'observation.severity_label': 'Severity',
|
||||
'observation.comment_label': 'Comment',
|
||||
'observation.comment_placeholder': 'Detailed clinical notes…',
|
||||
'observation.vertebrae_button': 'Vertebrae…',
|
||||
'observation.vertebrae_button_title': 'Specify vertebrae for this zone',
|
||||
'observation.remove_zone': 'Remove',
|
||||
'observation.expand_aria': 'Expand observation',
|
||||
'observation.collapse_aria': 'Collapse observation',
|
||||
|
||||
'findings.back_to_parent': 'Back to previous level',
|
||||
'findings.back': '← Back',
|
||||
'findings.no_options': 'No option available at this level.',
|
||||
'findings.open': 'Open',
|
||||
'findings.vet_referral': 'Refer to a veterinarian',
|
||||
'findings.selected_singular': 'finding selected',
|
||||
'findings.selected_plural': 'findings selected',
|
||||
|
||||
'form.practitioner.legend': 'Practitioner',
|
||||
'form.practitioner.name': 'Full name *',
|
||||
'form.practitioner.cabinet': 'Practice / clinic',
|
||||
'form.practitioner.contact': 'Contact (phone, email…)',
|
||||
'form.practitioner.siret': 'SIRET',
|
||||
'form.animal.legend': 'Animal & owner',
|
||||
'form.animal.species': 'Species *',
|
||||
'form.animal.name': 'Animal name *',
|
||||
'form.animal.breed': 'Breed',
|
||||
'form.animal.age': 'Age',
|
||||
'form.owner.name': 'Owner name *',
|
||||
|
||||
'conclusion.section_title': 'Conclusion & recommendations',
|
||||
'conclusion.conclusion': 'Conclusion',
|
||||
'conclusion.recommendations': 'Recommendations',
|
||||
'conclusion.next_appointment': 'Next appointment',
|
||||
'conclusion.next_kind_date': 'Date',
|
||||
'conclusion.next_kind_period': 'Free period',
|
||||
'conclusion.next_kind_none': 'None',
|
||||
'conclusion.next_period_placeholder': 'e.g. in 3 weeks',
|
||||
|
||||
'vertebra.title_prefix': 'Specify vertebrae — ',
|
||||
'vertebra.region.C': 'Cervical',
|
||||
'vertebra.region.T': 'Thoracic',
|
||||
'vertebra.region.L': 'Lumbar',
|
||||
'vertebra.region.S': 'Sacral',
|
||||
'vertebra.region.Cd': 'Caudal',
|
||||
'vertebra.check_all': 'Select all',
|
||||
'vertebra.uncheck_all': 'Clear all',
|
||||
|
||||
// laterality
|
||||
'lateral.which_side': 'Which side?',
|
||||
'lateral.left': 'Left',
|
||||
'lateral.right': 'Right',
|
||||
'lateral.both': 'Both',
|
||||
'lateral.left_short': 'L',
|
||||
'lateral.right_short': 'R',
|
||||
|
||||
'severity.aria': 'Severity',
|
||||
'severity.légère': 'mild',
|
||||
'severity.modérée': 'moderate',
|
||||
'severity.sévère': 'severe',
|
||||
|
||||
'pdf.eyebrow.observation': 'OBSERVATION',
|
||||
'pdf.eyebrow.synthesis': 'SYNTHESIS',
|
||||
'pdf.title.conclusion': 'Conclusion',
|
||||
'pdf.section.zones': 'ZONES',
|
||||
'pdf.section.findings_prefix': 'FINDINGS — ',
|
||||
'pdf.section.free_findings': 'FREE FINDINGS',
|
||||
'pdf.section.severity': 'SEVERITY',
|
||||
'pdf.section.comment': 'COMMENT',
|
||||
'pdf.section.conclusion': 'CONCLUSION',
|
||||
'pdf.section.recommendations': 'RECOMMENDATIONS',
|
||||
'pdf.section.next_appointment': 'NEXT APPOINTMENT',
|
||||
'pdf.view.general': 'GENERAL VIEW',
|
||||
'pdf.view.detail_prefix': 'DETAIL VIEW — ',
|
||||
'pdf.empty': '—',
|
||||
'pdf.owner_prefix': 'Owner: ',
|
||||
'pdf.siret_prefix': 'SIRET ',
|
||||
'pdf.title.suffix.bilan': 'Osteo report — ',
|
||||
'pdf.subject': 'Animal osteopathic report',
|
||||
|
||||
'lang.group_label': 'Language',
|
||||
'lang.switch_to_fr': 'Passer en français',
|
||||
'lang.switch_to_en': 'Switch to English',
|
||||
'lang.fr': 'FR',
|
||||
'lang.en': 'EN',
|
||||
|
||||
// svg editor
|
||||
'svg_editor.title': 'SVG Anatomy Editor',
|
||||
'svg_editor.subtitle': 'Points, zones & clickable categories',
|
||||
'svg_editor.file': 'File',
|
||||
'svg_editor.choose_file': 'Choose an SVG file',
|
||||
'svg_editor.change_file': 'Change SVG file',
|
||||
'svg_editor.export': 'Export SVG',
|
||||
'svg_editor.mode': 'Mode',
|
||||
'svg_editor.mode_select': 'Select / move',
|
||||
'svg_editor.mode_point': 'Add point',
|
||||
'svg_editor.mode_polygon': 'Add polygon',
|
||||
'svg_editor.validate_polygon': 'Validate polygon (Enter)',
|
||||
'svg_editor.cancel_polygon': 'Cancel (Esc)',
|
||||
'svg_editor.category_for_new': 'Category for new elements',
|
||||
'svg_editor.categories': 'Categories',
|
||||
'svg_editor.shared_color': '(shared color)',
|
||||
'svg_editor.category_placeholder': 'Category name',
|
||||
'svg_editor.selected_element': 'Selected element',
|
||||
'svg_editor.opens_detail': 'This zone opens a detail view',
|
||||
'svg_editor.detail_id_label': 'Detail view ID (e.g. head, front-leg)',
|
||||
'svg_editor.detail_id_placeholder': 'head',
|
||||
'svg_editor.name_fr': 'French name',
|
||||
'svg_editor.name_fr_placeholder': 'e.g. Hanche',
|
||||
'svg_editor.name_en': 'English name',
|
||||
'svg_editor.name_en_placeholder': 'e.g. Hip joint',
|
||||
'svg_editor.category': 'Category',
|
||||
'svg_editor.radius': 'Radius (circle)',
|
||||
'svg_editor.fill_opacity': 'Fill opacity',
|
||||
'svg_editor.polygon_editing': 'Polygon editing:',
|
||||
'svg_editor.polygon_drag': 'Drag a yellow handle to move it',
|
||||
'svg_editor.polygon_insert': 'Click a white mid-handle to insert a vertex',
|
||||
'svg_editor.polygon_delete': 'Alt+click or right-click a yellow handle to delete it',
|
||||
'svg_editor.redraw_polygon': 'Redraw this polygon',
|
||||
'svg_editor.delete': 'Delete',
|
||||
'svg_editor.elements': 'Elements',
|
||||
'svg_editor.filter_placeholder': 'Filter...',
|
||||
'svg_editor.welcome_title': 'SVG Anatomy Editor',
|
||||
'svg_editor.welcome_text': 'Upload an SVG file to begin. If your file already has points/zones with ',
|
||||
'svg_editor.welcome_text_suffix': ', they will be detected and configured automatically.',
|
||||
'svg_editor.welcome_drag_hint': 'or drag & drop an SVG file anywhere',
|
||||
'svg_editor.no_categories': 'No categories yet. Use the form below to add one.',
|
||||
'svg_editor.new_point_fr': 'Nouveau point',
|
||||
'svg_editor.new_point_en': 'New point',
|
||||
'svg_editor.new_zone_fr': 'Nouvelle zone',
|
||||
'svg_editor.new_zone_en': 'New zone',
|
||||
'svg_editor.alert_drop_svg': 'Drop an SVG file.',
|
||||
'svg_editor.alert_invalid_svg': 'Invalid file: no SVG element found.',
|
||||
'svg_editor.alert_min_3': 'Need at least 3 points.',
|
||||
'svg_editor.alert_min_3_vertices': 'A polygon must have at least 3 vertices.',
|
||||
'svg_editor.alert_upload_first': 'Upload an SVG first.',
|
||||
'svg_editor.alert_no_svg_loaded': 'No SVG loaded. Upload a file first.',
|
||||
'svg_editor.alert_cat_name_required': 'Give the category a name.',
|
||||
'svg_editor.alert_cat_invalid_name': 'Invalid name.',
|
||||
'svg_editor.alert_cat_exists': 'This category already exists.',
|
||||
'svg_editor.confirm_delete_element': 'Delete this element?',
|
||||
'svg_editor.confirm_delete_cat': 'Delete category "{name}"?',
|
||||
'svg_editor.confirm_delete_cat_count': '\n\nIt contains {count} element(s) that will also be deleted.',
|
||||
'svg_editor.confirm_redraw': 'Erase this polygon and redraw it?',
|
||||
'svg_editor.handle_drag': 'Drag to move | Alt+click or right-click to delete',
|
||||
'svg_editor.handle_insert': 'Click to insert a vertex here',
|
||||
'svg_editor.polygon_vertices': 'polygon ({count} vertices)',
|
||||
'svg_editor.drop_svg_here': 'Drop SVG here',
|
||||
'svg_editor.lateral': 'Laterality',
|
||||
'svg_editor.lateral_unpaired': 'Unilateral (no side)',
|
||||
'svg_editor.lateral_bilateral': 'Bilateral (left / right)',
|
||||
'svg_editor.source_project': 'Project SVGs',
|
||||
'svg_editor.source_upload': 'Upload a file',
|
||||
'svg_editor.species': 'Species',
|
||||
'svg_editor.view': 'View',
|
||||
'svg_editor.view_main': 'Full body',
|
||||
'svg_editor.view_detail': 'Detail: {name}',
|
||||
'svg_editor.load': 'Load',
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
import type { Dict } from './types'
|
||||
|
||||
export const fr: Dict = {
|
||||
// common
|
||||
'common.cancel': 'Annuler',
|
||||
'common.close': 'Fermer',
|
||||
'common.save': 'Enregistrer',
|
||||
'common.confirm': 'Valider',
|
||||
'common.delete': 'Supprimer',
|
||||
'common.add': 'Ajouter',
|
||||
'common.home': 'Accueil',
|
||||
'common.understood': 'Compris',
|
||||
'common.collapse': 'Réduire',
|
||||
'common.expand': 'Développer',
|
||||
'common.move_up': 'Monter',
|
||||
'common.move_down': 'Descendre',
|
||||
'common.back_to_home': "Retour à l'accueil",
|
||||
|
||||
// home
|
||||
'home.new_report.title': 'Nouveau bilan',
|
||||
'home.new_report.description': "Démarrer un nouveau bilan d'ostéopathie sur un animal.",
|
||||
'home.new_report.cta': 'Commencer',
|
||||
'home.import.title': 'Importer un PDF',
|
||||
'home.import.description':
|
||||
"Reprendre un bilan précédent généré par cette application pour effectuer un suivi.",
|
||||
'home.import.cta': 'Choisir un PDF',
|
||||
'home.import.loading': 'Lecture…',
|
||||
'home.import.error_generic': 'Erreur de lecture du PDF.',
|
||||
'home.import.error_invalid_pdf':
|
||||
"Ce fichier n'est pas un PDF lisible.",
|
||||
'home.import.error_no_attachment':
|
||||
"Ce PDF n'a pas été généré par Faunosteo (pas de données détectées).",
|
||||
'home.import.error_incompatible_version':
|
||||
"Ce PDF est au format v{version}, incompatible avec la version actuelle (v2). Réexportez le bilan depuis une version récente de l'application.",
|
||||
|
||||
// footer
|
||||
'footer.all_rights_reserved': 'Tous droits réservés.',
|
||||
'footer.powered_by': 'Propulsé par',
|
||||
'footer.editors': 'Éditeurs',
|
||||
'footer.in_partnership': 'En partenariat avec',
|
||||
|
||||
// editors page
|
||||
'editors.svg.title': 'Éditeur SVG',
|
||||
'editors.svg.description':
|
||||
'Annoter un fichier SVG anatomique : ajouter des zones cliquables, catégories et labels FR/EN.',
|
||||
'editors.svg.cta': 'Ouvrir',
|
||||
'editors.pathology.title': 'Éditeur de pathologies',
|
||||
'editors.pathology.description':
|
||||
'Créer et modifier le référentiel de pathologies (arbre JSON) pour une espèce.',
|
||||
'editors.pathology.cta': 'Ouvrir',
|
||||
|
||||
// not found
|
||||
'not_found.title': 'Page introuvable',
|
||||
'not_found.description': "Le chemin demandé n'existe pas.",
|
||||
|
||||
// new report
|
||||
'new_report.title': 'Nouveau bilan',
|
||||
'new_report.date_label': 'Date du bilan',
|
||||
'new_report.submit': 'Démarrer le bilan',
|
||||
|
||||
// editor
|
||||
'editor.export': 'Exporter en PDF',
|
||||
'editor.exporting': 'Génération…',
|
||||
'editor.export_failed': 'Échec de la génération du PDF. Réessayez ou contactez le support.',
|
||||
'editor.edit_infos': 'Modifier les infos',
|
||||
'editor.edit_dialog_title': 'Modifier les informations',
|
||||
'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale",
|
||||
'editor.detail_title_prefix': 'Détail — ',
|
||||
|
||||
// detail modal
|
||||
'detail.click_to_add': "Cliquez sur les zones pour les ajouter à l'observation en cours.",
|
||||
|
||||
// observation list / card
|
||||
'observation.section_title': 'Observations',
|
||||
'observation.add': '+ Nouvelle observation',
|
||||
'observation.empty':
|
||||
'Aucune observation. Cliquez sur "+ Nouvelle observation" puis sur les zones du schéma.',
|
||||
'observation.badge_n': 'Observation #',
|
||||
'observation.zone_label_singular': 'zone',
|
||||
'observation.zone_label_plural': 'zones',
|
||||
'observation.finding_label_singular': 'constat',
|
||||
'observation.finding_label_plural': 'constats',
|
||||
'observation.zones_label': 'Zones sélectionnées',
|
||||
'observation.zones_empty': 'Cliquez sur les zones du schéma pour les ajouter à cette observation.',
|
||||
'observation.findings_catalog_label': 'Constats (référentiel)',
|
||||
'observation.findings_pick_zone_first': 'Sélectionnez une zone pour accéder au référentiel.',
|
||||
'observation.findings_no_catalog':
|
||||
'Aucun référentiel disponible pour ces zones. Utilisez le texte libre ci-dessous.',
|
||||
'observation.findings_free_label': 'Constats (texte libre)',
|
||||
'observation.free_placeholder': 'Observation additionnelle (texte libre)',
|
||||
'observation.free_aria': 'Observation libre',
|
||||
'observation.severity_label': 'Sévérité',
|
||||
'observation.comment_label': 'Commentaire',
|
||||
'observation.comment_placeholder': 'Notes cliniques détaillées…',
|
||||
'observation.vertebrae_button': 'Vertèbres…',
|
||||
'observation.vertebrae_button_title': 'Préciser les vertèbres pour cette zone',
|
||||
'observation.remove_zone': 'Retirer',
|
||||
'observation.expand_aria': "Développer l'observation",
|
||||
'observation.collapse_aria': "Réduire l'observation",
|
||||
|
||||
// findings tree picker
|
||||
'findings.back_to_parent': 'Retour au niveau précédent',
|
||||
'findings.back': '← Retour',
|
||||
'findings.no_options': 'Aucune option disponible à ce niveau.',
|
||||
'findings.open': 'Ouvrir',
|
||||
'findings.vet_referral': 'Référer au vétérinaire',
|
||||
'findings.selected_singular': 'constat sélectionné',
|
||||
'findings.selected_plural': 'constats sélectionnés',
|
||||
|
||||
// forms
|
||||
'form.practitioner.legend': 'Praticien',
|
||||
'form.practitioner.name': 'Nom complet *',
|
||||
'form.practitioner.cabinet': 'Cabinet / clinique',
|
||||
'form.practitioner.contact': 'Contact (téléphone, email…)',
|
||||
'form.practitioner.siret': 'SIRET',
|
||||
'form.animal.legend': 'Animal & propriétaire',
|
||||
'form.animal.species': 'Espèce *',
|
||||
'form.animal.name': "Nom de l'animal *",
|
||||
'form.animal.breed': 'Race',
|
||||
'form.animal.age': 'Âge',
|
||||
'form.owner.name': 'Nom du propriétaire *',
|
||||
|
||||
// conclusion panel
|
||||
'conclusion.section_title': 'Conclusion & recommandations',
|
||||
'conclusion.conclusion': 'Conclusion',
|
||||
'conclusion.recommendations': 'Recommandations',
|
||||
'conclusion.next_appointment': 'Prochain rendez-vous',
|
||||
'conclusion.next_kind_date': 'Date',
|
||||
'conclusion.next_kind_period': 'Période libre',
|
||||
'conclusion.next_kind_none': 'Aucun',
|
||||
'conclusion.next_period_placeholder': 'ex. dans 3 semaines',
|
||||
|
||||
// vertebra picker
|
||||
'vertebra.title_prefix': 'Préciser les vertèbres — ',
|
||||
'vertebra.region.C': 'Cervicales',
|
||||
'vertebra.region.T': 'Thoraciques',
|
||||
'vertebra.region.L': 'Lombaires',
|
||||
'vertebra.region.S': 'Sacrales',
|
||||
'vertebra.region.Cd': 'Caudales',
|
||||
'vertebra.check_all': 'Tout cocher',
|
||||
'vertebra.uncheck_all': 'Tout décocher',
|
||||
|
||||
// laterality
|
||||
'lateral.which_side': 'Quel côté ?',
|
||||
'lateral.left': 'Gauche',
|
||||
'lateral.right': 'Droite',
|
||||
'lateral.both': 'Les deux',
|
||||
'lateral.left_short': 'G',
|
||||
'lateral.right_short': 'D',
|
||||
|
||||
// severity
|
||||
'severity.aria': 'Sévérité',
|
||||
'severity.légère': 'légère',
|
||||
'severity.modérée': 'modérée',
|
||||
'severity.sévère': 'sévère',
|
||||
|
||||
// pdf
|
||||
'pdf.eyebrow.observation': 'OBSERVATION',
|
||||
'pdf.eyebrow.synthesis': 'SYNTHÈSE',
|
||||
'pdf.title.conclusion': 'Conclusion',
|
||||
'pdf.section.zones': 'ZONES',
|
||||
'pdf.section.findings_prefix': 'CONSTATS — ',
|
||||
'pdf.section.free_findings': 'CONSTATS LIBRES',
|
||||
'pdf.section.severity': 'SÉVÉRITÉ',
|
||||
'pdf.section.comment': 'COMMENTAIRE',
|
||||
'pdf.section.conclusion': 'CONCLUSION',
|
||||
'pdf.section.recommendations': 'RECOMMANDATIONS',
|
||||
'pdf.section.next_appointment': 'PROCHAIN RENDEZ-VOUS',
|
||||
'pdf.view.general': 'VUE GÉNÉRALE',
|
||||
'pdf.view.detail_prefix': 'VUE DÉTAIL — ',
|
||||
'pdf.empty': '—',
|
||||
'pdf.owner_prefix': 'Propriétaire : ',
|
||||
'pdf.siret_prefix': 'SIRET ',
|
||||
'pdf.title.suffix.bilan': 'Bilan ostéo — ',
|
||||
'pdf.subject': "Bilan d'ostéopathie animalière",
|
||||
|
||||
// language switcher
|
||||
'lang.group_label': 'Langue',
|
||||
'lang.switch_to_fr': 'Passer en français',
|
||||
'lang.switch_to_en': 'Switch to English',
|
||||
'lang.fr': 'FR',
|
||||
'lang.en': 'EN',
|
||||
|
||||
// svg editor
|
||||
'svg_editor.title': 'Editeur SVG anatomique',
|
||||
'svg_editor.subtitle': 'Points, zones & catégories cliquables',
|
||||
'svg_editor.file': 'Fichier',
|
||||
'svg_editor.choose_file': 'Choisir un fichier SVG',
|
||||
'svg_editor.change_file': 'Changer de fichier SVG',
|
||||
'svg_editor.export': 'Exporter le SVG',
|
||||
'svg_editor.mode': 'Mode',
|
||||
'svg_editor.mode_select': 'Sélectionner / déplacer',
|
||||
'svg_editor.mode_point': 'Ajouter un point',
|
||||
'svg_editor.mode_polygon': 'Ajouter un polygone',
|
||||
'svg_editor.validate_polygon': 'Valider le polygone (Entrée)',
|
||||
'svg_editor.cancel_polygon': 'Annuler (Echap)',
|
||||
'svg_editor.category_for_new': 'Catégorie des nouveaux éléments',
|
||||
'svg_editor.categories': 'Catégories',
|
||||
'svg_editor.shared_color': '(couleur partagée)',
|
||||
'svg_editor.category_placeholder': 'Nom de catégorie',
|
||||
'svg_editor.selected_element': 'Elément sélectionné',
|
||||
'svg_editor.opens_detail': 'Cette zone ouvre une vue détaillée',
|
||||
'svg_editor.detail_id_label': 'ID vue détaillée (ex. head, front-leg)',
|
||||
'svg_editor.detail_id_placeholder': 'head',
|
||||
'svg_editor.name_fr': 'Nom français',
|
||||
'svg_editor.name_fr_placeholder': 'ex: Hanche',
|
||||
'svg_editor.name_en': 'Nom anglais',
|
||||
'svg_editor.name_en_placeholder': 'ex: Hip joint',
|
||||
'svg_editor.category': 'Catégorie',
|
||||
'svg_editor.radius': 'Rayon (cercle)',
|
||||
'svg_editor.fill_opacity': 'Opacité du remplissage',
|
||||
'svg_editor.polygon_editing': 'Edition du polygone :',
|
||||
'svg_editor.polygon_drag': 'Glissez une poignée jaune pour la déplacer',
|
||||
'svg_editor.polygon_insert': 'Cliquez une poignée blanche pour insérer un sommet',
|
||||
'svg_editor.polygon_delete': 'Alt+clic ou clic droit sur une poignée jaune pour la supprimer',
|
||||
'svg_editor.redraw_polygon': 'Redessiner ce polygone',
|
||||
'svg_editor.delete': 'Supprimer',
|
||||
'svg_editor.elements': 'Eléments',
|
||||
'svg_editor.filter_placeholder': 'Filtrer...',
|
||||
'svg_editor.welcome_title': 'Editeur SVG anatomique',
|
||||
'svg_editor.welcome_text': 'Importez un fichier SVG pour commencer. Si votre fichier contient déjà des points/zones avec ',
|
||||
'svg_editor.welcome_text_suffix': ', ils seront détectés et configurés automatiquement.',
|
||||
'svg_editor.welcome_drag_hint': 'ou glissez-déposez un fichier SVG n\'importe où',
|
||||
'svg_editor.no_categories': 'Aucune catégorie. Utilisez le formulaire ci-dessous pour en ajouter une.',
|
||||
'svg_editor.new_point_fr': 'Nouveau point',
|
||||
'svg_editor.new_point_en': 'New point',
|
||||
'svg_editor.new_zone_fr': 'Nouvelle zone',
|
||||
'svg_editor.new_zone_en': 'New zone',
|
||||
'svg_editor.alert_drop_svg': 'Déposez un fichier SVG.',
|
||||
'svg_editor.alert_invalid_svg': 'Fichier invalide : aucun élément SVG trouvé.',
|
||||
'svg_editor.alert_min_3': 'Il faut au moins 3 points.',
|
||||
'svg_editor.alert_min_3_vertices': 'Un polygone doit avoir au moins 3 sommets.',
|
||||
'svg_editor.alert_upload_first': 'Importez d\'abord un SVG.',
|
||||
'svg_editor.alert_no_svg_loaded': 'Aucun SVG chargé. Importez d\'abord un fichier.',
|
||||
'svg_editor.alert_cat_name_required': 'Donnez un nom à la catégorie.',
|
||||
'svg_editor.alert_cat_invalid_name': 'Nom invalide.',
|
||||
'svg_editor.alert_cat_exists': 'Cette catégorie existe déjà.',
|
||||
'svg_editor.confirm_delete_element': 'Supprimer cet élément ?',
|
||||
'svg_editor.confirm_delete_cat': 'Supprimer la catégorie "{name}" ?',
|
||||
'svg_editor.confirm_delete_cat_count': '\n\nElle contient {count} élément(s) qui seront aussi supprimés.',
|
||||
'svg_editor.confirm_redraw': 'Effacer ce polygone et le redessiner ?',
|
||||
'svg_editor.handle_drag': 'Glisser pour déplacer | Alt+clic ou clic droit pour supprimer',
|
||||
'svg_editor.handle_insert': 'Cliquez pour insérer un sommet ici',
|
||||
'svg_editor.polygon_vertices': 'polygone ({count} sommets)',
|
||||
'svg_editor.drop_svg_here': 'Déposez le SVG ici',
|
||||
'svg_editor.lateral': 'Latéralité',
|
||||
'svg_editor.lateral_unpaired': 'Unilatéral (pas de côté)',
|
||||
'svg_editor.lateral_bilateral': 'Bilatéral (gauche / droite)',
|
||||
'svg_editor.source_project': 'SVG du projet',
|
||||
'svg_editor.source_upload': 'Importer un fichier',
|
||||
'svg_editor.species': 'Espèce',
|
||||
'svg_editor.view': 'Vue',
|
||||
'svg_editor.view_main': 'Corps entier',
|
||||
'svg_editor.view_detail': 'Détail : {name}',
|
||||
'svg_editor.load': 'Charger',
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { fr } from './fr'
|
||||
import { en } from './en'
|
||||
import type { Dict, Locale } from './types'
|
||||
|
||||
export const dicts: Record<Locale, Dict> = { fr, en }
|
||||
|
||||
export function getDict(locale: Locale): Dict {
|
||||
return dicts[locale]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { Locale } from './types'
|
||||
|
||||
/**
|
||||
* Resolves a bilingual label for the active locale. Falls back to the
|
||||
* opposite language when the preferred one is missing/empty, then to the
|
||||
* provided fallback, so callers never render an empty string.
|
||||
*/
|
||||
export function pickLocaleLabel(
|
||||
fr: string | undefined,
|
||||
en: string | undefined,
|
||||
locale: Locale,
|
||||
fallback = '',
|
||||
): string {
|
||||
if (locale === 'en') return en || fr || fallback
|
||||
return fr || en || fallback
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export type Locale = 'fr' | 'en'
|
||||
export type Dict = Record<string, string>
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { getDict } from './index'
|
||||
|
||||
export function useT(): (key: string) => string {
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const dict = getDict(locale)
|
||||
return (key: string) => {
|
||||
const v = dict[key]
|
||||
if (v === undefined) {
|
||||
if (import.meta.env?.DEV) {
|
||||
console.warn(`i18n: missing key "${key}" for locale "${locale}"`)
|
||||
}
|
||||
return key
|
||||
}
|
||||
return v
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Asserts a condition is truthy; throws with the given message otherwise.
|
||||
* Use to enforce invariants at runtime boundaries.
|
||||
*/
|
||||
export function assert(condition: unknown, message: string): asserts condition {
|
||||
if (!condition) {
|
||||
throw new Error(`Assertion failed: ${message}`)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { Locale } from '@/i18n/types'
|
||||
|
||||
export function todayIso(): string {
|
||||
return new Date().toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
export function nowIso(): string {
|
||||
return new Date().toISOString()
|
||||
}
|
||||
|
||||
const LOCALE_TAG: Record<Locale, string> = {
|
||||
fr: 'fr-FR',
|
||||
en: 'en-US',
|
||||
}
|
||||
|
||||
export function formatDate(isoDate: string, locale: Locale): string {
|
||||
const match = isoDate.match(/^(\d{4})-(\d{2})-(\d{2})$/)
|
||||
if (!match) throw new Error(`Invalid ISO date: ${isoDate}`)
|
||||
const [, y, mo, d] = match
|
||||
const date = new Date(Date.UTC(Number(y), Number(mo) - 1, Number(d)))
|
||||
if (Number.isNaN(date.getTime())) throw new Error(`Invalid ISO date: ${isoDate}`)
|
||||
return new Intl.DateTimeFormat(LOCALE_TAG[locale], {
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
timeZone: 'UTC',
|
||||
}).format(date)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Generates a collision-resistant unique id using crypto.randomUUID().
|
||||
* Falls back to a timestamp-based id in environments without crypto.
|
||||
*/
|
||||
export function generateId(): string {
|
||||
if (
|
||||
typeof crypto !== 'undefined' &&
|
||||
typeof crypto.randomUUID === 'function'
|
||||
) {
|
||||
return crypto.randomUUID()
|
||||
}
|
||||
return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import type {
|
||||
ObservationZone,
|
||||
Vertebra,
|
||||
VertebralRegion,
|
||||
} from '@/domain/schema/observation'
|
||||
import type { Bone } from '@/anatomy/types'
|
||||
|
||||
/**
|
||||
* Infers the matching vertebral region from a free-form anatomical label
|
||||
* (zone name in FR or EN). Matches on substring roots, case-insensitive,
|
||||
* accent-insensitive. Returns undefined when no root matches.
|
||||
*/
|
||||
export function regionFromLabel(label: string): VertebralRegion | undefined {
|
||||
const norm = label
|
||||
.normalize('NFD')
|
||||
.replace(/\p{Diacritic}/gu, '')
|
||||
.toLowerCase()
|
||||
if (norm.includes('cervic')) return 'C'
|
||||
if (norm.includes('thorac') || norm.includes('dors')) return 'T'
|
||||
if (norm.includes('lombair') || norm.includes('lumbar')) return 'L'
|
||||
if (norm.includes('sacral') || norm.includes('sacre')) return 'S'
|
||||
if (norm.includes('caudal') || norm.includes('coccyg')) return 'Cd'
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the spine-zone boneId whose label maps to the given vertebral region.
|
||||
* Spine zones are the SVG elements flagged data-anno-special="vertebral-precision".
|
||||
* Returns undefined when the SVG exposes no zone for that region.
|
||||
*/
|
||||
export function findSpineZoneId(
|
||||
region: VertebralRegion,
|
||||
bones: Map<string, Bone>,
|
||||
): string | undefined {
|
||||
for (const [id, bone] of bones) {
|
||||
if (bone.special !== 'vertebral-precision') continue
|
||||
const r = regionFromLabel(bone.fr) ?? regionFromLabel(bone.en)
|
||||
if (r === region) return id
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
const key = (v: Vertebra) => `${v.region}${v.index}`
|
||||
|
||||
const isSpineZone = (z: ObservationZone, bones: Map<string, Bone>) =>
|
||||
!z.detailSourceId && bones.get(z.boneId)?.special === 'vertebral-precision'
|
||||
|
||||
/**
|
||||
* Gathers the union of vertebrae across every spine zone of an observation so
|
||||
* the picker can show selections from all regions at once. `priorityBoneId`'s
|
||||
* vertebrae are listed first so the picker opens on the clicked zone's tab
|
||||
* (the picker keys its default tab off the first vertebra's region).
|
||||
*
|
||||
* Deduplicated by region+index; order otherwise follows zone order.
|
||||
*/
|
||||
export function collectSpineVertebrae(
|
||||
zones: ObservationZone[],
|
||||
bones: Map<string, Bone>,
|
||||
priorityBoneId?: string,
|
||||
): Vertebra[] {
|
||||
const spine = zones.filter((z) => isSpineZone(z, bones))
|
||||
const ordered = priorityBoneId
|
||||
? [
|
||||
...spine.filter((z) => z.boneId === priorityBoneId),
|
||||
...spine.filter((z) => z.boneId !== priorityBoneId),
|
||||
]
|
||||
: spine
|
||||
|
||||
const out: Vertebra[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const z of ordered) {
|
||||
for (const v of z.vertebrae ?? []) {
|
||||
if (seen.has(key(v))) continue
|
||||
seen.add(key(v))
|
||||
out.push(v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconciles the observation's spine zones with the full set of vertebrae the
|
||||
* picker confirmed (the picker shows and edits every region at once).
|
||||
*
|
||||
* Authoritative per region: each region's zone gets exactly the vertebrae
|
||||
* picked for it (replace, so unchecking sticks); a region with no vertebrae
|
||||
* left has its spine zone pruned; a region picked for the first time spawns its
|
||||
* zone so the SVG highlights it and its findings picker appears. Non-spine
|
||||
* zones (and their order) are preserved untouched.
|
||||
*
|
||||
* Returns a new zones array; the original is not mutated.
|
||||
*/
|
||||
export function syncSpineZones(
|
||||
zones: ObservationZone[],
|
||||
vertebrae: Vertebra[],
|
||||
bones: Map<string, Bone>,
|
||||
): ObservationZone[] {
|
||||
const byRegion = new Map<VertebralRegion, Vertebra[]>()
|
||||
for (const v of vertebrae) {
|
||||
byRegion.set(v.region, [...(byRegion.get(v.region) ?? []), v])
|
||||
}
|
||||
|
||||
const result: ObservationZone[] = []
|
||||
const handled = new Set<VertebralRegion>()
|
||||
|
||||
for (const z of zones) {
|
||||
const bone = bones.get(z.boneId)
|
||||
const region =
|
||||
!z.detailSourceId && bone?.special === 'vertebral-precision'
|
||||
? (regionFromLabel(bone.fr) ?? regionFromLabel(bone.en))
|
||||
: undefined
|
||||
// Non-spine, detail-sourced, or unrecognized-label zones pass through.
|
||||
if (!region) {
|
||||
result.push(z)
|
||||
continue
|
||||
}
|
||||
const verts = byRegion.get(region)
|
||||
if (!verts) continue // region deselected to zero → prune the zone
|
||||
result.push({ ...z, vertebrae: verts })
|
||||
handled.add(region)
|
||||
}
|
||||
|
||||
// Regions picked that had no existing zone yet → spawn one.
|
||||
for (const [region, verts] of byRegion) {
|
||||
if (handled.has(region)) continue
|
||||
const zoneId = findSpineZoneId(region, bones)
|
||||
if (zoneId) result.push({ boneId: zoneId, vertebrae: verts })
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import type { ZoneFindings } from '@/domain/schema/findings'
|
||||
|
||||
/**
|
||||
* Bridges SVG anatomy labels to the JSON findings catalog when the two
|
||||
* carry slightly different strings (casse, accents, abbreviations like
|
||||
* "(ATM)" vs "Articulation Temporo-Mandibulaire (ATM)", or genuine typos).
|
||||
*
|
||||
* Strategy: normalize aggressively (lowercase + NFD-strip accents + drop
|
||||
* non-alphanumerics), then score each (boneLabel, zoneLabel) pair:
|
||||
*
|
||||
* 0 exact normalized match
|
||||
* 1 one normalized string is contained in the other (substring)
|
||||
* 2+d Levenshtein distance d, within a length-relative threshold
|
||||
* ∞ beyond tolerance — discarded
|
||||
*
|
||||
* Language strategy: English first (no accents → fewer normalization
|
||||
* edge cases), French as fallback, fuzzy matching across both languages
|
||||
* as last resort. Falls through silently when nothing matches.
|
||||
*/
|
||||
|
||||
export function normalizeLabel(s: string | undefined | null): string {
|
||||
if (!s) return ''
|
||||
return s
|
||||
.toLowerCase()
|
||||
.normalize('NFD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.replace(/[^a-z0-9]+/g, '')
|
||||
}
|
||||
|
||||
export function levenshtein(a: string, b: string): number {
|
||||
if (a === b) return 0
|
||||
const al = a.length
|
||||
const bl = b.length
|
||||
if (al === 0) return bl
|
||||
if (bl === 0) return al
|
||||
let prev: number[] = new Array(bl + 1)
|
||||
let curr: number[] = new Array(bl + 1)
|
||||
for (let j = 0; j <= bl; j += 1) prev[j] = j
|
||||
for (let i = 1; i <= al; i += 1) {
|
||||
curr[0] = i
|
||||
for (let j = 1; j <= bl; j += 1) {
|
||||
const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1
|
||||
curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost)
|
||||
}
|
||||
const tmp = prev
|
||||
prev = curr
|
||||
curr = tmp
|
||||
}
|
||||
return prev[bl]
|
||||
}
|
||||
|
||||
const SCORE_EXACT = 0
|
||||
const SCORE_SUBSTRING = 1
|
||||
const SCORE_FUZZY_BASE = 2
|
||||
const SCORE_NO_MATCH = Number.POSITIVE_INFINITY
|
||||
|
||||
/**
|
||||
* Compares two raw labels after normalization. Lower scores beat higher
|
||||
* ones; SCORE_NO_MATCH means the inputs are too dissimilar to be linked
|
||||
* confidently.
|
||||
*/
|
||||
export function scorePair(boneLabel: string, zoneLabel: string): number {
|
||||
const a = normalizeLabel(boneLabel)
|
||||
const b = normalizeLabel(zoneLabel)
|
||||
if (!a || !b) return SCORE_NO_MATCH
|
||||
if (a === b) return SCORE_EXACT
|
||||
if (a.includes(b) || b.includes(a)) return SCORE_SUBSTRING
|
||||
const distance = levenshtein(a, b)
|
||||
const longest = Math.max(a.length, b.length)
|
||||
// 25% character tolerance, with a minimum of 2 edits so short labels
|
||||
// (e.g. "Hip") still admit one typo without exploding into the matcher.
|
||||
const threshold = Math.max(2, Math.floor(longest * 0.25))
|
||||
if (distance > threshold) return SCORE_NO_MATCH
|
||||
return SCORE_FUZZY_BASE + distance
|
||||
}
|
||||
|
||||
export interface BoneLabels {
|
||||
fr: string
|
||||
en: string
|
||||
}
|
||||
|
||||
interface ScoredZone {
|
||||
zone: ZoneFindings
|
||||
score: number
|
||||
}
|
||||
|
||||
function bestOnLanguage(
|
||||
boneLabel: string,
|
||||
zones: ZoneFindings[],
|
||||
pickZoneLabel: (zone: ZoneFindings) => string,
|
||||
): ScoredZone | undefined {
|
||||
let best: ScoredZone | undefined
|
||||
for (const zone of zones) {
|
||||
const score = scorePair(boneLabel, pickZoneLabel(zone))
|
||||
if (score === SCORE_NO_MATCH) continue
|
||||
if (!best || score < best.score) best = { zone, score }
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the findings tree most likely to describe a clicked SVG zone.
|
||||
*
|
||||
* 1. If the English bone label exactly matches (or is contained in) an
|
||||
* English zone label, return that zone — cheapest, most reliable.
|
||||
* 2. Otherwise try the same on the French side.
|
||||
* 3. As a last resort, take the lowest fuzzy score across all four
|
||||
* (bone-lang, zone-lang) pairings.
|
||||
*/
|
||||
export function matchZoneFindings(
|
||||
bone: BoneLabels,
|
||||
zones: ZoneFindings[],
|
||||
): ZoneFindings | undefined {
|
||||
if (zones.length === 0) return undefined
|
||||
|
||||
const enOnEn = bestOnLanguage(bone.en, zones, (z) => z.name_en)
|
||||
if (enOnEn && enOnEn.score <= SCORE_SUBSTRING) return enOnEn.zone
|
||||
|
||||
const frOnFr = bestOnLanguage(bone.fr, zones, (z) => z.name_fr)
|
||||
if (frOnFr && frOnFr.score <= SCORE_SUBSTRING) return frOnFr.zone
|
||||
|
||||
const enOnFr = bestOnLanguage(bone.en, zones, (z) => z.name_fr)
|
||||
const frOnEn = bestOnLanguage(bone.fr, zones, (z) => z.name_en)
|
||||
const candidates = [enOnEn, frOnFr, enOnFr, frOnEn].filter(
|
||||
(x): x is ScoredZone => x !== undefined,
|
||||
)
|
||||
if (candidates.length === 0) return undefined
|
||||
candidates.sort((a, b) => a.score - b.score)
|
||||
return candidates[0].zone
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import '@/styles/index.css'
|
||||
import App from '@/app/App'
|
||||
|
||||
const rootEl = document.getElementById('root')
|
||||
|
||||
if (!rootEl) {
|
||||
throw new Error('Root element #root not found in the document')
|
||||
}
|
||||
|
||||
createRoot(rootEl).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,132 @@
|
||||
import { AFRelationship, type PDFDocument } from 'pdf-lib'
|
||||
import { ReportSchema, type Report } from '@/domain/schema/report'
|
||||
|
||||
const FILENAME = 'osteo-report.json'
|
||||
|
||||
/**
|
||||
* Internal sentinel raised when the attached JSON's `version` field is
|
||||
* present but not 2. The UI-facing message is composed by the importer
|
||||
* caller against the active i18n dict — this error only carries the
|
||||
* discriminating data.
|
||||
*/
|
||||
export class IncompatibleReportVersionError extends Error {
|
||||
constructor(public readonly foundVersion: number) {
|
||||
super(`incompatible_version:${foundVersion}`)
|
||||
this.name = 'IncompatibleReportVersionError'
|
||||
}
|
||||
}
|
||||
|
||||
export async function attachReportJson(pdfDoc: PDFDocument, report: Report): Promise<void> {
|
||||
const bytes = new TextEncoder().encode(JSON.stringify(report, null, 2))
|
||||
await pdfDoc.attach(bytes, FILENAME, {
|
||||
mimeType: 'application/json',
|
||||
description: 'Faunosteo state v2',
|
||||
creationDate: new Date(),
|
||||
modificationDate: new Date(),
|
||||
afRelationship: AFRelationship.Data,
|
||||
})
|
||||
}
|
||||
|
||||
export async function extractReportJson(pdfDoc: PDFDocument): Promise<Report> {
|
||||
const maybeApi = pdfDoc as unknown as { getAttachments?: () => Array<{ name: string; data: Uint8Array }> }
|
||||
if (typeof maybeApi.getAttachments === 'function') {
|
||||
const list = maybeApi.getAttachments()
|
||||
if (list && list.length) {
|
||||
const hit = list.find((a) => a.name.startsWith('osteo-report') && a.name.endsWith('.json')) ?? list[0]
|
||||
return parseAttachment(hit.data)
|
||||
}
|
||||
}
|
||||
const fallback = await traverseForJsonAttachment(pdfDoc)
|
||||
if (!fallback) throw new Error('No osteo-report attachment found')
|
||||
return parseAttachment(fallback)
|
||||
}
|
||||
|
||||
function parseAttachment(bytes: Uint8Array): Report {
|
||||
const text = new TextDecoder().decode(bytes)
|
||||
const data: unknown = JSON.parse(text)
|
||||
if (
|
||||
data !== null &&
|
||||
typeof data === 'object' &&
|
||||
'version' in data &&
|
||||
typeof (data as { version: unknown }).version === 'number' &&
|
||||
(data as { version: number }).version !== 2
|
||||
) {
|
||||
throw new IncompatibleReportVersionError((data as { version: number }).version)
|
||||
}
|
||||
return ReportSchema.parse(data)
|
||||
}
|
||||
|
||||
interface RawObj {
|
||||
contents?: Uint8Array
|
||||
dict?: { entries?: () => Array<[unknown, unknown]> }
|
||||
}
|
||||
|
||||
/**
|
||||
* Hard ceiling on inflated attachment size. A valid report JSON is far
|
||||
* smaller; anything bigger is a decompression bomb or corruption.
|
||||
*/
|
||||
const MAX_INFLATED_BYTES = 16 * 1024 * 1024
|
||||
|
||||
/** Exported for tests. Returns null on failure or when the cap is exceeded. */
|
||||
export async function inflateFlate(bytes: Uint8Array): Promise<Uint8Array | null> {
|
||||
if (typeof DecompressionStream === 'undefined') return null
|
||||
try {
|
||||
const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new DecompressionStream('deflate'))
|
||||
const reader = stream.getReader()
|
||||
const chunks: Uint8Array[] = []
|
||||
let total = 0
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
total += value.byteLength
|
||||
if (total > MAX_INFLATED_BYTES) {
|
||||
await reader.cancel()
|
||||
return null
|
||||
}
|
||||
chunks.push(value)
|
||||
}
|
||||
const out = new Uint8Array(total)
|
||||
let offset = 0
|
||||
for (const c of chunks) {
|
||||
out.set(c, offset)
|
||||
offset += c.byteLength
|
||||
}
|
||||
return out
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function dictHasFlateFilter(entries: Array<[unknown, unknown]>): boolean {
|
||||
for (const [k, v] of entries) {
|
||||
if (String(k).includes('Filter') && String(v).includes('FlateDecode')) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
async function traverseForJsonAttachment(pdfDoc: PDFDocument): Promise<Uint8Array | null> {
|
||||
const ctx = (pdfDoc as unknown as { context: { enumerateIndirectObjects(): Array<[unknown, RawObj]> } }).context
|
||||
for (const [, obj] of ctx.enumerateIndirectObjects()) {
|
||||
if (!obj || typeof obj !== 'object') continue
|
||||
if (!(obj.contents instanceof Uint8Array)) continue
|
||||
const entries = obj.dict?.entries?.() ?? []
|
||||
let isEmbeddedFile = false
|
||||
let isJsonSubtype = false
|
||||
for (const [k, v] of entries) {
|
||||
const ks = String(k)
|
||||
const vs = String(v)
|
||||
if (ks.includes('Type') && vs.includes('EmbeddedFile')) isEmbeddedFile = true
|
||||
// PDF name syntax escapes '/' as '#2F': /application#2Fjson
|
||||
if (ks.includes('Subtype') && (vs.includes('application/json') || vs.includes('application#2Fjson'))) {
|
||||
isJsonSubtype = true
|
||||
}
|
||||
}
|
||||
if (!isEmbeddedFile && !isJsonSubtype) continue
|
||||
if (dictHasFlateFilter(entries)) {
|
||||
const inflated = await inflateFlate(obj.contents)
|
||||
if (inflated) return inflated
|
||||
}
|
||||
return obj.contents
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import { PDFDocument } from 'pdf-lib'
|
||||
import type { Report } from '@/domain/schema/report'
|
||||
import type { SpeciesFindings } from '@/domain/schema/findings'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { getDict } from '@/i18n'
|
||||
import { embedFonts } from './fonts'
|
||||
import { addObservationPage } from './render/observationPage'
|
||||
import { addConclusionPage } from './render/conclusionPage'
|
||||
import { attachReportJson } from './attachment'
|
||||
import { drawFooter } from './render/footer'
|
||||
import { loadFaunosteoLogo, loadFaunosteoComLogo, loadZenqualityLogo } from './render/logo'
|
||||
import { rasterizeSvg } from './render/svgToPng'
|
||||
import { loadSvg } from '@/anatomy/svgLoader'
|
||||
import { parseSvgBones } from '@/anatomy/svgConvention'
|
||||
import { getSpecies } from '@/domain/species/registry'
|
||||
|
||||
export interface PdfExportOptions {
|
||||
locale: Locale
|
||||
}
|
||||
|
||||
/** Bilingual label pair surfaced to the PDF render layer. */
|
||||
export interface ZoneLabelPair {
|
||||
fr: string
|
||||
en: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a `data-anno-id → { fr, en }` map by parsing every SVG the
|
||||
* species manifest knows about. Each SVG is loaded independently so a
|
||||
* failure on the detail asset never prevents the main labels (or vice
|
||||
* versa) from making it into the returned map. The PDF render layer
|
||||
* picks the locale-appropriate label at draw time (falls back to the
|
||||
* opposite language when one side is missing).
|
||||
*
|
||||
* Exported for unit testing — the editor calls it indirectly via
|
||||
* `exportReportToPdf`.
|
||||
*/
|
||||
export async function buildZoneLabels(
|
||||
report: Report,
|
||||
): Promise<Map<string, ZoneLabelPair>> {
|
||||
const labels = new Map<string, ZoneLabelPair>()
|
||||
const species = getSpecies(report.animal.speciesId)
|
||||
if (!species) return labels
|
||||
|
||||
const sources: string[] = [
|
||||
species.mainSvg,
|
||||
...Object.values(species.details),
|
||||
]
|
||||
await Promise.all(
|
||||
sources.map(async (src) => {
|
||||
try {
|
||||
const root = await loadSvg(src)
|
||||
parseSvgBones(root).forEach((b, id) => {
|
||||
const existing = labels.get(id)
|
||||
if (existing) {
|
||||
if (!existing.fr && b.fr) existing.fr = b.fr
|
||||
if (!existing.en && b.en) existing.en = b.en
|
||||
} else if (b.fr || b.en) {
|
||||
labels.set(id, { fr: b.fr, en: b.en })
|
||||
}
|
||||
})
|
||||
} catch (err) {
|
||||
console.warn(`buildZoneLabels: skipped ${src}`, err)
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
return labels
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the parsed findings catalog for a species so the PDF renderer
|
||||
* can resolve a Finding's `zoneId` (JSON catalog key) back to its
|
||||
* human-readable zone name.
|
||||
*/
|
||||
async function loadSpeciesFindings(
|
||||
speciesId: string,
|
||||
): Promise<SpeciesFindings | null> {
|
||||
const species = getSpecies(speciesId)
|
||||
if (!species) return null
|
||||
try {
|
||||
const m = await species.findings()
|
||||
return m.default
|
||||
} catch (err) {
|
||||
console.warn(`loadSpeciesFindings: failed for ${speciesId}`, err)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function exportReportToPdf(
|
||||
report: Report,
|
||||
opts: PdfExportOptions,
|
||||
): Promise<Uint8Array> {
|
||||
const { locale } = opts
|
||||
const dict = getDict(locale)
|
||||
const pdfDoc = await PDFDocument.create()
|
||||
pdfDoc.setTitle(`${dict['pdf.title.suffix.bilan']}${report.animal.name}`)
|
||||
pdfDoc.setAuthor(report.practitioner.name)
|
||||
pdfDoc.setSubject(dict['pdf.subject'])
|
||||
pdfDoc.setCreationDate(new Date())
|
||||
pdfDoc.setModificationDate(new Date())
|
||||
|
||||
const fonts = await embedFonts(pdfDoc)
|
||||
const zoneLabels = await buildZoneLabels(report)
|
||||
const findingsTree = await loadSpeciesFindings(report.animal.speciesId)
|
||||
|
||||
let headerLogoPdf = null
|
||||
let footerLogoPdf = null
|
||||
let zqLogoPdfImage = null
|
||||
let pawsLogoPdf = null
|
||||
try {
|
||||
const bytes = await loadFaunosteoLogo()
|
||||
headerLogoPdf = await pdfDoc.embedPng(bytes)
|
||||
} catch (err) {
|
||||
console.warn('Faunosteo logo embed failed:', err)
|
||||
}
|
||||
try {
|
||||
const bytes = await loadFaunosteoComLogo()
|
||||
footerLogoPdf = await pdfDoc.embedPng(bytes)
|
||||
} catch (err) {
|
||||
console.warn('Faunosteo -com logo embed failed:', err)
|
||||
}
|
||||
try {
|
||||
const zqPngBytes = await loadZenqualityLogo()
|
||||
zqLogoPdfImage = await pdfDoc.embedPng(zqPngBytes)
|
||||
} catch (err) {
|
||||
console.warn('ZenQuality logo embed failed:', err)
|
||||
}
|
||||
try {
|
||||
const resp = await fetch('/Paws_in_harmony.svg')
|
||||
if (!resp.ok) throw new Error(`Paws logo fetch failed: HTTP ${resp.status}`)
|
||||
const svgText = await resp.text()
|
||||
const pawsPngBytes = await rasterizeSvg(svgText)
|
||||
pawsLogoPdf = await pdfDoc.embedPng(pawsPngBytes)
|
||||
} catch (err) {
|
||||
console.warn('Paws in Harmony logo embed failed:', err)
|
||||
}
|
||||
|
||||
const headerAssets = { logoPng: headerLogoPdf }
|
||||
const totalObs = report.observations.length
|
||||
|
||||
for (let i = 0; i < totalObs; i += 1) {
|
||||
await addObservationPage({
|
||||
pdfDoc,
|
||||
report,
|
||||
observation: report.observations[i],
|
||||
obsIndex: i,
|
||||
fonts,
|
||||
zoneLabels,
|
||||
findingsTree,
|
||||
locale,
|
||||
headerAssets,
|
||||
})
|
||||
}
|
||||
await addConclusionPage(pdfDoc, report, fonts, locale, headerAssets)
|
||||
|
||||
const pages = pdfDoc.getPages()
|
||||
const footerAssets = {
|
||||
logoPng: footerLogoPdf,
|
||||
zqLogoPng: zqLogoPdfImage,
|
||||
pawsLogoPng: pawsLogoPdf,
|
||||
}
|
||||
pages.forEach((page, idx) => {
|
||||
drawFooter(page, fonts, idx + 1, pages.length, locale, footerAssets)
|
||||
})
|
||||
|
||||
await attachReportJson(pdfDoc, report)
|
||||
return pdfDoc.save()
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { PDFDocument, StandardFonts, type PDFFont } from 'pdf-lib'
|
||||
|
||||
export interface EmbeddedFonts {
|
||||
bodyRegular: PDFFont
|
||||
bodyBold: PDFFont
|
||||
headingRegular: PDFFont
|
||||
}
|
||||
|
||||
export async function embedFonts(pdfDoc: PDFDocument): Promise<EmbeddedFonts> {
|
||||
const [bodyRegular, bodyBold, headingRegular] = await Promise.all([
|
||||
pdfDoc.embedFont(StandardFonts.Helvetica),
|
||||
pdfDoc.embedFont(StandardFonts.HelveticaBold),
|
||||
pdfDoc.embedFont(StandardFonts.TimesRoman),
|
||||
])
|
||||
return { bodyRegular, bodyBold, headingRegular }
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { PDFDocument } from 'pdf-lib'
|
||||
import { extractReportJson, IncompatibleReportVersionError } from './attachment'
|
||||
import type { Report } from '@/domain/schema/report'
|
||||
|
||||
export type ImportErrorKind =
|
||||
| 'invalid_pdf'
|
||||
| 'incompatible_version'
|
||||
| 'no_attachment'
|
||||
|
||||
/**
|
||||
* Localization-agnostic import error. Carries a kind discriminant + an
|
||||
* optional foundVersion so the caller (UI layer) can resolve the
|
||||
* user-facing message via the active i18n dict.
|
||||
*/
|
||||
export class ImportError extends Error {
|
||||
constructor(
|
||||
public readonly kind: ImportErrorKind,
|
||||
public readonly foundVersion?: number,
|
||||
) {
|
||||
super(kind)
|
||||
this.name = 'ImportError'
|
||||
}
|
||||
}
|
||||
|
||||
export async function importReportFromPdf(pdfBytes: Uint8Array): Promise<Report> {
|
||||
let pdfDoc: PDFDocument
|
||||
try {
|
||||
pdfDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true })
|
||||
} catch {
|
||||
throw new ImportError('invalid_pdf')
|
||||
}
|
||||
try {
|
||||
return await extractReportJson(pdfDoc)
|
||||
} catch (err) {
|
||||
if (err instanceof IncompatibleReportVersionError) {
|
||||
throw new ImportError('incompatible_version', err.foundVersion)
|
||||
}
|
||||
throw new ImportError('no_attachment')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { PageSizes, type PDFDocument } from 'pdf-lib'
|
||||
import type { EmbeddedFonts } from '@/pdf/fonts'
|
||||
import type { Report } from '@/domain/schema/report'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { getDict } from '@/i18n'
|
||||
import { drawHeader, type HeaderAssets } from './header'
|
||||
import { wrapLines } from './text'
|
||||
import { formatDate } from '@/lib/dates'
|
||||
import {
|
||||
MARGIN_X,
|
||||
EYEBROW_Y_OFFSET,
|
||||
TITLE_Y_OFFSET,
|
||||
TITLE_RULE_OFFSET,
|
||||
TITLE_RULE_WIDTH,
|
||||
SECTION_LABEL_GAP,
|
||||
COLOR_INK,
|
||||
COLOR_MUTED,
|
||||
COLOR_ACCENT,
|
||||
} from './constants'
|
||||
|
||||
const SECTION_TOP_GAP = 28
|
||||
const SECTION_BLOCK_GAP = 18
|
||||
const TEXT_LINE_HEIGHT = 14
|
||||
|
||||
export async function addConclusionPage(
|
||||
pdfDoc: PDFDocument,
|
||||
report: Report,
|
||||
fonts: EmbeddedFonts,
|
||||
locale: Locale,
|
||||
headerAssets: HeaderAssets,
|
||||
): Promise<void> {
|
||||
const dict = getDict(locale)
|
||||
const page = pdfDoc.addPage(PageSizes.A4)
|
||||
const { width, height } = page.getSize()
|
||||
const max = width - MARGIN_X * 2
|
||||
|
||||
drawHeader(page, report, fonts, locale, headerAssets)
|
||||
|
||||
const eyebrowY = height - EYEBROW_Y_OFFSET
|
||||
const titleY = height - TITLE_Y_OFFSET
|
||||
page.drawText(dict['pdf.eyebrow.synthesis'], {
|
||||
x: MARGIN_X,
|
||||
y: eyebrowY,
|
||||
size: 9,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
page.drawText(dict['pdf.title.conclusion'], {
|
||||
x: MARGIN_X,
|
||||
y: titleY,
|
||||
size: 22,
|
||||
font: fonts.headingRegular,
|
||||
color: COLOR_INK,
|
||||
})
|
||||
page.drawLine({
|
||||
start: { x: MARGIN_X, y: titleY - TITLE_RULE_OFFSET },
|
||||
end: { x: MARGIN_X + TITLE_RULE_WIDTH, y: titleY - TITLE_RULE_OFFSET },
|
||||
thickness: 2,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
|
||||
let cursorY = titleY - SECTION_TOP_GAP
|
||||
|
||||
const sections: Array<{ label: string; body: string; color?: typeof COLOR_INK }> = [
|
||||
{ label: dict['pdf.section.conclusion'], body: report.conclusion || dict['pdf.empty'] },
|
||||
{ label: dict['pdf.section.recommendations'], body: report.recommendations || dict['pdf.empty'] },
|
||||
]
|
||||
if (report.nextAppointment) {
|
||||
const txt =
|
||||
report.nextAppointment.kind === 'date'
|
||||
? formatDate(report.nextAppointment.date, locale)
|
||||
: report.nextAppointment.text
|
||||
sections.push({
|
||||
label: dict['pdf.section.next_appointment'],
|
||||
body: txt || dict['pdf.empty'],
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
}
|
||||
|
||||
for (const { label, body, color } of sections) {
|
||||
page.drawText(label, {
|
||||
x: MARGIN_X,
|
||||
y: cursorY,
|
||||
size: 9,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
cursorY -= SECTION_LABEL_GAP + 10
|
||||
wrapLines(body, fonts.bodyRegular, 11, max).forEach((line) => {
|
||||
page.drawText(line, {
|
||||
x: MARGIN_X,
|
||||
y: cursorY,
|
||||
size: 11,
|
||||
font: fonts.bodyRegular,
|
||||
color: color ?? COLOR_INK,
|
||||
})
|
||||
cursorY -= TEXT_LINE_HEIGHT
|
||||
})
|
||||
cursorY -= SECTION_BLOCK_GAP
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { rgb } from 'pdf-lib'
|
||||
|
||||
/**
|
||||
* Layout and color constants shared across PDF page renderers (header,
|
||||
* footer, observation page, conclusion page). Only values that are
|
||||
* byte-identical across all callers live here — a same-named constant
|
||||
* with a different value per file stays local to that file.
|
||||
*/
|
||||
|
||||
export const MARGIN_X = 36
|
||||
export const EYEBROW_Y_OFFSET = 95
|
||||
export const TITLE_Y_OFFSET = 122
|
||||
export const TITLE_RULE_OFFSET = 12
|
||||
export const TITLE_RULE_WIDTH = 48
|
||||
export const SECTION_LABEL_GAP = 4
|
||||
|
||||
export const COLOR_INK = rgb(0.12, 0.11, 0.09)
|
||||
export const COLOR_MUTED = rgb(0.42, 0.39, 0.35)
|
||||
export const COLOR_ACCENT = rgb(0.72, 0.35, 0.25)
|
||||
@@ -0,0 +1,173 @@
|
||||
import { rgb, type PDFPage, type PDFImage } from 'pdf-lib'
|
||||
import type { EmbeddedFonts } from '@/pdf/fonts'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { getDict } from '@/i18n'
|
||||
import { addLinkAnnotation } from './linkAnnotation'
|
||||
import { MARGIN_X, COLOR_MUTED } from './constants'
|
||||
|
||||
const FOOTER_BASE_Y = 20
|
||||
const FONT_SIZE = 8
|
||||
|
||||
export interface FooterAssets {
|
||||
logoPng: PDFImage | null
|
||||
zqLogoPng: PDFImage | null
|
||||
pawsLogoPng: PDFImage | null
|
||||
}
|
||||
|
||||
export function drawFooter(
|
||||
page: PDFPage,
|
||||
fonts: EmbeddedFonts,
|
||||
pageNumber: number,
|
||||
totalPages: number,
|
||||
locale: Locale,
|
||||
assets: FooterAssets,
|
||||
): void {
|
||||
const dict = getDict(locale)
|
||||
const { width } = page.getSize()
|
||||
const accent = rgb(0.28, 0.56, 0.42)
|
||||
|
||||
const logoW = 80
|
||||
const logoH = 30
|
||||
const rowY = FOOTER_BASE_Y + 14
|
||||
const separatorY = rowY + logoH + 6
|
||||
|
||||
page.drawLine({
|
||||
start: { x: MARGIN_X, y: separatorY },
|
||||
end: { x: width - MARGIN_X, y: separatorY },
|
||||
thickness: 0.5,
|
||||
color: rgb(0.85, 0.83, 0.8),
|
||||
})
|
||||
|
||||
if (assets.logoPng) {
|
||||
page.drawImage(assets.logoPng, {
|
||||
x: MARGIN_X,
|
||||
y: rowY,
|
||||
width: logoW,
|
||||
height: logoH,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: MARGIN_X,
|
||||
y: rowY,
|
||||
width: logoW,
|
||||
height: logoH,
|
||||
url: 'https://faunosteo.com',
|
||||
})
|
||||
}
|
||||
|
||||
const poweredLabel = `${dict['footer.powered_by']} `
|
||||
const poweredLabelW = fonts.bodyRegular.widthOfTextAtSize(poweredLabel, FONT_SIZE)
|
||||
const zqLogoW = 70
|
||||
const zqLogoH = 16
|
||||
const zqFallback = 'zenquality.fr'
|
||||
const zqFallbackW = fonts.bodyRegular.widthOfTextAtSize(zqFallback, FONT_SIZE)
|
||||
const poweredBlockW = assets.zqLogoPng
|
||||
? poweredLabelW + zqLogoW
|
||||
: poweredLabelW + zqFallbackW
|
||||
const poweredX = (width - poweredBlockW) / 2
|
||||
const textBaseY = rowY + 6
|
||||
|
||||
page.drawText(poweredLabel, {
|
||||
x: poweredX,
|
||||
y: textBaseY,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
const zqX = poweredX + poweredLabelW
|
||||
if (assets.zqLogoPng) {
|
||||
page.drawImage(assets.zqLogoPng, {
|
||||
x: zqX,
|
||||
y: rowY + 2,
|
||||
width: zqLogoW,
|
||||
height: zqLogoH,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: zqX,
|
||||
y: rowY + 2,
|
||||
width: zqLogoW,
|
||||
height: zqLogoH,
|
||||
url: 'https://zenquality.fr',
|
||||
})
|
||||
} else {
|
||||
page.drawText(zqFallback, {
|
||||
x: zqX,
|
||||
y: textBaseY,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: accent,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: zqX,
|
||||
y: textBaseY - 2,
|
||||
width: zqFallbackW,
|
||||
height: FONT_SIZE + 4,
|
||||
url: 'https://zenquality.fr',
|
||||
})
|
||||
}
|
||||
|
||||
const partnerLabel = `${dict['footer.in_partnership']} `
|
||||
const partnerLabelW = fonts.bodyRegular.widthOfTextAtSize(partnerLabel, FONT_SIZE)
|
||||
const partnerUrl = 'https://www.instagram.com/paws.iin.harmony'
|
||||
|
||||
if (assets.pawsLogoPng) {
|
||||
const pawsLogoH = 16
|
||||
const pawsLogoW = pawsLogoH * (assets.pawsLogoPng.width / assets.pawsLogoPng.height)
|
||||
const partnerX = width - MARGIN_X - partnerLabelW - pawsLogoW
|
||||
page.drawText(partnerLabel, {
|
||||
x: partnerX,
|
||||
y: textBaseY,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
const pawsX = partnerX + partnerLabelW
|
||||
page.drawImage(assets.pawsLogoPng, {
|
||||
x: pawsX,
|
||||
y: rowY + 2,
|
||||
width: pawsLogoW,
|
||||
height: pawsLogoH,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: pawsX,
|
||||
y: rowY + 2,
|
||||
width: pawsLogoW,
|
||||
height: pawsLogoH,
|
||||
url: partnerUrl,
|
||||
})
|
||||
} else {
|
||||
const handle = '@paws.iin.harmony'
|
||||
const handleW = fonts.bodyRegular.widthOfTextAtSize(handle, FONT_SIZE)
|
||||
const partnerX = width - MARGIN_X - partnerLabelW - handleW
|
||||
page.drawText(partnerLabel, {
|
||||
x: partnerX,
|
||||
y: textBaseY,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
page.drawText(handle, {
|
||||
x: partnerX + partnerLabelW,
|
||||
y: textBaseY,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: accent,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: partnerX + partnerLabelW,
|
||||
y: textBaseY - 2,
|
||||
width: handleW,
|
||||
height: FONT_SIZE + 4,
|
||||
url: partnerUrl,
|
||||
})
|
||||
}
|
||||
|
||||
const pageText = `${pageNumber} / ${totalPages}`
|
||||
const pageW = fonts.bodyRegular.widthOfTextAtSize(pageText, FONT_SIZE)
|
||||
page.drawText(pageText, {
|
||||
x: (width - pageW) / 2,
|
||||
y: FOOTER_BASE_Y + 2,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import type { PDFPage, PDFImage } from 'pdf-lib'
|
||||
import type { EmbeddedFonts } from '@/pdf/fonts'
|
||||
import type { Report } from '@/domain/schema/report'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { getDict } from '@/i18n'
|
||||
import { formatDate } from '@/lib/dates'
|
||||
import { addLinkAnnotation } from './linkAnnotation'
|
||||
import { MARGIN_X, COLOR_INK, COLOR_MUTED } from './constants'
|
||||
|
||||
const TOP_Y = 800
|
||||
const LOGO_WIDTH = 100
|
||||
const LOGO_HEIGHT = 38
|
||||
|
||||
export interface HeaderAssets {
|
||||
logoPng: PDFImage | null
|
||||
}
|
||||
|
||||
export function drawHeader(
|
||||
page: PDFPage,
|
||||
report: Report,
|
||||
fonts: EmbeddedFonts,
|
||||
locale: Locale,
|
||||
assets: HeaderAssets,
|
||||
): void {
|
||||
const dict = getDict(locale)
|
||||
const { width } = page.getSize()
|
||||
|
||||
const y = TOP_Y
|
||||
|
||||
const left = [
|
||||
report.practitioner.name,
|
||||
report.practitioner.cabinet,
|
||||
report.practitioner.contact,
|
||||
report.practitioner.siret
|
||||
? `${dict['pdf.siret_prefix']}${report.practitioner.siret}`
|
||||
: undefined,
|
||||
].filter(Boolean) as string[]
|
||||
|
||||
left.forEach((line, i) => {
|
||||
page.drawText(line, {
|
||||
x: MARGIN_X,
|
||||
y: y - i * 12,
|
||||
size: i === 0 ? 11 : 9,
|
||||
font: i === 0 ? fonts.bodyBold : fonts.bodyRegular,
|
||||
color: i === 0 ? COLOR_INK : COLOR_MUTED,
|
||||
})
|
||||
})
|
||||
|
||||
if (assets.logoPng) {
|
||||
const logoX = (width - LOGO_WIDTH) / 2
|
||||
const logoY = y - LOGO_HEIGHT + 10
|
||||
page.drawImage(assets.logoPng, {
|
||||
x: logoX,
|
||||
y: logoY,
|
||||
width: LOGO_WIDTH,
|
||||
height: LOGO_HEIGHT,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: logoX,
|
||||
y: logoY,
|
||||
width: LOGO_WIDTH,
|
||||
height: LOGO_HEIGHT,
|
||||
url: 'https://faunosteo.com',
|
||||
})
|
||||
}
|
||||
|
||||
const animalLine = [
|
||||
report.animal.name,
|
||||
report.animal.breed ? `(${report.animal.breed})` : '',
|
||||
report.animal.age ? `· ${report.animal.age}` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
|
||||
const right = [
|
||||
animalLine,
|
||||
`${dict['pdf.owner_prefix']}${report.owner.name}`,
|
||||
formatDate(report.date, locale),
|
||||
]
|
||||
right.forEach((line, i) => {
|
||||
const size = i === 0 ? 11 : 9
|
||||
const font = i === 0 ? fonts.bodyBold : fonts.bodyRegular
|
||||
const w = font.widthOfTextAtSize(line, size)
|
||||
page.drawText(line, {
|
||||
x: width - MARGIN_X - w,
|
||||
y: y - i * 12,
|
||||
size,
|
||||
font,
|
||||
color: i === 0 ? COLOR_INK : COLOR_MUTED,
|
||||
})
|
||||
})
|
||||
|
||||
const separatorY = y - Math.max(left.length * 12, LOGO_HEIGHT) - 8
|
||||
page.drawLine({
|
||||
start: { x: MARGIN_X, y: separatorY },
|
||||
end: { x: width - MARGIN_X, y: separatorY },
|
||||
thickness: 0.5,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { PDFName, PDFArray, PDFString, type PDFPage } from 'pdf-lib'
|
||||
|
||||
export interface LinkRect {
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
url: string
|
||||
}
|
||||
|
||||
export function addLinkAnnotation(page: PDFPage, rect: LinkRect): void {
|
||||
const context = page.doc.context
|
||||
|
||||
const actionDict = context.obj({
|
||||
Type: 'Action',
|
||||
S: 'URI',
|
||||
URI: PDFString.of(rect.url),
|
||||
})
|
||||
|
||||
const annotDict = context.obj({
|
||||
Type: 'Annot',
|
||||
Subtype: 'Link',
|
||||
Rect: [rect.x, rect.y, rect.x + rect.width, rect.y + rect.height],
|
||||
Border: [0, 0, 0],
|
||||
A: actionDict,
|
||||
})
|
||||
|
||||
const annots = page.node.lookup(PDFName.of('Annots'), PDFArray)
|
||||
if (annots) {
|
||||
annots.push(context.register(annotDict))
|
||||
} else {
|
||||
const arr = context.obj([context.register(annotDict)])
|
||||
page.node.set(PDFName.of('Annots'), arr)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
const FAUNOSTEO_LOGO = '/assets/faunosteo_logo_horizontal-512.png'
|
||||
const FAUNOSTEO_COM_LOGO = '/assets/faunosteo-horizontal-com-512.png'
|
||||
const ZENQUALITY_LOGO = '/brand/zenquality-logo-fr.png'
|
||||
|
||||
async function fetchPngBytes(path: string): Promise<Uint8Array> {
|
||||
const resp = await fetch(path)
|
||||
if (!resp.ok) throw new Error(`Logo fetch failed: HTTP ${resp.status}`)
|
||||
return new Uint8Array(await resp.arrayBuffer())
|
||||
}
|
||||
|
||||
export async function loadFaunosteoLogo(): Promise<Uint8Array> {
|
||||
return fetchPngBytes(FAUNOSTEO_LOGO)
|
||||
}
|
||||
|
||||
export async function loadFaunosteoComLogo(): Promise<Uint8Array> {
|
||||
return fetchPngBytes(FAUNOSTEO_COM_LOGO)
|
||||
}
|
||||
|
||||
export async function loadZenqualityLogo(): Promise<Uint8Array> {
|
||||
return fetchPngBytes(ZENQUALITY_LOGO)
|
||||
}
|
||||
@@ -0,0 +1,651 @@
|
||||
import { rgb, PageSizes, type PDFDocument, type PDFPage, type PDFImage } from 'pdf-lib'
|
||||
import type { EmbeddedFonts } from '@/pdf/fonts'
|
||||
import type { Report } from '@/domain/schema/report'
|
||||
import type { Finding, Observation } from '@/domain/schema/observation'
|
||||
import type { SpeciesFindings } from '@/domain/schema/findings'
|
||||
import type { SpeciesManifest } from '@/domain/species/types'
|
||||
import type { Locale, Dict } from '@/i18n/types'
|
||||
import { getDict } from '@/i18n'
|
||||
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
|
||||
import type { ZoneLabelPair } from '@/pdf/export'
|
||||
import { drawHeader, type HeaderAssets } from './header'
|
||||
import { rasterizeSvg } from './svgToPng'
|
||||
import { wrapLines } from './text'
|
||||
import { loadSvg } from '@/anatomy/svgLoader'
|
||||
import { parseSvgBones } from '@/anatomy/svgConvention'
|
||||
import { getSpecies } from '@/domain/species/registry'
|
||||
import {
|
||||
MARGIN_X,
|
||||
EYEBROW_Y_OFFSET,
|
||||
TITLE_Y_OFFSET,
|
||||
TITLE_RULE_OFFSET,
|
||||
TITLE_RULE_WIDTH,
|
||||
SECTION_LABEL_GAP,
|
||||
COLOR_INK,
|
||||
COLOR_MUTED,
|
||||
COLOR_ACCENT,
|
||||
} from './constants'
|
||||
|
||||
const MARGIN_BOTTOM = 48
|
||||
const IMAGE_TOP_GAP = 32
|
||||
const IMAGE_LABEL_GAP = 14
|
||||
const IMAGE_BOTTOM_GAP = 14
|
||||
const IMAGE_COL_GAP = 16
|
||||
const IMAGE_ROW_GAP = 12
|
||||
const IMAGE_MIN_CELL_H = 60
|
||||
const TEXT_TOP_GAP = 10
|
||||
const TEXT_LINE_HEIGHT = 13
|
||||
const SECTION_BLOCK_GAP = 10
|
||||
|
||||
const COLOR_WHITE = rgb(1, 1, 1)
|
||||
|
||||
const SEVERITY_BG: Record<string, ReturnType<typeof rgb>> = {
|
||||
'légère': rgb(0.55, 0.65, 0.45),
|
||||
'modérée': rgb(0.85, 0.55, 0.18),
|
||||
'sévère': rgb(0.78, 0.20, 0.20),
|
||||
}
|
||||
|
||||
const SECTION_TEXT_SIZE = 10
|
||||
const SEPARATOR_GLYPH = '•'
|
||||
const SEPARATOR_SIZE = 14
|
||||
const SEPARATOR_SIDE_GAP = 5
|
||||
|
||||
/** Width of the visible separator block including the empty space on each side. */
|
||||
function separatorWidth(fonts: EmbeddedFonts): number {
|
||||
return (
|
||||
fonts.bodyBold.widthOfTextAtSize(SEPARATOR_GLYPH, SEPARATOR_SIZE) +
|
||||
SEPARATOR_SIDE_GAP * 2
|
||||
)
|
||||
}
|
||||
|
||||
/** Counts the line breaks a list of items would consume when laid out on a maxWidth line. */
|
||||
function countSegmentedLines(
|
||||
items: string[],
|
||||
fonts: EmbeddedFonts,
|
||||
maxWidth: number,
|
||||
): number {
|
||||
if (items.length === 0) return 1
|
||||
const sepW = separatorWidth(fonts)
|
||||
let lines = 1
|
||||
let x = 0
|
||||
for (let i = 0; i < items.length; i += 1) {
|
||||
const itemW = fonts.bodyRegular.widthOfTextAtSize(
|
||||
items[i],
|
||||
SECTION_TEXT_SIZE,
|
||||
)
|
||||
if (x + itemW > maxWidth && x > 0) {
|
||||
lines += 1
|
||||
x = 0
|
||||
}
|
||||
x += itemW
|
||||
if (i < items.length - 1) {
|
||||
if (x + sepW > maxWidth) {
|
||||
lines += 1
|
||||
x = 0
|
||||
} else {
|
||||
x += sepW
|
||||
}
|
||||
}
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a list of items separated by a visibly larger accent-coloured
|
||||
* bullet. Returns the cursor y *below* the last line drawn so the
|
||||
* caller can keep advancing the page cursor like a plain wrapLines run.
|
||||
*/
|
||||
function drawSegmentedText(
|
||||
page: PDFPage,
|
||||
items: string[],
|
||||
startX: number,
|
||||
startY: number,
|
||||
maxWidth: number,
|
||||
fonts: EmbeddedFonts,
|
||||
): number {
|
||||
if (items.length === 0) return startY - TEXT_LINE_HEIGHT
|
||||
const sepW = separatorWidth(fonts)
|
||||
// The bullet's larger size pushes its baseline above the surrounding
|
||||
// text. Shift it down a touch so it visually centers on the x-height
|
||||
// of the items it separates.
|
||||
const sepBaselineOffset = (SEPARATOR_SIZE - SECTION_TEXT_SIZE) * 0.3
|
||||
|
||||
let x = startX
|
||||
let y = startY
|
||||
for (let i = 0; i < items.length; i += 1) {
|
||||
const item = items[i]
|
||||
const itemW = fonts.bodyRegular.widthOfTextAtSize(item, SECTION_TEXT_SIZE)
|
||||
if (x + itemW > startX + maxWidth && x > startX) {
|
||||
x = startX
|
||||
y -= TEXT_LINE_HEIGHT
|
||||
}
|
||||
page.drawText(item, {
|
||||
x,
|
||||
y,
|
||||
size: SECTION_TEXT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_INK,
|
||||
})
|
||||
x += itemW
|
||||
if (i < items.length - 1) {
|
||||
if (x + sepW > startX + maxWidth) {
|
||||
x = startX
|
||||
y -= TEXT_LINE_HEIGHT
|
||||
} else {
|
||||
page.drawText(SEPARATOR_GLYPH, {
|
||||
x: x + SEPARATOR_SIDE_GAP,
|
||||
y: y - sepBaselineOffset,
|
||||
size: SEPARATOR_SIZE,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
x += sepW
|
||||
}
|
||||
}
|
||||
}
|
||||
return y - TEXT_LINE_HEIGHT
|
||||
}
|
||||
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg'
|
||||
const HALO_FILTER_ID = 'osteo-halo'
|
||||
|
||||
/**
|
||||
* Adds a Gaussian-blur "halo" filter to the SVG defs the first time it
|
||||
* is called on a root. The filter widens the visible footprint of the
|
||||
* highlighted zones on the whole-animal view, where individual point
|
||||
* markers are otherwise tiny relative to the full body silhouette.
|
||||
*/
|
||||
function ensureHaloFilter(root: SVGSVGElement): void {
|
||||
const doc = root.ownerDocument
|
||||
if (!doc) return
|
||||
if (doc.getElementById(HALO_FILTER_ID)) return
|
||||
|
||||
let defs = root.querySelector('defs')
|
||||
if (!defs) {
|
||||
defs = doc.createElementNS(SVG_NS, 'defs')
|
||||
root.insertBefore(defs, root.firstChild)
|
||||
}
|
||||
|
||||
const filter = doc.createElementNS(SVG_NS, 'filter')
|
||||
filter.setAttribute('id', HALO_FILTER_ID)
|
||||
filter.setAttribute('x', '-100%')
|
||||
filter.setAttribute('y', '-100%')
|
||||
filter.setAttribute('width', '300%')
|
||||
filter.setAttribute('height', '300%')
|
||||
filter.setAttribute('filterUnits', 'userSpaceOnUse')
|
||||
|
||||
// Two-stage blur: a wide outer halo for "spotted from across the
|
||||
// room" visibility, plus a tighter inner halo that keeps the
|
||||
// selection anchored to the original point so it doesn't dissolve.
|
||||
const wide = doc.createElementNS(SVG_NS, 'feGaussianBlur')
|
||||
wide.setAttribute('in', 'SourceGraphic')
|
||||
wide.setAttribute('stdDeviation', '18')
|
||||
wide.setAttribute('result', 'haloWide')
|
||||
filter.appendChild(wide)
|
||||
|
||||
const tight = doc.createElementNS(SVG_NS, 'feGaussianBlur')
|
||||
tight.setAttribute('in', 'SourceGraphic')
|
||||
tight.setAttribute('stdDeviation', '8')
|
||||
tight.setAttribute('result', 'haloTight')
|
||||
filter.appendChild(tight)
|
||||
|
||||
const merge = doc.createElementNS(SVG_NS, 'feMerge')
|
||||
// Stack the wide halo three times so its contribution survives the
|
||||
// SVG → PNG → pdf-lib pipeline (each pass attenuates alpha) and
|
||||
// still reads as a strong glow at print scale.
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
const n = doc.createElementNS(SVG_NS, 'feMergeNode')
|
||||
n.setAttribute('in', 'haloWide')
|
||||
merge.appendChild(n)
|
||||
}
|
||||
for (let i = 0; i < 2; i += 1) {
|
||||
const n = doc.createElementNS(SVG_NS, 'feMergeNode')
|
||||
n.setAttribute('in', 'haloTight')
|
||||
merge.appendChild(n)
|
||||
}
|
||||
const source = doc.createElementNS(SVG_NS, 'feMergeNode')
|
||||
source.setAttribute('in', 'SourceGraphic')
|
||||
merge.appendChild(source)
|
||||
filter.appendChild(merge)
|
||||
|
||||
defs.appendChild(filter)
|
||||
}
|
||||
|
||||
async function colorizedSvgString(
|
||||
speciesSvgPath: string,
|
||||
observation: Observation,
|
||||
sourceDetailId: string | undefined,
|
||||
): Promise<string> {
|
||||
const root = await loadSvg(speciesSvgPath)
|
||||
const bones = parseSvgBones(root)
|
||||
const selectedIds = new Set(
|
||||
observation.zones
|
||||
.filter((z) => z.detailSourceId === sourceDetailId)
|
||||
.map((z) => z.boneId),
|
||||
)
|
||||
|
||||
// Whole-animal view: zone hitboxes are tiny markers on a big
|
||||
// silhouette, so we apply a blurred halo to make selections pop.
|
||||
// Detail views are already zoomed in and don't need it.
|
||||
const applyHalo = sourceDetailId === undefined
|
||||
if (applyHalo) ensureHaloFilter(root)
|
||||
|
||||
bones.forEach((bone, id) => {
|
||||
const selected = selectedIds.has(id)
|
||||
bone.els.forEach((el) => {
|
||||
if (selected) {
|
||||
el.setAttribute('fill', '#b85a3f')
|
||||
el.setAttribute('fill-opacity', '0.85')
|
||||
if (applyHalo) {
|
||||
el.setAttribute('filter', `url(#${HALO_FILTER_ID})`)
|
||||
}
|
||||
} else {
|
||||
el.setAttribute('display', 'none')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
root.querySelectorAll('[data-anno-id]').forEach((el) => {
|
||||
Array.from(el.attributes)
|
||||
.filter((a) => a.name.startsWith('data-anno-'))
|
||||
.forEach((a) => el.removeAttribute(a.name))
|
||||
})
|
||||
|
||||
return new XMLSerializer().serializeToString(root)
|
||||
}
|
||||
|
||||
/** Parameters needed to render one observation page. */
|
||||
export interface ObservationPageContext {
|
||||
pdfDoc: PDFDocument
|
||||
report: Report
|
||||
observation: Observation
|
||||
obsIndex: number
|
||||
fonts: EmbeddedFonts
|
||||
zoneLabels: Map<string, ZoneLabelPair>
|
||||
findingsTree: SpeciesFindings | null
|
||||
locale: Locale
|
||||
headerAssets: HeaderAssets
|
||||
}
|
||||
|
||||
/** Shared draw handles threaded through the observation-page sub-renderers. */
|
||||
interface PageDrawContext {
|
||||
page: PDFPage
|
||||
fonts: EmbeddedFonts
|
||||
width: number
|
||||
}
|
||||
|
||||
/** One rasterized anatomy view (main body or a detail popup) ready to embed. */
|
||||
interface RenderedImage {
|
||||
label: string
|
||||
img: PDFImage
|
||||
aspect: number
|
||||
}
|
||||
|
||||
/** One label/value block drawn under the images (zones, findings, comment...). */
|
||||
interface ObservationSection {
|
||||
label: string
|
||||
value: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws the eyebrow, index/severity title, and accent rule for an
|
||||
* observation page. Returns titleY so callers can lay out the content
|
||||
* below it.
|
||||
*/
|
||||
function drawObservationTitleBlock(
|
||||
ctx: PageDrawContext,
|
||||
dict: Dict,
|
||||
obsIndex: number,
|
||||
severity: Observation['severity'],
|
||||
): number {
|
||||
const { page, fonts } = ctx
|
||||
const { height } = page.getSize()
|
||||
const eyebrowY = height - EYEBROW_Y_OFFSET
|
||||
const titleY = height - TITLE_Y_OFFSET
|
||||
const obsLabel = String(obsIndex + 1).padStart(2, '0')
|
||||
page.drawText(dict['pdf.eyebrow.observation'], {
|
||||
x: MARGIN_X,
|
||||
y: eyebrowY,
|
||||
size: 9,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
page.drawText(obsLabel, {
|
||||
x: MARGIN_X,
|
||||
y: titleY,
|
||||
size: 22,
|
||||
font: fonts.headingRegular,
|
||||
color: COLOR_INK,
|
||||
})
|
||||
if (severity) {
|
||||
const numW = fonts.headingRegular.widthOfTextAtSize(obsLabel, 22)
|
||||
const sev = severity
|
||||
const sevLabel = dict[`severity.${sev}`] ?? sev
|
||||
const sevText = sevLabel.toUpperCase()
|
||||
const sevSize = 9
|
||||
const sevTextW = fonts.bodyBold.widthOfTextAtSize(sevText, sevSize)
|
||||
const padX = 8
|
||||
const padY = 4
|
||||
const pillW = sevTextW + padX * 2
|
||||
const pillH = sevSize + padY * 2
|
||||
const pillX = MARGIN_X + numW + 14
|
||||
const pillY = titleY + 4
|
||||
page.drawRectangle({
|
||||
x: pillX,
|
||||
y: pillY,
|
||||
width: pillW,
|
||||
height: pillH,
|
||||
color: SEVERITY_BG[sev] ?? COLOR_MUTED,
|
||||
})
|
||||
page.drawText(sevText, {
|
||||
x: pillX + padX,
|
||||
y: pillY + padY,
|
||||
size: sevSize,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_WHITE,
|
||||
})
|
||||
}
|
||||
page.drawLine({
|
||||
start: { x: MARGIN_X, y: titleY - TITLE_RULE_OFFSET },
|
||||
end: { x: MARGIN_X + TITLE_RULE_WIDTH, y: titleY - TITLE_RULE_OFFSET },
|
||||
thickness: 2,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
return titleY
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the main-body view plus every detail-popup view referenced by
|
||||
* the observation, rasterizing each to a PNG ready for pdf-lib.
|
||||
*/
|
||||
async function buildObservationImages(
|
||||
pdfDoc: PDFDocument,
|
||||
species: SpeciesManifest,
|
||||
observation: Observation,
|
||||
dict: Dict,
|
||||
): Promise<RenderedImage[]> {
|
||||
const hasMainZones = observation.zones.some((z) => !z.detailSourceId)
|
||||
const detailIds = Array.from(
|
||||
new Set(observation.zones.map((z) => z.detailSourceId).filter(Boolean) as string[]),
|
||||
)
|
||||
|
||||
const items: Array<{ label: string; src: string; sourceId: string | undefined }> = []
|
||||
if (hasMainZones) {
|
||||
items.push({ label: dict['pdf.view.general'], src: species.mainSvg, sourceId: undefined })
|
||||
}
|
||||
for (const detailId of detailIds) {
|
||||
const detailPath = species.details[detailId]
|
||||
if (!detailPath) continue
|
||||
items.push({
|
||||
label: `${dict['pdf.view.detail_prefix']}${detailId.toUpperCase()}`,
|
||||
src: detailPath,
|
||||
sourceId: detailId,
|
||||
})
|
||||
}
|
||||
|
||||
return Promise.all(
|
||||
items.map(async (it) => {
|
||||
const svgStr = await colorizedSvgString(it.src, observation, it.sourceId)
|
||||
const png = await rasterizeSvg(svgStr)
|
||||
const img = await pdfDoc.embedPng(png)
|
||||
const aspect = img.width > 0 ? img.height / img.width : 0.6
|
||||
return { label: it.label, img, aspect }
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/** Renders the "Zones" section value: bilingual labels + vertebra/side suffixes. */
|
||||
function describeObservationZones(
|
||||
zones: Observation['zones'],
|
||||
zoneLabels: Map<string, ZoneLabelPair>,
|
||||
locale: Locale,
|
||||
dict: Dict,
|
||||
): string {
|
||||
return zones
|
||||
.map((z) => {
|
||||
const pair = zoneLabels.get(z.boneId)
|
||||
const label = pickLocaleLabel(pair?.fr, pair?.en, locale, z.boneId)
|
||||
const v = z.vertebrae?.length
|
||||
? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})`
|
||||
: ''
|
||||
const side = z.side
|
||||
? ` (${dict[z.side === 'left' ? 'lateral.left' : 'lateral.right']})`
|
||||
: ''
|
||||
return `${label}${v}${side}`
|
||||
})
|
||||
.join(' · ')
|
||||
}
|
||||
|
||||
/** Groups findings by zone+side, one label/value section entry per group. */
|
||||
function buildFindingsSections(
|
||||
findings: Finding[],
|
||||
findingsTree: SpeciesFindings | null,
|
||||
locale: Locale,
|
||||
dict: Dict,
|
||||
): ObservationSection[] {
|
||||
const byZoneSide = new Map<string, Finding[]>()
|
||||
for (const f of findings) {
|
||||
const key = f.side ? `${f.zoneId}:${f.side}` : f.zoneId
|
||||
const list = byZoneSide.get(key)
|
||||
if (list) {
|
||||
list.push(f)
|
||||
} else {
|
||||
byZoneSide.set(key, [f])
|
||||
}
|
||||
}
|
||||
|
||||
const sections: ObservationSection[] = []
|
||||
for (const [key, group] of byZoneSide) {
|
||||
const zoneId = key.split(':')[0]
|
||||
const side = group[0]?.side
|
||||
const zoneTree = findingsTree?.zones[zoneId]
|
||||
let zoneName = zoneTree
|
||||
? locale === 'en'
|
||||
? zoneTree.name_en
|
||||
: zoneTree.name_fr
|
||||
: zoneId
|
||||
if (side) {
|
||||
const sideLabel = dict[side === 'left' ? 'lateral.left' : 'lateral.right']
|
||||
zoneName = `${zoneName} (${sideLabel})`
|
||||
}
|
||||
const value = group
|
||||
.map((f) => {
|
||||
const lbl = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot
|
||||
return f.requiresVetReferral ? `(!) ${lbl}` : lbl
|
||||
})
|
||||
.join(' · ')
|
||||
sections.push({
|
||||
label: `${dict['pdf.section.findings_prefix']}${zoneName.toUpperCase()}`,
|
||||
value,
|
||||
})
|
||||
}
|
||||
return sections
|
||||
}
|
||||
|
||||
/** Assembles the ordered label/value sections drawn below the images. */
|
||||
function buildObservationSections(
|
||||
observation: Observation,
|
||||
zoneLabels: Map<string, ZoneLabelPair>,
|
||||
findingsTree: SpeciesFindings | null,
|
||||
locale: Locale,
|
||||
dict: Dict,
|
||||
): ObservationSection[] {
|
||||
const zonesText = describeObservationZones(observation.zones, zoneLabels, locale, dict)
|
||||
const sections: ObservationSection[] = [
|
||||
{ label: dict['pdf.section.zones'], value: zonesText || dict['pdf.empty'] },
|
||||
]
|
||||
sections.push(...buildFindingsSections(observation.findings, findingsTree, locale, dict))
|
||||
|
||||
if (observation.freeTextFindings.length) {
|
||||
sections.push({
|
||||
label: dict['pdf.section.free_findings'],
|
||||
value: observation.freeTextFindings.join(' · '),
|
||||
})
|
||||
}
|
||||
if (observation.severity) {
|
||||
const sevLabel = dict[`severity.${observation.severity}`] ?? observation.severity
|
||||
sections.push({ label: dict['pdf.section.severity'], value: sevLabel })
|
||||
}
|
||||
if (observation.comment.trim()) {
|
||||
sections.push({ label: dict['pdf.section.comment'], value: observation.comment.trim() })
|
||||
}
|
||||
return sections
|
||||
}
|
||||
|
||||
/** Estimates the vertical space the given sections will occupy once drawn. */
|
||||
function estimateSectionsHeight(
|
||||
sections: ObservationSection[],
|
||||
fonts: EmbeddedFonts,
|
||||
maxTextW: number,
|
||||
): number {
|
||||
let h = TEXT_TOP_GAP
|
||||
for (const { value } of sections) {
|
||||
const lineCount = value.includes(' · ')
|
||||
? countSegmentedLines(value.split(' · '), fonts, maxTextW)
|
||||
: wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW).length
|
||||
h += SECTION_LABEL_GAP + 9 + lineCount * TEXT_LINE_HEIGHT + SECTION_BLOCK_GAP
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
/**
|
||||
* Lays out and draws the (up to 2-column) image grid for an observation
|
||||
* page. Returns the cursor y directly below the images — unchanged from
|
||||
* startY when there is nothing to draw.
|
||||
*/
|
||||
function drawObservationImageGrid(
|
||||
ctx: PageDrawContext,
|
||||
rendered: RenderedImage[],
|
||||
startY: number,
|
||||
reservedBottom: number,
|
||||
): number {
|
||||
const { page, fonts, width } = ctx
|
||||
let cursorY = startY
|
||||
if (rendered.length === 0) return cursorY
|
||||
|
||||
const isSingle = rendered.length === 1
|
||||
const cols = isSingle ? 1 : 2
|
||||
const rows = Math.ceil(rendered.length / cols)
|
||||
const fullCellW = (width - MARGIN_X * 2 - IMAGE_COL_GAP * (cols - 1)) / cols
|
||||
// Single-image observations get rendered at half the available width
|
||||
// and centered, so they don't dominate the page when the surrounding
|
||||
// text is short.
|
||||
const cellW = isSingle ? fullCellW / 2 : fullCellW
|
||||
const singleOffsetX = isSingle ? (fullCellW - cellW) / 2 : 0
|
||||
const availH = Math.max(IMAGE_MIN_CELL_H, cursorY - reservedBottom)
|
||||
const rowBudget = Math.max(
|
||||
IMAGE_MIN_CELL_H,
|
||||
(availH - rows * IMAGE_LABEL_GAP - (rows - 1) * IMAGE_ROW_GAP) / rows,
|
||||
)
|
||||
|
||||
for (let r = 0; r < rows; r += 1) {
|
||||
const rowItems = rendered.slice(r * cols, r * cols + cols)
|
||||
const cellHs = rowItems.map((it) => Math.min(cellW * it.aspect, rowBudget))
|
||||
const rowH = Math.max(0, ...cellHs)
|
||||
rowItems.forEach((it, c) => {
|
||||
const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP)
|
||||
page.drawText(it.label, {
|
||||
x,
|
||||
y: cursorY,
|
||||
size: 8,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
})
|
||||
cursorY -= IMAGE_LABEL_GAP
|
||||
rowItems.forEach((it, c) => {
|
||||
const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP)
|
||||
page.drawImage(it.img, {
|
||||
x,
|
||||
y: cursorY - cellHs[c],
|
||||
width: cellW,
|
||||
height: cellHs[c],
|
||||
})
|
||||
})
|
||||
cursorY -= rowH
|
||||
if (r < rows - 1) cursorY -= IMAGE_ROW_GAP
|
||||
}
|
||||
cursorY -= IMAGE_BOTTOM_GAP
|
||||
return cursorY
|
||||
}
|
||||
|
||||
/** Draws each label/value section, returns the cursor y below the last one. */
|
||||
function drawObservationSections(
|
||||
ctx: PageDrawContext,
|
||||
sections: ObservationSection[],
|
||||
startY: number,
|
||||
maxTextW: number,
|
||||
): number {
|
||||
const { page, fonts } = ctx
|
||||
let cursorY = startY
|
||||
for (const { label, value } of sections) {
|
||||
page.drawText(label, {
|
||||
x: MARGIN_X,
|
||||
y: cursorY,
|
||||
size: 8,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
cursorY -= SECTION_LABEL_GAP + 9
|
||||
if (value.includes(' · ')) {
|
||||
cursorY = drawSegmentedText(
|
||||
page,
|
||||
value.split(' · '),
|
||||
MARGIN_X,
|
||||
cursorY,
|
||||
maxTextW,
|
||||
fonts,
|
||||
)
|
||||
} else {
|
||||
const lines = wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW)
|
||||
for (const line of lines) {
|
||||
page.drawText(line, {
|
||||
x: MARGIN_X,
|
||||
y: cursorY,
|
||||
size: SECTION_TEXT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_INK,
|
||||
})
|
||||
cursorY -= TEXT_LINE_HEIGHT
|
||||
}
|
||||
}
|
||||
cursorY -= SECTION_BLOCK_GAP
|
||||
}
|
||||
return cursorY
|
||||
}
|
||||
|
||||
export async function addObservationPage(
|
||||
ctx: ObservationPageContext,
|
||||
): Promise<void> {
|
||||
const {
|
||||
pdfDoc,
|
||||
report,
|
||||
observation,
|
||||
obsIndex,
|
||||
fonts,
|
||||
zoneLabels,
|
||||
findingsTree,
|
||||
locale,
|
||||
headerAssets,
|
||||
} = ctx
|
||||
const dict = getDict(locale)
|
||||
const page = pdfDoc.addPage(PageSizes.A4)
|
||||
const { width } = page.getSize()
|
||||
drawHeader(page, report, fonts, locale, headerAssets)
|
||||
|
||||
const drawCtx: PageDrawContext = { page, fonts, width }
|
||||
const titleY = drawObservationTitleBlock(drawCtx, dict, obsIndex, observation.severity)
|
||||
|
||||
const species = getSpecies(report.animal.speciesId)
|
||||
if (!species) return
|
||||
|
||||
const rendered = await buildObservationImages(pdfDoc, species, observation, dict)
|
||||
|
||||
const maxTextW = width - MARGIN_X * 2
|
||||
const sections = buildObservationSections(observation, zoneLabels, findingsTree, locale, dict)
|
||||
const reservedBottom = MARGIN_BOTTOM + estimateSectionsHeight(sections, fonts, maxTextW) + IMAGE_BOTTOM_GAP
|
||||
|
||||
let cursorY = drawObservationImageGrid(drawCtx, rendered, titleY - IMAGE_TOP_GAP, reservedBottom)
|
||||
cursorY -= TEXT_TOP_GAP
|
||||
drawObservationSections(drawCtx, sections, cursorY, maxTextW)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
const TARGET_WIDTH = 1200
|
||||
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
|
||||
|
||||
function startsWithPngSignature(bytes: Uint8Array): boolean {
|
||||
if (bytes.length < PNG_SIGNATURE.length) return false
|
||||
for (let i = 0; i < PNG_SIGNATURE.length; i += 1) {
|
||||
if (bytes[i] !== PNG_SIGNATURE[i]) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function ensureSvgAttributes(
|
||||
svgString: string,
|
||||
widthPx: number,
|
||||
heightPx: number,
|
||||
): string {
|
||||
const doc = new DOMParser().parseFromString(svgString, 'image/svg+xml')
|
||||
const root = doc.documentElement
|
||||
if (root.namespaceURI !== 'http://www.w3.org/2000/svg') {
|
||||
// Some serializers strip xmlns; force the SVG namespace so
|
||||
// browsers will rasterize the blob URL as an image.
|
||||
root.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
|
||||
}
|
||||
if (!root.getAttribute('width')) root.setAttribute('width', String(widthPx))
|
||||
if (!root.getAttribute('height')) root.setAttribute('height', String(heightPx))
|
||||
return new XMLSerializer().serializeToString(root)
|
||||
}
|
||||
|
||||
function readViewBox(svgString: string): {
|
||||
widthPx: number
|
||||
heightPx: number
|
||||
} {
|
||||
const doc = new DOMParser().parseFromString(svgString, 'image/svg+xml')
|
||||
const vb = (doc.documentElement.getAttribute('viewBox') ?? '0 0 1000 600')
|
||||
.split(/\s+/)
|
||||
.map(Number)
|
||||
const ratio = vb[3] > 0 && vb[2] > 0 ? vb[3] / vb[2] : 0.6
|
||||
const widthPx = Math.max(1, Math.round(TARGET_WIDTH))
|
||||
const heightPx = Math.max(1, Math.round(ratio * widthPx))
|
||||
return { widthPx, heightPx }
|
||||
}
|
||||
|
||||
async function rasterizeWithImageElement(
|
||||
svgString: string,
|
||||
widthPx: number,
|
||||
heightPx: number,
|
||||
): Promise<HTMLCanvasElement> {
|
||||
const normalized = ensureSvgAttributes(svgString, widthPx, heightPx)
|
||||
const svgBlob = new Blob([normalized], {
|
||||
type: 'image/svg+xml;charset=utf-8',
|
||||
})
|
||||
const url = URL.createObjectURL(svgBlob)
|
||||
const img = new Image()
|
||||
img.decoding = 'sync'
|
||||
img.crossOrigin = 'anonymous'
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
img.onload = () => resolve()
|
||||
img.onerror = () =>
|
||||
reject(new Error('Browser failed to render the SVG into an Image'))
|
||||
img.src = url
|
||||
})
|
||||
} finally {
|
||||
// The Blob URL is single-use — release it once the Image has loaded
|
||||
// (or failed).
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = widthPx
|
||||
canvas.height = heightPx
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) throw new Error('Canvas 2D context unavailable')
|
||||
ctx.fillStyle = '#ffffff'
|
||||
ctx.fillRect(0, 0, widthPx, heightPx)
|
||||
ctx.drawImage(img, 0, 0, widthPx, heightPx)
|
||||
return canvas
|
||||
}
|
||||
|
||||
async function canvasToPngBytes(canvas: HTMLCanvasElement): Promise<Uint8Array> {
|
||||
const blob = await new Promise<Blob | null>((resolve) => {
|
||||
canvas.toBlob((b) => resolve(b), 'image/png')
|
||||
})
|
||||
if (blob) {
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer())
|
||||
if (startsWithPngSignature(bytes)) return bytes
|
||||
}
|
||||
const dataUrl = canvas.toDataURL('image/png')
|
||||
if (!dataUrl.startsWith('data:image/png')) {
|
||||
throw new Error(
|
||||
`canvas.toDataURL produced non-PNG payload: ${dataUrl.slice(0, 32)}`,
|
||||
)
|
||||
}
|
||||
const comma = dataUrl.indexOf(',')
|
||||
if (comma < 0) {
|
||||
throw new Error('canvas.toDataURL returned a data URL without a payload')
|
||||
}
|
||||
const binary = atob(dataUrl.slice(comma + 1))
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let i = 0; i < binary.length; i += 1) {
|
||||
bytes[i] = binary.charCodeAt(i)
|
||||
}
|
||||
if (!startsWithPngSignature(bytes)) {
|
||||
throw new Error('canvas.toDataURL produced bytes without a PNG signature')
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
||||
/**
|
||||
* Rasterizes an SVG string to a PNG byte array using the browser's native
|
||||
* SVG-to-Image pipeline. The browser parses + draws the SVG via an
|
||||
* Image/Blob URL pair, which renders identically to what the user sees in
|
||||
* the inline anatomy canvas.
|
||||
*
|
||||
* @param svgString Serialized SVG (must declare `xmlns`)
|
||||
*/
|
||||
export async function rasterizeSvg(svgString: string): Promise<Uint8Array> {
|
||||
const { widthPx, heightPx } = readViewBox(svgString)
|
||||
const canvas = await rasterizeWithImageElement(svgString, widthPx, heightPx)
|
||||
return canvasToPngBytes(canvas)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { PDFFont } from 'pdf-lib'
|
||||
|
||||
/**
|
||||
* Greedy word-wrap: splits `text` into lines whose rendered width at
|
||||
* `size` points stays within `max` for the given font.
|
||||
*/
|
||||
export function wrapLines(
|
||||
text: string,
|
||||
font: PDFFont,
|
||||
size: number,
|
||||
max: number,
|
||||
): string[] {
|
||||
const words = text.split(/\s+/)
|
||||
const lines: string[] = []
|
||||
let line = ''
|
||||
for (const w of words) {
|
||||
const test = line ? `${line} ${w}` : w
|
||||
if (font.widthOfTextAtSize(test, size) > max && line) {
|
||||
lines.push(line)
|
||||
line = w
|
||||
} else {
|
||||
line = test
|
||||
}
|
||||
}
|
||||
if (line) lines.push(line)
|
||||
return lines
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { create } from 'zustand'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
|
||||
export const LOCALE_STORAGE_KEY = 'osteo:locale'
|
||||
|
||||
function detectNavigatorLocale(): Locale | undefined {
|
||||
if (typeof navigator === 'undefined') return undefined
|
||||
const langs: string[] = Array.isArray(navigator.languages)
|
||||
? [...navigator.languages]
|
||||
: []
|
||||
if (typeof navigator.language === 'string') langs.push(navigator.language)
|
||||
for (const tag of langs) {
|
||||
const primary = tag.toLowerCase().split(/[-_]/)[0]
|
||||
if (primary === 'fr') return 'fr'
|
||||
if (primary === 'en') return 'en'
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Locale resolution priority:
|
||||
* 1. Explicit localStorage value (user previously toggled)
|
||||
* 2. Navigator language list (first fr/en hit on the user's prefs)
|
||||
* 3. 'fr' fallback (single-praticien project default)
|
||||
*/
|
||||
function readInitial(): Locale {
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
const raw = localStorage.getItem(LOCALE_STORAGE_KEY)
|
||||
if (raw === 'fr' || raw === 'en') return raw
|
||||
}
|
||||
return detectNavigatorLocale() ?? 'fr'
|
||||
}
|
||||
|
||||
export interface LocaleStore {
|
||||
locale: Locale
|
||||
setLocale: (next: Locale) => void
|
||||
}
|
||||
|
||||
export const useLocaleStore = create<LocaleStore>((set) => ({
|
||||
locale: readInitial(),
|
||||
setLocale: (next) => {
|
||||
set({ locale: next })
|
||||
if (typeof localStorage === 'undefined') return
|
||||
try {
|
||||
localStorage.setItem(LOCALE_STORAGE_KEY, next)
|
||||
} catch {
|
||||
// Quota / private mode — in-memory only.
|
||||
}
|
||||
},
|
||||
}))
|
||||
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
PractitionerSchema,
|
||||
type Practitioner,
|
||||
} from '@/domain/schema/practitioner'
|
||||
|
||||
const STORAGE_KEY = 'osteo:lastPractitioner'
|
||||
|
||||
export function readCachedPractitioner(): Practitioner | undefined {
|
||||
if (typeof localStorage === 'undefined') return undefined
|
||||
const raw = localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) return undefined
|
||||
try {
|
||||
const data = JSON.parse(raw)
|
||||
const parsed = PractitionerSchema.safeParse(data)
|
||||
return parsed.success ? parsed.data : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export function writeCachedPractitioner(practitioner: Practitioner): void {
|
||||
if (typeof localStorage === 'undefined') return
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(practitioner))
|
||||
}
|
||||
|
||||
export function clearPractitionerCache(): void {
|
||||
if (typeof localStorage === 'undefined') return
|
||||
localStorage.removeItem(STORAGE_KEY)
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import { create } from 'zustand'
|
||||
import { ReportSchema, type Report } from '@/domain/schema/report'
|
||||
import type { Observation } from '@/domain/schema/observation'
|
||||
import type { Practitioner } from '@/domain/schema/practitioner'
|
||||
import type { Animal, Owner } from '@/domain/schema/animal'
|
||||
import { generateId } from '@/lib/id'
|
||||
import { nowIso } from '@/lib/dates'
|
||||
|
||||
export interface ReportStore {
|
||||
report: Report | null
|
||||
activeObservationIndex: number
|
||||
initReport: (draft: Omit<Report, 'id' | 'createdAt' | 'version'>) => void
|
||||
hydrateReport: (report: Report) => void
|
||||
addObservation: () => void
|
||||
removeObservation: (index: number) => void
|
||||
moveObservationUp: (index: number) => void
|
||||
moveObservationDown: (index: number) => void
|
||||
updateObservation: (index: number, obs: Observation) => void
|
||||
setActiveObservation: (index: number) => void
|
||||
setPractitioner: (next: Practitioner) => void
|
||||
setAnimal: (next: Animal) => void
|
||||
setOwner: (next: Owner) => void
|
||||
setConclusion: (text: string) => void
|
||||
setRecommendations: (text: string) => void
|
||||
setNextAppointment: (next: Report['nextAppointment']) => void
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
function emptyObservation(): Observation {
|
||||
return {
|
||||
id: generateId(),
|
||||
zones: [],
|
||||
findings: [],
|
||||
freeTextFindings: [],
|
||||
comment: '',
|
||||
}
|
||||
}
|
||||
|
||||
const DRAFT_KEY = 'osteo:draft'
|
||||
|
||||
/** Reads the auto-saved draft back from sessionStorage (null if absent/invalid). */
|
||||
export function readPersistedDraft(): Report | null {
|
||||
if (typeof sessionStorage === 'undefined') return null
|
||||
const raw = sessionStorage.getItem(DRAFT_KEY)
|
||||
if (!raw) return null
|
||||
try {
|
||||
const parsed = ReportSchema.safeParse(JSON.parse(raw))
|
||||
return parsed.success ? parsed.data : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const useReportStore = create<ReportStore>((set) => ({
|
||||
// Restore the per-tab draft so a page refresh never loses the session.
|
||||
report: readPersistedDraft(),
|
||||
activeObservationIndex: 0,
|
||||
|
||||
initReport: (draft) =>
|
||||
set({
|
||||
report: {
|
||||
...draft,
|
||||
version: 2,
|
||||
id: generateId(),
|
||||
createdAt: nowIso(),
|
||||
observations:
|
||||
draft.observations.length === 0
|
||||
? [emptyObservation()]
|
||||
: draft.observations,
|
||||
},
|
||||
activeObservationIndex: 0,
|
||||
}),
|
||||
|
||||
hydrateReport: (report) => set({ report, activeObservationIndex: 0 }),
|
||||
|
||||
addObservation: () =>
|
||||
set((s) => {
|
||||
if (!s.report) return s
|
||||
const obs = emptyObservation()
|
||||
const observations = [...s.report.observations, obs]
|
||||
return {
|
||||
report: { ...s.report, observations },
|
||||
activeObservationIndex: observations.length - 1,
|
||||
}
|
||||
}),
|
||||
|
||||
removeObservation: (index) =>
|
||||
set((s) => {
|
||||
if (!s.report) return s
|
||||
const observations = s.report.observations.filter((_, i) => i !== index)
|
||||
const active = Math.min(
|
||||
s.activeObservationIndex,
|
||||
Math.max(0, observations.length - 1),
|
||||
)
|
||||
return {
|
||||
report: { ...s.report, observations },
|
||||
activeObservationIndex: active,
|
||||
}
|
||||
}),
|
||||
|
||||
moveObservationUp: (index) =>
|
||||
set((s) => {
|
||||
if (!s.report || index <= 0) return s
|
||||
const observations = [...s.report.observations]
|
||||
;[observations[index - 1], observations[index]] = [
|
||||
observations[index],
|
||||
observations[index - 1],
|
||||
]
|
||||
return { report: { ...s.report, observations } }
|
||||
}),
|
||||
|
||||
moveObservationDown: (index) =>
|
||||
set((s) => {
|
||||
if (!s.report || index >= s.report.observations.length - 1) return s
|
||||
const observations = [...s.report.observations]
|
||||
;[observations[index], observations[index + 1]] = [
|
||||
observations[index + 1],
|
||||
observations[index],
|
||||
]
|
||||
return { report: { ...s.report, observations } }
|
||||
}),
|
||||
|
||||
updateObservation: (index, obs) =>
|
||||
set((s) => {
|
||||
if (!s.report) return s
|
||||
const observations = s.report.observations.map((o, i) =>
|
||||
i === index ? obs : o,
|
||||
)
|
||||
return { report: { ...s.report, observations } }
|
||||
}),
|
||||
|
||||
setActiveObservation: (index) => set({ activeObservationIndex: index }),
|
||||
|
||||
setPractitioner: (next) =>
|
||||
set((s) => (s.report ? { report: { ...s.report, practitioner: next } } : s)),
|
||||
|
||||
setAnimal: (next) =>
|
||||
set((s) => (s.report ? { report: { ...s.report, animal: next } } : s)),
|
||||
|
||||
setOwner: (next) =>
|
||||
set((s) => (s.report ? { report: { ...s.report, owner: next } } : s)),
|
||||
|
||||
setConclusion: (text) =>
|
||||
set((s) => (s.report ? { report: { ...s.report, conclusion: text } } : s)),
|
||||
|
||||
setRecommendations: (text) =>
|
||||
set((s) =>
|
||||
s.report ? { report: { ...s.report, recommendations: text } } : s,
|
||||
),
|
||||
|
||||
setNextAppointment: (next) =>
|
||||
set((s) =>
|
||||
s.report ? { report: { ...s.report, nextAppointment: next } } : s,
|
||||
),
|
||||
|
||||
reset: () => set({ report: null, activeObservationIndex: 0 }),
|
||||
}))
|
||||
|
||||
useReportStore.subscribe((state) => {
|
||||
if (typeof sessionStorage === 'undefined') return
|
||||
if (state.report) {
|
||||
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(state.report))
|
||||
} else {
|
||||
sessionStorage.removeItem(DRAFT_KEY)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
@import 'tailwindcss';
|
||||
@import './tokens.css';
|
||||
|
||||
html, body, #root { height: 100%; }
|
||||
body {
|
||||
background: var(--color-bg);
|
||||
color: var(--color-ink);
|
||||
font-family: var(--font-sans);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
.svg-canvas [data-state='current'] { fill: var(--color-accent) !important; fill-opacity: 0.85 !important; }
|
||||
.svg-canvas [data-anno-id] { cursor: pointer; }
|
||||
.svg-canvas [data-anno-id]:hover { filter: brightness(1.05); }
|
||||
|
||||
.zone-tooltip {
|
||||
position: absolute;
|
||||
pointer-events: none;
|
||||
padding: 4px 10px;
|
||||
border-radius: 6px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
background: var(--color-ink);
|
||||
color: var(--color-bg);
|
||||
box-shadow: 0 2px 8px rgba(0,0,0,.18);
|
||||
transition: opacity 120ms ease;
|
||||
z-index: 50;
|
||||
}
|
||||
@@ -0,0 +1,528 @@
|
||||
.svg-editor-root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
font-family: var(--font-sans);
|
||||
color: var(--color-ink);
|
||||
background: var(--color-bg);
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.svg-editor-root {
|
||||
flex-direction: row;
|
||||
}
|
||||
}
|
||||
|
||||
.svg-editor-root * { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
.svg-editor-canvas {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
background: var(--color-surface);
|
||||
overflow: hidden;
|
||||
padding: 10px;
|
||||
min-height: 40vh;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.svg-editor-canvas {
|
||||
min-height: 0;
|
||||
}
|
||||
}
|
||||
.svg-editor-canvas-inner {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
position: relative;
|
||||
}
|
||||
.svg-editor-canvas-inner svg {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
width: auto;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.svg-editor-canvas.mode-point svg,
|
||||
.svg-editor-canvas.mode-polygon svg { cursor: crosshair; }
|
||||
.svg-editor-canvas.mode-select svg { cursor: default; }
|
||||
|
||||
.svg-editor-root [data-anno-id] { transition: filter 0.1s; }
|
||||
.svg-editor-root [data-anno-id]:hover {
|
||||
filter: brightness(1.3) drop-shadow(0 0 4px rgba(184, 90, 63, 0.7));
|
||||
}
|
||||
.svg-editor-root [data-anno-id].selected {
|
||||
filter: drop-shadow(0 0 12px var(--color-accent)) drop-shadow(0 0 6px var(--color-accent)) brightness(1.15);
|
||||
stroke: var(--color-accent) !important;
|
||||
stroke-width: 4 !important;
|
||||
stroke-opacity: 1 !important;
|
||||
}
|
||||
|
||||
.svg-editor-root .polygon-handle {
|
||||
cursor: move;
|
||||
fill: #ffd54f;
|
||||
stroke: var(--color-accent);
|
||||
stroke-width: 2;
|
||||
transition: r 0.1s;
|
||||
}
|
||||
.svg-editor-root .polygon-handle:hover {
|
||||
fill: #ffe082;
|
||||
stroke-width: 3;
|
||||
}
|
||||
.svg-editor-root .polygon-midhandle {
|
||||
cursor: copy;
|
||||
fill: var(--color-surface);
|
||||
stroke: var(--color-accent);
|
||||
stroke-width: 1.5;
|
||||
fill-opacity: 0.7;
|
||||
}
|
||||
.svg-editor-root .polygon-midhandle:hover {
|
||||
fill: #ffd54f;
|
||||
fill-opacity: 1;
|
||||
}
|
||||
|
||||
@keyframes svg-editor-flash-pulse {
|
||||
0%, 100% {
|
||||
stroke-width: 4;
|
||||
stroke: var(--color-accent);
|
||||
filter: drop-shadow(0 0 12px var(--color-accent)) brightness(1.15);
|
||||
}
|
||||
50% {
|
||||
stroke-width: 10;
|
||||
stroke: #ffd54f;
|
||||
filter: drop-shadow(0 0 24px #ffd54f) drop-shadow(0 0 12px var(--color-accent)) brightness(1.4);
|
||||
}
|
||||
}
|
||||
|
||||
.svg-editor-root [data-anno-id].flashing {
|
||||
animation: svg-editor-flash-pulse 0.6s ease-in-out 2;
|
||||
}
|
||||
|
||||
.svg-editor-root .polygon-preview {
|
||||
fill: rgba(184, 90, 63, 0.2);
|
||||
stroke: var(--color-accent);
|
||||
stroke-width: 2;
|
||||
stroke-dasharray: 5,3;
|
||||
}
|
||||
.svg-editor-root .polygon-preview-pt { fill: var(--color-accent); }
|
||||
|
||||
.svg-editor-sidebar {
|
||||
width: 100%;
|
||||
background: var(--color-surface);
|
||||
border-top: 1px solid var(--color-border);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
max-height: 50vh;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.svg-editor-sidebar {
|
||||
width: 380px;
|
||||
max-height: none;
|
||||
border-top: none;
|
||||
border-left: 1px solid var(--color-border);
|
||||
}
|
||||
}
|
||||
.svg-editor-sidebar header {
|
||||
padding: 14px 16px;
|
||||
background: var(--color-accent);
|
||||
color: white;
|
||||
}
|
||||
.svg-editor-sidebar header h1 { font-size: 16px; font-weight: 600; }
|
||||
.svg-editor-sidebar header .sub { font-size: 11px; opacity: 0.8; margin-top: 4px; }
|
||||
|
||||
.svg-editor-sidebar-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 14px 16px;
|
||||
}
|
||||
|
||||
.svg-editor-root .section { margin-bottom: 20px; }
|
||||
.svg-editor-root .section h3 {
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
color: var(--color-ink-muted);
|
||||
margin-bottom: 8px;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.svg-editor-root button,
|
||||
.svg-editor-root .btn {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 9px 12px;
|
||||
margin-bottom: 6px;
|
||||
background: var(--color-surface-strong);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
text-align: left;
|
||||
transition: all 0.1s;
|
||||
font-family: inherit;
|
||||
color: var(--color-ink);
|
||||
}
|
||||
.svg-editor-root button:hover { background: var(--color-border); }
|
||||
.svg-editor-root button.active {
|
||||
background: var(--color-accent);
|
||||
color: white;
|
||||
border-color: var(--color-accent);
|
||||
}
|
||||
.svg-editor-root button.danger {
|
||||
background: #fef2f2;
|
||||
border-color: #fecaca;
|
||||
color: var(--color-danger);
|
||||
}
|
||||
.svg-editor-root button.danger:hover { background: #fee2e2; }
|
||||
.svg-editor-root button.primary {
|
||||
background: var(--color-accent);
|
||||
color: white;
|
||||
border-color: var(--color-accent);
|
||||
}
|
||||
.svg-editor-root button.primary:hover { background: var(--color-accent-strong); }
|
||||
|
||||
.svg-editor-root input,
|
||||
.svg-editor-root select {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
margin-bottom: 6px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 6px;
|
||||
font-size: 13px;
|
||||
background: var(--color-surface);
|
||||
font-family: inherit;
|
||||
color: var(--color-ink);
|
||||
}
|
||||
.svg-editor-root input[type="color"] { padding: 2px; height: 32px; cursor: pointer; }
|
||||
.svg-editor-root input[type="file"] { background: var(--color-surface-strong); cursor: pointer; }
|
||||
.svg-editor-root label {
|
||||
font-size: 11px;
|
||||
color: var(--color-ink-muted);
|
||||
margin-bottom: 2px;
|
||||
display: block;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.svg-editor-root .element-list {
|
||||
max-height: 280px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 6px;
|
||||
background: var(--color-bg);
|
||||
}
|
||||
.svg-editor-root .element-item {
|
||||
padding: 6px 10px;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.svg-editor-root .element-item:last-child { border-bottom: none; }
|
||||
.svg-editor-root .element-item:hover { background: var(--color-surface-strong); }
|
||||
.svg-editor-root .element-item.selected {
|
||||
background: color-mix(in srgb, var(--color-accent) 12%, transparent);
|
||||
color: var(--color-accent-strong);
|
||||
font-weight: 600;
|
||||
}
|
||||
.svg-editor-root .element-item .swatch {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 3px;
|
||||
border: 1px solid rgba(0,0,0,0.15);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.svg-editor-root .element-item .name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.svg-editor-root .element-item .cat {
|
||||
font-size: 10px;
|
||||
color: var(--color-ink-muted);
|
||||
margin-left: auto;
|
||||
padding: 1px 6px;
|
||||
background: var(--color-surface-strong);
|
||||
border-radius: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.svg-editor-root .coords {
|
||||
font-family: monospace;
|
||||
font-size: 11px;
|
||||
color: var(--color-ink-muted);
|
||||
padding: 4px 8px;
|
||||
background: var(--color-bg);
|
||||
border-radius: 4px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.svg-editor-zoom-controls {
|
||||
position: absolute;
|
||||
bottom: 20px;
|
||||
left: 20px;
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 6px;
|
||||
padding: 4px;
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
box-shadow: 0 2px 8px rgba(0,0,0,0.08);
|
||||
}
|
||||
.svg-editor-zoom-controls button {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.svg-editor-zoom-controls button {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.svg-editor-root input[type="checkbox"] { width: auto; display: inline; margin: 0 6px 0 0; }
|
||||
|
||||
.svg-editor-root .cat-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 6px 4px;
|
||||
background: var(--color-bg);
|
||||
border-radius: 6px;
|
||||
margin-bottom: 4px;
|
||||
border: 1px solid var(--color-border);
|
||||
}
|
||||
.svg-editor-root .cat-row input[type="color"] { width: 32px; height: 28px; padding: 0; margin: 0; flex-shrink: 0; }
|
||||
.svg-editor-root .cat-row input[type="checkbox"] { margin: 0 4px 0 4px; flex-shrink: 0; }
|
||||
.svg-editor-root .cat-row .name {
|
||||
flex: 1;
|
||||
font-size: 13px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.svg-editor-root .cat-row .count {
|
||||
font-size: 10px;
|
||||
color: var(--color-ink-muted);
|
||||
padding: 1px 5px;
|
||||
background: var(--color-surface-strong);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.svg-editor-root .cat-row .delete {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.svg-editor-root .cat-row .delete:hover { background: #fef2f2; color: var(--color-danger); }
|
||||
.svg-editor-root .cat-row .special-btn {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
color: var(--color-ink-muted);
|
||||
}
|
||||
.svg-editor-root .cat-row .special-btn:hover { background: #fff8e1; color: #d97706; }
|
||||
.svg-editor-root .cat-row .special-btn.has-value { color: #d97706; }
|
||||
.svg-editor-root .cat-row .special-badge {
|
||||
font-size: 10px;
|
||||
padding: 1px 6px;
|
||||
background: #fff8e1;
|
||||
color: #92400e;
|
||||
border: 1px solid #ffd54f;
|
||||
border-radius: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.svg-editor-root .add-cat { display: flex; gap: 6px; margin-top: 8px; }
|
||||
.svg-editor-root .add-cat input { margin: 0; }
|
||||
.svg-editor-root .add-cat input[type="color"] { width: 36px; flex-shrink: 0; }
|
||||
.svg-editor-root .add-cat input[type="text"] { flex: 1; }
|
||||
.svg-editor-root .add-cat button { width: auto; padding: 6px 12px; margin: 0; flex-shrink: 0; }
|
||||
|
||||
.svg-editor-root .slider-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.svg-editor-root .slider-row input[type="range"] {
|
||||
flex: 1;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 28px;
|
||||
cursor: pointer;
|
||||
accent-color: var(--color-accent);
|
||||
}
|
||||
.svg-editor-root .slider-row input[type="number"] {
|
||||
width: 60px;
|
||||
margin: 0;
|
||||
padding: 6px 4px;
|
||||
text-align: center;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.svg-editor-root .detail-toggle {
|
||||
margin-top: 4px;
|
||||
padding: 8px 10px;
|
||||
background: #fff8e1;
|
||||
border: 1px solid #ffd54f;
|
||||
border-radius: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.svg-editor-root .detail-toggle label { margin: 0; color: #92400e; font-size: 13px; }
|
||||
.svg-editor-root .detail-toggle input[type="text"] { margin-top: 4px; margin-bottom: 0; }
|
||||
|
||||
.svg-editor-root .element-item .detail-badge {
|
||||
background: #ffd54f;
|
||||
color: #6b4500;
|
||||
font-size: 10px;
|
||||
padding: 1px 6px;
|
||||
border-radius: 8px;
|
||||
font-weight: 600;
|
||||
margin-left: 4px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.svg-editor-root [data-anno-opens-detail] { stroke-dasharray: 8,4; }
|
||||
.svg-editor-root .detail-zone { cursor: pointer; }
|
||||
|
||||
.svg-editor-root .welcome {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100%;
|
||||
text-align: center;
|
||||
color: var(--color-ink-muted);
|
||||
padding: 60px 20px;
|
||||
}
|
||||
.svg-editor-root .welcome-icon { font-size: 80px; margin-bottom: 20px; opacity: 0.7; }
|
||||
.svg-editor-root .welcome h2 {
|
||||
color: var(--color-accent);
|
||||
margin-bottom: 16px;
|
||||
font-size: 24px;
|
||||
font-family: var(--font-serif);
|
||||
}
|
||||
.svg-editor-root .welcome p {
|
||||
max-width: 480px;
|
||||
margin-bottom: 30px;
|
||||
line-height: 1.5;
|
||||
font-size: 14px;
|
||||
}
|
||||
.svg-editor-root .welcome p code {
|
||||
background: var(--color-surface-strong);
|
||||
padding: 2px 6px;
|
||||
border-radius: 3px;
|
||||
font-size: 90%;
|
||||
font-family: monospace;
|
||||
}
|
||||
.svg-editor-root .welcome-btn {
|
||||
width: auto !important;
|
||||
padding: 14px 28px !important;
|
||||
font-size: 15px !important;
|
||||
margin: 0 !important;
|
||||
}
|
||||
.svg-editor-root .welcome-hint {
|
||||
margin-top: 16px;
|
||||
color: var(--color-ink-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.svg-editor-root .welcome-tabs {
|
||||
display: flex;
|
||||
gap: 0;
|
||||
margin-bottom: 20px;
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--color-border);
|
||||
}
|
||||
.svg-editor-root .welcome-tab {
|
||||
padding: 8px 20px;
|
||||
font-size: 13px;
|
||||
background: var(--color-surface);
|
||||
color: var(--color-ink-muted);
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
.svg-editor-root .welcome-tab:not(:last-child) {
|
||||
border-right: 1px solid var(--color-border);
|
||||
}
|
||||
.svg-editor-root .welcome-tab.active {
|
||||
background: var(--color-accent);
|
||||
color: #fff;
|
||||
}
|
||||
.svg-editor-root .welcome-tab-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 260px;
|
||||
}
|
||||
.svg-editor-root .welcome-tab-content label {
|
||||
font-size: 12px;
|
||||
color: var(--color-ink-muted);
|
||||
align-self: flex-start;
|
||||
}
|
||||
.svg-editor-root .welcome-tab-content select {
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--color-border);
|
||||
background: var(--color-surface);
|
||||
color: var(--color-ink);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.svg-editor-canvas.dragging-over { background: color-mix(in srgb, var(--color-accent) 8%, var(--color-surface)); }
|
||||
.svg-editor-canvas.dragging-over .welcome { color: var(--color-accent); }
|
||||
.svg-editor-canvas.dragging-over::after {
|
||||
content: attr(data-drop-label);
|
||||
position: absolute;
|
||||
inset: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 32px;
|
||||
color: var(--color-accent);
|
||||
background: color-mix(in srgb, var(--color-accent) 8%, transparent 15%);
|
||||
border: 4px dashed var(--color-accent);
|
||||
border-radius: 8px;
|
||||
pointer-events: none;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.svg-editor-root .hide-articulation [data-anno-category="articulation"],
|
||||
.svg-editor-root .hide-charniere [data-anno-category="charniere"],
|
||||
.svg-editor-root .hide-cadran-crane [data-anno-category="cadran-crane"],
|
||||
.svg-editor-root .hide-os-overlay [data-anno-category="os-overlay"],
|
||||
.svg-editor-root .hide-spine-zone [data-anno-category="spine-zone"],
|
||||
.svg-editor-root .hide-custom [data-anno-category="custom"] { display: none; }
|
||||
@@ -0,0 +1,27 @@
|
||||
:root {
|
||||
--color-bg: #fbf9f5;
|
||||
--color-surface: #ffffff;
|
||||
--color-surface-strong: #f4efe6;
|
||||
--color-ink: #1f1b16;
|
||||
--color-ink-muted: #6b6359;
|
||||
--color-border: #e7e0d2;
|
||||
|
||||
--color-accent: #b85a3f;
|
||||
--color-accent-strong: #9c4831;
|
||||
--color-danger: #c0392b;
|
||||
--color-danger-strong: #962c21;
|
||||
|
||||
--obs-accent-0: #b85a3f;
|
||||
--obs-accent-1: #6b8e6b;
|
||||
--obs-accent-2: #3f7d8c;
|
||||
--obs-accent-3: #b88a3f;
|
||||
--obs-accent-4: #7a3f7d;
|
||||
--obs-accent-5: #8a6b3f;
|
||||
|
||||
--severity-mild: #6b8e6b;
|
||||
--severity-moderate: #b88a3f;
|
||||
--severity-severe: #c0392b;
|
||||
|
||||
--font-sans: 'Inter', system-ui, -apple-system, 'Segoe UI', sans-serif;
|
||||
--font-serif: 'Fraunces', 'Iowan Old Style', Georgia, serif;
|
||||
}
|
||||
Reference in new issue
Block a user