diff --git a/backend/src/lib/annotation-changes.ts b/backend/src/lib/annotation-changes.ts index b561306..b6b9e14 100644 --- a/backend/src/lib/annotation-changes.ts +++ b/backend/src/lib/annotation-changes.ts @@ -1,5 +1,3 @@ -import path from 'node:path' - import { Prisma, type PrismaClient } from '../generated/prisma/client.js' import { z } from 'zod' @@ -15,9 +13,9 @@ type Db = PrismaClient | Tx export const MAX_ANNOTATIONS_PER_TREE = 5000 // Un envoi de photo jamais proposé vit le temps d'un brouillon de la famille -export const PENDING_PHOTO_TTL_MS = 7 * 24 * 60 * 60 * 1000 +const PENDING_PHOTO_TTL_MS = 7 * 24 * 60 * 60 * 1000 // Une famille pose quelques photos à la fois ; au-delà, c'est un envoi en boucle -export const MAX_PENDING_PHOTOS_PER_TREE = 50 +const MAX_PENDING_PHOTOS_PER_TREE = 50 const MAX_STYLE_CHARS = 4000 const styleSchema = z.record(z.string(), z.unknown()).refine( @@ -93,7 +91,7 @@ export function normalizedAnnotationAfter(change: AnnotationChange, treeId: stri } // Identifiant de la photo d'une annotation (contenu JSON { photoPath }), ou null -export function annotationPhotoId(after: unknown, treeId: string): string | null { +function annotationPhotoId(after: unknown, treeId: string): string | null { if (!after || typeof after !== 'object' || Array.isArray(after)) return null const content = (after as { content?: unknown }).content if (typeof content !== 'string' || !content.startsWith('{')) return null @@ -227,8 +225,3 @@ export async function reservePendingPhoto(prisma: PrismaClient, treeId: string, export async function forgetPendingPhoto(db: Db, photoId: string): Promise { await db.annotationPhotoUpload.deleteMany({ where: { id: photoId } }) } - -// Chemin relatif sûr d'une photo d'annotation (sous /annotation-photos/) -export function annotationPhotoRelativePath(treeId: string, photoId: string, extension: string): string { - return path.posix.join(treeId, 'annotation-photos', `${photoId}${extension}`) -} diff --git a/backend/src/lib/avatar-crop.ts b/backend/src/lib/avatar-crop.ts index d386377..4ff3eb6 100644 --- a/backend/src/lib/avatar-crop.ts +++ b/backend/src/lib/avatar-crop.ts @@ -6,7 +6,7 @@ import { z } from 'zod' export const FRAME_SHAPES = ['round', 'square', 'polaroid', 'portrait', 'landscape'] as const export type AvatarCrop = { x: number; y: number; zoom: number; shape?: (typeof FRAME_SHAPES)[number] } -export const AVATAR_CROP_MAX_ZOOM = 4 +const AVATAR_CROP_MAX_ZOOM = 4 export const avatarCropInputSchema = z.object({ crop: z diff --git a/backend/src/lib/gedcom-events.ts b/backend/src/lib/gedcom-events.ts index c5cf8fe..34ff8f4 100644 --- a/backend/src/lib/gedcom-events.ts +++ b/backend/src/lib/gedcom-events.ts @@ -45,8 +45,11 @@ const clip = (value: string | null | undefined, max: number) => { const child = (node: Node | undefined, tag: string) => node?.children.find((c) => c.tag === tag) -// Même règle que le lieu de naissance : noms seulement, sans case vide ni code INSEE ou postal -export function cleanPlace(value: string | null | undefined): string | null { +// Lieu d'un GEDCOM : les logiciels remplissent toutes les colonnes de leur format de lieu, même vides, et y +// glissent des codes. Heredis écrit « La Roche-sur-Yon,85191,Vendée,Pays de la Loire,France, » (ville, code +// INSEE, département, région, pays, subdivision). On garde les noms, sans case vide, sans code INSEE ni +// postal, sans répétition : « La Roche-sur-Yon, Vendée, Pays de la Loire, France ». +export function cleanGedcomPlace(value: string | null | undefined): string | null { if (!value) return null const parts: string[] = [] for (const raw of value.split(',')) { @@ -58,7 +61,7 @@ export function cleanPlace(value: string | null | undefined): string | null { return parts.length ? parts.join(', ') : null } -export function isoToDbDate(iso: string | null | undefined): Date | null { +function isoToDbDate(iso: string | null | undefined): Date | null { if (!iso) return null if (/^\d{4}$/.test(iso)) return new Date(`${iso}-01-01T00:00:00.000Z`) if (/^\d{4}-\d{2}$/.test(iso)) return new Date(`${iso}-01T00:00:00.000Z`) @@ -76,7 +79,7 @@ function eventSources(node: Node, records: GedcomRecords): string | null { } // Ce qu'on lit d'un événement : date et précision, lieu (ou adresse), description, notes, sources -export function readEvent(node: Node, type: string, records: GedcomRecords): ImportedEvent { +function readEvent(node: Node, type: string, records: GedcomRecords): ImportedEvent { const dateText = child(node, 'DATE')?.value ?? null const parsed = parseGedcomDate(dateText) const addr = child(node, 'ADDR') @@ -84,7 +87,7 @@ export function readEvent(node: Node, type: string, records: GedcomRecords): Imp .map((part) => part.trim()) .filter(Boolean) .join(', ') - const place = cleanPlace(child(node, 'PLAC')?.value) ?? clip(address, 300) + const place = cleanGedcomPlace(child(node, 'PLAC')?.value) ?? clip(address, 300) const typeLabel = joinedText(child(node, 'TYPE')) const value = node.value && node.value.toUpperCase() !== 'Y' ? node.value : '' return { @@ -142,7 +145,7 @@ export function personExtras(indi: Node, records: GedcomRecords): PersonExtras { birthDateEnd: isoToDbDate(birthDate?.endIso), deathDatePrecision: deathDate && deathDate.precision !== 'exact' ? deathDate.precision : null, deathDateEnd: isoToDbDate(deathDate?.endIso), - deathPlace: clip(cleanPlace(child(death, 'PLAC')?.value), 200), + deathPlace: clip(cleanGedcomPlace(child(death, 'PLAC')?.value), 200), nickname: clip(child(nameNode, 'NICK')?.value ?? child(indi, 'NICK')?.value, 120), events, } @@ -171,7 +174,7 @@ export function familyExtras(fam: Node, records: GedcomRecords): UnionExtras { events.push(event) } return { - startPlace: clip(cleanPlace(child(marriage, 'PLAC')?.value), 300), + startPlace: clip(cleanGedcomPlace(child(marriage, 'PLAC')?.value), 300), startDatePrecision: date && date.precision !== 'exact' ? date.precision : null, events, } diff --git a/backend/src/lib/immich-secret.ts b/backend/src/lib/immich-secret.ts index 5a9d181..b9ca2c1 100644 --- a/backend/src/lib/immich-secret.ts +++ b/backend/src/lib/immich-secret.ts @@ -1,37 +1,6 @@ -import { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from 'node:crypto' - -import { env } from '../config/env.js' +import { sealedSecret } from './sealed-secret.js' // Clé d'API Immich d'un arbre : secrète au repos, jamais renvoyée au front ni écrite dans les -// journaux. Même mécanisme que le mot de passe de partage (share-password.ts) : AES-256-GCM, -// clé dérivée de JWT_SECRET. Changer ce secret rend les clés illisibles ; chaque arbre -// repasse alors en « à configurer », sans rien casser d'autre. -const VERSION = 'v1' - -function getKey(): Buffer { - return Buffer.from(hkdfSync('sha256', env.JWT_SECRET, 'parenthese', 'immich-api-key-v1', 32)) -} - -export function encryptImmichApiKey(value: string): string { - const iv = randomBytes(12) - const cipher = createCipheriv('aes-256-gcm', getKey(), iv) - const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]) - const tag = cipher.getAuthTag() - return `${VERSION}:${Buffer.concat([iv, tag, encrypted]).toString('base64')}` -} - -// null si la valeur stockée est absente, d'un autre format, ou illisible (JWT_SECRET changé). -export function decryptImmichApiKey(stored: string | null | undefined): string | null { - if (!stored || !stored.startsWith(`${VERSION}:`)) { - return null - } - - try { - const raw = Buffer.from(stored.slice(VERSION.length + 1), 'base64') - const decipher = createDecipheriv('aes-256-gcm', getKey(), raw.subarray(0, 12)) - decipher.setAuthTag(raw.subarray(12, 28)) - return Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString('utf8') - } catch { - return null - } -} +// journaux. Changer JWT_SECRET rend les clés illisibles ; chaque arbre repasse alors en +// « à configurer », sans rien casser d'autre. +export const { encrypt: encryptImmichApiKey, decrypt: decryptImmichApiKey } = sealedSecret('immich-api-key-v1') diff --git a/backend/src/lib/immich.ts b/backend/src/lib/immich.ts index b6bd2e4..92cb981 100644 --- a/backend/src/lib/immich.ts +++ b/backend/src/lib/immich.ts @@ -61,7 +61,7 @@ type ImmichPeoplePage = { hasNextPage?: unknown } -export class ImmichClient { +class ImmichClient { private readonly apiUrl: string private readonly apiKey: string @@ -274,7 +274,7 @@ export type ImmichInstance = { let instancesCache: ImmichInstance[] | undefined -export function immichInstanceId(apiUrl: string): string { +function immichInstanceId(apiUrl: string): string { return createHash('sha256').update(apiUrl).digest('hex').slice(0, 16) } diff --git a/backend/src/lib/media-people.ts b/backend/src/lib/media-people.ts index a8227f7..ef2adda 100644 --- a/backend/src/lib/media-people.ts +++ b/backend/src/lib/media-people.ts @@ -5,11 +5,11 @@ type Db = PrismaClient | Prisma.TransactionClient // Personnes identifiées sur un souvenir. La liste envoyée remplace la précédente : retirer quelqu'un, c'est // renvoyer la liste sans lui. Le point (x, y) est facultatif, en proportion de l'image (0 à 1), et va par paire. -export const MAX_PEOPLE_PER_MEDIA = 50 +const MAX_PEOPLE_PER_MEDIA = 50 const coordinate = z.number().min(0).max(1).nullable().optional() -export const mediaPersonSchema = z +const mediaPersonSchema = z .object({ personId: z.string().min(1).max(64), x: coordinate, @@ -28,15 +28,6 @@ export function normalizeMediaPeople(people: z.infer): return people.map((person) => ({ personId: person.personId, x: person.x ?? null, y: person.y ?? null })) } -export async function readMediaPeople(db: Db, treeId: string, mediaId: string): Promise { - const tags = await db.mediaPersonTag.findMany({ - where: { treeId, mediaId }, - select: { personId: true, x: true, y: true }, - orderBy: [{ createdAt: 'asc' }, { id: 'asc' }], - }) - return tags -} - // Remplace les personnes d'un souvenir. Une personne supprimée entre l'envoi et la relecture est écartée // sans faire échouer le reste. Renvoie la liste réellement enregistrée. export async function replaceMediaPeople( diff --git a/backend/src/lib/oidc.ts b/backend/src/lib/oidc.ts index 97a78ee..b3c222b 100644 --- a/backend/src/lib/oidc.ts +++ b/backend/src/lib/oidc.ts @@ -31,7 +31,7 @@ export function isOidcEnabled(): boolean { let configuration: Promise | null = null // Découverte faite au premier besoin puis gardée ; un échec (fournisseur injoignable) sera retenté à la connexion suivante -export function getOidcConfiguration(): Promise { +function getOidcConfiguration(): Promise { configuration ??= discover().catch((error: unknown) => { configuration = null throw error @@ -122,8 +122,3 @@ export async function finishAuthorization(callbackQuery: string, pending: OidcPe firstName: firstName?.slice(0, 60) ?? null, } } - -// Pour les tests : oublie la configuration découverte -export function resetOidcConfiguration() { - configuration = null -} diff --git a/backend/src/lib/sealed-secret.ts b/backend/src/lib/sealed-secret.ts new file mode 100644 index 0000000..0677809 --- /dev/null +++ b/backend/src/lib/sealed-secret.ts @@ -0,0 +1,37 @@ +import { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from 'node:crypto' + +import { env } from '../config/env.js' + +// Secret gardé au repos et relisible par le serveur : AES-256-GCM, clé dérivée de JWT_SECRET et d'un +// libellé propre à chaque usage. Changer JWT_SECRET rend les valeurs illisibles : la lecture renvoie null. +const VERSION = 'v1' + +export function sealedSecret(usage: string) { + const key = () => Buffer.from(hkdfSync('sha256', env.JWT_SECRET, 'parenthese', usage, 32)) + + function encrypt(value: string): string { + const iv = randomBytes(12) + const cipher = createCipheriv('aes-256-gcm', key(), iv) + const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]) + const tag = cipher.getAuthTag() + return `${VERSION}:${Buffer.concat([iv, tag, encrypted]).toString('base64')}` + } + + // null si la valeur stockée est absente, d'un autre format, ou illisible (JWT_SECRET changé). + function decrypt(stored: string | null | undefined): string | null { + if (!stored || !stored.startsWith(`${VERSION}:`)) { + return null + } + + try { + const raw = Buffer.from(stored.slice(VERSION.length + 1), 'base64') + const decipher = createDecipheriv('aes-256-gcm', key(), raw.subarray(0, 12)) + decipher.setAuthTag(raw.subarray(12, 28)) + return Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString('utf8') + } catch { + return null + } + } + + return { encrypt, decrypt } +} diff --git a/backend/src/lib/search-sources.ts b/backend/src/lib/search-sources.ts index 335ebc2..d2f4ba0 100644 --- a/backend/src/lib/search-sources.ts +++ b/backend/src/lib/search-sources.ts @@ -36,7 +36,7 @@ const TIMEOUT_MS = 10_000 const MAX_RESULTS = 10 const USER_AGENT = 'Parenthese (+https://parenthese.io)' -export function normalizeName(value: string): string { +function normalizeName(value: string): string { return value.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase().replace(/[^a-z]+/g, ' ').trim() } diff --git a/backend/src/lib/share-password.ts b/backend/src/lib/share-password.ts index f121fac..32bcfe9 100644 --- a/backend/src/lib/share-password.ts +++ b/backend/src/lib/share-password.ts @@ -1,35 +1,6 @@ -import { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from 'node:crypto' - -import { env } from '../config/env.js' +import { sealedSecret } from './sealed-secret.js' // Le mot de passe de partage est fait pour être donné à la famille : le propriétaire doit pouvoir le relire. -// Chiffré en AES-256-GCM, clé dérivée de JWT_SECRET (changer ce secret rend les valeurs illisibles, -// le panneau repasse alors en « à saisir », sans rien casser pour la famille). -const VERSION = 'v1' - -function getKey(): Buffer { - return Buffer.from(hkdfSync('sha256', env.JWT_SECRET, 'parenthese', 'share-password-v1', 32)) -} - -export function encryptSharePassword(value: string): string { - const iv = randomBytes(12) - const cipher = createCipheriv('aes-256-gcm', getKey(), iv) - const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]) - const tag = cipher.getAuthTag() - return `${VERSION}:${Buffer.concat([iv, tag, encrypted]).toString('base64')}` -} - -export function decryptSharePassword(stored: string | null | undefined): string | null { - if (!stored || !stored.startsWith(`${VERSION}:`)) { - return null - } - - try { - const raw = Buffer.from(stored.slice(VERSION.length + 1), 'base64') - const decipher = createDecipheriv('aes-256-gcm', getKey(), raw.subarray(0, 12)) - decipher.setAuthTag(raw.subarray(12, 28)) - return Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString('utf8') - } catch { - return null - } -} +// Changer JWT_SECRET rend les valeurs illisibles : le panneau repasse alors en « à saisir », sans rien +// casser pour la famille. +export const { encrypt: encryptSharePassword, decrypt: decryptSharePassword } = sealedSecret('share-password-v1') diff --git a/backend/src/lib/tree-access.ts b/backend/src/lib/tree-access.ts index 03685c5..f491d92 100644 --- a/backend/src/lib/tree-access.ts +++ b/backend/src/lib/tree-access.ts @@ -36,7 +36,7 @@ export async function canReadTree(app: FastifyInstance, treeId: string, actor: A // Les images sont chargées par , qui ne peut pas envoyer d'en-tête : leur adresse porte un jeton. // Ce jeton ne sert qu'à lire les médias d'un arbre, jamais la session du compte (qui finissait dans les // journaux, l'historique et les liens copiés). -export const MEDIA_TOKEN_TTL = '12h' +const MEDIA_TOKEN_TTL = '12h' export function signMediaToken(app: FastifyInstance, treeId: string, actor: NonNullable): string { const payload: MediaJwtPayload = { diff --git a/backend/src/lib/tree-purge.ts b/backend/src/lib/tree-purge.ts index 76fc701..b2895d4 100644 --- a/backend/src/lib/tree-purge.ts +++ b/backend/src/lib/tree-purge.ts @@ -10,7 +10,7 @@ export type PurgeLogger = { error: (details: Record, message: string) => void } -export function getMediaStorageRoot(): string { +function getMediaStorageRoot(): string { return path.resolve(env.MEDIA_STORAGE_PATH) } diff --git a/backend/src/lib/tree-visits.ts b/backend/src/lib/tree-visits.ts index 84dd2d7..27f9926 100644 --- a/backend/src/lib/tree-visits.ts +++ b/backend/src/lib/tree-visits.ts @@ -5,7 +5,7 @@ import { env } from '../config/env.js' // Une ouverture d'arbre = une visite. Les rechargements du même visiteur dans cette fenêtre // (graphe rechargé après une modification, onglet rouvert) ne comptent qu'une fois. -export const VISIT_DEDUP_WINDOW_MS = 30 * 60 * 1000 +const VISIT_DEDUP_WINDOW_MS = 30 * 60 * 1000 // Au-delà, les visites sont effacées : à l'enregistrement d'une visite (au plus une fois par heure, // pour tous les arbres) et à la lecture de l'onglet Visites export const VISIT_RETENTION_DAYS = 365 @@ -14,14 +14,14 @@ let lastPurgeAt = 0 export type VisitAccessKind = 'share' | 'member' | 'shared_account' -export function deviceFromUserAgent(userAgent: string): 'phone' | 'tablet' | 'desktop' { +function deviceFromUserAgent(userAgent: string): 'phone' | 'tablet' | 'desktop' { if (/iPad|Tablet/i.test(userAgent)) return 'tablet' if (/Mobi|Android|iPhone|iPod/i.test(userAgent)) return 'phone' return 'desktop' } // Prénom envoyé par l'app en en-tête X-Visitor-Name (encodé en URI pour les accents) -export function visitorNameFromHeader(value: unknown): string | null { +function visitorNameFromHeader(value: unknown): string | null { if (typeof value !== 'string' || !value) return null let decoded = value try { @@ -33,7 +33,7 @@ export function visitorNameFromHeader(value: unknown): string | null { return trimmed || null } -export function visitorKeyOf(treeId: string, ip: string, userAgent: string): string { +function visitorKeyOf(treeId: string, ip: string, userAgent: string): string { return createHash('sha256').update(`${env.JWT_SECRET}|${treeId}|${ip}|${userAgent}`).digest('hex').slice(0, 32) } diff --git a/backend/src/lib/unlock-guard.ts b/backend/src/lib/unlock-guard.ts index 16e4bfe..fae3b42 100644 --- a/backend/src/lib/unlock-guard.ts +++ b/backend/src/lib/unlock-guard.ts @@ -40,12 +40,6 @@ export function reserveTreeUnlockAttempt(treeId: string, now = Date.now()): (() } } -export function recordTreeUnlockFailure(treeId: string, now = Date.now()): void { - const recent = recentAttempts(treeId, now) - recent.push(now) - attemptsByTree.set(treeId, recent) -} - export function resetTreeUnlockGuard(): void { attemptsByTree.clear() } diff --git a/backend/src/routes/contributions.ts b/backend/src/routes/contributions.ts index 219c60f..4a43be8 100644 --- a/backend/src/routes/contributions.ts +++ b/backend/src/routes/contributions.ts @@ -1450,7 +1450,7 @@ export const contributionRoutes: FastifyPluginAsync = async (app) => { const rejectedMediaIds: string[] = [] const filesToRemove: string[] = [] - const { updatedSession, approvedCount, rejectedCount, conflictCount, status } = await app.prisma.$transaction(async (tx) => { + const { updatedSession, approvedCount, rejectedCount, conflictCount } = await app.prisma.$transaction(async (tx) => { // Deux relectures simultanées : la seconde attend le verrou de la ligne, puis ne trouve plus // la session en attente. Sans ce verrou, les deux appliquaient les mêmes ajouts. const claimed = await tx.contributionSession.updateMany({ diff --git a/backend/src/routes/gedcom.ts b/backend/src/routes/gedcom.ts index 563581e..8ee2a5a 100644 --- a/backend/src/routes/gedcom.ts +++ b/backend/src/routes/gedcom.ts @@ -3,7 +3,7 @@ import { z } from 'zod' import { UPLOAD_BODY_LIMIT } from '../config/env.js' import { parseGedcomDate } from '../lib/gedcom-dates.js' -import { adoptedFamilies, FAMILY_EVENT_TYPES, familyExtras, PERSON_EVENT_TYPES, personExtras } from '../lib/gedcom-events.js' +import { adoptedFamilies, cleanGedcomPlace, FAMILY_EVENT_TYPES, familyExtras, PERSON_EVENT_TYPES, personExtras } from '../lib/gedcom-events.js' import { indexGedcomRecords, mediaRefsForPerson, noteText, photoPathForPerson } from '../lib/gedcom-photos.js' import type { GedcomRecords } from '../lib/gedcom-photos.js' import type { MembershipRole } from '../types/auth.js' @@ -44,22 +44,6 @@ function clip(value: string | null, max: number): string | null { return trimmed ? trimmed.slice(0, max) : null } -// Lieu d'un GEDCOM : les logiciels remplissent toutes les colonnes de leur format de lieu, même vides, et y -// glissent des codes. Heredis écrit « La Roche-sur-Yon,85191,Vendée,Pays de la Loire,France, » (ville, code -// INSEE, département, région, pays, subdivision). On garde les noms, sans case vide, sans code INSEE ni -// postal, sans répétition : « La Roche-sur-Yon, Vendée, Pays de la Loire, France ». -export function cleanGedcomPlace(value: string | null | undefined): string | null { - if (!value) return null - const parts: string[] = [] - for (const raw of value.split(',')) { - const part = raw.trim() - if (!part || /^(\d{4,5}|2[AB]\d{3})$/i.test(part)) continue - if (parts.length && parts[parts.length - 1].toLowerCase() === part.toLowerCase()) continue - parts.push(part) - } - return parts.length ? parts.join(', ') : null -} - // Export : un champ sur une ligne ne doit jamais en créer une autre (enregistrement injecté) function oneLine(value: string | null | undefined): string { return String(value ?? '').replace(/[\r\n]+/g, ' ') diff --git a/backend/test/gedcom-place.test.ts b/backend/test/gedcom-place.test.ts index d82b0bc..5ca5ebc 100644 --- a/backend/test/gedcom-place.test.ts +++ b/backend/test/gedcom-place.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { cleanGedcomPlace } from '../src/routes/gedcom' +import { cleanGedcomPlace } from '../src/lib/gedcom-events' describe('lieu importé d’un GEDCOM', () => { it('Heredis : colonnes vides et code INSEE retirés', () => { diff --git a/backend/test/security-hardening.test.ts b/backend/test/security-hardening.test.ts index f5080ad..01c8561 100644 --- a/backend/test/security-hardening.test.ts +++ b/backend/test/security-hardening.test.ts @@ -6,7 +6,6 @@ import { isMimeAllowedForType, sanitizeImage, scrubMp4Location, sniffMimeType } import { matchSharePassword } from '../src/lib/password-variants.js' import { isTreeUnlockLocked, - recordTreeUnlockFailure, reserveTreeUnlockAttempt, resetTreeUnlockGuard, serializePasswordCheck, @@ -159,9 +158,9 @@ describe('mot de passe de partage', () => { it('verrouille un arbre après 30 échecs dans la fenêtre, puis le libère', () => { resetTreeUnlockGuard() const now = Date.now() - for (let i = 0; i < 29; i += 1) recordTreeUnlockFailure('tree-x', now) + for (let i = 0; i < 29; i += 1) reserveTreeUnlockAttempt('tree-x', now) expect(isTreeUnlockLocked('tree-x', now)).toBe(false) - recordTreeUnlockFailure('tree-x', now) + reserveTreeUnlockAttempt('tree-x', now) expect(isTreeUnlockLocked('tree-x', now)).toBe(true) expect(isTreeUnlockLocked('tree-autre', now)).toBe(false) expect(isTreeUnlockLocked('tree-x', now + 16 * 60 * 1000)).toBe(false) diff --git a/frontend/src/components/AccessGate.jsx b/frontend/src/components/AccessGate.jsx index 03f0d6c..ff85eb8 100644 --- a/frontend/src/components/AccessGate.jsx +++ b/frontend/src/components/AccessGate.jsx @@ -1,4 +1,4 @@ -import { Fragment, useEffect, useState } from 'react' +import { useEffect, useState } from 'react' import logoUrl from '../assets/parenthese-logo.svg?url' import './AccountScreens.css' import PzBusy from './PzBusy.jsx' @@ -6,15 +6,7 @@ import LanguageSwitch from './navbar/LanguageSwitch' import { t } from '../i18n/index.js' import { readContributorName, saveContributorName } from '../utils/contributorName.js' import { initialOf } from '../utils/initial.js' - -// Phrase traduite d'un bloc : les passages entre astérisques passent en , {slot} reçoit un nœud. -function richText(text, slotNode = null) { - return text.split(/(\{slot\})/).flatMap((chunk, chunkIndex) => ( - chunk === '{slot}' - ? [{slotNode}] - : chunk.split('*').map((part, index) => (index % 2 ? {part} : part)) - )) -} +import { richText } from '../utils/richText.jsx' const AccessGate = ({ initialTreeId, diff --git a/frontend/src/components/AccountDashboard.jsx b/frontend/src/components/AccountDashboard.jsx index 7705b06..392fe69 100644 --- a/frontend/src/components/AccountDashboard.jsx +++ b/frontend/src/components/AccountDashboard.jsx @@ -1,4 +1,4 @@ -import { Fragment, useEffect, useMemo, useState } from 'react' +import { useEffect, useMemo, useState } from 'react' import { ChevronRight, KeyRound, LogIn, LogOut, Plus, Sparkles, X } from 'lucide-react' import logoUrl from '../assets/parenthese-logo.svg?url' import './AccountScreens.css' @@ -7,15 +7,7 @@ import LanguageSwitch from './navbar/LanguageSwitch' import { t } from '../i18n/index.js' import { PRIVACY_URL } from '../utils/siteLinks.js' import { initialOf } from '../utils/initial.js' - -// Phrase traduite d'un bloc : les passages entre astérisques passent en , {slot} reçoit un nœud. -function richText(text, slotNode = null) { - return text.split(/(\{slot\})/).flatMap((chunk, chunkIndex) => ( - chunk === '{slot}' - ? [{slotNode}] - : chunk.split('*').map((part, index) => (index % 2 ? {part} : part)) - )) -} +import { richText } from '../utils/richText.jsx' const AccountDashboard = ({ authenticated, diff --git a/frontend/src/components/AddPersonPanel.jsx b/frontend/src/components/AddPersonPanel.jsx index 4cb1dce..7018d77 100644 --- a/frontend/src/components/AddPersonPanel.jsx +++ b/frontend/src/components/AddPersonPanel.jsx @@ -9,12 +9,7 @@ import { SEX_CHOICES } from '../utils/personSex.js' import { initialOf } from '../utils/initial.js' import { findLikelyDuplicates } from '../utils/duplicates.js' import PortraitThumb from './PortraitThumb.jsx' - -// Titre traduit d'un bloc : le passage entre et garde son italique -function withEmphasis(text) { - const [before, emphasized = '', after = ''] = text.split(/<\/?em>/) - return <>{before}{emphasized}{after} -} +import { withEmphasis } from '../utils/richText.jsx' /** * Panneau slide-in gauche pour ajouter une personne diff --git a/frontend/src/components/PhotoStartPanel.jsx b/frontend/src/components/PhotoStartPanel.jsx index 7df1f2d..5c1aed0 100644 --- a/frontend/src/components/PhotoStartPanel.jsx +++ b/frontend/src/components/PhotoStartPanel.jsx @@ -6,11 +6,7 @@ import { t } from '../i18n/index.js' import { matchPhotoFiles } from '../utils/photoImport.js' import { materializeFile } from '../utils/zipReader.js' import { initialsOf } from '../utils/initial.js' - -function withEmphasis(text) { - const [before, emphasized = '', after = ''] = text.split(/<\/?em>/) - return <>{before}{emphasized}{after} -} +import { withEmphasis } from '../utils/richText.jsx' function lifeYears(person) { if (!person.birthYear) return '' diff --git a/frontend/src/components/SearchSourcesPanel.jsx b/frontend/src/components/SearchSourcesPanel.jsx index c9b176a..e94644e 100644 --- a/frontend/src/components/SearchSourcesPanel.jsx +++ b/frontend/src/components/SearchSourcesPanel.jsx @@ -10,6 +10,7 @@ import { changesFromResult, personFromResult } from '../utils/searchResultChange import { fullNameLabel } from '../utils/personName.js' import Skeleton from './Skeleton.jsx' import PortraitThumb from './PortraitThumb.jsx' +import { withEmphasis } from '../utils/richText.jsx' // Ce que chaque source interrogée couvre et ce qui part vers elle : affiché avant qu'on coche const SOURCE_INFO = { @@ -86,12 +87,6 @@ function personYears(person) { return [birth, death].filter(Boolean).join(' – ') } -// Titre traduit : le passage entre et garde son italique (comme « Ajouter quelqu'un ») -function withEmphasis(text) { - const [before, emphasized = '', after = ''] = text.split(/<\/?em>/) - return <>{before}{emphasized}{after} -} - // Mêmes libellés que « Ajouter quelqu'un » : la nouvelle personne est parent, enfant… de quelqu'un de l'arbre const RELATION_TABS = { parent: t('Parent'), diff --git a/frontend/src/components/TreeCreationWizard.jsx b/frontend/src/components/TreeCreationWizard.jsx index 90c1a29..1168e3c 100644 --- a/frontend/src/components/TreeCreationWizard.jsx +++ b/frontend/src/components/TreeCreationWizard.jsx @@ -3,6 +3,7 @@ import { FileUp, ImagePlus } from 'lucide-react' import './TreeCreationWizard.css' import PzBusy from './PzBusy.jsx' import { t } from '../i18n/index.js' +import { withEmphasis } from '../utils/richText.jsx' const INITIAL_STATE = { treeName: '', @@ -15,12 +16,6 @@ const INITIAL_STATE = { gedcomFile: null, } -// Titre traduit d'un bloc : le passage entre et garde son italique -function withEmphasis(text) { - const [before, emphasized = '', after = ''] = text.split(/<\/?em>/) - return <>{before}{emphasized}{after} -} - function TreeCreationWizard({ visible, loading, diff --git a/frontend/src/components/coGestion.test.jsx b/frontend/src/components/coGestion.test.jsx index 986be6e..be4e085 100644 --- a/frontend/src/components/coGestion.test.jsx +++ b/frontend/src/components/coGestion.test.jsx @@ -2,7 +2,6 @@ import { renderToStaticMarkup } from 'react-dom/server' import { describe, expect, it } from 'vitest' import PersonCard from './PersonCard.jsx' import AdminPanel from './AdminPanel.jsx' -import TreeDropdown from './navbar/TreeDropdown.jsx' // Co-gestion (issue #145) et « Modifier » de la fiche : ce que chaque rôle voit. Les droits eux-mêmes sont tenus // par le serveur (backend/test/co-gestion.db.test.ts) ; ici, l'interface ne propose pas ce qui serait refusé. @@ -21,12 +20,6 @@ describe('fiche, « Modifier » d’un clic', () => { }) describe('co-gestionnaire dans les menus', () => { - it('le menu des arbres nomme le rôle « Co-gestionnaire », plus « Admin »', () => { - const html = renderToStaticMarkup() - expect(html).toContain('Co-gestionnaire') - expect(html).not.toContain('>Admin<') - }) - it('le panneau a un onglet Gestion', () => { const html = renderToStaticMarkup() expect(html).toContain('Gestion') diff --git a/frontend/src/components/navbar/TreeDropdown.css b/frontend/src/components/navbar/TreeDropdown.css deleted file mode 100644 index 1df4ca9..0000000 --- a/frontend/src/components/navbar/TreeDropdown.css +++ /dev/null @@ -1,151 +0,0 @@ -.tree-dropdown { - position: absolute; - bottom: calc(100% + 8px); - right: 0; - min-width: 320px; - max-width: 400px; - max-height: 480px; - background: rgba(242, 239, 234, 0.98); - backdrop-filter: blur(24px); - -webkit-backdrop-filter: blur(24px); - border-radius: 12px; - border: 1px solid rgba(42, 38, 34, 0.08); - box-shadow: - 0 8px 32px rgba(42, 38, 34, 0.25), - 0 2px 8px rgba(42, 38, 34, 0.08); - padding: 8px; - overflow-y: auto; - animation: dropdownSlideUp 0.25s cubic-bezier(0.22, 1, 0.36, 1); - transform-origin: bottom right; -} - -.tree-dropdown::-webkit-scrollbar { - width: 6px; -} - -.tree-dropdown::-webkit-scrollbar-track { - background: transparent; -} - -.tree-dropdown::-webkit-scrollbar-thumb { - background: rgba(147, 64, 42, 0.2); - border-radius: 3px; -} - -.tree-dropdown-section { - margin-bottom: 8px; -} - -.tree-dropdown-section:last-child { - margin-bottom: 0; -} - -.tree-dropdown-section-title { - font-family: 'Newsreader', Georgia, 'Times New Roman', serif; - font-size: 14px; - font-weight: 450; - color: #93402A; - text-transform: uppercase; - letter-spacing: 0.8px; - padding: 8px 12px 6px; -} - -.tree-dropdown-item { - width: 100%; - display: flex; - align-items: center; - gap: 12px; - padding: 10px 12px; - background: transparent; - border: none; - border-radius: 8px; - cursor: pointer; - text-align: left; - transition: all 0.2s ease; -} - -.tree-dropdown-item:hover { - background: rgba(147, 64, 42, 0.08); -} - -.tree-dropdown-item.active { - background: rgba(147, 64, 42, 0.15); -} - -.tree-dropdown-item-thumb { - width: 40px; - height: 40px; - border-radius: 8px; - overflow: hidden; - background: #2a2622; - flex-shrink: 0; - display: flex; - align-items: center; - justify-content: center; -} - -.tree-dropdown-item-thumb img { - width: 100%; - height: 100%; - object-fit: cover; -} - -.tree-dropdown-item-icon { - font-size: 20px; -} - -.tree-dropdown-item-info { - flex: 1; - min-width: 0; -} - -.tree-dropdown-item-name { - font-size: 14px; - font-weight: 500; - color: #2A2622; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} - -.tree-dropdown-item-role { - font-size: 14px; - color: #6B645D; - text-transform: uppercase; - letter-spacing: 0.3px; - margin-top: 2px; -} - -/* Actions */ -.tree-dropdown-actions { - border-top: 1px solid rgba(42, 38, 34, 0.08); - padding-top: 8px; - margin-top: 8px; -} - -.tree-dropdown-create { - width: 100%; - display: flex; - align-items: center; - gap: 10px; - padding: 10px 12px; - background: rgba(147, 64, 42, 0.08); - border: 1px dashed rgba(147, 64, 42, 0.3); - border-radius: 8px; - cursor: pointer; - font-family: 'DM Sans', system-ui, sans-serif; - font-size: 14px; - font-weight: 500; - color: #93402A; - transition: all 0.2s ease; -} - -.tree-dropdown-create:hover { - background: rgba(147, 64, 42, 0.15); - border-color: rgba(147, 64, 42, 0.5); -} - -.tree-dropdown-create-icon { - font-size: 20px; - font-weight: 300; -} diff --git a/frontend/src/components/navbar/TreeDropdown.jsx b/frontend/src/components/navbar/TreeDropdown.jsx deleted file mode 100644 index 86f2cdb..0000000 --- a/frontend/src/components/navbar/TreeDropdown.jsx +++ /dev/null @@ -1,116 +0,0 @@ -import { Trees } from 'lucide-react' -import { t } from '../../i18n/index.js' -import './TreeDropdown.css' - -/** - * Dropdown de sélection d'arbres - * Affiche la liste des arbres accessibles + option création - * - * @param {Object} props - * @param {Array} props.trees - Liste des arbres [{id, name, role, thumb}] - * @param {string} props.activeTreeId - ID de l'arbre actif - * @param {Function} props.onSelect - Handler sélection arbre (treeId) - * @param {Function} props.onCreate - Handler création nouvel arbre - */ -function TreeDropdown({ trees = [], activeTreeId, onSelect, onCreate }) { - // Séparer arbres par type - const myTrees = trees.filter((tree) => tree.role === 'owner' || tree.role === 'admin') - const sharedTrees = trees.filter((tree) => tree.role !== 'owner' && tree.role !== 'admin') - const mockTree = trees.find((tree) => tree.isMockTree) - - return ( -
- {/* Mes arbres */} - {myTrees.length > 0 && ( -
-
{t('Mes arbres')}
- {myTrees.map(tree => ( - - ))} -
- )} - - {/* Arbres partagés */} - {sharedTrees.length > 0 && ( -
-
{t('Arbres partagés')}
- {sharedTrees.map(tree => ( - - ))} -
- )} - - {/* Arbre mock */} - {mockTree && ( -
-
{t('Exemple')}
- -
- )} - - {/* Actions */} -
- -
-
- ) -} - -export default TreeDropdown diff --git a/frontend/src/hooks/useAuth.js b/frontend/src/hooks/useAuth.js index 4865a5e..6a35d7f 100644 --- a/frontend/src/hooks/useAuth.js +++ b/frontend/src/hooks/useAuth.js @@ -73,6 +73,19 @@ export function useAuth() { return { trees, lastOpenedTree: lastTree } } + // Session ouverte : jeton et profil gardés sur l'appareil, puis les arbres du compte + const openSession = async (token, user) => { + localStorage.setItem(USER_TOKEN_STORAGE_KEY, token) + saveUserProfile(user || null) + setUserAuth({ token, user }) + await Promise.all([ + loadAccountTrees(token), + fetchLastOpenedTree(token).then((lastTree) => { + if (lastTree) setLastOpenedTree(lastTree) + }).catch(() => {}), + ]) + } + const handleLogin = (email, password) => signIn(() => loginUser(email, password)) // Retour d'une connexion OIDC : le jeton de passage devient une session, comme une connexion par mot de passe @@ -89,15 +102,7 @@ export function useAuth() { ...(storedProfile && storedProfile.email === result.user?.email ? storedProfile : {}), ...(result.user || {}), } - localStorage.setItem(USER_TOKEN_STORAGE_KEY, result.token) - saveUserProfile(mergedUser || null) - setUserAuth({ token: result.token, user: mergedUser }) - await Promise.all([ - loadAccountTrees(result.token), - fetchLastOpenedTree(result.token).then((lastTree) => { - if (lastTree) setLastOpenedTree(lastTree) - }).catch(() => {}), - ]) + await openSession(result.token, mergedUser) return true } catch (error) { setAccountError(getAccountErrorMessage(error)) @@ -117,15 +122,7 @@ export function useAuth() { ...(result.user || {}), firstName: firstName || result.user?.firstName || '', } - localStorage.setItem(USER_TOKEN_STORAGE_KEY, result.token) - saveUserProfile(mergedUser || null) - setUserAuth({ token: result.token, user: mergedUser }) - await Promise.all([ - loadAccountTrees(result.token), - fetchLastOpenedTree(result.token).then((lastTree) => { - if (lastTree) setLastOpenedTree(lastTree) - }).catch(() => {}), - ]) + await openSession(result.token, mergedUser) return true } catch (error) { setAccountError(getAccountErrorMessage(error)) diff --git a/frontend/src/i18n/en/arbre.js b/frontend/src/i18n/en/arbre.js index c89418e..ac68e77 100644 --- a/frontend/src/i18n/en/arbre.js +++ b/frontend/src/i18n/en/arbre.js @@ -17,7 +17,7 @@ export default { // Le lien de parenté affiché au survol se nomme langue par langue dans utils/kinship/ - // Glisser pour ajouter une personne (components/ProximityFeedback.jsx) + // Ajouter un proche 'Conjoint': 'Partner', 'Frère·Sœur': 'Sibling', 'Lien': 'Link', @@ -38,8 +38,6 @@ export default { 'Épais': 'Thick', 'Couleur': 'Color', 'Épaisseur': 'Thickness', - 'Relâcher pour supprimer': 'Release to delete', - 'Glisser ici pour supprimer': 'Drag here to delete', 'Stickers': 'Stickers', 'Cliquez sur le canvas': 'Click on the canvas', 'Saisir du texte...': 'Type some text...', diff --git a/frontend/src/i18n/en/compte.js b/frontend/src/i18n/en/compte.js index d255ba4..127e5b1 100644 --- a/frontend/src/i18n/en/compte.js +++ b/frontend/src/i18n/en/compte.js @@ -8,18 +8,14 @@ export default { "Ouvrir {slot}": "Open {slot}", "Ouvrir un arbre *partagé*": "Open a *shared* tree", "Le lien est peut-être incomplet, ou l'arbre a été supprimé. Demandez un nouveau lien à la personne qui vous l'a envoyé.": "The link may be incomplete, or the tree may have been deleted. Ask the person who sent it for a new link.", - "Entrez le mot de passe reçu avec le lien. Pas besoin de compte pour regarder.": "Enter the password that came with the link. You don't need an account to look around.", "Entrez le code et le mot de passe reçus avec votre lien de partage.": "Enter the code and password that came with your share link.", "Partagé par {slot}": "Shared by {slot}", "Code de l'arbre": "Tree code", "Il commence souvent par cm": "It often starts with cm", "Votre prénom": "Your first name", - "Facultatif. Il sert à savoir qui est venu voir l'arbre.": "Optional. It shows who came to see the tree.", "Mot de passe de partage": "Sharing password", "Ouverture de l'arbre": "Opening the tree", - "Ouvrir l'arbre": "Open the tree", "Créer mon arbre": "Create my tree", - "Se connecter avec un compte": "Sign in with an account", "Créer un compte": "Create an account", // Connexion, inscription, liste des arbres, suppression du compte (AccountDashboard) "Revenir à l'arbre": "Back to the tree", @@ -40,8 +36,6 @@ export default { "En créant un compte, vous acceptez {slot}.": "By creating an account, you agree to {slot}.", "la façon dont Parenthèse traite vos données": "how Parenthèse handles your data", "ou": "or", - "Ouvrir un arbre partagé avec moi": "Open a tree shared with me", - "Vous avez déjà un compte ?": "Already have an account?", "Pas encore de compte ?": "Don't have an account yet?", "Cette instance n'accepte plus de nouveaux comptes. Demandez à la personne qui l'héberge.": "This instance no longer accepts new accounts. Ask the person who hosts it.", "Se connecter avec {name}": "Sign in with {name}", @@ -54,7 +48,6 @@ export default { "Votre fournisseur de connexion n'a pas donné d'adresse email. La personne qui héberge l'instance doit autoriser le partage de l'email.": "Your sign-in provider didn't share an email address. The person who hosts this instance needs to allow it.", "Le fournisseur de connexion ne répond pas. Réessayez dans un moment.": "The sign-in provider isn't responding. Try again in a moment.", "La connexion n'a pas abouti. Réessayez.": "Signing in didn't work. Try again.", - "Me connecter": "Sign in", "Vos *arbres*": "Your *trees*", "Ouvrez un arbre, ou commencez celui d'une autre branche de la famille.": "Open a tree, or start one for another branch of the family.", "Aucun arbre pour le moment.": "No trees yet.", @@ -185,7 +178,6 @@ export default { // Barre d'actions, menu du compte, choix de la langue (navbar) "Aucun arbre": "No tree", "Vos arbres": "Your trees", - "Arbre ouvert": "Current tree", "Langue": "Language", "Sélection": "Select", "Texte": "Text", @@ -194,7 +186,6 @@ export default { "Ajouter un souvenir": "Add a memory", "Ajouter une personne": "Add a person", "Plus": "More", - "Dessiner ou écrire sur l'arbre": "Draw or write on the tree", "Dessiner": "Draw", "Écrire un texte": "Write a text", "Poser un sticker": "Add a sticker", @@ -203,7 +194,6 @@ export default { "Le mode d'emploi": "User guide", "Modifier l'arbre": "Edit the tree", "Contributions": "Contributions", - "Contribuer (mot de passe contribution requis)": "Contribute (contribution password required)", "Modifier la démo": "Edit the demo", "Quitter l'édition": "Exit edit mode", "Supprimer": "Delete", @@ -211,11 +201,8 @@ export default { "Mes arbres": "My trees", "Propriétaire": "Owner", "Admin": "Admin", - "Arbres partagés": "Shared trees", "Contributeur": "Contributor", "Visiteur": "Visitor", - "Exemple": "Example", - "Arbre exemple": "Sample tree", "Votre prénom (facultatif)": "Your first name (optional)", "Il sert à savoir qui est venu voir l'arbre.": "It shows who came to see the tree.", "Mot de passe reçu avec le lien": "Password received with the link", diff --git a/frontend/src/i18n/en/contribution.js b/frontend/src/i18n/en/contribution.js index ff5c543..ba25719 100644 --- a/frontend/src/i18n/en/contribution.js +++ b/frontend/src/i18n/en/contribution.js @@ -179,9 +179,6 @@ export default { "Your latest changes aren't saved yet. They stay on this device until you discard them.", 'Abandonner': 'Discard', 'Enregistrer et quitter': 'Save and exit', - 'Mode édition actif': 'Edit mode on', - 'Mode contribution actif': 'Contribution mode on', - 'Envoyer les modifications': 'Send changes', 'Aucune modification à soumettre': 'No changes to submit', "Vous modifiez l'arbre": "You're editing the tree", 'Vous proposez des changements': 'You are suggesting changes', diff --git a/frontend/src/i18n/en/fiche.js b/frontend/src/i18n/en/fiche.js index f040e88..b0181c4 100644 --- a/frontend/src/i18n/en/fiche.js +++ b/frontend/src/i18n/en/fiche.js @@ -24,7 +24,6 @@ export default { 'Retirer': 'Remove', 'Prénom': 'First name', 'Nom': 'Last name', - 'Édition': 'Editing', 'Souvenirs': 'Memories', 'Infos': 'Details', 'Liens': 'Relatives', @@ -177,22 +176,16 @@ export default { 'Miniature cartographique': 'Map thumbnail', // Ajout d'une personne (AddPersonButton, AddPersonPanel, InlinePersonForm) - 'Glisser pour ajouter une personne': 'Drag to add a person', - 'Ajouter un conjoint': 'Add a partner', - 'Ajouter un frère/sœur': 'Add a sibling', - 'Relâcher pour créer': 'Release to create', 'Ajouter une personne': 'Add a person', 'Enfant': 'Child', 'Conjoint': 'Partner', 'Frère·Sœur': 'Sibling', - 'Positionnez la personne': 'Place the person', 'Parent de': 'Parent of', 'Enfant de': 'Child of', 'Conjoint·e de': 'Partner of', 'Frère·Sœur de': 'Sibling of', 'Parent': 'Parent', 'Conjoint·e': 'Partner', - 'Nouvelle fiche': 'New profile', "Ajouter quelqu'un": 'Add someone', 'Marie': 'Mary', 'Dupont': 'Smith', @@ -205,26 +198,12 @@ export default { "Chercher dans l'arbre": 'Search the tree', 'Ajout en cours': 'Adding', 'Ajouter cette personne': 'Add this person', - 'Enfant de {name}': 'Child of {name}', - 'Conjoint de {name}': 'Partner of {name}', - 'Frère·Sœur de {name}': 'Sibling of {name}', - 'Nouvel enfant': 'New child', - 'Nouveau conjoint': 'New partner', - 'Nouveau frère/sœur': 'New sibling', 'Nouvelle personne': 'New person', 'Jean': 'John', - 'Date naissance': 'Date of birth', - 'Lieu naissance': 'Birthplace', - 'Création en cours': 'Creating', 'Créer': 'Create', // Création d'un arbre (TreeCreationWizard) 'Vous': 'You', - 'Année de naissance (optionnel)': 'Year of birth (optional)', - 'Parent 1': 'Parent 1', - 'Parent 2': 'Parent 2', - 'Créer les 3 personnes': 'Create the 3 people', - 'Plus tard': 'Later', 'Étape {step} sur 2': 'Step {step} of 2', "Comment s'appelle votre famille ?": "What's your family called?", "Ce nom apparaîtra en haut de l'arbre et dans le lien que vous partagerez.": 'This name will appear at the top of the tree and in the link you share.', @@ -242,11 +221,6 @@ export default { 'Retour': 'Back', "Création de l'arbre": 'Creating the tree', 'Créer mon arbre': 'Create my tree', - 'Erreur lors de la création. Essayez un autre nom.': 'Something went wrong. Try another name.', - 'Créer votre arbre dès maintenant': 'Create your tree now', - 'Ex : Famille Martin': 'E.g. The Johnson family', - 'Adresse :': 'Address:', - "Créer l'arbre": 'Create the tree', // Recherche (search/*) 'Rechercher une personne': 'Search for a person', @@ -278,7 +252,6 @@ export default { 'Enseignante': 'Teacher', 'Mariage 1918': 'Wedding, 1918', 'Atelier de menuiserie': 'Joinery workshop', - 'Témoignage filmé 1960': 'Filmed interview, 1960', 'Jeunesse': 'Youth', 'Portrait de famille': 'Family portrait', 'Service militaire': 'Military service', @@ -286,9 +259,7 @@ export default { 'Années 70': 'The 70s', 'Diplôme': 'Graduation', 'Plan du cabinet 1985': 'Office floor plan, 1985', - 'Anniversaire 2020': 'Birthday, 2020', 'En rédaction': 'In the newsroom', - 'Interview archive radio': 'Archived radio interview', 'Inconnu': 'Unknown', // Place dans la fratrie (fiche, mode édition) 'Place {n} sur {total} parmi les frères et sœurs': 'Place {n} of {total} among siblings', @@ -300,7 +271,6 @@ export default { 'Aperçu indisponible': 'Preview unavailable', 'Un souvenir à regarder de plus près': 'A memory to take a closer look at', 'Retrouver vos souvenirs': 'Find your memories', - 'Choisissez une image pour l’agrandir, puis ajoutez-la aux souvenirs.': 'Open an image for a closer look, then add it to memories.', 'Retour aux photos': 'Back to photos', 'Aperçu de la vidéo': 'Video preview', 'Recherche dans Immich': 'Search Immich', @@ -346,7 +316,6 @@ export default { 'Terminer la sélection': 'Finish selecting', 'Depuis un fichier': 'From a file', 'Source du portrait': 'Portrait source', - 'Visage Immich': 'Immich face', 'Reconnaissance des visages': 'Face recognition', 'Immich n’est pas configuré pour cet arbre.': 'Immich is not configured for this tree.', 'Immich n’est pas configuré pour cet arbre. Ses administrateurs le règlent dans Paramètres de l’arbre.': 'Immich is not configured for this tree. Its administrators set it up in Tree settings.', @@ -451,7 +420,6 @@ export default { 'environ': 'about', 'Où ?': 'Where?', 'Ville ou adresse': 'Town or address', - 'Retirer la photo': 'Remove the photo', 'Une photo': 'A photo', 'Plus de détails': 'More details', 'Date exacte': 'Exact date', diff --git a/frontend/src/i18n/en/photos.js b/frontend/src/i18n/en/photos.js index 6d809b9..a798f82 100644 --- a/frontend/src/i18n/en/photos.js +++ b/frontend/src/i18n/en/photos.js @@ -66,14 +66,12 @@ export default { "Heredis, Geneanet, Gramps, MyHeritage ou Ancestry savent exporter un fichier .ged. Parenthèse reprend les personnes, les liens et les dates, puis vous aide à retrouver les photos.": "Heredis, Geneanet, Gramps, MyHeritage and Ancestry can all export a .ged file. Parenthèse brings in the people, links and dates, then helps you find the photos.", "Choisir le fichier .ged": "Choose the .ged file", "Cliquez pour en choisir un autre": "Click to choose another one", - "Exporté depuis le logiciel où vous tenez votre arbre": "Exported from the software where you keep your tree", "Importer mon arbre": "Import my tree", "Votre arbre est créé, mais l'import n'a pas abouti.": "Your tree is created, but the import didn't go through.", "Vous pouvez réessayer depuis les paramètres de l'arbre.": "You can try again from the tree settings.", // Import d’un zip (GEDCOM et ses photos) 'Ajoute les personnes et les liens du fichier à cet arbre. Un fichier .ged, ou un zip qui contient le .ged et ses photos.': 'Adds the people and links from the file to this tree. A .ged file, or a zip with the .ged and its photos.', 'Aucun fichier du zip ne correspond à ceux que votre logiciel citait. Choisissez le dossier où il les range.': 'No file in the zip matches the ones your software listed. Choose the folder where it keeps them.', - 'Votre zip contenait aussi les fichiers. Parenthèse a retrouvé ceux que votre logiciel citait.': 'Your zip also held the files. Parenthèse found the ones your software listed.', 'Choisir le fichier .ged ou le zip': 'Choose the .ged file or the zip', 'Exporté depuis votre logiciel. Un zip avec le .ged et ses photos fait tout en une fois.': 'Exported from your software. A zip with the .ged and its photos does it all at once.', 'Ce zip est protégé par un mot de passe. Refaites-le sans mot de passe, puis réessayez.': 'This zip is password protected. Make it again without a password, then try again.', diff --git a/frontend/src/utils/richText.jsx b/frontend/src/utils/richText.jsx new file mode 100644 index 0000000..f07fbe3 --- /dev/null +++ b/frontend/src/utils/richText.jsx @@ -0,0 +1,18 @@ +import { Fragment } from 'react' + +// Mise en forme des phrases traduites : le dictionnaire porte le texte, ces deux fonctions posent l'italique. + +// Titre traduit d'un bloc : le passage entre et garde son italique +export function withEmphasis(text) { + const [before, emphasized = '', after = ''] = text.split(/<\/?em>/) + return <>{before}{emphasized}{after} +} + +// Phrase traduite d'un bloc : les passages entre astérisques passent en , {slot} reçoit un nœud. +export function richText(text, slotNode = null) { + return text.split(/(\{slot\})/).flatMap((chunk, chunkIndex) => ( + chunk === '{slot}' + ? [{slotNode}] + : chunk.split('*').map((part, index) => (index % 2 ? {part} : part)) + )) +}