@intlayer/core
Version:
Includes core Intlayer functions like translation, dictionary, and utility functions shared across multiple packages.
60 lines (58 loc) • 2.21 kB
JavaScript
import { DURATION_DELAY_TRIGGER } from "./constants.mjs";
//#region src/markdown/renderer.ts
/**
* Creates a renderer for AST nodes.
* Renamed from `reactFor` to be framework-agnostic.
*
* @param render - The render function to call for each node
* @returns A function that renders AST to output
*/
const renderFor = (render) => (ast, state = {}) => {
const start = performance.now();
const patchedRender = (ast, state = {}) => renderFor(render)(ast, state);
if (Array.isArray(ast)) {
const oldKey = state.key;
const result = [];
let lastWasString = false;
let renderedIndex = 0;
for (let i = 0; i < ast.length; i++) {
const nodeOut = patchedRender(ast[i], {
...state,
key: renderedIndex
});
const isString = typeof nodeOut === "string";
if (isString && lastWasString) result[result.length - 1] = result[result.length - 1] + nodeOut;
else if (nodeOut !== null) {
result.push(nodeOut);
renderedIndex++;
}
lastWasString = isString;
}
state.key = oldKey;
const duration = performance.now() - start;
if (duration > 20) console.log(`renderFor (array): ${duration.toFixed(3)}ms, ast length: ${ast.length}`);
return result;
}
const result = render(ast, patchedRender, state);
const duration = performance.now() - start;
if (duration > 20) console.log(`renderFor (single): ${duration.toFixed(3)}ms, ast type: ${ast.type}`);
return result;
};
/**
* Creates a renderer from rules with optional custom render hook.
*
* @param rules - The rules object containing _render functions
* @param userRender - Optional custom render hook for full control
* @returns A render function for AST nodes
*/
const createRenderer = (rules, userRender) => (ast, render, state) => {
const start = performance.now();
const renderer = rules[ast.type]?._render;
const result = userRender ? userRender(() => renderer?.(ast, render, state), ast, render, state) : renderer?.(ast, render, state);
const duration = performance.now() - start;
if (duration > 20) console.log(`createRenderer: ${duration.toFixed(3)}ms, ast type: ${ast.type}, hasUserRender: ${!!userRender}`);
return result;
};
//#endregion
export { createRenderer, renderFor };
//# sourceMappingURL=renderer.mjs.map