From 73b7900572b5ae2a45ce587f3656aaf4b1f78e29 Mon Sep 17 00:00:00 2001 From: Jason Buckner Date: Wed, 30 Sep 2026 15:03:58 -0700 Subject: [PATCH 01/11] WEBDEV-9226: Set up string extraction and publish locale data Elements had msg() calls but no lit-localize.json or localize-tools, so none of them could be extracted and offshoot rendered them in English. This adds extraction to xliff/es.xlf, translates all 37 strings, and publishes them as @internetarchive/elements/locales/es.js for offshoot to merge into its bundle. The published module is lit-localize's runtime-mode templates with one change: scripts/build-locales.mts only writes messages that have a translation. An English fallback would override a real translation of the same text once the app merges it. The package never calls configureLocalization. ia-button dropped msg(this.loadingText). Extraction needs a literal, and every caller already passes a localized string. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HjwDQaR3hvZ8J2PP4117W2 --- README.md | 29 ++++++ eslint.config.mjs | 13 ++- lit-localize.json | 20 ++++ package.json | 26 ++++- pnpm-lock.yaml | 80 +++++++++++++- scripts/build-locales.mts | 91 ++++++++++++++++ src/elements/ia-button/ia-button.ts | 6 +- src/locales/es.ts | 47 +++++++++ src/locales/locales.test.ts | 52 ++++++++++ xliff/es.xlf | 155 ++++++++++++++++++++++++++++ 10 files changed, 510 insertions(+), 9 deletions(-) create mode 100644 lit-localize.json create mode 100644 scripts/build-locales.mts create mode 100644 src/locales/es.ts create mode 100644 src/locales/locales.test.ts create mode 100644 xliff/es.xlf diff --git a/README.md b/README.md index cd214aa0..7400be60 100644 --- a/README.md +++ b/README.md @@ -303,6 +303,35 @@ 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. A `msg()` that runs at module scope or in a static field resolves once at import, so it never changes language. + +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 137135dc..7960e266 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,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", @@ -44,6 +46,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", @@ -72,7 +75,8 @@ "exports": { ".": "./dist/src/index.js", "./*": "./dist/src/elements/*.js", - "./labs/*": "./dist/src/labs/*.js" + "./labs/*": "./dist/src/labs/*.js", + "./locales/*.js": "./dist/src/locales/*.js" }, "files": [ "README.md", @@ -134,6 +138,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/locales/es.ts b/src/locales/es.ts new file mode 100644 index 00000000..9eca0436 --- /dev/null +++ b/src/locales/es.ts @@ -0,0 +1,47 @@ +// Do not modify this file by hand! +// Re-generate this file by running lit-localize + +import { str } from '@lit/localize'; + +/* eslint-disable no-irregular-whitespace */ +/* eslint-disable @typescript-eslint/no-explicit-any */ + +export const templates = { + s061cc20e3432dead: `Pausar`, + s0661ae8e65d136c7: str`Imagen ${0} de ${1}`, + s13c406cbcde6b73f: `El código que has introducido no es válido o ha caducado`, + s1587aa01e9bb42c6: `Mostrar u ocultar la búsqueda rápida`, + s1c9c386a1a79feef: str`Resultado ${0} de ${1}`, + s290adadea9c2979c: `No se pudo cargar esta imagen.`, + s370e44cc8c6c311b: `Mostrar u ocultar opciones`, + s49730f3d5751a433: `Cargando...`, + s4c25f08d080da5fa: `No hay resultados.`, + s4e3bb79d82e09ea4: str`Volumen, actualmente al ${0} por ciento`, + s5d929ff1619ac0c9: `Buscar`, + s5f343a43e7ea9f91: `Error`, + s5f4586bc1e2740e6: `Borrar la búsqueda`, + s6aa79ab2e0656795: str`Velocidad de reproducción, actualmente ${0}`, + s7505401da0a6d6f7: `No hay opciones que coincidan`, + s7655667379814b36: `Busca en el archivo. Filtros y búsqueda avanzada disponible a continuación.`, + s78fa9c8370847255: `Resultado siguiente`, + s7ad0c46f2280e6b7: `Retroceder diez segundos`, + s7cc651d6e80f42f9: `Envíame otro código`, + s82fc0d7c4b5d5189: str`${0} resultados de búsqueda`, + s872b27cf7155f325: `Avanzar diez segundos`, + s8744f82be5bc754f: `Sección siguiente`, + s92a0d19a28995530: `Correcto`, + sa034673b5a3c355c: `Este campo es obligatorio`, + sa135b299b78d517d: `[Transcripción no disponible]`, + sac330cdfd2a92c75: `Resultado anterior`, + sb2d5fa10375dab13: `Desplazar el texto con el audio`, + sb4f1dffbb6be6302: `Borrar`, + sb9b90dd7e5256784: `Logotipo de la colección`, + sbfbc77dc3543556f: `Sección anterior`, + sc13705f8a93d185e: `Buscando en la transcripción`, + scd105819b5a10243: `Reproducir`, + sd4089915c0f14c1e: `Borrar la búsqueda`, + se645d473fbdc4705: `Imagen siguiente`, + se9d11cd23b249157: `Posición de reproducción`, + sfcae9f83f7f25e25: `Imagen anterior`, + sfe786d22e4310635: `Enviando el correo...`, +}; diff --git a/src/locales/locales.test.ts b/src/locales/locales.test.ts new file mode 100644 index 00000000..afd9efd2 --- /dev/null +++ b/src/locales/locales.test.ts @@ -0,0 +1,52 @@ +import { fixture } from '@open-wc/testing-helpers'; +import { configureLocalization } from '@lit/localize'; +import { html } from 'lit'; +import { describe, expect, test } from 'vitest'; + +import xliff from '../../xliff/es.xlf?raw'; +import { templates } from './es'; +import type { IAPlaybackControls } from '@src/elements/ia-playback-controls/ia-playback-controls'; +import '@src/elements/ia-playback-controls/ia-playback-controls'; + +// This package never configures localization. The app that uses it does, once, +// and this file stands in for that app. +const { setLocale } = configureLocalization({ + sourceLocale: 'en', + targetLocales: ['es'], + loadLocale: () => 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; +} + +describe('published es locale', () => { + 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', + ); + }); +}); diff --git a/xliff/es.xlf b/xliff/es.xlf new file mode 100644 index 00000000..b0be7534 --- /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 el archivo. Filtros y búsqueda avanzada disponible 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 que has 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] + + + + From cbc29275de44f23a3df5095df250bd57618dddcb Mon Sep 17 00:00:00 2001 From: Jason Buckner Date: Wed, 30 Sep 2026 15:04:26 -0700 Subject: [PATCH 02/11] 1.1.3-webdev-9226.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 7960e266..c36026e0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@internetarchive/elements", - "version": "1.1.2", + "version": "1.1.3-webdev-9226.0", "description": "A web component library from the Internet Archive.", "license": "AGPL-3.0-only", "types": "./dist/src/elements/index.d.ts", From 984d521de7184366a748ba41fb6287871a2d4376 Mon Sep 17 00:00:00 2001 From: Jason Buckner Date: Wed, 30 Sep 2026 15:24:12 -0700 Subject: [PATCH 03/11] WEBDEV-9226: Make the published Spanish reach the UI Having the translations isn't enough. Seven text properties took their default from msg() when the element was created, so an element built before the app loaded Spanish kept the English default. And no element re-rendered when the language changed, so a live switch only showed after a reload. The seven defaults (ia-scrubber-bar label, the two search bars' placeholder and label, ia-status-indicator's three titles) are now left unset and fall back to msg() at render. Every element that renders a msg() gets @localized(), including ia-transcript-entry, whose text comes from a msg() in TranscriptEntryConfig.displayText. Diff review caught that one. The locale test now switches elements that are already on the page, and fails against either the old defaults or a missing @localized(). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HjwDQaR3hvZ8J2PP4117W2 --- README.md | 5 ++- src/elements/ia-combo-box/ia-combo-box.ts | 3 +- .../ia-dropdown-search-bar.ts | 9 ++-- .../ia-expandable-search-bar.ts | 15 ++++--- .../ia-image-viewer/ia-image-viewer.ts | 3 +- .../ia-image-viewer/ia-imgview-controls.ts | 3 +- .../ia-image-viewer/ia-imgview-slide.ts | 3 +- src/elements/ia-otp-form/ia-otp-form.ts | 3 +- .../ia-playback-controls.ts | 3 +- .../ia-radio-player/ia-radio-player.ts | 3 +- .../ia-search-results-switcher.ts | 3 +- .../ia-scrubber-bar/ia-scrubber-bar.ts | 9 ++-- .../ia-status-indicator.ts | 23 +++++----- .../ia-transcript-view/ia-transcript-entry.ts | 3 ++ .../ia-transcript-view/ia-transcript-view.ts | 3 +- src/locales/locales.test.ts | 44 ++++++++++++++++++- 16 files changed, 98 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 7400be60..22b1b869 100644 --- a/README.md +++ b/README.md @@ -305,7 +305,10 @@ 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. A `msg()` that runs at module scope or in a static field resolves once at import, so it never changes language. +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: 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'; @@ -157,7 +158,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')} { + 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 @@ -49,4 +62,33 @@ describe('published es locale', () => { '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]'); + }); }); From 3ac331bf24407ea8c2c7a543894d316b25a88fe5 Mon Sep 17 00:00:00 2001 From: Jason Buckner Date: Wed, 30 Sep 2026 15:24:12 -0700 Subject: [PATCH 04/11] 1.1.3-webdev-9226.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index c36026e0..b69f9c15 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@internetarchive/elements", - "version": "1.1.3-webdev-9226.0", + "version": "1.1.3-webdev-9226.1", "description": "A web component library from the Internet Archive.", "license": "AGPL-3.0-only", "types": "./dist/src/elements/index.d.ts", From e064a4a1e8437f09794c16387102bceb818f5117 Mon Sep 17 00:00:00 2001 From: Jason Buckner Date: Thu, 1 Oct 2026 16:01:02 -0700 Subject: [PATCH 05/11] WEBDEV-9249: Add a language switch to the elements demo Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013cDnU6cdXPyqhk2vxquGpk --- demo/app-root.test.ts | 59 +++++++++++++++++++++++++++++++++++++++ demo/app-root.ts | 55 +++++++++++++++++++++++++++++++++++- demo/demo-localization.ts | 38 +++++++++++++++++++++++++ demo/index.css | 40 ++++++++++++++++++++++++++ eslint.config.mjs | 35 +++++++++++++++++++++++ 5 files changed, 226 insertions(+), 1 deletion(-) create mode 100644 demo/demo-localization.ts diff --git a/demo/app-root.test.ts b/demo/app-root.test.ts index 180c3aad..c9891782 100644 --- a/demo/app-root.test.ts +++ b/demo/app-root.test.ts @@ -4,6 +4,8 @@ import { html } from 'lit'; import type { AppRoot } from './app-root'; import './app-root'; +import { setLocale, writeLocaleToUrl } from './demo-localization'; +import type { IAPlaybackControls } from '@src/elements/ia-playback-controls/ia-playback-controls'; /** * Sets the hash without firing hashchange, so a fixture created afterwards @@ -251,4 +253,61 @@ describe('AppRoot', () => { expect(hrefs).to.include('#elem-ia-button'); }); }); + + describe('locale switch', () => { + afterEach(async () => { + // The configured locale and the URL param both outlive the fixture, so + // a test that switches to Spanish would otherwise leak into whatever + // runs next in this file. + await setLocale('en'); + writeLocaleToUrl('en'); + }); + + function backButtonLabel(el: AppRoot): string | null | undefined { + const controls = el + .querySelector('ia-playback-controls-story') + ?.shadowRoot?.querySelector('ia-playback-controls'); + return controls?.shadowRoot + ?.getElementById('back-btn') + ?.getAttribute('aria-label'); + } + + test('the EN/ES control switches a loaded element to Spanish live', async () => { + setHash('#elem-ia-playback-controls'); + const el = await appRoot(); + + await waitUntil( + () => el.querySelector('ia-playback-controls-story'), + ' was never rendered', + ); + await waitUntil( + () => backButtonLabel(el) != null, + 'the playback controls never rendered their back button', + ); + expect(backButtonLabel(el)).to.equal('Skip back ten seconds'); + + const esButton = el.querySelector('#ia-locale-es') as HTMLButtonElement; + esButton.click(); + + await waitUntil( + () => backButtonLabel(el) === 'Retroceder diez segundos', + 'the playback controls never switched to Spanish', + ); + expect(esButton.getAttribute('aria-pressed')).to.equal('true'); + }); + + test('a ?lang=es deep link starts the demo in Spanish', async () => { + window.history.replaceState( + null, + '', + '?lang=es#elem-ia-playback-controls', + ); + const el = await appRoot(); + + await waitUntil( + () => backButtonLabel(el) === 'Retroceder diez segundos', + 'the deep link never put the playback controls in Spanish', + ); + }); + }); }); diff --git a/demo/app-root.ts b/demo/app-root.ts index 85738eb6..d68a624b 100644 --- a/demo/app-root.ts +++ b/demo/app-root.ts @@ -6,6 +6,12 @@ import { customElement } from '@src/util/custom-element'; import { unsafeHTML } from 'lit/directives/unsafe-html.js'; import { HASH_PREFIX, tagFromHash } from './element-hash'; +import { + getLocale, + localeFromUrl, + setLocale, + writeLocaleToUrl, +} from './demo-localization'; // Globbed without `eager`, so the keys give us the full element list at build // time while each module is only fetched when its story is displayed. @@ -70,6 +76,9 @@ export class AppRoot extends LitElement { /** Sidebar highlight in the all-elements view, driven by scroll position. */ @state() private _activeTag?: string; + /** The demo's own locale, so the EN/ES control can show which is active. */ + @state() private _locale = getLocale(); + // Plain map rather than reactive state: Lit doesn't observe mutation, so // _loadStory requests its own update once a module settles. private _loadStates = new Map(); @@ -87,6 +96,10 @@ export class AppRoot extends LitElement { window.addEventListener('hashchange', this._onHashChange, { signal: this._abortController.signal, }); + // A `?lang=es` deep link gives a reviewer a one-click way to see elements + // in Spanish, so it wins over whatever locale the page started in. + const urlLocale = localeFromUrl(); + if (urlLocale !== this._locale) this._setLocale(urlLocale); // updated() owns the scroll spy, and disconnecting tore it down. An // unchanged hash resolves to the same StoryEntry object, so the assignment // above requests no update on its own, which would leave the spy dead. @@ -99,6 +112,15 @@ export class AppRoot extends LitElement { this._abortController?.abort(); } + /** Switches the demo's language, reflecting it in the URL and the page. */ + private _setLocale = async (locale: 'en' | 'es') => { + if (locale === this._locale) return; + await setLocale(locale); + this._locale = locale; + document.documentElement.lang = locale; + writeLocaleToUrl(locale); + }; + private _onHashChange = () => { const focused = entryFromHash(window.location.hash); if (focused === this._focused) return; @@ -172,7 +194,10 @@ export class AppRoot extends LitElement { return html` ${this._renderSidebar()}
-

