very-small-parser
Version:
A very small Markdown, HTML, and CSS parser.
66 lines (65 loc) • 2.23 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MdInlineParser = void 0;
const Parser_1 = require("../../Parser");
const util_1 = require("../../util");
class MdInlineParser extends Parser_1.Parser {
// biome-ignore lint: keep constructor for typing
constructor(opts) {
super(opts);
}
parse(src) {
const raw = super.parse(src);
// Combined pass: merge adjacent text tokens AND attach inline attributes.
// An inlineAttr token {args, value} directly after a non-text inline token
// has its args attached to that token. Otherwise it is folded into text.
const result = [];
let pendingText;
const flushText = () => {
if (pendingText) {
result.push(pendingText);
pendingText = undefined;
}
};
const appendText = (str, len) => {
if (pendingText) {
pendingText.value += str;
pendingText.len += len;
}
else {
pendingText = (0, util_1.token)(str, 'text', void 0, { value: str }, len);
}
};
const length = raw.length;
for (let i = 0; i < length; i++) {
const tok = raw[i];
if (tok.type === 'text') {
const t = tok;
if (pendingText) {
pendingText.value += t.value;
pendingText.len += tok.len;
}
else {
pendingText = { ...t };
}
}
else if (tok.type === 'inlineAttr') {
const attr = tok;
const last = result[result.length - 1];
if (!pendingText && last && last.type !== 'text') {
last.args = last.args ? [...last.args, ...attr.args] : [...attr.args];
}
else {
appendText(attr.value, tok.len);
}
}
else {
flushText();
result.push(tok);
}
}
flushText();
return result;
}
}
exports.MdInlineParser = MdInlineParser;