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
46 changes: 46 additions & 0 deletions scripts/i18n.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,52 @@ test('ICU select validation catches removed branches and missing other branches'
).toContain('plural selector "count" is missing "other"')
})

test('ICU select validation compares every occurrence when a selector variable repeats', () => {
const english =
'{role, select, admin {Admin} editor {Editor} other {Member}} ({role, select, guest {Guest} other {User}})'

// Dropping a branch from the first occurrence must still fail even when the second occurrence is intact.
expect(
validateTranslation(
english,
'{role, select, editor {Éditeur} other {Membre}} ({role, select, guest {Invité} other {Utilisateur}})',
'fr',
),
).toContain('select selector "role" is missing branch "admin"')

// Dropping "other" from an earlier occurrence must also fail.
expect(
validateTranslation(
english,
'{role, select, admin {Admin} editor {Éditeur}} ({role, select, guest {Invité} other {Utilisateur}})',
'fr',
),
).toContain('select selector "role" is missing "other"')

// Reordering the two select clauses in a translation remains valid when every occurrence keeps its branches.
expect(
validateTranslation(
english,
'({role, select, guest {Invité} other {Utilisateur}}) {role, select, admin {Admin} editor {Éditeur} other {Membre}}',
'fr',
),
).toEqual([])

// Removing one of the duplicate select expressions altogether must fail.
expect(
validateTranslation(
english,
'{role, select, admin {Admin} editor {Éditeur} other {Membre}}',
'fr',
),
).toContain('select selector "role" is missing or changed')

// Duplicate occurrences on an extra selector not in English still require "other" on every occurrence.
expect(
validateTranslation('Hello', '{extra, select, a {A}} {extra, select, b {B} other {O}}', 'fr'),
).toContain('select selector "extra" is missing "other"')
})

test('source drift fails checking, then extraction updates English and flags translations', () => {
const root = catalogProject()
const sample = join(root, 'packages/editor/src/sample.tsx')
Expand Down
94 changes: 81 additions & 13 deletions scripts/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,15 +283,17 @@ function plurals(tokens: CompiledToken[]): Map<string, { type: string; categorie
return found
}

function selects(tokens: CompiledToken[]): Map<string, Set<string>> {
const found = new Map<string, Set<string>>()
function selects(tokens: CompiledToken[]): Map<string, Set<string>[]> {
const found = new Map<string, Set<string>[]>()
const visit = (entries: CompiledToken[]) => {
for (const token of entries) {
if (typeof token === 'string') continue
const type = token[1]
const choices = token[2]
if (type === 'select' && choices && typeof choices === 'object') {
found.set(token[0], new Set(Object.keys(choices)))
const list = found.get(token[0]) ?? []
list.push(new Set(Object.keys(choices)))
found.set(token[0], list)
}
if (!(choices && typeof choices === 'object')) continue
for (const branch of Object.values(choices)) {
Expand All @@ -303,6 +305,43 @@ function selects(tokens: CompiledToken[]): Map<string, Set<string>> {
return found
}

function isBranchSuperset(candidate: Set<string>, required: Set<string>): boolean {
for (const branch of required) {
if (!candidate.has(branch)) return false
}
return true
}

function findMaxSelectMatches(
sourceOccurrences: Set<string>[],
translatedOccurrences: Set<string>[],
): Map<number, number> {
// Bipartite matching (source occurrence -> distinct translated occurrence that covers all its branches).
const matchedToSource = new Map<number, number>()
const augment = (srcIdx: number, visited: Set<number>): boolean => {
const req = sourceOccurrences[srcIdx]!
for (let tIdx = 0; tIdx < translatedOccurrences.length; tIdx++) {
if (visited.has(tIdx)) continue
if (!isBranchSuperset(translatedOccurrences[tIdx]!, req)) continue
visited.add(tIdx)
const prev = matchedToSource.get(tIdx)
if (prev === undefined || augment(prev, visited)) {
matchedToSource.set(tIdx, srcIdx)
return true
}
}
return false
}
for (let sIdx = 0; sIdx < sourceOccurrences.length; sIdx++) {
augment(sIdx, new Set())
}
const sourceToTranslated = new Map<number, number>()
for (const [tIdx, sIdx] of matchedToSource) {
sourceToTranslated.set(sIdx, tIdx)
}
return sourceToTranslated
}

function requiredPluralCategories(locale: string, type: string): Intl.LDMLPluralRule[] {
return new Intl.PluralRules(locale, {
type: type === 'selectordinal' ? 'ordinal' : 'cardinal',
Expand Down Expand Up @@ -393,23 +432,52 @@ export function validateTranslation(

const sourceSelects = selects(sourceTokens)
const translatedSelects = selects(translatedTokens)
for (const [name, sourceBranches] of sourceSelects) {
const translatedBranches = translatedSelects.get(name)
if (!translatedBranches) {
for (const [name, sourceOccurrences] of sourceSelects) {
const translatedOccurrences = translatedSelects.get(name)
if (!translatedOccurrences || translatedOccurrences.length === 0) {
errors.push(`select selector "${name}" is missing or changed`)
continue
}
for (const branch of sourceBranches) {
if (!translatedBranches.has(branch)) {
errors.push(`select selector "${name}" is missing branch "${branch}"`)
const matched = findMaxSelectMatches(sourceOccurrences, translatedOccurrences)
const usedTranslated = new Set(matched.values())
for (let sIdx = 0; sIdx < sourceOccurrences.length; sIdx++) {
if (matched.has(sIdx)) continue
const sourceBranches = sourceOccurrences[sIdx]!
let bestIdx = -1
let bestOverlap = -1
for (let tIdx = 0; tIdx < translatedOccurrences.length; tIdx++) {
if (usedTranslated.has(tIdx)) continue
let overlap = 0
for (const branch of sourceBranches) {
if (translatedOccurrences[tIdx]!.has(branch)) overlap++
}
if (overlap > bestOverlap) {
bestOverlap = overlap
bestIdx = tIdx
}
}
if (bestIdx === -1) {
errors.push(`select selector "${name}" is missing or changed`)
continue
}
usedTranslated.add(bestIdx)
const translatedBranches = translatedOccurrences[bestIdx]!
for (const branch of sourceBranches) {
if (!translatedBranches.has(branch)) {
errors.push(`select selector "${name}" is missing branch "${branch}"`)
}
}
}
if (!translatedBranches.has('other')) {
errors.push(`select selector "${name}" is missing "other"`)
for (const translatedBranches of translatedOccurrences) {
if (!translatedBranches.has('other')) {
errors.push(`select selector "${name}" is missing "other"`)
break
}
}
}
for (const [name, translatedBranches] of translatedSelects) {
if (!sourceSelects.has(name) && !translatedBranches.has('other')) {
for (const [name, translatedOccurrences] of translatedSelects) {
if (sourceSelects.has(name)) continue
if (translatedOccurrences.some((branches) => !branches.has('other'))) {
errors.push(`select selector "${name}" is missing "other"`)
}
}
Expand Down
Loading