Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion packages/core/src/events/bus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,13 @@ export interface CameraControlFitSceneEvent {
*/
export interface CameraControlFrameEvent {
bounds: { min: [number, number, number]; max: [number, number, number] } | null
pose?: { position: [number, number, number]; target: [number, number, number] }
pose?: {
position: [number, number, number]
target: [number, number, number]
mode?: 'perspective' | 'orthographic'
fov?: number
zoom?: number
}
}

export interface CameraPose {
Expand Down
55 changes: 55 additions & 0 deletions packages/core/src/i18n/i18n.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,61 @@ describe('message registry', () => {
).toBe('21 fallback items')
})

test('uses the fallback catalog locale plural rules when falling back from pt-PT to pt', async () => {
// In CLDR, `pt` selects "one" for 0 while `pt-PT` selects "other" for 0.
await registerMessages('pt', 'viewer', {
'test.pt-fallback-plural': '{count, plural, one {# item} other {# itens}}',
})
await registerMessages('pt', 'viewer', {
'test.pt-pt-override-plural': '{count, plural, one {# peça} other {# peças}}',
})
await registerMessages('pt-PT', 'viewer', {
'test.pt-pt-override-plural': '{count, plural, one {# artigo} other {# artigos}}',
})
setLocale('pt-PT')

// Message came from `pt`: must use `pt`'s plural rules (0 -> "one").
expect(
translate('viewer.test.pt-fallback-plural', '{count, plural, one {# item} other {# items}}', {
count: 0,
}),
).toBe('0 item')
// `pt-PT` overrides the `pt` message and keeps `pt-PT`'s plural rules (0 -> "other").
expect(
translate(
'viewer.test.pt-pt-override-plural',
'{count, plural, one {# article} other {# articles}}',
{ count: 0 },
),
).toBe('0 artigos')
})

test('the public Lingui runtime resolves fallback plurals like the scope', async () => {
await registerMessages('pt', 'viewer', {
'test.pt-public-runtime-plural': '{count, plural, one {# item} other {# itens}}',
})
const scope = createI18n({ locale: 'pt-PT' })
const id = 'viewer.test.pt-public-runtime-plural'

expect(scope._(id, { count: 0 })).toBe('0 item')
expect(scope.i18n._(id, { count: 0 })).toBe('0 item')
expect(scope.i18n.t(id, { count: 0 })).toBe('0 item')
scope.destroy()
})

test('a regional locale keeps its own number formatting for a parent-catalog message', async () => {
await registerMessages('de', 'viewer', { 'test.de-amount': 'Betrag: {amount, number}' })
const swiss = createI18n({ locale: 'de-CH' })

expect(swiss._('viewer.test.de-amount', { amount: 1234.5 })).toBe(
`Betrag: ${new Intl.NumberFormat('de-CH').format(1234.5)}`,
)
expect(new Intl.NumberFormat('de-CH').format(1234.5)).not.toBe(
new Intl.NumberFormat('de').format(1234.5),
)
swiss.destroy()
})

test('notifies subscribers for locale and active-catalog changes', async () => {
let changes = 0
let localeChanges = 0
Expand Down
76 changes: 70 additions & 6 deletions packages/core/src/i18n/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,19 @@ function mergedMessages(requestedLocale: string): Messages {
return messages
}

function hasPluralSelection(message: unknown): boolean {
if (!Array.isArray(message)) return false
return message.some(
(token) =>
Array.isArray(token) &&
(token[1] === 'plural' ||
token[1] === 'selectordinal' ||
(token[2] !== null &&
typeof token[2] === 'object' &&
Object.values(token[2] as Record<string, unknown>).some(hasPluralSelection))),
)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tagged plurals skip catalog locale rules

Medium Severity

hasPluralSelection only treats a nested array as a message of tokens, so a Lingui element/tag token whose children hold a plural is missed. A fallback-catalog message wrapped in tags then interpolates with the active locale’s plural rules instead of the catalog’s, so forms that differ by region (for example pt vs pt-PT at 0) come out wrong.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit af4715d. Configure here.


function warnMissing(key: string, requestedLocale: string): void {
if (!isDevelopment() || requestedLocale === 'en') return
const warningId = `${requestedLocale}:${key}`
Expand All @@ -105,16 +118,25 @@ function warnMissing(key: string, requestedLocale: string): void {
export class PascalI18n {
readonly i18n: LinguiI18n
private readonly englishI18n: LinguiI18n
private readonly runtimePool = new Map<string, LinguiI18n>()
private fallbackRuntimes: Array<{ locale: string; i18n: LinguiI18n }> = []
private readonly listeners = new Set<() => void>()
private readonly localeListeners = new Set<(locale: string) => void>()
private retentionCount = 0
private locale: string
private version = 0

private readonly activeTranslate: LinguiI18n['_']

constructor(initialLocale = 'en') {
this.locale = canonicalLocale(initialLocale)
this.i18n = setupI18n()
this.englishI18n = setupI18n()
// `i18n` is public, so its own `_`/`t` must resolve the same runtime as `scope._()`.
this.activeTranslate = this.i18n._.bind(this.i18n)
const translate = this._.bind(this) as LinguiI18n['_']
this.i18n._ = translate
this.i18n.t = translate
this.refresh(false)
}

Expand Down Expand Up @@ -173,18 +195,38 @@ export class PascalI18n {
scopes.delete(this)
this.listeners.clear()
this.localeListeners.clear()
this.runtimePool.clear()
this.fallbackRuntimes = []
}

_(descriptor: MessageDescriptor): string
_(id: string, values?: Values, options?: MessageOptions): string
_(idOrDescriptor: string | MessageDescriptor, values?: Values, options?: MessageOptions): string {
const id = typeof idOrDescriptor === 'string' ? idOrDescriptor : idOrDescriptor.id
const translated = this.locale === 'en' || Object.hasOwn(this.i18n.messages, id)
const runtime = translated ? this.i18n : this.englishI18n
if (!translated) warnMissing(id, this.locale)
const id = (typeof idOrDescriptor === 'string' ? idOrDescriptor : idOrDescriptor.id) ?? ''
let translate: LinguiI18n['_'] | undefined
if (this.locale === 'en') {
translate = this.englishI18n._.bind(this.englishI18n)
} else {
for (const candidate of this.fallbackRuntimes) {
const message = candidate.i18n.messages[id]
if (message === undefined || !Object.hasOwn(candidate.i18n.messages, id)) continue
// Lingui takes one locale for both plural rules and number/date formatting.
// Only a message that pluralizes needs its catalog's rules; any other keeps
// the active locale's formatting (the merged runtime holds the same message).
translate =
candidate.locale === this.locale || !hasPluralSelection(message)
? this.activeTranslate
: candidate.i18n._.bind(candidate.i18n)
break
}
}
if (!translate) {
warnMissing(id, this.locale)
translate = this.englishI18n._.bind(this.englishI18n)
}
return typeof idOrDescriptor === 'string'
? runtime._(idOrDescriptor, values, options)
: runtime._(idOrDescriptor)
? translate(idOrDescriptor, values, options)
: translate(idOrDescriptor)
}

refresh(notify = true): void {
Expand All @@ -196,6 +238,28 @@ export class PascalI18n {
locale: 'en',
messages: mergedMessages('en'),
})
const runtimes: Array<{ locale: string; i18n: LinguiI18n }> = []
if (this.locale !== 'en') {
for (const candidate of localeFallbacks(this.locale)) {
if (candidate === 'en') {
runtimes.push({ locale: 'en', i18n: this.englishI18n })
continue
}
const catalog = catalogs.get(candidate)
if (!catalog) continue
let candidateI18n = this.runtimePool.get(candidate)
if (!candidateI18n) {
candidateI18n = setupI18n()
this.runtimePool.set(candidate, candidateI18n)
}
candidateI18n.loadAndActivate({
locale: candidate,
messages: Object.assign(emptyMessages(), catalog),
})
runtimes.push({ locale: candidate, i18n: candidateI18n })
}
}
this.fallbackRuntimes = runtimes
if (!notify) return
this.version += 1
for (const listener of [...this.listeners]) listener()
Expand Down
49 changes: 49 additions & 0 deletions packages/core/src/schema/camera.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { describe, expect, test } from 'bun:test'
import { CameraSchema } from './camera'
import { SiteNode } from './nodes/site'

describe('CameraSchema', () => {
test('parses a legacy { position, target } camera without defaulting mode and round-trips cleanly', () => {
const legacy = {
position: [10, 12, 14] as [number, number, number],
target: [0, 1, 0] as [number, number, number],
}

const parsed = CameraSchema.parse(legacy)
expect(parsed.mode).toBeUndefined()
expect(parsed.fov).toBeUndefined()
expect(parsed.zoom).toBeUndefined()
expect(parsed).toEqual(legacy)

const roundTripped = CameraSchema.parse(JSON.parse(JSON.stringify(parsed)))
expect(roundTripped.mode).toBeUndefined()
expect(roundTripped).toEqual(legacy)

const site = SiteNode.parse({
id: 'site_legacy_cam',
camera: legacy,
})
expect(site.camera?.mode).toBeUndefined()
const siteRoundTripped = SiteNode.parse(JSON.parse(JSON.stringify(site)))
expect(siteRoundTripped.camera).toEqual(legacy)
expect(siteRoundTripped.camera?.mode).toBeUndefined()
})

test('preserves explicit projection mode and lens fields on round-trip', () => {
const persp = {
position: [14, 7, 18] as [number, number, number],
target: [2, 1.2, -3] as [number, number, number],
mode: 'perspective' as const,
fov: 34,
}
const ortho = {
position: [16, 12, 20] as [number, number, number],
target: [3, 1.5, -2] as [number, number, number],
mode: 'orthographic' as const,
zoom: 85,
}

expect(CameraSchema.parse(JSON.parse(JSON.stringify(CameraSchema.parse(persp))))).toEqual(persp)
expect(CameraSchema.parse(JSON.parse(JSON.stringify(CameraSchema.parse(ortho))))).toEqual(ortho)
})
})
2 changes: 1 addition & 1 deletion packages/core/src/schema/camera.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const Vector3Schema = z.tuple([z.number(), z.number(), z.number()])
export const CameraSchema = z.object({
position: Vector3Schema,
target: Vector3Schema,
mode: z.enum(['perspective', 'orthographic']).default('perspective'),
mode: z.enum(['perspective', 'orthographic']).optional(),
fov: z.number().optional(), // For perspective
zoom: z.number().optional(), // For orthographic
})
Expand Down
Loading
Loading