@vdatacloud/cx-commons 0.1.8 → 0.1.9

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/README.md CHANGED
@@ -42,7 +42,7 @@ This repository publishes `@vdatacloud/cx-commons` with modular export entry poi
42
42
  ├── (default) --> exports index.ts (Astro integration plugin `cxCommons()`)
43
43
  ├── /styles/global.css --> exports canonical LNF design system tokens & Tailwind rules
44
44
  ├── /components/* --> exports shared Astro UI components (Nav, Footer, StatusBadge, EyebrowLabel, ApiErrorNotice, CantonId)
45
- ├── /sdk/* --> exports browser SDK helpers (api-error, api-error-notice, canton-id, canton-id-view, status-colors)
45
+ ├── /sdk/* --> exports browser SDK helpers (i18n, cx-messages, api-error, api-error-notice, canton-id, canton-id-view, status-colors)
46
46
  └── /schema/api-error.json --> the canonical API error JSON Schema
47
47
  ```
48
48
 
@@ -83,6 +83,29 @@ There are three kinds of Canton id. Each has one parser and one short form, mirr
83
83
 
84
84
  ---
85
85
 
86
+ ### Internationalization (`sdk/i18n`, `sdk/cx-messages`)
87
+
88
+ Zero-dependency i18n for every app on the platform (English and French today; built so Japanese, Chinese and
89
+ Korean are catalog work, not a rewrite). Vocabulary follows daml-escrow's `docs/i18n/GLOSSARY.md`.
90
+
91
+ - **Messages:** an ICU MessageFormat subset -- `{name}`, `{n, plural, one {# item} other {# items}}`,
92
+ `{kind, select, ...}` -- over `Intl.PluralRules`. Apostrophes are plain text (French), so literal braces aren't
93
+ supported. Never concatenate fragments; word order differs between languages.
94
+ - **Catalogs:** `registerMessages({ en: {...}, fr: {...} })` -- an app's catalogs override the library defaults
95
+ (cx-commons registers its own `cx.*` strings on import). `getTranslator(locale)` -> `t(key, params)`, falling
96
+ back `fr-CA` -> `fr` -> `en` -> the key; `maybe(key)` returns `undefined` instead.
97
+ - **Choosing the language:** `resolveLocale({ cookie, acceptLanguage, supported })` -- the remembered choice
98
+ (`locale` cookie, `localeCookie()` / `chooseLocale()`), else `Accept-Language`, else English. No URL prefix.
99
+ Set `<html lang>`; client code reads it via `documentLocale()`.
100
+ - **Formatting:** `formatNumber`, `formatMoney` (always with the code; non-ISO instruments such as USDC after the
101
+ amount; ledger Decimal strings keep their precision), `formatDate`, `formatDateTime`, `formatRelativeTime` --
102
+ use these, never `toLocaleString()`.
103
+ - **Components** take an optional `locale` prop (else `Astro.locals.locale`, else `Astro.currentLocale`, else
104
+ `en`). `StatusBadge` shows `cx.status.<STATUS>` (e.g. `FUNDED` -> "Funds committed"); `ApiErrorNotice` /
105
+ `renderApiErrorNotice` translate `errors.<CODE>.message|hint` and `stages.<stage>` when the app registers them,
106
+ keeping the server's original message in the details.
107
+ - **CJK:** elements that uppercase/letter-space carry `.cx-caps`, switched off under `:lang(ja|zh|ko)`.
108
+
86
109
  ## 5. Quick Start & Integration Guide
87
110
 
88
111
  ### Step 1: Install or Link Package
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vdatacloud/cx-commons",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "description": "Product CX Commons - Shared design system, UI components, and Astro integration for Data Cloud web applications",
5
5
  "repository": {
6
6
  "type": "git",
@@ -11,12 +11,14 @@ export interface Props {
11
11
  error: ApiError;
12
12
  level?: ApiErrorDetail;
13
13
  class?: string;
14
+ locale?: string;
14
15
  }
15
16
 
16
17
  const { error, level = 'full', class: className = '' } = Astro.props;
18
+ const locale = Astro.props.locale ?? (Astro.locals as { locale?: string }).locale ?? Astro.currentLocale ?? 'en';
17
19
  ---
18
20
 
19
- <div data-api-error={canonicalApiError(error, level)} data-api-error-level={level} class={className}>
21
+ <div data-api-error={canonicalApiError(error, level)} data-api-error-level={level} data-api-error-locale={locale} class={className}>
20
22
  <p role="alert" class="rounded-2xl border border-status-disputed/30 bg-status-disputed/5 p-4 text-sm text-slate-800 dark:border-status-disputed/20 dark:bg-status-disputed/10 dark:text-slate-100">
21
23
  {formatApiError(error)}
22
24
  </p>
@@ -12,9 +12,11 @@ export interface Props {
12
12
  value: string;
13
13
  label?: string;
14
14
  copy?: boolean;
15
+ locale?: string;
15
16
  }
16
17
 
17
18
  const { value, label, copy = true } = Astro.props;
19
+ const locale = Astro.props.locale ?? (Astro.locals as { locale?: string }).locale ?? Astro.currentLocale ?? 'en';
18
20
  ---
19
21
 
20
22
  <span
@@ -22,6 +24,7 @@ const { value, label, copy = true } = Astro.props;
22
24
  data-canton-id={value}
23
25
  data-canton-id-label={label}
24
26
  data-canton-id-copy={copy ? 'true' : 'false'}
27
+ data-canton-id-locale={locale}
25
28
  >
26
29
  <span class={label ? CANTON_ID_LABEL_CLASS : CANTON_ID_TEXT_CLASS} title={cantonIdTitle(value, label)}>{label || shortCantonId(value)}</span>
27
30
  </span>
@@ -17,6 +17,6 @@ const colorStyles = {
17
17
  const currentColor = colorClass || colorStyles[color];
18
18
  ---
19
19
 
20
- <span class={`block text-[10px] font-black uppercase tracking-widest mb-1.5 ${currentColor} ${className}`}>
20
+ <span class={`cx-caps block text-[10px] font-black uppercase tracking-widest mb-1.5 ${currentColor} ${className}`}>
21
21
  <slot>{text}</slot>
22
22
  </span>
@@ -1,8 +1,14 @@
1
1
  ---
2
+ import { getTranslator } from '../sdk/i18n';
3
+ import '../sdk/cx-messages';
4
+
2
5
  export interface Props {
3
6
  showTelemetry?: boolean;
7
+ locale?: string;
4
8
  }
5
9
  const { showTelemetry = false } = Astro.props;
10
+ const locale = Astro.props.locale ?? (Astro.locals as { locale?: string }).locale ?? Astro.currentLocale ?? 'en';
11
+ const t = getTranslator(locale);
6
12
  const year = new Date().getFullYear();
7
13
  ---
8
14
 
@@ -13,22 +19,22 @@ const year = new Date().getFullYear();
13
19
  class="container mx-auto flex flex-col md:flex-row justify-between items-center gap-4 text-xs font-medium text-slate-500 dark:text-slate-400"
14
20
  >
15
21
  <div class="flex items-center gap-3">
16
- <p>copyright (c) {year}, Data Cloud, LLC, All Rights Reserved</p>
22
+ <p>{t.t('cx.footer.copyright', { year: String(year) })}</p>
17
23
  </div>
18
24
 
19
- <div class="flex items-center gap-5 uppercase tracking-wider font-black text-[10px]">
25
+ <div class="cx-caps flex items-center gap-5 uppercase tracking-wider font-black text-[10px]">
20
26
  <a href="/terms-and-conditions/" class="hover:text-brand-600 dark:hover:text-brand-400 transition-colors">
21
- Terms and Conditions
27
+ {t.t('cx.footer.terms')}
22
28
  </a>
23
29
  <a href="/privacy-policy/" class="hover:text-brand-600 dark:hover:text-brand-400 transition-colors">
24
- Privacy Policy
30
+ {t.t('cx.footer.privacy')}
25
31
  </a>
26
32
  <button
27
33
  id="open-cookie-preferences"
28
34
  type="button"
29
- class="hover:text-brand-600 dark:hover:text-brand-400 transition-colors border-none bg-transparent cursor-pointer uppercase tracking-wider font-black text-[10px] p-0"
35
+ class="cx-caps hover:text-brand-600 dark:hover:text-brand-400 transition-colors border-none bg-transparent cursor-pointer uppercase tracking-wider font-black text-[10px] p-0"
30
36
  >
31
- Cookie Preferences
37
+ {t.t('cx.footer.cookies')}
32
38
  </button>
33
39
  </div>
34
40
  </div>
@@ -1,4 +1,7 @@
1
1
  ---
2
+ import { getTranslator } from '../sdk/i18n';
3
+ import '../sdk/cx-messages';
4
+
2
5
  export interface NavItem {
3
6
  href: string;
4
7
  label: string;
@@ -8,14 +11,18 @@ export interface Props {
8
11
  navLinks?: NavItem[];
9
12
  brandName?: string;
10
13
  logoSrc?: string;
14
+ locale?: string;
11
15
  }
12
16
 
17
+ const locale = Astro.props.locale ?? (Astro.locals as { locale?: string }).locale ?? Astro.currentLocale ?? 'en';
18
+ const t = getTranslator(locale);
19
+
13
20
  const {
14
21
  navLinks = [
15
- { href: '/', label: 'Home' },
16
- { href: '/products/tripart/', label: 'Products' },
17
- { href: '/blog/', label: 'Blog' },
18
- { href: '/about/', label: 'About' },
22
+ { href: '/', label: t.t('cx.nav.home') },
23
+ { href: '/products/tripart/', label: t.t('cx.nav.products') },
24
+ { href: '/blog/', label: t.t('cx.nav.blog') },
25
+ { href: '/about/', label: t.t('cx.nav.about') },
19
26
  ],
20
27
  brandName = 'Data Cloud LLC',
21
28
  logoSrc = '/favicon.svg'
@@ -35,7 +42,7 @@ const currentPath = Astro.url.pathname;
35
42
  <span class="text-sm font-black tracking-tight text-slate-800 dark:text-white uppercase">{brandName}</span>
36
43
  </a>
37
44
 
38
- <div class="flex flex-wrap items-center gap-3 sm:gap-6 text-xs font-black uppercase tracking-wider">
45
+ <div class="cx-caps flex flex-wrap items-center gap-3 sm:gap-6 text-xs font-black uppercase tracking-wider">
39
46
  {
40
47
  navLinks.map((link) => {
41
48
  const isActive = link.href === '/' ? currentPath === '/' : currentPath.startsWith(link.href);
@@ -58,7 +65,7 @@ const currentPath = Astro.url.pathname;
58
65
  <button
59
66
  id="theme-toggle"
60
67
  type="button"
61
- aria-label="Toggle dark mode"
68
+ aria-label={t.t('cx.nav.toggleDarkMode')}
62
69
  class="p-2 rounded-xl text-slate-500 dark:text-slate-400 hover:bg-slate-200/50 dark:hover:bg-slate-800/50 transition-colors border-none bg-transparent cursor-pointer"
63
70
  >
64
71
  <svg
@@ -1,11 +1,18 @@
1
1
  ---
2
+ import { getTranslator } from '../sdk/i18n';
3
+ import '../sdk/cx-messages';
4
+
2
5
  export interface Props {
3
6
  status: 'DRAFT' | 'FUNDED' | 'ACTIVE' | 'PROPOSED' | 'DISPUTED' | 'ARBITRATION' | 'SETTLED' | 'AWAITING_CUSTODY_APPROVAL' | 'FIAT_PENDING' | 'LAPSED' | string;
4
7
  size?: 'sm' | 'md';
5
8
  colorClass?: string;
9
+ /** Overrides the translated label (cx.status.<STATUS>). */
10
+ label?: string;
11
+ locale?: string;
6
12
  }
