Files
faunosteo/src/components/observation/FindingsTreePicker.tsx
T
Bastien ChanotandClaude Opus 4.7 4dd6432ed6 fix(editor): boost findings-tree slide to be perceptible on mobile
Previous 16px / 180ms transition was barely visible on a 360-420px
wide mobile viewport. Adjustments:
- Slide distance 16px → 32px so the off-position is clearly off-axis
  on small screens.
- Duration 180ms → 220ms — slightly longer keeps the slide visible
  through the iOS/Android touch-event paint cycle.
- Hint with willChange: 'transform, opacity' so mobile Safari
  promotes the ul to its own compositor layer up front, avoiding a
  first-frame flicker on weaker GPUs.

No behavioural change to direction logic; tests still 155/155.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 07:28:28 +02:00

286 lines
9.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useMemo, useState } from 'react'
import { motion } from 'motion/react'
import type {
FindingNode,
ZoneFindings,
} from '@/domain/schema/findings'
import type { Finding } 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
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,
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 isLeafSelected(leafPath: string[]): boolean {
return selected.some(
(f) => f.zoneId === zoneId && samePath(f.path, leafPath),
)
}
function countSelectedUnder(nodePath: string[]): number {
let n = 0
for (const f of selected) {
if (f.zoneId !== zoneId) continue
if (!pathStartsWith(f.path, nodePath)) continue
n += 1
}
return n
}
function toggleLeaf(leafPath: string[], leaf: FindingNode) {
if (isLeafSelected(leafPath)) {
onChange(
selected.filter(
(f) => !(f.zoneId === zoneId && 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
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>
)
}