@sveltia/i18n 0.1.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.
package/README.md ADDED
@@ -0,0 +1,709 @@
1
+ # Sveltia I18n
2
+
3
+ An internationalization (i18n) library for Svelte applications. Heavily inspired by [svelte-i18n](https://github.com/kaisermann/svelte-i18n), but powered by Svelte 5 Runes and the [messageformat](https://github.com/messageformat/messageformat) library for formatting messages using [Unicode MessageFormat 2](https://messageformat.unicode.org/) (MF2), which supports complex pluralization and selection patterns in addition to simple variable interpolation.
4
+
5
+ ## Table of Contents
6
+
7
+ - [Installation](#installation)
8
+ - [Usage](#usage)
9
+ - [SvelteKit usage](#sveltekit-usage)
10
+ - [Async loading with SSR](#async-loading-with-ssr)
11
+ - [Server-side locale via `Accept-Language`](#server-side-locale-via-accept-language)
12
+ - [Client-side locale detection](#client-side-locale-detection)
13
+ - [API](#api)
14
+ - [State](#state)
15
+ - [`locales`](#locales)
16
+ - [`dictionary`](#dictionary)
17
+ - [`isLoading()`](#isloading)
18
+ - [`isRTL()`](#isrtl)
19
+ - [Locale](#locale)
20
+ - [`locale`](#locale-1)
21
+ - [`getLocaleFromNavigator()`](#getlocalefromnavigator)
22
+ - [`getLocaleFromHostname(pattern)`](#getlocalefromhostnamepattern)
23
+ - [`getLocaleFromPathname(pattern)`](#getlocalefrompathnamepattern)
24
+ - [`getLocaleFromQueryString(key)`](#getlocalefromquerystringkey)
25
+ - [`getLocaleFromHash(key)`](#getlocalefromhashkey)
26
+ - [Configuration](#configuration)
27
+ - [`init(options)`](#initoptions)
28
+ - [Loader](#loader)
29
+ - [`register(localeCode, loader)`](#registerlocalecode-loader)
30
+ - [`waitLocale(localeCode?)`](#waitlocalelocalecode)
31
+ - [Messages](#messages)
32
+ - [`addMessages(localeCode, ...maps)`](#addmessageslocalecode-maps)
33
+ - [Formatting](#formatting)
34
+ - [`format(key, options?)` / `_(key, options?)` / `t(key, options?)`](#formatkey-options--_key-options--tkey-options)
35
+ - [`json(prefix, options?)`](#jsonprefix-options)
36
+ - [Date, time & number](#date-time--number)
37
+ - [`date(value, options?)`](#datevalue-options)
38
+ - [`time(value, options?)`](#timevalue-options)
39
+ - [`number(value, options?)`](#numbervalue-options)
40
+ - [Message Format](#message-format)
41
+ - [Simple interpolation](#simple-interpolation)
42
+ - [Pluralization](#pluralization)
43
+ - [Ordinal numbers](#ordinal-numbers)
44
+ - [Gender selection](#gender-selection)
45
+ - [Number formatting](#number-formatting)
46
+ - [Date and time](#date-and-time)
47
+ - [Built-in MF2 functions](#built-in-mf2-functions)
48
+ - [Compatibility with svelte-i18n](#svelte-i18n-compatibility)
49
+ - [Functions](#functions)
50
+ - [Key differences](#key-differences)
51
+
52
+ ## Installation
53
+
54
+ ```bash
55
+ pnpm add @sveltia/i18n
56
+ ```
57
+
58
+ ## Usage
59
+
60
+ ```js
61
+ import { _, addMessages, init, locale, register, waitLocale } from '@sveltia/i18n';
62
+ ```
63
+
64
+ ## SvelteKit usage
65
+
66
+ ### Async loading with SSR
67
+
68
+ Register loaders in a shared module, then await them in the root layout's `load` function:
69
+
70
+ ```js
71
+ // src/lib/i18n.js
72
+ import { register, init } from '@sveltia/i18n';
73
+
74
+ register('en-US', () => import('./locales/en-US.yaml?raw').then((m) => parseYaml(m.default)));
75
+ register('fr', () => import('./locales/fr.yaml?raw').then((m) => parseYaml(m.default)));
76
+
77
+ init({ fallbackLocale: 'en-US' });
78
+ ```
79
+
80
+ ```js
81
+ // src/routes/+layout.js
82
+ import { browser } from '$app/environment';
83
+ import '$lib/i18n'; // initialize
84
+ import { locale, waitLocale, getLocaleFromNavigator } from '@sveltia/i18n';
85
+
86
+ export const load = async () => {
87
+ if (browser) await locale.set(getLocaleFromNavigator());
88
+ await waitLocale();
89
+ };
90
+ ```
91
+
92
+ ### Server-side locale via `Accept-Language`
93
+
94
+ Read the request header in a server hook and set the locale before rendering:
95
+
96
+ ```js
97
+ // src/hooks.server.js
98
+ import { locale } from '@sveltia/i18n';
99
+
100
+ export const handle = async ({ event, resolve }) => {
101
+ const lang = event.request.headers.get('accept-language')?.split(',')[0];
102
+ if (lang) await locale.set(lang);
103
+ return resolve(event);
104
+ };
105
+ ```
106
+
107
+ ### Client-side locale detection
108
+
109
+ For client-only apps (no SSR), detect the locale directly from the browser environment and call `locale.set()` in `onMount` or in a `+layout.js` `load` function guarded by `browser`:
110
+
111
+ ```js
112
+ // src/routes/+layout.js
113
+ import { browser } from '$app/environment';
114
+ import '$lib/i18n'; // initialize
115
+ import {
116
+ locale,
117
+ waitLocale,
118
+ getLocaleFromNavigator,
119
+ getLocaleFromQueryString,
120
+ } from '@sveltia/i18n';
121
+
122
+ export const load = async () => {
123
+ if (browser) {
124
+ // Pick the first available source: ?lang= query param, then browser preference
125
+ const detected = getLocaleFromQueryString('lang') ?? getLocaleFromNavigator();
126
+ await locale.set(detected ?? 'en-US');
127
+ }
128
+ await waitLocale();
129
+ };
130
+ ```
131
+
132
+ You can combine any of the `getLocaleFrom*` helpers in priority order:
133
+
134
+ | Helper | Source |
135
+ | ---------------------------------------- | ----------------------------------------------- |
136
+ | `getLocaleFromNavigator()` | `navigator.languages[0]` / `navigator.language` |
137
+ | `getLocaleFromQueryString('lang')` | `?lang=fr` URL parameter |
138
+ | `getLocaleFromPathname(/^\/([\w-]+)\//)` | `/fr/page` path prefix |
139
+ | `getLocaleFromHostname(/^([\w-]+)\./)` | `fr.example.com` subdomain |
140
+ | `getLocaleFromHash('lang')` | `#lang=fr` hash parameter |
141
+
142
+ ## API
143
+
144
+ ### State
145
+
146
+ #### `locales`
147
+
148
+ A reactive array of all registered locale codes.
149
+
150
+ ```js
151
+ import { locales } from '@sveltia/i18n';
152
+ // ['en-US', 'fr', 'ja']
153
+ ```
154
+
155
+ ---
156
+
157
+ #### `dictionary`
158
+
159
+ A reactive record of all registered messages, keyed by locale code then message key. Values are `Intl.MessageFormat` instances. Useful for advanced inspection; prefer `format`/`_` for normal use.
160
+
161
+ ---
162
+
163
+ #### `isLoading()`
164
+
165
+ Returns `true` when a locale has been set but its messages have not yet been loaded. Useful to show a loading indicator or guard rendering until resources are ready.
166
+
167
+ ```js
168
+ import { isLoading } from '@sveltia/i18n';
169
+ if (isLoading()) return; // messages still loading
170
+ ```
171
+
172
+ ---
173
+
174
+ #### `isRTL()`
175
+
176
+ Returns `true` when the current locale is written right-to-left (e.g. Arabic, Hebrew, Persian). Reactive: re-evaluates automatically whenever the locale changes.
177
+
178
+ ```js
179
+ import { isRTL } from '@sveltia/i18n';
180
+ if (isRTL()) console.log('RTL layout active');
181
+ ```
182
+
183
+ In a Svelte template:
184
+
185
+ ```svelte
186
+ <div dir={isRTL() ? 'rtl' : 'ltr'}>
187
+ {_('content')}
188
+ </div>
189
+ ```
190
+
191
+ ---
192
+
193
+ ### Locale
194
+
195
+ #### `locale`
196
+
197
+ A reactive object representing the current locale.
198
+
199
+ ```js
200
+ locale.current; // → 'en-US'
201
+ await locale.set('fr'); // switch to French, triggers any registered loader, updates <html lang>
202
+ ```
203
+
204
+ `locale.set(value)` returns a `Promise<void>` that resolves once any loader registered for the new locale has finished loading. It also keeps `document.documentElement.lang` and `document.documentElement.dir` (`ltr`/`rtl`) in sync automatically.
205
+
206
+ **Locale negotiation:** if the requested value is not in the registered `locales` list, `locale.set()` tries to find the best match by language subtag before falling back to the original value. For example, if `en-US` is registered and the user's browser reports `en-CA`, `locale.current` is set to `en-US`.
207
+
208
+ ```js
209
+ // locales registered: ['en-US', 'fr', 'ja']
210
+ await locale.set('en-CA'); // locale.current → 'en-US'
211
+ await locale.set('zh-TW'); // no match → locale.current stays 'zh-TW'
212
+ ```
213
+
214
+ #### `getLocaleFromNavigator()`
215
+
216
+ Returns the user's preferred locale from the browser (`navigator.languages[0]` or `navigator.language`).
217
+
218
+ ```js
219
+ import { getLocaleFromNavigator } from '@sveltia/i18n';
220
+ const lang = getLocaleFromNavigator(); // e.g. 'ja'
221
+ ```
222
+
223
+ ---
224
+
225
+ #### `getLocaleFromHostname(pattern)`
226
+
227
+ Matches `location.hostname` against a `RegExp` and returns capture group 1.
228
+
229
+ ```js
230
+ import { getLocaleFromHostname } from '@sveltia/i18n';
231
+ // URL: https://fr.example.com/
232
+ getLocaleFromHostname(/^(.*?)\./); // → 'fr'
233
+ ```
234
+
235
+ ---
236
+
237
+ #### `getLocaleFromPathname(pattern)`
238
+
239
+ Matches `location.pathname` against a `RegExp` and returns capture group 1.
240
+
241
+ ```js
242
+ import { getLocaleFromPathname } from '@sveltia/i18n';
243
+ // URL: https://example.com/en-US/about
244
+ getLocaleFromPathname(/^\/(\w[\w-]*)\//); // → 'en-US'
245
+ ```
246
+
247
+ ---
248
+
249
+ #### `getLocaleFromQueryString(key)`
250
+
251
+ Reads a locale code from a URL query string parameter.
252
+
253
+ ```js
254
+ import { getLocaleFromQueryString } from '@sveltia/i18n';
255
+ // URL: https://example.com/?lang=ja
256
+ getLocaleFromQueryString('lang'); // → 'ja'
257
+ ```
258
+
259
+ ---
260
+
261
+ #### `getLocaleFromHash(key)`
262
+
263
+ Reads a locale code from a `key=value` pair in `location.hash`.
264
+
265
+ ```js
266
+ import { getLocaleFromHash } from '@sveltia/i18n';
267
+ // URL: https://example.com/#lang=fr
268
+ getLocaleFromHash('lang'); // → 'fr'
269
+ ```
270
+
271
+ ---
272
+
273
+ ### Configuration
274
+
275
+ #### `init(options)`
276
+
277
+ Configures the library. All options except `fallbackLocale` are optional.
278
+
279
+ | Option | Type | Description |
280
+ | --- | --- | --- |
281
+ | `fallbackLocale` | `string` | Locale used when a key is missing from the current locale. |
282
+ | `initialLocale` | `string` | Locale to activate immediately. |
283
+ | `formats` | `{ number?, date?, time? }` | Custom named formats for `number()`, `date()`, and `time()`. |
284
+ | `handleMissingMessage` | `(key, locale, defaultValue) => string \| void` | Called when a key is not found. Return a string to replace the fallback, or `undefined` to continue with the default behaviour. |
285
+
286
+ ```js
287
+ import { getLocaleFromNavigator, init } from '@sveltia/i18n';
288
+
289
+ init({
290
+ fallbackLocale: 'en-US',
291
+ initialLocale: getLocaleFromNavigator(),
292
+ formats: {
293
+ number: { EUR: { style: 'currency', currency: 'EUR' } },
294
+ },
295
+ handleMissingMessage: (key, locale) => {
296
+ console.warn(`Missing message: ${key} (${locale})`);
297
+ },
298
+ });
299
+ ```
300
+
301
+ ---
302
+
303
+ ### Loader
304
+
305
+ #### `register(localeCode, loader)`
306
+
307
+ Registers an async loader function for a locale. The loader is called the first time `waitLocale(localeCode)` is invoked for that locale, and its result is passed to `addMessages`. (`locale.set()` triggers loading by calling `waitLocale()` internally.) Calling `register()` again for the same locale invalidates the cached promise so the new loader is picked up on the next `waitLocale()` call.
308
+
309
+ ```js
310
+ import { register, waitLocale, locale } from '@sveltia/i18n';
311
+
312
+ register('en-US', () => import('./locales/en-US.yaml?raw').then((m) => parseYaml(m.default)));
313
+ register('fr', () => import('./locales/fr.yaml?raw').then((m) => parseYaml(m.default)));
314
+
315
+ // In a SvelteKit +layout.js load function:
316
+ export const load = async () => {
317
+ locale.set('en-US');
318
+ await waitLocale();
319
+ };
320
+ ```
321
+
322
+ ---
323
+
324
+ #### `waitLocale(localeCode?)`
325
+
326
+ Executes the loader registered for `localeCode` (defaults to `locale.current`) and returns a `Promise<void>` that resolves when the messages are loaded. Repeated calls for the same locale return the same promise (deduplication). Safe to call even when no loader is registered — it resolves immediately. If the loader rejects, the cached promise is cleared so the next `waitLocale()` call will retry.
327
+
328
+ ```js
329
+ await waitLocale('fr'); // load French
330
+ await waitLocale(); // load the current locale
331
+ ```
332
+
333
+ ---
334
+
335
+ ### Messages
336
+
337
+ #### `addMessages(localeCode, ...maps)`
338
+
339
+ Registers one or more message maps for a locale. Values must be valid [MF2](https://messageformat.unicode.org/) message strings. Maps may be **flat** (dot-separated keys) or **nested** objects — both are normalised to dot-separated keys. Multiple maps are merged in order, matching svelte-i18n's variadic signature.
340
+
341
+ ```js
342
+ import { addMessages } from '@sveltia/i18n';
343
+
344
+ // Flat
345
+ addMessages('en-US', {
346
+ 'field.name': 'Name',
347
+ 'field.birth': 'Date of birth',
348
+ });
349
+
350
+ // Nested (equivalent)
351
+ addMessages('en-US', {
352
+ field: {
353
+ name: 'Name',
354
+ birth: 'Date of birth',
355
+ },
356
+ notifications: `
357
+ .input {$count :integer}
358
+ .match $count
359
+ 0 {{You have no notifications.}}
360
+ one {{You have {$count} notification.}}
361
+ * {{You have {$count} notifications.}}
362
+ `,
363
+ });
364
+
365
+ // Multiple maps merged in one call
366
+ addMessages('en-US', { 'field.name': 'Name' }, { 'field.birth': 'Date of birth' });
367
+
368
+ _('field.name'); // → 'Name'
369
+ ```
370
+
371
+ ---
372
+
373
+ ### Formatting
374
+
375
+ #### `format(key, options?)` / `_(key, options?)` / `t(key, options?)`
376
+
377
+ Formats a message by key. `_` and `t` are aliases for `format`.
378
+
379
+ Supports two call signatures (matching svelte-i18n):
380
+
381
+ - `format(id, options?)` — key as first argument
382
+ - `format({ id, values?, locale?, default? })` — options object only
383
+
384
+ | Option | Type | Description |
385
+ | --- | --- | --- |
386
+ | `values` | `Record<string, any>` | Variables to interpolate into the message. |
387
+ | `locale` | `string` | Override the active locale for this call only. If the key is not found in the override locale, the lookup still falls back to `fallbackLocale`. |
388
+ | `default` | `string` | Fallback string if the key is not found in any locale. |
389
+
390
+ ```js
391
+ import { _, t } from '@sveltia/i18n';
392
+
393
+ _('hello', { values: { name: 'Alice' } }); // → 'Hello, Alice!'
394
+ _('notifications', { values: { count: 3 } }); // → 'You have 3 notifications.'
395
+ _('missing.key', { default: 'Not found' }); // → 'Not found'
396
+ _('missing.key'); // → 'missing.key'
397
+
398
+ // Per-call locale override (does not change locale.current)
399
+ _('hello', { locale: 'fr', values: { name: 'Alice' } }); // → 'Bonjour, Alice!'
400
+
401
+ // Object-first signature (svelte-i18n compatible)
402
+ _({ id: 'hello', values: { name: 'Alice' } }); // → 'Hello, Alice!'
403
+
404
+ // svelte-i18n-style alias
405
+ t('hello'); // → 'Hello!'
406
+ ```
407
+
408
+ ---
409
+
410
+ #### `json(prefix, options?)`
411
+
412
+ Returns a flat object of formatted strings for all message keys under the given prefix. Equivalent to svelte-i18n's `$json()`. Useful for iterating over a group of related messages without knowing every key name.
413
+
414
+ ```js
415
+ import { json } from '@sveltia/i18n';
416
+
417
+ // Locale file has: nav.home, nav.about, nav.contact
418
+ json('nav'); // → { home: 'Home', about: 'About', contact: 'Contact' }
419
+ json('unknown'); // → undefined
420
+ ```
421
+
422
+ When the active locale has no messages, `json()` falls back to the `fallbackLocale` dictionary, matching the same fallback behaviour as `format()`.
423
+
424
+ In a Svelte template:
425
+
426
+ ```svelte
427
+ {#each Object.entries(json('nav') ?? {}) as [key, label]}
428
+ <a href="/{key}">{label}</a>
429
+ {/each}
430
+ ```
431
+
432
+ Options:
433
+
434
+ | Option | Type | Description |
435
+ | -------- | -------- | ---------------------------------------- |
436
+ | `locale` | `string` | Override the active locale for this call |
437
+
438
+ ---
439
+
440
+ ### Date, time & number
441
+
442
+ #### `date(value, options?)`
443
+
444
+ Formats a `Date` as a localized date string. Equivalent to svelte-i18n's `$date()`.
445
+
446
+ Options accept any `Intl.DateTimeFormatOptions` plus:
447
+
448
+ | Option | Type | Description |
449
+ | --- | --- | --- |
450
+ | `locale` | `string` | Override the active locale for this call. |
451
+ | `format` | `string` | A named format: `short`, `medium`, `long`, `full`, or a custom name defined in `init({ formats })`. |
452
+
453
+ ```js
454
+ import { date } from '@sveltia/i18n';
455
+
456
+ date(new Date('2026-01-23')); // → '1/23/2026'
457
+ date(new Date('2026-01-23'), { format: 'long' }); // → 'January 23, 2026'
458
+ date(new Date('2026-01-23'), { locale: 'fr-FR', format: 'long' }); // → '23 janvier 2026'
459
+ ```
460
+
461
+ ---
462
+
463
+ #### `time(value, options?)`
464
+
465
+ Formats a `Date` as a localized time string. Equivalent to svelte-i18n's `$time()`.
466
+
467
+ Options accept any `Intl.DateTimeFormatOptions` plus `locale` and `format` (same named formats as `date()` but from the `time` set: `short`, `medium`, `long`, `full`).
468
+
469
+ ```js
470
+ import { time } from '@sveltia/i18n';
471
+
472
+ time(new Date('2026-01-23T15:04:00')); // → '3:04 PM'
473
+ time(new Date('2026-01-23T15:04:00'), { format: 'medium' }); // → '3:04:00 PM'
474
+ ```
475
+
476
+ ---
477
+
478
+ #### `number(value, options?)`
479
+
480
+ Formats a number as a localized string. Equivalent to svelte-i18n's `$number()`.
481
+
482
+ Options accept any `Intl.NumberFormatOptions` plus:
483
+
484
+ | Option | Type | Description |
485
+ | --- | --- | --- |
486
+ | `locale` | `string` | Override the active locale for this call. |
487
+ | `format` | `string` | A named format: `currency`, `percent`, `scientific`, `engineering`, `compactLong`, `compactShort`, or a custom name defined in `init({ formats })`. |
488
+
489
+ ```js
490
+ import { number } from '@sveltia/i18n';
491
+
492
+ number(1234567); // → '1,234,567'
493
+ number(0.42, { format: 'percent' }); // → '42%'
494
+ number(9.99, { style: 'currency', currency: 'USD' }); // → '$9.99'
495
+
496
+ // Custom named format defined in init()
497
+ // init({ formats: { number: { EUR: { style: 'currency', currency: 'EUR' } } } })
498
+ number(9.99, { format: 'EUR' }); // → '€9.99'
499
+ ```
500
+
501
+ ---
502
+
503
+ ## Message Format
504
+
505
+ Locale files use [MF2 syntax](https://messageformat.unicode.org/). Single-pattern messages can be written as plain YAML strings; multi-pattern messages use YAML block scalars.
506
+
507
+ ### Simple interpolation
508
+
509
+ ```yaml
510
+ # en-US.yaml
511
+ greeting: 'Hello, {$name}!'
512
+ farewell: 'Goodbye, {$name}. See you on {$date :date length=long}.'
513
+ ```
514
+
515
+ ### Pluralization
516
+
517
+ English has two plural forms (`one` / `*`):
518
+
519
+ ```yaml
520
+ # en-US.yaml
521
+ notifications: |
522
+ .input {$count :integer}
523
+ .match $count
524
+ 0 {{You have no notifications.}}
525
+ one {{You have {$count} notification.}}
526
+ * {{You have {$count} notifications.}}
527
+ ```
528
+
529
+ French treats 0 as singular:
530
+
531
+ <!-- cSpell:disable -->
532
+
533
+ ```yaml
534
+ # fr.yaml
535
+ notifications: |
536
+ .input {$count :integer}
537
+ .match $count
538
+ 0 {{Vous n'avez pas de notifications.}}
539
+ one {{Vous avez {$count} notification.}}
540
+ * {{Vous avez {$count} notifications.}}
541
+ ```
542
+
543
+ <!-- cSpell:enable -->
544
+
545
+ Polish has four plural forms — `one`, `few` (2–4, except teens), `many` (5+, teens), and `*` (fractions) — making it a good stress-test for pluralization logic:
546
+
547
+ <!-- cSpell:disable -->
548
+
549
+ ```yaml
550
+ # pl.yaml
551
+ notifications: |
552
+ .input {$count :integer}
553
+ .match $count
554
+ 0 {{Nie masz żadnych powiadomień.}}
555
+ one {{Masz {$count} powiadomienie.}}
556
+ few {{Masz {$count} powiadomienia.}}
557
+ many {{Masz {$count} powiadomień.}}
558
+ * {{Masz {$count} powiadomienia.}}
559
+
560
+ items: |
561
+ .input {$count :integer}
562
+ .match $count
563
+ one {{Znaleziono {$count} element.}}
564
+ few {{Znaleziono {$count} elementy.}}
565
+ many {{Znaleziono {$count} elementów.}}
566
+ * {{Znaleziono {$count} elementów.}}
567
+ ```
568
+
569
+ <!-- cSpell:enable -->
570
+
571
+ Arabic has six plural forms (`zero`, `one`, `two`, `few`, `many`, `*`):
572
+
573
+ <!-- cSpell:disable -->
574
+
575
+ ```yaml
576
+ # ar.yaml
577
+ notifications: |
578
+ .input {$count :integer}
579
+ .match $count
580
+ 0 {{ليس لديك أي إشعارات.}}
581
+ one {{لديك إشعار واحد.}}
582
+ two {{لديك إشعاران.}}
583
+ few {{لديك {$count} إشعارات.}}
584
+ many {{لديك {$count} إشعارًا.}}
585
+ * {{لديك {$count} إشعار.}}
586
+ ```
587
+
588
+ <!-- cSpell:enable -->
589
+
590
+ ### Ordinal numbers
591
+
592
+ English ordinal suffixes (`1st`, `2nd`, `3rd`, `4th`, …):
593
+
594
+ ```yaml
595
+ # en-US.yaml
596
+ ranking: |
597
+ .input {$rank :number select=ordinal}
598
+ .match $rank
599
+ one {{You are ranked {$rank}st.}}
600
+ two {{You are ranked {$rank}nd.}}
601
+ few {{You are ranked {$rank}rd.}}
602
+ * {{You are ranked {$rank}th.}}
603
+ ```
604
+
605
+ ### Gender selection
606
+
607
+ A single gender variable:
608
+
609
+ ```yaml
610
+ # en-US.yaml
611
+ welcome: |
612
+ .input {$gender :string}
613
+ .match $gender
614
+ female {{Welcome, Ms. {$name}.}}
615
+ male {{Welcome, Mr. {$name}.}}
616
+ * {{Welcome, {$name}.}}
617
+ ```
618
+
619
+ Multiple selectors (gender × guest count):
620
+
621
+ ```yaml
622
+ # en-US.yaml
623
+ party: |
624
+ .input {$hostGender :string}
625
+ .input {$guestCount :number}
626
+ .match $hostGender $guestCount
627
+ female 0 {{{$hostName} does not give a party.}}
628
+ female 1 {{{$hostName} invites {$guestName} to her party.}}
629
+ female * {{{$hostName} invites {$guestCount} people, including {$guestName}, to her party.}}
630
+ male 0 {{{$hostName} does not give a party.}}
631
+ male 1 {{{$hostName} invites {$guestName} to his party.}}
632
+ male * {{{$hostName} invites {$guestCount} people, including {$guestName}, to his party.}}
633
+ * 0 {{{$hostName} does not give a party.}}
634
+ * 1 {{{$hostName} invites {$guestName} to their party.}}
635
+ * * {{{$hostName} invites {$guestCount} people, including {$guestName}, to their party.}}
636
+ ```
637
+
638
+ ### Number formatting
639
+
640
+ ```yaml
641
+ # en-US.yaml
642
+ price: 'Price: {$amount :currency currency=USD}.'
643
+ progress: 'Progress: {$ratio :percent}.'
644
+ decimal: 'Value: {$num :number minimumFractionDigits=2}.'
645
+ signed: 'Change: {$num :number signDisplay=always}.'
646
+ id: 'ID: {$num :number minimumIntegerDigits=4}.'
647
+ ```
648
+
649
+ ### Date and time
650
+
651
+ ```yaml
652
+ # en-US.yaml
653
+ today: 'Today is {$date :date}.'
654
+ date-short: 'Short date: {$date :date length=short}.'
655
+ date-long: 'Long date: {$date :date fields=|month-day-weekday| length=long}.'
656
+ datetime: 'Appointment: {$date :datetime}.'
657
+ time: 'The time is {$time :time}.'
658
+ time-precise: 'Precise time: {$time :time precision=second}.'
659
+ ```
660
+
661
+ ### Built-in MF2 functions
662
+
663
+ Built-in MF2 functions available via `DraftFunctions`:
664
+
665
+ | Function | Purpose | Example |
666
+ | ----------- | ---------------------------------------- | -------------------------------------- |
667
+ | `:number` | Decimal number formatting | `{$n :number minimumFractionDigits=2}` |
668
+ | `:integer` | Integer (no decimals) + plural selection | `{$n :integer}` |
669
+ | `:percent` | Percentage (multiplies by 100) | `{$r :percent}` |
670
+ | `:currency` | Currency formatting | `{$n :currency currency=USD}` |
671
+ | `:date` | Date-only formatting | `{$d :date length=short}` |
672
+ | `:time` | Time-only formatting | `{$t :time precision=second}` |
673
+ | `:datetime` | Date + time formatting | `{$d :datetime}` |
674
+ | `:string` | String selector | `{$s :string}` |
675
+
676
+ ---
677
+
678
+ ## Compatibility with svelte-i18n
679
+
680
+ Sveltia I18n is designed to be a modern alternative to [svelte-i18n](https://github.com/kaisermann/svelte-i18n). The table below summarises the mapping between the two APIs.
681
+
682
+ ### Functions
683
+
684
+ | svelte-i18n | Sveltia I18n | Notes |
685
+ | --- | --- | --- |
686
+ | `$_()` / `$t()` / `$format()` | `_()` / `t()` / `format()` | Same two signatures: `(id, opts?)` and `({ id, values?, locale?, default? })`. Not a Svelte store; call directly. |
687
+ | `$json()` | `json()` | Identical behaviour. |
688
+ | `$date()` | `date()` | Identical signature and named formats (`short`, `medium`, `long`, `full`). |
689
+ | `$time()` | `time()` | Identical signature and named formats. |
690
+ | `$number()` | `number()` | Identical signature and named formats (`currency`, `percent`, `scientific`, `engineering`, `compactLong`, `compactShort`). |
691
+ | `$locale` | `locale` / `locale.current` | Reactive object instead of a Svelte store. Use `locale.current` to read and `locale.set(value)` to write. |
692
+ | `$isLoading` | `isLoading()` | Function instead of a store. |
693
+ | N/A | `isRTL()` | Returns `true` when the current locale is RTL. No svelte-i18n equivalent. |
694
+ | `$locales` | `locales` | Reactive array instead of a store. |
695
+ | `$dictionary` | `dictionary` | Reactive object instead of a store. |
696
+ | `init()` | `init()` | Identical option names. `initialLocale` and `formats` are supported. |
697
+ | `addMessages()` | `addMessages()` | Variadic (`...maps`) signature supported. |
698
+ | `register()` | `register()` | Identical. |
699
+ | `waitLocale()` | `waitLocale()` | Identical. |
700
+ | `getLocaleFromNavigator()` | `getLocaleFromNavigator()` | Identical. |
701
+ | `getLocaleFromHostname()` | `getLocaleFromHostname()` | Identical. |
702
+ | `getLocaleFromPathname()` | `getLocaleFromPathname()` | Identical. |
703
+ | `getLocaleFromQueryString()` | `getLocaleFromQueryString()` | Identical. |
704
+ | `getLocaleFromHash()` | `getLocaleFromHash()` | Identical. |
705
+
706
+ ### Key differences
707
+
708
+ - **Message format**: svelte-i18n uses its own `{variable}` interpolation syntax (with optional ICU-style pluralization via `intl-messageformat`). Sveltia I18n uses [Unicode MessageFormat 2 (MF2)](https://messageformat.unicode.org/) syntax exclusively, which is not backwards-compatible. Locale files need to be migrated.
709
+ - **Reactivity model**: svelte-i18n exposes Svelte stores. Sveltia I18n uses Svelte 5 Runes (`$state`). Wrap in a reactive context (e.g. `$derived`) or call directly in templates — no `$`-prefix auto-subscription needed.