@kiosko/sdk 0.2.5 → 0.2.6

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/schema.js CHANGED
@@ -41,6 +41,9 @@ export const t = {
41
41
  export const FILTER_HELP = {
42
42
  en: 'Empty: all. Names or patterns, comma-separated: * matches anything, a leading ! leaves out (web, acme/*, !*-old).',
43
43
  es: 'Vacío: todos. Nombres o patrones separados por comas: * vale por cualquier cosa y un ! delante excluye (web, acme/*, !*-old).',
44
+ de: 'Leer: alle. Namen oder Muster, durch Kommas getrennt: * steht für alles, ein ! davor schließt aus (web, acme/*, !*-old).',
45
+ 'zh-Hant': '留空:全部。填入名稱或模式,以逗號分隔:* 代表任意字元,開頭加 ! 則排除(web, acme/*, !*-old)。',
46
+ 'zh-Hans': '留空:全部。填写名称或模式,用逗号分隔:* 匹配任意内容,开头加 ! 表示排除(web, acme/*, !*-old)。',
44
47
  };
45
48
  function clone(v) {
46
49
  return v === undefined ? v : JSON.parse(JSON.stringify(v));
package/dist/testing.d.ts CHANGED
@@ -71,7 +71,7 @@ export interface PluginIssue {
71
71
  /**
72
72
  * Paints every widget of a plugin with its demo data at its minimum and
73
73
  * preferred sizes and a wide and a tall one, in every theme and in each
74
- * language given, and lists what went wrong: a `render` that throws, one
74
+ * language given (by default the ones the plugin declares), and lists what went wrong: a `render` that throws, one
75
75
  * that paints nothing, paints outside its box, or takes longer than
76
76
  * `slowMs` (Kiosko warns at 50 ms). An empty list is a pass.
77
77
  */
package/dist/testing.js CHANGED
@@ -100,13 +100,13 @@ export function widgetState(w, hook, o = {}) {
100
100
  /**
101
101
  * Paints every widget of a plugin with its demo data at its minimum and
102
102
  * preferred sizes and a wide and a tall one, in every theme and in each
103
- * language given, and lists what went wrong: a `render` that throws, one
103
+ * language given (by default the ones the plugin declares), and lists what went wrong: a `render` that throws, one
104
104
  * that paints nothing, paints outside its box, or takes longer than
105
105
  * `slowMs` (Kiosko warns at 50 ms). An empty list is a pass.
106
106
  */
107
107
  export function checkPlugin(p, o = {}) {
108
108
  const issues = [];
109
- const locales = o.locales ?? ['en', 'es'];
109
+ const locales = o.locales ?? (p.languages?.length ? p.languages : ['en', 'es']);
110
110
  const themes = o.themes ?? THEMES.map((t) => t.id);
111
111
  const slow = o.slowMs ?? 50;
112
112
  for (const w of p.widgets ?? []) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kiosko/sdk",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "description": "Plugin SDK for Kiosko: define widgets, data sources and interludes for small always-on LCD panels.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -15,6 +15,16 @@
15
15
  "types": "./dist/workday.d.ts",
16
16
  "default": "./dist/workday.js"
17
17
  },
18
+ "./languages": {
19
+ "source": "./src/languages.ts",
20
+ "types": "./dist/languages.d.ts",
21
+ "default": "./dist/languages.js"
22
+ },
23
+ "./i18n": {
24
+ "source": "./src/i18n.ts",
25
+ "types": "./dist/i18n.d.ts",
26
+ "default": "./dist/i18n.js"
27
+ },
18
28
  "./format": {
19
29
  "source": "./src/format.ts",
20
30
  "types": "./dist/format.d.ts",
package/src/context.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  * const ctx = { ...createBaseContext({ now, locale: 'es' }), options, signal, intervalMs: 60_000, timeoutMs: 20_000 };
7
7
  */
8
8
  import { createFormatters, type TimeFormat } from './format.ts';
9
- import { localize, type Localized } from './i18n.ts';
9
+ import { localize, pickLocale, plural, type Localized, type PluralForms } from './i18n.ts';
10
10
  import type { BaseContext, Location, Logger } from './plugin.ts';
11
11
  import { DEFAULT_WORKDAY, type Workday } from './workday.ts';
12
12
 
@@ -16,6 +16,8 @@ export function createBaseContext(o: { now: number; locale?: string; timeFormat?
16
16
  now: o.now,
17
17
  locale,
18
18
  t: (text: Localized) => localize(text, locale),
19
+ plural: (n: number, forms: Record<string, PluralForms>) => plural(n, forms, locale),
20
+ pickLanguage: (available: readonly string[]) => pickLocale(available, locale) ?? (available.includes('en') ? 'en' : available[0] ?? 'en'),
19
21
  fmt: createFormatters({ locale, timeFormat: o.timeFormat ?? 'auto', now: o.now }),
20
22
  log: o.log ?? (() => undefined),
21
23
  dataDir: o.dataDir ?? '',
package/src/format.ts CHANGED
@@ -2,13 +2,15 @@
2
2
  * Times and lengths of time, written the same way by every widget:
3
3
  * `ctx.fmt.time(at)`, `ctx.fmt.ago(at)` and `ctx.fmt.duration(ms)`.
4
4
  *
5
- * They follow the panel's language (English and Spanish words; any other
6
- * language gets the English ones) and the config's `timeFormat`. Hand-written
5
+ * They follow the panel's language (English, Spanish, German, Traditional and
6
+ * Simplified Chinese words; any other language gets the English ones) and the config's `timeFormat`. Hand-written
7
7
  * rather than `Intl.RelativeTimeFormat`: its short forms differ between ICU
8
8
  * versions (Node, Chromium, WebKit), and a panel must paint the same thing in
9
9
  * the editor, the browser demo and on the glass.
10
10
  */
11
11
 
12
+ import { pickLocale } from './i18n.ts';
13
+
12
14
  /** How clock times are written: `auto` follows the language (24 h in Spanish, 12 h in US English). */
13
15
  export type TimeFormat = 'auto' | '24h' | '12h';
14
16
  export const TIME_FORMATS: readonly TimeFormat[] = ['auto', '24h', '12h'];
@@ -18,10 +20,15 @@ export interface Formatters {
18
20
  readonly hour12: boolean;
19
21
  /**
20
22
  * A clock time: `"09:05"` on a 24-hour clock, `"9:05 AM"` (`"9:05 a. m."`)
21
- * on a 12-hour one. `seconds` adds `":07"`; `ampm: false` leaves out
23
+ * on a 12-hour one (`"上午 9:05"` in Chinese). `seconds` adds `":07"`; `ampm: false` leaves out
22
24
  * AM/PM (a big clock that paints it apart).
23
25
  */
24
26
  time(at: number | Date, o?: { seconds?: boolean; ampm?: boolean }): string;
27
+ /**
28
+ * From one clock time to another: `"14:00–15:30"`, `"3:30–4:00 PM"`,
29
+ * `"下午 3:30–4:00"` (AM/PM once when both are in the same half of the day).
30
+ */
31
+ range(from: number | Date, to: number | Date, o?: { seconds?: boolean }): string;
25
32
  /**
26
33
  * How long ago `at` (epoch ms, a Date or an ISO string) was, from `ctx.now`:
27
34
  * `"just now"`, `"5 min ago"`, `"3 h ago"`, `"4 d ago"`, `"2 wk ago"`,
@@ -39,23 +46,76 @@ export interface Formatters {
39
46
  duration(ms: number, o?: { seconds?: boolean; round?: 'down' | 'up' | 'nearest'; compact?: boolean }): string;
40
47
  }
41
48
 
49
+ /**
50
+ * A language's words for times. Every unit gets the number, so a language
51
+ * whose units change with it (Polish, Russian, Arabic) can say so.
52
+ */
42
53
  interface Words {
43
54
  now: string;
44
55
  justNow: string;
45
- ago: (v: string) => string;
46
- wk: string;
56
+ /** `v` is the age already written ("5 min"), `n` its number. */
57
+ ago: (v: string, n: number) => string;
58
+ s: (n: number) => string;
59
+ min: (n: number) => string;
60
+ h: (n: number) => string;
61
+ d: (n: number) => string;
62
+ wk: (n: number) => string;
47
63
  yr: (n: number) => string;
64
+ /** Hours and minutes of a running length: "1 h 05", "1 小時 5 分". */
65
+ hm: (h: number, m: number) => string;
66
+ /** Days and hours: "2 d 3 h". */
67
+ dh: (d: number, h: number) => string;
48
68
  am: string;
49
69
  pm: string;
70
+ /** AM/PM goes before the time (上午 9:05), not after. */
71
+ ampmFirst?: boolean;
50
72
  }
51
73
 
74
+ const latin = (wk: string, yr: (n: number) => string) => ({
75
+ s: (n: number) => `${n} s`,
76
+ min: (n: number) => `${n} min`,
77
+ h: (n: number) => `${n} h`,
78
+ d: (n: number) => `${n} d`,
79
+ wk: (n: number) => `${n} ${wk}`,
80
+ yr: (n: number) => `${n} ${yr(n)}`,
81
+ hm: (h: number, m: number) => `${h} h ${pad2(m)}`,
82
+ dh: (d: number, h: number) => `${d} d ${h} h`,
83
+ });
84
+ // German: abbreviations with a full stop (5 Min., 3 Std.), which also spare the dative after "vor" (vor 2 Tagen); a running length as 1:05 h.
85
+ const german = {
86
+ s: (n: number) => `${n} s`,
87
+ min: (n: number) => `${n} Min.`,
88
+ h: (n: number) => `${n} Std.`,
89
+ d: (n: number) => `${n} T.`,
90
+ wk: (n: number) => `${n} Wo.`,
91
+ yr: (n: number) => `${n} J.`,
92
+ hm: (h: number, m: number) => `${h}:${pad2(m)} h`,
93
+ dh: (d: number, h: number) => `${d} T. ${h} Std.`,
94
+ };
95
+ const chinese = (u: { min: string; h: string; wk: string }) => ({
96
+ s: (n: number) => `${n} 秒`,
97
+ min: (n: number) => `${n} ${u.min}`,
98
+ h: (n: number) => `${n} ${u.h}`,
99
+ d: (n: number) => `${n} 天`,
100
+ wk: (n: number) => `${n} ${u.wk}`,
101
+ yr: (n: number) => `${n} 年`,
102
+ // No leading zero in Chinese: 1 小時 5 分.
103
+ hm: (h: number, m: number) => `${h} ${u.h} ${m} 分`,
104
+ dh: (d: number, h: number) => `${d} 天 ${h} ${u.h}`,
105
+ });
106
+
52
107
  const WORDS: Record<string, Words> = {
53
- en: { now: 'now', justNow: 'just now', ago: (v) => `${v} ago`, wk: 'wk', yr: () => 'yr', am: 'AM', pm: 'PM' },
54
- es: { now: 'ahora', justNow: 'ahora mismo', ago: (v) => `hace ${v}`, wk: 'sem', yr: (n) => (n === 1 ? 'año' : 'años'), am: 'a. m.', pm: 'p. m.' },
108
+ en: { now: 'now', justNow: 'just now', ago: (v) => `${v} ago`, am: 'AM', pm: 'PM', ...latin('wk', () => 'yr') },
109
+ es: { now: 'ahora', justNow: 'ahora mismo', ago: (v) => `hace ${v}`, am: 'a. m.', pm: 'p. m.', ...latin('sem', (n) => (n === 1 ? 'año' : 'años')) },
110
+ de: { now: 'jetzt', justNow: 'gerade eben', ago: (v) => `vor ${v}`, am: 'AM', pm: 'PM', ...german },
111
+ 'zh-Hant': { now: '現在', justNow: '剛剛', ago: (v) => `${v}前`, am: '上午', pm: '下午', ampmFirst: true, ...chinese({ min: '分鐘', h: '小時', wk: '週' }) },
112
+ 'zh-Hans': { now: '现在', justNow: '刚刚', ago: (v) => `${v}前`, am: '上午', pm: '下午', ampmFirst: true, ...chinese({ min: '分钟', h: '小时', wk: '周' }) },
55
113
  };
114
+ /** The languages ctx.fmt has words for (a test checks every language Kiosko speaks is here). */
115
+ export const FORMAT_LANGUAGES = Object.keys(WORDS);
116
+ const LANGS = Object.keys(WORDS);
56
117
 
57
- const langOf = (locale: string) => locale.toLowerCase().split(/[-_]/)[0] ?? 'en';
58
- const wordsFor = (locale: string): Words => WORDS[langOf(locale)] ?? WORDS.en!;
118
+ const wordsFor = (locale: string): Words => WORDS[pickLocale(LANGS, locale) ?? 'en'] ?? WORDS.en!;
59
119
  const pad2 = (n: number) => String(n).padStart(2, '0');
60
120
 
61
121
  const cycles = new Map<string, boolean>();
@@ -89,7 +149,7 @@ function toMs(at: number | Date | string): number {
89
149
  export function createFormatters(o: { locale: string; timeFormat?: TimeFormat; now: number }): Formatters {
90
150
  const w = wordsFor(o.locale);
91
151
  const hour12 = usesHour12(o.locale, o.timeFormat);
92
- return {
152
+ const fmt: Formatters = {
93
153
  hour12,
94
154
  time(at, opts = {}) {
95
155
  const d = new Date(toMs(at));
@@ -97,7 +157,16 @@ export function createFormatters(o: { locale: string; timeFormat?: TimeFormat; n
97
157
  const rest = `:${pad2(d.getMinutes())}${opts.seconds ? `:${pad2(d.getSeconds())}` : ''}`;
98
158
  if (!hour12) return `${pad2(h)}${rest}`;
99
159
  const base = `${h % 12 || 12}${rest}`;
100
- return opts.ampm === false ? base : `${base} ${h < 12 ? w.am : w.pm}`;
160
+ if (opts.ampm === false) return base;
161
+ const mark = h < 12 ? w.am : w.pm;
162
+ return w.ampmFirst ? `${mark} ${base}` : `${base} ${mark}`;
163
+ },
164
+ range(from, to, opts = {}) {
165
+ const a = new Date(toMs(from));
166
+ const b = new Date(toMs(to));
167
+ if (!hour12 || (a.getHours() < 12) !== (b.getHours() < 12)) return `${fmt.time(a, opts)}–${fmt.time(b, opts)}`;
168
+ // The same half of the day: AM/PM once, where the language puts it.
169
+ return w.ampmFirst ? `${fmt.time(a, opts)}–${fmt.time(b, { ...opts, ampm: false })}` : `${fmt.time(a, { ...opts, ampm: false })}–${fmt.time(b, opts)}`;
101
170
  },
102
171
  ago(at, opts = {}) {
103
172
  const suffix = opts.suffix !== false;
@@ -106,18 +175,19 @@ export function createFormatters(o: { locale: string; timeFormat?: TimeFormat; n
106
175
  if (!Number.isFinite(min) || min < 1) return suffix ? w.justNow : w.now;
107
176
  const h = Math.floor(min / 60);
108
177
  const d = Math.floor(h / 24);
109
- const v = min < 60 ? `${min} min` : h < 24 ? `${h} h` : d < 14 ? `${d} d` : d < 365 ? `${Math.floor(d / 7)} ${w.wk}` : `${Math.floor(d / 365)} ${w.yr(Math.floor(d / 365))}`;
110
- return suffix ? w.ago(v) : v;
178
+ const [v, n] = min < 60 ? [w.min(min), min] : h < 24 ? [w.h(h), h] : d < 14 ? [w.d(d), d] : d < 365 ? [w.wk(Math.floor(d / 7)), Math.floor(d / 7)] : [w.yr(Math.floor(d / 365)), Math.floor(d / 365)];
179
+ return suffix ? w.ago(v, n) : v;
111
180
  },
112
181
  duration(ms, opts = {}) {
113
182
  const round = opts.round === 'up' ? Math.ceil : opts.round === 'nearest' ? Math.round : Math.floor;
114
183
  const safe = Number.isFinite(ms) ? Math.max(0, ms) : 0;
115
- if (opts.seconds && safe < 60_000) return `${round(safe / 1000)} s`;
184
+ if (opts.seconds && safe < 60_000) return w.s(round(safe / 1000));
116
185
  const min = round(safe / 60_000);
117
- if (min < 60) return `${min} min`;
186
+ if (min < 60) return w.min(min);
118
187
  const h = Math.floor(min / 60);
119
- if (h < 24) return opts.compact && min % 60 === 0 ? `${h} h` : `${h} h ${pad2(min % 60)}`;
120
- return opts.compact && h % 24 === 0 ? `${h / 24} d` : `${Math.floor(h / 24)} d ${h % 24} h`;
188
+ if (h < 24) return opts.compact && min % 60 === 0 ? w.h(h) : w.hm(h, min % 60);
189
+ return opts.compact && h % 24 === 0 ? w.d(h / 24) : w.dh(Math.floor(h / 24), h % 24);
121
190
  },
122
191
  };
192
+ return fmt;
123
193
  }
package/src/i18n.ts CHANGED
@@ -1,13 +1,166 @@
1
1
  /**
2
2
  * Plugin texts can be a plain string (shown as is) or a map by language.
3
- * The editor and the panel pick the user's locale, then English, then the
4
- * first one available.
3
+ * The editor and the panel pick the user's locale (see `pickLocale`), then
4
+ * English, then the first one available.
5
+ *
6
+ * Chinese goes by script: write `zh-Hant` (Taiwan, Hong Kong) and `zh-Hans`
7
+ * (mainland China). `zh-TW` and `zh-CN` work too; a bare `zh` is read as
8
+ * Simplified and never shown to someone who reads Traditional. The same
9
+ * holds for any language written in two scripts (`sr-Latn`, `sr-Cyrl`).
5
10
  */
6
11
  export type Localized = string | ({ en: string } & Partial<Record<string, string>>);
7
12
 
13
+ /** Old or other codes for the same language, as Intl leaves them. */
14
+ const ALIASES: Record<string, string> = { iw: 'he', in: 'id', ji: 'yi', tl: 'fil', no: 'nb', cmn: 'zh' };
15
+ /** Languages that read texts written for another one: Cantonese reads Chinese. */
16
+ const READS: Record<string, string> = { yue: 'zh', nn: 'nb' };
17
+
18
+ /**
19
+ * A language tag as Intl understands it, or null: POSIX forms cleaned
20
+ * (`zh_TW.UTF-8` → `zh-TW`, `sr_RS@latin` → `sr-Latn-RS`), old codes mapped
21
+ * (`iw` → `he`), case fixed.
22
+ */
23
+ export function parseLocale(tag: string | undefined): Intl.Locale | null {
24
+ if (!tag) return null;
25
+ let t = tag.trim();
26
+ const latin = /@latin\b/i.test(t);
27
+ t = t.replace(/[.@].*$/, '').replace(/_/g, '-');
28
+ if (!t || t === 'C' || t === 'POSIX') return null;
29
+ try {
30
+ let l = new Intl.Locale(Intl.getCanonicalLocales(t)[0]!);
31
+ const alias = ALIASES[l.language];
32
+ if (alias) l = new Intl.Locale(alias, { ...(l.script ? { script: l.script } : {}), ...(l.region ? { region: l.region } : {}) });
33
+ if (latin && !l.script) l = new Intl.Locale(l.language, { script: 'Latn', ...(l.region ? { region: l.region } : {}) });
34
+ return l;
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ /** Latin American regions: they read `es-419` (or the Mexican variant) before Spain's. */
41
+ const LATAM = new Set(['419', 'AR', 'BO', 'CL', 'CO', 'CR', 'CU', 'DO', 'EC', 'GT', 'HN', 'MX', 'NI', 'PA', 'PE', 'PR', 'PY', 'SV', 'US', 'UY', 'VE']);
42
+ /** Portuguese outside Brazil reads Portugal's before Brazil's. */
43
+ const PT_PT = new Set(['PT', 'AO', 'MZ', 'CV', 'GW', 'ST', 'TL', 'MO', 'GQ', 'LU', 'CH']);
44
+
45
+ /**
46
+ * The best of `available` (language tags, any case) for someone reading in
47
+ * `locale`, or undefined if none fits (the caller falls back to English).
48
+ *
49
+ * The same language and the same script, never another script: a reader
50
+ * of Traditional Chinese never gets Simplified (a bare `zh` is
51
+ * Simplified), nor a reader of Serbian in Latin letters Cyrillic. Among
52
+ * those: the exact tag, then the same region, then the region's usual
53
+ * variant (`es-419`/`es-MX` for Latin America, `pt-PT` outside Brazil),
54
+ * then the least specific one (`es` for `es-CL`), then any.
55
+ */
56
+ export function pickLocale(available: readonly string[], locale: string | undefined): string | undefined {
57
+ if (!locale || !available.length) return undefined;
58
+ const exact = available.find((k) => k.toLowerCase() === locale.replace(/_/g, '-').toLowerCase());
59
+ if (exact) return exact;
60
+ const want = parseLocale(locale);
61
+ if (!want) return undefined;
62
+ const w = want.maximize();
63
+ const lang = READS[w.language] ?? w.language;
64
+ const fits = available
65
+ .map((k) => ({ k, l: parseLocale(k) }))
66
+ .filter((c): c is { k: string; l: Intl.Locale } => !!c.l)
67
+ .map((c) => ({ ...c, m: c.l.maximize() }))
68
+ .filter((c) => (READS[c.m.language] ?? c.m.language) === lang && c.m.script === w.script);
69
+ if (!fits.length) return undefined;
70
+ const same = (a: Intl.Locale, b: Intl.Locale) => a.baseName === b.baseName;
71
+ const byTag = fits.find((c) => same(c.l, want));
72
+ if (byTag) return byTag.k;
73
+ if (w.region) {
74
+ const byRegion = fits.find((c) => c.m.region === w.region && c.l.region);
75
+ if (byRegion) return byRegion.k;
76
+ const usual = (r: string) => (lang === 'es' && LATAM.has(w.region!) ? ['419', 'MX'].includes(r) : lang === 'pt' && PT_PT.has(w.region!) ? r === 'PT' : false);
77
+ const variant = fits.find((c) => c.l.region && usual(c.l.region));
78
+ if (variant) return variant.k;
79
+ }
80
+ // The least specific: `es` before `es-ES`, `zh-Hant` before `zh-TW`.
81
+ const plain = [...fits].sort((a, b) => a.l.baseName.split('-').length - b.l.baseName.split('-').length);
82
+ return plain[0]!.k;
83
+ }
84
+
85
+ /** Plural forms of a text, as Intl.PluralRules names them; `other` is required. */
86
+ export type PluralForms = Partial<Record<Intl.LDMLPluralRule, string>> & { other: string };
87
+
88
+ /**
89
+ * `{n} files` in the user's language, with the plural form its rules ask
90
+ * for (Polish has four, Chinese one): `forms` by language, `{n}` filled in
91
+ * with the number written the language's way.
92
+ */
93
+ export function plural(n: number, forms: Record<string, PluralForms>, locale = 'en'): string {
94
+ const key = pickLocale(Object.keys(forms), locale) ?? (forms.en ? 'en' : Object.keys(forms)[0]!);
95
+ const f = forms[key]!;
96
+ let rule: Intl.LDMLPluralRule = 'other';
97
+ try {
98
+ rule = new Intl.PluralRules(key).select(n);
99
+ } catch {
100
+ /* an odd tag: other */
101
+ }
102
+ const text = f[rule] ?? f.other;
103
+ let num = String(n);
104
+ try {
105
+ num = new Intl.NumberFormat(key).format(n);
106
+ } catch {
107
+ /* as is */
108
+ }
109
+ return text.replaceAll('{n}', num);
110
+ }
111
+
8
112
  export function localize(text: Localized | undefined, locale = 'en'): string {
9
113
  if (text === undefined) return '';
10
114
  if (typeof text === 'string') return text;
11
- const lang = locale.toLowerCase().split(/[-_]/)[0]!;
12
- return text[locale] ?? text[lang] ?? text.en ?? Object.values(text).find((v) => typeof v === 'string') ?? '';
115
+ const key = pickLocale(Object.keys(text), locale);
116
+ return (key ? text[key] : undefined) ?? text.en ?? Object.values(text).find((v) => typeof v === 'string') ?? '';
117
+ }
118
+
119
+ /**
120
+ * The Han writing a locale reads in, for picking glyphs: the same character
121
+ * is drawn differently in Taiwan (`Hant`), Hong Kong (`Hant-HK`), mainland
122
+ * China (`Hans`), Japan (`Jpan`) and Korea (`Kore`). `null` for locales
123
+ * that do not write with Han characters.
124
+ *
125
+ * Goes by script, not by region code: `zh-TW`, `zh-Hant` and `zh-MO` are
126
+ * Traditional, `zh`, `zh-CN` and `zh-SG` Simplified.
127
+ */
128
+ export type HanScript = 'Hant' | 'Hant-HK' | 'Hans' | 'Jpan' | 'Kore';
129
+
130
+ export function hanScript(locale: string | undefined): HanScript | null {
131
+ const l = parseLocale(locale || 'en');
132
+ if (!l) return null;
133
+ const full = l.maximize();
134
+ switch (READS[full.language] ?? full.language) {
135
+ case 'zh':
136
+ if (full.script === 'Hant') return full.region === 'HK' || full.region === 'MO' ? 'Hant-HK' : 'Hant';
137
+ return 'Hans';
138
+ case 'ja':
139
+ return 'Jpan';
140
+ case 'ko':
141
+ return 'Kore';
142
+ default:
143
+ return null;
144
+ }
145
+ }
146
+
147
+ /**
148
+ * An error to show the user, in their language: `throw new PluginError({
149
+ * en: 'Set your place in Settings', 'zh-Hant': '請在設定中設定位置', … })`.
150
+ * Its `message` is the English one (logs); Kiosko shows `text` in the
151
+ * user's language in the editor and on the tile.
152
+ */
153
+ export class PluginError extends Error {
154
+ readonly text: Localized;
155
+ constructor(text: Localized, options?: { cause?: unknown }) {
156
+ super(localize(text, 'en'), options);
157
+ this.name = 'PluginError';
158
+ this.text = text;
159
+ }
160
+ }
161
+
162
+ /** What to show for an error: a PluginError's text in `locale`, else the message. */
163
+ export function errorMessage(err: unknown, locale = 'en'): string {
164
+ if (err instanceof Error && 'text' in err && (err as PluginError).text !== undefined) return localize((err as PluginError).text, locale);
165
+ return err instanceof Error ? err.message : String(err);
13
166
  }
package/src/index.ts CHANGED
@@ -2,6 +2,7 @@ export * from './plugin.ts';
2
2
  export * from './schema.ts';
3
3
  export * from './theme.ts';
4
4
  export * from './i18n.ts';
5
+ export * from './languages.ts';
5
6
  export * from './format.ts';
6
7
  export * from './workday.ts';
7
8
  export * from './list.ts';
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The languages Kiosko speaks: the editor, the site, the panel's words for
3
+ * times (ctx.fmt) and the official plugins. One list, read by all of them;
4
+ * a test (packages/web/landing/languages.test.ts) checks that each has its
5
+ * dictionary, site page, time words and plugin texts. Adding a language
6
+ * starts here (CONTRIBUTING.md, "Translations").
7
+ */
8
+ export interface Language {
9
+ /** BCP 47 tag, as the texts are keyed (`es`, `zh-Hant`). */
10
+ id: string;
11
+ /** Its name in itself, for the language pickers. */
12
+ name: string;
13
+ /** The locale the panel paints the site's samples in (dates, times): `zh-TW` for `zh-Hant`. */
14
+ panel: string;
15
+ /** Open Graph locale of its site page (`zh_TW`). */
16
+ ogLocale: string;
17
+ /** What its site page is declared to be for (`hreflang`); English is also `x-default`. */
18
+ hreflang: string[];
19
+ /** Writing direction. Right-to-left is not drawn right on the panel yet. */
20
+ dir: 'ltr' | 'rtl';
21
+ /**
22
+ * Where this language's readers live, the services some plugins need may not
23
+ * be offered. The site, the sample config and the editor's tour leave those
24
+ * plugins out for it (`without`), lead with others (`first`) and paint these
25
+ * widgets in place of the missing ones (`instead`, type by type).
26
+ */
27
+ plugins?: { without: readonly string[]; first: readonly string[]; instead: Readonly<Record<string, string>> };
28
+ }
29
+
30
+ /**
31
+ * Simplified Chinese is read in mainland China, where Claude (and Gemini) are
32
+ * not offered: no AI-agent, cats-room nor Claude-usage plugins there, and local
33
+ * models (Qwen, DeepSeek… on your own GPU) in their place.
34
+ */
35
+ const MAINLAND_CHINA: NonNullable<Language['plugins']> = {
36
+ without: ['agents', 'cats', 'usage'],
37
+ first: ['llm', 'gpu'],
38
+ instead: { 'agents/summary': 'llm/status', 'agents/sessions': 'llm/models', 'usage/rail': 'gpu/cards', 'cats/room': 'gpu/history' },
39
+ };
40
+
41
+ export const LANGUAGES: readonly Language[] = [
42
+ { id: 'en', name: 'English', panel: 'en', ogLocale: 'en_US', hreflang: ['en', 'x-default'], dir: 'ltr' },
43
+ { id: 'es', name: 'Español', panel: 'es', ogLocale: 'es_ES', hreflang: ['es'], dir: 'ltr' },
44
+ { id: 'de', name: 'Deutsch', panel: 'de', ogLocale: 'de_DE', hreflang: ['de'], dir: 'ltr' },
45
+ { id: 'zh-Hant', name: '繁體中文', panel: 'zh-TW', ogLocale: 'zh_TW', hreflang: ['zh-Hant', 'zh-TW', 'zh-HK'], dir: 'ltr' },
46
+ { id: 'zh-Hans', name: '简体中文', panel: 'zh-CN', ogLocale: 'zh_CN', hreflang: ['zh-Hans', 'zh-CN'], dir: 'ltr', plugins: MAINLAND_CHINA },
47
+ ];
48
+
49
+ export const LANGUAGE_IDS: readonly string[] = LANGUAGES.map((l) => l.id);
50
+
51
+ /** The language with this id (`zh-Hant`), if Kiosko speaks it. */
52
+ export function languageById(id: string): Language | undefined {
53
+ return LANGUAGES.find((l) => l.id === id);
54
+ }
package/src/list.ts CHANGED
@@ -34,9 +34,9 @@ export type ListLayout = 'one-line' | 'detailed';
34
34
  export type ListLayoutChoice = 'auto' | ListLayout;
35
35
 
36
36
  const LAYOUT_LABELS: Record<ListLayoutChoice, Localized> = {
37
- auto: { en: 'Automatic', es: 'Automático' },
38
- 'one-line': { en: 'One line', es: 'Una línea' },
39
- detailed: { en: 'Detailed', es: 'Detallado' },
37
+ auto: { en: 'Automatic', es: 'Automático', de: 'Automatisch', 'zh-Hant': '自動', 'zh-Hans': '自动' },
38
+ 'one-line': { en: 'One line', es: 'Una línea', de: 'Eine Zeile', 'zh-Hant': '單行', 'zh-Hans': '单行' },
39
+ detailed: { en: 'Detailed', es: 'Detallado', de: 'Ausführlich', 'zh-Hant': '詳細', 'zh-Hans': '详细' },
40
40
  };
41
41
 
42
42
  const rowsField = (def: number): NumberField =>
@@ -44,10 +44,13 @@ const rowsField = (def: number): NumberField =>
44
44
  default: def,
45
45
  min: 0,
46
46
  max: 30,
47
- label: { en: 'Rows', es: 'Filas' },
47
+ label: { en: 'Rows', es: 'Filas', de: 'Zeilen', 'zh-Hant': '列數', 'zh-Hans': '行数' },
48
48
  help: {
49
49
  en: '0 = as many as fit. A number shows that many, in rows of a readable size (fewer when the tile is too small for them); the rest are counted in "+N more".',
50
50
  es: '0 = las que quepan. Con un número se ven esas, en filas de un tamaño legible (menos si la tesela no da para ellas); el resto se cuenta en «+N más».',
51
+ de: '0 = so viele, wie passen. Eine Zahl zeigt so viele, in Zeilen lesbarer Größe (weniger, wenn die Kachel dafür zu klein ist); der Rest wird als „+N weitere“ gezählt.',
52
+ 'zh-Hant': '0 = 盡量放滿。填數字則顯示該數量,並以易讀的大小排列(方格太小時會減少);其餘的計入「還有 N 個」。',
53
+ 'zh-Hans': '0 = 尽量放满。填数字则显示该数量,并以易读的大小排列(格子太小时会减少);其余的计入“还有 N 个”。',
51
54
  },
52
55
  });
53
56
 
@@ -67,9 +70,9 @@ export function listOptions(o: { rows?: number; layouts?: readonly ListLayout[];
67
70
  rows,
68
71
  layout: t.enum(values, {
69
72
  default: o.layout ?? 'auto',
70
- label: { en: 'Row layout', es: 'Formato de fila' },
73
+ label: { en: 'Row layout', es: 'Formato de fila', de: 'Zeilenlayout', 'zh-Hant': '列版面', 'zh-Hans': '行布局' },
71
74
  labels: Object.fromEntries(values.map((v) => [v, LAYOUT_LABELS[v]])),
72
- help: { en: 'Automatic: the widget picks by the tile\'s shape.', es: 'Automático: el widget elige según la forma de la tesela.' },
75
+ help: { en: 'Automatic: the widget picks by the tile\'s shape.', es: 'Automático: el widget elige según la forma de la tesela.', de: 'Automatisch: Das Widget wählt nach der Form der Kachel.', 'zh-Hant': '自動:小工具依方格形狀選擇。', 'zh-Hans': '自动:小组件根据格子形状选择。' },
73
76
  }),
74
77
  };
75
78
  }
@@ -182,7 +185,7 @@ export function listLayout<L extends ListLayout>(box: Box, count: number, option
182
185
 
183
186
  /** `"+3 more"` / `"+3 más"`. */
184
187
  export function moreLabel(n: number, tr: (text: Localized) => string): string {
185
- return tr({ en: `+${n} more`, es: `+${n} más` });
188
+ return tr({ en: `+${n} more`, es: `+${n} más`, de: `+${n} weitere`, 'zh-Hant': `還有 ${n} 個`, 'zh-Hans': `还有 ${n} 个` });
186
189
  }
187
190
 
188
191
  type DrawCtx = Pick<RenderContext<unknown, unknown>, 'kit' | 'theme' | 't'>;
package/src/location.ts CHANGED
@@ -18,11 +18,11 @@ export function locationOptions(): { latitude: NumberField; longitude: NumberFie
18
18
  step: 0.0001,
19
19
  unit: '°',
20
20
  advanced: true,
21
- label: { en: 'Latitude', es: 'Latitud' },
22
- help: { en: 'Leave latitude and longitude at 0 to use the place in Settings.', es: 'Con latitud y longitud a 0 se usa el lugar de los ajustes.' },
21
+ label: { en: 'Latitude', es: 'Latitud', de: 'Breitengrad', 'zh-Hant': '緯度', 'zh-Hans': '纬度' },
22
+ help: { en: 'Leave latitude and longitude at 0 to use the place in Settings.', es: 'Con latitud y longitud a 0 se usa el lugar de los ajustes.', de: 'Breiten- und Längengrad auf 0 lassen, um den Ort aus den Einstellungen zu verwenden.', 'zh-Hant': '緯度和經度保持 0 即使用設定中的地點。', 'zh-Hans': '纬度和经度保持为 0 时使用设置中的地点。' },
23
23
  }),
24
- longitude: t.number({ default: 0, min: -180, max: 180, step: 0.0001, unit: '°', advanced: true, label: { en: 'Longitude', es: 'Longitud' } }),
25
- placeName: t.string({ advanced: true, placeholder: 'Madrid', label: { en: 'Place name', es: 'Nombre del lugar' }, help: { en: 'Empty: the one in Settings.', es: 'Vacío: el de los ajustes.' } }),
24
+ longitude: t.number({ default: 0, min: -180, max: 180, step: 0.0001, unit: '°', advanced: true, label: { en: 'Longitude', es: 'Longitud', de: 'Längengrad', 'zh-Hant': '經度', 'zh-Hans': '经度' } }),
25
+ placeName: t.string({ advanced: true, placeholder: 'Madrid', label: { en: 'Place name', es: 'Nombre del lugar', de: 'Ortsname', 'zh-Hant': '地點名稱', 'zh-Hans': '地点名称' }, help: { en: 'Empty: the one in Settings.', es: 'Vacío: el de los ajustes.', de: 'Leer: der aus den Einstellungen.', 'zh-Hant': '留空:使用設定中的地點。', 'zh-Hans': '留空:使用设置中的地点。' } }),
26
26
  };
27
27
  }
28
28
 
package/src/plugin.ts CHANGED
@@ -20,7 +20,7 @@
20
20
  import type { Canvas, Image, SKRSContext2D, createCanvas, loadImage } from '@napi-rs/canvas';
21
21
  import type * as Kit from '@loksly/lcd-canvas-kit';
22
22
  import type { Formatters } from './format.ts';
23
- import type { Localized } from './i18n.ts';
23
+ import type { Localized, PluralForms } from './i18n.ts';
24
24
  import type { Field, Infer, ObjectField } from './schema.ts';
25
25
  import type { Theme } from './theme.ts';
26
26
  import type { Workday } from './workday.ts';
@@ -62,15 +62,15 @@ export interface Size {
62
62
  export type Category = 'agents' | 'system' | 'time' | 'productivity' | 'dev' | 'info' | 'media' | 'scene' | 'fun';
63
63
 
64
64
  export const CATEGORIES: { id: Category; label: Localized }[] = [
65
- { id: 'agents', label: { en: 'AI agents', es: 'Agentes IA' } },
66
- { id: 'system', label: { en: 'System', es: 'Sistema' } },
67
- { id: 'time', label: { en: 'Time & calendar', es: 'Tiempo y agenda' } },
68
- { id: 'productivity', label: { en: 'Productivity', es: 'Productividad' } },
69
- { id: 'dev', label: { en: 'Development', es: 'Desarrollo' } },
70
- { id: 'info', label: { en: 'News & world', es: 'Noticias y mundo' } },
71
- { id: 'media', label: { en: 'Media', es: 'Multimedia' } },
72
- { id: 'scene', label: { en: 'Scenes', es: 'Escenas' } },
73
- { id: 'fun', label: { en: 'Fun', es: 'Diversión' } },
65
+ { id: 'agents', label: { en: 'AI agents', es: 'Agentes IA', de: 'KI-Agenten', 'zh-Hant': 'AI 代理', 'zh-Hans': 'AI 智能体' } },
66
+ { id: 'system', label: { en: 'System', es: 'Sistema', de: 'System', 'zh-Hant': '系統', 'zh-Hans': '系统' } },
67
+ { id: 'time', label: { en: 'Time & calendar', es: 'Tiempo y agenda', de: 'Zeit & Kalender', 'zh-Hant': '時間與行事曆', 'zh-Hans': '时间与日历' } },
68
+ { id: 'productivity', label: { en: 'Productivity', es: 'Productividad', de: 'Produktivität', 'zh-Hant': '生產力', 'zh-Hans': '效率' } },
69
+ { id: 'dev', label: { en: 'Development', es: 'Desarrollo', de: 'Entwicklung', 'zh-Hant': '開發', 'zh-Hans': '开发' } },
70
+ { id: 'info', label: { en: 'News & world', es: 'Noticias y mundo', de: 'Nachrichten & Welt', 'zh-Hant': '新聞與世界', 'zh-Hans': '新闻与世界' } },
71
+ { id: 'media', label: { en: 'Media', es: 'Multimedia', de: 'Medien', 'zh-Hant': '多媒體', 'zh-Hans': '多媒体' } },
72
+ { id: 'scene', label: { en: 'Scenes', es: 'Escenas', de: 'Szenen', 'zh-Hant': '場景', 'zh-Hans': '场景' } },
73
+ { id: 'fun', label: { en: 'Fun', es: 'Diversión', de: 'Spaß', 'zh-Hant': '趣味', 'zh-Hans': '趣味' } },
74
74
  ];
75
75
 
76
76
  export interface Logger {
@@ -92,6 +92,18 @@ export interface BaseContext {
92
92
  locale: string;
93
93
  /** Picks the user's language from a `Localized` text. */
94
94
  t: (text: Localized) => string;
95
+ /**
96
+ * `{n} files` with the plural form the user's language asks for:
97
+ * `ctx.plural(n, { en: { one: '{n} file', other: '{n} files' }, 'zh-Hant': { other: '{n} 個檔案' } })`.
98
+ * Use it for any text with a count in it, rather than `n === 1 ? … : …`.
99
+ */
100
+ plural: (n: number, forms: Record<string, PluralForms>) => string;
101
+ /**
102
+ * Which of `available` (language tags) to use for this user: for tables
103
+ * kept one per language (`TABLES[ctx.pickLanguage(Object.keys(TABLES))]`).
104
+ * English when none fits, else the first.
105
+ */
106
+ pickLanguage: (available: readonly string[]) => string;
95
107
  /**
96
108
  * Times and lengths of time in the user's language and clock (Settings →
97
109
  * time format): `fmt.time(at)` "14:05" / "2:05 PM", `fmt.ago(at)`
@@ -430,7 +442,7 @@ export interface InterludeDefinition<OF extends ObjectField<any> = ObjectField<a
430
442
  * package.json, `"kiosko": { "sdk": "^0.2.0" }`, so it can be refused before
431
443
  * it runs); the registry compares them with `satisfies`.
432
444
  */
433
- export const SDK_VERSION = '0.2.5';
445
+ export const SDK_VERSION = '0.2.6';
434
446
 
435
447
  /**
436
448
  * What a plugin does on the machine, declared for the person who installs
@@ -519,6 +531,15 @@ export interface PluginDefinition {
519
531
  optional?: string[];
520
532
  /** The operating systems it works on. Omitted: all. Also npm's `os` in package.json. */
521
533
  platforms?: Platform[];
534
+ /**
535
+ * The languages its texts come in, as BCP 47 tags, English first:
536
+ * `['en', 'es', 'zh-Hant', 'zh-Hans']`. Chinese goes by script (`zh-Hant`
537
+ * for Taiwan and Hong Kong, `zh-Hans` for mainland China), never a bare
538
+ * `zh`. Every `Localized` text of the plugin has them all (the linter
539
+ * says which lack one). Also `kiosko.languages` in package.json, so a
540
+ * catalogue knows without running it. Omitted: the ones its texts use.
541
+ */
542
+ languages?: string[];
522
543
  widgets?: WidgetDefinition<any, any>[];
523
544
  sources?: SourceDefinition<any, any>[];
524
545
  interludes?: InterludeDefinition<any>[];