rehype-custom-component
Version:
Rehype plugin to transform custom components into to handle with React
77 lines (75 loc) • 2.69 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
default: () => rehypeCustomComponent
});
module.exports = __toCommonJS(index_exports);
var import_unist_util_visit = require("unist-util-visit");
function rehypeCustomComponent({
tagName = "custom-component",
matchName = "CustomComponent"
} = {}) {
const REGEX = /<MATCH\s+([^>]*?)\/>/;
const CC_REGEX = new RegExp(REGEX.source.replace("MATCH", matchName), "gs");
const processTextNode = (text) => {
const nodes = [];
let lastIndex = 0;
for (const match of text.matchAll(CC_REGEX)) {
const [fullMatch, attributesString] = match;
const startIndex = match.index ?? 0;
if (startIndex > lastIndex) {
nodes.push({
type: "text",
value: text.slice(lastIndex, startIndex)
});
}
const properties = [...attributesString.matchAll(/(\w+)(?:=(?:"([^"]*)"|([^\s>]+)))?/g)].reduce((acc, [, attrName, quotedValue, unquotedValue]) => ({
...acc,
[attrName]: quotedValue ?? unquotedValue ?? true
}), {});
nodes.push({
type: "element",
tagName,
properties,
children: []
});
lastIndex = startIndex + fullMatch.length;
}
if (lastIndex < text.length) {
nodes.push({
type: "text",
value: text.slice(lastIndex)
});
}
return nodes.length > 0 ? nodes : [{ type: "text", value: text }];
};
const onVisit = (node, index, parent) => {
if (!parent || index === void 0 || !("children" in parent)) return;
const processed = processTextNode(node.value);
if (processed.length > 1 || processed[0]?.type === "element") {
parent.children.splice(index, 1, ...processed);
}
};
return (tree) => {
(0, import_unist_util_visit.visit)(tree, "text", onVisit);
(0, import_unist_util_visit.visit)(tree, "raw", onVisit);
};
}