import { DEV } from "solid-js"; import type { JSX } from "@solidjs/web"; export type BaseRecordDict = { readonly [K: string | number]: unknown }; export type BaseArrayDict = readonly unknown[]; export type BaseDict = BaseRecordDict | BaseArrayDict; const hasOwn = Object.prototype.hasOwnProperty; const isDict = (value: unknown): value is BaseDict => value != null && ((value = Object.getPrototypeOf(value)), value === Array.prototype || value === Object.prototype); const isRecordDict = (value: unknown): value is BaseRecordDict => value != null && Object.getPrototypeOf(value) === Object.prototype; type JoinPath = A extends string | number ? B extends string | number ? `${A}.${B}` : A : B extends string | number ? B : ""; type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; /** * Flatten a nested dictionary into a flat dictionary. * * @example * ```ts * type Dict = { * a: { * foo: string; * b: { bar: number } * } * } * * type FlatDict = Flatten; * * type FlatDict = { * a: { * foo: string; * b: { bar: number } * }, * "a.foo": string; * "a.b": { bar: number} , * "a.b.bar": number; * } * ``` */ export type Flatten = number extends T ? /* catch any */ BaseRecordDict : T extends (infer V)[] ? /* array */ { readonly [K in JoinPath]?: V } & (V extends BaseDict ? Partial>> : {}) : /* record */ UnionToIntersection< { [K in keyof T]: T[K] extends BaseDict ? Flatten> : never }[keyof T] > & { readonly [K in keyof T as JoinPath]: T[K] }; function visitDict(flatDict: Record, dict: BaseDict, path: string): void { for (const [key, value] of Object.entries(dict)) { const keyPath = `${path}.${key}`; flatDict[keyPath] = value; isDict(value) && visitDict(flatDict, value, keyPath); } } /** * Flatten a nested dictionary into a flat dictionary. * * This way each nested property is available as a flat key. * * @example * ```ts * const dict = { * a: { * foo: "foo", * b: { bar: 1 } * } * } * * const flatDict = flatten(dict); * * flatDict === { * a: { * foo: "foo", * b: { bar: 1 } * }, * "a.foo": "foo", * "a.b": { bar: 1 }, * "a.b.bar": 1, * } * ``` */ export function flatten(dict: T): Flatten { const flatDict: Record = { ...dict }; for (const [key, value] of Object.entries(dict)) { isDict(value) && visitDict(flatDict, value, key); } return flatDict as Flatten; } export type Prefixed = { readonly [K in keyof T as `${P}.${K & (string | number)}`]: T[K]; }; /** * Prefix all *(own)* keys in the dictionary with the provided prefix. * * Useful for namespacing a dictionary when combining multiple dictionaries. * * @example * ```ts * const dict = { * hello: "hello", * goodbye: "goodbye", * food: { meat: "meat" }, * } * * const prefixedDict = prefix(dict, "greetings"); * * prefixedDict === { * "greetings.hello": "hello", * "greetings.goodbye": "goodbye", * "greetings.food": { meat: "meat" }, * } * ``` */ export const prefix: ( dict: T, prefix: P, ) => Prefixed = (dict: BaseRecordDict, prefix: string): any => { prefix += "."; const result: Record = {}; for (const [key, value] of Object.entries(dict)) { result[prefix + key] = value; } return result; }; export type BaseTemplateArgs = Record; /** * A string branded with arguments needed to resolve the template. */ export type Template = string & { __template_args: T }; export type TemplateArgs> = T extends Template ? R : never; /** * Identity function that returns the same string branded as {@link Template} with the arguments needed to resolve the template. * * @example * ```ts * const template = i18n.template<{ name: string }>("hello {{ name }}!"); * * // same as * const template = "hello {{ name }}!" as Template<{ name: string }>; * ``` */ export const template = (source: string): Template => source as any; /** * Resolve a {@link Template} with the provided {@link TemplateArgs}. */ export type TemplateResolver = ( template: T, ...args: ResolveArgs ) => O; /** * Simple template resolver that replaces `{{ key }}` with the value of `args.key`. * * @example * ```ts * resolveTemplate("hello {{ name }}!", { name: "John" }); * // => "hello John!" * ``` */ export const resolveTemplate: TemplateResolver = (string: string, args?: BaseTemplateArgs) => { if (args) for (const [key, value] of Object.entries(args)) string = string.replace(new RegExp(`{{\\s*${key}\\s*}}`, "g"), value as string); return string; }; /** * Template resolver that does nothing. It's used as a fallback when no template resolver is provided. */ export const identityResolveTemplate = (v => v) as TemplateResolver; /** * Template resolver that behaves like {@link resolveTemplate}, but also accepts JSX nodes as * argument values, e.g. to splice a link or other component into a translation. * * Returns a plain `string` when every substituted value is a string, exactly matching * {@link resolveTemplate}. Returns a `JSX.Element` as soon as any substituted value isn't a string. * * @example * ```tsx * const dict = { * forMoreInfo: "For more information, {{ clickHere }}", * }; * * const t = i18n.translator(() => dict, i18n.resolveRichTemplate); * * t("forMoreInfo", { clickHere: click here }); // => JSX.Element * t("forMoreInfo", { clickHere: "click here" }); // => "For more information, click here" * ``` */ export const resolveRichTemplate: TemplateResolver = ( string: string, args?: BaseTemplateArgs, ) => { if (!args) return string; const regex = /\{\{\s*(\w+)\s*\}\}/g; const parts: (string | JSX.Element)[] = []; let lastIndex = 0; let isRich = false; let match: RegExpExecArray | null; while ((match = regex.exec(string))) { parts.push(string.slice(lastIndex, match.index)); const value = args[match[1]!]; if (value !== undefined && typeof value !== "string") isRich = true; parts.push(value === undefined ? match[0] : (value as string | JSX.Element)); lastIndex = regex.lastIndex; } parts.push(string.slice(lastIndex)); return isRich ? (parts as JSX.Element) : parts.join(""); }; export type RichTextTags = Record JSX.Element>; const RICH_TEXT_OPEN_TAG_RE = /<(\w+)>/g; const RICH_TEXT_CLOSE_TAG_RE = /<\/(\w+)>/g; /** * Resolves `content` markup in an already-resolved translation string into JSX, by * calling the matching {@link tags} renderer with the tag's inner content. * * Meant to be composed with {@link translator}/{@link resolveTemplate} for `{{ }}` variable * substitution — resolve variables first, then pass the result through `richText` for tags. * Tags don't nest. * * There's no type-safety tying tag names to {@link tags} — a typo in either the dictionary or * the {@link tags} map can't be caught at compile time. To catch it at runtime instead, an * unmapped tag logs a dev-only warning and renders its contents as plain text; this check is * stripped from production builds. * * @example * ```tsx * const dict = { * message: "Please refer to the guidelines", * }; * * const t = i18n.translator(() => dict, i18n.resolveTemplate); * * i18n.richText(t("message"), { * guidelines: text => {text}, * }); * ``` */ export function richText(string: string, tags: RichTextTags): JSX.Element { const parts: JSX.Element[] = []; // Index every closing tag once, grouped by name. Opening tags are visited in increasing order, so // each name's cursor only ever moves forward and the whole pass is linear. A regex like // `<(\w+)>[\s\S]*?`, or an `indexOf` per opening tag, rescans the rest of the string for // every unclosed tag, which is quadratic on input like `…` or `…`. const closers = new Map(); for (const m of string.matchAll(RICH_TEXT_CLOSE_TAG_RE)) { const name = m[1]!; const entry = closers.get(name); if (entry) entry.at.push(m.index!); else closers.set(name, { at: [m.index!], next: 0 }); } const openTag = new RegExp(RICH_TEXT_OPEN_TAG_RE); let last = 0; let match: RegExpExecArray | null; while ((match = openTag.exec(string))) { const tag = match[1]!; const entry = closers.get(tag); if (!entry) continue; // First closer for this tag that starts after the opening tag. const innerStart = match.index + match[0].length; while (entry.next < entry.at.length && entry.at[entry.next]! < innerStart) entry.next++; if (entry.next === entry.at.length) continue; const closeStart = entry.at[entry.next]!; parts.push(string.slice(last, match.index)); const inner = string.slice(innerStart, closeStart); const render = hasOwn.call(tags, tag) ? tags[tag] : undefined; if (render) { parts.push(render(inner)); } else { if (DEV) // oxlint-disable-next-line no-console console.warn( `[@solid-primitives/i18n] richText: no renderer for tag "<${tag}>" was provided, rendering its contents as plain text.`, ); parts.push(inner); } last = closeStart + tag.length + 3; // "" openTag.lastIndex = last; } parts.push(string.slice(last)); return parts; } export type Resolved = T extends (...args: any[]) => infer R ? R : T extends O ? O : T; export type ResolveArgs = T extends (...args: infer A) => any ? A : T extends Template ? [args: R] : T extends O ? [args?: BaseTemplateArgs] : []; export type Resolver = (...args: ResolveArgs) => Resolved; export type NullableResolver = (...args: ResolveArgs) => Resolved | undefined; export type Translator = ( path: K, ...args: ResolveArgs ) => Resolved; export type NullableTranslator = ( path: K, ...args: ResolveArgs ) => Resolved | undefined; /** * Called when a lookup finds the dictionary itself but not the requested {@link path} within it — * i.e. a genuinely missing translation, as opposed to the dictionary not being loaded yet. * Its return value is used as the translation result. * * Receives the same arguments that were passed to the translator after the path, so a handler can * resolve the path itself as a template — e.g. when using source text as keys, see {@link missingKeyAsTemplate}. */ export type MissingKeyHandler = (path: string, ...args: any[]) => O | undefined; /** * A {@link MissingKeyHandler} that returns the requested path itself, e.g. `"food.meat"`, * making missing translations visible in the UI instead of silently rendering blank. * * @example * ```ts * const t = i18n.translator(() => flatDict, i18n.resolveTemplate, i18n.missingKeyAsPath); * ``` */ export const missingKeyAsPath: MissingKeyHandler = path => path; /** * Creates a {@link MissingKeyHandler} that resolves the requested path itself as a template with * the arguments passed to the translator. * * Useful when the source-language text is used as the key (`t("Hello {{ name }}!", { name })`): * the source text doubles as the fallback, so the source language needs no dictionary entries, * and other languages' dictionaries are keyed by that same text. * * @param resolveTemplate The template resolver to apply to the path. Usually the same one passed to {@link translator}. * * @example * ```ts * const de = { "Hello {{ name }}!": "Hallo {{ name }}!" }; * * const t = i18n.translator( * (): Record => (locale() === "de" ? de : {}), * i18n.resolveTemplate, * i18n.missingKeyAsTemplate(i18n.resolveTemplate), * ); * * t("Hello {{ name }}!", { name: "John" }); // => "Hello John!" (en), "Hallo John!" (de) * ``` */ export const missingKeyAsTemplate = (resolveTemplate: TemplateResolver): MissingKeyHandler => (path, args?: BaseTemplateArgs) => (resolveTemplate as (template: string, args?: BaseTemplateArgs) => O)(path, args); /** * Create a translator function that will resolve the path in the dictionary and return the value. * * If the value is a function it will call it with the provided arguments. * * If the value is a string it will resolve the template using {@link resolveTemplate} with the provided arguments. * * If the dictionary exists but has no value at {@link path}, {@link onMissingKey} is called (if provided) * and its result is returned. By default (no {@link onMissingKey}), a missing key resolves to `undefined`, * same as when the dictionary itself isn't available yet. * Only the dictionary's own keys are looked up — inherited names like `"toString"` count as missing. * * Otherwise it will return the value as is. * * @param dict A function that returns the dictionary to use for translation. Will be called on each translation. * @param resolveTemplate A function that will resolve the template. Defaults to {@link identityResolveTemplate}. * @param onMissingKey Called with the requested path (and the translator's arguments) when the dictionary exists but has no value there. * Use {@link missingKeyAsPath} to fall back to the path itself, or provide a custom handler, * e.g. to log/report missing translations. * * @example * ```ts * const dict = { * hello: "hello {{ name }}!", * goodbye: (name: string) => `goodbye ${name}!`, * food: { * meat: "meat", * } * } * const flatDict = i18n.flatten(dict); * * const t = i18n.translator(() => flatDict, i18n.resolveTemplate); * * t("hello", { name: "John" }) // => "hello John!" * t("goodbye", "John") // => "goodbye John!" * t("food.meat") // => "meat" * ``` */ export function translator( dict: () => T, resolveTemplate?: TemplateResolver, onMissingKey?: MissingKeyHandler, ): Translator; export function translator( dict: () => T | undefined, resolveTemplate?: TemplateResolver, onMissingKey?: MissingKeyHandler, ): NullableTranslator; export function translator( dict: () => T | undefined, resolveTemplate: TemplateResolver = identityResolveTemplate, onMissingKey?: MissingKeyHandler, ): any { return (path: string, ...args: any[]) => { if (path[0] === ".") path = path.slice(1); const currentDict = dict(); // Only own keys count: inherited names like "toString" or "constructor" are treated as // missing, since keys (especially source-text keys) can be arbitrary strings. const value = currentDict != null && hasOwn.call(currentDict, path) ? currentDict[path] : undefined; switch (typeof value) { case "function": return value(...args); case "string": return resolveTemplate(value, args[0]); case "undefined": return currentDict !== undefined && onMissingKey ? onMissingKey(path, ...args) : value; default: return value; } }; } export type Scopes = { [K in T]: K extends `${infer S}.${infer R}` ? S | `${S}.${Scopes}` : never; }[T]; export type Scoped> = { readonly [K in keyof T as K extends `${S}.${infer R}` ? R : never]: T[K]; }; /** * Scopes the provided {@link Translator} to the given {@link scope}. * * @example * ```ts * const dict = { * greetings: { * hello: "hello {{ name }}!", * hi: "hi {{ name }}!", * }, * goodbye: (name: string) => `goodbye ${name}!`, * } * const flatDict = i18n.flatten(dict); * * const t = i18n.translator(() => flatDict, i18n.resolveTemplate); * * const greetings = i18n.scopedTranslator(t, "greetings"); * * greetings("hello", { name: "John" }) // => "hello John!" * greetings("hi", { name: "John" }) // => "hi John!" * greetings("goodbye", "John") // => undefined * ``` */ export function scopedTranslator>( translator: Translator, scope: S, ): Translator, O>; export function scopedTranslator>( translator: NullableTranslator, scope: S, ): NullableTranslator, O>; export function scopedTranslator( translator: Translator, scope: string, ): Translator, O> { return (path, ...args) => translator(`${scope}.${path}`, ...args); } export type ChainedTranslator = { readonly [K in keyof T]: T[K] extends BaseRecordDict ? ChainedTranslator : Resolver; }; export type NullableChainedTranslator = { readonly [K in keyof T]: T[K] extends BaseRecordDict ? NullableChainedTranslator : NullableResolver; }; /** * Create an object-chained translator that will resolve the path in the dictionary and return the value. * * @param initDict The initial dictionary used for getting the structure of nested objects. * @param translate {@link Translator} function that will resolve the path in the dictionary and return the value. * * @example * ```ts * const dict = { * greetings: { * hello: "hello {{ name }}!", * hi: "hi!", * }, * goodbye: (name: string) => `goodbye ${name}!`, * } * const flatDict = i18n.flatten(dict); * * const t = i18n.translator(() => flatDict, i18n.resolveTemplate); * * const chained = i18n.chainedTranslator(dict, t); * * chained.greetings.hello({ name: "John" }) // => "hello John!" * chained.greetings.hi() // => "hi!" * chained.goodbye("John") // => "goodbye John!" * ``` */ export function chainedTranslator( initDict: T, translate: Translator, path?: string, ): ChainedTranslator; export function chainedTranslator( initDict: T, translate: NullableTranslator, path?: string, ): NullableChainedTranslator; export function chainedTranslator( initDict: T, translate: Translator, path: string = "", ): any { const result: any = { ...initDict }; for (const [key, value] of Object.entries(initDict)) { const keyPath = `${path}.${key}`; result[key] = isRecordDict(value) ? chainedTranslator(value, translate, keyPath) : (...args: any[]) => translate( keyPath, // @ts-expect-error ...args, ); } return result; } /** * Create an object-chained translator *(implemented using a Proxy)* that will resolve the path in the dictionary and return the value. * * @param translate {@link Translator} function that will resolve the path in the dictionary and return the value. * * @example * ```ts * const dict = { * greetings: { * hello: "hello {{ name }}!", * hi: "hi!", * }, * goodbye: (name: string) => `goodbye ${name}!`, * } * const flatDict = i18n.flatten(dict); * * const t = i18n.translator(() => flatDict, i18n.resolveTemplate); * * const proxy = i18n.proxyTranslator(t); * * proxy.greetings.hello({ name: "John" }) // => "hello John!" * proxy.greetings.hi() // => "hi!" * proxy.goodbye("John") // => "goodbye John!" * ``` */ export function proxyTranslator( translate: Translator, path?: string, ): ChainedTranslator; export function proxyTranslator( translate: NullableTranslator, path?: string, ): NullableChainedTranslator; export function proxyTranslator( translate: Translator, path: string = "", ): any { return new Proxy(translate.bind(void 0, path), new Traps(translate, path)); } class Traps { constructor( private readonly translate: Translator, private readonly path: string, ) {} get(target: any, prop: PropertyKey): any { if (typeof prop !== "string") return Reflect.get(target, prop); return (proxyTranslator as any)(this.translate, `${this.path}.${prop}`); } has(target: any, prop: PropertyKey): boolean { if (typeof prop !== "string") return Reflect.has(target, prop); return (proxyTranslator as any)(this.translate, `${this.path}.${prop}`) !== undefined; } getOwnPropertyDescriptor(target: any, prop: PropertyKey): PropertyDescriptor | undefined { if (typeof prop !== "string") return Reflect.getOwnPropertyDescriptor(target, prop); return { enumerable: true, get: () => (proxyTranslator as any)(this.translate, `${this.path}.${prop}`), }; } }