UNPKG

@intlayer/core

Version:

Includes core Intlayer functions like translation, dictionary, and utility functions shared across multiple packages.

87 lines (85 loc) 2.34 kB
const require_interpreter_getContent_deepTransform = require('../interpreter/getContent/deepTransform.cjs'); const require_transpiler_translation_translation = require('../transpiler/translation/translation.cjs'); //#region src/deepTransformPlugins/getMultilingualDictionary.ts /** * Transform a per-locale dictionary into a multilingual dictionary. * * Example: * ```json * { * "key": "about-page", * "locale": "en", * "content": { * "myContent": "English content" * } * } * ``` * * ```json * { * "key": "about-page", * "content": { * "myContent": t({ * "en": "English content", * }) * } * } * ``` */ const getMultilingualDictionary = (dictionary) => { if (!dictionary.locale) return dictionary; const locale = dictionary.locale; const transformedContent = require_interpreter_getContent_deepTransform.deepTransformNode(JSON.parse(JSON.stringify(dictionary.content)), { dictionaryKey: dictionary.key, keyPath: [], plugins: [{ id: "traverse-typed-node-plugin", canHandle: (node) => typeof node === "object" && typeof node?.nodeType === "string", transform: (node, props, transformFn) => { const nodeType = node.nodeType; const inner = structuredClone(node[nodeType]); if (typeof inner !== "object" || inner === null) { const transformed = transformFn(inner, { ...props, children: inner, keyPath: [...props.keyPath, { type: nodeType, key: nodeType }] }); return { ...node, [nodeType]: transformed }; } for (const key in inner) { const childProps = { ...props, children: inner[key], keyPath: [...props.keyPath, { type: nodeType, key }] }; inner[key] = transformFn(inner[key], childProps); } return { ...node, [nodeType]: inner }; } }, { id: "wrap-primitive-in-translation", canHandle: (node) => typeof node === "string" || typeof node === "number" || typeof node === "boolean", transform: (node) => require_transpiler_translation_translation.t({ [locale]: node }) }] }); const { locale: _omitLocale,...rest } = dictionary; return { ...rest, content: transformedContent }; }; //#endregion exports.getMultilingualDictionary = getMultilingualDictionary; //# sourceMappingURL=getMultilingualDictionary.cjs.map