ngwr 16.7.1 → 16.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/charts/donut-chart/styles/_index.scss +9 -3
- package/charts/meter-group/styles/_index.scss +8 -1
- package/charts/sparkline/styles/_index.scss +6 -3
- package/command-palette/styles/_index.scss +10 -0
- package/descriptions/styles/_index.scss +91 -0
- package/fesm2022/ngwr-anchor.mjs +48 -10
- package/fesm2022/ngwr-anchor.mjs.map +1 -1
- package/fesm2022/ngwr-carousel.mjs +3 -2
- package/fesm2022/ngwr-carousel.mjs.map +1 -1
- package/fesm2022/ngwr-charts-calendar-heatmap.mjs +3 -1
- package/fesm2022/ngwr-charts-calendar-heatmap.mjs.map +1 -1
- package/fesm2022/ngwr-charts-core.mjs +17 -0
- package/fesm2022/ngwr-charts-core.mjs.map +1 -1
- package/fesm2022/ngwr-charts-donut-chart-testing.mjs +27 -0
- package/fesm2022/ngwr-charts-donut-chart-testing.mjs.map +1 -1
- package/fesm2022/ngwr-charts-donut-chart.mjs +54 -6
- package/fesm2022/ngwr-charts-donut-chart.mjs.map +1 -1
- package/fesm2022/ngwr-charts-meter-group-testing.mjs +27 -0
- package/fesm2022/ngwr-charts-meter-group-testing.mjs.map +1 -1
- package/fesm2022/ngwr-charts-meter-group.mjs +54 -6
- package/fesm2022/ngwr-charts-meter-group.mjs.map +1 -1
- package/fesm2022/ngwr-charts-sparkline-testing.mjs +27 -0
- package/fesm2022/ngwr-charts-sparkline-testing.mjs.map +1 -1
- package/fesm2022/ngwr-charts-sparkline.mjs +45 -4
- package/fesm2022/ngwr-charts-sparkline.mjs.map +1 -1
- package/fesm2022/ngwr-checkbox.mjs +38 -3
- package/fesm2022/ngwr-checkbox.mjs.map +1 -1
- package/fesm2022/ngwr-color-picker-testing.mjs.map +1 -1
- package/fesm2022/ngwr-color-picker.mjs +4 -3
- package/fesm2022/ngwr-color-picker.mjs.map +1 -1
- package/fesm2022/ngwr-command-palette.mjs +39 -19
- package/fesm2022/ngwr-command-palette.mjs.map +1 -1
- package/fesm2022/ngwr-compare.mjs +4 -0
- package/fesm2022/ngwr-compare.mjs.map +1 -1
- package/fesm2022/ngwr-context-menu.mjs +7 -2
- package/fesm2022/ngwr-context-menu.mjs.map +1 -1
- package/fesm2022/ngwr-cookie.mjs +6 -3
- package/fesm2022/ngwr-cookie.mjs.map +1 -1
- package/fesm2022/ngwr-date-stamp-testing.mjs +3 -0
- package/fesm2022/ngwr-date-stamp-testing.mjs.map +1 -1
- package/fesm2022/ngwr-date-stamp.mjs +81 -4
- package/fesm2022/ngwr-date-stamp.mjs.map +1 -1
- package/fesm2022/ngwr-date.mjs +16 -2
- package/fesm2022/ngwr-date.mjs.map +1 -1
- package/fesm2022/ngwr-density.mjs +4 -3
- package/fesm2022/ngwr-density.mjs.map +1 -1
- package/fesm2022/ngwr-descriptions.mjs +77 -20
- package/fesm2022/ngwr-descriptions.mjs.map +1 -1
- package/fesm2022/ngwr-dialog.mjs +10 -7
- package/fesm2022/ngwr-dialog.mjs.map +1 -1
- package/fesm2022/ngwr-directives.mjs +12 -0
- package/fesm2022/ngwr-directives.mjs.map +1 -1
- package/fesm2022/ngwr-drawer.mjs +14 -8
- package/fesm2022/ngwr-drawer.mjs.map +1 -1
- package/fesm2022/ngwr-editor.mjs +1 -0
- package/fesm2022/ngwr-editor.mjs.map +1 -1
- package/fesm2022/ngwr-file-upload.mjs +4 -5
- package/fesm2022/ngwr-file-upload.mjs.map +1 -1
- package/fesm2022/ngwr-form.mjs.map +1 -1
- package/fesm2022/ngwr-hotkey.mjs +10 -5
- package/fesm2022/ngwr-hotkey.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-ar.mjs +18 -5
- package/fesm2022/ngwr-i18n-ar.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-cs.mjs +18 -5
- package/fesm2022/ngwr-i18n-cs.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-de.mjs +18 -5
- package/fesm2022/ngwr-i18n-de.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-en.mjs +18 -5
- package/fesm2022/ngwr-i18n-en.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-es.mjs +18 -5
- package/fesm2022/ngwr-i18n-es.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-fr.mjs +18 -5
- package/fesm2022/ngwr-i18n-fr.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-he.mjs +18 -5
- package/fesm2022/ngwr-i18n-he.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-hi.mjs +18 -5
- package/fesm2022/ngwr-i18n-hi.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-id.mjs +18 -5
- package/fesm2022/ngwr-i18n-id.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-it.mjs +18 -5
- package/fesm2022/ngwr-i18n-it.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-ja.mjs +18 -5
- package/fesm2022/ngwr-i18n-ja.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-kk.mjs +18 -5
- package/fesm2022/ngwr-i18n-kk.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-ko.mjs +18 -5
- package/fesm2022/ngwr-i18n-ko.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-nl.mjs +18 -5
- package/fesm2022/ngwr-i18n-nl.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-pl.mjs +18 -5
- package/fesm2022/ngwr-i18n-pl.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-pt.mjs +18 -5
- package/fesm2022/ngwr-i18n-pt.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-ru.mjs +18 -5
- package/fesm2022/ngwr-i18n-ru.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-sv.mjs +18 -5
- package/fesm2022/ngwr-i18n-sv.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-tr.mjs +18 -5
- package/fesm2022/ngwr-i18n-tr.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-uk.mjs +18 -5
- package/fesm2022/ngwr-i18n-uk.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-vi.mjs +18 -5
- package/fesm2022/ngwr-i18n-vi.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-zh-tw.mjs +18 -5
- package/fesm2022/ngwr-i18n-zh-tw.mjs.map +1 -1
- package/fesm2022/ngwr-i18n-zh.mjs +18 -5
- package/fesm2022/ngwr-i18n-zh.mjs.map +1 -1
- package/fesm2022/ngwr-i18n.mjs +7 -6
- package/fesm2022/ngwr-i18n.mjs.map +1 -1
- package/fesm2022/ngwr-image-cropper-testing.mjs +33 -0
- package/fesm2022/ngwr-image-cropper-testing.mjs.map +1 -1
- package/fesm2022/ngwr-image-cropper.mjs +536 -30
- package/fesm2022/ngwr-image-cropper.mjs.map +1 -1
- package/fesm2022/ngwr-input-number.mjs +33 -10
- package/fesm2022/ngwr-input-number.mjs.map +1 -1
- package/fesm2022/ngwr-input-otp.mjs +24 -10
- package/fesm2022/ngwr-input-otp.mjs.map +1 -1
- package/fesm2022/ngwr-input.mjs +2 -2
- package/fesm2022/ngwr-input.mjs.map +1 -1
- package/fesm2022/ngwr-knob.mjs +5 -0
- package/fesm2022/ngwr-knob.mjs.map +1 -1
- package/fesm2022/ngwr-lightbox.mjs +5 -3
- package/fesm2022/ngwr-lightbox.mjs.map +1 -1
- package/fesm2022/ngwr-mention.mjs +2 -0
- package/fesm2022/ngwr-mention.mjs.map +1 -1
- package/fesm2022/ngwr-meta.mjs +43 -8
- package/fesm2022/ngwr-meta.mjs.map +1 -1
- package/fesm2022/ngwr-overlay.mjs +51 -2
- package/fesm2022/ngwr-overlay.mjs.map +1 -1
- package/fesm2022/ngwr-pagination.mjs +1 -1
- package/fesm2022/ngwr-pagination.mjs.map +1 -1
- package/fesm2022/ngwr-pipes.mjs +160 -8
- package/fesm2022/ngwr-pipes.mjs.map +1 -1
- package/fesm2022/ngwr-popconfirm.mjs +2 -2
- package/fesm2022/ngwr-popconfirm.mjs.map +1 -1
- package/fesm2022/ngwr-qr.mjs +65 -7
- package/fesm2022/ngwr-qr.mjs.map +1 -1
- package/fesm2022/ngwr-schema-form.mjs +2 -2
- package/fesm2022/ngwr-schema-form.mjs.map +1 -1
- package/fesm2022/ngwr-scroll.mjs +1 -2
- package/fesm2022/ngwr-scroll.mjs.map +1 -1
- package/fesm2022/ngwr-slider.mjs +22 -17
- package/fesm2022/ngwr-slider.mjs.map +1 -1
- package/fesm2022/ngwr-speed-dial.mjs +30 -1
- package/fesm2022/ngwr-speed-dial.mjs.map +1 -1
- package/fesm2022/ngwr-statistic.mjs +1 -1
- package/fesm2022/ngwr-stepper-testing.mjs +7 -1
- package/fesm2022/ngwr-stepper-testing.mjs.map +1 -1
- package/fesm2022/ngwr-stepper.mjs +55 -4
- package/fesm2022/ngwr-stepper.mjs.map +1 -1
- package/fesm2022/ngwr-switch.mjs +33 -3
- package/fesm2022/ngwr-switch.mjs.map +1 -1
- package/fesm2022/ngwr-timeline.mjs +4 -0
- package/fesm2022/ngwr-timeline.mjs.map +1 -1
- package/fesm2022/ngwr-toolbar.mjs +171 -16
- package/fesm2022/ngwr-toolbar.mjs.map +1 -1
- package/fesm2022/ngwr-tour.mjs +8 -3
- package/fesm2022/ngwr-tour.mjs.map +1 -1
- package/fesm2022/ngwr-transfer.mjs +3 -2
- package/fesm2022/ngwr-transfer.mjs.map +1 -1
- package/fesm2022/ngwr-tree.mjs +1 -1
- package/fesm2022/ngwr-utils.mjs +46 -8
- package/fesm2022/ngwr-utils.mjs.map +1 -1
- package/fesm2022/ngwr-version.mjs +1 -1
- package/fesm2022/ngwr-version.mjs.map +1 -1
- package/fesm2022/ngwr-virtual-scroll.mjs +2 -2
- package/fesm2022/ngwr-virtual-scroll.mjs.map +1 -1
- package/i18n/ar.json +18 -5
- package/i18n/cs.json +18 -5
- package/i18n/de.json +18 -5
- package/i18n/en.json +18 -5
- package/i18n/es.json +18 -5
- package/i18n/fr.json +18 -5
- package/i18n/he.json +18 -5
- package/i18n/hi.json +18 -5
- package/i18n/id.json +18 -5
- package/i18n/it.json +18 -5
- package/i18n/ja.json +18 -5
- package/i18n/kk.json +18 -5
- package/i18n/ko.json +18 -5
- package/i18n/nl.json +18 -5
- package/i18n/pl.json +18 -5
- package/i18n/pt.json +18 -5
- package/i18n/ru.json +18 -5
- package/i18n/sv.json +18 -5
- package/i18n/tr.json +18 -5
- package/i18n/uk.json +18 -5
- package/i18n/vi.json +18 -5
- package/i18n/zh-TW.json +18 -5
- package/i18n/zh.json +18 -5
- package/image-cropper/styles/_index.scss +30 -1
- package/llms-full.txt +9 -9
- package/package.json +1 -1
- package/schematics/use/rule.js +1 -0
- package/schematics/use/symbol-map.json +2 -0
- package/skills/ngwr/SKILL.md +2 -2
- package/stepper/styles/_index.scss +33 -0
- package/tour/styles/_index.scss +11 -7
- package/types/ngwr-anchor.d.ts +14 -1
- package/types/ngwr-charts-donut-chart-testing.d.ts +32 -3
- package/types/ngwr-charts-donut-chart.d.ts +45 -6
- package/types/ngwr-charts-meter-group-testing.d.ts +29 -1
- package/types/ngwr-charts-meter-group.d.ts +43 -4
- package/types/ngwr-charts-sparkline-testing.d.ts +32 -2
- package/types/ngwr-charts-sparkline.d.ts +42 -3
- package/types/ngwr-checkbox.d.ts +14 -0
- package/types/ngwr-color-picker-testing.d.ts +1 -1
- package/types/ngwr-command-palette.d.ts +2 -1
- package/types/ngwr-date-stamp-testing.d.ts +2 -0
- package/types/ngwr-date-stamp.d.ts +41 -2
- package/types/ngwr-date.d.ts +3 -1
- package/types/ngwr-descriptions.d.ts +33 -5
- package/types/ngwr-dialog.d.ts +11 -6
- package/types/ngwr-directives.d.ts +1 -0
- package/types/ngwr-drawer.d.ts +12 -4
- package/types/ngwr-file-upload.d.ts +1 -1
- package/types/ngwr-form.d.ts +4 -0
- package/types/ngwr-hotkey.d.ts +2 -0
- package/types/ngwr-image-cropper-testing.d.ts +33 -1
- package/types/ngwr-image-cropper.d.ts +214 -6
- package/types/ngwr-input-number.d.ts +14 -2
- package/types/ngwr-input-otp.d.ts +2 -0
- package/types/ngwr-lightbox.d.ts +1 -0
- package/types/ngwr-meta.d.ts +13 -1
- package/types/ngwr-overlay.d.ts +20 -1
- package/types/ngwr-pipes.d.ts +125 -1
- package/types/ngwr-qr.d.ts +17 -0
- package/types/ngwr-slider.d.ts +3 -1
- package/types/ngwr-speed-dial.d.ts +10 -0
- package/types/ngwr-stepper-testing.d.ts +10 -0
- package/types/ngwr-stepper.d.ts +47 -1
- package/types/ngwr-switch.d.ts +13 -0
- package/types/ngwr-toolbar.d.ts +27 -0
- package/types/ngwr-transfer.d.ts +2 -0
- package/types/ngwr-utils.d.ts +61 -2
- package/types/ngwr-version.d.ts +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ngwr-i18n.mjs","names":[],"sources":["../../../projects/lib/i18n/i18n-base-catalogs.ts","../../../projects/lib/i18n/i18n-config.ts","../../../projects/lib/i18n/i18n-loader.ts","../../../projects/lib/i18n/i18n.ts","../../../projects/lib/i18n/t.pipe.ts","../../../projects/lib/i18n/t.directive.ts","../../../projects/lib/i18n/loaders/static-loader.ts","../../../projects/lib/i18n/loaders/http-loader.ts","../../../projects/lib/i18n/provide-wr-i18n.ts","../../../projects/lib/i18n/util.ts","../../../projects/lib/i18n/http-error.ts"],"sourcesContent":["/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { InjectionToken } from '@angular/core';\n\nimport { type WrI18nCatalog } from './i18n-config';\n\n/** Base catalogs keyed by locale, contributed by {@link provideWrI18nBaseCatalogs}. */\nexport type WrI18nBaseCatalogs = Readonly<Record<string, WrI18nCatalog>>;\n\n/**\n * Catalogs consulted *underneath* whatever the loader returned — the place for\n * ngwr's own built-in strings.\n *\n * A loader **replaces** the catalog for a locale rather than extending it, so an\n * app whose JSON holds only its own keys used to lose every built-in label to\n * its hardcoded English fallback, silently. Registering `wrRu` / `wrEn` here\n * puts them back without the app having to merge anything itself.\n *\n * `multi`, so several features can each contribute; later contributions win on\n * a key collision, and anything the loader returned still wins over all of them.\n *\n * It has to be handed in by the consumer rather than wired up inside\n * `provideWrI18n()`: the catalogs are their own entry points (`ngwr/i18n/ru`)\n * and they already import from `ngwr/i18n`, so importing them back here would\n * be a circular dependency between entry points. Passing them in also keeps\n * the locales you don't ship out of your bundle.\n */\nexport const WR_I18N_BASE_CATALOGS = new InjectionToken<readonly WrI18nBaseCatalogs[]>('WR_I18N_BASE_CATALOGS');\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { InjectionToken, LOCALE_ID, inject } from '@angular/core';\n\n/** Translation catalog — flat or nested record of strings. */\nexport interface WrI18nCatalog {\n readonly [key: string]: string | WrI18nCatalog;\n}\n\n/** Parameters passed to interpolation — coerced to strings via `String(v)`. */\nexport type WrI18nParams = Readonly<Record<string, unknown>>;\n\n/**\n * The third argument of `WrI18n.t()`, `WrI18n.translate()` and the `wrT` pipe,\n * where a bare string is the scope.\n */\nexport interface WrI18nTranslateOptions {\n /** Scoped lookup first, then the root catalog. */\n readonly scope?: string;\n\n /**\n * Returned as is when the key is missing: no interpolation, no\n * `missingHandler` call. `null` and `undefined` mean no fallback.\n */\n readonly fallback?: string | null;\n}\n\n/** Hook called once on every key that resolves to nothing. */\nexport type WrI18nMissingHandler = (key: string, locale: string) => string;\n\n/** User-facing config for {@link provideWrI18n}. */\nexport interface WrI18nConfig {\n /**\n * BCP-47 tag used until the user calls `use()`.\n *\n * Omitted, it is Angular's own `LOCALE_ID` — the app already states its\n * locale there, and ngwr having a second, unrelated default is how a fully\n * Russian app came to render an English calendar inside itself. See\n * {@link WrI18n} for the whole precedence.\n *\n * @default LOCALE_ID\n */\n readonly defaultLocale?: string;\n\n /**\n * Whitelisted locales — `use()` ignores anything outside this list. Omitted,\n * it is `[defaultLocale]`: it used to be a hardcoded `['en']`, so\n * `provideWrI18n({ defaultLocale: 'ru' })` produced a service whose own\n * default locale was not switchable back to.\n *\n * @default [defaultLocale]\n */\n readonly availableLocales?: readonly string[];\n\n /**\n * Storage key for persisting the active locale (via `WrStorage`).\n * Set to `null` to disable persistence. @default 'wr:i18n:locale'\n */\n readonly storageKey?: string | null;\n\n /** Called when a key is missing. Default returns the key itself. */\n readonly missingHandler?: WrI18nMissingHandler;\n}\n\n/** Resolved config — every field non-optional. @internal */\nexport interface WrI18nConfigResolved {\n readonly defaultLocale: string;\n readonly availableLocales: readonly string[];\n readonly storageKey: string | null;\n readonly missingHandler: WrI18nMissingHandler;\n}\n\n/**\n * Everything but the locale, which cannot be a constant: it is resolved from\n * `LOCALE_ID` in an injection context. @internal\n */\nexport const DEFAULT_WR_I18N_CONFIG: Omit<WrI18nConfigResolved, 'defaultLocale' | 'availableLocales'> = {\n storageKey: 'wr:i18n:locale',\n missingHandler: key => key,\n};\n\n/**\n * Resolve the locale half of the config. Callable only from an injection\n * context, because the seed is `LOCALE_ID`. @internal\n */\nexport function resolveWrI18nLocales(\n config: WrI18nConfig\n): Pick<WrI18nConfigResolved, 'defaultLocale' | 'availableLocales'> {\n const defaultLocale = config.defaultLocale ?? inject(LOCALE_ID);\n return { defaultLocale, availableLocales: config.availableLocales ?? [defaultLocale] };\n}\n\nexport const WR_I18N_CONFIG = new InjectionToken<WrI18nConfigResolved>('WR_I18N_CONFIG', {\n factory: () => ({ ...DEFAULT_WR_I18N_CONFIG, ...resolveWrI18nLocales({}) }),\n});\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { InjectionToken } from '@angular/core';\n\nimport { of, type Observable } from 'rxjs';\n\nimport { type WrI18nCatalog } from './i18n-config';\n\n/**\n * Loads a catalog for a `(locale, scope)` pair. `scope` is `null` for the\n * root catalog. Implementations may return the catalog synchronously\n * (via `of(...)`) for static catalogs or asynchronously (via HTTP) for\n * lazy fetches.\n */\nexport interface WrI18nLoader {\n load(locale: string, scope: string | null): Observable<WrI18nCatalog>;\n}\n\n/**\n * The active loader.\n *\n * Defaults to one that serves an empty catalog, which is what makes\n * `provideWrI18n()` genuinely optional: every ngwr component routes its\n * built-in strings through `useI18nText` / `wrReadI18nText`, those inject\n * `WrI18n` optionally — and because `WrI18n` is `providedIn: 'root'`, an\n * optional inject still CONSTRUCTS it. Without a default here that construction\n * threw `NG0201: No provider found for WR_I18N_LOADER`, so an app that had\n * simply not configured i18n could not render `<wr-alert>` at all.\n *\n * With the empty catalog, every lookup misses, `t()` hands back the key, and\n * the helpers fall through to the component's own English default — the\n * documented no-i18n behaviour.\n */\nexport const WR_I18N_LOADER = new InjectionToken<WrI18nLoader>('WR_I18N_LOADER', {\n providedIn: 'root',\n factory: () => ({ load: () => of({}) }),\n});\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { LOCALE_ID, Service, type Signal, computed, effect, inject, isDevMode, signal } from '@angular/core';\n\nimport { type Observable, firstValueFrom } from 'rxjs';\n\nimport { WrStorage } from 'ngwr/storage';\n\nimport { WR_I18N_BASE_CATALOGS } from './i18n-base-catalogs';\nimport { WR_I18N_CONFIG, type WrI18nCatalog, type WrI18nParams, type WrI18nTranslateOptions } from './i18n-config';\nimport { WR_I18N_LOADER } from './i18n-loader';\n\n/** Cache key shape: `<locale>::<scope|''>`. @internal */\nfunction cacheKey(locale: string, scope: string | null): string {\n return `${locale}::${scope ?? ''}`;\n}\n\n/**\n * A locale and the language under it: `'ru-RU'` gives `['ru-RU', 'ru']`.\n *\n * Every lookup and every load walks this, so a catalog registered as `ru`\n * answers an app running `ru-RU`. Without it the two spellings are unrelated\n * strings, and the miss is silent — `t()` returns the key, `useI18nText` reads\n * that as \"missing\" and serves the English fallback, so a fully translated app\n * renders English with nothing logged. It only ever truncates: an `en` lookup\n * never reaches an `en-US` catalog, because a language is not a region.\n *\n * @internal\n */\nfunction localeChain(locale: string): readonly string[] {\n const dash = locale.indexOf('-');\n return dash > 0 ? [locale, locale.slice(0, dash)] : [locale];\n}\n\n/** Walk a dotted path through a catalog tree. Returns string | null. @internal */\nfunction walk(cat: WrI18nCatalog | null, key: string): string | null {\n if (!cat) return null;\n let node: string | WrI18nCatalog | undefined = cat;\n for (const part of key.split('.')) {\n if (node === undefined || typeof node === 'string') return null;\n node = node[part];\n }\n return typeof node === 'string' ? node : null;\n}\n\n/**\n * `{{name}}` interpolation. Missing params resolve to `''`. Exported so\n * helpers in `util.ts` can interpolate the fallback template when no\n * `WrI18n` provider is wired up.\n *\n * @internal\n */\nexport function wrInterpolate(template: string, params: WrI18nParams | undefined): string {\n if (!params) return template;\n return template.replace(/\\{\\{\\s*([\\w.-]+)\\s*\\}\\}/g, (_match, name: string) => {\n const v = params[name];\n if (v === undefined || v === null) return '';\n if (typeof v === 'string') return v;\n if (typeof v === 'number' || typeof v === 'boolean') return String(v);\n try {\n return JSON.stringify(v);\n } catch {\n return '';\n }\n });\n}\n\n/**\n * Reactive i18n service. Holds:\n *\n * - the active locale as a `Signal<string>`\n * - per-`(locale, scope)` catalogs in a `Map` (loaded once, then cached)\n * - a per-locale signal counter so every `translate()` reading the signal\n * re-evaluates the moment a new catalog finishes loading\n *\n * Translations are looked up scope-first then root, per locale, and the locale\n * itself is tried as the full tag before the bare language underneath it — so\n * an app running `ru-RU` resolves against a catalog registered as `ru`, and a\n * regional catalog is never shadowed by a scope in the base language. For an\n * app that spells its locale one way, which is every app that existed before\n * the chain, the order is exactly what it always was.\n *\n * ## Which locale wins\n *\n * ngwr has three locale inputs and they used to be three unrelated answers — an\n * app that set `LOCALE_ID: 'ru-RU'` correctly still rendered an English\n * calendar, because the date token defaulted to `navigator.language`. The\n * precedence is now stated, highest first:\n *\n * 1. **A subsystem's own explicit option.** `withDates({ locale })` pins\n * dates; `provideWrI18n({ defaultLocale })` pins the catalog. The most\n * specific statement wins, because it can only have been deliberate.\n * 2. **`WrI18n.locale()` — the runtime value.** The only one of the three that\n * can change without a reload, so it is what a language switcher writes.\n * With `provideWrI18n()` in the app, dates are written in it.\n * 3. **`LOCALE_ID`.** Angular's app-wide constant, and the seed for both of the\n * above when neither was given. One statement, one answer.\n * 4. `'en-US'`, which is what `LOCALE_ID` itself falls back to.\n *\n * `navigator.language` is deliberately NOT in that list. It is the browser's\n * preference, not the application's, and reading it made prerendered output and\n * the hydrated page disagree.\n *\n * **What a runtime switch reaches, and what it does not.** `use()` repaints\n * every catalog string, and every date: the date adapter, and so\n * `wr-calendar`, `wr-date-picker`, `wrDate` and `wr-date-stamp`, formats in\n * this locale unless `withDates({ locale })` pinned another. It does not move\n * `LOCALE_ID`, which is a constant, so anything keyed on it — `wrNumber` /\n * `wrPlural`, `wr-input-number`, `wr-statistic`, `wr-counter` — stays where it\n * was. `use()` says so once in dev mode rather than leaving it to be\n * discovered.\n *\n * @example\n * ```ts\n * const i18n = inject(WrI18n);\n * i18n.use('ru'); // switch locale\n * i18n.t('cart.checkout'); // → 'Оформить заказ'\n * i18n.t('greeting', { name: 'Ada' }); // → 'Hello, Ada!'\n * i18n.t(`types.${type}`, undefined, { fallback: type }); // → type, when no key\n *\n * effect(() => console.log(i18n.translate('hi')())); // re-runs on locale change\n * ```\n *\n * @see https://ngwr.dev/reference/services/i18n\n */\n@Service()\nexport class WrI18n {\n private readonly config = inject(WR_I18N_CONFIG);\n private readonly loader = inject(WR_I18N_LOADER);\n private readonly storage = inject(WrStorage);\n\n /**\n * Angular's own locale. Read for the dev-mode drift warning only — the\n * resolved default already folded it in through `WR_I18N_CONFIG`. @internal\n */\n private readonly localeId = inject(LOCALE_ID);\n\n /**\n * Catalogs registered via `provideWrI18nBaseCatalogs()` — the floor under the\n * loader's own catalogs, so ngwr's built-in strings survive an app that only\n * ships its own keys. @internal\n */\n private readonly baseCatalogs = inject(WR_I18N_BASE_CATALOGS, { optional: true }) ?? [];\n\n /** Per-(locale,scope) catalogs, populated by `loadCatalog`. @internal */\n private readonly catalogs = new Map<string, WrI18nCatalog>();\n\n /** Bumped after each catalog write so reactive translates recompute. @internal */\n private readonly revision = signal(0);\n\n /** In-flight load promises — dedupes parallel `t()` callers. @internal */\n private readonly inflight = new Map<string, Promise<WrI18nCatalog>>();\n\n /** Keys whose last load failed: `t()` does not retry them, `use()` and `registerScope()` do. @internal */\n private readonly failed = new Set<string>();\n\n /** Registered scopes — auto-loaded whenever the locale changes. @internal */\n private readonly scopes = new Set<string>();\n\n /** Active locale. Writes go through `use()` so storage stays in sync. */\n private readonly _locale = signal<string>(this.initialLocale());\n readonly locale: Signal<string> = this._locale.asReadonly();\n\n constructor() {\n // Eagerly load the root catalog + every registered scope for the\n // current locale. Subsequent locale changes refire the same effect.\n effect(() => {\n const lc = this._locale();\n void this.loadChain(lc, null);\n for (const sc of this.scopes) void this.loadChain(lc, sc);\n });\n }\n\n // Locale\n\n /**\n * Switch active locale. Ignored when not whitelisted.\n *\n * Text and dates — see the class docs for what a runtime switch cannot reach. The\n * dev-mode warning below is the whole reporting of that limit; without it the\n * failure is a screen showing German labels beside `1,234.5`, with nothing\n * anywhere saying why.\n */\n use(locale: string): void {\n if (!this.config.availableLocales.includes(locale)) return;\n const previous = this._locale();\n this._locale.set(locale);\n if (this.config.storageKey) this.storage.set(this.config.storageKey, locale);\n void this.loadChain(locale, null);\n for (const sc of this.scopes) void this.loadChain(locale, sc);\n if (isDevMode() && previous !== locale) this.warnOnLocaleIdDrift(locale);\n }\n\n /** Available locales — pass-through from config. */\n available(): readonly string[] {\n return this.config.availableLocales;\n }\n\n // Scopes\n\n /**\n * Register a scope so its catalog loads alongside the root one. Idempotent.\n * Returns a promise resolving once the current locale's scope catalog is in\n * the cache — handy for feature `canActivate` guards.\n */\n registerScope(scope: string): Promise<WrI18nCatalog> {\n this.scopes.add(scope);\n const lc = this._locale();\n // Resolve on the exact tag: the promise is what a `canActivate` waits on,\n // and the base-language catalog is only ever a fallback under it.\n const exact = this.loadCatalog(lc, scope);\n void this.loadChain(lc, scope);\n return exact;\n }\n\n // Translate\n\n /**\n * Eager translate — returns the current value or the missing-handler\n * fallback. Does NOT auto-load missing catalogs; combine with the\n * reactive `translate(...)` if you want load-on-demand.\n *\n * The third argument is a scope, or `{ scope, fallback }`. With a `fallback`\n * a missing key returns it as is, not interpolated, and `missingHandler` is\n * not called: for a key built from a server value that may have no\n * translation.\n */\n t(key: string, params?: WrI18nParams, scopeOrOptions?: string | WrI18nTranslateOptions): string {\n // Read revision so callers inside computed/effect re-run on updates.\n this.revision();\n const lc = this._locale();\n const options = typeof scopeOrOptions === 'string' ? { scope: scopeOrOptions } : scopeOrOptions;\n const scope = options?.scope;\n\n const chain = localeChain(lc);\n let hit: string | null = null;\n for (const candidate of chain) {\n if (scope) hit = walk(this.catalogs.get(cacheKey(candidate, scope)) ?? null, key);\n hit ??= walk(this.catalogs.get(cacheKey(candidate, null)) ?? null, key);\n if (hit !== null) break;\n }\n // Base catalogs are the floor: consulted only once the loader's own catalogs\n // have missed, so an app's keys always win, but ngwr's built-in strings are\n // still there when the app's catalog doesn't carry them.\n hit ??= this.walkBase(chain, key);\n\n if (hit === null) {\n // Fire a background load so a future read can resolve it.\n void this.loadChain(lc, scope ?? null, true);\n return options?.fallback ?? this.config.missingHandler(key, lc);\n }\n return wrInterpolate(hit, params);\n }\n\n /** Reactive translate — re-evaluates on locale or catalog updates. */\n translate(key: string, params?: WrI18nParams, scopeOrOptions?: string | WrI18nTranslateOptions): Signal<string> {\n return computed(() => this.t(key, params, scopeOrOptions));\n }\n\n // Internals\n\n /**\n * Look a key up in the registered base catalogs, later contributions first so\n * a feature can shadow an earlier one.\n */\n private walkBase(chain: readonly string[], key: string): string | null {\n for (const locale of chain) {\n for (let i = this.baseCatalogs.length - 1; i >= 0; i--) {\n const hit = walk(this.baseCatalogs[i][locale] ?? null, key);\n if (hit !== null) return hit;\n }\n }\n return null;\n }\n\n private initialLocale(): string {\n if (this.config.storageKey) {\n const saved = this.storage.get<string>(this.config.storageKey);\n if (saved && this.config.availableLocales.includes(saved)) return saved;\n }\n return this.config.defaultLocale;\n }\n\n /**\n * Load a `(locale, scope)` catalog and, when the locale carries a region, the\n * bare-language one under it. Both go in the cache; `t()` reads them in that\n * order.\n */\n private loadChain(locale: string, scope: string | null, auto = false): Promise<unknown> {\n return Promise.all(localeChain(locale).map(candidate => this.loadCatalog(candidate, scope, auto)));\n }\n\n /** One warning per service, not one per switch. @internal */\n private warnedLocaleIdDrift = false;\n\n /**\n * Say once, in dev, that a runtime switch moved the text and nothing else.\n *\n * The mismatch is otherwise invisible in the way that costs the most time:\n * the catalog strings and the dates all change, which reads as \"the switch\n * worked\", and the numbers beside them are still correct-looking output in\n * the old locale. Silent when the new locale IS `LOCALE_ID`, because then nothing is\n * out of step and a warning that fires when everything agrees is one people\n * learn to ignore. Production builds drop the call entirely via `isDevMode()`\n * tree-shaking.\n */\n private warnOnLocaleIdDrift(locale: string): void {\n if (this.warnedLocaleIdDrift || locale === this.localeId) return;\n this.warnedLocaleIdDrift = true;\n // eslint-disable-next-line no-console -- dev-mode validation\n console.warn(\n `[NGWR] WrI18n.use('${locale}') switched the catalog, but LOCALE_ID is still '${this.localeId}'. ` +\n `Dates follow the switch (wrDate, wr-calendar, wr-date-picker), unless withDates({ locale }) pinned ` +\n `them. LOCALE_ID is an Angular constant, so formatted numbers do not and stay on '${this.localeId}': ` +\n `the wrNumber / wrPlural pipes, wr-input-number, wr-statistic, wr-counter, wr-pagination's total ` +\n `and wr-file-upload's sizes. Reload the app with the new LOCALE_ID to move those.`\n );\n }\n\n private loadCatalog(locale: string, scope: string | null, auto = false): Promise<WrI18nCatalog> {\n const ck = cacheKey(locale, scope);\n const cached = this.catalogs.get(ck);\n if (cached) return Promise.resolve(cached);\n if (auto && this.failed.has(ck)) return Promise.resolve({});\n\n const pending = this.inflight.get(ck);\n if (pending) return pending;\n\n const stream: Observable<WrI18nCatalog> = this.loader.load(locale, scope);\n const promise = firstValueFrom(stream)\n .then(catalog => {\n this.failed.delete(ck);\n this.catalogs.set(ck, catalog);\n this.revision.update(v => v + 1);\n return catalog;\n })\n .catch((err: unknown) => {\n // eslint-disable-next-line no-console -- intentional diagnostic for missing catalog\n console.warn(`[ngwr/i18n] failed to load (${locale}, ${scope ?? 'root'})`, err);\n this.failed.add(ck);\n const empty: WrI18nCatalog = {};\n return empty;\n })\n .finally(() => {\n this.inflight.delete(ck);\n });\n\n this.inflight.set(ck, promise);\n return promise;\n }\n}\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { Pipe, type PipeTransform, inject } from '@angular/core';\n\nimport { WrI18n } from './i18n';\nimport { type WrI18nParams, type WrI18nTranslateOptions } from './i18n-config';\n\n/**\n * Translate a key. Impure — re-evaluates on every CD so locale switches\n * and catalog loads propagate without a manual refresh.\n *\n * @example\n * ```html\n * <h1>{{ 'home.title' | wrT }}</h1>\n * <p>{{ 'greeting' | wrT: { name: user().name } }}</p>\n * <button>{{ 'forms.save' | wrT: null : 'checkout' }}</button>\n * <span>{{ 'types.' + type | wrT: null : { fallback: type } }}</span>\n * ```\n */\n// eslint-disable-next-line @angular-eslint/no-pipe-impure -- intentional: locale + catalog updates must propagate even when args are stable\n@Pipe({ name: 'wrT', pure: false })\nexport class WrTPipe implements PipeTransform {\n private readonly i18n = inject(WrI18n);\n\n transform(key: string, params?: WrI18nParams | null, scopeOrOptions?: string | WrI18nTranslateOptions): string {\n return this.i18n.t(key, params ?? undefined, scopeOrOptions);\n }\n}\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { Directive, ElementRef, computed, effect, inject, input } from '@angular/core';\n\nimport { WrI18n } from './i18n';\nimport { type WrI18nParams } from './i18n-config';\n\n/**\n * Attribute directive that sets `textContent` of its host to the translation\n * of the bound key. Reactive — re-renders on locale + catalog changes.\n *\n * @example\n * ```html\n * <span [wrT]=\"'home.title'\"></span>\n * <span [wrT]=\"'greeting'\" [wrTParams]=\"{ name: user().name }\"></span>\n * <span [wrT]=\"'forms.save'\" wrTScope=\"checkout\"></span>\n * <span [wrT]=\"'types.' + type\" [wrTFallback]=\"type\"></span>\n * ```\n */\n@Directive({\n selector: '[wrT]',\n})\nexport class WrTDirective {\n /** Translation key. Required. */\n readonly wrT = input.required<string>();\n\n /** Interpolation params for `{{name}}` tokens. */\n readonly wrTParams = input<WrI18nParams | null>(null);\n\n /** Optional scope — scoped lookup first, then root fallback. */\n readonly wrTScope = input<string | null>(null);\n\n /** Text shown as is when the key is missing; `missingHandler` is not called. */\n readonly wrTFallback = input<string | null>(null);\n\n private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);\n private readonly i18n = inject(WrI18n);\n\n private readonly text = computed(() =>\n this.i18n.t(this.wrT(), this.wrTParams() ?? undefined, {\n scope: this.wrTScope() ?? undefined,\n fallback: this.wrTFallback(),\n })\n );\n\n constructor() {\n effect(() => {\n this.host.nativeElement.textContent = this.text();\n });\n }\n}\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { type Observable, of } from 'rxjs';\n\nimport { type WrI18nCatalog } from '../i18n-config';\nimport { type WrI18nLoader } from '../i18n-loader';\n\n/** Root catalogs keyed by locale: `{ en: catalog, ru: catalog, … }`. */\nexport type WrI18nStaticCatalogs = Readonly<Record<string, WrI18nCatalog>>;\n\n/** Per-scope catalogs: `{ checkout: { en: catalog, ru: catalog }, … }`. */\nexport type WrI18nStaticScopedCatalogs = Readonly<Record<string, WrI18nStaticCatalogs>>;\n\n/**\n * Loader for catalogs already in memory (imported from JSON or generated).\n *\n * - Pass `catalogs` for the root catalog of every locale.\n * - Pass `scopes` if you ship per-feature catalogs the loader should serve\n * to `WrI18n.registerScope(name)` calls.\n *\n * Missing locale or scope resolves to `{}` — the missing-key handler then\n * decides what to render.\n */\nexport class WrI18nStaticLoader implements WrI18nLoader {\n constructor(\n private readonly catalogs: WrI18nStaticCatalogs,\n private readonly scopes: WrI18nStaticScopedCatalogs = {}\n ) {}\n\n load(locale: string, scope: string | null): Observable<WrI18nCatalog> {\n if (scope === null) return of(this.catalogs[locale] ?? {});\n return of(this.scopes[scope]?.[locale] ?? {});\n }\n}\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { HttpClient } from '@angular/common/http';\nimport { inject } from '@angular/core';\n\nimport { type Observable } from 'rxjs';\n\nimport { type WrI18nCatalog } from '../i18n-config';\nimport { type WrI18nLoader } from '../i18n-loader';\n\n/** Configuration for {@link WrI18nHttpLoader}. */\nexport interface WrI18nHttpLoaderConfig {\n /**\n * URL template. Tokens:\n * - `{locale}` — required, BCP-47 tag (e.g. `en`).\n * - `{scope}` — optional, scope name. Use the `rootPath` if you need a\n * different path entirely for the root catalog.\n *\n * @example\n * ```ts\n * { path: '/assets/i18n/{locale}.json' } // root only\n * { path: '/assets/i18n/{scope}/{locale}.json',\n * rootPath: '/assets/i18n/{locale}.json' } // root + scopes\n * ```\n */\n readonly path: string;\n /** Path template for the root catalog. Defaults to `path`. */\n readonly rootPath?: string;\n}\n\n/**\n * Loader that fetches catalogs via `HttpClient`. A failure errors the stream;\n * the service logs it, serves the key and retries on the next `use()`.\n */\nexport class WrI18nHttpLoader implements WrI18nLoader {\n private readonly http = inject(HttpClient);\n\n constructor(private readonly config: WrI18nHttpLoaderConfig) {}\n\n load(locale: string, scope: string | null): Observable<WrI18nCatalog> {\n const template = scope === null ? (this.config.rootPath ?? this.config.path) : this.config.path;\n const url = template.replaceAll('{locale}', locale).replaceAll('{scope}', scope ?? '');\n return this.http.get<WrI18nCatalog>(url);\n }\n}\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport {\n ApplicationRef,\n EnvironmentInjector,\n type EnvironmentProviders,\n type Provider,\n inject,\n makeEnvironmentProviders,\n provideEnvironmentInitializer,\n} from '@angular/core';\n\nimport { WR_LIVE_LOCALE } from 'ngwr/utils';\n\nimport { WrI18n } from './i18n';\nimport { WR_I18N_BASE_CATALOGS, type WrI18nBaseCatalogs } from './i18n-base-catalogs';\nimport {\n DEFAULT_WR_I18N_CONFIG,\n WR_I18N_CONFIG,\n type WrI18nConfig,\n type WrI18nConfigResolved,\n resolveWrI18nLocales,\n} from './i18n-config';\nimport { WR_I18N_LOADER, type WrI18nLoader } from './i18n-loader';\nimport { WrI18nHttpLoader, type WrI18nHttpLoaderConfig } from './loaders/http-loader';\nimport {\n WrI18nStaticLoader,\n type WrI18nStaticCatalogs,\n type WrI18nStaticScopedCatalogs,\n} from './loaders/static-loader';\n\n/**\n * Configure {@link WrI18n}. Either pass a `loader` directly, or use the\n * `provideWrI18nHttpLoader` / `provideWrI18nStaticLoader` helpers in the\n * same providers array.\n */\nexport interface ProvideWrI18nOptions extends WrI18nConfig {\n readonly loader?: WrI18nLoader;\n}\n\n/**\n * Configure {@link WrI18n} for the application.\n *\n * Call it in the application's root providers (`bootstrapApplication` or\n * `ApplicationConfig`), together with {@link provideWrI18nBaseCatalogs} and the\n * loader. `WrI18n` is a root service: a route's `providers` or a lazy module\n * never reach it, so a locale or catalogs given there do nothing, and dev mode\n * warns. A lazy area switches the language at runtime with\n * `inject(WrI18n).use('de')`, for example in its resolver. The switch is\n * app-wide, and the locale must be in the root `availableLocales`. The area's\n * own keys load with `registerScope()`.\n */\nexport function provideWrI18n(options: ProvideWrI18nOptions = {}): EnvironmentProviders {\n const { loader, ...config } = options;\n\n const providers: (Provider | EnvironmentProviders)[] = [\n {\n provide: WR_I18N_CONFIG,\n // A factory rather than a value: `defaultLocale` falls back to `LOCALE_ID`,\n // which only an injection context can read.\n useFactory: (): WrI18nConfigResolved => ({\n ...DEFAULT_WR_I18N_CONFIG,\n ...config,\n ...resolveWrI18nLocales(config),\n }),\n },\n ];\n if (loader) providers.push({ provide: WR_I18N_LOADER, useValue: loader });\n // What `ngwr/date` formats in, so dates follow `use()` without importing this entry point.\n providers.push({ provide: WR_LIVE_LOCALE, useFactory: () => inject(WrI18n).locale });\n\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n providers.push(\n provideEnvironmentInitializer(() => {\n const here = inject(EnvironmentInjector);\n if (here === inject(ApplicationRef, { optional: true })?.injector) return;\n // An injector that lists WrI18n itself owns an instance that does read this config.\n if (here.get(WrI18n, null, { self: true })) return;\n // eslint-disable-next-line no-console -- dev-mode validation\n console.warn(\n '[NGWR] provideWrI18n() is in a route or child injector. WrI18n is a root service, so this ' +\n \"configuration is ignored. Move provideWrI18n() and the catalogs to the application's root \" +\n 'providers, and switch a lazy area with inject(WrI18n).use(locale).'\n );\n })\n );\n }\n\n return makeEnvironmentProviders(providers);\n}\n\n/**\n * Provide a static loader — catalogs already in memory.\n *\n * A loader serves only the catalog you pass it, and ngwr registers none of its\n * own. Pass only your own keys here and register ngwr's catalogs with\n * {@link provideWrI18nBaseCatalogs} — not `{ ...wrRu, ...yours }`. A spread is\n * shallow, so any namespace you share with ngwr, e.g. `common`, `form`,\n * `table`, keeps only the keys of the side spread last, and the other side's\n * keys stop resolving with nothing logged: ngwr's components fall back to their\n * English defaults, and a `wrT` read of a lost key renders the raw key under the\n * default missing handler.\n *\n * @param catalogs Root catalogs keyed by locale.\n * @param scopes Optional per-scope catalogs served to `registerScope(name)`.\n */\nexport function provideWrI18nStaticLoader(\n catalogs: WrI18nStaticCatalogs,\n scopes?: WrI18nStaticScopedCatalogs\n): Provider {\n return { provide: WR_I18N_LOADER, useValue: new WrI18nStaticLoader(catalogs, scopes) };\n}\n\n/**\n * Register catalogs consulted *underneath* the loader — this is how ngwr's own\n * built-in strings survive when you supply your own catalogs.\n *\n * A loader replaces the catalog for a locale instead of extending it, so a JSON\n * file holding only your keys leaves every built-in label on its hardcoded\n * English fallback, with nothing logged. One line fixes it, on either loader:\n *\n * @example\n * ```ts\n * import { wrRu } from 'ngwr/i18n/ru';\n *\n * providers: [\n * provideWrI18n({ defaultLocale: 'ru', availableLocales: ['ru'] }),\n * provideWrI18nBaseCatalogs({ ru: wrRu }),\n * provideWrI18nHttpLoader({ path: '/assets/i18n/{locale}.json' }),\n * ]\n * ```\n *\n * Pass only the locales you ship — the ones you leave out stay out of the\n * bundle. Your own keys always win; this is a floor, not an override.\n *\n * Use it instead of spreading `wrRu` into your own catalog, too: the lookup\n * walks these key by key after the loader's catalog misses, so a namespace both\n * define keeps both halves, where a shallow spread keeps only one.\n */\nexport function provideWrI18nBaseCatalogs(catalogs: WrI18nBaseCatalogs): Provider {\n return { provide: WR_I18N_BASE_CATALOGS, useValue: catalogs, multi: true };\n}\n\n/** Provide an HTTP loader — catalogs fetched from URLs. Requires `provideHttpClient`. */\nexport function provideWrI18nHttpLoader(config: WrI18nHttpLoaderConfig): Provider {\n return { provide: WR_I18N_LOADER, useFactory: () => new WrI18nHttpLoader(config) };\n}\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { type Signal, computed, inject, signal } from '@angular/core';\n\nimport { WrI18n, wrInterpolate } from './i18n';\nimport type { WrI18nParams } from './i18n-config';\n\n/**\n * Helper for component default text. Returns a reactive string that:\n *\n * 1. Prefers the consumer's override (an `input<string | null>()` value).\n * 2. Falls back to the i18n catalog under `key` — re-renders on locale\n * change so a switcher updates the DOM live.\n * 3. Falls back to `fallback` when no `WrI18n` is provided OR the catalog\n * is missing the key.\n *\n * Components don't need a hard dependency on `provideWrI18n` — without it,\n * the fallback is returned and everything still works.\n *\n * @example\n * ```ts\n * readonly emptyText = input<string | null>(null);\n * protected readonly empty = useI18nText(this.emptyText, 'table.empty', 'No data');\n *\n * // In template: <div>{{ empty() }}</div>\n * ```\n */\nexport function useI18nText(binding: Signal<string | null | undefined>, key: string, fallback: string): Signal<string> {\n const i18n = inject(WrI18n, { optional: true });\n if (!i18n) {\n return computed(() => {\n const v = binding();\n return v ?? fallback;\n });\n }\n\n return computed(() => {\n const v = binding();\n if (v !== null && v !== undefined && v !== '') return v;\n const translated = i18n.t(key);\n // Default missing handler returns the key itself — treat that as \"missing\"\n // and use our explicit fallback.\n return translated === key ? fallback : translated;\n });\n}\n\n/**\n * {@link useI18nText} without a binding to forward — for a built-in string the\n * component exposes no override input for. Same reactivity, same fallback\n * rules; the only difference is the missing first argument.\n *\n * It used to return a plain `string`, resolved once at injection time, and\n * that was wrong in the ordinary case rather than an edge one: `WrI18n` writes\n * every loader-backed catalog from `firstValueFrom(...).then(...)`, so even a\n * static loader serving an object literal lands a microtask AFTER the first\n * change-detection pass. Every component built in that pass read an empty\n * catalog and froze its English fallback for the life of the app — in one\n * `<wr-date-picker>` the field said \"Открыть календарь\" and the calendar\n * button beside it \"Open calendar\", off the same key.\n */\nexport function wrReadI18nText(key: string, fallback: string): Signal<string> {\n const i18n = inject(WrI18n, { optional: true });\n if (!i18n) return computed(() => fallback);\n\n return computed(() => {\n const v = i18n.t(key);\n return v === key ? fallback : v;\n });\n}\n\n/** Tiny shim — useful when the caller doesn't have an `input` to forward. */\nexport function nullSignal(): Signal<null> {\n return signal(null).asReadonly();\n}\n\n/**\n * Build a per-call formatter for parametrized labels (e.g. ARIA labels\n * that interpolate a per-row value: `\"Remove {{label}}\"`). Returns a\n * function the template calls with the params for the current item.\n *\n * The returned function:\n * - Re-resolves the i18n catalog on every call (live locale switches just\n * work — re-rendered templates pick up new strings).\n * - Falls back to the literal `fallback` template with the same\n * `{{name}}` syntax when no `WrI18n` provider is present, or when the\n * key is missing.\n *\n * Use this for labels that vary per row. For static labels, prefer\n * {@link useI18nText} or {@link wrReadI18nText}.\n *\n * @example\n * ```ts\n * protected readonly removeChipLabel = useI18nFormatter('select.removeItem', 'Remove {{label}}');\n *\n * // In template:\n * // [attr.aria-label]=\"removeChipLabel({ label: chip.label })\"\n * ```\n */\nexport function useI18nFormatter(key: string, fallback: string): (params?: WrI18nParams) => string {\n const i18n = inject(WrI18n, { optional: true });\n if (!i18n) {\n return (params?: WrI18nParams) => wrInterpolate(fallback, params);\n }\n return (params?: WrI18nParams) => {\n const v = i18n.t(key, params);\n return v === key ? wrInterpolate(fallback, params) : v;\n };\n}\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { type Injector, inject } from '@angular/core';\n\nimport { WrI18n, wrInterpolate } from './i18n';\n\n/** The English catalog's `httpError`, for an app with no catalog registered. */\nconst FALLBACK: Readonly<Record<string, string>> = {\n network: 'No connection to the server. Check your network and try again.',\n 400: 'The server did not accept the data. Check the fields.',\n 401: 'Your session has ended. Sign in again.',\n 403: 'You do not have permission for this action.',\n 404: 'Not found. It may have been deleted.',\n 409: 'This conflicts with existing data. Refresh the page and try again.',\n 413: 'The data is too large to send.',\n 422: 'Some of the data is not valid. Check the fields.',\n 429: 'Too many requests. Try again in a moment.',\n 503: 'The server is unavailable. Try again in a minute.',\n '4xx': 'The request was refused. Error code: {{status}}.',\n '5xx': 'The server failed. Try again later. Error code: {{status}}.',\n unknown: 'Something went wrong. Try again later.',\n};\n\n/** Most specific first. */\nfunction catalogKeys(status: number | null): readonly string[] {\n if (status === null) return ['unknown'];\n if (status === 0) return ['network'];\n if (status >= 400 && status < 500) return [String(status), '4xx', 'unknown'];\n if (status >= 500 && status < 600) return [String(status), '5xx', 'unknown'];\n return [String(status), 'unknown'];\n}\n\nfunction serverMessage(error: unknown): string | null {\n const body = (error as { error?: unknown } | null | undefined)?.error;\n if (typeof body === 'string') {\n const text = body.trim();\n // A proxy answers with an HTML page, which is a string body too.\n return text === '' || text.startsWith('<') ? null : text;\n }\n const message = (body as { message?: unknown } | null | undefined)?.message;\n return typeof message === 'string' && message.trim() !== '' ? message.trim() : null;\n}\n\n/** A screen's own sentence for one status: the text, or a function of the error. */\nexport type WrHttpErrorOverride = string | ((error: unknown) => string);\n\n/** Options of {@link wrHttpErrorText}. */\nexport interface WrHttpErrorTextOptions {\n /** The screen's own sentence per status, `0` being a network failure. Wins over everything else. */\n readonly overrides?: Readonly<Partial<Record<number, WrHttpErrorOverride>>>;\n /**\n * Prefer the sentence the server put in the body: `error.error.message`, or\n * a body that is a plain string. For an API that writes its errors for the\n * person at the screen.\n * @default false\n */\n readonly serverMessage?: boolean;\n /** Where to read `WrI18n` from when the call is outside an injection context, such as a `catch`. */\n readonly injector?: Injector;\n}\n\n/**\n * The HTTP status of a failed request: of an `HttpErrorResponse`, a `Response`\n * or anything else carrying a numeric `status`. `0` is a request nothing\n * answered (offline, CORS, a dropped connection); `null` is a value that is not\n * an HTTP error at all.\n *\n * @example\n * ```ts\n * if (wrHttpStatus(error) === 401) void router.navigate(['/login']);\n * ```\n *\n * @see https://ngwr.dev/reference/utils/wr-http-error-text\n */\nexport function wrHttpStatus(error: unknown): number | null {\n const status = (error as { status?: unknown } | null | undefined)?.status;\n return typeof status === 'number' && Number.isInteger(status) && status >= 0 ? status : null;\n}\n\n/**\n * A sentence for a failed request, in the active language. Highest first:\n *\n * 1. `overrides[status]`, the screen's own wording.\n * 2. With `serverMessage`, the sentence in the response body.\n * 3. The catalog: `httpError.<status>`, then `httpError.4xx` / `httpError.5xx`\n * (both take `{{status}}`), `httpError.network` for status `0`, and\n * `httpError.unknown` for the rest. An app's own catalog wins over ngwr's,\n * and English is the floor when neither has the key.\n *\n * Call it in an injection context, or pass `injector` from a `catch` or a\n * callback.\n *\n * @example\n * ```ts\n * private readonly injector = inject(Injector);\n *\n * try {\n * await this.api.save(order);\n * } catch (error) {\n * this.toast.danger(\n * wrHttpErrorText(error, { injector: this.injector, overrides: { 409: 'This name is taken.' } })\n * );\n * }\n * ```\n *\n * @see https://ngwr.dev/reference/utils/wr-http-error-text\n */\nexport function wrHttpErrorText(error: unknown, options: WrHttpErrorTextOptions = {}): string {\n const status = wrHttpStatus(error);\n\n const override = status === null ? undefined : options.overrides?.[status];\n if (override !== undefined) return typeof override === 'function' ? override(error) : override;\n\n if (options.serverMessage && status !== null) {\n const said = serverMessage(error);\n if (said !== null) return said;\n }\n\n const i18n = options.injector ? options.injector.get(WrI18n, null) : inject(WrI18n, { optional: true });\n const keys = catalogKeys(status);\n const params = { status };\n\n for (const key of keys) {\n const hit = i18n?.t(`httpError.${key}`, params, { fallback: '' });\n if (hit) return hit;\n }\n for (const key of keys) {\n if (key in FALLBACK) return wrInterpolate(FALLBACK[key], params);\n }\n return FALLBACK['unknown'];\n}\n"],"mappings":";;;;;;;;;;;;AAgCA,MAAa,wBAAwB,IAAI,eAA8C,uBAAuB;;;;;;;ACiD9G,MAAa,yBAA2F;CACtG,YAAY;CACZ,iBAAgB,QAAO;AACxB;AAMD,SAAgB,qBACd,QAAoB;CAEpB,MAAM,gBAAgB,OAAO,iBAAiB,OAAO,SAAS;CAC9D,OAAO;EAAE;EAAe,kBAAkB,OAAO,oBAAoB,CAAC,aAAa;CAAC;AACtF;AAEA,MAAa,iBAAiB,IAAI,eAAqC,kBAAkB,EACvF,gBAAgB;CAAE,GAAG;CAAwB,GAAG,qBAAqB,CAAA,CAAE;AAAC,GACzE,CAAA;;;;;;;AC7DD,MAAa,iBAAiB,IAAI,eAA6B,kBAAkB;CAC/E,YAAY;CACZ,gBAAgB,EAAE,YAAY,GAAG,CAAA,CAAE,EAAC;AACrC,CAAA;;;;;;;ACvBD,SAAS,SAAS,QAAgB,OAAoB;CACpD,OAAO,GAAG,OAAM,IAAK,SAAS;AAChC;AAcA,SAAS,YAAY,QAAc;CACjC,MAAM,OAAO,OAAO,QAAQ,GAAG;CAC/B,OAAO,OAAO,IAAI,CAAC,QAAQ,OAAO,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM;AAC7D;AAGA,S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AAI,MAAO,KAAK,QAAQ,KAAI,IAAK;AACjF;AAiCA,SAAgB,aAAa,OAAc;CACzC,MAAM,SAAU,OAAmD;CACnE,OAAO,OAAO,WAAW,YAAY,OAAO,UAAU,MAAM,KAAK,UAAU,IAAI,SAAS;AAC1F;AA8BA,SAAgB,gBAAgB,OAAgB,UAAkC,CAAA,GAAE;CAClF,MAAM,SAAS,aAAa,KAAK;CAEjC,MAAM,WAAW,WAAW,OAAO,SAAY,QAAQ,YAAY;CACnE,IAAI,aAAa,QAAW,OAAO,OAAO,aAAa,aAAa,SAAS,KAAK,IAAI;CAEtF,IAAI,QAAQ,iBAAiB,WAAW,MAAM;EAC5C,MAAM,OAAO,cAAc,KAAK;EAChC,IAAI,SAAS,MAAM,OAAO;CAC5B;CAEA,MAAM,OAAO,QAAQ,WAAW,QAAQ,SAAS,IAAI,QAAQ,IAAI,IAAI,OAAO,QAAQ,EAAE,UAAU,KAAI,CAAE;CACtG,MAAM,OAAO,YAAY,MAAM;CAC/B,MAAM,SAAS,EAAE,OAAM;CAEvB,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,MAAM,MAAM,EAAE,aAAa,OAAO,QAAQ,EAAE,UAAU,GAAE,CAAE;EAChE,IAAI,KAAK,OAAO;CAClB;CACA,KAAK,MAAM,OAAO,MAChB,IAAI,OAAO,UAAU,OAAO,cAAc,SAAS,MAAM,MAAM;CAEjE,OAAO,SAAS;AAClB"}
|
|
1
|
+
{"version":3,"file":"ngwr-i18n.mjs","names":[],"sources":["../../../projects/lib/i18n/i18n-base-catalogs.ts","../../../projects/lib/i18n/i18n-config.ts","../../../projects/lib/i18n/i18n-loader.ts","../../../projects/lib/i18n/i18n.ts","../../../projects/lib/i18n/t.pipe.ts","../../../projects/lib/i18n/t.directive.ts","../../../projects/lib/i18n/loaders/static-loader.ts","../../../projects/lib/i18n/loaders/http-loader.ts","../../../projects/lib/i18n/provide-wr-i18n.ts","../../../projects/lib/i18n/util.ts","../../../projects/lib/i18n/http-error.ts"],"sourcesContent":["/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { InjectionToken } from '@angular/core';\n\nimport { type WrI18nCatalog } from './i18n-config';\n\n/** Base catalogs keyed by locale, contributed by {@link provideWrI18nBaseCatalogs}. */\nexport type WrI18nBaseCatalogs = Readonly<Record<string, WrI18nCatalog>>;\n\n/**\n * Catalogs consulted *underneath* whatever the loader returned — the place for\n * ngwr's own built-in strings.\n *\n * A loader **replaces** the catalog for a locale rather than extending it, so an\n * app whose JSON holds only its own keys used to lose every built-in label to\n * its hardcoded English fallback, silently. Registering `wrRu` / `wrEn` here\n * puts them back without the app having to merge anything itself.\n *\n * `multi`, so several features can each contribute; later contributions win on\n * a key collision, and anything the loader returned still wins over all of them.\n *\n * It has to be handed in by the consumer rather than wired up inside\n * `provideWrI18n()`: the catalogs are their own entry points (`ngwr/i18n/ru`)\n * and they already import from `ngwr/i18n`, so importing them back here would\n * be a circular dependency between entry points. Passing them in also keeps\n * the locales you don't ship out of your bundle.\n */\nexport const WR_I18N_BASE_CATALOGS = new InjectionToken<readonly WrI18nBaseCatalogs[]>('WR_I18N_BASE_CATALOGS');\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { InjectionToken, LOCALE_ID, inject } from '@angular/core';\n\n/** Translation catalog — flat or nested record of strings. */\nexport interface WrI18nCatalog {\n readonly [key: string]: string | WrI18nCatalog;\n}\n\n/** Parameters passed to interpolation — coerced to strings via `String(v)`. */\nexport type WrI18nParams = Readonly<Record<string, unknown>>;\n\n/**\n * The third argument of `WrI18n.t()`, `WrI18n.translate()` and the `wrT` pipe,\n * where a bare string is the scope.\n */\nexport interface WrI18nTranslateOptions {\n /** Scoped lookup first, then the root catalog. */\n readonly scope?: string;\n\n /**\n * Returned as is when the key is missing: no interpolation, no\n * `missingHandler` call. `null` and `undefined` mean no fallback.\n */\n readonly fallback?: string | null;\n}\n\n/** Hook called once on every key that resolves to nothing. */\nexport type WrI18nMissingHandler = (key: string, locale: string) => string;\n\n/** User-facing config for {@link provideWrI18n}. */\nexport interface WrI18nConfig {\n /**\n * BCP-47 tag used until the user calls `use()`.\n *\n * Omitted, it is Angular's own `LOCALE_ID` — the app already states its\n * locale there, and ngwr having a second, unrelated default is how a fully\n * Russian app came to render an English calendar inside itself. See\n * {@link WrI18n} for the whole precedence.\n *\n * @default LOCALE_ID\n */\n readonly defaultLocale?: string;\n\n /**\n * Whitelisted locales — `use()` ignores anything outside this list. Omitted,\n * it is `[defaultLocale]`: it used to be a hardcoded `['en']`, so\n * `provideWrI18n({ defaultLocale: 'ru' })` produced a service whose own\n * default locale was not switchable back to.\n *\n * @default [defaultLocale]\n */\n readonly availableLocales?: readonly string[];\n\n /**\n * Storage key for persisting the active locale (via `WrStorage`).\n * Set to `null` to disable persistence. @default 'wr:i18n:locale'\n */\n readonly storageKey?: string | null;\n\n /** Called when a key is missing. Default returns the key itself. */\n readonly missingHandler?: WrI18nMissingHandler;\n}\n\n/** Resolved config — every field non-optional. @internal */\nexport interface WrI18nConfigResolved {\n readonly defaultLocale: string;\n readonly availableLocales: readonly string[];\n readonly storageKey: string | null;\n readonly missingHandler: WrI18nMissingHandler;\n}\n\n/**\n * Everything but the locale, which cannot be a constant: it is resolved from\n * `LOCALE_ID` in an injection context. @internal\n */\nexport const DEFAULT_WR_I18N_CONFIG: Omit<WrI18nConfigResolved, 'defaultLocale' | 'availableLocales'> = {\n storageKey: 'wr:i18n:locale',\n missingHandler: key => key,\n};\n\n/**\n * Resolve the locale half of the config. Callable only from an injection\n * context, because the seed is `LOCALE_ID`. @internal\n */\nexport function resolveWrI18nLocales(\n config: WrI18nConfig\n): Pick<WrI18nConfigResolved, 'defaultLocale' | 'availableLocales'> {\n const defaultLocale = config.defaultLocale ?? inject(LOCALE_ID);\n return { defaultLocale, availableLocales: config.availableLocales ?? [defaultLocale] };\n}\n\nexport const WR_I18N_CONFIG = new InjectionToken<WrI18nConfigResolved>('WR_I18N_CONFIG', {\n factory: () => ({ ...DEFAULT_WR_I18N_CONFIG, ...resolveWrI18nLocales({}) }),\n});\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { InjectionToken } from '@angular/core';\n\nimport { of, type Observable } from 'rxjs';\n\nimport { type WrI18nCatalog } from './i18n-config';\n\n/**\n * Loads a catalog for a `(locale, scope)` pair. `scope` is `null` for the\n * root catalog. Implementations may return the catalog synchronously\n * (via `of(...)`) for static catalogs or asynchronously (via HTTP) for\n * lazy fetches.\n */\nexport interface WrI18nLoader {\n load(locale: string, scope: string | null): Observable<WrI18nCatalog>;\n}\n\n/**\n * The active loader.\n *\n * Defaults to one that serves an empty catalog, which is what makes\n * `provideWrI18n()` genuinely optional: every ngwr component routes its\n * built-in strings through `useI18nText` / `wrReadI18nText`, those inject\n * `WrI18n` optionally — and because `WrI18n` is `providedIn: 'root'`, an\n * optional inject still CONSTRUCTS it. Without a default here that construction\n * threw `NG0201: No provider found for WR_I18N_LOADER`, so an app that had\n * simply not configured i18n could not render `<wr-alert>` at all.\n *\n * With the empty catalog, every lookup misses, `t()` hands back the key, and\n * the helpers fall through to the component's own English default — the\n * documented no-i18n behaviour.\n */\nexport const WR_I18N_LOADER = new InjectionToken<WrI18nLoader>('WR_I18N_LOADER', {\n providedIn: 'root',\n factory: () => ({ load: () => of({}) }),\n});\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { LOCALE_ID, Service, type Signal, computed, effect, inject, isDevMode, signal } from '@angular/core';\n\nimport { type Observable, firstValueFrom } from 'rxjs';\n\nimport { WrStorage } from 'ngwr/storage';\n\nimport { WR_I18N_BASE_CATALOGS } from './i18n-base-catalogs';\nimport { WR_I18N_CONFIG, type WrI18nCatalog, type WrI18nParams, type WrI18nTranslateOptions } from './i18n-config';\nimport { WR_I18N_LOADER } from './i18n-loader';\n\n/** Cache key shape: `<locale>::<scope|''>`. @internal */\nfunction cacheKey(locale: string, scope: string | null): string {\n return `${locale}::${scope ?? ''}`;\n}\n\n/**\n * A locale and the language under it: `'ru-RU'` gives `['ru-RU', 'ru']`.\n *\n * Every lookup and every load walks this, so a catalog registered as `ru`\n * answers an app running `ru-RU`. Without it the two spellings are unrelated\n * strings, and the miss is silent — `t()` returns the key, `useI18nText` reads\n * that as \"missing\" and serves the English fallback, so a fully translated app\n * renders English with nothing logged. It only ever truncates: an `en` lookup\n * never reaches an `en-US` catalog, because a language is not a region.\n *\n * @internal\n */\nfunction localeChain(locale: string): readonly string[] {\n const dash = locale.indexOf('-');\n return dash > 0 ? [locale, locale.slice(0, dash)] : [locale];\n}\n\n/** Walk a dotted path through a catalog tree. Returns string | null. @internal */\nfunction walk(cat: WrI18nCatalog | null, key: string): string | null {\n if (!cat) return null;\n let node: string | WrI18nCatalog | undefined = cat;\n for (const part of key.split('.')) {\n if (node === undefined || typeof node === 'string') return null;\n node = node[part];\n }\n return typeof node === 'string' ? node : null;\n}\n\n/**\n * `{{name}}` interpolation. Missing params resolve to `''`. Exported so\n * helpers in `util.ts` can interpolate the fallback template when no\n * `WrI18n` provider is wired up.\n *\n * @internal\n */\nexport function wrInterpolate(template: string, params: WrI18nParams | undefined): string {\n if (!params) return template;\n return template.replace(/\\{\\{\\s*([\\w.-]+)\\s*\\}\\}/g, (_match, name: string) => {\n const v = params[name];\n if (v === undefined || v === null) return '';\n if (typeof v === 'string') return v;\n if (typeof v === 'number' || typeof v === 'boolean') return String(v);\n try {\n return JSON.stringify(v);\n } catch {\n return '';\n }\n });\n}\n\n/**\n * Reactive i18n service. Holds:\n *\n * - the active locale as a `Signal<string>`\n * - per-`(locale, scope)` catalogs in a `Map` (loaded once, then cached)\n * - a per-locale signal counter so every `translate()` reading the signal\n * re-evaluates the moment a new catalog finishes loading\n *\n * Translations are looked up scope-first then root, per locale, and the locale\n * itself is tried as the full tag before the bare language underneath it — so\n * an app running `ru-RU` resolves against a catalog registered as `ru`, and a\n * regional catalog is never shadowed by a scope in the base language. For an\n * app that spells its locale one way, which is every app that existed before\n * the chain, the order is exactly what it always was.\n *\n * ## Which locale wins\n *\n * ngwr has three locale inputs and they used to be three unrelated answers — an\n * app that set `LOCALE_ID: 'ru-RU'` correctly still rendered an English\n * calendar, because the date token defaulted to `navigator.language`. The\n * precedence is now stated, highest first:\n *\n * 1. **A subsystem's own explicit option.** `withDates({ locale })` pins\n * dates; `provideWrI18n({ defaultLocale })` pins the catalog. The most\n * specific statement wins, because it can only have been deliberate.\n * 2. **`WrI18n.locale()` — the runtime value.** The only one of the three that\n * can change without a reload, so it is what a language switcher writes.\n * With `provideWrI18n()` in the app, dates are written in it.\n * 3. **`LOCALE_ID`.** Angular's app-wide constant, and the seed for both of the\n * above when neither was given. One statement, one answer.\n * 4. `'en-US'`, which is what `LOCALE_ID` itself falls back to.\n *\n * `navigator.language` is deliberately NOT in that list. It is the browser's\n * preference, not the application's, and reading it made prerendered output and\n * the hydrated page disagree.\n *\n * **What a runtime switch reaches, and what it does not.** `use()` repaints\n * every catalog string, and every date: the date adapter, and so\n * `wr-calendar`, `wr-date-picker`, `wrDate` and `wr-date-stamp`, formats in\n * this locale unless `withDates({ locale })` pinned another. It does not move\n * `LOCALE_ID`, which is a constant, so anything keyed on it — `wrNumber` /\n * `wrPlural`, `wr-input-number`, `wr-statistic`, `wr-counter` — stays where it\n * was. `use()` says so once in dev mode rather than leaving it to be\n * discovered.\n *\n * @example\n * ```ts\n * const i18n = inject(WrI18n);\n * i18n.use('ru'); // switch locale\n * i18n.t('cart.checkout'); // → 'Оформить заказ'\n * i18n.t('greeting', { name: 'Ada' }); // → 'Hello, Ada!'\n * i18n.t(`types.${type}`, undefined, { fallback: type }); // → type, when no key\n *\n * effect(() => console.log(i18n.translate('hi')())); // re-runs on locale change\n * ```\n *\n * @see https://ngwr.dev/reference/services/i18n\n */\n@Service()\nexport class WrI18n {\n private readonly config = inject(WR_I18N_CONFIG);\n private readonly loader = inject(WR_I18N_LOADER);\n private readonly storage = inject(WrStorage);\n\n /**\n * Angular's own locale. Read for the dev-mode drift warning only — the\n * resolved default already folded it in through `WR_I18N_CONFIG`. @internal\n */\n private readonly localeId = inject(LOCALE_ID);\n\n /**\n * Catalogs registered via `provideWrI18nBaseCatalogs()` — the floor under the\n * loader's own catalogs, so ngwr's built-in strings survive an app that only\n * ships its own keys. @internal\n */\n private readonly baseCatalogs = inject(WR_I18N_BASE_CATALOGS, { optional: true }) ?? [];\n\n /** Per-(locale,scope) catalogs, populated by `loadCatalog`. @internal */\n private readonly catalogs = new Map<string, WrI18nCatalog>();\n\n /** Bumped after each catalog write so reactive translates recompute. @internal */\n private readonly revision = signal(0);\n\n /** In-flight load promises — dedupes parallel `t()` callers. @internal */\n private readonly inflight = new Map<string, Promise<WrI18nCatalog>>();\n\n /** Keys whose last load failed: `t()` does not retry them, `use()` and `registerScope()` do. @internal */\n private readonly failed = new Set<string>();\n\n /** Registered scopes — auto-loaded whenever the locale changes. @internal */\n private readonly scopes = new Set<string>();\n\n /** Active locale. Writes go through `use()` so storage stays in sync. */\n private readonly _locale = signal<string>(this.initialLocale());\n readonly locale: Signal<string> = this._locale.asReadonly();\n\n constructor() {\n // Eagerly load the root catalog + every registered scope for the\n // current locale. Subsequent locale changes refire the same effect.\n effect(() => {\n const lc = this._locale();\n void this.loadChain(lc, null);\n for (const sc of this.scopes) void this.loadChain(lc, sc);\n });\n }\n\n // Locale\n\n /**\n * Switch active locale. Ignored when not whitelisted.\n *\n * Text and dates — see the class docs for what a runtime switch cannot reach. The\n * dev-mode warning below is the whole reporting of that limit; without it the\n * failure is a screen showing German labels beside `1,234.5`, with nothing\n * anywhere saying why.\n */\n use(locale: string): void {\n if (!this.config.availableLocales.includes(locale)) return;\n const previous = this._locale();\n this._locale.set(locale);\n if (this.config.storageKey) this.storage.set(this.config.storageKey, locale);\n void this.loadChain(locale, null);\n for (const sc of this.scopes) void this.loadChain(locale, sc);\n if (isDevMode() && previous !== locale) this.warnOnLocaleIdDrift(locale);\n }\n\n /** Available locales — pass-through from config. */\n available(): readonly string[] {\n return this.config.availableLocales;\n }\n\n // Scopes\n\n /**\n * Register a scope so its catalog loads alongside the root one. Idempotent.\n * Returns a promise resolving once the current locale's scope catalog is in\n * the cache — handy for feature `canActivate` guards.\n */\n registerScope(scope: string): Promise<WrI18nCatalog> {\n this.scopes.add(scope);\n const lc = this._locale();\n // Resolve on the exact tag: the promise is what a `canActivate` waits on,\n // and the base-language catalog is only ever a fallback under it.\n const exact = this.loadCatalog(lc, scope);\n void this.loadChain(lc, scope);\n return exact;\n }\n\n // Translate\n\n /**\n * Eager translate — returns the current value or the missing-handler\n * fallback. Does NOT auto-load missing catalogs; combine with the\n * reactive `translate(...)` if you want load-on-demand.\n *\n * The third argument is a scope, or `{ scope, fallback }`. With a `fallback`\n * a missing key returns it as is, not interpolated, and `missingHandler` is\n * not called: for a key built from a server value that may have no\n * translation.\n */\n t(key: string, params?: WrI18nParams, scopeOrOptions?: string | WrI18nTranslateOptions): string {\n // Read revision so callers inside computed/effect re-run on updates.\n this.revision();\n const lc = this._locale();\n const options = typeof scopeOrOptions === 'string' ? { scope: scopeOrOptions } : scopeOrOptions;\n const scope = options?.scope;\n\n const chain = localeChain(lc);\n let hit: string | null = null;\n for (const candidate of chain) {\n if (scope) hit = walk(this.catalogs.get(cacheKey(candidate, scope)) ?? null, key);\n hit ??= walk(this.catalogs.get(cacheKey(candidate, null)) ?? null, key);\n if (hit !== null) break;\n }\n // Base catalogs are the floor: consulted only once the loader's own catalogs\n // have missed, so an app's keys always win, but ngwr's built-in strings are\n // still there when the app's catalog doesn't carry them.\n hit ??= this.walkBase(chain, key);\n\n if (hit === null) {\n // Fire a background load so a future read can resolve it.\n void this.loadChain(lc, scope ?? null, true);\n return options?.fallback ?? this.config.missingHandler(key, lc);\n }\n return wrInterpolate(hit, params);\n }\n\n /** Reactive translate — re-evaluates on locale or catalog updates. */\n translate(key: string, params?: WrI18nParams, scopeOrOptions?: string | WrI18nTranslateOptions): Signal<string> {\n return computed(() => this.t(key, params, scopeOrOptions));\n }\n\n // Internals\n\n /**\n * Look a key up in the registered base catalogs, later contributions first so\n * a feature can shadow an earlier one.\n */\n private walkBase(chain: readonly string[], key: string): string | null {\n for (const locale of chain) {\n for (let i = this.baseCatalogs.length - 1; i >= 0; i--) {\n const hit = walk(this.baseCatalogs[i][locale] ?? null, key);\n if (hit !== null) return hit;\n }\n }\n return null;\n }\n\n private initialLocale(): string {\n if (this.config.storageKey) {\n const saved = this.storage.get<string>(this.config.storageKey);\n if (saved && this.config.availableLocales.includes(saved)) return saved;\n }\n return this.config.defaultLocale;\n }\n\n /**\n * Load a `(locale, scope)` catalog and, when the locale carries a region, the\n * bare-language one under it. Both go in the cache; `t()` reads them in that\n * order.\n */\n private loadChain(locale: string, scope: string | null, auto = false): Promise<unknown> {\n return Promise.all(localeChain(locale).map(candidate => this.loadCatalog(candidate, scope, auto)));\n }\n\n /** One warning per service, not one per switch. @internal */\n private warnedLocaleIdDrift = false;\n\n /**\n * Say once, in dev, that a runtime switch moved the text and nothing else.\n *\n * The mismatch is otherwise invisible in the way that costs the most time:\n * the catalog strings and the dates all change, which reads as \"the switch\n * worked\", and the numbers beside them are still correct-looking output in\n * the old locale. Silent when the new locale IS `LOCALE_ID`, because then nothing is\n * out of step and a warning that fires when everything agrees is one people\n * learn to ignore. Production builds drop the call entirely via `isDevMode()`\n * tree-shaking.\n */\n private warnOnLocaleIdDrift(locale: string): void {\n if (this.warnedLocaleIdDrift || locale === this.localeId) return;\n this.warnedLocaleIdDrift = true;\n // eslint-disable-next-line no-console -- dev-mode validation\n console.warn(\n `[NGWR] WrI18n.use('${locale}') switched the catalog, but LOCALE_ID is still '${this.localeId}'. ` +\n `Dates follow the switch (wrDate, wr-calendar, wr-date-picker), unless withDates({ locale }) pinned ` +\n `them. LOCALE_ID is an Angular constant, so formatted numbers do not and stay on '${this.localeId}': ` +\n `the wrNumber / wrPlural pipes, wr-input-number, wr-statistic, wr-counter, wr-pagination's total ` +\n `and wr-file-upload's sizes. Reload the app with the new LOCALE_ID to move those.`\n );\n }\n\n private loadCatalog(locale: string, scope: string | null, auto = false): Promise<WrI18nCatalog> {\n const ck = cacheKey(locale, scope);\n const cached = this.catalogs.get(ck);\n if (cached) return Promise.resolve(cached);\n if (auto && this.failed.has(ck)) return Promise.resolve({});\n\n const pending = this.inflight.get(ck);\n if (pending) return pending;\n\n const stream: Observable<WrI18nCatalog> = this.loader.load(locale, scope);\n const promise = firstValueFrom(stream)\n .then(catalog => {\n this.failed.delete(ck);\n this.catalogs.set(ck, catalog);\n this.revision.update(v => v + 1);\n return catalog;\n })\n .catch((err: unknown) => {\n // eslint-disable-next-line no-console -- intentional diagnostic for missing catalog\n console.warn(`[ngwr/i18n] failed to load (${locale}, ${scope ?? 'root'})`, err);\n this.failed.add(ck);\n const empty: WrI18nCatalog = {};\n return empty;\n })\n .finally(() => {\n this.inflight.delete(ck);\n });\n\n this.inflight.set(ck, promise);\n return promise;\n }\n}\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { Pipe, type PipeTransform, inject } from '@angular/core';\n\nimport { WrI18n } from './i18n';\nimport { type WrI18nParams, type WrI18nTranslateOptions } from './i18n-config';\n\n/**\n * Translate a key. Impure — re-evaluates on every CD so locale switches\n * and catalog loads propagate without a manual refresh.\n *\n * @example\n * ```html\n * <h1>{{ 'home.title' | wrT }}</h1>\n * <p>{{ 'greeting' | wrT: { name: user().name } }}</p>\n * <button>{{ 'forms.save' | wrT: null : 'checkout' }}</button>\n * <span>{{ 'types.' + type | wrT: null : { fallback: type } }}</span>\n * ```\n */\n// eslint-disable-next-line @angular-eslint/no-pipe-impure -- intentional: locale + catalog updates must propagate even when args are stable\n@Pipe({ name: 'wrT', pure: false })\nexport class WrTPipe implements PipeTransform {\n private readonly i18n = inject(WrI18n);\n\n transform(key: string, params?: WrI18nParams | null, scopeOrOptions?: string | WrI18nTranslateOptions): string {\n return this.i18n.t(key, params ?? undefined, scopeOrOptions);\n }\n}\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { Directive, ElementRef, computed, effect, inject, input } from '@angular/core';\n\nimport { WrI18n } from './i18n';\nimport { type WrI18nParams } from './i18n-config';\n\n/**\n * Attribute directive that sets `textContent` of its host to the translation\n * of the bound key. Reactive — re-renders on locale + catalog changes.\n *\n * @example\n * ```html\n * <span [wrT]=\"'home.title'\"></span>\n * <span [wrT]=\"'greeting'\" [wrTParams]=\"{ name: user().name }\"></span>\n * <span [wrT]=\"'forms.save'\" wrTScope=\"checkout\"></span>\n * <span [wrT]=\"'types.' + type\" [wrTFallback]=\"type\"></span>\n * ```\n */\n@Directive({\n selector: '[wrT]',\n})\nexport class WrTDirective {\n /** Translation key. Required. */\n readonly wrT = input.required<string>();\n\n /** Interpolation params for `{{name}}` tokens. */\n readonly wrTParams = input<WrI18nParams | null>(null);\n\n /** Optional scope — scoped lookup first, then root fallback. */\n readonly wrTScope = input<string | null>(null);\n\n /** Text shown as is when the key is missing; `missingHandler` is not called. */\n readonly wrTFallback = input<string | null>(null);\n\n private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);\n private readonly i18n = inject(WrI18n);\n\n private readonly text = computed(() =>\n this.i18n.t(this.wrT(), this.wrTParams() ?? undefined, {\n scope: this.wrTScope() ?? undefined,\n fallback: this.wrTFallback(),\n })\n );\n\n constructor() {\n effect(() => {\n this.host.nativeElement.textContent = this.text();\n });\n }\n}\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { type Observable, of } from 'rxjs';\n\nimport { type WrI18nCatalog } from '../i18n-config';\nimport { type WrI18nLoader } from '../i18n-loader';\n\n/** Root catalogs keyed by locale: `{ en: catalog, ru: catalog, … }`. */\nexport type WrI18nStaticCatalogs = Readonly<Record<string, WrI18nCatalog>>;\n\n/** Per-scope catalogs: `{ checkout: { en: catalog, ru: catalog }, … }`. */\nexport type WrI18nStaticScopedCatalogs = Readonly<Record<string, WrI18nStaticCatalogs>>;\n\n/**\n * Loader for catalogs already in memory (imported from JSON or generated).\n *\n * - Pass `catalogs` for the root catalog of every locale.\n * - Pass `scopes` if you ship per-feature catalogs the loader should serve\n * to `WrI18n.registerScope(name)` calls.\n *\n * Missing locale or scope resolves to `{}` — the missing-key handler then\n * decides what to render.\n */\nexport class WrI18nStaticLoader implements WrI18nLoader {\n constructor(\n private readonly catalogs: WrI18nStaticCatalogs,\n private readonly scopes: WrI18nStaticScopedCatalogs = {}\n ) {}\n\n load(locale: string, scope: string | null): Observable<WrI18nCatalog> {\n if (scope === null) return of(this.catalogs[locale] ?? {});\n return of(this.scopes[scope]?.[locale] ?? {});\n }\n}\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { HttpClient } from '@angular/common/http';\nimport { inject } from '@angular/core';\n\nimport { type Observable } from 'rxjs';\n\nimport { type WrI18nCatalog } from '../i18n-config';\nimport { type WrI18nLoader } from '../i18n-loader';\n\n/** Configuration for {@link WrI18nHttpLoader}. */\nexport interface WrI18nHttpLoaderConfig {\n /**\n * URL template. Tokens:\n * - `{locale}` — required, BCP-47 tag (e.g. `en`).\n * - `{scope}` — optional, scope name. Use the `rootPath` if you need a\n * different path entirely for the root catalog.\n *\n * @example\n * ```ts\n * { path: '/assets/i18n/{locale}.json' } // root only\n * { path: '/assets/i18n/{scope}/{locale}.json',\n * rootPath: '/assets/i18n/{locale}.json' } // root + scopes\n * ```\n */\n readonly path: string;\n /** Path template for the root catalog. Defaults to `path`. */\n readonly rootPath?: string;\n}\n\n/**\n * Loader that fetches catalogs via `HttpClient`. A failure errors the stream;\n * the service logs it, serves the key and retries on the next `use()`.\n */\nexport class WrI18nHttpLoader implements WrI18nLoader {\n private readonly http = inject(HttpClient);\n\n constructor(private readonly config: WrI18nHttpLoaderConfig) {}\n\n load(locale: string, scope: string | null): Observable<WrI18nCatalog> {\n const template = scope === null ? (this.config.rootPath ?? this.config.path) : this.config.path;\n const url = template.replaceAll('{locale}', locale).replaceAll('{scope}', scope ?? '');\n return this.http.get<WrI18nCatalog>(url);\n }\n}\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport {\n ApplicationRef,\n EnvironmentInjector,\n type EnvironmentProviders,\n type Provider,\n inject,\n makeEnvironmentProviders,\n provideEnvironmentInitializer,\n} from '@angular/core';\n\nimport { WR_LIVE_LOCALE } from 'ngwr/utils';\n\nimport { WrI18n } from './i18n';\nimport { WR_I18N_BASE_CATALOGS, type WrI18nBaseCatalogs } from './i18n-base-catalogs';\nimport {\n DEFAULT_WR_I18N_CONFIG,\n WR_I18N_CONFIG,\n type WrI18nConfig,\n type WrI18nConfigResolved,\n resolveWrI18nLocales,\n} from './i18n-config';\nimport { WR_I18N_LOADER, type WrI18nLoader } from './i18n-loader';\nimport { WrI18nHttpLoader, type WrI18nHttpLoaderConfig } from './loaders/http-loader';\nimport {\n WrI18nStaticLoader,\n type WrI18nStaticCatalogs,\n type WrI18nStaticScopedCatalogs,\n} from './loaders/static-loader';\n\n/**\n * Configure {@link WrI18n}. Either pass a `loader` directly, or use the\n * `provideWrI18nHttpLoader` / `provideWrI18nStaticLoader` helpers in the\n * same providers array.\n */\nexport interface ProvideWrI18nOptions extends WrI18nConfig {\n readonly loader?: WrI18nLoader;\n}\n\n/**\n * Configure {@link WrI18n} for the application.\n *\n * Call it in the application's root providers (`bootstrapApplication` or\n * `ApplicationConfig`), together with {@link provideWrI18nBaseCatalogs} and the\n * loader. `WrI18n` is a root service: a route's `providers` or a lazy module\n * never reach it, so a locale or catalogs given there do nothing, and dev mode\n * warns. A lazy area switches the language at runtime with\n * `inject(WrI18n).use('de')`, for example in its resolver. The switch is\n * app-wide, and the locale must be in the root `availableLocales`. The area's\n * own keys load with `registerScope()`.\n */\nexport function provideWrI18n(options: ProvideWrI18nOptions = {}): EnvironmentProviders {\n const { loader, ...config } = options;\n\n const providers: (Provider | EnvironmentProviders)[] = [\n {\n provide: WR_I18N_CONFIG,\n // A factory rather than a value: `defaultLocale` falls back to `LOCALE_ID`,\n // which only an injection context can read.\n useFactory: (): WrI18nConfigResolved => ({\n ...DEFAULT_WR_I18N_CONFIG,\n ...config,\n ...resolveWrI18nLocales(config),\n }),\n },\n ];\n if (loader) providers.push({ provide: WR_I18N_LOADER, useValue: loader });\n // What `ngwr/date` formats in, so dates follow `use()` without importing this entry point.\n providers.push({ provide: WR_LIVE_LOCALE, useFactory: () => inject(WrI18n).locale });\n\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n providers.push(\n provideEnvironmentInitializer(() => {\n const here = inject(EnvironmentInjector);\n if (here === inject(ApplicationRef, { optional: true })?.injector) return;\n // An injector that lists WrI18n itself owns an instance that does read this config.\n if (here.get(WrI18n, null, { self: true })) return;\n // eslint-disable-next-line no-console -- dev-mode validation\n console.warn(\n '[NGWR] provideWrI18n() is in a route or child injector. WrI18n is a root service, so this ' +\n \"configuration is ignored. Move provideWrI18n() and the catalogs to the application's root \" +\n 'providers, and switch a lazy area with inject(WrI18n).use(locale).'\n );\n })\n );\n }\n\n return makeEnvironmentProviders(providers);\n}\n\n/**\n * Provide a static loader — catalogs already in memory.\n *\n * A loader serves only the catalog you pass it, and ngwr registers none of its\n * own. Pass only your own keys here and register ngwr's catalogs with\n * {@link provideWrI18nBaseCatalogs} — not `{ ...wrRu, ...yours }`. A spread is\n * shallow, so any namespace you share with ngwr, e.g. `common`, `form`,\n * `table`, keeps only the keys of the side spread last, and the other side's\n * keys stop resolving with nothing logged: ngwr's components fall back to their\n * English defaults, and a `wrT` read of a lost key renders the raw key under the\n * default missing handler.\n *\n * @param catalogs Root catalogs keyed by locale.\n * @param scopes Optional per-scope catalogs served to `registerScope(name)`.\n */\nexport function provideWrI18nStaticLoader(\n catalogs: WrI18nStaticCatalogs,\n scopes?: WrI18nStaticScopedCatalogs\n): Provider {\n return { provide: WR_I18N_LOADER, useValue: new WrI18nStaticLoader(catalogs, scopes) };\n}\n\n/**\n * Register catalogs consulted *underneath* the loader — this is how ngwr's own\n * built-in strings survive when you supply your own catalogs.\n *\n * A loader replaces the catalog for a locale instead of extending it, so a JSON\n * file holding only your keys leaves every built-in label on its hardcoded\n * English fallback, with nothing logged. One line fixes it, on either loader:\n *\n * @example\n * ```ts\n * import { wrRu } from 'ngwr/i18n/ru';\n *\n * providers: [\n * provideWrI18n({ defaultLocale: 'ru', availableLocales: ['ru'] }),\n * provideWrI18nBaseCatalogs({ ru: wrRu }),\n * provideWrI18nHttpLoader({ path: '/assets/i18n/{locale}.json' }),\n * ]\n * ```\n *\n * Pass only the locales you ship — the ones you leave out stay out of the\n * bundle. Your own keys always win; this is a floor, not an override.\n *\n * Use it instead of spreading `wrRu` into your own catalog, too: the lookup\n * walks these key by key after the loader's catalog misses, so a namespace both\n * define keeps both halves, where a shallow spread keeps only one.\n */\nexport function provideWrI18nBaseCatalogs(catalogs: WrI18nBaseCatalogs): Provider {\n return { provide: WR_I18N_BASE_CATALOGS, useValue: catalogs, multi: true };\n}\n\n/** Provide an HTTP loader — catalogs fetched from URLs. Requires `provideHttpClient`. */\nexport function provideWrI18nHttpLoader(config: WrI18nHttpLoaderConfig): Provider {\n return { provide: WR_I18N_LOADER, useFactory: () => new WrI18nHttpLoader(config) };\n}\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { type Signal, computed, inject, signal } from '@angular/core';\n\nimport { WrI18n, wrInterpolate } from './i18n';\nimport type { WrI18nParams } from './i18n-config';\n\n/** What `WrI18n.t` returns on a miss here: it skips `missingHandler`, and no catalog holds this. */\nconst MISS = '\\u0000wr-i18n-miss';\n\n/**\n * Helper for component default text. Returns a reactive string that:\n *\n * 1. Prefers the consumer's override (an `input<string | null>()` value).\n * 2. Falls back to the i18n catalog under `key` — re-renders on locale\n * change so a switcher updates the DOM live.\n * 3. Falls back to `fallback` when no `WrI18n` is provided OR the catalog\n * is missing the key.\n *\n * Components don't need a hard dependency on `provideWrI18n` — without it,\n * the fallback is returned and everything still works.\n *\n * @example\n * ```ts\n * readonly emptyText = input<string | null>(null);\n * protected readonly empty = useI18nText(this.emptyText, 'table.empty', 'No data');\n *\n * // In template: <div>{{ empty() }}</div>\n * ```\n */\nexport function useI18nText(binding: Signal<string | null | undefined>, key: string, fallback: string): Signal<string> {\n const i18n = inject(WrI18n, { optional: true });\n if (!i18n) {\n return computed(() => {\n const v = binding();\n return v ?? fallback;\n });\n }\n\n return computed(() => {\n const v = binding();\n if (v !== null && v !== undefined && v !== '') return v;\n // A miss answers the sentinel, so a custom `missingHandler` never sees a built-in key.\n const translated = i18n.t(key, undefined, { fallback: MISS });\n return translated === MISS ? fallback : translated;\n });\n}\n\n/**\n * {@link useI18nText} without a binding to forward — for a built-in string the\n * component exposes no override input for. Same reactivity, same fallback\n * rules; the only difference is the missing first argument.\n *\n * It used to return a plain `string`, resolved once at injection time, and\n * that was wrong in the ordinary case rather than an edge one: `WrI18n` writes\n * every loader-backed catalog from `firstValueFrom(...).then(...)`, so even a\n * static loader serving an object literal lands a microtask AFTER the first\n * change-detection pass. Every component built in that pass read an empty\n * catalog and froze its English fallback for the life of the app — in one\n * `<wr-date-picker>` the field said \"Открыть календарь\" and the calendar\n * button beside it \"Open calendar\", off the same key.\n */\nexport function wrReadI18nText(key: string, fallback: string): Signal<string> {\n const i18n = inject(WrI18n, { optional: true });\n if (!i18n) return computed(() => fallback);\n\n return computed(() => {\n const v = i18n.t(key, undefined, { fallback: MISS });\n return v === MISS ? fallback : v;\n });\n}\n\n/** Tiny shim — useful when the caller doesn't have an `input` to forward. */\nexport function nullSignal(): Signal<null> {\n return signal(null).asReadonly();\n}\n\n/**\n * Build a per-call formatter for parametrized labels (e.g. ARIA labels\n * that interpolate a per-row value: `\"Remove {{label}}\"`). Returns a\n * function the template calls with the params for the current item.\n *\n * The returned function:\n * - Re-resolves the i18n catalog on every call (live locale switches just\n * work — re-rendered templates pick up new strings).\n * - Falls back to the literal `fallback` template with the same\n * `{{name}}` syntax when no `WrI18n` provider is present, or when the\n * key is missing.\n *\n * Use this for labels that vary per row. For static labels, prefer\n * {@link useI18nText} or {@link wrReadI18nText}.\n *\n * @example\n * ```ts\n * protected readonly removeChipLabel = useI18nFormatter('select.removeItem', 'Remove {{label}}');\n *\n * // In template:\n * // [attr.aria-label]=\"removeChipLabel({ label: chip.label })\"\n * ```\n */\nexport function useI18nFormatter(key: string, fallback: string): (params?: WrI18nParams) => string {\n const i18n = inject(WrI18n, { optional: true });\n if (!i18n) {\n return (params?: WrI18nParams) => wrInterpolate(fallback, params);\n }\n return (params?: WrI18nParams) => {\n const v = i18n.t(key, params, { fallback: MISS });\n return v === MISS ? wrInterpolate(fallback, params) : v;\n };\n}\n","/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { type Injector, inject } from '@angular/core';\n\nimport { WrI18n, wrInterpolate } from './i18n';\n\n/** The English catalog's `httpError`, for an app with no catalog registered. */\nconst FALLBACK: Readonly<Record<string, string>> = {\n network: 'No connection to the server. Check your network and try again.',\n 400: 'The server did not accept the data. Check the fields.',\n 401: 'Your session has ended. Sign in again.',\n 403: 'You do not have permission for this action.',\n 404: 'Not found. It may have been deleted.',\n 409: 'This conflicts with existing data. Refresh the page and try again.',\n 413: 'The data is too large to send.',\n 422: 'Some of the data is not valid. Check the fields.',\n 429: 'Too many requests. Try again in a moment.',\n 503: 'The server is unavailable. Try again in a minute.',\n '4xx': 'The request was refused. Error code: {{status}}.',\n '5xx': 'The server failed. Try again later. Error code: {{status}}.',\n unknown: 'Something went wrong. Try again later.',\n};\n\n/** Most specific first. */\nfunction catalogKeys(status: number | null): readonly string[] {\n if (status === null) return ['unknown'];\n if (status === 0) return ['network'];\n if (status >= 400 && status < 500) return [String(status), '4xx', 'unknown'];\n if (status >= 500 && status < 600) return [String(status), '5xx', 'unknown'];\n return [String(status), 'unknown'];\n}\n\nfunction serverMessage(error: unknown): string | null {\n const body = (error as { error?: unknown } | null | undefined)?.error;\n if (typeof body === 'string') {\n const text = body.trim();\n // A proxy answers with an HTML page, which is a string body too.\n return text === '' || text.startsWith('<') ? null : text;\n }\n const message = (body as { message?: unknown } | null | undefined)?.message;\n return typeof message === 'string' && message.trim() !== '' ? message.trim() : null;\n}\n\n/** A screen's own sentence for one status: the text, or a function of the error. */\nexport type WrHttpErrorOverride = string | ((error: unknown) => string);\n\n/** Options of {@link wrHttpErrorText}. */\nexport interface WrHttpErrorTextOptions {\n /** The screen's own sentence per status, `0` being a network failure. Wins over everything else. */\n readonly overrides?: Readonly<Partial<Record<number, WrHttpErrorOverride>>>;\n /**\n * Prefer the sentence the server put in the body: `error.error.message`, or\n * a body that is a plain string. For an API that writes its errors for the\n * person at the screen.\n * @default false\n */\n readonly serverMessage?: boolean;\n /** Where to read `WrI18n` from when the call is outside an injection context, such as a `catch`. */\n readonly injector?: Injector;\n}\n\n/**\n * The HTTP status of a failed request: of an `HttpErrorResponse`, a `Response`\n * or anything else carrying a numeric `status`. `0` is a request nothing\n * answered (offline, CORS, a dropped connection); `null` is a value that is not\n * an HTTP error at all.\n *\n * @example\n * ```ts\n * if (wrHttpStatus(error) === 401) void router.navigate(['/login']);\n * ```\n *\n * @see https://ngwr.dev/reference/utils/wr-http-error-text\n */\nexport function wrHttpStatus(error: unknown): number | null {\n const status = (error as { status?: unknown } | null | undefined)?.status;\n return typeof status === 'number' && Number.isInteger(status) && status >= 0 ? status : null;\n}\n\n/**\n * A sentence for a failed request, in the active language. Highest first:\n *\n * 1. `overrides[status]`, the screen's own wording.\n * 2. With `serverMessage`, the sentence in the response body.\n * 3. The catalog: `httpError.<status>`, then `httpError.4xx` / `httpError.5xx`\n * (both take `{{status}}`), `httpError.network` for status `0`, and\n * `httpError.unknown` for the rest. An app's own catalog wins over ngwr's,\n * and English is the floor when neither has the key.\n *\n * Call it in an injection context, or pass `injector` from a `catch` or a\n * callback.\n *\n * @example\n * ```ts\n * private readonly injector = inject(Injector);\n *\n * try {\n * await this.api.save(order);\n * } catch (error) {\n * this.toast.danger(\n * wrHttpErrorText(error, { injector: this.injector, overrides: { 409: 'This name is taken.' } })\n * );\n * }\n * ```\n *\n * @see https://ngwr.dev/reference/utils/wr-http-error-text\n */\nexport function wrHttpErrorText(error: unknown, options: WrHttpErrorTextOptions = {}): string {\n const status = wrHttpStatus(error);\n\n const override = status === null ? undefined : options.overrides?.[status];\n if (override !== undefined) return typeof override === 'function' ? override(error) : override;\n\n if (options.serverMessage && status !== null) {\n const said = serverMessage(error);\n if (said !== null) return said;\n }\n\n const i18n = options.injector ? options.injector.get(WrI18n, null) : inject(WrI18n, { optional: true });\n const keys = catalogKeys(status);\n const params = { status };\n\n for (const key of keys) {\n const hit = i18n?.t(`httpError.${key}`, params, { fallback: '' });\n if (hit) return hit;\n }\n for (const key of keys) {\n if (key in FALLBACK) return wrInterpolate(FALLBACK[key], params);\n }\n return FALLBACK['unknown'];\n}\n"],"mappings":";;;;;;;;;;;;AAgCA,MAAa,wBAAwB,IAAI,eAA8C,uBAAuB;;;;;;;ACiD9G,MAAa,yBAA2F;CACtG,YAAY;CACZ,iBAAgB,QAAO;AACxB;AAMD,SAAgB,qBACd,QAAoB;CAEpB,MAAM,gBAAgB,OAAO,iBAAiB,OAAO,SAAS;CAC9D,OA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U,KAAI,CAAE;CACtG,MAAM,OAAO,YAAY,MAAM;CAC/B,MAAM,SAAS,EAAE,OAAM;CAEvB,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,MAAM,MAAM,EAAE,aAAa,OAAO,QAAQ,EAAE,UAAU,GAAE,CAAE;EAChE,IAAI,KAAK,OAAO;CAClB;CACA,KAAK,MAAM,OAAO,MAChB,IAAI,OAAO,UAAU,OAAO,cAAc,SAAS,MAAM,MAAM;CAEjE,OAAO,SAAS;AAClB"}
|
|
@@ -69,6 +69,22 @@ var WrImageCropperHarness = class WrImageCropperHarness extends ComponentHarness
|
|
|
69
69
|
const keys = ARROWS[arrow];
|
|
70
70
|
await (modifiers.alt || modifiers.shift ? window_.sendKeys(modifiers, keys) : window_.sendKeys(keys));
|
|
71
71
|
}
|
|
72
|
+
async getZoom() {
|
|
73
|
+
return (await this.viewTransform("getZoom")).zoom;
|
|
74
|
+
}
|
|
75
|
+
async getRotation() {
|
|
76
|
+
return (await this.viewTransform("getRotation")).rotation;
|
|
77
|
+
}
|
|
78
|
+
async zoomIn() {
|
|
79
|
+
await (await this.requireReady("zoomIn")).sendKeys("+");
|
|
80
|
+
}
|
|
81
|
+
async zoomOut() {
|
|
82
|
+
await (await this.requireReady("zoomOut")).sendKeys("-");
|
|
83
|
+
}
|
|
84
|
+
async rotate(direction = "cw") {
|
|
85
|
+
const window_ = await this.requireReady("rotate");
|
|
86
|
+
await (direction === "ccw" ? window_.sendKeys({ shift: true }, "r") : window_.sendKeys("r"));
|
|
87
|
+
}
|
|
72
88
|
async getCropWindowLabel() {
|
|
73
89
|
return (await this.requireReady("getCropWindowLabel")).getAttribute("aria-label");
|
|
74
90
|
}
|
|
@@ -77,6 +93,23 @@ var WrImageCropperHarness = class WrImageCropperHarness extends ComponentHarness
|
|
|
77
93
|
const status = await this.locatorForOptional("[role=\"status\"]")();
|
|
78
94
|
return status ? status.text() : "";
|
|
79
95
|
}
|
|
96
|
+
async viewTransform(method) {
|
|
97
|
+
await this.requireReady(method);
|
|
98
|
+
const transform = await (await this.locatorFor(".wr-image-cropper__image")()).getCssValue("transform");
|
|
99
|
+
const matrix = /^matrix\(([^)]+)\)/.exec(transform)?.[1].split(",").map(Number);
|
|
100
|
+
if (matrix) {
|
|
101
|
+
const [a, b] = matrix;
|
|
102
|
+
const turn = Math.round(Math.atan2(b, a) * 180 / Math.PI / 90) * 90;
|
|
103
|
+
return {
|
|
104
|
+
zoom: Math.round(Math.hypot(a, b) * 1e3) / 1e3,
|
|
105
|
+
rotation: (turn + 360) % 360
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
return {
|
|
109
|
+
zoom: Number(/scale\(([\d.]+)\)/.exec(transform)?.[1] ?? 1),
|
|
110
|
+
rotation: Number(/rotate\((\d+)deg\)/.exec(transform)?.[1] ?? 0)
|
|
111
|
+
};
|
|
112
|
+
}
|
|
80
113
|
async requireReady(method) {
|
|
81
114
|
const window_ = await this.cropWindow();
|
|
82
115
|
if (window_) return window_;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ngwr-image-cropper-testing.mjs","names":[],"sources":["../../../projects/lib/image-cropper/testing/wr-image-cropper-harness.ts"],"sourcesContent":["/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { ComponentHarness, HarnessPredicate, TestKey, type TestElement } from '@angular/cdk/testing';\n\nimport type { WrCropHandle } from 'ngwr/image-cropper';\n\nimport type { WrImageCropperHarnessFilters } from './types';\n\nconst ARROWS = {\n left: TestKey.LEFT_ARROW,\n right: TestKey.RIGHT_ARROW,\n up: TestKey.UP_ARROW,\n down: TestKey.DOWN_ARROW,\n} as const;\n\n/** The four directions the crop window's keyboard model understands. */\nexport type WrCropArrow = keyof typeof ARROWS;\n\n/** Where the crop window sits over the DISPLAYED image, in CSS pixels. */\nexport interface WrCropWindowBox {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * Test harness for `<wr-image-cropper>`.\n *\n * **This is the smallest honest surface of any harness here, and the reason is worth\n * reading before you reach for a method that is not on it.** Almost everything the\n * cropper does is measured: it reads the `<img>`'s rendered box and its\n * `naturalWidth`, converts between display and source pixels, and moves the crop\n * window with pointer deltas. jsdom measures nothing — every rect is 0×0 and\n * `naturalWidth` is 0 — so an image never \"loads\", the crop UI never renders, and a\n * synthetic drag divides by zero. There is deliberately no drag method: it would\n * write `NaN` and report success.\n *\n * What a spec CAN do is give the image a box and a natural size itself, then call\n * {@link dispatchImageLoad} — the two numbers `onImageLoad` reads are the whole\n * stub, and from there {@link getCropBox} and {@link getHandles} are real answers,\n * because the component writes the crop window's geometry as inline pixels. The\n * KEYBOARD path needs the same stub to get the crop UI up, but nothing beyond it:\n * its step is a constant rather than a pointer delta, so {@link pressArrow} lands\n * on a number a spec can name.\n *\n * ```ts\n * // In your spec, before dispatching the load:\n * const img = fixture.nativeElement.querySelector('.wr-image-cropper__image');\n * img.getBoundingClientRect = () => ({ width: 400, height: 400, x: 0, y: 0 }) as DOMRect;\n * Object.defineProperty(img, 'naturalWidth', { value: 800 });\n * Object.defineProperty(img, 'naturalHeight', { value: 800 });\n * ```\n *\n * **There is nothing to click.** The cropper renders no buttons: the result\n * arrives on the `(cropped)` output, which emits a `Blob` after each drag end or\n * each run of arrow keys, and a consumer who wants a one-off read calls `toBlob()` /\n * `toDataUrl()` — or `cropRect()` for the geometry — on the component through a\n * `viewChild`. The same goes for `(loadError)` and `status()`, which is why\n * {@link isFailed} reads the failure off the host class instead. Outputs and instance\n * members are component API rather than DOM, so all of it is outside what a harness\n * can reach at all, which is worth knowing rather than discovering.\n *\n * @example\n * ```ts\n * const cropper = await loader.getHarness(WrImageCropperHarness);\n *\n * expect(await cropper.isEmpty()).toBe(false);\n * expect(await cropper.isReady()).toBe(false); // nothing measured yet\n *\n * await cropper.dispatchImageLoad();\n * expect(await cropper.getCropBox()).toEqual({ x: 80, y: 80, width: 240, height: 240 });\n * ```\n *\n * @see https://ngwr.dev/guides/testing\n */\nexport class WrImageCropperHarness extends ComponentHarness {\n static hostSelector = 'wr-image-cropper';\n\n /** Build a predicate that narrows the query — pass to `getHarness` / `getAllHarnesses`. */\n static with(options: WrImageCropperHarnessFilters = {}): HarnessPredicate<WrImageCropperHarness> {\n return new HarnessPredicate(WrImageCropperHarness, options).addOption(\n 'empty',\n options.empty,\n async (harness, empty) => (await harness.isEmpty()) === empty\n );\n }\n\n private readonly image = this.locatorForOptional('.wr-image-cropper__image');\n private readonly cropWindow = this.locatorForOptional('.wr-image-cropper__window');\n\n /** Whether the cropper has no source at all, and is showing its placeholder. */\n async isEmpty(): Promise<boolean> {\n return (await this.locatorForOptional('.wr-image-cropper__empty')()) !== null;\n }\n\n /** The placeholder's text, or `null` when there is an image. Comes from the catalog. */\n async getEmptyText(): Promise<string | null> {\n const empty = await this.locatorForOptional('.wr-image-cropper__empty')();\n return empty ? empty.text() : null;\n }\n\n /**\n * Whether the crop UI is up.\n *\n * Not the same question as {@link isEmpty}: a cropper with a perfectly good `src`\n * shows nothing but the image until it has been MEASURED, because the window's size\n * is a fraction of the rendered box. In a browser that happens on load; in a unit\n * test it happens when the spec stubs the box and calls\n * {@link dispatchImageLoad}.\n */\n async isReady(): Promise<boolean> {\n return (await this.cropWindow()) !== null;\n }\n\n /**\n * What the `<img>` is pointing at.\n *\n * A `File` or `Blob` source becomes an object URL, so this is `blob:…` for those\n * and the plain string for a string `src`. Comparing the two is not useful; asking\n * whether it CHANGED is.\n */\n async getImageSrc(): Promise<string | null> {\n const image = await this.image();\n return image ? image.getProperty<string>('src') : null;\n }\n\n /**\n * Fire the image's `load` event.\n *\n * The event, not a real load: jsdom fetches nothing, and the handler reads\n * `getBoundingClientRect()` and `naturalWidth` off the element. Stub those first —\n * see this class's docs — or the crop window will still not render and\n * {@link isReady} will stay `false`, which is exactly what a real cropper does with\n * a zero-sized image.\n */\n async dispatchImageLoad(): Promise<void> {\n const image = await this.image();\n if (!image) {\n throw new Error(\n 'WrImageCropperHarness.dispatchImageLoad(): there is no image — the cropper has no `src`, so it is ' +\n 'showing its empty state.'\n );\n }\n await image.dispatchEvent('load');\n }\n\n /**\n * Fire the image's `error` event — what a browser does with a source it cannot\n * decode, and the only way to get one in a unit test, where nothing is decoded.\n *\n * Afterwards {@link isFailed} is `true` and the component has emitted\n * `(loadError)`; a spec that wants the payload binds that output on its host.\n */\n async dispatchImageError(): Promise<void> {\n const image = await this.image();\n if (!image) {\n throw new Error(\n 'WrImageCropperHarness.dispatchImageError(): there is no image — the cropper has no `src`, so it is ' +\n 'showing its empty state and there is nothing to fail.'\n );\n }\n await image.dispatchEvent('error');\n }\n\n /**\n * Whether the browser failed to decode the current source.\n *\n * Read off the `wr-image-cropper--failed` host modifier — the part of the failure\n * the DOM shows. It is a third answer beside {@link isEmpty} and {@link isReady},\n * not a combination of them: a failed cropper has a `src` (so it is not empty) and\n * no crop window (so it is not ready), which is also exactly what a cropper still\n * LOADING looks like. Asking those two would call a broken image a slow one.\n *\n * The component renders no message for it, so there is no text to read here; the\n * host's own message is the host's to assert.\n */\n async isFailed(): Promise<boolean> {\n return (await this.host()).hasClass('wr-image-cropper--failed');\n }\n\n /**\n * Where the crop window sits over the displayed image, in CSS pixels.\n *\n * From the inline styles the component writes — a measured box would be 0×0 — and\n * in DISPLAY pixels, which is not what a consumer receives: `cropRect()` converts\n * to the image's natural pixels, and that conversion is the component's own contract\n * rather than something the DOM shows.\n */\n async getCropBox(): Promise<WrCropWindowBox> {\n const window_ = await this.requireReady('getCropBox');\n return {\n x: Number.parseFloat(await window_.getCssValue('left')),\n y: Number.parseFloat(await window_.getCssValue('top')),\n width: Number.parseFloat(await window_.getCssValue('width')),\n height: Number.parseFloat(await window_.getCssValue('height')),\n };\n }\n\n /** The eight resize handles, by their compass suffix. Throws before the crop UI is up. */\n async getHandles(): Promise<WrCropHandle[]> {\n await this.requireReady('getHandles');\n const handles = await this.locatorForAll('.wr-image-cropper__handle')();\n\n return Promise.all(\n handles.map(async handle => {\n const classes = (await handle.getAttribute('class')) ?? '';\n const found = classes.split(/\\s+/).find(name => name.startsWith('wr-image-cropper__handle--'));\n return (found?.slice('wr-image-cropper__handle--'.length) ?? '') as WrCropHandle;\n })\n );\n }\n\n /** Whether the dimming backdrop with the cut-out is drawn. */\n async hasBackdrop(): Promise<boolean> {\n return (await this.locatorForOptional('.wr-image-cropper__backdrop')()) !== null;\n }\n\n /**\n * Press an arrow key on the crop window — one display pixel, or ten with\n * `shift`; `alt` resizes from the east / south edge instead of moving.\n *\n * Sent to the crop window, where the component listens, so it does not depend on\n * jsdom having managed to focus anything. `sendKeys` fires keyup as well as\n * keydown, which is what makes `(cropped)` emit — the component treats a run of\n * arrows as one gesture, the way a drag is one.\n */\n async pressArrow(arrow: WrCropArrow, modifiers: { alt?: boolean; shift?: boolean } = {}): Promise<void> {\n const window_ = await this.requireReady('pressArrow');\n const keys = ARROWS[arrow];\n await (modifiers.alt || modifiers.shift ? window_.sendKeys(modifiers, keys) : window_.sendKeys(keys));\n }\n\n /** The crop window's accessible name. Comes from the catalog. */\n async getCropWindowLabel(): Promise<string | null> {\n return (await this.requireReady('getCropWindowLabel')).getAttribute('aria-label');\n }\n\n /**\n * The last thing the live region announced — the crop rect in SOURCE pixels,\n * as `x, y, width × height`.\n *\n * Empty until a key has moved the crop: a pointer drag deliberately says nothing\n * (it would flood the region and the sighted user can see it), and the initial\n * crop is not news. Two questions, not one — {@link getCropBox} reads the window's\n * DISPLAY geometry, and a component that moved the box without announcing it\n * would still pass that one.\n */\n async getAnnouncement(): Promise<string> {\n await this.requireReady('getAnnouncement');\n const status = await this.locatorForOptional('[role=\"status\"]')();\n return status ? status.text() : '';\n }\n\n private async requireReady(method: string): Promise<TestElement> {\n const window_ = await this.cropWindow();\n if (window_) return window_;\n\n throw new Error(\n `WrImageCropperHarness.${method}(): the crop window is not rendered. The cropper sizes it from the ` +\n \"image's MEASURED box, and a unit test has none — give the <img> a `getB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IAAI,SAAS,OAAO;EAEpB,MAAM,IAAI,MACR,yBAAyB,OAAM,sNAEmB;CAEtD"}
|
|
1
|
+
{"version":3,"file":"ngwr-image-cropper-testing.mjs","names":[],"sources":["../../../projects/lib/image-cropper/testing/wr-image-cropper-harness.ts"],"sourcesContent":["/**\n * @license\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://github.com/thekhegay/ngwr/blob/main/LICENSE\n */\n\nimport { ComponentHarness, HarnessPredicate, TestKey, type TestElement } from '@angular/cdk/testing';\n\nimport type { WrCropHandle, WrImageRotation } from 'ngwr/image-cropper';\n\nimport type { WrImageCropperHarnessFilters } from './types';\n\nconst ARROWS = {\n left: TestKey.LEFT_ARROW,\n right: TestKey.RIGHT_ARROW,\n up: TestKey.UP_ARROW,\n down: TestKey.DOWN_ARROW,\n} as const;\n\n/** The four directions the crop window's keyboard model understands. */\nexport type WrCropArrow = keyof typeof ARROWS;\n\n/** Where the crop window sits over the DISPLAYED image, in CSS pixels. */\nexport interface WrCropWindowBox {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * Test harness for `<wr-image-cropper>`.\n *\n * **This is the smallest honest surface of any harness here, and the reason is worth\n * reading before you reach for a method that is not on it.** Almost everything the\n * cropper does is measured: it reads the `<img>`'s rendered box and its\n * `naturalWidth`, converts between display and source pixels, and moves the crop\n * window with pointer deltas. jsdom measures nothing — every rect is 0×0 and\n * `naturalWidth` is 0 — so an image never \"loads\", the crop UI never renders, and a\n * synthetic drag divides by zero. There is deliberately no drag method: it would\n * write `NaN` and report success.\n *\n * What a spec CAN do is give the image a box and a natural size itself, then call\n * {@link dispatchImageLoad} — the two numbers `onImageLoad` reads are the whole\n * stub, and from there {@link getCropBox} and {@link getHandles} are real answers,\n * because the component writes the crop window's geometry as inline pixels. The\n * KEYBOARD path needs the same stub to get the crop UI up, but nothing beyond it:\n * its step is a constant rather than a pointer delta, so {@link pressArrow} lands\n * on a number a spec can name.\n *\n * ```ts\n * // In your spec, before dispatching the load:\n * const img = fixture.nativeElement.querySelector('.wr-image-cropper__image');\n * img.getBoundingClientRect = () => ({ width: 400, height: 400, x: 0, y: 0 }) as DOMRect;\n * Object.defineProperty(img, 'naturalWidth', { value: 800 });\n * Object.defineProperty(img, 'naturalHeight', { value: 800 });\n * ```\n *\n * Zoom and rotation are keys on the crop window too, so {@link zoomIn},\n * {@link zoomOut} and {@link rotate} are real, and {@link getZoom} and\n * {@link getRotation} read the transform the component writes on the picture. The\n * wheel, the pinch and the pan are pointer geometry, and are not here.\n *\n * **There is nothing to click.** The cropper renders no buttons: the result\n * arrives on the `(cropped)` output, which emits a `Blob` after each drag end or\n * each run of arrow keys, and a consumer who wants a one-off read calls `toBlob()` /\n * `toDataUrl()` — or `cropRect()` for the geometry — on the component through a\n * `viewChild`. The same goes for `(loadError)` and `status()`, which is why\n * {@link isFailed} reads the failure off the host class instead. Outputs and instance\n * members are component API rather than DOM, so all of it is outside what a harness\n * can reach at all, which is worth knowing rather than discovering.\n *\n * @example\n * ```ts\n * const cropper = await loader.getHarness(WrImageCropperHarness);\n *\n * expect(await cropper.isEmpty()).toBe(false);\n * expect(await cropper.isReady()).toBe(false); // nothing measured yet\n *\n * await cropper.dispatchImageLoad();\n * expect(await cropper.getCropBox()).toEqual({ x: 80, y: 80, width: 240, height: 240 });\n * ```\n *\n * @see https://ngwr.dev/guides/testing\n */\nexport class WrImageCropperHarness extends ComponentHarness {\n static hostSelector = 'wr-image-cropper';\n\n /** Build a predicate that narrows the query — pass to `getHarness` / `getAllHarnesses`. */\n static with(options: WrImageCropperHarnessFilters = {}): HarnessPredicate<WrImageCropperHarness> {\n return new HarnessPredicate(WrImageCropperHarness, options).addOption(\n 'empty',\n options.empty,\n async (harness, empty) => (await harness.isEmpty()) === empty\n );\n }\n\n private readonly image = this.locatorForOptional('.wr-image-cropper__image');\n private readonly cropWindow = this.locatorForOptional('.wr-image-cropper__window');\n\n /** Whether the cropper has no source at all, and is showing its placeholder. */\n async isEmpty(): Promise<boolean> {\n return (await this.locatorForOptional('.wr-image-cropper__empty')()) !== null;\n }\n\n /** The placeholder's text, or `null` when there is an image. Comes from the catalog. */\n async getEmptyText(): Promise<string | null> {\n const empty = await this.locatorForOptional('.wr-image-cropper__empty')();\n return empty ? empty.text() : null;\n }\n\n /**\n * Whether the crop UI is up.\n *\n * Not the same question as {@link isEmpty}: a cropper with a perfectly good `src`\n * shows nothing but the image until it has been MEASURED, because the window's size\n * is a fraction of the rendered box. In a browser that happens on load; in a unit\n * test it happens when the spec stubs the box and calls\n * {@link dispatchImageLoad}.\n */\n async isReady(): Promise<boolean> {\n return (await this.cropWindow()) !== null;\n }\n\n /**\n * What the `<img>` is pointing at.\n *\n * A `File` or `Blob` source becomes an object URL, so this is `blob:…` for those\n * and the plain string for a string `src`. Comparing the two is not useful; asking\n * whether it CHANGED is.\n */\n async getImageSrc(): Promise<string | null> {\n const image = await this.image();\n return image ? image.getProperty<string>('src') : null;\n }\n\n /**\n * Fire the image's `load` event.\n *\n * The event, not a real load: jsdom fetches nothing, and the handler reads\n * `getBoundingClientRect()` and `naturalWidth` off the element. Stub those first —\n * see this class's docs — or the crop window will still not render and\n * {@link isReady} will stay `false`, which is exactly what a real cropper does with\n * a zero-sized image.\n */\n async dispatchImageLoad(): Promise<void> {\n const image = await this.image();\n if (!image) {\n throw new Error(\n 'WrImageCropperHarness.dispatchImageLoad(): there is no image — the cropper has no `src`, so it is ' +\n 'showing its empty state.'\n );\n }\n await image.dispatchEvent('load');\n }\n\n /**\n * Fire the image's `error` event — what a browser does with a source it cannot\n * decode, and the only way to get one in a unit test, where nothing is decoded.\n *\n * Afterwards {@link isFailed} is `true` and the component has emitted\n * `(loadError)`; a spec that wants the payload binds that output on its host.\n */\n async dispatchImageError(): Promise<void> {\n const image = await this.image();\n if (!image) {\n throw new Error(\n 'WrImageCropperHarness.dispatchImageError(): there is no image — the cropper has no `src`, so it is ' +\n 'showing its empty state and there is nothing to fail.'\n );\n }\n await image.dispatchEvent('error');\n }\n\n /**\n * Whether the browser failed to decode the current source.\n *\n * Read off the `wr-image-cropper--failed` host modifier — the part of the failure\n * the DOM shows. It is a third answer beside {@link isEmpty} and {@link isReady},\n * not a combination of them: a failed cropper has a `src` (so it is not empty) and\n * no crop window (so it is not ready), which is also exactly what a cropper still\n * LOADING looks like. Asking those two would call a broken image a slow one.\n *\n * The component renders no message for it, so there is no text to read here; the\n * host's own message is the host's to assert.\n */\n async isFailed(): Promise<boolean> {\n return (await this.host()).hasClass('wr-image-cropper--failed');\n }\n\n /**\n * Where the crop window sits over the displayed image, in CSS pixels.\n *\n * From the inline styles the component writes — a measured box would be 0×0 — and\n * in DISPLAY pixels, which is not what a consumer receives: `cropRect()` converts\n * to the image's natural pixels, and that conversion is the component's own contract\n * rather than something the DOM shows.\n */\n async getCropBox(): Promise<WrCropWindowBox> {\n const window_ = await this.requireReady('getCropBox');\n return {\n x: Number.parseFloat(await window_.getCssValue('left')),\n y: Number.parseFloat(await window_.getCssValue('top')),\n width: Number.parseFloat(await window_.getCssValue('width')),\n height: Number.parseFloat(await window_.getCssValue('height')),\n };\n }\n\n /** The eight resize handles, by their compass suffix. Throws before the crop UI is up. */\n async getHandles(): Promise<WrCropHandle[]> {\n await this.requireReady('getHandles');\n const handles = await this.locatorForAll('.wr-image-cropper__handle')();\n\n return Promise.all(\n handles.map(async handle => {\n const classes = (await handle.getAttribute('class')) ?? '';\n const found = classes.split(/\\s+/).find(name => name.startsWith('wr-image-cropper__handle--'));\n return (found?.slice('wr-image-cropper__handle--'.length) ?? '') as WrCropHandle;\n })\n );\n }\n\n /** Whether the dimming backdrop with the cut-out is drawn. */\n async hasBackdrop(): Promise<boolean> {\n return (await this.locatorForOptional('.wr-image-cropper__backdrop')()) !== null;\n }\n\n /**\n * Press an arrow key on the crop window — one display pixel, or ten with\n * `shift`; `alt` resizes from the east / south edge instead of moving.\n *\n * Sent to the crop window, where the component listens, so it does not depend on\n * jsdom having managed to focus anything. `sendKeys` fires keyup as well as\n * keydown, which is what makes `(cropped)` emit — the component treats a run of\n * arrows as one gesture, the way a drag is one.\n */\n async pressArrow(arrow: WrCropArrow, modifiers: { alt?: boolean; shift?: boolean } = {}): Promise<void> {\n const window_ = await this.requireReady('pressArrow');\n const keys = ARROWS[arrow];\n await (modifiers.alt || modifiers.shift ? window_.sendKeys(modifiers, keys) : window_.sendKeys(keys));\n }\n\n /**\n * How far the image is zoomed, `1` to `4`.\n *\n * Read off the transform the component writes on the picture, like\n * {@link getCropBox} off the window's inline pixels: the `zoom` model itself is\n * component API, outside what a harness reaches.\n */\n async getZoom(): Promise<number> {\n return (await this.viewTransform('getZoom')).zoom;\n }\n\n /** How far the image is turned, in degrees clockwise. Read like {@link getZoom}. */\n async getRotation(): Promise<WrImageRotation> {\n return (await this.viewTransform('getRotation')).rotation;\n }\n\n /** Press `+` on the crop window: one zoom step in, around the middle of the window. */\n async zoomIn(): Promise<void> {\n await (await this.requireReady('zoomIn')).sendKeys('+');\n }\n\n /** Press `-` on the crop window: one zoom step out. */\n async zoomOut(): Promise<void> {\n await (await this.requireReady('zoomOut')).sendKeys('-');\n }\n\n /**\n * Press `R` on the crop window, or Shift with `R` for `'ccw'`: a quarter turn.\n *\n * A turned image has no measured box in a unit test, so the stage becomes the\n * box it had, swapped and scaled to fit inside itself. {@link getCropBox} is in\n * that stage's pixels.\n */\n async rotate(direction: 'cw' | 'ccw' = 'cw'): Promise<void> {\n const window_ = await this.requireReady('rotate');\n await (direction === 'ccw' ? window_.sendKeys({ shift: true }, 'r') : window_.sendKeys('r'));\n }\n\n /** The crop window's accessible name. Comes from the catalog. */\n async getCropWindowLabel(): Promise<string | null> {\n return (await this.requireReady('getCropWindowLabel')).getAttribute('aria-label');\n }\n\n /**\n * The last thing the live region announced — the crop rect in SOURCE pixels,\n * as `x, y, width × height`.\n *\n * Empty until a key has moved the crop: a pointer drag deliberately says nothing\n * (it would flood the region and the sighted user can see it), and the initial\n * crop is not news. Two questions, not one — {@link getCropBox} reads the window's\n * DISPLAY geometry, and a component that moved the box without announcing it\n * would still pass that one.\n */\n async getAnnouncement(): Promise<string> {\n await this.requireReady('getAnnouncement');\n const status = await this.locatorForOptional('[role=\"status\"]')();\n return status ? status.text() : '';\n }\n\n /**\n * The picture's zoom and rotation, from its `transform`. jsdom answers with the\n * list the component wrote; a browser answers with the matrix it resolved to.\n */\n private async viewTransform(method: string): Promise<{ zoom: number; rotation: WrImageRotation }> {\n await this.requireReady(method);\n const transform = await (await this.locatorFor('.wr-image-cropper__image')()).getCssValue('transform');\n const matrix = /^matrix\\(([^)]+)\\)/.exec(transform)?.[1].split(',').map(Number);\n if (matrix) {\n const [a, b] = matrix;\n const turn = Math.round((Math.atan2(b, a) * 180) / Math.PI / 90) * 90;\n return { zoom: Math.round(Math.hypot(a, b) * 1000) / 1000, rotation: ((turn + 360) % 360) as WrImageRotation };\n }\n return {\n zoom: Number(/scale\\(([\\d.]+)\\)/.exec(transform)?.[1] ?? 1),\n rotation: Number(/rotate\\((\\d+)deg\\)/.exec(transform)?.[1] ?? 0) as WrImageRotation,\n };\n }\n\n private async requireReady(method: string): Promise<TestElement> {\n const window_ = await this.cropWindow();\n if (window_) return window_;\n\n throw new Error(\n `WrImageCropperHarness.${method}(): the crop window is not rendered. The cropper sizes it from the ` +\n \"image's MEASURED box, and a unit test has none — give the <img> a `getBoundingClientRect` and a \" +\n '`naturalWidth`, then call dispatchImageLoad().'\n );\n }\n}\n"],"mappings":";;;;;;;AAaA,MAAM,SAAS;CACb,MAAM,QAAQ;CACd,OAAO,QAAQ;CACf,IAAI,QAAQ;CACZ,MAAM,QAAQ;AACN;AAoEV,IAAa,wBAAb,MAAa,8BAA8B,iBAAgB;CACzD,OAAO,eAAe;CAGtB,OAAO,KAAK,UAAwC,CAAA,GAAE;EACpD,OAAO,IAAI,iBAAiB,uBAAuB,OAAO,CAAC,CAAC,UAC1D,SACA,QAAQ,OACR,OAAO,SAAS,UAAW,MAAM,QAAQ,QAAO,MAA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