@proveanything/smartlinks 3.0.0-alpha.0 → 3.0.0-alpha.1

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.
@@ -1,6 +1,6 @@
1
1
  # Smartlinks API Summary
2
2
 
3
- Version: 3.0.0-alpha.0 | Generated: 2026-11-24T13:24:06.036Z
3
+ Version: 3.0.0-alpha.1 | Generated: 2026-11-24T15:23:46.728Z
4
4
 
5
5
  This is a concise summary of all available API functions and types.
6
6
 
package/dist/docs/i18n.md CHANGED
@@ -1,14 +1,16 @@
1
1
  # Internationalization (i18n): an app's own words
2
2
 
3
- **Use the SDK's `i18n` helper** (SDK 2.1.27+). The copied-in `src/i18n/LanguageContext` scaffold further
4
- down is the older way; new apps and upgrades use the helper.
3
+ **Use the SDK's `i18n` helper** (SDK 2.2.1+). Don't build your own language system (a `LanguageContext`,
4
+ your own detection, English/German/French written into components): that was the old scaffold, and
5
+ Forge's step 21 moves an app off it.
5
6
 
6
7
  ## How it works
7
8
 
8
9
  1. **Your app keeps its English as keys** in `public/i18n/en.json`. The build ships it at
9
10
  `<bundle>/i18n/en.json`. That is your only translation job: don't hard-code English in components.
10
- 2. **The platform translates.** When your app is published, SmartLinks translates the English into the
11
- admin languages it supports (Simplified Chinese first) and adds `<bundle>/i18n/<lang>.json`. Keys whose
11
+ 2. **The platform translates, once.** When your app is published, SmartLinks translates the English into
12
+ the common languages it supports and adds `<bundle>/i18n/<lang>.json`: static files, one small fetch
13
+ before the first render, no lookups per label and no flash of English. Keys whose
12
14
  English hasn't changed keep their earlier (possibly human-reviewed) translation. If you ship your own
13
15
  `public/i18n/<lang>.json`, its keys win and the platform fills only the gaps.
14
16
  3. **The host says which language.** Studio passes the person's own Studio language as `?lang=`, and later
@@ -29,7 +31,7 @@ export function useT() {
29
31
  useSyncExternalStore(i18n.subscribe, i18n.snapshot)
30
32
  return i18n.t
31
33
  }
32
- export const fmt = i18n.format // dates and numbers in the current language
34
+ export const fmt = i18n.format // numbers, dates and money in the current language
33
35
  ```
34
36
 
35
37
  ```tsx
@@ -37,6 +39,7 @@ const t = useT()
37
39
  <Button>{t('contacts.add')}</Button>
38
40
  <span>{t('contacts.count', { count: rows.length })}</span>
39
41
  <span>{fmt.date(contact.createdAt)}</span>
