@cf-wasm/og
Version:
Generate Open Graph Images dynamically from HTML/CSS without a browser.
74 lines (73 loc) • 2.73 kB
JavaScript
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
let _hedgedoc_html_to_react = require("@hedgedoc/html-to-react");
let react = require("react");
//#region src/html-to-react.ts
var Transformer = class {
constructor(options = {}) {
this.options = {
tailwind: false,
...options
};
}
transform(html) {
return this.wrapper((0, _hedgedoc_html_to_react.convertHtmlToReact)(html));
}
wrapper(children) {
if (children.length === 1 && (0, react.isValidElement)(children[0])) return this.element(children[0]);
return this.fragment(children);
}
element(element) {
return (0, react.createElement)(element.type, typeof element.props === "object" && element.props ? this.props(element.props) : {});
}
fragment(children) {
const transformed = this.children(children);
return (0, react.createElement)(react.Fragment, typeof transformed !== "undefined" ? { children: transformed } : {});
}
props(input) {
const props = { ...input };
if ("children" in props) {
const transformed = this.children(props.children);
if (typeof transformed === "undefined") delete props.children;
else props.children = transformed;
}
if (this.options.tailwind === true || this.options.tailwind === "class") {
if ("className" in props && typeof props.className === "string") props.tw = props.className;
} else if (this.options.tailwind === "data") {
if ("data-tw" in props && typeof props["data-tw"] === "string") props.tw = props["data-tw"];
}
return props;
}
children(children) {
if (children === null || typeof children === "undefined" || typeof children === "boolean") return;
if ((0, react.isValidElement)(children)) return this.element(children);
if (Array.isArray(children)) {
const filtered = [];
for (const child of children) {
if (child === null || typeof child === "undefined" || typeof child === "boolean") continue;
if ((0, react.isValidElement)(child)) filtered.push(this.element(child));
else filtered.push(child);
}
if (filtered.length === 0) return;
if (filtered.length === 1) return filtered[0];
return filtered;
}
return children;
}
};
/**
* A helper function to parse html string to a {@link ReactElement} like object
*
* @param html The html string to parse
* @param options Options
*
* @returns The {@link ReactElement}
*/
const htmlToReact = (html, options = {}) => {
if (typeof html !== "string") throw new TypeError("Argument 1 must be of type string");
if (html.trim().length === 0) throw new TypeError("Blank html string cannot be parsed");
return new Transformer(options).transform(html);
};
//#endregion
exports.htmlToReact = htmlToReact;
exports.t = htmlToReact;
//# sourceMappingURL=html-to-react.cjs.map