@vdatacloud/cx-commons 0.1.9 → 0.1.10

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
@@ -41,8 +41,8 @@ This repository publishes `@vdatacloud/cx-commons` with modular export entry poi
41
41
  @vdatacloud/cx-commons
42
42
  ├── (default) --> exports index.ts (Astro integration plugin `cxCommons()`)
43
43
  ├── /styles/global.css --> exports canonical LNF design system tokens & Tailwind rules
44
- ├── /components/* --> exports shared Astro UI components (Nav, Footer, StatusBadge, EyebrowLabel, ApiErrorNotice, CantonId)
45
- ├── /sdk/* --> exports browser SDK helpers (i18n, cx-messages, api-error, api-error-notice, canton-id, canton-id-view, status-colors)
44
+ ├── /components/* --> exports shared Astro UI components (Nav, Footer, StatusBadge, EyebrowLabel, ApiErrorNotice, CantonId, LanguageSwitcher)
45
+ ├── /sdk/* --> exports browser SDK helpers (i18n, cx-messages, dialogs, 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
 
@@ -104,6 +104,11 @@ Korean are catalog work, not a rewrite). Vocabulary follows daml-escrow's `docs/
104
104
  `en`). `StatusBadge` shows `cx.status.<STATUS>` (e.g. `FUNDED` -> "Funds committed"); `ApiErrorNotice` /
105
105
  `renderApiErrorNotice` translate `errors.<CODE>.message|hint` and `stages.<stage>` when the app registers them,
106
106
  keeping the server's original message in the details.
107
+ - **Language switcher:** `components/LanguageSwitcher` -- sets the `locale` cookie and reloads; pass the app's
108
+ `locales`.
109
+ - **Dialogs:** `sdk/dialogs` -- `confirmDialog`, `promptDialog`, `formDialog`, `acknowledge`, `notifyError`,
110
+ `showErrorIn`, `notifyInfo` replace `window.confirm`/`prompt`/`alert` in the page's language (see
111
+ `docs/COMPONENTS.md`).
107
112
  - **CJK:** elements that uppercase/letter-space carry `.cx-caps`, switched off under `:lang(ja|zh|ko)`.
108
113
 
109
114
  ## 5. Quick Start & Integration Guide
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vdatacloud/cx-commons",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
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",
@@ -0,0 +1,44 @@
1
+ ---
2
+ // Language choice: remembered in the locale cookie (sdk/i18n chooseLocale)
3
+ // and applied by reloading, so server-rendered text follows. No URL prefix.
4
+ // Works for signed-out visitors too. Each language is named in itself
5
+ // (cx.language.<code>), so a reader can always find their own.
6
+ import { getTranslator } from '../sdk/i18n';
7
+ import { CX_LOCALES } from '../sdk/cx-messages';
8
+
9
+ interface Props {
10
+ /** The page's locale (default: Astro.locals.locale, else 'en'). */
11
+ locale?: string;
12
+ /** The locales to offer (default: every locale cx-commons ships strings for). */
13
+ locales?: readonly string[];
14
+ /** Extra classes for the wrapper. */
15
+ class?: string;
16
+ }
17
+
18
+ const locale = Astro.props.locale ?? (Astro.locals as { locale?: string }).locale ?? Astro.currentLocale ?? 'en';
19
+ const locales = Astro.props.locales ?? CX_LOCALES;
20
+ const { t } = getTranslator(locale);
21
+ const lang = locale.split('-')[0];
22
+ ---
23
+
24
+ <label class:list={['relative inline-flex items-center normal-case tracking-normal', Astro.props.class]}>
25
+ <span class="sr-only">{t('cx.language.choose')}</span>
26
+ <select
27
+ data-cx-language-switcher
28
+ class="appearance-none cursor-pointer rounded-xl border border-slate-200 bg-transparent py-1.5 pl-2.5 pr-6 text-[11px] font-bold text-slate-600 hover:border-brand-400 dark:border-slate-700 dark:text-slate-300"
29
+ title={t('cx.language.label')}
30
+ >
31
+ {locales.map((l) => (
32
+ <option value={l} selected={l === lang} lang={l}>{getTranslator(l).maybe(`cx.language.${l}`) ?? l}</option>
33
+ ))}
34
+ </select>
35
+ <svg class="pointer-events-none absolute right-1.5 h-3 w-3 text-slate-400" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" /></svg>
36
+ </label>
37
+
38
+ <script>
39
+ import { chooseLocale } from '../sdk/i18n';
40
+
41
+ document.querySelectorAll<HTMLSelectElement>('select[data-cx-language-switcher]').forEach((s) => {
42
+ s.addEventListener('change', () => chooseLocale(s.value));
43
+ });
44
+ </script>
@@ -59,8 +59,15 @@ export const cxMessages = {
59
59
  FIAT_PENDING: 'Fiat payment pending',
60
60
  LAPSED: 'Lapsed',
61
61
  },