42
+ <span>{fmt.money(order.total, order.currency)}</span> {/* minor units: "1.299,50 €" in German */}
40
43
  ```
41
44
 
42
45
  `public/i18n/en.json`:
@@ -61,303 +64,54 @@ const t = useT()
61
64
  - `i18n.language()` is the language in use; `i18n.setLanguage(code)` switches; `i18n.has(key)` says
62
65
  whether a real translation exists.
63
66
 
64
- ---
67
+ ## Which languages: the business decides
65
68
 
66
- # The older scaffold (superseded)
69
+ An app shows only the languages the site has turned on. In Portal and Hub the host passes the visitor's
70
+ language (already limited to the site's languages); in Studio it's the person's Studio language. A
71
+ standalone page with no host should pass the site's languages, so a browser language is used only when
72
+ the site offers it:
67
73
 
68
- ## Internationalization (i18n) System
69
-
70
- This document explains the i18n system for SmartLinks apps, covering URL-based language selection, static translations, and dynamic overrides.
71
-
72
- ---
73
-
74
- ## Overview
75
-
76
- The i18n system supports:
77
-
78
- - **URL parameter language selection** (`?lang=de`) - Ideal for iframe embedding
79
- - **Static translations** in JSON files - Fast, no API calls
80
- - **Dynamic overrides** via SmartLinks appConfig - Customer-configurable
81
- - **Type-safe translation keys** - Compile-time safety
82
- - **Widget support** - Translations can be passed to embedded widgets
83
-
84
- ---
85
-
86
- ## Quick Start
87
-
88
- ### Using Translations in Components
89
-
90
- ```typescript
91
- import { useLanguage } from '@/i18n';
92
-
93
- export const MyComponent = () => {
94
- const { t, lang } = useLanguage();
95
-
96
- return (
97
- <div>
98
- <h1>{t('public.title')}</h1>
99
- <p>{t('public.description')}</p>
100
- <small>Language: {lang}</small>
101
- </div>
102
- );
103
- };
104
- ```
105
-
106
- ### With Parameter Interpolation
107
-
108
- ```typescript
109
- const { t } = useLanguage();
110
-
111
- // Translation: "Hello, {{name}}!"
112
- t('greeting', { name: 'John' }); // "Hello, John!"
113
- ```
114
-
115
- ---
116
-
117
- ## Language Detection Priority
118
-
119
- The system detects language from multiple sources (in order):
120
-
121
- | Priority | Source | Example |
122
- |----------|--------|---------|
123
- | 1 | URL parameter | `?lang=de` |
124
- | 2 | localStorage | `smartlinks-lang` key |
125
- | 3 | Browser language | `navigator.language` |
126
- | 4 | Default | `en` |
127
-
128
- For iframe apps, the SmartLinks platform passes the language via URL parameter.
129
-
130
- ---
131
-
132
- ## File Structure
133
-
134
- ```text
135
- src/i18n/
136
- ├── index.ts # Main exports
137
- ├── LanguageContext.tsx # React context + provider
138
- ├── types.ts # TypeScript types
139
- └── locales/
140
- ├── en.json # English translations
141
- ├── de.json # German translations
142
- └── fr.json # French translations
143
- ```
144
-
145
- ---
146
-
147
- ## Adding New Translations
148
-
149
- ### 1. Add the Key to Types
150
-
151
- ```typescript
152
- // src/i18n/types.ts
153
- export type TranslationKey =
154
- | 'common.loading'
155
- | 'common.error'
156
- | 'myFeature.title' // Add new key
157
- | 'myFeature.description';
158
- ```
159
-
160
- ### 2. Add Translations to All Locales
161
-
162
- ```json
163
- // src/i18n/locales/en.json
164
- {
165
- "myFeature.title": "My Feature",
166
- "myFeature.description": "Description of my feature"
167
- }
168
-
169
- // src/i18n/locales/de.json
170
- {
171
- "myFeature.title": "Meine Funktion",
172
- "myFeature.description": "Beschreibung meiner Funktion"
173
- }
174
- ```
175
-
176
- ### 3. Use in Components
177
-
178
- ```typescript
179
- const { t } = useLanguage();
180
- return <h1>{t('myFeature.title')}</h1>;
181
- ```
182
-
183
- ---
184
-
185
- ## Adding New Languages
186
-
187
- ### 1. Create the Locale File
188
-
189
- ```json
190
- // src/i18n/locales/es.json
191
- {
192
- "common.loading": "Cargando...",
193
- "common.error": "Algo salió mal",
194
- // ... all other keys
195
- }
196
- ```
197
-
198
- ### 2. Import in LanguageContext
199
-
200
- ```typescript
201
- // src/i18n/LanguageContext.tsx
202
- import es from './locales/es.json';
203
-
204
- const staticTranslations: Record<string, PartialTranslations> = {
205
- en: en as PartialTranslations,
206
- de: de as PartialTranslations,
207
- fr: fr as PartialTranslations,
208
- es: es as PartialTranslations, // Add new language
209
- };
210
-
211
- const SUPPORTED_LANGUAGES = ['en', 'de', 'fr', 'es']; // Add to list
212
- ```
213
-
214
- ---
215
-
216
- ## Dynamic Translations (SmartLinks appConfig)
217
-
218
- For customer-configurable translations, store them in SmartLinks appConfig:
219
-
220
- ### Config Structure
221
-
222
- ```json
223
- {
224
- "i18n": {
225
- "supportedLanguages": ["en", "de"],
226
- "defaultLanguage": "en",
227
- "translations": {
228
- "en": {
229
- "public.title": "Custom Brand Title",
230
- "public.description": "Custom brand description"
231
- },
232
- "de": {
233
- "public.title": "Benutzerdefinierter Markentitel",
234
- "public.description": "Benutzerdefinierte Markenbeschreibung"
235
- }
236
- }
237
- }
238
- }
239
- ```
240
-
241
- ### Loading Dynamic Translations
242
-
243
- ```typescript
244
- import { useCollectionAppConfig } from '@/hooks/useSmartLinksData';
245
- import { LanguageProvider } from '@/i18n';
246
-
247
- const App = () => {
248
- const { data: config } = useCollectionAppConfig(collectionId, appId);
249
-
250
- return (
251
- <LanguageProvider dynamicTranslations={config?.i18n?.translations}>
252
- <MyApp />
253
- </LanguageProvider>
254
- );
255
- };
256
- ```
257
-
258
- Dynamic translations override static ones, so customers can customize specific strings while inheriting defaults.
259
-
260
- ---
261
-
262
- ## Widgets
263
-
264
- Widgets receive language context via props rather than React context (since they may run outside the provider).
265
-
266
- ### Widget Props
267
-
268
- ```typescript
269
- interface SmartLinksWidgetProps {
270
- // ... other props
271
- lang?: string;
272
- translations?: Record<string, string>;
273
- }
274
- ```
275
-
276
- ### Using in Widgets
277
-
278
- ```typescript
279
- import { createTranslator } from '@/i18n';
280
-
281
- export const MyWidget: React.FC<SmartLinksWidgetProps> = ({
282
- lang = 'en',
283
- translations = {},
284
- ...props
285
- }) => {
286
- const t = createTranslator(lang, translations);
287
-
288
- return <div>{t('widget.title')}</div>;
289
- };
290
- ```
291
-
292
- The `createTranslator` function creates a standalone translation function that doesn't require React context.
293
-
294
- ---
295
-
296
- ## URL Examples
297
-
298
- ```
299
- # English (default)
300
- /#/?collectionId=abc&appId=pamphlet
301
-
302
- # German
303
- /#/?collectionId=abc&appId=pamphlet&lang=de
304
-
305
- # French
306
- /#/?collectionId=abc&appId=pamphlet&lang=fr
74
+ ```ts
75
+ await i18n.init({ languages: collection.languages?.map((l) => l.code) })
307
76
  ```
308
77
 
