@fluentic/i18n 0.0.0-stage → 0.1.0-beta.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/CHANGELOG.md +10 -0
- package/LICENSE +21 -0
- package/README.md +21 -2
- package/dist/adapter-CWC8rng-.d.ts +178 -0
- package/dist/adapter.d.ts +4 -0
- package/dist/adapter.js +4 -0
- package/dist/analyze-CdXCxQDg.d.ts +14 -0
- package/dist/compact-CJ0OWoIv.d.ts +7 -0
- package/dist/compact-E3zj3Z8d.js +34 -0
- package/dist/compact-E3zj3Z8d.js.map +1 -0
- package/dist/compiled.d.ts +27 -0
- package/dist/compiled.js +51 -0
- package/dist/compiled.js.map +1 -0
- package/dist/compiler-BZtB9WLi.js +365 -0
- package/dist/compiler-BZtB9WLi.js.map +1 -0
- package/dist/compiler.d.ts +35 -0
- package/dist/compiler.js +3 -0
- package/dist/core/index.d.ts +5 -0
- package/dist/core/index.js +4 -0
- package/dist/i18n-CfYNwubL.d.ts +25 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +4 -0
- package/dist/interpreter-Dld8QyOI.js +186 -0
- package/dist/interpreter-Dld8QyOI.js.map +1 -0
- package/dist/manager-BW778X1Y.js +193 -0
- package/dist/manager-BW778X1Y.js.map +1 -0
- package/dist/options-DE7vYj0e.d.ts +7 -0
- package/dist/options-Dxxx0aOz.js +23 -0
- package/dist/options-Dxxx0aOz.js.map +1 -0
- package/dist/plugin/babel.d.ts +11 -0
- package/dist/plugin/babel.js +31 -0
- package/dist/plugin/babel.js.map +1 -0
- package/dist/plugin/esbuild.d.ts +7 -0
- package/dist/plugin/esbuild.js +37 -0
- package/dist/plugin/esbuild.js.map +1 -0
- package/dist/plugin/rollup.d.ts +30 -0
- package/dist/plugin/rollup.js +34 -0
- package/dist/plugin/rollup.js.map +1 -0
- package/dist/plugin/vite.d.ts +31 -0
- package/dist/plugin/vite.js +11 -0
- package/dist/plugin/vite.js.map +1 -0
- package/dist/plugin/webpack-loader.d.ts +3 -0
- package/dist/plugin/webpack-loader.js +21 -0
- package/dist/plugin/webpack-loader.js.map +1 -0
- package/dist/plugin/webpack.d.ts +8 -0
- package/dist/plugin/webpack.js +22 -0
- package/dist/plugin/webpack.js.map +1 -0
- package/dist/react.d.ts +53 -0
- package/dist/react.js +60 -0
- package/dist/react.js.map +1 -0
- package/dist/src-BovRx-mX.js +142 -0
- package/dist/src-BovRx-mX.js.map +1 -0
- package/dist/translation-manager-C79eKu2K.js +213 -0
- package/dist/translation-manager-C79eKu2K.js.map +1 -0
- package/dist/types-BkDsJfVD.js +13 -0
- package/dist/types-BkDsJfVD.js.map +1 -0
- package/dist/types-BuGoCU3P.d.ts +75 -0
- package/dist/types.d.ts +2 -0
- package/dist/types.js +1 -0
- package/dist-cjs/babel.cjs +379 -0
- package/dist-cjs/babel.cjs.map +1 -0
- package/package.json +130 -3
- package/src/adapter.ts +6 -0
- package/src/compiled.ts +116 -0
- package/src/compiler/analyze.ts +182 -0
- package/src/compiler/index.ts +208 -0
- package/src/compiler/message.ts +74 -0
- package/src/core/format.ts +40 -0
- package/src/core/i18n.ts +124 -0
- package/src/core/index.ts +1 -0
- package/src/core/types.ts +121 -0
- package/src/index.ts +9 -0
- package/src/manager.ts +175 -0
- package/src/plugin/babel.ts +34 -0
- package/src/plugin/esbuild.ts +45 -0
- package/src/plugin/options.ts +24 -0
- package/src/plugin/rollup.ts +29 -0
- package/src/plugin/vite.ts +6 -0
- package/src/plugin/webpack-loader.ts +22 -0
- package/src/plugin/webpack.ts +15 -0
- package/src/react.ts +97 -0
- package/src/registry-manager.ts +3 -0
- package/src/shared/compact.ts +51 -0
- package/src/shared/formatting.ts +121 -0
- package/src/shared/interpreter.ts +128 -0
- package/src/shared/runtime.ts +131 -0
- package/src/state-manager.ts +29 -0
- package/src/state.ts +20 -0
- package/src/storage-manager.ts +47 -0
- package/src/translation-manager.ts +82 -0
- package/src/translation.ts +106 -0
- package/src/types.ts +2 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import remapping from '@jridgewell/remapping';
|
|
2
|
+
import { transform } from '../compiler';
|
|
3
|
+
import { loadOptions } from './options';
|
|
4
|
+
|
|
5
|
+
export default function loader(this: any, code: string, inputMap: unknown) {
|
|
6
|
+
this.cacheable?.();
|
|
7
|
+
const options = loadOptions(this.getOptions?.() ?? {}, this.rootContext);
|
|
8
|
+
|
|
9
|
+
if (options.configFile) this.addDependency(options.configFile);
|
|
10
|
+
if (this.resourcePath.endsWith('.jsonl')) {
|
|
11
|
+
this.callback(null, 'export default ' + JSON.stringify(code));
|
|
12
|
+
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const result = options.compiled ? transform(code, { filename: this.resourcePath, ...options }) : null;
|
|
17
|
+
this.callback(
|
|
18
|
+
null,
|
|
19
|
+
result?.code ?? code,
|
|
20
|
+
result?.map && inputMap ? remapping([result.map as any, inputMap as any], () => null) : result?.map ?? inputMap,
|
|
21
|
+
);
|
|
22
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import type { PluginOptions } from './options';
|
|
3
|
+
|
|
4
|
+
const require = createRequire(import.meta.url);
|
|
5
|
+
export default class FluenticI18nPlugin {
|
|
6
|
+
constructor(private options: PluginOptions = {}) {}
|
|
7
|
+
apply(compiler: any) {
|
|
8
|
+
compiler.options.module.rules.push({
|
|
9
|
+
test: /(?:\.[cm]?[jt]sx?|\.jsonl)$/,
|
|
10
|
+
enforce: 'pre',
|
|
11
|
+
...(this.options.includeDependencies ? {} : { exclude: /node_modules/ }),
|
|
12
|
+
use: [{ loader: require.resolve('@fluentic/i18n/plugin/webpack-loader'), options: this.options }],
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
}
|
package/src/react.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import React, { createContext, useContext, useRef, useSyncExternalStore } from 'react';
|
|
2
|
+
import type { MessageFormatOptions } from './core/types';
|
|
3
|
+
import { createI18nManager, defaultManaged, type I18nSnapshot, type ManagedI18n } from './manager';
|
|
4
|
+
import { defaultRuntime, getRuntime, type PartsRenderer, type Runtime, withRuntime } from './shared/runtime';
|
|
5
|
+
|
|
6
|
+
declare module '@fluentic/i18n/types' {
|
|
7
|
+
interface I18nJsxConfig {
|
|
8
|
+
JSX: React.ReactElement;
|
|
9
|
+
Element: React.ReactElement;
|
|
10
|
+
Value: React.ReactNode;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
const Context = createContext<ManagedI18n | null>(null);
|
|
14
|
+
|
|
15
|
+
function TranslatedMessage({ render }: { render: PartsRenderer; }) {
|
|
16
|
+
const managed = useContext(Context);
|
|
17
|
+
const runtime = managed?.runtime ?? getRuntime();
|
|
18
|
+
useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot);
|
|
19
|
+
|
|
20
|
+
return React.createElement(
|
|
21
|
+
React.Fragment,
|
|
22
|
+
null,
|
|
23
|
+
...render(runtime).map((part, index) =>
|
|
24
|
+
React.createElement(React.Fragment, { key: index }, part as React.ReactNode)
|
|
25
|
+
),
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function installReactAdapter(runtime: Runtime, lineBreak: React.ReactNode = React.createElement('br')): void {
|
|
30
|
+
runtime.jsxLineBreak = lineBreak;
|
|
31
|
+
runtime.jsxHandler = (_options: MessageFormatOptions, render: PartsRenderer) =>
|
|
32
|
+
React.createElement(TranslatedMessage, { render });
|
|
33
|
+
runtime.tagElement = (element) => {
|
|
34
|
+
if (!React.isValidElement(element)) throw new TypeError('[i18n] t.tag expects a handler or React element');
|
|
35
|
+
|
|
36
|
+
return (chunks) => React.cloneElement(element, undefined, ...chunks as React.ReactNode[]);
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
installReactAdapter(defaultRuntime);
|
|
40
|
+
export const I18nManager = defaultManaged.manager;
|
|
41
|
+
export const I18nState = {
|
|
42
|
+
get: defaultManaged.state.get,
|
|
43
|
+
subscribe: defaultManaged.state.subscribe,
|
|
44
|
+
use() {
|
|
45
|
+
const managed = useContext(Context) ?? defaultManaged;
|
|
46
|
+
|
|
47
|
+
return useSyncExternalStore(managed.state.subscribe, managed.state.get, managed.state.get);
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export function I18nProvider(
|
|
52
|
+
{ children, snapshot, instance, lineBreak }: {
|
|
53
|
+
children?: React.ReactNode;
|
|
54
|
+
snapshot?: I18nSnapshot;
|
|
55
|
+
instance?: ManagedI18n;
|
|
56
|
+
lineBreak?: React.ReactNode;
|
|
57
|
+
},
|
|
58
|
+
) {
|
|
59
|
+
const ref = useRef<
|
|
60
|
+
{ managed: ManagedI18n; snapshot?: I18nSnapshot; instance?: ManagedI18n; lineBreak?: React.ReactNode; } | null
|
|
61
|
+
>(null);
|
|
62
|
+
|
|
63
|
+
if (
|
|
64
|
+
!ref.current || ref.current.snapshot !== snapshot || ref.current.instance !== instance ||
|
|
65
|
+
ref.current.lineBreak !== lineBreak
|
|
66
|
+
) {
|
|
67
|
+
if (snapshot && instance) throw new Error('[i18n] pass either snapshot or instance, not both');
|
|
68
|
+
|
|
69
|
+
const managed = instance ?? createI18nManager();
|
|
70
|
+
installReactAdapter(managed.runtime, lineBreak);
|
|
71
|
+
if (snapshot) managed.manager.hydrate(snapshot);
|
|
72
|
+
ref.current = { managed, snapshot, instance, lineBreak };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const managed = ref.current.managed;
|
|
76
|
+
const state = useSyncExternalStore(managed.state.subscribe, managed.state.get, managed.state.get);
|
|
77
|
+
|
|
78
|
+
if (!state.ready) throw new Error('[i18n] initialize the provider instance or pass a ready snapshot');
|
|
79
|
+
|
|
80
|
+
return React.createElement(Context.Provider, { value: managed }, children);
|
|
81
|
+
}
|
|
82
|
+
/** Explicit binding for text attributes in isolated providers and SSR. */
|
|
83
|
+
export function useI18nRuntime(): Runtime {
|
|
84
|
+
const managed = useContext(Context) ?? defaultManaged;
|
|
85
|
+
useSyncExternalStore(managed.state.subscribe, managed.state.get, managed.state.get);
|
|
86
|
+
|
|
87
|
+
return managed.runtime;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export { createI18nManager, defineTranslationLoader } from './manager';
|
|
91
|
+
export type { I18nSnapshot, I18nStorage, ManagedI18n, StateData } from './manager';
|
|
92
|
+
/** Bind an existing universal renderer to this provider (including client SSR). */
|
|
93
|
+
export function useI18nRenderer<F extends (...args: any[]) => any>(renderer: F): F {
|
|
94
|
+
const runtime = useI18nRuntime();
|
|
95
|
+
|
|
96
|
+
return ((...args: Parameters<F>) => withRuntime(runtime, () => renderer(...args))) as F;
|
|
97
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** Compact message format v1. Strings are literal messages or literal parts. */
|
|
2
|
+
export type CompactMessage = string | CompactPart[];
|
|
3
|
+
|
|
4
|
+
export type CompactPart =
|
|
5
|
+
| string
|
|
6
|
+
| [0, string]
|
|
7
|
+
| [1, string, string | Record<string, unknown> | null]
|
|
8
|
+
| [2 | 3, string, string | Record<string, unknown> | null]
|
|
9
|
+
| [4, string, Record<string, CompactMessage>]
|
|
10
|
+
| [5, string, number, 0 | 1, Record<string, CompactMessage>]
|
|
11
|
+
| [6]
|
|
12
|
+
| [7, string, CompactMessage];
|
|
13
|
+
|
|
14
|
+
export const COMPACT_VERSION = 1;
|
|
15
|
+
|
|
16
|
+
export function validateCompact(value: unknown, depth = 0): asserts value is CompactMessage {
|
|
17
|
+
if (depth > 100) throw new TypeError('[i18n] compact message nesting exceeds 100');
|
|
18
|
+
if (typeof value === 'string') return;
|
|
19
|
+
if (!Array.isArray(value)) throw new TypeError('[i18n] invalid compact message');
|
|
20
|
+
|
|
21
|
+
for (const part of value) {
|
|
22
|
+
if (typeof part === 'string') continue;
|
|
23
|
+
if (!Array.isArray(part)) throw new TypeError('[i18n] invalid compact instruction');
|
|
24
|
+
|
|
25
|
+
const [op, name] = part;
|
|
26
|
+
const lengths: Record<number, number> = { 0: 2, 1: 3, 2: 3, 3: 3, 4: 3, 5: 5, 6: 1, 7: 3 };
|
|
27
|
+
|
|
28
|
+
if (
|
|
29
|
+
!Object.prototype.hasOwnProperty.call(lengths, op) || part.length !== lengths[op] ||
|
|
30
|
+
(op !== 6 && typeof name !== 'string')
|
|
31
|
+
) throw new TypeError('[i18n] invalid compact opcode');
|
|
32
|
+
if (
|
|
33
|
+
op >= 1 && op <= 3 && part[2] !== null && typeof part[2] !== 'string' &&
|
|
34
|
+
(typeof part[2] !== 'object' || Array.isArray(part[2]))
|
|
35
|
+
) throw new TypeError('[i18n] invalid compact format');
|
|
36
|
+
if (op === 5 && (typeof part[2] !== 'number' || !Number.isFinite(part[2]) || ![0, 1].includes(part[3]))) {
|
|
37
|
+
throw new TypeError('[i18n] invalid compact plural');
|
|
38
|
+
}
|
|
39
|
+
if (op === 4 || op === 5) {
|
|
40
|
+
const branches = part[op === 4 ? 2 : 4];
|
|
41
|
+
|
|
42
|
+
if (
|
|
43
|
+
!branches || typeof branches !== 'object' || Array.isArray(branches) ||
|
|
44
|
+
!Object.prototype.hasOwnProperty.call(branches, 'other')
|
|
45
|
+
) throw new TypeError('[i18n] missing other branch');
|
|
46
|
+
|
|
47
|
+
for (const child of Object.values(branches)) validateCompact(child, depth + 1);
|
|
48
|
+
}
|
|
49
|
+
if (op === 7) validateCompact(part[2], depth + 1);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { isMessageDescriptor, isMessageSchemaValue, isMessageTagHandler } from '../core/types';
|
|
2
|
+
import type { MessageFormatOptions, MessageParam } from '../core/types';
|
|
3
|
+
import type { CompactMessage } from './compact';
|
|
4
|
+
import { type Formats, getFormats, getRuntime, type Runtime } from './runtime';
|
|
5
|
+
|
|
6
|
+
export type Engine = (
|
|
7
|
+
message: CompactMessage,
|
|
8
|
+
languageId: string,
|
|
9
|
+
formats: Partial<Formats>,
|
|
10
|
+
values: Record<string, unknown>,
|
|
11
|
+
compiled: boolean,
|
|
12
|
+
) => unknown[];
|
|
13
|
+
|
|
14
|
+
export type Formatting = ReturnType<typeof createFormatting>;
|
|
15
|
+
|
|
16
|
+
export function createFormatting(
|
|
17
|
+
engine: Engine,
|
|
18
|
+
compiled = false,
|
|
19
|
+
getCompiledId?: (context: string | null, message: string) => string,
|
|
20
|
+
) {
|
|
21
|
+
const getMessageParts = (options: MessageFormatOptions, runtime = getRuntime(), jsx = false): unknown[] => {
|
|
22
|
+
if (!runtime.ready) throw new Error('[i18n] runtime is not ready; await adapter initialization before rendering');
|
|
23
|
+
|
|
24
|
+
const languageId = options.languageId ?? runtime.languageId;
|
|
25
|
+
|
|
26
|
+
const descriptor = isMessageDescriptor(options.msg)
|
|
27
|
+
? options.msg
|
|
28
|
+
: { text: options.msg, context: null, schema: {}, compiled: undefined };
|
|
29
|
+
|
|
30
|
+
if (compiled && !descriptor.compiled) {
|
|
31
|
+
throw new TypeError('[i18n] compiled runtime requires compiled messages; enable the Fluentic plugin');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const key = descriptor.compiled?.[0] ?? descriptor.text;
|
|
35
|
+
|
|
36
|
+
const translated = runtime.translationsEnabled
|
|
37
|
+
? runtime.translationGetter?.({
|
|
38
|
+
languageId,
|
|
39
|
+
context: descriptor.compiled ? null : descriptor.context,
|
|
40
|
+
message: key,
|
|
41
|
+
getCompiledId: getCompiledId && !descriptor.compiled
|
|
42
|
+
? () => getCompiledId(descriptor.context, descriptor.text)
|
|
43
|
+
: undefined,
|
|
44
|
+
})
|
|
45
|
+
: null;
|
|
46
|
+
const compiledTranslation = typeof translated === 'object' && translated !== null && !Array.isArray(translated);
|
|
47
|
+
if (compiled && typeof translated === 'string') {
|
|
48
|
+
throw new TypeError('[i18n] compiled runtime requires compiled translations');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const message = compiledTranslation
|
|
52
|
+
? translated.compiled
|
|
53
|
+
: translated ?? descriptor.compiled?.[1] ?? descriptor.text;
|
|
54
|
+
const isCompiled = compiled || compiledTranslation || Array.isArray(message);
|
|
55
|
+
const values: Record<string, unknown> = {};
|
|
56
|
+
|
|
57
|
+
const resolve = (value: MessageParam): unknown => {
|
|
58
|
+
if (isMessageTagHandler(value)) return value;
|
|
59
|
+
if (isMessageSchemaValue(value)) {
|
|
60
|
+
throw new Error('[i18n] Message parameter schemas are only valid in t.msg(); pass a real value');
|
|
61
|
+
}
|
|
62
|
+
if (typeof value === 'function') return resolve(value({ languageId }) as MessageParam);
|
|
63
|
+
if (isMessageDescriptor(value)) return getText({ msg: value, languageId }, runtime);
|
|
64
|
+
|
|
65
|
+
return value;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
for (const [key, value] of Object.entries(options.params ?? {})) values[key] = resolve(value);
|
|
69
|
+
values.break = jsx ? runtime.jsxLineBreak : '\n';
|
|
70
|
+
|
|
71
|
+
for (const [key, expected] of Object.entries(descriptor.schema)) {
|
|
72
|
+
if (key !== 'break' && (!options.params || options.params[key] === undefined)) {
|
|
73
|
+
throw new Error('[i18n] Missing required message parameter: ' + key);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const value = values[key];
|
|
77
|
+
|
|
78
|
+
const valid = expected === String
|
|
79
|
+
? typeof value === 'string'
|
|
80
|
+
: expected === Number
|
|
81
|
+
? typeof value === 'number'
|
|
82
|
+
: expected === Boolean
|
|
83
|
+
? typeof value === 'boolean'
|
|
84
|
+
: expected === Date
|
|
85
|
+
? value instanceof Date && !Number.isNaN(value.getTime())
|
|
86
|
+
: true;
|
|
87
|
+
|
|
88
|
+
if (!valid) {
|
|
89
|
+
throw new Error('[i18n] Message parameter "' + key + '" must be a ' + (expected as { name: string; }).name);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return engine(message, languageId, getFormats(runtime, languageId), values, isCompiled);
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const getText = (options: MessageFormatOptions, runtime = getRuntime()): string => {
|
|
97
|
+
const parts = getMessageParts(options, runtime);
|
|
98
|
+
|
|
99
|
+
if (parts.some((part) => typeof part !== 'string')) {
|
|
100
|
+
throw new Error('[i18n] t.text() received a non-text rich value; use t.jsx() instead');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return parts.join('');
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const getJsx = (options: MessageFormatOptions): unknown => {
|
|
107
|
+
const runtime = getRuntime();
|
|
108
|
+
|
|
109
|
+
if (!runtime.jsxHandler) throw new Error('[i18n] JSX renderer is not configured; initialize a platform adapter');
|
|
110
|
+
// Capture notranslate at element creation, not at React's later render.
|
|
111
|
+
const enabled = runtime.translationsEnabled;
|
|
112
|
+
|
|
113
|
+
return runtime.jsxHandler(
|
|
114
|
+
options,
|
|
115
|
+
(current = getRuntime()) =>
|
|
116
|
+
getMessageParts(options, enabled ? current : { ...current, translationsEnabled: false }, true),
|
|
117
|
+
);
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
return { getText, getJsx, getMessageParts, formatMessage: getText };
|
|
121
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type { CompactMessage } from './compact';
|
|
2
|
+
import type { Engine } from './formatting';
|
|
3
|
+
|
|
4
|
+
const numberCache = new Map<string, Intl.NumberFormat>();
|
|
5
|
+
const dateCache = new Map<string, Intl.DateTimeFormat>();
|
|
6
|
+
const pluralCache = new Map<string, Intl.PluralRules>();
|
|
7
|
+
|
|
8
|
+
function cached<T>(map: Map<string, T>, key: string, create: () => T): T {
|
|
9
|
+
let value = map.get(key);
|
|
10
|
+
|
|
11
|
+
if (!value) {
|
|
12
|
+
value = create();
|
|
13
|
+
if (map.size >= 100) map.delete(map.keys().next().value!);
|
|
14
|
+
map.set(key, value);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const numberDefaults = {
|
|
21
|
+
integer: { maximumFractionDigits: 0 },
|
|
22
|
+
currency: { style: 'currency' },
|
|
23
|
+
percent: { style: 'percent' },
|
|
24
|
+
};
|
|
25
|
+
const dateDefaults = {
|
|
26
|
+
short: { month: 'numeric', day: 'numeric', year: '2-digit' },
|
|
27
|
+
medium: { month: 'short', day: 'numeric', year: 'numeric' },
|
|
28
|
+
long: { month: 'long', day: 'numeric', year: 'numeric' },
|
|
29
|
+
full: { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' },
|
|
30
|
+
};
|
|
31
|
+
const timeDefaults = {
|
|
32
|
+
short: { hour: 'numeric', minute: 'numeric' },
|
|
33
|
+
medium: { hour: 'numeric', minute: 'numeric', second: 'numeric' },
|
|
34
|
+
long: { hour: 'numeric', minute: 'numeric', second: 'numeric', timeZoneName: 'short' },
|
|
35
|
+
full: { hour: 'numeric', minute: 'numeric', second: 'numeric', timeZoneName: 'long' },
|
|
36
|
+
};
|
|
37
|
+
export const interpret: Engine = (message, locale, formats, values) => {
|
|
38
|
+
const number = (value: number, options?: Intl.NumberFormatOptions) =>
|
|
39
|
+
cached(numberCache, JSON.stringify([locale, options]), () => new Intl.NumberFormat(locale, options)).format(value);
|
|
40
|
+
|
|
41
|
+
const render = (message: CompactMessage, pound?: number): unknown[] => {
|
|
42
|
+
if (typeof message === 'string') return [message];
|
|
43
|
+
|
|
44
|
+
const output: unknown[] = [];
|
|
45
|
+
|
|
46
|
+
const append = (value: unknown) => {
|
|
47
|
+
if (Array.isArray(value)) {
|
|
48
|
+
for (const part of value) append(part);
|
|
49
|
+
} else if (typeof value === 'string' && typeof output[output.length - 1] === 'string') {
|
|
50
|
+
output[output.length - 1] += value;
|
|
51
|
+
} else output.push(value);
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
for (const part of message) {
|
|
55
|
+
if (typeof part === 'string') {
|
|
56
|
+
append(part);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const op = part[0];
|
|
61
|
+
|
|
62
|
+
if (op === 6) {
|
|
63
|
+
if (pound !== undefined) append(number(pound));
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const name = part[1];
|
|
68
|
+
|
|
69
|
+
if (!(name in values)) throw new Error('[i18n] Missing required message parameter: ' + name);
|
|
70
|
+
|
|
71
|
+
const value = values[name];
|
|
72
|
+
|
|
73
|
+
if (op === 0) {
|
|
74
|
+
append(typeof value === 'string' || typeof value === 'number' ? String(value) : value || '');
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (op >= 1 && op <= 3) {
|
|
78
|
+
const style = part[2] as string | Record<string, unknown> | null;
|
|
79
|
+
const kind = op === 1 ? 'number' : op === 2 ? 'date' : 'time';
|
|
80
|
+
const defaults = op === 1 ? numberDefaults : op === 2 ? dateDefaults : timeDefaults;
|
|
81
|
+
|
|
82
|
+
const options = (typeof style === 'string'
|
|
83
|
+
? formats[kind]?.[style] ?? (defaults as Record<string, object>)[style]
|
|
84
|
+
: style ?? (op === 3 ? timeDefaults.medium : undefined)) as Record<string, unknown> | undefined;
|
|
85
|
+
|
|
86
|
+
if (op === 1) {
|
|
87
|
+
append(number(Number(value) * (Number(options?.scale ?? 1)), options));
|
|
88
|
+
} else {
|
|
89
|
+
append(
|
|
90
|
+
cached(
|
|
91
|
+
dateCache,
|
|
92
|
+
JSON.stringify([locale, options]),
|
|
93
|
+
() => new Intl.DateTimeFormat(locale, options as Intl.DateTimeFormatOptions),
|
|
94
|
+
).format(value as Date),
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
} else if (op === 4) {
|
|
98
|
+
const branches = part[2];
|
|
99
|
+
append(
|
|
100
|
+
render(
|
|
101
|
+
Object.prototype.hasOwnProperty.call(branches, String(value)) ? branches[String(value)] : branches.other,
|
|
102
|
+
),
|
|
103
|
+
);
|
|
104
|
+
} else if (op === 5) {
|
|
105
|
+
const count = Number(value);
|
|
106
|
+
const adjusted = count - part[2];
|
|
107
|
+
const branches = part[4];
|
|
108
|
+
const exact = '=' + count;
|
|
109
|
+
|
|
110
|
+
const key = Object.prototype.hasOwnProperty.call(branches, exact)
|
|
111
|
+
? exact
|
|
112
|
+
: cached(
|
|
113
|
+
pluralCache,
|
|
114
|
+
locale + ':' + part[3],
|
|
115
|
+
() => new Intl.PluralRules(locale, { type: part[3] ? 'ordinal' : 'cardinal' }),
|
|
116
|
+
).select(adjusted);
|
|
117
|
+
append(render(branches[key] ?? branches.other, adjusted));
|
|
118
|
+
} else if (op === 7) {
|
|
119
|
+
if (typeof value !== 'function') throw new TypeError('[i18n] rich tag ' + name + ' requires a handler');
|
|
120
|
+
append(value(render(part[2], pound)));
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return output;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
return render(message);
|
|
128
|
+
};
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import type { MessageFormatOptions, MessageTagHandler, TranslationGetter } from '../core/types';
|
|
2
|
+
|
|
3
|
+
export type Formats = {
|
|
4
|
+
number: Record<string, Intl.NumberFormatOptions>;
|
|
5
|
+
date: Record<string, Intl.DateTimeFormatOptions>;
|
|
6
|
+
time: Record<string, Intl.DateTimeFormatOptions>;
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
export type FormatContext = { languageId: string; };
|
|
10
|
+
export type FormatFactory<T> = T | ((context: FormatContext) => T);
|
|
11
|
+
export type RegistryConfig = { [K in keyof Formats]: Record<string, FormatFactory<Formats[K][string]>>; };
|
|
12
|
+
export type PartsRenderer = (runtime?: Runtime) => unknown[];
|
|
13
|
+
|
|
14
|
+
export type Runtime = {
|
|
15
|
+
languageId: string;
|
|
16
|
+
ready: boolean;
|
|
17
|
+
translationsEnabled: boolean;
|
|
18
|
+
translationGetter: TranslationGetter | null;
|
|
19
|
+
formats: Partial<Formats>;
|
|
20
|
+
registry: RegistryConfig;
|
|
21
|
+
jsxLineBreak: unknown;
|
|
22
|
+
jsxHandler: ((options: MessageFormatOptions, render: PartsRenderer) => unknown) | null;
|
|
23
|
+
tagElement: ((element: unknown) => (chunks: unknown[]) => unknown) | null;
|
|
24
|
+
subscribe: (listener: () => void) => () => void;
|
|
25
|
+
getSnapshot: () => unknown;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export function createRuntime(): Runtime {
|
|
29
|
+
return {
|
|
30
|
+
languageId: 'en',
|
|
31
|
+
ready: false,
|
|
32
|
+
translationsEnabled: true,
|
|
33
|
+
translationGetter: null,
|
|
34
|
+
formats: {},
|
|
35
|
+
registry: { number: {}, date: {}, time: {} },
|
|
36
|
+
jsxLineBreak: '\n',
|
|
37
|
+
jsxHandler: null,
|
|
38
|
+
tagElement: null,
|
|
39
|
+
subscribe: () => () => {},
|
|
40
|
+
getSnapshot: () => null,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const defaultRuntime = createRuntime();
|
|
45
|
+
let resolver = () => defaultRuntime;
|
|
46
|
+
|
|
47
|
+
export function setRuntimeResolver(next: () => Runtime): void {
|
|
48
|
+
resolver = next;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function getRuntime(): Runtime {
|
|
52
|
+
return resolver();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function setTranslationGetter(getter: TranslationGetter | null): void {
|
|
56
|
+
getRuntime().translationGetter = getter;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function setLanguageId(languageId: string): void {
|
|
60
|
+
getRuntime().languageId = languageId;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function setFormats(formats: Partial<Formats>): void {
|
|
64
|
+
getRuntime().formats = formats;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function setGetJsxHandler(handler: Runtime['jsxHandler']): void {
|
|
68
|
+
getRuntime().jsxHandler = handler;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export const I18nRegistry = {
|
|
72
|
+
addNumberFormat(name: string, format: FormatFactory<Intl.NumberFormatOptions>) {
|
|
73
|
+
getRuntime().registry.number[name] = format;
|
|
74
|
+
},
|
|
75
|
+
addDateFormat(name: string, format: FormatFactory<Intl.DateTimeFormatOptions>) {
|
|
76
|
+
getRuntime().registry.date[name] = format;
|
|
77
|
+
},
|
|
78
|
+
addTimeFormat(name: string, format: FormatFactory<Intl.DateTimeFormatOptions>) {
|
|
79
|
+
getRuntime().registry.time[name] = format;
|
|
80
|
+
},
|
|
81
|
+
setLanguageId,
|
|
82
|
+
getConfig(): RegistryConfig {
|
|
83
|
+
const r = getRuntime().registry;
|
|
84
|
+
|
|
85
|
+
return { number: { ...r.number }, date: { ...r.date }, time: { ...r.time } };
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
export function getFormats(runtime: Runtime, languageId: string): Partial<Formats> {
|
|
90
|
+
const resolve = <T>(entries: Record<string, FormatFactory<T>>) =>
|
|
91
|
+
Object.fromEntries(
|
|
92
|
+
Object.entries(entries).map((
|
|
93
|
+
[key, value],
|
|
94
|
+
) => [key, typeof value === 'function' ? (value as (context: FormatContext) => T)({ languageId }) : value]),
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
number: { ...runtime.formats.number, ...resolve(runtime.registry.number) },
|
|
99
|
+
date: { ...runtime.formats.date, ...resolve(runtime.registry.date) },
|
|
100
|
+
time: { ...runtime.formats.time, ...resolve(runtime.registry.time) },
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function noTranslate<T>(fn: () => T): T {
|
|
105
|
+
const runtime = getRuntime();
|
|
106
|
+
const previous = runtime.translationsEnabled;
|
|
107
|
+
runtime.translationsEnabled = false;
|
|
108
|
+
|
|
109
|
+
try {
|
|
110
|
+
return fn();
|
|
111
|
+
} finally {
|
|
112
|
+
runtime.translationsEnabled = previous;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function createTagHandler<T, R>(handler: (chunks: Array<string | T>) => R): MessageTagHandler<T, R> {
|
|
117
|
+
Object.defineProperty(handler, '__fluenticTagHandler', { value: true });
|
|
118
|
+
|
|
119
|
+
return handler as MessageTagHandler<T, R>;
|
|
120
|
+
}
|
|
121
|
+
/** Synchronous binding only: async callers must keep and use their own instance. */
|
|
122
|
+
export function withRuntime<T>(runtime: Runtime, fn: () => T): T {
|
|
123
|
+
const previous = resolver;
|
|
124
|
+
resolver = () => runtime;
|
|
125
|
+
|
|
126
|
+
try {
|
|
127
|
+
return fn();
|
|
128
|
+
} finally {
|
|
129
|
+
resolver = previous;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export type StateManager<StateData> = {
|
|
2
|
+
get(): StateData;
|
|
3
|
+
subscribe(listener: () => void): () => void;
|
|
4
|
+
set(partial: Partial<StateData>): void;
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
export function createStateManager<StateData extends object>(initial: StateData): StateManager<StateData> {
|
|
8
|
+
let current = initial;
|
|
9
|
+
|
|
10
|
+
const listeners = new Set<() => void>();
|
|
11
|
+
|
|
12
|
+
return {
|
|
13
|
+
get: () => current,
|
|
14
|
+
subscribe: (listener) => {
|
|
15
|
+
listeners.add(listener);
|
|
16
|
+
|
|
17
|
+
return () => listeners.delete(listener);
|
|
18
|
+
},
|
|
19
|
+
set(partial) {
|
|
20
|
+
const next = { ...current, ...partial };
|
|
21
|
+
const changed = Object.keys(next).some((key) => current[key as keyof StateData] !== next[key as keyof StateData]);
|
|
22
|
+
|
|
23
|
+
if (!changed) return;
|
|
24
|
+
current = next;
|
|
25
|
+
|
|
26
|
+
for (const listener of listeners) listener();
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
package/src/state.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { useSyncExternalStore } from 'react';
|
|
2
|
+
import { defaultI18nState, type StateData } from './manager';
|
|
3
|
+
|
|
4
|
+
export type { StateData } from './manager';
|
|
5
|
+
|
|
6
|
+
export const I18nState = {
|
|
7
|
+
get(): StateData {
|
|
8
|
+
return defaultI18nState.get();
|
|
9
|
+
},
|
|
10
|
+
subscribe(listener: () => void): () => void {
|
|
11
|
+
return defaultI18nState.subscribe(listener);
|
|
12
|
+
},
|
|
13
|
+
use(): StateData {
|
|
14
|
+
return useSyncExternalStore(I18nState.subscribe, I18nState.get, I18nState.get);
|
|
15
|
+
},
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export function updateState(next: Partial<StateData>): void {
|
|
19
|
+
defaultI18nState.set(next);
|
|
20
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { LanguageId } from './core/types';
|
|
2
|
+
|
|
3
|
+
export type StoredState = { languageId: LanguageId; };
|
|
4
|
+
|
|
5
|
+
export type I18nStorage = {
|
|
6
|
+
read(): StoredState | null | Promise<StoredState | null>;
|
|
7
|
+
write(state: StoredState): void | Promise<void>;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export function createStorageManager(initial: I18nStorage | null = null) {
|
|
11
|
+
let storage = initial;
|
|
12
|
+
|
|
13
|
+
return {
|
|
14
|
+
setStorage(next: I18nStorage | null): void {
|
|
15
|
+
storage = next;
|
|
16
|
+
},
|
|
17
|
+
getStorage(): I18nStorage {
|
|
18
|
+
if (!storage) throw new Error('[i18n] storage is not configured');
|
|
19
|
+
|
|
20
|
+
return storage;
|
|
21
|
+
},
|
|
22
|
+
hasStorage(): boolean {
|
|
23
|
+
return storage !== null;
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function createLocalStorage(): I18nStorage | null {
|
|
29
|
+
if (typeof globalThis.localStorage === 'undefined') return null;
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
read() {
|
|
33
|
+
const value = globalThis.localStorage.getItem('fluentic:i18n:state');
|
|
34
|
+
|
|
35
|
+
if (!value) return null;
|
|
36
|
+
|
|
37
|
+
try {
|
|
38
|
+
return JSON.parse(value) as StoredState;
|
|
39
|
+
} catch {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
write(state) {
|
|
44
|
+
globalThis.localStorage.setItem('fluentic:i18n:state', JSON.stringify(state));
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|