62
+ dialog: {
63
+ confirm: 'Confirm',
64
+ cancel: 'Cancel',
65
+ ok: 'OK',
66
+ close: 'Close',
67
+ },
62
68
  language: {
63
69
  label: 'Language',
70
+ choose: 'Choose language',
64
71
  en: 'English',
65
72
  fr: 'Français',
66
73
  },
@@ -118,8 +125,15 @@ export const cxMessages = {
118
125
  FIAT_PENDING: 'Paiement fiat en attente',
119
126
  LAPSED: 'Expiré',
120
127
  },
128
+ dialog: {
129
+ confirm: 'Confirmer',
130
+ cancel: 'Annuler',
131
+ ok: 'OK',
132
+ close: 'Fermer',
133
+ },
121
134
  language: {
122
135
  label: 'Langue',
136
+ choose: 'Choisir la langue',
123
137
  en: 'English',
124
138
  fr: 'Français',
125
139
  },
@@ -0,0 +1,178 @@
1
+ // In-page replacements for window.confirm / prompt / alert (promoted from
2
+ // daml-escrow's frontend, PLAN.md Phase 71). The browser's own dialogs block the page, can't be
3
+ // styled, ignore the page's language for their buttons, and lose an error's
4
+ // code and request id. These render a <dialog> (or, for errors, the
5
+ // cx-commons error notice) in the page's language.
6
+ //
7
+ // Built with DOM APIs and textContent only -- messages often carry values
8
+ // from the server or other parties and must never become markup.
9
+
10
+ // Button labels are cx.dialog.* (sdk/cx-messages); an app overrides them by
11
+ // registering the same keys. Styling uses the design system's tokens
12
+ // (brand-*, status-*), so it follows white-labeling.
13
+
14
+ import { mountApiErrorNotice } from './api-error-notice';
15
+ import { apiErrorFromUnknown, isApiError, type ApiError } from './api-error';
16
+ import { getTranslator } from './i18n';
17
+ import './cx-messages';
18
+
19
+ const BUTTON = 'rounded-lg px-4 py-2 text-sm font-bold cursor-pointer';
20
+ const SECONDARY = `${BUTTON} border border-slate-200 text-slate-700 hover:bg-slate-100 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800`;
21
+ const PRIMARY = `${BUTTON} bg-brand-600 text-white hover:bg-brand-700 border-none`;
22
+ const DANGER = `${BUTTON} bg-status-disputed text-white hover:opacity-90 border-none`;
23
+ const INPUT = 'w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-900 dark:border-slate-700 dark:bg-slate-800 dark:text-white';
24
+
25
+ function el<K extends keyof HTMLElementTagNameMap>(tag: K, className = '', text?: string): HTMLElementTagNameMap[K] {
26
+ const n = document.createElement(tag);
27
+ if (className) n.className = className;
28
+ if (text !== undefined) n.textContent = text;
29
+ return n;
30
+ }
31
+
32
+ export interface Field {
33
+ name: string;
34
+ label: string;
35
+ defaultValue?: string;
36
+ placeholder?: string;
37
+ required?: boolean;
38
+ type?: 'text' | 'number';
39
+ }
40
+
41
+ interface DialogSpec {
42
+ title?: string;
43
+ message: string;
44
+ fields?: Field[];
45
+ confirmLabel?: string;
46
+ cancelLabel?: string;
47
+ danger?: boolean;
48
+ }
49
+
50
+ // open renders a modal and resolves with the field values on confirm, or
51
+ // null on cancel / Escape / close. The safe choice (Cancel) has focus unless
52
+ // there are fields to fill.
53
+ function open(spec: DialogSpec): Promise<Record<string, string> | null> {
54
+ const { t } = getTranslator();
55
+ return new Promise((resolve) => {
56
+ const dialog = el('dialog', 'm-auto w-full max-w-md rounded-2xl border border-slate-200 bg-white p-6 shadow-xl backdrop:bg-slate-900/50 dark:border-slate-700 dark:bg-slate-900');
57
+ dialog.dataset.appDialog = '';
58
+ const form = el('form', 'space-y-4');
59
+ form.method = 'dialog';
60
+ if (spec.title) form.append(el('h2', 'text-lg font-bold text-slate-900 dark:text-white', spec.title));
61
+ form.append(el('p', 'text-sm text-slate-700 dark:text-slate-200 whitespace-pre-line', spec.message));
62
+ const inputs: HTMLInputElement[] = [];
63
+ for (const f of spec.fields ?? []) {
64
+ const label = el('label', 'block space-y-1');
65
+ label.append(el('span', 'text-xs font-semibold text-slate-500 dark:text-slate-400', f.label));
66
+ const input = el('input', INPUT);
67
+ input.name = f.name;
68
+ input.type = f.type ?? 'text';
69
+ if (f.type === 'number') input.step = 'any';
70
+ input.value = f.defaultValue ?? '';
71
+ if (f.placeholder) input.placeholder = f.placeholder;
72
+ input.required = !!f.required;
73
+ label.append(input);
74
+ form.append(label);
75
+ inputs.push(input);
76
+ }
77
+ const actions = el('div', 'flex justify-end gap-2 pt-2');
78
+ const cancel = el('button', SECONDARY, spec.cancelLabel || t('cx.dialog.cancel'));
79
+ cancel.type = 'button';
80
+ // An empty cancelLabel means a single-button (acknowledge) dialog.
81
+ if (spec.cancelLabel === '') cancel.hidden = true;
82
+ const ok = el('button', spec.danger ? DANGER : PRIMARY, spec.confirmLabel ?? t('cx.dialog.confirm'));
83
+ ok.type = 'submit';
84
+ actions.append(cancel, ok);
85
+ form.append(actions);
86
+ dialog.append(form);
87
+
88
+ let settled = false;
89
+ const finish = (value: Record<string, string> | null) => {
90
+ if (settled) return;
91
+ settled = true;
92
+ dialog.close();
93
+ dialog.remove();
94
+ resolve(value);
95
+ };
96
+ form.addEventListener('submit', (e) => {
97
+ e.preventDefault();
98
+ if (!form.reportValidity()) return;
99
+ finish(Object.fromEntries(inputs.map((i) => [i.name, i.value.trim()])));
100
+ });
101
+ cancel.addEventListener('click', () => finish(null));
102
+ dialog.addEventListener('close', () => finish(null));
103
+ document.body.append(dialog);
104
+ dialog.showModal();
105
+ (inputs[0] ?? (cancel.hidden ? ok : cancel)).focus();
106
+ });
107
+ }
108
+
109
+ /** Asks a yes/no question; resolves true only on an explicit confirm. */
110
+ export async function confirmDialog(message: string, opts: Omit<DialogSpec, 'message' | 'fields'> = {}): Promise<boolean> {
111
+ return (await open({ ...opts, message })) !== null;
112
+ }
113
+
114
+ /** Shows a message that needs reading before the page moves on (e.g. before a reload). */
115
+ export async function acknowledge(message: string, opts: { title?: string } = {}): Promise<void> {
116
+ const { t } = getTranslator();
117
+ await open({ ...opts, message, confirmLabel: t('cx.dialog.ok'), cancelLabel: '' });
118
+ }
119
+
120
+ /** Asks for one value; resolves the trimmed value, or null when cancelled. */
121
+ export async function promptDialog(message: string, field: Omit<Field, 'name'> & { name?: string }, opts: Omit<DialogSpec, 'message' | 'fields'> = {}): Promise<string | null> {
122
+ const name = field.name ?? 'value';
123
+ const values = await open({ ...opts, message, fields: [{ ...field, name }] });
124
+ return values ? values[name] : null;
125
+ }
126
+
127
+ /** Asks for several values; resolves them by field name, or null when cancelled. */
128
+ export function formDialog(message: string, fields: Field[], opts: Omit<DialogSpec, 'message' | 'fields'> = {}): Promise<Record<string, string> | null> {
129
+ return open({ ...opts, message, fields });
130
+ }
131
+
132
+ // Notices stack in one fixed region, top right, newest first.
133
+ function region(): HTMLElement {
134
+ let r = document.getElementById('app-notices');
135
+ if (!r) {
136
+ r = el('div', 'fixed right-4 top-20 z-[200] flex w-full max-w-md flex-col gap-3');
137
+ r.id = 'app-notices';
138
+ r.setAttribute('aria-live', 'polite');
139
+ document.body.append(r);
140
+ }
141
+ return r;
142
+ }
143
+
144
+ /**
145
+ * Shows a failure with the platform error notice (code, stage, hint, request
146
+ * id, details), in the page's language. Anything carrying the error envelope
147
+ * (ApiRequestError, wallet errors) shows as-is; anything else is normalized.
148
+ */
149
+ export function notifyError(err: unknown, stage?: string): ApiError {
150
+ const carried = (err as { apiError?: unknown } | null)?.apiError;
151
+ const e = isApiError(carried) ? carried : apiErrorFromUnknown(err, { stage });
152
+ const host = el('div', 'shadow-xl rounded-2xl bg-white dark:bg-slate-900');
153
+ region().prepend(host);
154
+ mountApiErrorNotice(host, e, { onDismiss: () => host.remove() });
155
+ return e;
156
+ }
157
+
158
+ /** Renders a failure into host (e.g. a modal's status area) with the platform error notice. */
159
+ export function showErrorIn(host: HTMLElement | null, err: unknown, stage?: string): void {
160
+ if (!host) return;
161
+ const carried = (err as { apiError?: unknown } | null)?.apiError;
162
+ mountApiErrorNotice(host, isApiError(carried) ? carried : apiErrorFromUnknown(err, { stage }));
163
+ }
164
+
165
+ /** Shows a short confirmation that dismisses itself. */
166
+ export function notifyInfo(message: string, ms = 6000): HTMLElement {
167
+ const { t } = getTranslator();
168
+ const host = el('div', 'flex items-start gap-3 rounded-2xl border border-slate-200 bg-white p-4 text-sm text-slate-800 shadow-xl dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100');
169
+ host.setAttribute('role', 'status');
170
+ host.append(el('p', 'flex-1', message));
171
+ const close = el('button', 'text-xs font-bold text-slate-400 hover:text-slate-600 border-none bg-transparent cursor-pointer', t('cx.dialog.close'));
172
+ close.type = 'button';
173
+ close.addEventListener('click', () => host.remove());
174
+ host.append(close);
175
+ region().prepend(host);
176
+ if (ms > 0) setTimeout(() => host.remove(), ms);
177
+ return host;
178
+ }