309
- ---
310
-
311
- ## Best Practices
78
+ Never add your own language picker, and never translate into a language because the browser asks for it.
79
+ If a site is English only, it stays English (a visitor can still use their browser's own translation).
312
80
 
313
- 1. **Use dot notation** for key namespacing: `category.subcategory.key`
314
- 2. **Keep translations flat** - avoid nested objects in locale files
315
- 3. **Add keys to types.ts first** - ensures type safety
316
- 4. **Provide fallbacks** - English is always the fallback language
317
- 5. **Test all languages** - Use `?lang=xx` to switch during development
81
+ ## Hand-written translations are welcome
318
82
 
319
- ---
83
+ For a fixed set of labels you know well (a regulated product passport, a spec sheet), ship your own
84
+ `public/i18n/<lang>.json` files, as many languages as you like. Your keys win; the platform only fills
85
+ what you left out. That's faster to read and exact. What you should not do is hand-write the machinery.
320
86
 
321
- ## API Reference
87
+ ## Numbers, money and dates
322
88
 
323
- ### `useLanguage()`
89
+ Formats differ: "1,299.50" in English is "1.299,50" in German and "1 299,50" in French; dates and the
90
+ currency symbol move too. Always format in the language in use:
324
91
 
325
- Hook to access language context.
92
+ - `i18n.format.number(n)`, `i18n.format.date(d)`, `i18n.format.dateTime(d)`, `i18n.format.money(minor, currency)`.
93
+ - Outside the helper: `n.toLocaleString(utils.pageLocale())`, `utils.formatMinor(minor, currency)`,
94
+ `shop.formatMoney(...)`, `subscriptions.describePrice(...)`.
95
+ - Never a bare `toLocaleString()` / `toLocaleDateString()` (that's the browser's language, not the one the
96
+ visitor chose), never a fixed `'en-US'` or `'en-GB'`, never `(x / 100).toFixed(2)` or a hard-coded £/€/$.
97
+ Amounts are minor units in the currency's own decimals (whole units for JPY and KRW).
98
+ - **Reading what people type**: a German seller writes 12,99. Accept both decimal marks (the last `.` or
99
+ `,` followed by one or two digits is the decimal mark; the rest are thousands separators). Never strip
100
+ commas and never `Number(text)` a price field directly.
101
+ - Content (product names, page text) isn't your job: the platform translates it (`translations.resolve`).
326
102
 
327
- ```typescript
328
- const {
329
- lang, // Current language code
330
- setLang, // Function to change language
331
- t, // Translation function
332
- supportedLanguages // Array of supported language codes
333
- } = useLanguage();
334
- ```
103
+ ## Right-to-left languages (Arabic, Hebrew, Persian, Urdu)
335
104
 
336
- ### `createTranslator(lang, overrides)`
105
+ `i18n.textDirection(lang)` returns `'rtl'` or `'ltr'`. Portal and Hub set `<html dir>` from the
106
+ visitor's language, widgets inherit it, and iframe apps get it from `theme-boot.js` (from `?lang=` and
107
+ live `smartlinks:root-state`). For the layout to mirror, write direction-neutral CSS: Tailwind's
108
+ `ms-*`/`me-*`, `ps-*`/`pe-*`, `start-*`/`end-*`, `text-start`/`text-end`, `border-s`/`border-e`,
109
+ `rounded-s`/`rounded-e` instead of the left/right forms, and flip arrow icons that mean "forward" or
110
+ "back" with `rtl:-scale-x-100`.
337
111
 
338
- Creates a standalone translation function for widgets.
112
+ ## Moving off the older scaffold
339
113
 
340
- ```typescript
341
- const t = createTranslator('de', { 'custom.key': 'Custom value' });
342
- t('common.loading'); // "Laden..."
343
- t('custom.key'); // "Custom value"
344
- ```
345
-
346
- ### `LanguageProvider`
347
-
348
- React provider component.
349
-
350
- ```typescript
351
- <LanguageProvider dynamicTranslations={optionalOverrides}>
352
- <App />
353
- </LanguageProvider>
354
- ```
355
-
356
- ## Right-to-left languages (Arabic, Hebrew, Persian, Urdu)
357
-
358
- `i18n.textDirection(lang)` returns `'rtl'` or `'ltr'`. Portal and Hub set `<html dir>` from the
359
- visitor's language, widgets inherit it, and iframe apps get it from `theme-boot.js` (from `?lang=` and
360
- live `smartlinks:root-state`). For the layout to mirror, write direction-neutral CSS: Tailwind's
361
- `ms-*`/`me-*`, `ps-*`/`pe-*`, `start-*`/`end-*`, `text-start`/`text-end`, `border-s`/`border-e`,
362
- `rounded-s`/`rounded-e` instead of the left/right forms, and flip arrow icons that mean "forward" or
363
- "back" with `rtl:-scale-x-100`.
114
+ Apps built with the copied-in `src/i18n/` scaffold (`LanguageContext`, `src/i18n/locales/*.json`,
115
+ `createTranslator`) still work, but move them: put the English in `public/i18n/en.json` (keep any
116
+ hand-written languages as `public/i18n/<lang>.json`), read it with the helper above, and delete the
117
+ scaffold. In Forge this is step 21, "Speak the visitor's language".
package/dist/i18n.d.ts CHANGED
@@ -10,6 +10,12 @@ export interface I18nInitOptions {
10
10
  catalogs?: Record<string, Catalog>;
11
11
  /** The app's source language. Default 'en'. */
12
12
  sourceLanguage?: string;
13
+ /**
14
+ * The languages the site has turned on (its collection's languages). Languages are the business's
15
+ * choice: with no language from the host or the page, the browser's is used only when it is one of
16
+ * these; otherwise the app stays in its source language. Not given: never the browser's.
17
+ */
18
+ languages?: string[];
13
19
  }
14
20
  /**
15
21
  * The text direction for a language: 'rtl' for Arabic, Hebrew, Persian, Urdu and the like, else 'ltr'.
@@ -19,8 +25,12 @@ export interface I18nInitOptions {
19
25
  export declare function textDirection(code: string | null | undefined): 'rtl' | 'ltr';
20
26
  /** The language the host asked for, in a normal form ('zh-hans' -> 'zh-Hans', 'FR' -> 'fr'). */
21
27
  export declare function normalizeLanguage(code: string | null | undefined): string | null;
