feat(i18n): navigator-detect default locale + locale-aware bone labels
- localeStore.readInitial now consults navigator.language(s) when
localStorage is empty (first fr/en hit, FR fallback). Persisted user
choice still wins.
- New helper src/anatomy/labels.ts (boneLabel(b, locale, fallback))
with cross-language fallback so missing labels never render blank.
- AnatomyCanvas rewrites native SVG <title> tooltips per locale on
mount and on locale change (upstream SVG ships titles as "FR / EN"
concat; we replace with the active-locale label only). Detail-popup
trigger titles ("🔍 Zoom: …") left intact.
- DetailModal + EditorRoute detail title prefix + vertebra picker
title now route through useT()/boneLabel.
- ObservationCard.describeZone takes locale, picks bone.fr / bone.en.
- PDF: buildZoneLabels returns Map<id, { fr, en }> instead of FR-only;
observationPage picks per locale with cross-language fallback.
- Tests: FindingsTreePicker + VertebraPicker reset locale to 'fr' in
beforeEach (navigator-detect may land on EN in happy-dom).
- pdf.zoneLabels test updated to assert the new pair shape.
154/154 tests pass, lint clean, typecheck clean, build OK.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
1 parent
31bd82de58
commit
9cf8a66dad
13 files changed
+156
-35
No files matched your search
@@ -0,0 +1,19 @@
|
||||
import type { Locale } from '@/i18n/types'
|
||||
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
|
||||
if (locale === 'en') return bone.en || bone.fr || fallback
|
||||
return bone.fr || bone.en || fallback
|
||||
}
|
||||
@@ -25,6 +25,7 @@ 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'
|
||||
|
||||
@@ -198,7 +199,7 @@ export default function EditorRoute() {
|
||||
setDetail({
|
||||
id: bone.opensDetail,
|
||||
src: species.details[bone.opensDetail],
|
||||
title: bone.fr,
|
||||
title: boneLabel(bone, locale, bone.opensDetail),
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -323,7 +324,7 @@ export default function EditorRoute() {
|
||||
onClose={() => setDetail(null)}
|
||||
detailSrc={detail.src}
|
||||
detailId={detail.id}
|
||||
title={`Détail — ${detail.title}`}
|
||||
title={`${t('editor.detail_title_prefix')}${detail.title}`}
|
||||
boneStates={boneStates}
|
||||
onZoneClick={(id, did) => onZoneClick(id, did)}
|
||||
/>
|
||||
@@ -408,7 +409,11 @@ export default function EditorRoute() {
|
||||
}}
|
||||
initial={activeObs.zones[vertebraTarget].vertebrae ?? []}
|
||||
formula={species.vertebralFormula}
|
||||
title={`${t('vertebra.title_prefix')}${bones.get(activeObs.zones[vertebraTarget].boneId)?.fr ?? ''}`}
|
||||
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 ?? '')
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from 'react'
|
||||
import { loadSvg } from '@/anatomy/svgLoader'
|
||||
import { getBoneIdFromEvent } from '@/anatomy/svgConvention'
|
||||
import type { BoneState } from '@/anatomy/types'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
export interface AnatomyCanvasProps {
|
||||
src: string
|
||||
@@ -18,6 +19,7 @@ export default function AnatomyCanvas({
|
||||
}: AnatomyCanvasProps) {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null)
|
||||
const [loadedSrc, setLoadedSrc] = useState<string | null>(null)
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
@@ -56,6 +58,33 @@ export default function AnatomyCanvas({
|
||||
})
|
||||
}, [boneStates, loadedSrc, src])
|
||||
|
||||
// Rewrite native SVG <title> tooltips to match the active locale. The
|
||||
// upstream SVG ships titles as "FR / EN" concatenations; we replace the
|
||||
// text content with just the locale-relevant label so the browser-native
|
||||
// hover tooltip stays in sync with the rest of the UI. The detail-popup
|
||||
// hint ("🔍 Zoom: head") is left intact since it carries an emoji affordance,
|
||||
// not a translatable label.
|
||||
useEffect(() => {
|
||||
const c = containerRef.current
|
||||
if (!c || loadedSrc !== src) return
|
||||
const annotated = c.querySelectorAll<Element>('[data-anno-id]')
|
||||
annotated.forEach((el) => {
|
||||
if (el.hasAttribute('data-anno-opens-detail')) return
|
||||
const fr = el.getAttribute('data-anno-name-fr') ?? ''
|
||||
const en = el.getAttribute('data-anno-name-en') ?? ''
|
||||
const preferred = locale === 'en' ? en || fr : fr || en
|
||||
if (!preferred) return
|
||||
let titleEl = el.querySelector(':scope > title')
|
||||
if (!titleEl) {
|
||||
const doc = el.ownerDocument
|
||||
if (!doc) return
|
||||
titleEl = doc.createElementNS('http://www.w3.org/2000/svg', 'title')
|
||||
el.insertBefore(titleEl, el.firstChild)
|
||||
}
|
||||
titleEl.textContent = preferred
|
||||
})
|
||||
}, [locale, loadedSrc, src])
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="anatomy-canvas"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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
|
||||
@@ -21,6 +22,7 @@ export default function DetailModal({
|
||||
boneStates,
|
||||
onZoneClick,
|
||||
}: DetailModalProps) {
|
||||
const t = useT()
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} title={title} size="xl">
|
||||
<div className="aspect-[4/3] w-full">
|
||||
@@ -31,7 +33,7 @@ export default function DetailModal({
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-4 text-sm text-[var(--color-ink-muted)]">
|
||||
Cliquez sur les zones pour les ajouter à l'observation en cours.
|
||||
{t('detail.click_to_add')}
|
||||
</p>
|
||||
</Dialog>
|
||||
)
|
||||
|
||||
@@ -21,6 +21,8 @@ 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
|
||||
@@ -40,9 +42,12 @@ export interface ObservationCardProps {
|
||||
onRemoveZone: (zoneIndex: number) => void
|
||||
}
|
||||
|
||||
function describeZone(z: ObservationZone, bones: Map<string, Bone>): string {
|
||||
const b = bones.get(z.boneId)
|
||||
const label = b?.fr ?? z.boneId
|
||||
function describeZone(
|
||||
z: ObservationZone,
|
||||
bones: Map<string, Bone>,
|
||||
locale: Locale,
|
||||
): 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}`)
|
||||
@@ -240,7 +245,7 @@ export default function ObservationCard({
|
||||
return (
|
||||
<li key={`${z.boneId}-${i}`}>
|
||||
<Badge tone="accent" className="gap-2">
|
||||
{describeZone(z, bones)}
|
||||
{describeZone(z, bones, locale)}
|
||||
{supportsVertebrae && (
|
||||
<button
|
||||
type="button"
|
||||
@@ -253,7 +258,7 @@ export default function ObservationCard({
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`${t('observation.remove_zone')} ${b?.fr ?? z.boneId}`}
|
||||
aria-label={`${t('observation.remove_zone')} ${boneLabel(b, locale, z.boneId)}`}
|
||||
onClick={() => onRemoveZone(i)}
|
||||
className="ml-1 text-[var(--color-accent-strong)]"
|
||||
>
|
||||
|
||||
@@ -43,6 +43,9 @@ export const en: Dict = {
|
||||
'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',
|
||||
|
||||
@@ -50,6 +50,10 @@ export const fr: Dict = {
|
||||
'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',
|
||||
|
||||
+21
-5
@@ -16,17 +16,27 @@ 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 → French label` map by parsing every SVG the
|
||||
* 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.
|
||||
* 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, string>> {
|
||||
const labels = new Map<string, string>()
|
||||
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
|
||||
|
||||
@@ -39,7 +49,13 @@ export async function buildZoneLabels(report: Report): Promise<Map<string, strin
|
||||
try {
|
||||
const root = await loadSvg(src)
|
||||
parseSvgBones(root).forEach((b, id) => {
|
||||
if (b.fr) labels.set(id, b.fr)
|
||||
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)
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { Finding, Observation } from '@/domain/schema/observation'
|
||||
import type { SpeciesFindings } from '@/domain/schema/findings'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { getDict } from '@/i18n'
|
||||
import type { ZoneLabelPair } from '@/pdf/export'
|
||||
import { drawHeader } from './header'
|
||||
import { rasterizeSvg } from './svgToPng'
|
||||
import { loadSvg } from '@/anatomy/svgLoader'
|
||||
@@ -271,7 +272,7 @@ export async function addObservationPage(
|
||||
observation: Observation,
|
||||
obsIndex: number,
|
||||
fonts: EmbeddedFonts,
|
||||
zoneLabels: Map<string, string>,
|
||||
zoneLabels: Map<string, ZoneLabelPair>,
|
||||
findingsTree: SpeciesFindings | null,
|
||||
locale: Locale,
|
||||
): Promise<void> {
|
||||
@@ -366,7 +367,10 @@ export async function addObservationPage(
|
||||
|
||||
const zonesText = observation.zones
|
||||
.map((z) => {
|
||||
const label = zoneLabels.get(z.boneId) ?? z.boneId
|
||||
const pair = zoneLabels.get(z.boneId)
|
||||
const label = pair
|
||||
? (locale === 'en' ? pair.en || pair.fr : pair.fr || pair.en) || z.boneId
|
||||
: z.boneId
|
||||
const v = z.vertebrae?.length
|
||||
? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})`
|
||||
: ''
|
||||
|
||||
@@ -3,10 +3,32 @@ 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') return 'fr'
|
||||
const raw = localStorage.getItem(LOCALE_STORAGE_KEY)
|
||||
return raw === 'fr' || raw === 'en' ? raw : 'fr'
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
const raw = localStorage.getItem(LOCALE_STORAGE_KEY)
|
||||
if (raw === 'fr' || raw === 'en') return raw
|
||||
}
|
||||
return detectNavigatorLocale() ?? 'fr'
|
||||
}
|
||||
|
||||
export interface LocaleStore {
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import FindingsTreePicker from '@/components/observation/FindingsTreePicker'
|
||||
import type { ZoneFindings } from '@/domain/schema/findings'
|
||||
import type { Finding } from '@/domain/schema/observation'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
beforeEach(() => {
|
||||
// Navigator-detected default may land on EN in happy-dom; force FR so the
|
||||
// FR-label assertions in this file remain stable regardless of the runner's
|
||||
// navigator.language.
|
||||
useLocaleStore.setState({ locale: 'fr' })
|
||||
})
|
||||
|
||||
const TREE: ZoneFindings = {
|
||||
id: 'sphenoid',
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import VertebraPicker, {
|
||||
regionFromLabel,
|
||||
} from '@/components/observation/VertebraPicker'
|
||||
import { EQUINE_VERTEBRAL_FORMULA } from '@/domain/species/equine/vertebrae'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
|
||||
beforeEach(() => {
|
||||
useLocaleStore.setState({ locale: 'fr' })
|
||||
})
|
||||
|
||||
describe('VertebraPicker', () => {
|
||||
it('renders region tabs based on the formula', () => {
|
||||
|
||||
@@ -58,33 +58,32 @@ const baseReport: Report = {
|
||||
}
|
||||
|
||||
describe('buildZoneLabels', () => {
|
||||
it('maps detail-popup boneIds to their FR labels', async () => {
|
||||
it('maps detail-popup boneIds to their FR + EN labels', async () => {
|
||||
detailFetchShouldFail = false
|
||||
const labels = await buildZoneLabels(baseReport)
|
||||
// ATM hitbox in Horse_head.svg
|
||||
expect(labels.get('point-mpbyo7zq')).toBe(
|
||||
'Articulation Temporo-Mandibulaire (ATM)',
|
||||
)
|
||||
// Sphénoïde hitbox in Horse_head.svg
|
||||
expect(labels.get('point-mpbymcln')).toBe('Sphénoïde')
|
||||
const atm = labels.get('point-mpbyo7zq')
|
||||
expect(atm?.fr).toBe('Articulation Temporo-Mandibulaire (ATM)')
|
||||
expect(atm?.en).toBe('Temporomandibular Joint (TMJ)')
|
||||
const sphenoid = labels.get('point-mpbymcln')
|
||||
expect(sphenoid?.fr).toBe('Sphénoïde')
|
||||
expect(sphenoid?.en).toBe('Sphenoid')
|
||||
})
|
||||
|
||||
it('maps main-SVG boneIds to their FR labels', async () => {
|
||||
it('maps main-SVG boneIds to their FR + EN labels', async () => {
|
||||
detailFetchShouldFail = false
|
||||
const labels = await buildZoneLabels(baseReport)
|
||||
expect(labels.size).toBeGreaterThan(0)
|
||||
// The map should contain at least one Vertèbres entry from the main SVG.
|
||||
const values = Array.from(labels.values())
|
||||
expect(values.some((v) => v.includes('Vertèbres'))).toBe(true)
|
||||
const pairs = Array.from(labels.values())
|
||||
expect(pairs.some((p) => p.fr.includes('Vertèbres'))).toBe(true)
|
||||
expect(pairs.some((p) => p.en.includes('Vertebrae'))).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps the main labels even when the detail SVG fetch fails', async () => {
|
||||
detailFetchShouldFail = true
|
||||
const labels = await buildZoneLabels(baseReport)
|
||||
// Detail entries gone — but main entries must survive the partial failure.
|
||||
expect(labels.get('point-mpbymcln')).toBeUndefined()
|
||||
const values = Array.from(labels.values())
|
||||
expect(values.some((v) => v.includes('Vertèbres'))).toBe(true)
|
||||
const pairs = Array.from(labels.values())
|
||||
expect(pairs.some((p) => p.fr.includes('Vertèbres'))).toBe(true)
|
||||
})
|
||||
|
||||
it('returns an empty map for an unknown species', async () => {
|
||||
|
||||
Reference in new issue
Block a user