UNPKG

@sv443-network/coreutils

Version:

Cross-platform, general-purpose, JavaScript core library for Node, Deno and the browser. Intended to be used in conjunction with `@sv443-network/userutils` and `@sv443-network/djsutils`, but can be used independently as well.

66 lines (65 loc) 2.76 kB
/** * @module Translate * This module contains a sophisticated but still lightweight, JSON-based translation system - [see the documentation for more info](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#class-translate) */ import type { Stringifiable } from "./types.js"; /** * Translation object to pass to {@linkcode tr.addTranslations()} * Can be a flat object of identifier keys and the translation text as the value, or an infinitely nestable object containing the same. * * @example * // Flat object: * const tr_en: TrObject = { * hello: "Hello, %1!", * foo: "Foo", * }; * * // Nested object: * const tr_de: TrObject = { * hello: "Hallo, %1!", * foo: { * bar: "Foo bar", * }, * }; */ export interface TrObject { [key: string]: string | TrObject; } /** Properties for the transform function that transforms a matched translation string into something else */ export type TransformFnProps<TTrKey extends string = string> = { /** The currently set language - empty string if not set yet */ language: string; /** The matches as returned by `RegExp.exec()` */ matches: RegExpExecArray[]; /** The translation key */ trKey: TTrKey; /** Translation value before any transformations */ trValue: string; /** Current value, possibly in-between transformations */ currentValue: string; /** Arguments passed to the translation function */ trArgs: (Stringifiable | Record<string, Stringifiable>)[]; }; /** Function that transforms a matched translation string into another string */ export type TransformFn<TTrKey extends string = string> = (props: TransformFnProps<TTrKey>) => Stringifiable; /** * Pass a nested or flat translation object to this generic type to recursively get all keys in the object. * @example ```ts * type Keys = TrKeys<{ a: { b: { c: "bar" }, d: "foo" }, e: "baz" }>; * // ^? type Keys = "a.b.c" | "a.d" | "e" * ``` */ export type TrKeys<TTrObj, P extends string = ""> = { [K in keyof TTrObj]: K extends string | number | boolean | null | undefined ? TTrObj[K] extends object ? TrKeys<TTrObj[K], `${P}${K}.`> : `${P}${K}` : never; }[keyof TTrObj]; /** Options for the {@linkcode Translate} class */ export type TranslateOptions = {}; /** * Class that manages translations, provides many utility functions, handles fallbacks and allows you to specify custom transforms to insert values or modify the translation string in pretty much any way imaginable. */ export declare class Translate { readonly options: TranslateOptions; /** All translations loaded into memory */ protected translations: Record<string, TrObject>; constructor(options: TranslateOptions); }