22
- /** Which language to start in: what the host passed, else the page's, else the browser's, else the source. */
23
- export declare function detectLanguage(): string;
28
+ /**
29
+ * Which language to start in: what the host passed, else the page's, else the browser's when the site
30
+ * has turned that language on (`approved`), else the source. A language the business hasn't chosen is
31
+ * never picked from the browser alone.
32
+ */
33
+ export declare function detectLanguage(approved?: string[]): string;
24
34
  /**
25
35
  * Load the source catalog and the current language's. Call once before the first render; safe to
26
36
  * call again. Never throws: with nothing found, `t` returns the keys' English or the keys.
@@ -50,6 +60,8 @@ export declare const format: {
50
60
  number: (n: number, opts?: Intl.NumberFormatOptions) => string;
51
61
  date: (d: Date | string | number, opts?: Intl.DateTimeFormatOptions) => string;
52
62
  dateTime: (d: Date | string | number, opts?: Intl.DateTimeFormatOptions) => string;
63
+ /** Minor units as money in the current language: `money(129950, 'EUR')` → "1.299,50 €" in German. */
64
+ money: (minor: number, currency: string) => string;
53
65
  };
54
66
  /** Forget loaded catalogs and listeners (tests). */
55
67
  export declare function _reset(): void;
package/dist/i18n.js CHANGED
@@ -28,6 +28,7 @@
28
28
  // Nested keys are read with dots. `{{name}}` is replaced from the values. With `count`, the plural
29
29
  // form for the language is picked (`_one`, `_other`, …; Chinese has only `_other`).
30
30
  import { readContext } from './context.js';
31
+ import { formatMinor } from './utils/money.js';
31
32
  let source = 'en';
32
33
  let current = 'en';
33
34
  let base = null;
@@ -94,8 +95,12 @@ function candidates(lang) {
94
95
  out.push(l);
95
96
  return Array.from(new Set(out));
96
97
  }