7
13
 
8
- const { status, size = 'sm', colorClass } = Astro.props;
14
+ const { status, size = 'sm', colorClass, label } = Astro.props;
15
+ const locale = Astro.props.locale ?? (Astro.locals as { locale?: string }).locale ?? Astro.currentLocale ?? 'en';
9
16
 
10
17
  const statusUpper = status.toUpperCase();
11
18
 
@@ -22,6 +29,8 @@ const badgeStyles: Record<string, string> = {
22
29
  LAPSED: 'text-status-lapsed bg-status-lapsed/10 border-status-lapsed/20 dark:bg-status-lapsed/5 dark:border-status-lapsed/10',
23
30
  };
24
31
 
32
+ const text = label ?? getTranslator(locale).maybe(`cx.status.${statusUpper}`) ?? statusUpper.replaceAll('_', ' ');
33
+
25
34
  const currentStyle = colorClass || badgeStyles[statusUpper] || badgeStyles.DRAFT;
26
35
 
27
36
  const sizeStyles = {
@@ -30,6 +39,6 @@ const sizeStyles = {
30
39
  };
31
40
  ---
32
41
 
33
- <span class={`inline-flex items-center justify-center rounded-full border uppercase transition-all duration-300 ${currentStyle} ${sizeStyles[size]}`}>
34
- <slot>{statusUpper.replace('_', ' ')}</slot>
42
+ <span class={`inline-flex items-center justify-center cx-caps rounded-full border uppercase transition-all duration-300 ${currentStyle} ${sizeStyles[size]}`}>
43
+ <slot>{text}</slot>
35
44
  </span>
@@ -6,14 +6,25 @@
6
6
 
7
7
  import { canonicalApiError, atDetail, type ApiError, type ApiErrorDetail } from './api-error';
8
8
  import { renderCantonId } from './canton-id-view';
9
+ import { getTranslator, type Translator } from './i18n';
10
+ import './cx-messages';
9
11
 
10
12
  export interface ApiErrorNoticeOptions {
11
13
  /** 'full' (default) shows details in a collapsed section; 'summary' omits them. */
12
14
  level?: ApiErrorDetail;
13
15
  /** Adds a dismiss button that calls this. */
14
16
  onDismiss?: () => void;
17
+ /** Locale for labels and translated messages (default: the page's <html lang>). */
18
+ locale?: string;
15
19
  }
16
20
 
21
+ // Translation by code (daml-escrow PLAN.md Phase 71): servers answer in
22
+ // English; an app that registers `errors.<CODE>.message` / `errors.<CODE>.hint`
23
+ // (and `stages.<stage>`) gets them shown in the person's language. Message
24
+ // params: {status}, {stage}, {service} and every string detail. When a
25
+ // translation replaces the server's text, the original stays in the details
26
+ // (support works from the English message and the request id).
27
+
17
28
  // Retryable/transient failures render in the warning tone, the rest in the
18
29
  // error tone. Class strings are spelled out in full for Tailwind's scanner.
19
30
  const TRANSIENT = new Set(['RATE_LIMITED', 'UNAVAILABLE', 'TIMEOUT', 'LEDGER_UNAVAILABLE', 'LEDGER_CONFLICT', 'CONFLICT']);
@@ -29,11 +40,11 @@ const TONE = {
29
40
  chip: 'text-status-proposed bg-status-proposed/10 border-status-proposed/20 dark:bg-status-proposed/5 dark:border-status-proposed/10',
30
41
  },
31
42
  };
