@embedpdf/plugin-i18n 3.0.0-next.13 → 3.0.0-next.15

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/dist/index.js CHANGED
@@ -1,23 +1,764 @@
1
- import { t as I18nToken } from "./contract-D08iYq9-.js";
2
- import { definePlugin } from "@embedpdf/core";
3
- //#region src/translate.ts
1
+ import { n as I18nToken, t as I18N_DEFAULTS } from "./contract-w0S-ipz5.js";
2
+ import { PluginError, definePlugin, defineState, isPluginError, memo, toPluginError, toPluginErrorInfo } from "@embedpdf/core";
3
+ //#region src/model.ts
4
+ /** Nothing loaded yet: the controller seeds the state from the settings. */
5
+ const initialI18nState = () => ({
6
+ locale: "",
7
+ locales: {},
8
+ loading: null,
9
+ waitingTranslations: {}
10
+ });
11
+ /**
12
+ * The state the settings start with: their languages loaded, and their `locale` current. A start
13
+ * language that is still to load shows `fallbackLocale` meanwhile, and `loading` names it, so the
14
+ * loader fetches it once connected.
15
+ */
16
+ function seedFromSettings(state, settings) {
17
+ const seeded = settings.locales.reduce(registerLocale, state);
18
+ const locale = settings.locale ?? settings.fallbackLocale;
19
+ if (seeded.locales[locale] || settings.loaders[locale] === void 0) return {
20
+ ...seeded,
21
+ locale
22
+ };
23
+ return {
24
+ ...seeded,
25
+ locale: settings.fallbackLocale,
26
+ loading: locale
27
+ };
28
+ }
29
+ /** Deep merge of two dictionaries: later leaves win, branches merge. */
30
+ function mergeTranslations(base, patch) {
31
+ const merged = { ...base };
32
+ for (const [key, value] of Object.entries(patch)) {
33
+ const current = merged[key];
34
+ merged[key] = typeof value === "object" && typeof current === "object" ? mergeTranslations(current, value) : value;
35
+ }
36
+ return merged;
37
+ }
38
+ const hasDottedKey = (dictionary) => Object.entries(dictionary).some(([key, value]) => key.includes(".") || typeof value === "object" && hasDottedKey(value));
39
+ /**
40
+ * Dotted keys as branches, the shape `t()` walks: `{ 'review.reject': 'Afwijzen' }` is
41
+ * `{ review: { reject: 'Afwijzen' } }`. Keys merge in order, so a later one wins. A dictionary
42
+ * without a dotted key comes back as it is.
43
+ */
44
+ function nestKeys(dictionary) {
45
+ if (!hasDottedKey(dictionary)) return dictionary;
46
+ let nested = {};
47
+ for (const [key, value] of Object.entries(dictionary)) {
48
+ const leaf = typeof value === "object" ? nestKeys(value) : value;
49
+ const branch = key.split(".").reduceRight((inner, part) => ({ [part]: inner }), leaf);
50
+ nested = mergeTranslations(nested, branch);
51
+ }
52
+ return nested;
53
+ }
54
+ const withNestedKeys = (locale) => {
55
+ const translations = nestKeys(locale.translations);
56
+ return translations === locale.translations ? locale : {
57
+ ...locale,
58
+ translations
59
+ };
60
+ };
61
+ /**
62
+ * Switch to a loaded language and end any load. A code that isn't loaded changes nothing: a
63
+ * language in `loaders` becomes current through {@link startLocaleLoad}, {@link registerLocale}
64
+ * and then this transition, which the loader drives.
65
+ */
66
+ function setLocale(state, code) {
67
+ if (!state.locales[code]) return state;
68
+ if (state.locale === code && state.loading === null) return state;
69
+ return {
70
+ ...state,
71
+ locale: code,
72
+ loading: null
73
+ };
74
+ }
75
+ /** Add a language, with any strings that were added to it before it loaded on top. */
76
+ function registerLocale(state, locale) {
77
+ const pack = withNestedKeys(locale);
78
+ const waiting = state.waitingTranslations[locale.code];
79
+ if (!waiting) return {
80
+ ...state,
81
+ locales: {
82
+ ...state.locales,
83
+ [locale.code]: pack
84
+ }
85
+ };
86
+ const { [locale.code]: _merged, ...stillWaiting } = state.waitingTranslations;
87
+ return {
88
+ ...state,
89
+ locales: {
90
+ ...state.locales,
91
+ [locale.code]: {
92
+ ...pack,
93
+ translations: mergeTranslations(pack.translations, waiting)
94
+ }
95
+ },
96
+ waitingTranslations: stillWaiting
97
+ };
98
+ }
99
+ function unregisterLocale(state, code) {
100
+ if (!state.locales[code]) return state;
101
+ const { [code]: _removed, ...locales } = state.locales;
102
+ return {
103
+ ...state,
104
+ locales
105
+ };
106
+ }
107
+ /**
108
+ * Merge strings into a language, later keys winning. For a language that isn't loaded yet (one in
109
+ * `loaders`), the strings wait and merge in when it loads; the controller only lets codes with a
110
+ * loader get here.
111
+ */
112
+ function addTranslations(state, code, dictionary) {
113
+ const strings = nestKeys(dictionary);
114
+ const pack = state.locales[code];
115
+ if (!pack) {
116
+ const waiting = state.waitingTranslations[code] ?? {};
117
+ return {
118
+ ...state,
119
+ waitingTranslations: {
120
+ ...state.waitingTranslations,
121
+ [code]: mergeTranslations(waiting, strings)
122
+ }
123
+ };
124
+ }
125
+ return {
126
+ ...state,
127
+ locales: {
128
+ ...state.locales,
129
+ [code]: {
130
+ ...pack,
131
+ translations: mergeTranslations(pack.translations, strings)
132
+ }
133
+ }
134
+ };
135
+ }
136
+ /** A language in `loaders` is wanted: the loader fetches whatever `loading` names. */
137
+ function startLocaleLoad(state, code) {
138
+ return state.loading === code ? state : {
139
+ ...state,
140
+ loading: code
141
+ };
142
+ }
143
+ /** A load ended without switching: it failed or was cancelled. Only the load still wanted ends. */
144
+ function endLocaleLoad(state, code) {
145
+ return state.loading === code ? {
146
+ ...state,
147
+ loading: null
148
+ } : state;
149
+ }
150
+ //#endregion
151
+ //#region src/sync/loaders.ts
4
152
  /**
5
- * The pure lookup core — state in, string out. No platform access anywhere
6
- * (`Intl.PluralRules` is core ECMAScript, not DOM); this is the part that
7
- * ports to Rust verbatim.
153
+ * The plugin's only side effect: fetching languages from `loaders`. Driven by
154
+ * state: a load is `state.loading`, set by `setLocale` (a switch to a language
155
+ * still to load) or by the seeded state (a start language still to load), so a
156
+ * load asked for before `connect` ran is picked up here.
8
157
  */
