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' export interface AnatomyCanvasProps { src: string boneStates: Map onZoneClick: (boneId: string) => void className?: string } export default function AnatomyCanvas({ src, boneStates, onZoneClick, className = '', }: AnatomyCanvasProps) { const wrapperRef = useRef(null) const svgRef = useRef(null) const tooltipRef = useRef(null) const [loadedSrc, setLoadedSrc] = useState(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('[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 = locale === 'en' ? en || fr : fr || en 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 (
) }