yarn-spinner-runner-ts
Version:
TypeScript parser, compiler, and runtime for Yarn Spinner 3.x with React adapter [NPM package](https://www.npmjs.com/package/yarn-spinner-runner-ts)
64 lines • 2.77 kB
JavaScript
import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
import React from "react";
const DEFAULT_HTML_TAGS = new Set(["b", "em", "small", "strong", "sub", "sup", "ins", "del", "mark", "br"]);
export function MarkupRenderer({ text, markup, length }) {
const maxLength = length ?? text.length;
if (!markup || markup.segments.length === 0) {
return _jsx(_Fragment, { children: text.slice(0, maxLength) });
}
const pieces = [];
const limit = Math.max(0, Math.min(maxLength, markup.text.length));
markup.segments.forEach((segment, index) => {
if (segment.selfClosing) {
if (segment.start <= limit) {
pieces.push({
text: "",
wrappers: segment.wrappers,
selfClosing: true,
key: `self-${index}`,
});
}
return;
}
const start = Math.max(0, Math.min(segment.start, limit));
const end = Math.max(start, Math.min(segment.end, limit));
if (end <= start) {
return;
}
const segmentText = markup.text.slice(start, end);
pieces.push({
text: segmentText,
wrappers: segment.wrappers,
key: `seg-${index}-${start}-${end}`,
});
});
if (pieces.length === 0) {
return _jsx(_Fragment, { children: text.slice(0, maxLength) });
}
return (_jsx(_Fragment, { children: pieces.map((piece, pieceIndex) => renderPiece(piece, pieceIndex)) }));
}
function renderPiece(piece, pieceIndex) {
const baseKey = `${piece.key}-${pieceIndex}`;
if (piece.selfClosing) {
return piece.wrappers.reduceRight((child, wrapper, wrapperIndex) => createWrapperElement(wrapper, `${baseKey}-wrapper-${wrapperIndex}`, child), null);
}
const content = piece.wrappers.reduceRight((child, wrapper, wrapperIndex) => createWrapperElement(wrapper, `${baseKey}-wrapper-${wrapperIndex}`, child), piece.text);
return _jsx(React.Fragment, { children: content }, baseKey);
}
function createWrapperElement(wrapper, key, children) {
const tagName = DEFAULT_HTML_TAGS.has(wrapper.name) ? wrapper.name : "span";
const className = wrapper.type === "custom" ? `yd-markup-${sanitizeClassName(wrapper.name)}` : undefined;
const dataAttributes = {};
for (const [propertyName, value] of Object.entries(wrapper.properties)) {
dataAttributes[`data-markup-${propertyName}`] = String(value);
}
return React.createElement(tagName, {
key,
className,
...dataAttributes,
}, children);
}
function sanitizeClassName(name) {
return name.toLowerCase().replace(/[^a-z0-9_-]/g, "-");
}
//# sourceMappingURL=MarkupRenderer.js.map