diff --git a/README.md b/README.md index eed923de..58dd1dbb 100644 --- a/README.md +++ b/README.md @@ -303,6 +303,38 @@ For any styles that you won't be exposing to consumers via the story, you can pr ``` +### Localization + +Wrap user-facing text in `msg()` from `@lit/localize`, inside `render()` or a getter it calls. The first argument has to be a literal: a string, `` str`...${x}` `` when it has an expression, or `` html`...` `` when it has markup. + +- Decorate any element that renders a `msg()` with `@localized()`, so it re-renders when the app switches language. That includes one rendering a getter that calls `msg()`, like `TranscriptEntryConfig.displayText`. +- Don't resolve `msg()` ahead of render. At module scope or in a static field it's fixed at import, and as a property default it's fixed when the element is created. For a text property with a default, leave the property unset and fall back when rendering: `aria-label=${this.label ?? msg('Search')}`. + +This package never calls `configureLocalization`. `@lit/localize` can only be configured once per page, so the app owns that call and loads one bundle holding its own messages and ours. We publish our translations for the app to merge in: + +```zsh +pnpm run strings:extract # add new msg() strings to xliff/.xlf +# translate the empty s in xliff/.xlf +pnpm run strings:build # write src/locales/.ts +``` + +Commit all three: the XLIFF, the generated module and the source change. + +#### What gets published + +`@internetarchive/elements/locales/.js` exports `templates`, the same shape `lit-localize build` writes in runtime mode: an object keyed by message id (a hash of the English source) whose values are what `loadLocale` returns. It only holds messages that have a translation. A message with no translation is left out instead of falling back to English, so merging it can never override another package's or the app's translation of the same text. + +To merge it, an app spreads it under its own templates, app last so the app wins a conflict: + +```ts +import { templates as elements } from '@internetarchive/elements/locales/es.js'; +import { templates as app } from './app-es'; + +export const templates = { ...elements, ...app }; +``` + +The XLIFF in `xliff/` is where translations are edited. It isn't published. + ## Component Inventory To kickstart our library, we are going to take inventory of what already exists diff --git a/eslint.config.mjs b/eslint.config.mjs index 4885590a..309b8a7b 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -62,7 +62,18 @@ export default [ }, }, { - ignores: ['**/*.js', '**/*.mjs', '**/*.d.ts', '.claude/', '.wireit/'], + ignores: [ + '**/*.js', + '**/*.mjs', + '**/*.d.ts', + '.claude/', + '.wireit/', + // Generated by `pnpm run strings:build`. Its eslint-disable comments go + // unused, so `eslint --fix` would strip them and leave the file out of + // step with what the build writes. + 'src/locales/*.ts', + '!src/locales/*.test.ts', + ], }, { files: ['**/*.test.ts'], diff --git a/lit-localize.json b/lit-localize.json new file mode 100644 index 00000000..abc39e19 --- /dev/null +++ b/lit-localize.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://raw.githubusercontent.com/lit/lit/main/packages/localize-tools/config.schema.json", + "sourceLocale": "en", + "targetLocales": ["es"], + "tsConfig": "./tsconfig.json", + "inputFiles": [ + "src/**/*.ts", + "!src/**/*.test.ts", + "!src/**/*-story.ts", + "!src/locales/**" + ], + "output": { + "outputDir": "src/locales", + "mode": "runtime" + }, + "interchange": { + "format": "xliff", + "xliffDir": "./xliff" + } +} diff --git a/package.json b/package.json index 213ae52a..b0dda2ac 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,9 @@ "circular": "wireit", "prepare": "wireit", "test": "wireit", - "ghpages:build": "wireit" + "ghpages:build": "wireit", + "strings:extract": "wireit", + "strings:build": "wireit" }, "dependencies": { "@internetarchive/ia-clearable-text-input": "^1.1.1", @@ -43,6 +45,7 @@ "devDependencies": { "@eslint/eslintrc": "^3.3.5", "@eslint/js": "^9.39.1", + "@lit/localize-tools": "^0.8.2", "@open-wc/testing-helpers": "^3.0.1", "@typescript-eslint/eslint-plugin": "^8.46.4", "@typescript-eslint/parser": "^8.46.4", @@ -70,7 +73,8 @@ }, "exports": { "./*": "./dist/src/elements/*.js", - "./labs/*": "./dist/src/labs/*.js" + "./labs/*": "./dist/src/labs/*.js", + "./locales/*.js": "./dist/src/locales/*.js" }, "files": [ "README.md", @@ -132,6 +136,24 @@ }, "ghpages:build": { "command": "vite build --config vite.config.ghpages.ts && touch ./ghpages/.nojekyll" + }, + "strings:extract": { + "command": "lit-localize extract", + "files": [ + "src/**/*.ts", + "lit-localize.json", + "tsconfig.json" + ] + }, + "strings:build": { + "command": "node scripts/build-locales.mts && prettier --write \"src/locales/*.ts\"", + "files": [ + "xliff/*.xlf", + "src/**/*.ts", + "!src/locales/*.ts", + "lit-localize.json", + "scripts/build-locales.mts" + ] } } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 32739f8b..f2e2ea35 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -194,6 +194,9 @@ importers: '@eslint/js': specifier: ^9.39.1 version: 9.39.5 + '@lit/localize-tools': + specifier: ^0.8.2 + version: 0.8.2 '@open-wc/testing-helpers': specifier: ^3.0.1 version: 3.0.1 @@ -541,6 +544,10 @@ packages: '@lit-labs/ssr-dom-shim@1.6.0': resolution: {integrity: sha512-VHb0ALPMTlgKjM6yIxxoQNnpKyUKLD04VzeQdsiXkMqkvYlAHxq9glGLmgbb889/1GsohSOAjvQYoiBppXFqrQ==} + '@lit/localize-tools@0.8.2': + resolution: {integrity: sha512-Hf7jMfamdX26FN4SBRtM7zoToCUeShzI8NQcLdHLdpPdNPlqbEYMjqRaTQPm/PsbzTl6uZwfE3/kV+NvvrJS2A==} + hasBin: true + '@lit/localize@0.12.2': resolution: {integrity: sha512-Qv9kvgJKDq/JVSwXOxuWvQnnOBysHA99ti9im9a4fImCmx+fto+XXcUYQbjZHqiueEEc4V20PcRDPO+1g/6seQ==} @@ -571,6 +578,9 @@ packages: '@open-wc/testing-helpers@3.0.1': resolution: {integrity: sha512-hyNysSatbgT2FNxHJsS3rGKcLEo6+HwDFu1UQL6jcSQUabp/tj3PyX7UnXL3H5YGv0lJArdYLSnvjLnjn3O2fw==} + '@parse5/tools@0.3.0': + resolution: {integrity: sha512-zxRyTHkqb7WQMV8kTNBKWb1BeOFUKXBXTBWuxg9H9hfvQB3IwP6Iw2U75Ia5eyRxPNltmY7E8YAlz6zWwUnjKg==} + '@polka/url@1.0.0-next.29': resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==} @@ -887,6 +897,10 @@ packages: '@vue/shared@3.5.39': resolution: {integrity: sha512-l1rrBtBfTnmxvtsvdQDXltUUy8S1Y+ZaqdfUzmAnJkTd8Z8rv5v/ytW+TKiqEOWyHPoqtPlNFSs0lhRmYVSHVA==} + '@xmldom/xmldom@0.8.15': + resolution: {integrity: sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA==} + engines: {node: '>=10.0.0'} + acorn-jsx@5.3.2: resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} peerDependencies: @@ -1008,6 +1022,9 @@ packages: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} + buffer-from@1.1.2: + resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} + buffer@5.7.1: resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} @@ -1497,6 +1514,10 @@ packages: resolution: {integrity: sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==} engines: {node: '>= 0.4'} + fs-extra@10.1.0: + resolution: {integrity: sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==} + engines: {node: '>=12'} + fsevents@2.3.2: resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -1836,6 +1857,12 @@ packages: jsonc-parser@3.3.1: resolution: {integrity: sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==} + jsonfile@6.2.1: + resolution: {integrity: sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==} + + jsonschema@1.5.0: + resolution: {integrity: sha512-K+A9hhqbn0f3pJX17Q/7H6yQfD/5OXgdrR5UE12gMXCiN9D5Xq2o5mddV2QEcX/bjla99ASsAAQUyMCCRWAEhw==} + keyv@4.5.4: resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} @@ -2321,6 +2348,9 @@ packages: resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} + source-map-support@0.5.21: + resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==} + source-map@0.6.1: resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} engines: {node: '>=0.10.0'} @@ -2489,6 +2519,10 @@ packages: undici-types@8.3.0: resolution: {integrity: sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==} + universalify@2.0.1: + resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==} + engines: {node: '>= 10.0.0'} + uri-js@4.4.1: resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} @@ -2864,6 +2898,20 @@ snapshots: '@lit-labs/ssr-dom-shim@1.6.0': {} + '@lit/localize-tools@0.8.2': + dependencies: + '@lit/localize': 0.12.2 + '@parse5/tools': 0.3.0 + '@xmldom/xmldom': 0.8.15 + fast-glob: 3.3.3 + fs-extra: 10.1.0 + jsonschema: 1.5.0 + lit: 3.3.3 + minimist: 1.2.8 + parse5: 7.3.0 + source-map-support: 0.5.21 + typescript: 5.9.3 + '@lit/localize@0.12.2': dependencies: lit: 3.3.3 @@ -2901,6 +2949,10 @@ snapshots: lit: 3.3.3 lit-html: 3.3.3 + '@parse5/tools@0.3.0': + dependencies: + parse5: 7.3.0 + '@polka/url@1.0.0-next.29': {} '@rollup/rollup-android-arm-eabi@4.62.2': @@ -3236,6 +3288,8 @@ snapshots: '@vue/shared@3.5.39': {} + '@xmldom/xmldom@0.8.15': {} + acorn-jsx@5.3.2(acorn@8.17.0): dependencies: acorn: 8.17.0 @@ -3369,6 +3423,8 @@ snapshots: dependencies: fill-range: 7.1.1 + buffer-from@1.1.2: {} + buffer@5.7.1: dependencies: base64-js: 1.5.1 @@ -4005,6 +4061,12 @@ snapshots: dependencies: is-callable: 1.2.7 + fs-extra@10.1.0: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 6.2.1 + universalify: 2.0.1 + fsevents@2.3.2: optional: true @@ -4329,6 +4391,14 @@ snapshots: jsonc-parser@3.3.1: {} + jsonfile@6.2.1: + dependencies: + universalify: 2.0.1 + optionalDependencies: + graceful-fs: 4.2.11 + + jsonschema@1.5.0: {} + keyv@4.5.4: dependencies: json-buffer: 3.0.1 @@ -4897,8 +4967,12 @@ snapshots: source-map-js@1.2.1: {} - source-map@0.6.1: - optional: true + source-map-support@0.5.21: + dependencies: + buffer-from: 1.1.2 + source-map: 0.6.1 + + source-map@0.6.1: {} stackback@0.0.2: {} @@ -5089,6 +5163,8 @@ snapshots: undici-types@8.3.0: {} + universalify@2.0.1: {} + uri-js@4.4.1: dependencies: punycode: 2.3.1 diff --git a/scripts/build-locales.mts b/scripts/build-locales.mts new file mode 100644 index 00000000..abc2d362 --- /dev/null +++ b/scripts/build-locales.mts @@ -0,0 +1,91 @@ +/** + * Builds the published locale modules, `src/locales/.ts`, from the + * XLIFF files in `xliff/`. + * + * This is `lit-localize build` in runtime mode with one change: only messages + * that have a translation are written. The app merges these modules with its + * own, and a message with no translation has to be absent rather than present + * as English, or it would override a real translation of the same text from + * somewhere else. + * + * Only the app calls `configureLocalization`. This package never does. + */ +import { readConfigFileAndWriteSchema } from '@lit/localize-tools/lib/config.js'; +import type { Message } from '@lit/localize-tools/lib/messages.js'; +import { RuntimeLitLocalizer } from '@lit/localize-tools/lib/modes/runtime.js'; +import type { RuntimeOutputConfig } from '@lit/localize-tools/lib/types/modes.js'; +import type { Config } from '@lit/localize-tools/lib/types/config.js'; +import type { Locale } from '@lit/localize-tools/lib/types/locale.js'; + +type RuntimeConfig = Config & { output: RuntimeOutputConfig }; + +/** A target that is missing or blank is not a translation. */ +function isTranslated(message: Message): boolean { + return message.contents.some( + (part) => typeof part !== 'string' || part.trim() !== '', + ); +} + +class TranslatedOnlyLocalizer extends RuntimeLitLocalizer { + private readonly locale: Locale; + + constructor(config: RuntimeConfig, locale: Locale) { + super({ ...config, targetLocales: [locale] }); + this.locale = locale; + } + + private translatedNames(): Set { + const messages = super.readTranslationsSync().translations.get(this.locale); + return new Set( + (messages ?? []).filter(isTranslated).map((message) => message.name), + ); + } + + override readTranslationsSync(): ReturnType< + RuntimeLitLocalizer['readTranslationsSync'] + > { + const { translations } = super.readTranslationsSync(); + const translated = this.translatedNames(); + const messages = (translations.get(this.locale) ?? []).filter((message) => + translated.has(message.name), + ); + return { translations: new Map([[this.locale, messages]]) }; + } + + override extractSourceMessages(): ReturnType< + RuntimeLitLocalizer['extractSourceMessages'] + > { + const { messages, errors } = super.extractSourceMessages(); + const translated = this.translatedNames(); + return { + messages: messages.filter((message) => translated.has(message.name)), + errors, + }; + } +} + +const config = readConfigFileAndWriteSchema('lit-localize.json'); +if (config.output.mode !== 'runtime') { + throw new Error('lit-localize.json output.mode has to be "runtime"'); +} + +for (const locale of config.targetLocales) { + const localizer = new TranslatedOnlyLocalizer( + config as RuntimeConfig, + locale, + ); + const { errors } = localizer.extractSourceMessages(); + if (errors.length > 0) { + throw new Error( + `${errors.length} msg() call(s) could not be analyzed, run lit-localize extract to see them`, + ); + } + const { errors: placeholderErrors } = localizer.validateTranslations(); + if (placeholderErrors.length > 0) { + throw new Error(placeholderErrors.join('\n')); + } + await localizer.build(); + const count = + localizer.readTranslationsSync().translations.get(locale)?.length ?? 0; + console.log(`${locale}: ${count} translated messages`); +} diff --git a/src/elements/ia-button/ia-button.ts b/src/elements/ia-button/ia-button.ts index ec573a37..b2714b6a 100644 --- a/src/elements/ia-button/ia-button.ts +++ b/src/elements/ia-button/ia-button.ts @@ -7,7 +7,6 @@ import { PropertyValues, render, } from 'lit'; -import { msg } from '@lit/localize'; import { property } from 'lit/decorators.js'; import { customElement } from '@src/util/custom-element'; import themeStyles from '@src/themes/theme-styles'; @@ -100,9 +99,8 @@ export class IAButton extends LitElement { private get loadingStateTemplate(): TemplateResult { return html` - ${msg( - this.loadingText, - )} + ${this + .loadingText} `; } diff --git a/src/elements/ia-combo-box/ia-combo-box.ts b/src/elements/ia-combo-box/ia-combo-box.ts index ddc7d867..bcd7ad15 100644 --- a/src/elements/ia-combo-box/ia-combo-box.ts +++ b/src/elements/ia-combo-box/ia-combo-box.ts @@ -13,7 +13,7 @@ import { classMap } from 'lit/directives/class-map.js'; import { ifDefined } from 'lit/directives/if-defined.js'; import { live } from 'lit/directives/live.js'; import { when } from 'lit/directives/when.js'; -import { msg } from '@lit/localize'; +import { localized, msg } from '@lit/localize'; import { hasAnyOf, @@ -55,6 +55,7 @@ const STRING_LOWER_CASE_FN = (str: string): string => str.toLocaleLowerCase(); * freeform text to filter down & find specific options. */ @customElement('ia-combo-box') +@localized() export class IAComboBox extends LitElement { /** * Array of options representing values that this combo box can take. diff --git a/src/elements/ia-dropdown-search-bar/ia-dropdown-search-bar.ts b/src/elements/ia-dropdown-search-bar/ia-dropdown-search-bar.ts index d18a709d..3ed75693 100644 --- a/src/elements/ia-dropdown-search-bar/ia-dropdown-search-bar.ts +++ b/src/elements/ia-dropdown-search-bar/ia-dropdown-search-bar.ts @@ -1,4 +1,4 @@ -import { msg } from '@lit/localize'; +import { localized, msg } from '@lit/localize'; import { css, html, @@ -29,6 +29,7 @@ const Events = { }; @customElement('ia-dropdown-search-bar') +@localized() export class IADropdownSearchBar extends LitElement { /** The query that appears in the search bar */ @property({ type: String }) query?: string; @@ -39,8 +40,8 @@ export class IADropdownSearchBar extends LitElement { /** The currently selected dropdown category ID */ @property({ type: String }) selectedCategory?: string; - /** Placeholder text for the search input */ - @property({ type: String }) placeholder = msg('Search'); + /** Placeholder text for the search input. Defaults to "Search". */ + @property({ type: String }) placeholder?: string; /** Whether to use the mobile layout */ @property({ type: Boolean }) useMobileView = false; @@ -126,7 +127,7 @@ export class IADropdownSearchBar extends LitElement { id="search-input" part="search-input" .value=${this.spacedQuery} - placeholder=${this.placeholder} + placeholder=${this.placeholder ?? msg('Search')} clearButtonScreenReaderLabel=${msg('Clear search query')} screenReaderLabel=${msg( 'Search the Archive. Filters and Advanced Search available below.', diff --git a/src/elements/ia-expandable-search-bar/ia-expandable-search-bar.ts b/src/elements/ia-expandable-search-bar/ia-expandable-search-bar.ts index e4f30ea6..94289b52 100644 --- a/src/elements/ia-expandable-search-bar/ia-expandable-search-bar.ts +++ b/src/elements/ia-expandable-search-bar/ia-expandable-search-bar.ts @@ -8,7 +8,7 @@ import { } from 'lit'; import { property, query } from 'lit/decorators.js'; import { customElement } from '@src/util/custom-element'; -import { msg } from '@lit/localize'; +import { localized, msg } from '@lit/localize'; import type { QuickSearchEntry } from './models'; @@ -32,6 +32,7 @@ const Events = { * A search bar with a quick search list that expands underneath it. */ @customElement('ia-expandable-search-bar') +@localized() export class IAExpandableSearchBar extends LitElement { /** Whether the quick search list is showing */ @property({ type: Boolean }) isOpen = false; @@ -45,11 +46,11 @@ export class IAExpandableSearchBar extends LitElement { /** The suggestions to offer in the quick search list */ @property({ type: Array }) quickSearches: QuickSearchEntry[] = []; - /** Placeholder text for the input */ - @property({ type: String }) placeholder = msg('Search'); + /** Placeholder text for the input. Defaults to "Search". */ + @property({ type: String }) placeholder?: string; - /** The accessible name for the input */ - @property({ type: String }) label = msg('Search'); + /** The accessible name for the input. Defaults to "Search". */ + @property({ type: String }) label?: string; @query('#search-input') private searchInput?: HTMLInputElement | null; @@ -66,8 +67,8 @@ export class IAExpandableSearchBar extends LitElement { ; * stops the default of opening the image in a new tab. */ @customElement('ia-image-viewer') +@localized() export class IAImageViewer extends LitElement { @property({ type: Array }) images: ImageViewerImage[] = []; diff --git a/src/elements/ia-image-viewer/ia-imgview-controls.ts b/src/elements/ia-image-viewer/ia-imgview-controls.ts index f51cdce7..bf6db35c 100644 --- a/src/elements/ia-image-viewer/ia-imgview-controls.ts +++ b/src/elements/ia-image-viewer/ia-imgview-controls.ts @@ -7,7 +7,7 @@ import { } from 'lit'; import { property } from 'lit/decorators.js'; import { customElement } from '@src/util/custom-element'; -import { msg } from '@lit/localize'; +import { localized, msg } from '@lit/localize'; import themeStyles from '@src/themes/theme-styles'; @@ -30,6 +30,7 @@ import themeStyles from '@src/themes/theme-styles'; * anything to shrink-wrap. */ @customElement('ia-imgview-controls') +@localized() export class IAImageViewerControls extends LitElement { /** Zero-based index of the image being shown, for the counter. */ @property({ type: Number }) currentIndex = 0; diff --git a/src/elements/ia-image-viewer/ia-imgview-slide.ts b/src/elements/ia-image-viewer/ia-imgview-slide.ts index f817c50d..42cb83aa 100644 --- a/src/elements/ia-image-viewer/ia-imgview-slide.ts +++ b/src/elements/ia-image-viewer/ia-imgview-slide.ts @@ -10,7 +10,7 @@ import { import { property, query, state } from 'lit/decorators.js'; import { customElement } from '@src/util/custom-element'; import { classMap } from 'lit/directives/class-map.js'; -import { msg } from '@lit/localize'; +import { localized, msg } from '@lit/localize'; import themeStyles from '@src/themes/theme-styles'; import type { ImageViewerImage } from './models'; @@ -24,6 +24,7 @@ import type { ImageViewerImage } from './models'; * per-instance setup beyond its properties. */ @customElement('ia-imgview-slide') +@localized() export class IAImageViewerSlide extends LitElement { @property({ type: Object }) image?: ImageViewerImage; diff --git a/src/elements/ia-otp-form/ia-otp-form.ts b/src/elements/ia-otp-form/ia-otp-form.ts index 4c955b9b..0073c7b5 100644 --- a/src/elements/ia-otp-form/ia-otp-form.ts +++ b/src/elements/ia-otp-form/ia-otp-form.ts @@ -7,7 +7,7 @@ import { nothing, PropertyValues, } from 'lit'; -import { msg } from '@lit/localize'; +import { localized, msg } from '@lit/localize'; import { property, query } from 'lit/decorators.js'; import { customElement } from '@src/util/custom-element'; @@ -32,6 +32,7 @@ const Events = { * Form for entering OTP codes, including success/loading/error states and a request new code button */ @customElement('ia-otp-form') +@localized() export class IAOTPForm extends LitElement { /* The state of the validation process */ @property({ type: String }) diff --git a/src/elements/ia-playback-controls/ia-playback-controls.ts b/src/elements/ia-playback-controls/ia-playback-controls.ts index cbf64a24..c25d1bc5 100644 --- a/src/elements/ia-playback-controls/ia-playback-controls.ts +++ b/src/elements/ia-playback-controls/ia-playback-controls.ts @@ -7,7 +7,7 @@ import { } from 'lit'; import { property } from 'lit/decorators.js'; import { customElement } from '@src/util/custom-element'; -import { msg, str } from '@lit/localize'; +import { localized, msg, str } from '@lit/localize'; import { PlaybackMode } from './models'; @@ -53,6 +53,7 @@ const VOLUME_STEP = 0.25; * playing the audio decide what to do with them. */ @customElement('ia-playback-controls') +@localized() export class IAPlaybackControls extends LitElement { /** Whether the track is playing or paused */ @property({ type: String }) playbackMode: PlaybackMode = PlaybackMode.paused; diff --git a/src/elements/ia-radio-player/ia-radio-player.ts b/src/elements/ia-radio-player/ia-radio-player.ts index 925faea1..827c464e 100644 --- a/src/elements/ia-radio-player/ia-radio-player.ts +++ b/src/elements/ia-radio-player/ia-radio-player.ts @@ -9,7 +9,7 @@ import { } from 'lit'; import { property, query, state } from 'lit/decorators.js'; import { customElement } from '@src/util/custom-element'; -import { msg, str } from '@lit/localize'; +import { localized, msg, str } from '@lit/localize'; import type { AudioSource } from '@src/elements/ia-audio-element/models'; import type { QuickSearchEntry } from '@src/elements/ia-expandable-search-bar/models'; @@ -78,6 +78,7 @@ const SECTION_SEEK_NUDGE = 0.1; * and hands searching off to whatever `searchHandler` it is given. */ @customElement('ia-radio-player') +@localized() export class IARadioPlayer extends LitElement { /** What is being played, and what to show about it */ @property({ type: Object }) config?: RadioPlayerConfig; diff --git a/src/elements/ia-radio-player/ia-search-results-switcher.ts b/src/elements/ia-radio-player/ia-search-results-switcher.ts index e91130a7..8ab74d03 100644 --- a/src/elements/ia-radio-player/ia-search-results-switcher.ts +++ b/src/elements/ia-radio-player/ia-search-results-switcher.ts @@ -8,7 +8,7 @@ import { } from 'lit'; import { property } from 'lit/decorators.js'; import { customElement } from '@src/util/custom-element'; -import { msg, str } from '@lit/localize'; +import { localized, msg, str } from '@lit/localize'; import nextResultIcon from './assets/next-result'; import previousResultIcon from './assets/previous-result'; @@ -26,6 +26,7 @@ const Events = { * Both ends wrap around, so there is always somewhere to go. */ @customElement('ia-search-results-switcher') +@localized() export class IASearchResultsSwitcher extends LitElement { /** How many results there are to step through */ @property({ type: Number }) numberOfResults = 0; diff --git a/src/elements/ia-scrubber-bar/ia-scrubber-bar.ts b/src/elements/ia-scrubber-bar/ia-scrubber-bar.ts index 7e2bca79..870e2ca4 100644 --- a/src/elements/ia-scrubber-bar/ia-scrubber-bar.ts +++ b/src/elements/ia-scrubber-bar/ia-scrubber-bar.ts @@ -8,7 +8,7 @@ import { } from 'lit'; import { property, state } from 'lit/decorators.js'; import { customElement } from '@src/util/custom-element'; -import { msg } from '@lit/localize'; +import { localized, msg } from '@lit/localize'; import { SectionMarkerMode } from './models'; @@ -56,6 +56,7 @@ interface SurroundingMarkers { * laid over the track. */ @customElement('ia-scrubber-bar') +@localized() export class IAScrubberBar extends LitElement { /** The current position along the track */ @property({ type: Number }) value = 0; @@ -75,8 +76,8 @@ export class IAScrubberBar extends LitElement { /** Whether the markers either side of the playhead point towards it */ @property({ type: Boolean }) expandSectionMarkers = false; - /** The accessible name for the slider */ - @property({ type: String }) label = msg('Playback position'); + /** The accessible name for the slider. Defaults to "Playback position". */ + @property({ type: String }) label?: string; /** * The position actually shown. @@ -119,7 +120,7 @@ export class IAScrubberBar extends LitElement { = { * 4. three animated dots (the default) */ @customElement('ia-status-indicator') +@localized() export class IAStatusIndicator extends LitElement { - /* An optional title to use for the loading state of the indicator. Will be used for screen readers. */ - @property({ type: String }) loadingTitle = msg('Loading...'); + /* An optional title to use for the loading state of the indicator. Will be used for screen readers. Defaults to "Loading...". */ + @property({ type: String }) loadingTitle?: string; - /* An optional title to use for the success state of the indicator. Will be used for screen readers. */ - @property({ type: String }) successTitle = msg('Success'); + /* An optional title to use for the success state of the indicator. Will be used for screen readers. Defaults to "Success". */ + @property({ type: String }) successTitle?: string; - /* An optional title to use for the error state of the indicator. Will be used for screen readers. */ - @property({ type: String }) errorTitle = msg('Error'); + /* An optional title to use for the error state of the indicator. Will be used for screen readers. Defaults to "Error". */ + @property({ type: String }) errorTitle?: string; /* The state of the indicator that should be shown */ @property({ type: String }) mode: LoadingStatus = 'loading'; @@ -260,7 +261,7 @@ export class IAStatusIndicator extends LitElement { xmlns:xlink="http://www.w3.org/1999/xlink" role="status" > - ${this.loadingTitle} + ${this.loadingTitle ?? msg('Loading...')} - ${this.loadingTitle} + ${this.loadingTitle ?? msg('Loading...')} - ${this.successTitle} + ${this.successTitle ?? msg('Success')} - ${this.errorTitle} + ${this.errorTitle ?? msg('Error')} import('./es'), +}); + +/** Units in the XLIFF with a non-blank target. */ +const translatedIds = [ + ...xliff.matchAll(/]*>([\s\S]*?)<\/trans-unit>/g), +] + .filter(([, , unit]) => { + const target = /([\s\S]*?)<\/target>/.exec(unit); + return target !== null && target[1].trim() !== ''; + }) + .map(([, id]) => id); + +function labelOf(el: IAPlaybackControls, id: string): string | null { + return el.shadowRoot?.getElementById(id)?.getAttribute('aria-label') ?? null; +} + +function titleOf(el: IAStatusIndicator): string | null { + return el.shadowRoot?.querySelector('title')?.textContent ?? null; +} + +describe('published es locale', () => { + afterEach(async () => { + await setLocale('en'); + }); + + test('has exactly the translated units in the XLIFF', () => { + // An untranslated message has to be missing, not English. The app merges + // this module with others, and an English entry would override a real + // translation of the same text. + expect(Object.keys(templates).sort()).toEqual([...translatedIds].sort()); + }); + + test('renders an element in Spanish once the app sets the locale', async () => { + await setLocale('es'); + const el = await fixture( + html``, + ); + + expect(labelOf(el, 'back-btn')).toBe('Retroceder diez segundos'); + expect(labelOf(el, 'volume-control-btn')).toBe( + 'Volumen, actualmente al 50 por ciento', + ); + }); + + test('switches an element already on the page', async () => { + const controls = await fixture( + html``, + ); + // The default title is resolved when it renders, not when the element is + // created, so it follows the locale too. + const indicator = await fixture( + html``, + ); + // Its text comes from a model getter, so the entry has to re-render itself. + const music = await fixture( + html``, + ); + expect(labelOf(controls, 'back-btn')).toBe('Skip back ten seconds'); + expect(titleOf(indicator)).toBe('Loading...'); + expect(music.shadowRoot?.textContent).toBe('[Transcript unavailable]'); + + await setLocale('es'); + await controls.updateComplete; + await indicator.updateComplete; + await music.updateComplete; + + expect(labelOf(controls, 'back-btn')).toBe('Retroceder diez segundos'); + expect(titleOf(indicator)).toBe('Cargando...'); + expect(music.shadowRoot?.textContent).toBe('[Transcripción no disponible]'); + }); +}); diff --git a/xliff/es.xlf b/xliff/es.xlf new file mode 100644 index 00000000..b96ccc45 --- /dev/null +++ b/xliff/es.xlf @@ -0,0 +1,155 @@ + + + + + + Clear +Borrar + + + Toggle options +Mostrar u ocultar opciones + + + No matching options +No hay opciones que coincidan + + + A value is required +Este campo es obligatorio + + + Search +Buscar + + + Clear search query +Borrar la búsqueda + + + Search the Archive. Filters and Advanced Search available below. +Busca en Internet Archive. Filtros y búsqueda avanzada disponibles a continuación. + + + Clear search +Borrar la búsqueda + + + Toggle quick search +Mostrar u ocultar la búsqueda rápida + + + Image of +Imagen de + + + Previous image +Imagen anterior + + + Next image +Imagen siguiente + + + This image could not be loaded. +No se pudo cargar esta imagen. + + + The code entered is invalid or expired +El código introducido no es válido o ha caducado + + + Emailing... +Enviando el correo... + + + Email me another code +Envíame otro código + + + Previous section +Sección anterior + + + Skip back ten seconds +Retroceder diez segundos + + + Pause +Pausar + + + Play +Reproducir + + + Skip ahead ten seconds +Avanzar diez segundos + + + Next section +Sección siguiente + + + Playback speed, currently +Velocidad de reproducción, actualmente + + + Volume, currently percent +Volumen, actualmente al por ciento + + + Collection logo +Logotipo de la colección + + + Searching the transcript +Buscando en la transcripción + + + No search results. +No hay resultados. + + + search results + resultados de búsqueda + + + Previous search result +Resultado anterior + + + Next search result +Resultado siguiente + + + Search result of +Resultado de + + + Playback position +Posición de reproducción + + + Loading... +Cargando... + + + Success +Correcto + + + Error +Error + + + Scroll text with audio +Desplazar el texto con el audio + + + [Transcript unavailable] +[Transcripción no disponible] + + + +