9
- /** Walk a dotted path ('commands.zoom.in') through a dictionary tree. */
10
- function lookup(dict, key) {
11
- if (!dict) return void 0;
12
- let node = dict;
158
+ function createLoaders(ctx, settings, settlers, onFailed) {
159
+ const load = (code) => {
160
+ const loader = settings.get().loaders[code];
161
+ if (!loader) {
162
+ ctx.state.update(endLocaleLoad, code);
163
+ return;
164
+ }
165
+ loader().then((locale) => {
166
+ ctx.state.update(registerLocale, locale);
167
+ if (ctx.state.get().loading === code) {
168
+ ctx.state.update(setLocale, locale.code);
169
+ settlers.settle(code, { ok: true });
170
+ }
171
+ }, (error) => {
172
+ ctx.state.update(endLocaleLoad, code);
173
+ onFailed(code, error);
174
+ settlers.settle(code, {
175
+ ok: false,
176
+ error: new PluginError("operation-failed", "i18n", `locale '${code}' failed to load`, { details: toPluginErrorInfo(toPluginError("i18n", error)) })
177
+ });
178
+ });
179
+ };
180
+ /** Fetch the language `loading` names now, and each one asked for after. */
181
+ const connect = () => {
182
+ const loadRequested = (code) => {
183
+ if (code) load(code);
184
+ };
185
+ loadRequested(ctx.state.get().loading);
186
+ ctx.watch(() => ctx.state.get().loading, loadRequested);
187
+ };
188
+ return { connect };
189
+ }
190
+ //#endregion
191
+ //#region src/negotiate.ts
192
+ /**
193
+ * Pure locale negotiation over language tags (RFC 5646) — strings in, string
194
+ * out. The plugin never reads the platform; the embedder feeds it whatever
195
+ * request list its environment offers:
196
+ *
197
+ * ```ts
198
+ * // browser shell: negotiateLocale(['en', 'es', 'ar'], navigator.languages)
199
+ * // server render: negotiateLocale(codes, parseAcceptLanguage(header))
200
+ * ```
201
+ *
202
+ * Matching, per requested code in preference order:
203
+ * 1. exact match (case-insensitive): `es-MX` → `es-MX`
204
+ * 2. request narrowed to its language: `en-GB` → `en`
205
+ * 3. any available dialect of the language: `zh` → `zh-Hans`
206
+ *
207
+ * Steps 2 and 3 match only within the script the language is written in, as
208
+ * `Intl.Locale#maximize` gives it: `zh-TW` and `zh-HK` are Traditional
209
+ * Chinese, so `zh-CN` (Simplified) isn't theirs, and they get no match until
210
+ * a Traditional language is available. Where the platform can't tell a tag's
211
+ * script, the language alone decides.
212
+ *
213
+ * Returns the matched code exactly as it appears in `available`, or null.
214
+ */
215
+ /** The script a tag's language is written in (`zh-TW` → `Hant`, `zh` → `Hans`), or null. */
216
+ function scriptOf(code) {
217
+ try {
218
+ return new Intl.Locale(code).maximize().script ?? null;
219
+ } catch {
220
+ return null;
221
+ }
222
+ }
223
+ /** Whether two tags are written in the same script, or one of them can't say. */
224
+ function sameScript(left, right) {
225
+ const leftScript = scriptOf(left);
226
+ const rightScript = scriptOf(right);
227
+ return leftScript === null || rightScript === null || leftScript === rightScript;
228
+ }
229
+ function negotiateLocale(available, requested) {
230
+ const byCanonical = /* @__PURE__ */ new Map();
231
+ for (const code of available) {
232
+ const canonical = code.toLowerCase();
233
+ if (!byCanonical.has(canonical)) byCanonical.set(canonical, code);
234
+ }
235
+ const languageOf = (code) => code.toLowerCase().split("-")[0];
236
+ for (const wanted of requested) {
237
+ const exact = byCanonical.get(wanted.toLowerCase());
238
+ if (exact !== void 0) return exact;
239
+ }
240
+ for (const wanted of requested) {
241
+ const narrowed = byCanonical.get(languageOf(wanted));
242
+ if (narrowed !== void 0 && sameScript(wanted, narrowed)) return narrowed;
243
+ }
244
+ for (const wanted of requested) {
245
+ const language = languageOf(wanted);
246
+ for (const [canonical, original] of byCanonical) if (languageOf(canonical) === language && sameScript(wanted, original)) return original;
247
+ }
248
+ return null;
249
+ }
250
+ //#endregion
251
+ //#region src/strings/index.ts
252
+ const EMBEDPDF_STRINGS = {
253
+ en: { commands: {
254
+ zoom: {
255
+ in: "Zoom in",
256
+ out: "Zoom out",
257
+ fitWidth: "Fit width",
258
+ fitPage: "Fit page"
259
+ },
260
+ page: {
261
+ next: "Next page",
262
+ previous: "Previous page",
263
+ first: "First page",
264
+ last: "Last page"
265
+ },
266
+ view: {
267
+ rotateClockwise: "Rotate clockwise",
268
+ rotateCounterclockwise: "Rotate counterclockwise"
269
+ },
270
+ selection: { copy: "Copy" },
271
+ annotation: { delete: "Delete" },
272
+ document: {
273
+ download: "Download",
274
+ print: "Print"
275
+ },
276
+ tool: {
277
+ pointer: "Select",
278
+ pan: "Pan",
279
+ highlight: "Highlight",
280
+ underline: "Underline",
281
+ strikeout: "Strikethrough",
282
+ squiggly: "Squiggly underline",
283
+ "insert-text": "Insert text",
284
+ "replace-text": "Replace text",
285
+ ink: "Draw",
286
+ "ink-highlight": "Highlighter",
287
+ "free-text": "Text box",
288
+ "free-text-callout": "Callout",
289
+ note: "Note",
290
+ square: "Rectangle",
291
+ circle: "Ellipse",
292
+ line: "Line",
293
+ polygon: "Polygon",
294
+ polyline: "Polyline",
295
+ link: "Link",
296
+ stamp: "Stamp",
297
+ attachment: "Attach file",
298
+ redact: "Redact",
299
+ distance: "Distance",
300
+ perimeter: "Perimeter",
301
+ area: "Area",
302
+ calibrate: "Calibrate",
303
+ "form-fill": "Fill form",
304
+ "form-edit": "Edit form",
305
+ "form-text": "Text field",
306
+ "form-checkbox": "Checkbox",
307
+ "form-radio": "Radio button",
308
+ "form-combobox": "Dropdown",
309
+ "form-listbox": "List box",
310
+ "form-signature": "Signature field"
311
+ }
312
+ } },
313
+ nl: { commands: {
314
+ zoom: {
315
+ in: "Inzoomen",
316
+ out: "Uitzoomen",
317
+ fitWidth: "Paginabreedte",
318
+ fitPage: "Hele pagina"
319
+ },
320
+ page: {
321
+ next: "Volgende pagina",
322
+ previous: "Vorige pagina",
323
+ first: "Eerste pagina",
324
+ last: "Laatste pagina"
325
+ },
326
+ view: {
327
+ rotateClockwise: "Rechtsom draaien",
328
+ rotateCounterclockwise: "Linksom draaien"
329
+ },
330
+ selection: { copy: "Kopiëren" },
331
+ annotation: { delete: "Verwijderen" },
332
+ document: {
333
+ download: "Downloaden",
334
+ print: "Afdrukken"
335
+ },
336
+ tool: {
337
+ pointer: "Selecteren",
338
+ pan: "Verschuiven",
339
+ highlight: "Markeren",
340
+ underline: "Onderstrepen",
341
+ strikeout: "Doorhalen",
342
+ squiggly: "Golflijn",
343
+ "insert-text": "Tekst invoegen",
344
+ "replace-text": "Tekst vervangen",
345
+ ink: "Tekenen",
346
+ "ink-highlight": "Markeerstift",
347
+ "free-text": "Tekstvak",
348
+ "free-text-callout": "Toelichting",
349
+ note: "Notitie",
350
+ square: "Rechthoek",
351
+ circle: "Ellips",
352
+ line: "Lijn",
353
+ polygon: "Veelhoek",
354
+ polyline: "Polylijn",
355
+ link: "Koppeling",
356
+ stamp: "Stempel",
357
+ attachment: "Bestand bijvoegen",
358
+ redact: "Redigeren",
359
+ distance: "Afstand",
360
+ perimeter: "Omtrek",
361
+ area: "Oppervlakte",
362
+ calibrate: "Kalibreren",
363
+ "form-fill": "Formulier invullen",
364
+ "form-edit": "Formulier bewerken",
365
+ "form-text": "Tekstveld",
366
+ "form-checkbox": "Selectievakje",
367
+ "form-radio": "Keuzerondje",
368
+ "form-combobox": "Vervolgkeuzelijst",
369
+ "form-listbox": "Keuzelijst",
370
+ "form-signature": "Handtekeningveld"
371
+ }
372
+ } },
373
+ de: { commands: {
374
+ zoom: {
375
+ in: "Vergrößern",
376
+ out: "Verkleinern",
377
+ fitWidth: "Seitenbreite",
378
+ fitPage: "Ganze Seite"
379
+ },
380
+ page: {
381
+ next: "Nächste Seite",
382
+ previous: "Vorherige Seite",
383
+ first: "Erste Seite",
384
+ last: "Letzte Seite"
385
+ },
386
+ view: {
387
+ rotateClockwise: "Im Uhrzeigersinn drehen",
388
+ rotateCounterclockwise: "Gegen den Uhrzeigersinn drehen"
389
+ },
390
+ selection: { copy: "Kopieren" },
391
+ annotation: { delete: "Löschen" },
392
+ document: {
393
+ download: "Herunterladen",
394
+ print: "Drucken"
395
+ },
396
+ tool: {
397
+ pointer: "Auswählen",
398
+ pan: "Verschieben",
399
+ highlight: "Hervorheben",
400
+ underline: "Unterstreichen",
401
+ strikeout: "Durchstreichen",
402
+ squiggly: "Wellenlinie",
403
+ "insert-text": "Text einfügen",
404
+ "replace-text": "Text ersetzen",
405
+ ink: "Zeichnen",
406
+ "ink-highlight": "Textmarker",
407
+ "free-text": "Textkommentar",
408
+ "free-text-callout": "Legende",
409
+ note: "Notiz",
410
+ square: "Rechteck",
411
+ circle: "Ellipse",
412
+ line: "Linie",
413
+ polygon: "Polygon",
414
+ polyline: "Polylinie",
415
+ link: "Link",
416
+ stamp: "Stempel",
417
+ attachment: "Datei anhängen",
418
+ redact: "Schwärzen",
419
+ distance: "Abstand",
420
+ perimeter: "Umfang",
421
+ area: "Fläche",
422
+ calibrate: "Kalibrieren",
423
+ "form-fill": "Formular ausfüllen",
424
+ "form-edit": "Formular bearbeiten",
425
+ "form-text": "Textfeld",
426
+ "form-checkbox": "Kontrollkästchen",
427
+ "form-radio": "Optionsfeld",
428
+ "form-combobox": "Dropdown-Liste",
429
+ "form-listbox": "Listenfeld",
430
+ "form-signature": "Unterschriftsfeld"
431
+ }
432
+ } },
433
+ fr: { commands: {
434
+ zoom: {
435
+ in: "Zoom avant",
436
+ out: "Zoom arrière",
437
+ fitWidth: "Pleine largeur",
438
+ fitPage: "Page entière"
439
+ },
440
+ page: {
441
+ next: "Page suivante",
442
+ previous: "Page précédente",
443
+ first: "Première page",
444
+ last: "Dernière page"
445
+ },
446
+ view: {
447
+ rotateClockwise: "Rotation horaire",
448
+ rotateCounterclockwise: "Rotation antihoraire"
449
+ },
450
+ selection: { copy: "Copier" },
451
+ annotation: { delete: "Supprimer" },
452
+ document: {
453
+ download: "Télécharger",
454
+ print: "Imprimer"
455
+ },
456
+ tool: {
457
+ pointer: "Sélectionner",
458
+ pan: "Déplacer",
459
+ highlight: "Surligner",
460
+ underline: "Souligner",
461
+ strikeout: "Barrer",
462
+ squiggly: "Soulignement ondulé",
463
+ "insert-text": "Insérer du texte",
464
+ "replace-text": "Remplacer le texte",
465
+ ink: "Dessiner",
466
+ "ink-highlight": "Surligneur",
467
+ "free-text": "Zone de texte",
468
+ "free-text-callout": "Légende",
469
+ note: "Note",
470
+ square: "Rectangle",
471
+ circle: "Ellipse",
472
+ line: "Ligne",
473
+ polygon: "Polygone",
474
+ polyline: "Polyligne",
475
+ link: "Lien",
476
+ stamp: "Tampon",
477
+ attachment: "Joindre un fichier",
478
+ redact: "Biffer",
479
+ distance: "Distance",
480
+ perimeter: "Périmètre",
481
+ area: "Aire",
482
+ calibrate: "Étalonner",
483
+ "form-fill": "Remplir le formulaire",
484
+ "form-edit": "Modifier le formulaire",
485
+ "form-text": "Champ de texte",
486
+ "form-checkbox": "Case à cocher",
487
+ "form-radio": "Bouton radio",
488
+ "form-combobox": "Liste déroulante",
489
+ "form-listbox": "Zone de liste",
490
+ "form-signature": "Champ de signature"
491
+ }
492
+ } },
493
+ es: { commands: {
494
+ zoom: {
495
+ in: "Acercar",
496
+ out: "Alejar",
497
+ fitWidth: "Ajustar al ancho",
498
+ fitPage: "Ajustar a la página"
499
+ },
500
+ page: {
501
+ next: "Página siguiente",
502
+ previous: "Página anterior",
503
+ first: "Primera página",
504
+ last: "Última página"
505
+ },
506
+ view: {
507
+ rotateClockwise: "Girar a la derecha",
508
+ rotateCounterclockwise: "Girar a la izquierda"
509
+ },
510
+ selection: { copy: "Copiar" },
511
+ annotation: { delete: "Eliminar" },
512
+ document: {
513
+ download: "Descargar",
514
+ print: "Imprimir"
515
+ },
516
+ tool: {
517
+ pointer: "Seleccionar",
518
+ pan: "Desplazar",
519
+ highlight: "Resaltar",
520
+ underline: "Subrayar",
521
+ strikeout: "Tachar",
522
+ squiggly: "Subrayado ondulado",
523
+ "insert-text": "Insertar texto",
524
+ "replace-text": "Reemplazar texto",
525
+ ink: "Dibujar",
526
+ "ink-highlight": "Marcador",
527
+ "free-text": "Cuadro de texto",
528
+ "free-text-callout": "Llamada",
529
+ note: "Nota",
530
+ square: "Rectángulo",
531
+ circle: "Elipse",
532
+ line: "Línea",
533
+ polygon: "Polígono",
534
+ polyline: "Polilínea",
535
+ link: "Enlace",
536
+ stamp: "Sello",
537
+ attachment: "Adjuntar archivo",
538
+ redact: "Censurar",
539
+ distance: "Distancia",
540
+ perimeter: "Perímetro",
541
+ area: "Área",
542
+ calibrate: "Calibrar",
543
+ "form-fill": "Rellenar formulario",
544
+ "form-edit": "Editar formulario",
545
+ "form-text": "Campo de texto",
546
+ "form-checkbox": "Casilla de verificación",
547
+ "form-radio": "Botón de opción",
548
+ "form-combobox": "Lista desplegable",
549
+ "form-listbox": "Cuadro de lista",
550
+ "form-signature": "Campo de firma"
551
+ }
552
+ } },
553
+ "zh-CN": { commands: {
554
+ zoom: {
555
+ in: "放大",
556
+ out: "缩小",
557
+ fitWidth: "适合宽度",
558
+ fitPage: "适合页面"
559
+ },
560
+ page: {
561
+ next: "下一页",
562
+ previous: "上一页",
563
+ first: "第一页",
564
+ last: "最后一页"
565
+ },
566
+ view: {
567
+ rotateClockwise: "顺时针旋转",
568
+ rotateCounterclockwise: "逆时针旋转"
569
+ },
570
+ selection: { copy: "复制" },
571
+ annotation: { delete: "删除" },
572
+ document: {
573
+ download: "下载",
574
+ print: "打印"
575
+ },
576
+ tool: {
577
+ pointer: "选择",
578
+ pan: "平移",
579
+ highlight: "高亮",
580
+ underline: "下划线",
581
+ strikeout: "删除线",
582
+ squiggly: "波浪线",
583
+ "insert-text": "插入文本",
584
+ "replace-text": "替换文本",
585
+ ink: "绘图",
586
+ "ink-highlight": "荧光笔",
587
+ "free-text": "文本框",
588
+ "free-text-callout": "标注",
589
+ note: "便笺",
590
+ square: "矩形",
591
+ circle: "椭圆",
592
+ line: "直线",
593
+ polygon: "多边形",
594
+ polyline: "折线",
595
+ link: "链接",
596
+ stamp: "图章",
597
+ attachment: "附加文件",
598
+ redact: "涂黑",
599
+ distance: "距离",
600
+ perimeter: "周长",
601
+ area: "面积",
602
+ calibrate: "校准",
603
+ "form-fill": "填写表单",
604
+ "form-edit": "编辑表单",
605
+ "form-text": "文本字段",
606
+ "form-checkbox": "复选框",
607
+ "form-radio": "单选按钮",
608
+ "form-combobox": "下拉列表",
609
+ "form-listbox": "列表框",
610
+ "form-signature": "签名字段"
611
+ }
612
+ } },
613
+ sv: { commands: {
614
+ zoom: {
615
+ in: "Zooma in",
616
+ out: "Zooma ut",
617
+ fitWidth: "Anpassa till bredd",
618
+ fitPage: "Anpassa till sida"
619
+ },
620
+ page: {
621
+ next: "Nästa sida",
622
+ previous: "Föregående sida",
623
+ first: "Första sidan",
624
+ last: "Sista sidan"
625
+ },
626
+ view: {
627
+ rotateClockwise: "Rotera medurs",
628
+ rotateCounterclockwise: "Rotera moturs"
629
+ },
630
+ selection: { copy: "Kopiera" },
631
+ annotation: { delete: "Ta bort" },
632
+ document: {
633
+ download: "Ladda ned",
634
+ print: "Skriv ut"
635
+ },
636
+ tool: {
637
+ pointer: "Välj",
638
+ pan: "Panorera",
639
+ highlight: "Markera",
640
+ underline: "Stryk under",
641
+ strikeout: "Stryk över",
642
+ squiggly: "Vågig understrykning",
643
+ "insert-text": "Infoga text",
644
+ "replace-text": "Ersätt text",
645
+ ink: "Rita",
646
+ "ink-highlight": "Överstrykningspenna",
647
+ "free-text": "Textruta",
648
+ "free-text-callout": "Pratbubbla",
649
+ note: "Anteckning",
650
+ square: "Rektangel",
651
+ circle: "Ellips",
652
+ line: "Linje",
653
+ polygon: "Polygon",
654
+ polyline: "Polylinje",
655
+ link: "Länk",
656
+ stamp: "Stämpel",
657
+ attachment: "Bifoga fil",
658
+ redact: "Maskera",
659
+ distance: "Avstånd",
660
+ perimeter: "Omkrets",
661
+ area: "Area",
662
+ calibrate: "Kalibrera",
663
+ "form-fill": "Fyll i formulär",
664
+ "form-edit": "Redigera formulär",
665
+ "form-text": "Textfält",
666
+ "form-checkbox": "Kryssruta",
667
+ "form-radio": "Alternativknapp",
668
+ "form-combobox": "Rullgardinsmeny",
669
+ "form-listbox": "Listruta",
670
+ "form-signature": "Signaturfält"
671
+ }
672
+ } },
673
+ ja: { commands: {
674
+ zoom: {
675
+ in: "拡大",
676
+ out: "縮小",
677
+ fitWidth: "幅に合わせる",
678
+ fitPage: "ページ全体を表示"
679
+ },
680
+ page: {
681
+ next: "次のページ",
682
+ previous: "前のページ",
683
+ first: "最初のページ",
684
+ last: "最後のページ"
685
+ },
686
+ view: {
687
+ rotateClockwise: "右に回転",
688
+ rotateCounterclockwise: "左に回転"
689
+ },
690
+ selection: { copy: "コピー" },
691
+ annotation: { delete: "削除" },
692
+ document: {
693
+ download: "ダウンロード",
694
+ print: "印刷"
695
+ },
696
+ tool: {
697
+ pointer: "選択",
698
+ pan: "パン",
699
+ highlight: "ハイライト",
700
+ underline: "下線",
701
+ strikeout: "取り消し線",
702
+ squiggly: "波線",
703
+ "insert-text": "テキストを挿入",
704
+ "replace-text": "テキストを置換",
705
+ ink: "描画",
706
+ "ink-highlight": "蛍光ペン",
707
+ "free-text": "テキストボックス",
708
+ "free-text-callout": "引き出し線",
709
+ note: "ノート",
710
+ square: "長方形",
711
+ circle: "楕円",
712
+ line: "線",
713
+ polygon: "多角形",
714
+ polyline: "折れ線",
715
+ link: "リンク",
716
+ stamp: "スタンプ",
717
+ attachment: "ファイルを添付",
718
+ redact: "墨消し",
719
+ distance: "距離",
720
+ perimeter: "周囲長",
721
+ area: "面積",
722
+ calibrate: "校正",
723
+ "form-fill": "フォームに入力",
724
+ "form-edit": "フォームを編集",
725
+ "form-text": "テキストフィールド",
726
+ "form-checkbox": "チェックボックス",
727
+ "form-radio": "ラジオボタン",
728
+ "form-combobox": "ドロップダウン",
729
+ "form-listbox": "リストボックス",
730
+ "form-signature": "署名フィールド"
731
+ }
732
+ } }
733
+ };
734
+ const CODES = Object.keys(EMBEDPDF_STRINGS);
735
+ /** Which of EmbedPDF's languages each code reads, decided once per code. */
736
+ const languageOf = /* @__PURE__ */ new Map();
737
+ /**
738
+ * EmbedPDF's strings for a language code, matched as `negotiateLocale` matches: `nl-BE` reads
739
+ * Dutch and `zh` Simplified Chinese. `undefined` for a language EmbedPDF has no strings in.
740
+ */
741
+ function embedpdfStringsFor(code) {
742
+ let language = languageOf.get(code);
743
+ if (language === void 0) {
744
+ language = negotiateLocale(CODES, [code]);
745
+ languageOf.set(code, language);
746
+ }
747
+ return language === null ? void 0 : EMBEDPDF_STRINGS[language];
748
+ }
749
+ //#endregion
750
+ //#region src/translate.ts
751
+ /** Walk a dotted path (`'commands.zoom.in'`) through a dictionary. */
752
+ function lookup(dictionary, key) {
753
+ if (!dictionary) return void 0;
754
+ let node = dictionary;
13
755
  for (const part of key.split(".")) {
14
756
  if (node === void 0 || typeof node === "string") return void 0;
15
757
  node = node[part];
16
758
  }
17
759
  return node;
18
760
  }
19
- /** CLDR plural category for a count, with a safe fallback when the runtime
20
- * lacks ICU data for the locale. */
761
+ /** The language's plural form for a count; `'one'` or `'other'` when the runtime has no rules for it. */
21
762
  function pluralCategory(locale, count) {
22
763
  try {
23
764
  return new Intl.PluralRules(locale).select(count);
@@ -25,7 +766,7 @@ function pluralCategory(locale, count) {
25
766
  return count === 1 ? "one" : "other";
26
767
  }
27
768
  }
28
- /** A leaf hit is a string; a branch object needs a plural pick via `count`. */
769
+ /** A string is the answer; a branch needs a plural form, picked by `params.count`. */
29
770
  function resolveNode(node, locale, params) {
30
771
  if (typeof node === "string") return node;
31
772
  if (node !== void 0 && typeof params?.count === "number") {
@@ -33,18 +774,22 @@ function resolveNode(node, locale, params) {
33
774
  if (typeof branch === "string") return branch;
34
775
  }
35
776
  }
36
- /** Replace `{slot}` markers; unknown slots stay verbatim (visible in QA). */
777
+ /** Fill in `{name}` slots; a slot without a value stays as it is, so it shows while testing. */
37
778
  function interpolate(text, params) {
38
779
  if (!params) return text;
39
780
  return text.replace(/\{(\w+)\}/g, (match, slot) => params[slot] !== void 0 ? String(params[slot]) : match);
40
781
  }
782
+ /** A key in one language: the app's string, then EmbedPDF's own. */
783
+ const stringIn = (sources, code, key, params) => resolveNode(lookup(sources.locales[code]?.translations, key), code, params) ?? resolveNode(lookup(embedpdfStringsFor(code), key), code, params);
41
784
  /**
42
- * Resolve a key against the state: current locale → fallback locale →
43
- * `options.fallback` (interpolated too) → the key itself.
785
+ * A key's string: in the current language (the key, then `options.fallbackKey`), then the same in
786
+ * the fallback language, then `options.fallback` (with its slots filled too), then the key itself.
44
787
  */
45
- function translate(state, key, options) {
46
- const { locale, fallbackLocale, locales } = state;
47
- const text = resolveNode(lookup(locales[locale]?.translations, key), locale, options?.params) ?? resolveNode(lookup(locales[fallbackLocale]?.translations, key), fallbackLocale, options?.params);
788
+ function translate(sources, key, options) {
789
+ const params = options?.params;
790
+ const fallbackKey = options?.fallbackKey;
791
+ const inLanguage = (code) => stringIn(sources, code, key, params) ?? (fallbackKey === void 0 ? void 0 : stringIn(sources, code, fallbackKey, params));
792
+ const text = inLanguage(sources.locale) ?? inLanguage(sources.fallbackLocale);
48
793
  if (text !== void 0) return {
49
794
  text: interpolate(text, options?.params),
50
795
  found: true
@@ -59,203 +804,192 @@ function translate(state, key, options) {
59
804
  };
60
805
  }
61
806
  //#endregion
62
- //#region src/capability.ts
807
+ //#region src/controller.ts
63
808
  /**
64
- * The i18n capability — selectors (pure reads over state) + intents (the only
65
- * writers). Built synchronously in `createKernel()`, so `t()` works before the
66
- * engine exists — including inside the viewer shell's loading UI.
809
+ * The i18n controller: reads over the state, the language verbs, the
810
+ * `onLocaleChanged` derivation, and the loader wired at `connect`. Built
811
+ * synchronously in `createKernel()`, so `t()` works before the engine exists.
67
812
  */
68
- function createI18nCapability(ctx, config) {
813
+ const unknownLocale = (code) => new PluginError("not-found", "i18n", `unknown locale '${code}': not loaded and not in loaders`);
814
+ function createI18nController(ctx) {
815
+ const settings = ctx.settings();
816
+ const localeChanged = ctx.events.source();
817
+ const localeLoadFailed = ctx.events.source();
818
+ const state = () => ctx.state.get();
819
+ ctx.state.update(seedFromSettings, settings.get());
820
+ let announced = state().locale;
821
+ ctx.state.onChange(({ next }) => {
822
+ if (next.loading !== null || next.locale === announced) return;
823
+ const previousLocale = announced;
824
+ announced = next.locale;
825
+ localeChanged.emit({
826
+ locale: next.locale,
827
+ previousLocale
828
+ });
829
+ });
830
+ const sources = () => ({
831
+ locale: state().locale,
832
+ fallbackLocale: settings.get().fallbackLocale,
833
+ locales: state().locales
834
+ });
69
835
  const warned = /* @__PURE__ */ new Set();
70
- const warnOnce = (id, message) => {
71
- if (warned.has(id)) return;
72
- warned.add(id);
73
- console.warn(message);
836
+ const translateKey = (key, options) => {
837
+ const result = translate(sources(), key, options);
838
+ const missing = options?.fallbackKey === void 0 ? `"${key}"` : `"${key}" or "${options.fallbackKey}"`;
839
+ if (!result.found && options?.fallback === void 0 && !warned.has(missing)) {
840
+ warned.add(missing);
841
+ console.warn(`[i18n] missing translation ${missing} (locale: ${state().locale})`);
842
+ }
843
+ return result.text;
74
844
  };
75
- return {
76
- t: (key, options) => {
77
- const result = translate(ctx.getState(), key, options);
78
- if (!result.found && options?.fallback === void 0) warnOnce(`key:${key}`, `[i18n] missing translation "${key}" (locale: ${ctx.getState().locale})`);
79
- return result.text;
80
- },
81
- locale: () => ctx.getState().locale,
82
- dir: () => {
83
- const { locales, locale } = ctx.getState();
84
- return locales[locale]?.dir ?? "ltr";
85
- },
86
- locales: () => {
87
- const { locales } = ctx.getState();
88
- const known = Object.values(locales).map((locale) => ({
89
- code: locale.code,
90
- name: locale.name,
91
- dir: locale.dir ?? "ltr",
92
- loaded: true
93
- }));
94
- for (const code of Object.keys(config.loaders ?? {})) if (!locales[code]) known.push({
95
- code,
96
- name: code,
97
- dir: "ltr",
98
- loaded: false
99
- });
100
- return known;
101
- },
102
- loading: () => ctx.getState().loading,
103
- setLocale: (code) => {
104
- if (ctx.getState().locales[code]) ctx.dispatch({
105
- type: "I18N/SET_LOCALE",
106
- locale: code
107
- });
108
- else if (config.loaders?.[code]) ctx.dispatch({
109
- type: "I18N/LOAD_STARTED",
110
- locale: code
845
+ /** A new translate function only when the strings it can return may differ. */
846
+ const getTranslator = memo(() => [
847
+ state().locale,
848
+ state().locales,
849
+ settings.get().fallbackLocale
850
+ ], (_locale, _locales, _fallbackLocale) => (key, options) => translateKey(key, options));
851
+ /** The languages a picker shows, rebuilt only when the languages or the loaders change. */
852
+ const listLocales = memo(() => [state().locales, settings.get().loaders], (locales, loaders) => {
853
+ const known = Object.values(locales).map((locale) => ({
854
+ code: locale.code,
855
+ name: locale.name,
856
+ direction: locale.direction ?? "ltr",
857
+ loaded: true
858
+ }));
859
+ for (const code of Object.keys(loaders)) if (!locales[code]) known.push({
860
+ code,
861
+ name: code,
862
+ direction: "ltr",
863
+ loaded: false
864
+ });
865
+ return known;
866
+ });
867
+ /** The caller waiting for a language to load; a newer switch replaces it. */
868
+ const pending = /* @__PURE__ */ new Map();
869
+ const settle = (code, outcome) => {
870
+ const waiter = pending.get(code);
871
+ if (!waiter) return;
872
+ pending.delete(code);
873
+ if (outcome.ok) waiter.resolve();
874
+ else waiter.reject(outcome.error);
875
+ };
876
+ const supersede = () => {
877
+ for (const [code, waiter] of pending) {
878
+ pending.delete(code);
879
+ waiter.reject(new PluginError("operation-cancelled", "i18n", `switching to '${code}' was replaced`));
880
+ }
881
+ };
882
+ const loaders = createLoaders(ctx, settings, { settle }, (locale, error) => localeLoadFailed.emit({
883
+ locale,
884
+ error: toPluginErrorInfo(toPluginError("i18n", error))
885
+ }));
886
+ const setLocale$1 = (code, options = {}) => {
887
+ const { signal } = options;
888
+ if (signal?.aborted) return Promise.reject(new PluginError("operation-cancelled", "i18n", "operation cancelled"));
889
+ if (state().locales[code]) {
890
+ supersede();
891
+ ctx.state.update(setLocale, code);
892
+ return Promise.resolve();
893
+ }
894
+ if (!settings.get().loaders[code]) return Promise.reject(unknownLocale(code));
895
+ supersede();
896
+ const loaded = new Promise((resolve, reject) => {
897
+ pending.set(code, {
898
+ resolve,
899
+ reject
111
900
  });
112
- else warnOnce(`locale:${code}`, `[i18n] unknown locale "${code}" — not registered and no loader configured`);
113
- },
114
- registerLocale: (locale) => ctx.dispatch({
115
- type: "I18N/REGISTER_LOCALE",
116
- locale
117
- })
901
+ ctx.state.update(startLocaleLoad, code);
902
+ });
903
+ signal?.addEventListener("abort", () => {
904
+ if (!pending.delete(code)) return;
905
+ ctx.state.update(endLocaleLoad, code);
906
+ }, { once: true });
907
+ return ctx.cancellable(signal, loaded);
118
908
  };
119
- }
120
- //#endregion
121
- //#region src/effects.ts
122
- /**
123
- * The plugin's ONE side-effect: fetching lazy locale packs. State-driven — a
124
- * load is `state.loading`, set by the capability (a switch to a lazy pack) or
125
- * by the initial state (a lazy startup locale), so a load requested before
126
- * effects ran is picked up here and nothing is lost to boot ordering.
127
- */
128
- function registerI18nEffects(config) {
129
- return (ctx) => {
130
- const load = (code) => {
131
- const loader = config.loaders?.[code];
132
- if (!loader) return;
133
- loader().then((locale) => {
134
- ctx.dispatch({
135
- type: "I18N/REGISTER_LOCALE",
136
- locale
137
- });
138
- if (ctx.getState().loading === code) ctx.dispatch({
139
- type: "I18N/SET_LOCALE",
140
- locale: locale.code
909
+ /** Follow a settings change: new languages register, and a new `locale` becomes current. */
910
+ const followSettings = () => {
911
+ let previous = settings.get();
912
+ ctx.listen(settings.api.onSettingsChanged, ({ settings: next, changed }) => {
913
+ if (changed.includes("locales")) {
914
+ for (const locale of previous.locales) if (!next.locales.some((other) => other.code === locale.code)) ctx.state.update(unregisterLocale, locale.code);
915
+ for (const locale of next.locales) if (!previous.locales.includes(locale)) ctx.state.update(registerLocale, locale);
916
+ }
917
+ if (changed.includes("locale")) {
918
+ const code = next.locale ?? next.fallbackLocale;
919
+ setLocale$1(code).catch((error) => {
920
+ if (isPluginError(error, "not-found")) console.warn(`[i18n] ${error.message}`);
141
921
  });
142
- }, () => ctx.dispatch({
143
- type: "I18N/LOAD_FAILED",
144
- locale: code
145
- }));
146
- };
147
- const pending = ctx.getState().loading;
148
- if (pending) load(pending);
149
- ctx.watch(() => ctx.getState().loading, (code) => {
150
- if (code) load(code);
922
+ }
923
+ previous = next;
151
924
  });
152
925
  };
153
- }
154
- //#endregion
155
- //#region src/reducer.ts
156
- /**
157
- * Pure and serializable — locale packs are data, so they live HERE, not in a
158
- * side-table. One source of truth: `t()` is a pure function of this state and
159
- * reactivity rides the kernel's one change stream (no emitters).
160
- */
161
- function initialI18nState(config) {
162
- const fallbackLocale = config.fallbackLocale ?? "en";
163
- const locales = {};
164
- for (const locale of config.locales ?? []) locales[locale.code] = locale;
165
- const locale = config.locale ?? fallbackLocale;
166
926
  return {
167
- locale,
168
- fallbackLocale,
169
- locales,
170
- loading: !locales[locale] && config.loaders?.[locale] !== void 0 ? locale : null
927
+ api: {
928
+ ...settings.api,
929
+ t: translateKey,
930
+ getTranslator,
931
+ hasKey: (key) => translate(sources(), key).found,
932
+ getLocale: () => state().locale,
933
+ getDirection: () => state().locales[state().locale]?.direction ?? "ltr",
934
+ listLocales,
935
+ getLoadingLocale: () => state().loading,
936
+ setLocale: setLocale$1,
937
+ registerLocale: (locale) => {
938
+ ctx.state.update(registerLocale, locale);
939
+ return () => ctx.state.update(unregisterLocale, locale.code);
940
+ },
941
+ addTranslations: (code, translations) => {
942
+ if (!state().locales[code] && !settings.get().loaders[code]) throw unknownLocale(code);
943
+ ctx.state.update(addTranslations, code, translations);
944
+ },
945
+ onLocaleChanged: localeChanged.on,
946
+ onLocaleLoadFailed: localeLoadFailed.on
947
+ },
948
+ connect() {
949
+ loaders.connect();
950
+ followSettings();
951
+ }
171
952
  };
172
953
  }
173
- function i18nReducer(state, action) {
174
- switch (action.type) {
175
- case "I18N/SET_LOCALE":
176
- if (!state.locales[action.locale]) return state;
177
- if (state.locale === action.locale && state.loading === null) return state;
178
- return {
179
- ...state,
180
- locale: action.locale,
181
- loading: null
182
- };
183
- case "I18N/REGISTER_LOCALE": return {
184
- ...state,
185
- locales: {
186
- ...state.locales,
187
- [action.locale.code]: action.locale
188
- }
189
- };
190
- case "I18N/LOAD_STARTED": return state.loading === action.locale ? state : {
191
- ...state,
192
- loading: action.locale
193
- };
194
- case "I18N/LOAD_FAILED": return state.loading === action.locale ? {
195
- ...state,
196
- loading: null
197
- } : state;
198
- default: return state;
199
- }
200
- }
201
954
  //#endregion
202
955
  //#region src/i18n.plugin.ts
203
956
  /**
204
- * The i18n plugin: workspace-scoped (locale is a workspace concern) with NO
205
- * dependencies — engine-free, DOM-free. Its capability is built synchronously
206
- * in `createKernel()`, so the shell translates from the first frame, while
207
- * the engine is still booting.
957
+ * Translations and the current language. Workspace-scoped, with no dependencies and no engine
958
+ * calls: the capability exists from `createKernel()`, so the viewer translates while the engine
959
+ * is still loading. `config` is the settings the app registers, over {@link I18N_DEFAULTS}.
208
960
  */
209
- const i18nPlugin = (config = {}) => definePlugin({
961
+ const i18nPlugin = (config) => definePlugin({
210
962
  id: "i18n",
211
963
  scope: "workspace",
212
964
  token: I18nToken,
213
- initialState: () => initialI18nState(config),
214
- reduce: i18nReducer,
215
- capability: (ctx) => createI18nCapability(ctx, config),
216
- effects: registerI18nEffects(config)
965
+ state: initialI18nState,
966
+ settings: {
967
+ defaults: I18N_DEFAULTS,
968
+ registered: config
969
+ },
970
+ create: createI18nController
217
971
  });
218
972
  //#endregion
219
- //#region src/negotiate.ts
973
+ //#region src/state.ts
220
974
  /**
221
- * Pure BCP-47 locale negotiation — strings in, string out. The plugin never
222
- * reads the platform; the EMBEDDER feeds it whatever request list its
223
- * environment offers:
224
- *
225
- * ```ts
226
- * // browser shell: negotiateLocale(['en', 'es', 'ar'], navigator.languages)
227
- * // server render: negotiateLocale(codes, parseAcceptLanguage(header))
228
- * ```
229
- *
230
- * Matching, per requested code in preference order:
231
- * 1. exact match (case-insensitive): 'es-MX' → 'es-MX'
232
- * 2. request narrowed to its language: 'en-GB' → 'en'
233
- * 3. any available dialect of the language: 'zh' → 'zh-Hans'
234
- *
235
- * Returns the matched code exactly as it appears in `available`, or null.
975
+ * The translations page's State table as code: what `useI18nState()` returns,
976
+ * and the same fields in every other framework.
236
977
  */
237
- function negotiateLocale(available, requested) {
238
- const byCanon = /* @__PURE__ */ new Map();
239
- for (const code of available) {
240
- const canon = code.toLowerCase();
241
- if (!byCanon.has(canon)) byCanon.set(canon, code);
242
- }
243
- const languageOf = (code) => code.toLowerCase().split("-")[0];
244
- for (const want of requested) {
245
- const exact = byCanon.get(want.toLowerCase());
246
- if (exact !== void 0) return exact;
978
+ const i18nState = defineState(I18nToken, {
979
+ read: (i18n) => ({
980
+ locale: i18n.getLocale(),
981
+ direction: i18n.getDirection(),
982
+ locales: i18n.listLocales(),
983
+ loading: i18n.getLoadingLocale()
984
+ }),
985
+ empty: {
986
+ locale: "en",
987
+ direction: "ltr",
988
+ locales: [],
989
+ loading: null
247
990
  }
248
- for (const want of requested) {
249
- const narrowed = byCanon.get(languageOf(want));
250
- if (narrowed !== void 0) return narrowed;
251
- }
252
- for (const want of requested) {
253
- const language = languageOf(want);
254
- for (const [canon, original] of byCanon) if (languageOf(canon) === language) return original;
255
- }
256
- return null;
257
- }
991
+ });
258
992
  //#endregion
259
- export { I18nToken, i18nPlugin, interpolate, negotiateLocale, translate };
993
+ export { I18N_DEFAULTS, I18nToken, i18nPlugin, i18nState, negotiateLocale };
260
994
 
261
995
  //# sourceMappingURL=index.js.map