32
- const CHIP_BASE = 'inline-flex items-center rounded-full border px-2 py-0.5 font-mono text-[10px] font-black tracking-widest uppercase';
43
+ const CHIP_BASE = 'cx-caps inline-flex items-center rounded-full border px-2 py-0.5 font-mono text-[10px] font-black tracking-widest uppercase';
33
44
  const NEUTRAL_CHIP = 'text-slate-600 bg-slate-100 border-slate-200 dark:text-slate-300 dark:bg-slate-800 dark:border-slate-700';
34
45
  const MONO = 'font-mono text-xs break-all text-slate-700 dark:text-slate-200';
35
46
  const LABEL = 'text-[11px] font-semibold text-slate-500 dark:text-slate-400';
36
- const BUTTON = 'rounded-md border border-slate-200 px-2 py-0.5 text-[10px] font-bold uppercase tracking-widest text-slate-600 hover:bg-slate-100 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800';
47
+ const BUTTON = 'cx-caps rounded-md border border-slate-200 px-2 py-0.5 text-[10px] font-bold uppercase tracking-widest text-slate-600 hover:bg-slate-100 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800';
37
48
 
38
49
  function el<K extends keyof HTMLElementTagNameMap>(tag: K, className = '', text?: string): HTMLElementTagNameMap[K] {
39
50
  const n = document.createElement(tag);
@@ -42,15 +53,15 @@ function el<K extends keyof HTMLElementTagNameMap>(tag: K, className = '', text?
42
53
  return n;
43
54
  }
44
55
 
45
- function copyButton(label: string, value: () => string): HTMLButtonElement {
56
+ function copyButton(t: Translator, label: string, value: () => string): HTMLButtonElement {
46
57
  const b = el('button', BUTTON, label);
47
58
  b.type = 'button';
48
59
  b.addEventListener('click', async () => {
49
60
  try {
50
61
  await navigator.clipboard.writeText(value());
51
- b.textContent = 'Copied';
62
+ b.textContent = t.t('cx.copied');
52
63
  } catch {
53
- b.textContent = 'Copy failed';
64
+ b.textContent = t.t('cx.copyFailed');
54
65
  }
55
66
  setTimeout(() => (b.textContent = label), 1500);
56
67
  });
@@ -59,41 +70,31 @@ function copyButton(label: string, value: () => string): HTMLButtonElement {
59
70
 
60
71
  // row is a labeled value: ids through the shared CantonId display (short,
61
72
  // full on hover, copy); plain values as-is with a copy button.
62
- function row(label: string, value: string, asId = true): HTMLElement {
73
+ function row(t: Translator, label: string, value: string, asId = true): HTMLElement {
63
74
  const r = el('div', 'flex flex-wrap items-center gap-2');
64
75
  r.append(el('dt', LABEL, label));
65
76
  const dd = el('dd', 'min-w-0');
66
77
  if (asId) {
67
- dd.append(renderCantonId(value));
78
+ dd.append(renderCantonId(value, { locale: t.locale }));
68
79
  } else {
69
- dd.append(el('span', MONO, value), document.createTextNode(' '), copyButton('Copy', () => value));
80
+ dd.append(el('span', MONO, value), document.createTextNode(' '), copyButton(t, t.t('cx.copy'), () => value));
70
81
  }
71
82
  r.append(dd);
72
83
  return r;
73
84
  }
74
85
 
75
- // Known detail keys read as words a person recognizes; any other key is
76
- // split from camelCase ("publicKeyFingerprint" -> "Public key fingerprint").
77
- const DETAIL_LABELS: Record<string, string> = {
78
- party: 'Account (party)',
79
- partyFingerprint: 'Account key fingerprint',
80
- publicKeyFingerprint: 'Your key fingerprint',
81
- signatureReceived: 'Signature received',
82
- signedBy: 'Signed by key',
83
- signedMessage: 'What was signed',
84
- expectedHash: 'Expected transaction hash',
85
- computedHash: 'Computed transaction hash',
86
- ledgerUser: 'Ledger user',
87
- actAs: 'Acting as',
88
- };
86
+ // Known detail keys read as words a person recognizes (cx.detail.<key> in
87
+ // the catalogs, overridable by the app); any other key is split from
88
+ // camelCase ("publicKeyFingerprint" -> "Public key fingerprint").
89
89
 
90
90
  /** A readable label for a details key. */
91
- export function detailLabel(key: string): string {
91
+ export function detailLabel(key: string, locale?: string): string {
92
+ const t = getTranslator(locale);
92
93
  const m = /^(.*)\[(\d+)\]$/.exec(key);
93
94
  const base = m ? m[1] : key;
94
- const label = DETAIL_LABELS[base] ??
95
+ const label = t.maybe(`cx.detail.${base}`) ??
95
96
  base.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/^./, (c) => c.toUpperCase()).replace(/ ([A-Z])(?=[a-z])/g, (_, c) => ' ' + c.toLowerCase());
96
- return m ? `${label} ${Number(m[2]) + 1}` : label;
97
+ return m ? t.t('cx.numbered', { label, n: Number(m[2]) + 1 }) : label;
97
98
  }
98
99
 
99
100
  function detailValue(v: unknown): string {
@@ -106,10 +107,16 @@ function detailValue(v: unknown): string {
106
107
  export function renderApiErrorNotice(e: ApiError, opts: ApiErrorNoticeOptions = {}): HTMLElement {
107
108
  const level = opts.level ?? 'full';
108
109
  const shown = atDetail(e, level);
110
+ const t = getTranslator(opts.locale);
111
+ const params: Record<string, string | number> = { status: e.status ?? '', stage: e.stage ?? '', service: e.upstream?.service ?? '' };
112
+ for (const [k, v] of Object.entries(e.details ?? {})) if (typeof v === 'string') params[k] = v;
113
+ const message = t.maybe(`errors.${e.code}.message`, params) ?? e.error;
114
+ const hint = e.hint ? (t.maybe(`errors.${e.code}.hint`, params) ?? e.hint) : t.maybe(`errors.${e.code}.hint`, params);
109
115
  const tone = TRANSIENT.has(e.code) ? TONE.warning : TONE.error;
110
116
 
111
117
  const root = el('div', `rounded-2xl border p-4 text-sm text-slate-800 dark:text-slate-100 ${tone.box}`);
112
118
  root.setAttribute('role', 'alert');
119
+ root.lang = t.locale;
113
120
  root.dataset.apiErrorCode = e.code;
114
121
 
115
122
  const layout = el('div', 'flex items-start gap-3');
@@ -119,9 +126,9 @@ export function renderApiErrorNotice(e: ApiError, opts: ApiErrorNoticeOptions =
119
126
  root.append(layout);
120
127
 
121
128
  const head = el('div', 'flex items-start justify-between gap-2');
122
- head.append(el('p', 'font-semibold', e.error));
129
+ head.append(el('p', 'font-semibold', message));
123
130
  if (opts.onDismiss) {
124
- const close = el('button', BUTTON, 'Dismiss');
131
+ const close = el('button', BUTTON, t.t('cx.dismiss'));
125
132
  close.type = 'button';
126
133
  close.addEventListener('click', () => opts.onDismiss?.());
127
134
  head.append(close);
@@ -130,32 +137,37 @@ export function renderApiErrorNotice(e: ApiError, opts: ApiErrorNoticeOptions =
130
137
 
131
138
  const chips = el('div', 'flex flex-wrap gap-1.5');
132
139
  chips.append(el('span', `${CHIP_BASE} ${tone.chip}`, e.code));
133
- if (e.stage) chips.append(el('span', `${CHIP_BASE} ${NEUTRAL_CHIP}`, e.stage));
140
+ if (e.stage) chips.append(el('span', `${CHIP_BASE} ${NEUTRAL_CHIP}`, t.maybe(`stages.${e.stage}`) ?? e.stage));
134
141
  if (e.upstream && (e.upstream.grpcCode || e.upstream.code)) {
135
142
  chips.append(el('span', `${CHIP_BASE} ${NEUTRAL_CHIP}`, `${e.upstream.service} ${e.upstream.grpcCode || e.upstream.code}`));
136
143
  }
137
144
  body.append(chips);
138
145
 
139
- if (e.hint) body.append(el('p', 'text-slate-600 dark:text-slate-300', e.hint));
146
+ if (hint) body.append(el('p', 'text-slate-600 dark:text-slate-300', hint));
140
147
 
141
148
  const meta = el('dl', 'space-y-1');
142
- if (e.requestId) meta.append(row('Request', e.requestId));
143
- if (e.upstream?.traceId) meta.append(row('Trace', e.upstream.traceId));
144
- if (e.upstream?.node) meta.append(row('Node', e.upstream.node, false));
149
+ if (e.requestId) meta.append(row(t, t.t('cx.request'), e.requestId));
150
+ if (e.upstream?.traceId) meta.append(row(t, t.t('cx.trace'), e.upstream.traceId));
151
+ if (e.upstream?.node) meta.append(row(t, t.t('cx.node'), e.upstream.node, false));
145
152
  if (meta.childElementCount) body.append(meta);
146
153
 
154
+ const translated = message !== e.error;
147
155
  const hasDetails = shown.details && Object.keys(shown.details).length > 0;
148
- if (hasDetails || shown.upstream?.cause) {
156
+ if (hasDetails || shown.upstream?.cause || translated) {
149
157
  const det = el('details', 'rounded-lg border border-slate-200 p-2 dark:border-slate-700');
150
- det.append(el('summary', `${LABEL} cursor-pointer select-none`, 'Details'));
158
+ det.append(el('summary', `${LABEL} cursor-pointer select-none`, t.t('cx.details')));
151
159
  const dl = el('dl', 'mt-2 space-y-1');
152
- if (shown.upstream?.cause) dl.append(row(`${shown.upstream.service.charAt(0).toUpperCase()}${shown.upstream.service.slice(1)} says`, shown.upstream.cause, false));
160
+ if (translated) dl.append(row(t, t.t('cx.originalMessage'), e.error, false));
161
+ if (shown.upstream?.cause) {
162
+ const service = `${shown.upstream.service.charAt(0).toUpperCase()}${shown.upstream.service.slice(1)}`;
163
+ dl.append(row(t, t.t('cx.upstreamSays', { service }), shown.upstream.cause, false));
164
+ }
153
165
  for (const k of Object.keys(shown.details ?? {}).sort()) {
154
166
  const v = shown.details![k];
155
167
  if (Array.isArray(v) && v.every((x) => typeof x === 'string')) {
156
- v.forEach((x, i) => dl.append(row(detailLabel(v.length > 1 ? `${k}[${i}]` : k), x)));
168
+ v.forEach((x, i) => dl.append(row(t, detailLabel(v.length > 1 ? `${k}[${i}]` : k, t.locale), x)));
157
169
  } else {
158
- dl.append(row(detailLabel(k), detailValue(v), typeof v === 'string'));
170
+ dl.append(row(t, detailLabel(k, t.locale), detailValue(v), typeof v === 'string'));
159
171
  }
160
172
  }
161
173
  det.append(dl);
@@ -163,7 +175,7 @@ export function renderApiErrorNotice(e: ApiError, opts: ApiErrorNoticeOptions =
163
175
  }
164
176
 
165
177
  const actions = el('div', 'flex gap-2');
166
- actions.append(copyButton('Copy error JSON', () => canonicalApiError(e, level)));
178
+ actions.append(copyButton(t, t.t('cx.copyErrorJson'), () => canonicalApiError(e, level)));
167
179
  body.append(actions);
168
180
  return root;
169
181
  }
@@ -185,7 +197,7 @@ export function hydrateApiErrorNotices(root: ParentNode = document): void {
185
197
  try {
186
198
  const e = JSON.parse(host.dataset.apiError ?? '') as ApiError;
187
199
  const level = host.dataset.apiErrorLevel === 'summary' ? 'summary' : 'full';
188
- mountApiErrorNotice(host, e, { level });
200
+ mountApiErrorNotice(host, e, { level, locale: host.dataset.apiErrorLocale || undefined });
189
201
  host.dataset.apiErrorRendered = '';
190
202
  } catch {
191
203
  // leave the server-rendered fallback text in place
@@ -6,19 +6,23 @@
6
6
  // textContent only.
7
7
 
8
8
  import { shortCantonId, classifyCantonId, type CantonIdKind } from './canton-id';
9
+ import { getTranslator } from './i18n';
10
+ import './cx-messages';
9
11
 
10
12
  export interface CantonIdOptions {
11
13
  /** A human label shown instead of the short id (e.g. "Joey Depositor"); hover then shows both. */
12
14
  label?: string;
13
15
  /** Adds a copy button (default true). */
14
16
  copy?: boolean;
17
+ /** Locale for the button text (default: the page's <html lang>). */
18
+ locale?: string;
15
19
  }
16
20
 
17
21
  export const CANTON_ID_CLASS = 'inline-flex max-w-full items-center gap-1.5 align-middle';
18
22
  export const CANTON_ID_TEXT_CLASS = 'font-mono text-xs break-all text-slate-700 dark:text-slate-200';
19
23
  export const CANTON_ID_LABEL_CLASS = 'text-xs font-semibold text-slate-800 dark:text-slate-100';
20
24
  export const CANTON_ID_COPY_CLASS =
21
- 'rounded-md border border-slate-200 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-widest text-slate-600 hover:bg-slate-100 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800';
25
+ 'cx-caps rounded-md border border-slate-200 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-widest text-slate-600 hover:bg-slate-100 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800';
22
26
 
23
27
  /** The hover text: the full value, under the label and short form when labeled. */
24
28
  export function cantonIdTitle(value: string, label?: string): string {
@@ -44,16 +48,17 @@ export function renderCantonId(value: string, opts: CantonIdOptions = {}): HTMLE
44
48
  const b = document.createElement('button');
45
49
  b.type = 'button';
46
50
  b.className = CANTON_ID_COPY_CLASS;
47
- b.textContent = 'Copy';
48
- b.setAttribute('aria-label', `Copy ${kind === 'party' ? 'party id' : kind === 'fingerprint' ? 'fingerprint' : 'value'}`);
51
+ const t = getTranslator(opts.locale);
52
+ b.textContent = t.t('cx.copy');
53
+ b.setAttribute('aria-label', t.t('cx.copyId', { kind }));
49
54
  b.addEventListener('click', async () => {
50
55
  try {
51
56
  await navigator.clipboard.writeText(value);
52
- b.textContent = 'Copied';
57
+ b.textContent = t.t('cx.copied');
53
58
  } catch {
54
- b.textContent = 'Copy failed';
59
+ b.textContent = t.t('cx.copyFailed');
55
60
  }
56
- setTimeout(() => (b.textContent = 'Copy'), 1500);
61
+ setTimeout(() => (b.textContent = t.t('cx.copy')), 1500);
57
62
  });
58
63
  root.append(b);
59
64
  }
@@ -67,7 +72,11 @@ export function renderCantonId(value: string, opts: CantonIdOptions = {}): HTMLE
67
72
  export function hydrateCantonIds(root: ParentNode = document): void {
68
73
  root.querySelectorAll<HTMLElement>('[data-canton-id]:not([data-canton-id-rendered])').forEach((host) => {
69
74
  const value = host.dataset.cantonId ?? '';
70
- const rendered = renderCantonId(value, { label: host.dataset.cantonIdLabel || undefined, copy: host.dataset.cantonIdCopy !== 'false' });
75
+ const rendered = renderCantonId(value, {
76
+ label: host.dataset.cantonIdLabel || undefined,
77
+ copy: host.dataset.cantonIdCopy !== 'false',
78
+ locale: host.dataset.cantonIdLocale || undefined,
79
+ });
71
80
  rendered.dataset.cantonIdRendered = '';
72
81
  host.replaceWith(rendered);
73
82
  });
@@ -0,0 +1,133 @@
1
+ // cx-commons' own strings, in every locale it ships (daml-escrow PLAN.md
2
+ // Phase 71). Registered as library defaults on import, so an app's catalogs
3
+ // override any of them by key. Vocabulary follows daml-escrow
4
+ // docs/i18n/GLOSSARY.md (e.g. "Ledger ID", D1). French is a machine draft
5
+ // pending review (D12).
6
+
7
+ import { registerMessages, type Catalogs } from './i18n';
8
+
9
+ export const cxMessages = {
10
+ en: {
11
+ cx: {
12
+ copy: 'Copy',
13
+ copied: 'Copied',
14
+ copyFailed: 'Copy failed',
15
+ dismiss: 'Dismiss',
16
+ details: 'Details',
17
+ copyErrorJson: 'Copy error JSON',
18
+ request: 'Request',
19
+ trace: 'Trace',
20
+ node: 'Node',
21
+ upstreamSays: '{service} says',
22
+ originalMessage: 'Original message',
23
+ copyId: '{kind, select, party {Copy ledger ID} fingerprint {Copy key fingerprint} hash {Copy hash} other {Copy value}}',
24
+ numbered: '{label} {n}',
25
+ detail: {
26
+ party: 'Ledger ID',
27
+ partyFingerprint: 'Ledger ID key fingerprint',
28
+ publicKeyFingerprint: 'Your key fingerprint',
29
+ signatureReceived: 'Signature received',
30
+ signedBy: 'Signed by key',
31
+ signedMessage: 'What was signed',
32
+ expectedHash: 'Expected transaction hash',
33
+ computedHash: 'Computed transaction hash',
34
+ ledgerUser: 'Ledger user',
35
+ actAs: 'Acting as',
36
+ },
37
+ footer: {
38
+ copyright: '© {year} Data Cloud, LLC. All rights reserved.',
39
+ terms: 'Terms and conditions',
40
+ privacy: 'Privacy policy',
41
+ cookies: 'Cookie preferences',
42
+ },
43
+ nav: {
44
+ home: 'Home',
45
+ products: 'Products',
46
+ blog: 'Blog',
47
+ about: 'About',
48
+ toggleDarkMode: 'Toggle dark mode',
49
+ },
50
+ status: {
51
+ DRAFT: 'Draft',
52
+ FUNDED: 'Funds committed',
53
+ ACTIVE: 'Active',
54
+ PROPOSED: 'Settlement offered',
55
+ DISPUTED: 'Disputed',
56
+ ARBITRATION: 'Arbitration',
57
+ SETTLED: 'Settled',
58
+ AWAITING_CUSTODY_APPROVAL: 'Awaiting custody approval',
59
+ FIAT_PENDING: 'Fiat payment pending',
60
+ LAPSED: 'Lapsed',
61
+ },
62
+ language: {
63
+ label: 'Language',
64
+ en: 'English',
65
+ fr: 'Français',
66
+ },
67
+ },
68
+ },
69
+ fr: {
70
+ cx: {
71
+ copy: 'Copier',
72
+ copied: 'Copié',
73
+ copyFailed: 'Échec de la copie',
74
+ dismiss: 'Fermer',
75
+ details: 'Détails',
76
+ copyErrorJson: 'Copier le JSON de l’erreur',
77
+ request: 'Requête',
78
+ trace: 'Trace',
79
+ node: 'Nœud',
80
+ upstreamSays: 'Réponse de {service}',
81
+ originalMessage: 'Message d’origine',
82
+ copyId: '{kind, select, party {Copier l’identifiant sur le registre} fingerprint {Copier l’empreinte de la clé} hash {Copier l’empreinte} other {Copier la valeur}}',
83
+ numbered: '{label} {n}',
84
+ detail: {
85
+ party: 'Identifiant sur le registre',
86
+ partyFingerprint: 'Empreinte de la clé de l’identifiant',
87
+ publicKeyFingerprint: 'Empreinte de votre clé',
88
+ signatureReceived: 'Signature reçue',
89
+ signedBy: 'Signé par la clé',
90
+ signedMessage: 'Contenu signé',
91
+ expectedHash: 'Empreinte de transaction attendue',
92
+ computedHash: 'Empreinte de transaction calculée',
93
+ ledgerUser: 'Utilisateur du registre',
94
+ actAs: 'Agit en tant que',
95
+ },
96
+ footer: {
97
+ copyright: '© {year} Data Cloud, LLC. Tous droits réservés.',
98
+ terms: 'Conditions générales',
99
+ privacy: 'Politique de confidentialité',
100
+ cookies: 'Préférences en matière de cookies',
101
+ },
102
+ nav: {
103
+ home: 'Accueil',
104
+ products: 'Produits',
105
+ blog: 'Blog',
106
+ about: 'À propos',
107
+ toggleDarkMode: 'Basculer le mode sombre',
108
+ },
109
+ status: {
110
+ DRAFT: 'Projet',
111
+ FUNDED: 'Fonds engagés',
112
+ ACTIVE: 'Actif',
113
+ PROPOSED: 'Règlement proposé',
114
+ DISPUTED: 'En litige',
115
+ ARBITRATION: 'Arbitrage',
116
+ SETTLED: 'Réglé',
117
+ AWAITING_CUSTODY_APPROVAL: 'En attente d’approbation de la conservation',
118
+ FIAT_PENDING: 'Paiement fiat en attente',
119
+ LAPSED: 'Expiré',
120
+ },
121
+ language: {
122
+ label: 'Langue',
123
+ en: 'English',
124
+ fr: 'Français',
125
+ },
126
+ },
127
+ },
128
+ } satisfies Catalogs;
129
+
130
+ /** The locales cx-commons ships strings for. */
131
+ export const CX_LOCALES = Object.keys(cxMessages);
132
+
133
+ registerMessages(cxMessages, { layer: 'defaults' });
@@ -0,0 +1,410 @@
1
+ // Internationalization for every app on the platform (daml-escrow PLAN.md
2
+ // Phase 71). Zero dependencies: messages use a subset of ICU MessageFormat
3
+ // over the platform's Intl, which is all French and the CJK languages need
4
+ // (CJK has no plural forms; French needs one/many/other).
5
+ //
6
+ // Rules this module exists to enforce (see daml-escrow docs/i18n/GLOSSARY.md):
7
+ // - Whole messages with placeholders -- never concatenate fragments. Word
8
+ // order differs between English, French, Japanese, Chinese and Korean.
9
+ // - Plurals through {n, plural, ...}, never `n === 1 ? 'x' : 'xs'`.
10
+ // - Numbers, money and dates only through the format* helpers below.
11
+ //
12
+ // Message syntax (ICU subset):
13
+ // {name} a parameter
14
+ // {n, plural, =0 {none} one {# item} other {# items}} # = the number, locale-formatted
15
+ // {kind, select, party {a party} other {a value}}
16
+ // Apostrophes are plain text (French needs them everywhere), so -- unlike
17
+ // full ICU -- there is no quoting and literal braces are not supported.
18
+
19
+ /** A catalog: nested keys to messages. `{ errors: { NOT_FOUND: { hint: '...' } } }` is key `errors.NOT_FOUND.hint`. */
20
+ export interface Messages {
21
+ [key: string]: string | Messages;
22
+ }
23
+
24
+ /** Catalogs by locale: `{ en: {...}, fr: {...} }`. */
25
+ export type Catalogs = Record<string, Messages>;
26
+
27
+ export type Params = Record<string, string | number | Date | null | undefined>;
28
+
29
+ export const DEFAULT_LOCALE = 'en';
30
+ /** The cookie that remembers the person's language choice (read server-side too, so SSR matches). */
31
+ export const LOCALE_COOKIE = 'locale';
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // Message formatting
35
+
36
+ type Node =
37
+ | string
38
+ | { arg: string }
39
+ | { arg: string; kind: 'plural'; offset: number; cases: Record<string, Node[]> }
40
+ | { arg: string; kind: 'select'; cases: Record<string, Node[]> }
41
+ | { pound: true };
42
+
43
+ class Parser {
44
+ private i = 0;
45
+ constructor(private readonly src: string) {}
46
+
47
+ parse(): Node[] {
48
+ const nodes = this.nodes(false, false);
49
+ if (this.i < this.src.length) throw this.error('unexpected "}"');
50
+ return nodes;
51
+ }
52
+
53
+ private error(msg: string): Error {
54
+ return new Error(`i18n: ${msg} at ${this.i} in "${this.src}"`);
55
+ }
56
+
57
+ // nodes reads until end of input or an unmatched "}" (inside a case).
58
+ private nodes(inCase: boolean, inPlural: boolean): Node[] {
59
+ const out: Node[] = [];
60
+ let text = '';
61
+ while (this.i < this.src.length) {
62
+ const c = this.src[this.i];
63
+ if (c === '}') {
64
+ if (!inCase) throw this.error('unexpected "}"');
65
+ break;
66
+ }
67
+ if (c === '#' && inPlural) {
68
+ if (text) out.push(text), (text = '');
69
+ out.push({ pound: true });
70
+ this.i++;
71
+ continue;
72
+ }
73
+ if (c === '{') {
74
+ if (text) out.push(text), (text = '');
75
+ out.push(this.argument());
76
+ continue;
77
+ }
78
+ text += c;
79
+ this.i++;
80
+ }
81
+ if (text) out.push(text);
82
+ return out;
83
+ }
84
+
85
+ private ws() {
86
+ while (this.i < this.src.length && /\s/.test(this.src[this.i])) this.i++;
87
+ }
88
+
89
+ private word(): string {
90
+ this.ws();
91
+ const m = /^[^\s,{}]+/.exec(this.src.slice(this.i));
92
+ if (!m) throw this.error('expected a name');
93
+ this.i += m[0].length;
94
+ return m[0];
95
+ }
96
+
97
+ private expect(ch: string) {
98
+ this.ws();
99
+ if (this.src[this.i] !== ch) throw this.error(`expected "${ch}"`);
100
+ this.i++;
101
+ }
102
+
103
+ private argument(): Node {
104
+ this.expect('{');
105
+ const arg = this.word();
106
+ this.ws();
107
+ if (this.src[this.i] === '}') {
108
+ this.i++;
109
+ return { arg };
110
+ }
111
+ this.expect(',');
112
+ const kind = this.word();
113
+ if (kind !== 'plural' && kind !== 'select') throw this.error(`unsupported argument type "${kind}"`);
114
+ this.expect(',');
115
+ let offset = 0;
116
+ const cases: Record<string, Node[]> = {};
117
+ for (;;) {
118
+ this.ws();
119
+ if (this.src[this.i] === '}') {
120
+ this.i++;
121
+ break;
122
+ }
123
+ const key = this.word();
124
+ if (kind === 'plural' && key.startsWith('offset:')) {
125
+ offset = Number(key.slice(7));
126
+ continue;
127
+ }
128
+ this.expect('{');
129
+ cases[key] = this.nodes(true, kind === 'plural');
130
+ this.expect('}');
131
+ }
132
+ if (!cases.other) throw this.error(`"${arg}" needs an "other" case`);
133
+ return kind === 'plural' ? { arg, kind, offset, cases } : { arg, kind, cases };
134
+ }
135
+ }
136
+
137
+ const parsed = new Map<string, Node[]>();
138
+ const pluralRules = new Map<string, Intl.PluralRules>();
139
+
140
+ function rulesFor(locale: string): Intl.PluralRules {
141
+ let r = pluralRules.get(locale);
142
+ if (!r) pluralRules.set(locale, (r = new Intl.PluralRules(locale)));
143
+ return r;
144
+ }
145
+
146
+ function show(v: Params[string], locale: string): string {
147
+ if (v === null || v === undefined) return '';
148
+ if (typeof v === 'number') return formatNumber(v, locale);
149
+ if (v instanceof Date) return formatDate(v, locale);
150
+ return v;
151
+ }
152
+
153
+ function render(nodes: Node[], params: Params, locale: string, pound?: number): string {
154
+ let out = '';
155
+ for (const n of nodes) {
156
+ if (typeof n === 'string') out += n;
157
+ else if ('pound' in n) out += pound === undefined ? '#' : formatNumber(pound, locale);
158
+ else if (!('kind' in n)) out += n.arg in params ? show(params[n.arg], locale) : `{${n.arg}}`;
159
+ else if (n.kind === 'plural') {
160
+ const value = Number(params[n.arg] ?? 0) - n.offset;
161
+ const exact = n.cases[`=${value + n.offset}`];
162
+ const branch = exact ?? n.cases[rulesFor(locale).select(value)] ?? n.cases.other;
163
+ out += render(branch, params, locale, value);
164
+ } else {
165
+ const branch = n.cases[String(params[n.arg] ?? 'other')] ?? n.cases.other;
166
+ out += render(branch, params, locale, pound);
167
+ }
168
+ }
169
+ return out;
170
+ }
171
+
172
+ /** Formats one message. Throws on malformed syntax (catalog tests catch that before release). */
173
+ export function formatMessage(message: string, params: Params = {}, locale: string = DEFAULT_LOCALE): string {
174
+ let nodes = parsed.get(message);
175
+ if (!nodes) parsed.set(message, (nodes = new Parser(message).parse()));
176
+ return render(nodes, params, locale);
177
+ }
178
+
179
+ /** The parameter names a message uses (for catalog parity tests: every locale must use the same ones). */
180
+ export function messageParams(message: string): string[] {
181
+ const names = new Set<string>();
182
+ const walk = (nodes: Node[]) => {
183
+ for (const n of nodes) {
184
+ if (typeof n === 'string' || 'pound' in n) continue;
185
+ names.add(n.arg);
186
+ if ('kind' in n) Object.values(n.cases).forEach(walk);
187
+ }
188
+ };
189
+ walk(new Parser(message).parse());
190
+ return [...names].sort();
191
+ }
192
+
193
+ // ---------------------------------------------------------------------------
194
+ // Catalogs and translators
195
+
196
+ /** Flattens a catalog to dotted keys. */
197
+ export function flattenMessages(m: Messages, prefix = ''): Record<string, string> {
198
+ const out: Record<string, string> = {};
199
+ for (const [k, v] of Object.entries(m)) {
200
+ const key = prefix ? `${prefix}.${k}` : k;
201
+ if (typeof v === 'string') out[key] = v;
202
+ else Object.assign(out, flattenMessages(v, key));
203
+ }
204
+ return out;
205
+ }
206
+
207
+ // Two layers: a library's own defaults (cx-commons registers its strings on
208
+ // import) and the app's, which win. Order of registration doesn't matter.
209
+ const layers: { defaults: Record<string, Record<string, string>>; app: Record<string, Record<string, string>> } = {
210
+ defaults: {},
211
+ app: {},
212
+ };
213
+
214
+ /**
215
+ * Adds catalogs to the shared registry that translators read. Libraries pass
216
+ * `{ layer: 'defaults' }`; an app's own catalogs (the default layer) override
217
+ * any library string with the same key.
218
+ */
219
+ export function registerMessages(catalogs: Catalogs, opts: { layer?: 'defaults' | 'app' } = {}): void {
220
+ const layer = layers[opts.layer ?? 'app'];
221
+ for (const [locale, messages] of Object.entries(catalogs)) {
222
+ layer[locale] = { ...layer[locale], ...flattenMessages(messages) };
223
+ }
224
+ }
225
+
226
+ /** The locales any registered catalog covers. */
227
+ export function registeredLocales(): string[] {
228
+ return [...new Set([...Object.keys(layers.defaults), ...Object.keys(layers.app)])].sort();
229
+ }
230
+
231
+ export interface Translator {
232
+ readonly locale: string;
233
+ /** The message for key, formatted; falls back to the base language, then English, then the key itself. */
234
+ t(key: string, params?: Params): string;
235
+ /** The message for key if one exists in this locale's chain, else undefined. */
236
+ maybe(key: string, params?: Params): string | undefined;
237
+ has(key: string): boolean;
238
+ }
239
+
240
+ /** fr-CA -> [fr-CA, fr, en]. */
241
+ function chain(locale: string, fallback: string): string[] {
242
+ const out = [locale];
243
+ const base = locale.split('-')[0];
244
+ if (base !== locale) out.push(base);
245
+ if (!out.includes(fallback)) out.push(fallback);
246
+ return out;
247
+ }
248
+
249
+ /**
250
+ * A translator over the registry (plus any catalogs passed here, which win).
251
+ * The locale defaults to the page's `<html lang>` in the browser.
252
+ */
253
+ export function getTranslator(locale?: string, opts: { catalogs?: Catalogs; fallback?: string } = {}): Translator {
254
+ const loc = canonicalLocale(locale ?? documentLocale());
255
+ const fallback = opts.fallback ?? DEFAULT_LOCALE;
256
+ const local: Record<string, Record<string, string>> = {};
257
+ for (const [l, m] of Object.entries(opts.catalogs ?? {})) local[l] = flattenMessages(m);
258
+ const locales = chain(loc, fallback);
259
+ const lookup = (key: string): { message: string; locale: string } | undefined => {
260
+ for (const l of locales) {
261
+ const m = local[l]?.[key] ?? layers.app[l]?.[key] ?? layers.defaults[l]?.[key];
262
+ if (m !== undefined) return { message: m, locale: l };
263
+ }
264
+ return undefined;
265
+ };
266
+ return {
267
+ locale: loc,
268
+ t(key, params) {
269
+ const hit = lookup(key);
270
+ return hit ? formatMessage(hit.message, params, loc) : key;
271
+ },
272
+ maybe(key, params) {
273
+ const hit = lookup(key);
274
+ return hit ? formatMessage(hit.message, params, loc) : undefined;
275
+ },
276
+ has: (key) => lookup(key) !== undefined,
277
+ };
278
+ }
279
+
280
+ // ---------------------------------------------------------------------------
281
+ // Choosing the locale (D11: a remembered choice, else the browser's language, else English)
282
+
283
+ /** "FR-ca" -> "fr-CA"; anything unparseable -> DEFAULT_LOCALE. */
284
+ export function canonicalLocale(tag: string | null | undefined): string {
285
+ if (!tag) return DEFAULT_LOCALE;
286
+ try {
287
+ return Intl.getCanonicalLocales(tag.trim())[0] ?? DEFAULT_LOCALE;
288
+ } catch {
289
+ return DEFAULT_LOCALE;
290
+ }
291
+ }
292
+
293
+ /** Accept-Language -> tags, highest quality first ("*" and q=0 dropped). */
294
+ export function parseAcceptLanguage(header: string | null | undefined): string[] {
295
+ if (!header) return [];
296
+ return header
297
+ .split(',')
298
+ .map((part, idx) => {
299
+ const [tag, ...ps] = part.trim().split(';');
300
+ const q = ps.map((p) => p.trim()).find((p) => p.startsWith('q='));
301
+ return { tag: tag.trim(), q: q ? Number(q.slice(2)) : 1, idx };
302
+ })
303
+ .filter((x) => x.tag && x.tag !== '*' && x.q > 0 && !Number.isNaN(x.q))
304
+ .sort((a, b) => b.q - a.q || a.idx - b.idx)
305
+ .map((x) => x.tag);
306
+ }
307
+
308
+ /** The best supported locale for the requested ones (exact, then same language), else fallback. */
309
+ export function negotiateLocale(requested: readonly string[], supported: readonly string[], fallback = DEFAULT_LOCALE): string {
310
+ const sup = supported.map(canonicalLocale);
311
+ for (const r of requested) {
312
+ const want = canonicalLocale(r);
313
+ const exact = sup.find((s) => s.toLowerCase() === want.toLowerCase());
314
+ if (exact) return exact;
315
+ const lang = want.split('-')[0].toLowerCase();
316
+ const same = sup.find((s) => s.split('-')[0].toLowerCase() === lang);
317
+ if (same) return same;
318
+ }
319
+ return canonicalLocale(fallback);
320
+ }
321
+
322
+ /** The value of the locale cookie in a Cookie header, if any. */
323
+ export function readLocaleCookie(cookieHeader: string | null | undefined): string | undefined {
324
+ if (!cookieHeader) return undefined;
325
+ for (const part of cookieHeader.split(';')) {
326
+ const [k, ...v] = part.trim().split('=');
327
+ if (k === LOCALE_COOKIE) return decodeURIComponent(v.join('='));
328
+ }
329
+ return undefined;
330
+ }
331
+
332
+ /** Resolves a request's locale: the remembered choice if supported, else Accept-Language, else fallback. */
333
+ export function resolveLocale(input: {
334
+ cookie?: string | null;
335
+ acceptLanguage?: string | null;
336
+ supported: readonly string[];
337
+ fallback?: string;
338
+ }): string {
339
+ const chosen = readLocaleCookie(input.cookie);
340
+ const requested = [...(chosen ? [chosen] : []), ...parseAcceptLanguage(input.acceptLanguage)];
341
+ return negotiateLocale(requested, input.supported, input.fallback ?? DEFAULT_LOCALE);
342
+ }
343
+
344
+ /** A Set-Cookie / document.cookie value remembering the choice for a year. */
345
+ export function localeCookie(locale: string, maxAgeDays = 365): string {
346
+ return `${LOCALE_COOKIE}=${encodeURIComponent(canonicalLocale(locale))}; Path=/; Max-Age=${maxAgeDays * 86400}; SameSite=Lax`;
347
+ }
348
+
349
+ /** The page's language (`<html lang>`), or DEFAULT_LOCALE outside a browser. */
350
+ export function documentLocale(): string {
351
+ if (typeof document === 'undefined') return DEFAULT_LOCALE;
352
+ return canonicalLocale(document.documentElement.lang || DEFAULT_LOCALE);
353
+ }
354
+
355
+ /** Remembers a choice and reloads so server-rendered text follows (browser only). */
356
+ export function chooseLocale(locale: string): void {
357
+ document.cookie = localeCookie(locale);
358
+ location.reload();
359
+ }
360
+
361
+ // ---------------------------------------------------------------------------
362
+ // Numbers, money and dates -- always through these, never toLocaleString()
363
+
364
+ const ISO_CURRENCY = /^[A-Z]{3}$/;
365
+
366
+ /** A number in the locale's notation. Decimal strings ("1234.5600000000", from the ledger) keep their precision. */
367
+ export function formatNumber(value: number | string, locale: string = documentLocale(), opts: Intl.NumberFormatOptions = {}): string {
368
+ // Intl formats numeric strings as exact decimals (ES2023), so ledger Decimals don't round-trip through float.
369
+ return new Intl.NumberFormat(locale, opts).format(value as unknown as number);
370
+ }
371
+
372
+ /**
373
+ * An amount with its currency or instrument, always with the code (never a
374
+ * bare "$", which is ambiguous across markets): ISO 4217 codes use the
375
+ * locale's currency layout ("USD 1,234.56" in en, "1 234,56 USD" in fr);
376
+ * anything else -- USDC, a deposit token -- goes after the amount
377
+ * ("1 234,56 USDC").
378
+ */
379
+ export function formatMoney(
380
+ amount: number | string,
381
+ currency: string,
382
+ locale: string = documentLocale(),
383
+ opts: { minimumFractionDigits?: number; maximumFractionDigits?: number } = {},
384
+ ): string {
385
+ const digits = { minimumFractionDigits: opts.minimumFractionDigits ?? 2, maximumFractionDigits: opts.maximumFractionDigits ?? Math.max(2, opts.minimumFractionDigits ?? 2) };
386
+ const code = currency.trim().toUpperCase();
387
+ if (ISO_CURRENCY.test(code)) {
388
+ try {
389
+ return formatNumber(amount, locale, { style: 'currency', currency: code, currencyDisplay: 'code', ...digits });
390
+ } catch {
391
+ // fall through to the plain form
392
+ }
393
+ }
394
+ return formatMessage('{amount} {code}', { amount: formatNumber(amount, locale, digits), code }, locale);
395
+ }
396
+
397
+ /** A date (default: medium date, no time). */
398
+ export function formatDate(value: Date | string | number, locale: string = documentLocale(), opts: Intl.DateTimeFormatOptions = { dateStyle: 'medium' }): string {
399
+ return new Intl.DateTimeFormat(locale, opts).format(new Date(value));
400
+ }
401
+
402
+ /** A date and time (default: medium date, short time). */
403
+ export function formatDateTime(value: Date | string | number, locale: string = documentLocale(), opts: Intl.DateTimeFormatOptions = { dateStyle: 'medium', timeStyle: 'short' }): string {
404
+ return new Intl.DateTimeFormat(locale, opts).format(new Date(value));
405
+ }
406
+
407
+ /** "in 3 days", "il y a 2 heures". */
408
+ export function formatRelativeTime(value: number, unit: Intl.RelativeTimeFormatUnit, locale: string = documentLocale()): string {
409
+ return new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(value, unit);
410
+ }
@@ -243,3 +243,14 @@
243
243
  ::-webkit-scrollbar-thumb:hover {
244
244
  background: #94a3b8;
245
245
  }
246
+
247
+ /*
248
+ * Uppercase + wide tracking is a Latin-script effect. Elements that use it
249
+ * carry .cx-caps so it can be switched off where it harms legibility: CJK
250
+ * scripts have no case, and letter-spacing breaks their character rhythm
251
+ * (daml-escrow PLAN.md Phase 71). Set <html lang> and this applies itself.
252
+ */
253
+ :where(:lang(ja), :lang(zh), :lang(ko)) .cx-caps {
254
+ text-transform: none;
255
+ letter-spacing: normal;
256
+ }