Internet Archive Elements

+
+

Internet Archive Elements

+ ${this._renderLocaleSwitch()} +
${this._focused ? this._renderFocused(this._focused) : this._renderAll()} @@ -180,6 +205,34 @@ export class AppRoot extends LitElement { `; } + /** + * Demo-only EN/ES toggle so a reviewer can see elements in Spanish from a + * PR preview, without digging through dev tools. It's the one place in + * this repo that owns a locale switch; everything under src/ just renders + * whatever locale this picks. + */ + private _renderLocaleSwitch(): TemplateResult { + const localeButton = (locale: 'en' | 'es', label: string) => html` + + `; + + return html` +
+ ${localeButton('en', 'EN')} ${localeButton('es', 'ES')} +
+ `; + } + private _renderSidebar() { const showingAll = !this._focused; const activeTag = this._focused ? this._focused.tag : this._activeTag; diff --git a/demo/demo-localization.ts b/demo/demo-localization.ts new file mode 100644 index 00000000..a5dad12d --- /dev/null +++ b/demo/demo-localization.ts @@ -0,0 +1,38 @@ +import { configureLocalization } from '@lit/localize'; + +/** The URL query param a deep link uses to request a starting locale. */ +export const LANG_PARAM = 'lang'; + +/** + * The demo app is the one place in this repo allowed to call + * configureLocalization: @lit/localize throws if it's configured twice, and + * every element's own msg() calls expect a single app-level owner. The + * package's source never calls it; only this demo does, so a reviewer can + * view elements in Spanish from a PR preview. + */ +export const { getLocale, setLocale } = configureLocalization({ + sourceLocale: 'en', + targetLocales: ['es'], + // The demo is this package's own test bed, so it loads the built Spanish + // module straight from source rather than through a published dependency. + loadLocale: () => import('@src/locales/es'), +}); + +/** Reads the locale a deep link's `?lang=` param asks for. */ +export function localeFromUrl(): 'en' | 'es' { + const requested = new URLSearchParams(window.location.search).get(LANG_PARAM); + return requested === 'es' ? 'es' : 'en'; +} + +/** + * Writes the given locale into the URL's `lang` param, replacing history + * rather than pushing so switching languages doesn't add back-button stops. + * The source locale is the default, so it's left as an absent param rather + * than written out as `lang=en`. + */ +export function writeLocaleToUrl(locale: 'en' | 'es'): void { + const url = new URL(window.location.href); + if (locale === 'en') url.searchParams.delete(LANG_PARAM); + else url.searchParams.set(LANG_PARAM, locale); + window.history.replaceState(null, '', url); +} diff --git a/demo/index.css b/demo/index.css index f44c65bc..4488280e 100644 --- a/demo/index.css +++ b/demo/index.css @@ -148,6 +148,14 @@ app-root { margin-bottom: 0.5rem; } +#ia-title-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + flex-wrap: wrap; +} + #ia-content h1 { font-size: 1.4rem; margin: 0 0 0.25rem; @@ -155,6 +163,38 @@ app-root { align-items: center; } +#ia-locale-switch { + display: flex; + gap: 0.25rem; + margin-bottom: 0.25rem; +} + +.ia-locale-btn { + padding: 0.3rem 0.6rem; + border: 1px solid #bbb; + border-radius: 4px; + background: #fff; + color: #213547; + font-size: 0.8rem; + font-weight: 600; + cursor: pointer; + transition: + background 0.1s, + color 0.1s, + border-color 0.1s; +} + +.ia-locale-btn:hover { + background: #f0f0f0; + border-color: #767676; +} + +.ia-locale-btn.ia-locale-active { + color: #fff; + background: #194880; + border-color: #194880; +} + #ia-content h2 { font-size: 1.1rem; font-weight: 600; diff --git a/eslint.config.mjs b/eslint.config.mjs index 309b8a7b..3582f132 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -81,4 +81,39 @@ export default [ '@typescript-eslint/no-unused-expressions': 'off', }, }, + { + // Only the demo app calls configureLocalization (demo/demo-localization.ts). + // @lit/localize throws if it's configured twice, so this package's own + // source never does. Test files are exempt: they stand in for the app to + // exercise a published locale module on its own. + files: ['src/**/*.ts'], + ignores: ['src/**/*.test.ts'], + rules: { + 'no-restricted-imports': [ + 'error', + { + paths: [ + { + name: 'lit/decorators.js', + importNames: ['customElement'], + message: + "Import customElement from '@src/util/custom-element' instead, so a tag already claimed by another bundle of this package is skipped rather than throwing.", + }, + { + name: 'lit/decorators/custom-element.js', + importNames: ['customElement'], + message: + "Import customElement from '@src/util/custom-element' instead, so a tag already claimed by another bundle of this package is skipped rather than throwing.", + }, + { + name: '@lit/localize', + importNames: ['configureLocalization'], + message: + 'Only the demo app (demo/demo-localization.ts) calls configureLocalization. @lit/localize throws if configured twice, so this package never does.', + }, + ], + }, + ], + }, + }, ]; From c926ac4a3a46cb28d26d214cbd888734e204e475 Mon Sep 17 00:00:00 2001 From: Jason Buckner Date: Thu, 1 Oct 2026 16:06:05 -0700 Subject: [PATCH 06/11] WEBDEV-9249: Fix a stale locale switch overwriting a quicker one Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013cDnU6cdXPyqhk2vxquGpk --- demo/app-root.test.ts | 24 ++++++++++++++++++++++++ demo/app-root.ts | 9 ++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/demo/app-root.test.ts b/demo/app-root.test.ts index c9891782..741c451e 100644 --- a/demo/app-root.test.ts +++ b/demo/app-root.test.ts @@ -309,5 +309,29 @@ describe('AppRoot', () => { 'the deep link never put the playback controls in Spanish', ); }); + + test('a quick EN click after ES wins, even if the Spanish load resolves later', async () => { + setHash('#elem-ia-playback-controls'); + const el = await appRoot(); + await waitUntil( + () => backButtonLabel(el) != null, + 'the playback controls never rendered their back button', + ); + + // Neither await is started before the next fires, the way two quick + // clicks would land. Spanish has to come over the network while + // English is already loaded, so the ES call is still the one in + // flight when the EN call starts. + const setLocaleOnEl = ( + el as unknown as { _setLocale(locale: 'en' | 'es'): Promise } + )._setLocale.bind(el); + const first = setLocaleOnEl('es'); + const second = setLocaleOnEl('en'); + await Promise.all([first, second]); + + expect(backButtonLabel(el)).to.equal('Skip back ten seconds'); + const enButton = el.querySelector('#ia-locale-en') as HTMLButtonElement; + expect(enButton.getAttribute('aria-pressed')).to.equal('true'); + }); }); }); diff --git a/demo/app-root.ts b/demo/app-root.ts index d68a624b..652b0814 100644 --- a/demo/app-root.ts +++ b/demo/app-root.ts @@ -112,10 +112,17 @@ export class AppRoot extends LitElement { this._abortController?.abort(); } + // Counts _setLocale calls so a reply that arrives after a newer one was + // made doesn't overwrite it. this._locale only updates once setLocale + // resolves, so comparing against it can't tell a request already in flight + // from one that's stale. + private _localeRequestId = 0; + /** Switches the demo's language, reflecting it in the URL and the page. */ private _setLocale = async (locale: 'en' | 'es') => { - if (locale === this._locale) return; + const requestId = ++this._localeRequestId; await setLocale(locale); + if (requestId !== this._localeRequestId) return; this._locale = locale; document.documentElement.lang = locale; writeLocaleToUrl(locale); From 4eafe98e2a86297343deb1308ce7f2bac9759eea Mon Sep 17 00:00:00 2001 From: Jason Buckner Date: Thu, 1 Oct 2026 16:19:03 -0700 Subject: [PATCH 07/11] WEBDEV-9249: Make the race-guard test actually exercise the race MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The "quick EN click after ES wins" test awaited Promise.all on two real setLocale calls, but @lit/localize already serializes and drops stale loads internally, and both calls were awaiting one shared Deferred — so their continuations ran in call order regardless of _setLocale's own request-id guard. The test passed even with that guard removed. Stubs setLocale per-test so the ES and EN calls get independently resolvable promises, letting the test deliver the EN reply before the ES one despite ES being requested first. That's the only way the request-id guard's check is actually exercised. Co-Authored-By: Claude Opus 5.5 --- demo/app-root.test.ts | 42 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/demo/app-root.test.ts b/demo/app-root.test.ts index 741c451e..b3338a2c 100644 --- a/demo/app-root.test.ts +++ b/demo/app-root.test.ts @@ -1,5 +1,5 @@ import { fixture, fixtureCleanup, waitUntil } from '@open-wc/testing-helpers'; -import { afterEach, describe, expect, test } from 'vitest'; +import { afterEach, describe, expect, test, vi } from 'vitest'; import { html } from 'lit'; import type { AppRoot } from './app-root'; @@ -7,6 +7,22 @@ import './app-root'; import { setLocale, writeLocaleToUrl } from './demo-localization'; import type { IAPlaybackControls } from '@src/elements/ia-playback-controls/ia-playback-controls'; +// A test-only seam into demo-localization's setLocale: null defers to the +// real implementation, so every test gets the genuine @lit/localize behavior +// unless it opts into controlling the timing of a setLocale call itself. +const localeOverride = vi.hoisted(() => ({ + fn: null as ((locale: 'en' | 'es') => Promise) | null, +})); + +vi.mock('./demo-localization', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + setLocale: (locale: 'en' | 'es') => + (localeOverride.fn ?? actual.setLocale)(locale), + }; +}); + /** * Sets the hash without firing hashchange, so a fixture created afterwards * picks it up as its initial view. @@ -259,6 +275,7 @@ describe('AppRoot', () => { // The configured locale and the URL param both outlive the fixture, so // a test that switches to Spanish would otherwise leak into whatever // runs next in this file. + localeOverride.fn = null; await setLocale('en'); writeLocaleToUrl('en'); }); @@ -318,20 +335,33 @@ describe('AppRoot', () => { 'the playback controls never rendered their back button', ); - // Neither await is started before the next fires, the way two quick - // clicks would land. Spanish has to come over the network while - // English is already loaded, so the ES call is still the one in - // flight when the EN call starts. + // Stubs setLocale with one controllable promise per call, so the test + // can make the ES call's reply arrive after the EN call's even though + // ES was requested first. That's the out-of-order network reply + // _setLocale's request-id guard exists for. Neither call's await is + // started before the next fires, the way two quick clicks would land. + const resolvers = new Map<'en' | 'es', () => void>(); + localeOverride.fn = (locale) => + new Promise((resolve) => resolvers.set(locale, resolve)); + const setLocaleOnEl = ( el as unknown as { _setLocale(locale: 'en' | 'es'): Promise } )._setLocale.bind(el); const first = setLocaleOnEl('es'); const second = setLocaleOnEl('en'); - await Promise.all([first, second]); + + // The EN reply lands first even though it was requested second. + resolvers.get('en')?.(); + await second; + resolvers.get('es')?.(); + await first; expect(backButtonLabel(el)).to.equal('Skip back ten seconds'); const enButton = el.querySelector('#ia-locale-en') as HTMLButtonElement; + const esButton = el.querySelector('#ia-locale-es') as HTMLButtonElement; expect(enButton.getAttribute('aria-pressed')).to.equal('true'); + expect(esButton.getAttribute('aria-pressed')).to.equal('false'); + expect(document.documentElement.lang).to.equal('en'); }); }); }); From 0085e124879bc3e521d08478a97030365a41c671 Mon Sep 17 00:00:00 2001 From: Jason Buckner Date: Thu, 1 Oct 2026 16:25:42 -0700 Subject: [PATCH 08/11] WEBDEV-9249: Drop the redundant locale request-id counter @lit/localize's own setLocale already serializes concurrent switches and drops a stale load, so every caller's continuation runs in call order regardless of which locale's module arrives first. The counter added in the prior commit duplicated that guarantee; the stale-switch bug it was chasing was actually the earlier "if (locale === this._locale) return" early exit, which skipped a newer request whenever it matched the not-yet-updated this._locale. Removing that early exit (now covered by a plain unconditional set after await) is the fix; the existing "quick EN click after ES wins" test already catches a regression of it. Also: - Warn instead of silently swallowing a rejected _setLocale call at both fire-and-forget call sites (the deep-link check and the click handler). - Close an eslint guard gap: `@lit/localize/init/*` re-exports configureLocalization and configureTransformLocalization under paths the existing `@lit/localize` specifier check didn't cover, and configureTransformLocalization wasn't restricted at all. - Share the customElement restricted-imports list between the two no-restricted-imports blocks instead of repeating it. Co-Authored-By: Claude Opus 5.5 --- demo/app-root.test.ts | 42 +++++-------------------------- demo/app-root.ts | 19 +++++++------- eslint.config.mjs | 58 ++++++++++++++++++++++++------------------- 3 files changed, 48 insertions(+), 71 deletions(-) diff --git a/demo/app-root.test.ts b/demo/app-root.test.ts index b3338a2c..741c451e 100644 --- a/demo/app-root.test.ts +++ b/demo/app-root.test.ts @@ -1,5 +1,5 @@ import { fixture, fixtureCleanup, waitUntil } from '@open-wc/testing-helpers'; -import { afterEach, describe, expect, test, vi } from 'vitest'; +import { afterEach, describe, expect, test } from 'vitest'; import { html } from 'lit'; import type { AppRoot } from './app-root'; @@ -7,22 +7,6 @@ import './app-root'; import { setLocale, writeLocaleToUrl } from './demo-localization'; import type { IAPlaybackControls } from '@src/elements/ia-playback-controls/ia-playback-controls'; -// A test-only seam into demo-localization's setLocale: null defers to the -// real implementation, so every test gets the genuine @lit/localize behavior -// unless it opts into controlling the timing of a setLocale call itself. -const localeOverride = vi.hoisted(() => ({ - fn: null as ((locale: 'en' | 'es') => Promise) | null, -})); - -vi.mock('./demo-localization', async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - setLocale: (locale: 'en' | 'es') => - (localeOverride.fn ?? actual.setLocale)(locale), - }; -}); - /** * Sets the hash without firing hashchange, so a fixture created afterwards * picks it up as its initial view. @@ -275,7 +259,6 @@ describe('AppRoot', () => { // The configured locale and the URL param both outlive the fixture, so // a test that switches to Spanish would otherwise leak into whatever // runs next in this file. - localeOverride.fn = null; await setLocale('en'); writeLocaleToUrl('en'); }); @@ -335,33 +318,20 @@ describe('AppRoot', () => { 'the playback controls never rendered their back button', ); - // Stubs setLocale with one controllable promise per call, so the test - // can make the ES call's reply arrive after the EN call's even though - // ES was requested first. That's the out-of-order network reply - // _setLocale's request-id guard exists for. Neither call's await is - // started before the next fires, the way two quick clicks would land. - const resolvers = new Map<'en' | 'es', () => void>(); - localeOverride.fn = (locale) => - new Promise((resolve) => resolvers.set(locale, resolve)); - + // Neither await is started before the next fires, the way two quick + // clicks would land. Spanish has to come over the network while + // English is already loaded, so the ES call is still the one in + // flight when the EN call starts. const setLocaleOnEl = ( el as unknown as { _setLocale(locale: 'en' | 'es'): Promise } )._setLocale.bind(el); const first = setLocaleOnEl('es'); const second = setLocaleOnEl('en'); - - // The EN reply lands first even though it was requested second. - resolvers.get('en')?.(); - await second; - resolvers.get('es')?.(); - await first; + await Promise.all([first, second]); expect(backButtonLabel(el)).to.equal('Skip back ten seconds'); const enButton = el.querySelector('#ia-locale-en') as HTMLButtonElement; - const esButton = el.querySelector('#ia-locale-es') as HTMLButtonElement; expect(enButton.getAttribute('aria-pressed')).to.equal('true'); - expect(esButton.getAttribute('aria-pressed')).to.equal('false'); - expect(document.documentElement.lang).to.equal('en'); }); }); }); diff --git a/demo/app-root.ts b/demo/app-root.ts index 652b0814..c1441f9f 100644 --- a/demo/app-root.ts +++ b/demo/app-root.ts @@ -99,7 +99,11 @@ export class AppRoot extends LitElement { // A `?lang=es` deep link gives a reviewer a one-click way to see elements // in Spanish, so it wins over whatever locale the page started in. const urlLocale = localeFromUrl(); - if (urlLocale !== this._locale) this._setLocale(urlLocale); + if (urlLocale !== this._locale) { + this._setLocale(urlLocale).catch((e) => + console.warn('Failed to apply the deep-linked demo locale:', e), + ); + } // updated() owns the scroll spy, and disconnecting tore it down. An // unchanged hash resolves to the same StoryEntry object, so the assignment // above requests no update on its own, which would leave the spy dead. @@ -112,17 +116,9 @@ export class AppRoot extends LitElement { this._abortController?.abort(); } - // Counts _setLocale calls so a reply that arrives after a newer one was - // made doesn't overwrite it. this._locale only updates once setLocale - // resolves, so comparing against it can't tell a request already in flight - // from one that's stale. - private _localeRequestId = 0; - /** Switches the demo's language, reflecting it in the URL and the page. */ private _setLocale = async (locale: 'en' | 'es') => { - const requestId = ++this._localeRequestId; await setLocale(locale); - if (requestId !== this._localeRequestId) return; this._locale = locale; document.documentElement.lang = locale; writeLocaleToUrl(locale); @@ -227,7 +223,10 @@ export class AppRoot extends LitElement { ? 'ia-locale-active' : ''}" aria-pressed="${this._locale === locale}" - @click=${() => this._setLocale(locale)} + @click=${() => + this._setLocale(locale).catch((e) => + console.warn('Failed to switch the demo locale:', e), + )} > ${label} diff --git a/eslint.config.mjs b/eslint.config.mjs index 3582f132..ed724e12 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -14,6 +14,24 @@ const compat = new FlatCompat({ allConfig: js.configs.all, }); +// Flat config has no equivalent to extending a rule's existing options, so +// both `no-restricted-imports` blocks below spread this in rather than +// repeating it. +const customElementRestrictedImports = [ + { + name: 'lit/decorators.js', + importNames: ['customElement'], + message: + "Import customElement from '@src/util/custom-element' instead, so a tag already claimed by another bundle of this package is skipped rather than throwing.", + }, + { + name: 'lit/decorators/custom-element.js', + importNames: ['customElement'], + message: + "Import customElement from '@src/util/custom-element' instead, so a tag already claimed by another bundle of this package is skipped rather than throwing.", + }, +]; + export default [ ...compat.extends('plugin:@typescript-eslint/recommended'), { @@ -43,20 +61,7 @@ export default [ 'no-restricted-imports': [ 'error', { - paths: [ - { - name: 'lit/decorators.js', - importNames: ['customElement'], - message: - "Import customElement from '@src/util/custom-element' instead, so a tag already claimed by another bundle of this package is skipped rather than throwing.", - }, - { - name: 'lit/decorators/custom-element.js', - importNames: ['customElement'], - message: - "Import customElement from '@src/util/custom-element' instead, so a tag already claimed by another bundle of this package is skipped rather than throwing.", - }, - ], + paths: [...customElementRestrictedImports], }, ], }, @@ -93,21 +98,24 @@ export default [ 'error', { paths: [ + ...customElementRestrictedImports, { - name: 'lit/decorators.js', - importNames: ['customElement'], - message: - "Import customElement from '@src/util/custom-element' instead, so a tag already claimed by another bundle of this package is skipped rather than throwing.", - }, - { - name: 'lit/decorators/custom-element.js', - importNames: ['customElement'], + name: '@lit/localize', + importNames: [ + 'configureLocalization', + 'configureTransformLocalization', + ], message: - "Import customElement from '@src/util/custom-element' instead, so a tag already claimed by another bundle of this package is skipped rather than throwing.", + 'Only the demo app (demo/demo-localization.ts) calls configureLocalization. @lit/localize throws if configured twice, so this package never does.', }, + ], + patterns: [ { - name: '@lit/localize', - importNames: ['configureLocalization'], + // configureLocalization and configureTransformLocalization also + // live at these deep import paths, which the `paths` entry + // above (matched on the `@lit/localize` specifier alone) + // doesn't catch. + group: ['@lit/localize/init/*'], message: 'Only the demo app (demo/demo-localization.ts) calls configureLocalization. @lit/localize throws if configured twice, so this package never does.', }, From 643780ebef27405d0d59be8e4aa3da828d3cf643 Mon Sep 17 00:00:00 2001 From: Jason Buckner Date: Thu, 1 Oct 2026 19:10:09 -0700 Subject: [PATCH 09/11] WEBDEV-9256: Give the focused-story test room for a slow lazy import Loading is a lazy dynamic import, and a busy CI runner can take more than the default 1-second waitUntil timeout to finish it. Other waits on lazy-loaded story content in this file already carry a 5000ms timeout for the same reason; this one never got the same bump. Co-Authored-By: Claude Opus 5.5 --- demo/app-root.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/demo/app-root.test.ts b/demo/app-root.test.ts index 678c815c..95e1b070 100644 --- a/demo/app-root.test.ts +++ b/demo/app-root.test.ts @@ -291,9 +291,12 @@ describe('AppRoot', () => { setHash('#elem-ia-button'); const el = await appRoot(); + // Loading the story is a lazy import, which a busy CI runner can take + // more than the default second over. await waitUntil( () => el.querySelector('ia-button-story'), ' was never rendered', + { timeout: 5000 }, ); expect(customElements.get('ia-button-story')).to.exist; }); From f03fa786497f98916681c0d5fd8839427ce6f137 Mon Sep 17 00:00:00 2001 From: Jason Buckner Date: Mon, 5 Oct 2026 15:44:56 -0700 Subject: [PATCH 10/11] WEBDEV-9249: Put the language switch in the phone bar It only lived in the picker sheet, so a phone had to open the element picker to find it. It's now in the bottom bar with 44px tap targets. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RNuZNwqp3yntWMyppd6XzM --- demo/app-root.test.ts | 8 ++++++-- demo/app-root.ts | 7 ++++--- demo/index.css | 24 ++++++++++++++++++++---- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/demo/app-root.test.ts b/demo/app-root.test.ts index 439e8dd3..90c10899 100644 --- a/demo/app-root.test.ts +++ b/demo/app-root.test.ts @@ -497,11 +497,12 @@ describe('AppRoot', () => { expect(enButton.getAttribute('aria-pressed')).to.equal('true'); }); - test('moves into the picker sheet header on a narrow viewport', async () => { + test('moves into the bottom bar on a narrow viewport', async () => { stubNarrowViewport(true); const el = await appRoot(); - expect(el.querySelector('.ia-picker-head #ia-locale-switch')).to.exist; + expect(el.querySelector('#ia-bar #ia-locale-switch')).to.exist; + expect(el.querySelector('#ia-picker #ia-locale-switch')).to.not.exist; expect(el.querySelector('#ia-content-header #ia-locale-switch')).to.not .exist; }); @@ -971,6 +972,9 @@ describe('AppRoot', () => { barButton(el, 'prev'), barButton(el, 'name'), barButton(el, 'next'), + ...Array.from( + el.querySelectorAll('#ia-bar .ia-locale-btn'), + ), el.querySelector('#ia-picker-close') as HTMLElement, el.querySelector('#ia-picker-search') as HTMLElement, ...Array.from( diff --git a/demo/app-root.ts b/demo/app-root.ts index 461e8829..ac9662dc 100644 --- a/demo/app-root.ts +++ b/demo/app-root.ts @@ -504,8 +504,9 @@ export class AppRoot extends LitElement { /** * The phone layout's way around: step to the element either side, or tap - * the name in the middle for the full list. Along the bottom of the screen - * where a thumb reaches it, and there at any scroll position. + * the name in the middle for the full list, or switch the demo's language. + * Along the bottom of the screen where a thumb reaches it, and there at any + * scroll position. */ private _renderBar(): TemplateResult { const back = this._neighbour(-1); @@ -553,6 +554,7 @@ export class AppRoot extends LitElement { > › + ${this._renderLocaleSwitch()} `; } @@ -586,7 +588,6 @@ export class AppRoot extends LitElement {

Elements

- ${this._renderLocaleSwitch()}