@proveanything/smartlinks 2.2.0 → 2.2.3

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/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,297 +64,41 @@ 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
307
- ```
308
-
309
- ---
310
-
311
- ## Best Practices
312
-
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
318
-
319
- ---
320
-
321
- ## API Reference
322
-
323
- ### `useLanguage()`
324
-
325
- Hook to access language context.
326
-
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();
74
+ ```ts
75
+ await i18n.init({ languages: collection.languages?.map((l) => l.code) })
334
76
  ```
335
77
 
336
- ### `createTranslator(lang, overrides)`
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).
337
80
 
338
- Creates a standalone translation function for widgets.
81
+ ## Hand-written translations are welcome
339
82
 
340
- ```typescript
341
- const t = createTranslator('de', { 'custom.key': 'Custom value' });
342
- t('common.loading'); // "Laden..."
343
- t('custom.key'); // "Custom value"
344
- ```
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.
345
86
 
346
- ### `LanguageProvider`
87
+ ## Numbers, money and dates
347
88
 
348
- React provider component.
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:
349
91
 
350
- ```typescript
351
- <LanguageProvider dynamicTranslations={optionalOverrides}>
352
- <App />
353
- </LanguageProvider>
354
- ```
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`).
355
102
 
356
103
  ## Right-to-left languages (Arabic, Hebrew, Persian, Urdu)
357
104
 
@@ -361,3 +108,10 @@ live `smartlinks:root-state`). For the layout to mirror, write direction-neutral
361
108
  `ms-*`/`me-*`, `ps-*`/`pe-*`, `start-*`/`end-*`, `text-start`/`text-end`, `border-s`/`border-e`,
362
109
  `rounded-s`/`rounded-e` instead of the left/right forms, and flip arrow icons that mean "forward" or
363
110
  "back" with `rtl:-scale-x-100`.
111
+
112
+ ## Moving off the older scaffold
113
+
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".
@@ -430,6 +430,17 @@ The responder handles these message types from the iframe:
430
430
  }
431
431
  ```
432
432
 
433
+ ### Data changed
434
+
435
+ Parent → Iframe, after a change the app did not make itself (an assistant's change applied, a save in
436
+ another app). The app's SDK forgets the reads it kept and its open screen reads again. See
437
+ `docs/data-changed.md`.
438
+
439
+ ```ts
440
+ responder.dataChanged({ collectionId, changes: [{ type: 'product', id }], source: 'assistant' })
441
+ // → { type: 'smartlinks:data-changed', collectionId, changes: [...], source }
442
+ ```
443
+
433
444
  ## TypeScript Support
434
445
 
435
446
  All types are exported for full TypeScript support:
package/docs/overview.md CHANGED
@@ -100,6 +100,7 @@ The SmartLinks SDK (`@proveanything/smartlinks`) includes comprehensive document
100
100
  | **App Data Storage** | `docs/app-data-storage.md` | Decision guide: pick between `appConfiguration` / `userAppData` / `app.records` |
101
101
  | **Attestations** | `docs/attestations.md` | Postgres attestations API (proof-level user/admin data; replaces the legacy Firestore path) |
102
102
  | **Caching** | `docs/caching.md` | SDK GET cache tiers + TTLs, `invalidateCache({ exact })`, and `force`/push guidance |
103
+ | **Data Changed** | `docs/data-changed.md` | The host tells an open admin screen that records changed behind its back (the assistant, another app): `onDataChanged`, `postDataChanged`, and what to do with a form in mid-edit |
103
104
  | **Comms & Broadcasts** | `docs/comms.md` | Transactional comms, campaigns, consent, push |
104
105
  | **Container Tracking** | `docs/container-tracking.md` | Physical/logical **item** container groupings — *not* app containers (see containers.md) |
105
106
  | **Lots** | `docs/lots.md` | Cross-SKU production "Lot" entity |
package/docs/realtime.md CHANGED
@@ -136,3 +136,9 @@ example, `scan`: a tag they just scanned with Sidekick on another device.
136
136
  `realtime.getPublicToken()` and `realtime.getAdminToken()` return raw provider tokens for the old
137
137
  `collection:{id}:*` and `interaction:{uid}` channels. They still work, but publishing is now limited to
138
138
  the collection's admins. Move to `channel` / `onChange` / `onMine`.
139
+
140
+ ## Changes the host already knows about
141
+
142
+ An app inside Studio does not need its own connection to hear that the assistant or another app changed
143
+ a record: the host passes that into the frame as `smartlinks:data-changed`. Listen with
144
+ `SL.onDataChanged` (`docs/data-changed.md`).
@@ -100,9 +100,18 @@ await app.records.query(collectionId, appId, {
100
100
 
101
101
  ## Sorting and paging
102
102
 
103
- `orderBy` takes up to 3 `{ field: 'asc' | 'desc' }`. Only fields that are never empty can be sorted
104
- on (ask `queryFields`). Pass the answer's `nextCursor` as `cursor` for the next page, with the **same**
105
- `where` and `orderBy`; a cursor from a different query is refused.
103
+ `orderBy` takes up to 3 `{ field: 'asc' | 'desc' }`, on the fields that can sort (ask `queryFields`: their
104
+ `can` includes `sort`). A few of them can be empty, such as an app record's `startsAt` and `expiresAt`:
105
+ the rows without one come **last**, whichever way you sort, and paging carries on through them. Pass the
106
+ answer's `nextCursor` as `cursor` for the next page, with the **same** `where` and `orderBy`; a cursor from
107
+ a different query is refused.
108
+
109
+ ```typescript
110
+ // An app's events, latest first; any without a date at the end
111
+ await app.records.query(collectionId, appId, { where: { recordType: 'event' }, orderBy: [{ startsAt: 'desc' }], limit: 100 })
112
+ ```
113
+
114
+ A page holds at most 200 rows (`limit` 1–200). To read more, follow `nextCursor`.
106
115
 
107
116
  ```typescript
108
117
  let cursor: string | null = null
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@proveanything/smartlinks",
3
- "version": "2.2.0",
3
+ "version": "2.2.3",
4
4
  "description": "Official JavaScript/TypeScript SDK for the Smartlinks API",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",