97
- /** Which language to start in: what the host passed, else the page's, else the browser's, else the source. */
98
- export function detectLanguage() {
98
+ /**
99
+ * Which language to start in: what the host passed, else the page's, else the browser's when the site
100
+ * has turned that language on (`approved`), else the source. A language the business hasn't chosen is
101
+ * never picked from the browser alone.
102
+ */
103
+ export function detectLanguage(approved) {
99
104
  try {
100
105
  const fromHost = normalizeLanguage(readContext().lang);
101
106
  if (fromHost)
@@ -106,15 +111,25 @@ export function detectLanguage() {
106
111
  if (fromPage)
107
112
  return fromPage;
108
113
  }
109
- if (typeof navigator !== 'undefined') {
114
+ if (approved && approved.length && typeof navigator !== 'undefined') {
110
115
  const fromBrowser = normalizeLanguage(navigator.language);
111
- if (fromBrowser)
112
- return fromBrowser;
116
+ const match = fromBrowser && pickApproved(fromBrowser, approved);
117
+ if (match)
118
+ return match;
113
119
  }
114
120
  }
115
121
  catch ( /* not in a browser */_a) { /* not in a browser */ }
116
122
  return source;
117
123
  }
124
+ /** The approved language `lang` stands for: exact, else the same base language ("fr-CA" -> "fr"). */
125
+ function pickApproved(lang, approved) {
126
+ const list = approved.map((l) => normalizeLanguage(l)).filter((l) => !!l);
127
+ const exact = list.find((l) => l.toLowerCase() === lang.toLowerCase());
128
+ if (exact)
129
+ return exact;
130
+ const base = lang.toLowerCase().split('-')[0];
131
+ return list.find((l) => l.toLowerCase().split('-')[0] === base) || null;
132
+ }
118
133
  /** Mark the page with the language in use (screen readers, fonts), where there is a page. */
119
134
  function setPageLanguage(lang) {
120
135
  try {
@@ -177,7 +192,7 @@ export async function init(options = {}) {
177
192
  const key = normalizeLanguage(lang) || lang;
178
193
  supplied.set(key, cat);
179
194
  }
180
- current = normalizeLanguage(options.language) || detectLanguage();
195
+ current = normalizeLanguage(options.language) || detectLanguage(options.languages);
181
196
  listen();
182
197
  await Promise.all([fetchCatalog(source), current === source ? null : fetchCatalog(current)]);
183
198
  setPageLanguage(current);
@@ -295,6 +310,8 @@ export const format = {
295
310
  return String(d);
296
311
  }
297
312
  },
313
+ /** Minor units as money in the current language: `money(129950, 'EUR')` → "1.299,50 €" in German. */
314
+ money: (minor, currency) => formatMinor(minor, currency, current),
298
315
  };
299
316
  /** Forget loaded catalogs and listeners (tests). */
300
317
  export function _reset() {
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "3.0.0-alpha.0";
1
+ export declare const SDK_VERSION = "3.0.0-alpha.1";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // Generated by scripts/write-version.mjs from package.json. Do not edit.
2
- export const SDK_VERSION = "3.0.0-alpha.0";
2
+ export const SDK_VERSION = "3.0.0-alpha.1";
@@ -1,6 +1,6 @@
1
1
  # Smartlinks API Summary
2
2
 
3
- Version: 3.0.0-alpha.0 | Generated: 2026-11-24T13:24:06.036Z
3
+ Version: 3.0.0-alpha.1 | Generated: 2026-11-24T15:23:46.728Z
4
4
 
5
5
  This is a concise summary of all available API functions and types.
6
6
 
package/docs/i18n.md CHANGED
@@ -1,14 +1,16 @@
1
1
  # Internationalization (i18n): an app's own words
2
2
 
3
- **Use the SDK's `i18n` helper** (SDK 2.1.27+). The copied-in `src/i18n/LanguageContext` scaffold further
4
- down is the older way; new apps and upgrades use the helper.
3
+ **Use the SDK's `i18n` helper** (SDK 2.2.1+). Don't build your own language system (a `LanguageContext`,
4
+ your own detection, English/German/French written into components): that was the old scaffold, and
5
+ Forge's step 21 moves an app off it.
5
6
 
6
7
  ## How it works
7
8
 
8
9
  1. **Your app keeps its English as keys** in `public/i18n/en.json`. The build ships it at
9
10
  `<bundle>/i18n/en.json`. That is your only translation job: don't hard-code English in components.
10
- 2. **The platform translates.** When your app is published, SmartLinks translates the English into the
11
- admin languages it supports (Simplified Chinese first) and adds `<bundle>/i18n/<lang>.json`. Keys whose
11
+ 2. **The platform translates, once.** When your app is published, SmartLinks translates the English into
12
+ the common languages it supports and adds `<bundle>/i18n/<lang>.json`: static files, one small fetch
13
+ before the first render, no lookups per label and no flash of English. Keys whose
12
14
  English hasn't changed keep their earlier (possibly human-reviewed) translation. If you ship your own
13
15
  `public/i18n/<lang>.json`, its keys win and the platform fills only the gaps.
14
16
  3. **The host says which language.** Studio passes the person's own Studio language as `?lang=`, and later
@@ -29,7 +31,7 @@ export function useT() {
29
31
  useSyncExternalStore(i18n.subscribe, i18n.snapshot)
30
32
  return i18n.t
31
33
  }
32
- export const fmt = i18n.format // dates and numbers in the current language
34
+ export const fmt = i18n.format // numbers, dates and money in the current language
33
35
  ```
34
36
 
35
37
  ```tsx
@@ -37,6 +39,7 @@ const t = useT()
37
39
  <Button>{t('contacts.add')}</Button>
38
40
  <span>{t('contacts.count', { count: rows.length })}</span>
39
41
  <span>{fmt.date(contact.createdAt)}</span>
42
+ <span>{fmt.money(order.total, order.currency)}</span> {/* minor units: "1.299,50 €" in German */}
40
43
  ```
41
44
 
42
45
  `public/i18n/en.json`:
@@ -61,303 +64,54 @@ const t = useT()
61
64
  - `i18n.language()` is the language in use; `i18n.setLanguage(code)` switches; `i18n.has(key)` says
62
65
  whether a real translation exists.
63
66
 
64
- ---
67
+ ## Which languages: the business decides
65
68
 
66
- # The older scaffold (superseded)
69
+ An app shows only the languages the site has turned on. In Portal and Hub the host passes the visitor's
70
+ language (already limited to the site's languages); in Studio it's the person's Studio language. A
71
+ standalone page with no host should pass the site's languages, so a browser language is used only when
72
+ the site offers it:
67
73
 
68
- ## Internationalization (i18n) System
69
-
70
- This document explains the i18n system for SmartLinks apps, covering URL-based language selection, static translations, and dynamic overrides.
71
-
72
- ---
73
-
74
- ## Overview
75
-
76
- The i18n system supports:
77
-
78
- - **URL parameter language selection** (`?lang=de`) - Ideal for iframe embedding
79
- - **Static translations** in JSON files - Fast, no API calls
80
- - **Dynamic overrides** via SmartLinks appConfig - Customer-configurable
81
- - **Type-safe translation keys** - Compile-time safety
82
- - **Widget support** - Translations can be passed to embedded widgets
83
-
84
- ---
85
-
86
- ## Quick Start
87
-
88
- ### Using Translations in Components
89
-
90
- ```typescript
91
- import { useLanguage } from '@/i18n';
92
-
93
- export const MyComponent = () => {
94
- const { t, lang } = useLanguage();
95
-
96
- return (
97
- <div>
98
- <h1>{t('public.title')}</h1>
99
- <p>{t('public.description')}</p>
100
- <small>Language: {lang}</small>
101
- </div>
102
- );
103
- };
104
- ```
105
-
106
- ### With Parameter Interpolation
107
-
108
- ```typescript
109
- const { t } = useLanguage();
110
-
111
- // Translation: "Hello, {{name}}!"
112
- t('greeting', { name: 'John' }); // "Hello, John!"
113
- ```
114
-
115
- ---
116
-
117
- ## Language Detection Priority
118
-
119
- The system detects language from multiple sources (in order):
120
-
121
- | Priority | Source | Example |
122
- |----------|--------|---------|
123
- | 1 | URL parameter | `?lang=de` |
124
- | 2 | localStorage | `smartlinks-lang` key |
125
- | 3 | Browser language | `navigator.language` |
126
- | 4 | Default | `en` |
127
-
128
- For iframe apps, the SmartLinks platform passes the language via URL parameter.
129
-
130
- ---
131
-
132
- ## File Structure
133
-
134
- ```text
135
- src/i18n/
136
- ├── index.ts # Main exports
137
- ├── LanguageContext.tsx # React context + provider
138
- ├── types.ts # TypeScript types
139
- └── locales/
140
- ├── en.json # English translations
141
- ├── de.json # German translations
142
- └── fr.json # French translations
143
- ```
144
-
145
- ---
146
-
147
- ## Adding New Translations
148
-
149
- ### 1. Add the Key to Types
150
-
151
- ```typescript
152
- // src/i18n/types.ts
153
- export type TranslationKey =
154
- | 'common.loading'
155
- | 'common.error'
156
- | 'myFeature.title' // Add new key
157
- | 'myFeature.description';
158
- ```
159
-
160
- ### 2. Add Translations to All Locales
161
-
162
- ```json
163
- // src/i18n/locales/en.json
164
- {
165
- "myFeature.title": "My Feature",
166
- "myFeature.description": "Description of my feature"
167
- }
168
-
169
- // src/i18n/locales/de.json
170
- {
171
- "myFeature.title": "Meine Funktion",
172
- "myFeature.description": "Beschreibung meiner Funktion"
173
- }
174
- ```
175
-
176
- ### 3. Use in Components
177
-
178
- ```typescript
179
- const { t } = useLanguage();
180
- return <h1>{t('myFeature.title')}</h1>;
181
- ```
182
-
183
- ---
184
-
185
- ## Adding New Languages
186
-
187
- ### 1. Create the Locale File
188
-
189
- ```json
190
- // src/i18n/locales/es.json
191
- {
192
- "common.loading": "Cargando...",
193
- "common.error": "Algo salió mal",
194
- // ... all other keys
195
- }
196
- ```
197
-
198
- ### 2. Import in LanguageContext
199
-
200
- ```typescript
201
- // src/i18n/LanguageContext.tsx
202
- import es from './locales/es.json';
203
-
204
- const staticTranslations: Record<string, PartialTranslations> = {
205
- en: en as PartialTranslations,
206
- de: de as PartialTranslations,
207
- fr: fr as PartialTranslations,
208
- es: es as PartialTranslations, // Add new language
209
- };
210
-
211
- const SUPPORTED_LANGUAGES = ['en', 'de', 'fr', 'es']; // Add to list
212
- ```
213
-
214
- ---
215
-
216
- ## Dynamic Translations (SmartLinks appConfig)
217
-
218
- For customer-configurable translations, store them in SmartLinks appConfig:
219
-
220
- ### Config Structure
221
-
222
- ```json
223
- {
224
- "i18n": {
225
- "supportedLanguages": ["en", "de"],
226
- "defaultLanguage": "en",
227
- "translations": {
228
- "en": {
229
- "public.title": "Custom Brand Title",
230
- "public.description": "Custom brand description"
231
- },
232
- "de": {
233
- "public.title": "Benutzerdefinierter Markentitel",
234
- "public.description": "Benutzerdefinierte Markenbeschreibung"
235
- }
236
- }
237
- }
238
- }
239
- ```
240
-
241
- ### Loading Dynamic Translations
242
-
243
- ```typescript
244
- import { useCollectionAppConfig } from '@/hooks/useSmartLinksData';
245
- import { LanguageProvider } from '@/i18n';
246
-
247
- const App = () => {
248
- const { data: config } = useCollectionAppConfig(collectionId, appId);
249
-
250
- return (
251
- <LanguageProvider dynamicTranslations={config?.i18n?.translations}>
252
- <MyApp />
253
- </LanguageProvider>
254
- );
255
- };
256
- ```
257
-
258
- Dynamic translations override static ones, so customers can customize specific strings while inheriting defaults.
259
-
260
- ---
261
-
262
- ## Widgets
263
-
264
- Widgets receive language context via props rather than React context (since they may run outside the provider).
265
-
266
- ### Widget Props
267
-
268
- ```typescript
269
- interface SmartLinksWidgetProps {
270
- // ... other props
271
- lang?: string;
272
- translations?: Record<string, string>;
273
- }
274
- ```
275
-
276
- ### Using in Widgets
277
-
278
- ```typescript
279
- import { createTranslator } from '@/i18n';
280
-
281
- export const MyWidget: React.FC<SmartLinksWidgetProps> = ({
282
- lang = 'en',
283
- translations = {},
284
- ...props
285
- }) => {
286
- const t = createTranslator(lang, translations);
287
-
288
- return <div>{t('widget.title')}</div>;
289
- };
290
- ```
291
-
292
- The `createTranslator` function creates a standalone translation function that doesn't require React context.
293
-
294
- ---
295
-
296
- ## URL Examples
297
-
298
- ```
299
- # English (default)
300
- /#/?collectionId=abc&appId=pamphlet
301
-
302
- # German
303
- /#/?collectionId=abc&appId=pamphlet&lang=de
304
-
305
- # French
306
- /#/?collectionId=abc&appId=pamphlet&lang=fr
74
+ ```ts
75
+ await i18n.init({ languages: collection.languages?.map((l) => l.code) })
307
76
  ```
308
77
 
309
- ---
310
-
311
- ## Best Practices
78
+ Never add your own language picker, and never translate into a language because the browser asks for it.
79
+ If a site is English only, it stays English (a visitor can still use their browser's own translation).
312
80
 
313
- 1. **Use dot notation** for key namespacing: `category.subcategory.key`
314
- 2. **Keep translations flat** - avoid nested objects in locale files
315
- 3. **Add keys to types.ts first** - ensures type safety
316
- 4. **Provide fallbacks** - English is always the fallback language
317
- 5. **Test all languages** - Use `?lang=xx` to switch during development
81
+ ## Hand-written translations are welcome
318
82
 
319
- ---
83
+ For a fixed set of labels you know well (a regulated product passport, a spec sheet), ship your own
84
+ `public/i18n/<lang>.json` files, as many languages as you like. Your keys win; the platform only fills
85
+ what you left out. That's faster to read and exact. What you should not do is hand-write the machinery.
320
86
 
321
- ## API Reference
87
+ ## Numbers, money and dates
322
88
 
323
- ### `useLanguage()`
89
+ Formats differ: "1,299.50" in English is "1.299,50" in German and "1 299,50" in French; dates and the
90
+ currency symbol move too. Always format in the language in use:
324
91
 
325
- Hook to access language context.
92
+ - `i18n.format.number(n)`, `i18n.format.date(d)`, `i18n.format.dateTime(d)`, `i18n.format.money(minor, currency)`.
93
+ - Outside the helper: `n.toLocaleString(utils.pageLocale())`, `utils.formatMinor(minor, currency)`,
94
+ `shop.formatMoney(...)`, `subscriptions.describePrice(...)`.
95
+ - Never a bare `toLocaleString()` / `toLocaleDateString()` (that's the browser's language, not the one the
96
+ visitor chose), never a fixed `'en-US'` or `'en-GB'`, never `(x / 100).toFixed(2)` or a hard-coded £/€/$.
97
+ Amounts are minor units in the currency's own decimals (whole units for JPY and KRW).
98
+ - **Reading what people type**: a German seller writes 12,99. Accept both decimal marks (the last `.` or
99
+ `,` followed by one or two digits is the decimal mark; the rest are thousands separators). Never strip
100
+ commas and never `Number(text)` a price field directly.
101
+ - Content (product names, page text) isn't your job: the platform translates it (`translations.resolve`).
326
102
 
327
- ```typescript
328
- const {
329
- lang, // Current language code
330
- setLang, // Function to change language
331
- t, // Translation function
332
- supportedLanguages // Array of supported language codes
333
- } = useLanguage();
334
- ```
103
+ ## Right-to-left languages (Arabic, Hebrew, Persian, Urdu)
335
104
 
336
- ### `createTranslator(lang, overrides)`
105
+ `i18n.textDirection(lang)` returns `'rtl'` or `'ltr'`. Portal and Hub set `<html dir>` from the
106
+ visitor's language, widgets inherit it, and iframe apps get it from `theme-boot.js` (from `?lang=` and
107
+ live `smartlinks:root-state`). For the layout to mirror, write direction-neutral CSS: Tailwind's
108
+ `ms-*`/`me-*`, `ps-*`/`pe-*`, `start-*`/`end-*`, `text-start`/`text-end`, `border-s`/`border-e`,
109
+ `rounded-s`/`rounded-e` instead of the left/right forms, and flip arrow icons that mean "forward" or
110
+ "back" with `rtl:-scale-x-100`.
337
111
 
338
- Creates a standalone translation function for widgets.
112
+ ## Moving off the older scaffold
339
113
 
340
- ```typescript
341
- const t = createTranslator('de', { 'custom.key': 'Custom value' });
342
- t('common.loading'); // "Laden..."
343
- t('custom.key'); // "Custom value"
344
- ```
345
-
346
- ### `LanguageProvider`
347
-
348
- React provider component.
349
-
350
- ```typescript
351
- <LanguageProvider dynamicTranslations={optionalOverrides}>
352
- <App />
353
- </LanguageProvider>
354
- ```
355
-
356
- ## Right-to-left languages (Arabic, Hebrew, Persian, Urdu)
357
-
358
- `i18n.textDirection(lang)` returns `'rtl'` or `'ltr'`. Portal and Hub set `<html dir>` from the
359
- visitor's language, widgets inherit it, and iframe apps get it from `theme-boot.js` (from `?lang=` and
360
- live `smartlinks:root-state`). For the layout to mirror, write direction-neutral CSS: Tailwind's
361
- `ms-*`/`me-*`, `ps-*`/`pe-*`, `start-*`/`end-*`, `text-start`/`text-end`, `border-s`/`border-e`,
362
- `rounded-s`/`rounded-e` instead of the left/right forms, and flip arrow icons that mean "forward" or
363
- "back" with `rtl:-scale-x-100`.
114
+ Apps built with the copied-in `src/i18n/` scaffold (`LanguageContext`, `src/i18n/locales/*.json`,
115
+ `createTranslator`) still work, but move them: put the English in `public/i18n/en.json` (keep any
116
+ hand-written languages as `public/i18n/<lang>.json`), read it with the helper above, and delete the
117
+ scaffold. In Forge this is step 21, "Speak the visitor's language".
package/package.json CHANGED
@@ -1,91 +1,91 @@
1
- {
2
- "name": "@proveanything/smartlinks",
3
- "version": "3.0.0-alpha.0",
4
- "description": "Official JavaScript/TypeScript SDK for the Smartlinks API",
5
- "type": "module",
6
- "main": "dist/index.js",
7
- "types": "dist/index.d.ts",
8
- "exports": {
9
- ".": {
10
- "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js",
12
- "default": "./dist/index.js"
13
- },
14
- "./testing": {
15
- "types": "./dist/testing/index.d.ts",
16
- "import": "./dist/testing/index.js",
17
- "default": "./dist/testing/index.js"
18
- },
19
- "./*": {
20
- "types": "./dist/*.d.ts",
21
- "import": "./dist/*.js",
22
- "default": "./dist/*.js"
23
- },
24
- "./baseline.css": "./dist/baseline.css",
25
- "./baseline.classes.json": "./dist/baseline.classes.json",
26
- "./theme.css": "./dist/theme.css",
27
- "./theme-boot.js": "./dist/theme-boot.js",
28
- "./package.json": "./package.json"
29
- },
30
- "bin": {
31
- "smartlinks-register-release": "scripts/register-release.mjs",
32
- "smartlinks-publish": "scripts/publish.mjs",
33
- "smartlinks-doctor": "scripts/doctor.mjs",
34
- "smartlinks-headless": "scripts/headless-check.mjs",
35
- "smartlinks-upgrade": "scripts/upgrade.mjs"
36
- },
37
- "files": [
38
- "dist/",
39
- "docs/",
40
- "upgrade/",
41
- "scripts/register-release.mjs",
42
- "scripts/publish.mjs",
43
- "scripts/doctor.mjs",
44
- "scripts/upgrade.mjs",
45
- "scripts/headless-check.mjs",
46
- "scripts/lib/",
47
- "openapi.yaml",
48
- "README.md"
49
- ],
50
- "scripts": {
51
- "test": "node test/run.cjs",
52
- "build": "node scripts/write-version.mjs && node scripts/upgrade-table.mjs --check && tsc && node scripts/fix-esm-extensions.mjs && node generate-api-summary.cjs && node generate-openapi.cjs && node scripts/copy-docs-to-dist.cjs && node scripts/build-baseline.mjs",
53
- "docs": "typedoc",
54
- "docs:summary": "node generate-api-summary.cjs",
55
- "docs:openapi": "node generate-openapi.cjs",
56
- "docs:openapi:lint": "npx --yes @redocly/cli@latest lint openapi.yaml",
57
- "docs:openapi:check": "node generate-openapi.cjs && npx --yes @redocly/cli@latest lint openapi.yaml",
58
- "build:docs": "tsc build-docs.ts --outDir dist && node dist/build-docs.js",
59
- "prepublishOnly": "npm run build",
60
- "docs:upgrade": "node scripts/upgrade-table.mjs"
61
- },
62
- "keywords": [
63
- "smartlinks",
64
- "api",
65
- "authentication",
66
- "traceability",
67
- "blockchain",
68
- "typescript",
69
- "sdk"
70
- ],
71
- "author": "Glenn Shoosmith",
72
- "license": "MIT",
73
- "publishConfig": {
74
- "access": "public"
75
- },
76
- "dependencies": {
77
- "cross-fetch": "^3.1.5",
78
- "es-module-lexer": "^1.7.0"
79
- },
80
- "devDependencies": {
81
- "ts-node": "^10.9.1",
82
- "typedoc": "^0.25.13",
83
- "typedoc-plugin-markdown": "^3.17.1",
84
- "typescript": "^4.9.0"
85
- },
86
- "repository": {
87
- "type": "git",
88
- "url": "https://github.com/Prove-Anything/smartlinks.git"
89
- },
90
- "homepage": "https://smartlinks.app"
91
- }
1
+ {
2
+ "name": "@proveanything/smartlinks",
3
+ "version": "3.0.0-alpha.1",
4
+ "description": "Official JavaScript/TypeScript SDK for the Smartlinks API",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./testing": {
15
+ "types": "./dist/testing/index.d.ts",
16
+ "import": "./dist/testing/index.js",
17
+ "default": "./dist/testing/index.js"
18
+ },
19
+ "./*": {
20
+ "types": "./dist/*.d.ts",
21
+ "import": "./dist/*.js",
22
+ "default": "./dist/*.js"
23
+ },
24
+ "./baseline.css": "./dist/baseline.css",
25
+ "./baseline.classes.json": "./dist/baseline.classes.json",
26
+ "./theme.css": "./dist/theme.css",
27
+ "./theme-boot.js": "./dist/theme-boot.js",
28
+ "./package.json": "./package.json"
29
+ },
30
+ "bin": {
31
+ "smartlinks-register-release": "scripts/register-release.mjs",
32
+ "smartlinks-publish": "scripts/publish.mjs",
33
+ "smartlinks-doctor": "scripts/doctor.mjs",
34
+ "smartlinks-headless": "scripts/headless-check.mjs",
35
+ "smartlinks-upgrade": "scripts/upgrade.mjs"
36
+ },
37
+ "files": [
38
+ "dist/",
39
+ "docs/",
40
+ "upgrade/",
41
+ "scripts/register-release.mjs",
42
+ "scripts/publish.mjs",
43
+ "scripts/doctor.mjs",
44
+ "scripts/upgrade.mjs",
45
+ "scripts/headless-check.mjs",
46
+ "scripts/lib/",
47
+ "openapi.yaml",
48
+ "README.md"
49
+ ],
50
+ "scripts": {
51
+ "test": "node test/run.cjs",
52
+ "build": "node scripts/write-version.mjs && node scripts/upgrade-table.mjs --check && tsc && node scripts/fix-esm-extensions.mjs && node generate-api-summary.cjs && node generate-openapi.cjs && node scripts/copy-docs-to-dist.cjs && node scripts/build-baseline.mjs",
53
+ "docs": "typedoc",
54
+ "docs:summary": "node generate-api-summary.cjs",
55
+ "docs:openapi": "node generate-openapi.cjs",
56
+ "docs:openapi:lint": "npx --yes @redocly/cli@latest lint openapi.yaml",
57
+ "docs:openapi:check": "node generate-openapi.cjs && npx --yes @redocly/cli@latest lint openapi.yaml",
58
+ "build:docs": "tsc build-docs.ts --outDir dist && node dist/build-docs.js",
59
+ "prepublishOnly": "npm run build",
60
+ "docs:upgrade": "node scripts/upgrade-table.mjs"
61
+ },
62
+ "keywords": [
63
+ "smartlinks",
64
+ "api",
65
+ "authentication",
66
+ "traceability",
67
+ "blockchain",
68
+ "typescript",
69
+ "sdk"
70
+ ],
71
+ "author": "Glenn Shoosmith",
72
+ "license": "MIT",
73
+ "publishConfig": {
74
+ "access": "public"
75
+ },
76
+ "dependencies": {
77
+ "cross-fetch": "^3.1.5",
78
+ "es-module-lexer": "^1.7.0"
79
+ },
80
+ "devDependencies": {
81
+ "ts-node": "^10.9.1",
82
+ "typedoc": "^0.25.13",
83
+ "typedoc-plugin-markdown": "^3.17.1",
84
+ "typescript": "^4.9.0"
85
+ },
86
+ "repository": {
87
+ "type": "git",
88
+ "url": "https://github.com/Prove-Anything/smartlinks.git"
89
+ },
90
+ "homepage": "https://smartlinks.app"
91
+ }