@intlayer/core
Version:
Includes core Intlayer functions like translation, dictionary, and utility functions shared across multiple packages.
87 lines (85 loc) • 2.19 kB
JavaScript
import { deepTransformNode } from "../interpreter/getContent/deepTransform.mjs";
import { t as translation } from "../transpiler/translation/translation.mjs";
//#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 = 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) => translation({ [locale]: node })
}]
});
const { locale: _omitLocale, ...rest } = dictionary;
return {
...rest,
content: transformedContent
};
};
//#endregion
export { getMultilingualDictionary };
//# sourceMappingURL=getMultilingualDictionary.mjs.map