/*
* Custom HTML normalizer for TipTap input.
* Mirrors the native GumboNormalizer (cpp/parser/GumboNormalizer.c)
*/
type CssStyles = {
bold: boolean;
italic: boolean;
underline: boolean;
strikethrough: boolean;
};
const INLINE_TAGS = new Set([
'b',
'i',
'u',
's',
'code',
'a',
'strong',
'em',
'del',
'strike',
'ins',
'mention',
]);
const BLOCK_TAGS = new Set([
'p',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'ul',
'ol',
'li',
'blockquote',
'codeblock',
'pre',
]);
const SELF_CLOSING_TAGS = new Set(['br', 'img']);
const PASS_TAGS = new Set(['html', 'head', 'body']);
const STRIPPED_TAGS = new Set(['meta', 'style', 'script', 'title', 'link']);
const TABLE_TAGS = new Set([
'table',
'thead',
'tbody',
'tfoot',
'tr',
'td',
'th',
'caption',
'colgroup',
'col',
]);
// table tags that hold inline text rather than other table parts
const TABLE_TEXT_TAGS = new Set(['td', 'th', 'caption']);
function canonicalName(name: string): string {
switch (name) {
case 'strong':
return 'b';
case 'em':
return 'i';
case 'del':
case 'strike':
return 's';
case 'ins':
return 'u';
case 'pre':
return 'codeblock';
default:
return name;
}
}
type TagClass = 'skip' | 'inline' | 'block' | 'self-closing' | 'pass';
function classifyTag(name: string): TagClass {
if (INLINE_TAGS.has(name)) return 'inline';
if (BLOCK_TAGS.has(name)) return 'block';
if (SELF_CLOSING_TAGS.has(name)) return 'self-closing';
if (PASS_TAGS.has(name)) return 'pass';
return 'skip';
}
function isElement(node: Node | null): node is Element {
return !!node && node.nodeType === Node.ELEMENT_NODE;
}
function isText(node: Node | null): boolean {
return !!node && node.nodeType === Node.TEXT_NODE;
}
function tagName(node: Node | null): string | null {
if (!isElement(node)) return null;
return node.tagName.toLowerCase();
}
function isListNode(node: Node | null): boolean {
const n = tagName(node);
return n === 'ul' || n === 'ol';
}
function isBlockquoteNode(node: Node | null): boolean {
return tagName(node) === 'blockquote';
}
function isBrNode(node: Node | null): boolean {
return tagName(node) === 'br';
}
function isBlockProducing(node: Node | null): boolean {
const n = tagName(node);
if (!n) return false;
if (classifyTag(n) === 'block') return true;
return n === 'div' || n === 'table' || n === 'tr';
}
function isPurelyInline(node: Element): boolean {
for (const child of Array.from(node.childNodes)) {
if (isBlockProducing(child)) return false;
}
return true;
}
function hasBlockOrBqChild(node: Element): boolean {
for (const child of Array.from(node.childNodes)) {
if (isBlockProducing(child) || isBlockquoteNode(child)) return true;
}
return false;
}
function findCssValue(style: string, prop: string): string | null {
// Returns the value of the last declaration with this property name.
// Mirrors GumboNormalizer's find_css_value scanning behavior.
const re = new RegExp(
`(?:^|;)\\s*${prop.replace(/[-/\\^$*+?.()|[\\]{}]/g, '\\$&')}\\s*:\\s*([^;]*)`,
'i'
);
const m = re.exec(style);
if (m !== null) {
return (m[1] ?? '').trim();
}
return null;
}
function findAllCssValues(style: string, prop: string): string[] {
const re = new RegExp(
`(?:^|;)\\s*${prop.replace(/[-/\\^$*+?.()|[\\]{}]/g, '\\$&')}\\s*:\\s*([^;]*)`,
'gi'
);
const out: string[] = [];
let m: RegExpExecArray | null;
while ((m = re.exec(style)) !== null) {
out.push((m[1] ?? '').trim());
}
return out;
}
function parseCssStyle(style: string | null): CssStyles {
const result: CssStyles = {
bold: false,
italic: false,
underline: false,
strikethrough: false,
};
if (!style) return result;
const fw = findCssValue(style, 'font-weight');
if (fw) {
const lower = fw.toLowerCase();
if (lower.includes('bold') || lower.includes('bolder')) {
result.bold = true;
} else {
const num = parseInt(fw, 10);
if (!Number.isNaN(num) && num >= 700) result.bold = true;
}
}
const fs = findCssValue(style, 'font-style');
if (fs) {
const lower = fs.toLowerCase();
if (lower.includes('italic') || lower.includes('oblique'))
result.italic = true;
}
// text-decoration / text-decoration-line: scan ALL declarations
const decorations = [
...findAllCssValues(style, 'text-decoration-line'),
...findAllCssValues(style, 'text-decoration'),
];
for (const v of decorations) {
const lower = v.toLowerCase();
if (lower.includes('underline')) result.underline = true;
if (lower.includes('line-through')) result.strikethrough = true;
}
return result;
}
type CustomStyle = {
fg: string;
bg: string;
fontSize: string;
fontFamily: string;
};
function ownCssValue(value: string): string {
// `inherit` must not overwrite the parent span's value
return value.toLowerCase() === 'inherit' ? '' : value;
}
function parseCustomStyle(el: Element): CustomStyle {
const style = (el as HTMLElement).style;
return {
fg: ownCssValue(style.color),
// we don't want `transparent` to overwrite it's parent span's background-color
bg:
style.backgroundColor.toLowerCase() === 'transparent'
? ''
: ownCssValue(style.backgroundColor),
fontSize: ownCssValue(style.fontSize),
fontFamily: escapeText(ownCssValue(style.fontFamily)),
};
}
function customStyleIsEmpty(s: CustomStyle): boolean {
return !s.fg && !s.bg && !s.fontSize && !s.fontFamily;
}
function emitCustomStyleOpen(s: CustomStyle): string {
const styleParts: string[] = [];
if (s.fg) styleParts.push(`color: ${s.fg}`);
if (s.bg) styleParts.push(`background-color: ${s.bg}`);
if (s.fontSize) styleParts.push(`font-size: ${s.fontSize}`);
if (s.fontFamily) styleParts.push(`font-family: ${s.fontFamily}`);
return ``;
}
function extraStyles(s: CssStyles, tag: string): CssStyles {
return {
bold: s.bold && tag !== 'b',
italic: s.italic && tag !== 'i',
underline: s.underline && tag !== 'u',
strikethrough: s.strikethrough && tag !== 's',
};
}
function emitStylesOpen(s: CssStyles): string {
let out = '';
if (s.bold) out += '';
if (s.italic) out += '';
if (s.underline) out += '';
if (s.strikethrough) out += ' 123 456 . Inter-block whitespace (newlines /
* spaces between block tags in pretty-printed HTML) is discarded so it does
* not become empty paragraphs that later serialize as extra ${ib.buf} ; carry over its text-align (if any).
flushInlineP(ib, out, emitAlignment(node, 'p'));
return;
}
walkNode(node, ib, inherited);
}
// --- List item content flattening ---
type LiCtx = {
el: Element;
styles: CssStyles;
nestedLists: Element[];
hasEmitted: boolean;
inherited: CustomStyle | null;
};
function flushLiBuffer(
ib: { buf: string },
out: { buf: string },
ctx: LiCtx
): void {
// Whitespace around blocks inside an a when mixed with blocks
if (
hasBlock &&
!parentIsList &&
!isBlockProducing(child) &&
!(isElement(child) && isBlockquoteNode(child))
) {
const ib = { buf: '' };
while (i < children.length) {
const cur = children[i]!;
if (
isBlockProducing(cur) ||
(isElement(cur) && isBlockquoteNode(cur))
) {
break;
}
if (isElement(cur) && isBrNode(cur)) {
// Whitespace-only buffer is layout noise; treat like empty → per line, since line breaks in code are significant. A line break is
* a newline in text or a ${html} ${line}';
return out;
}
function emitStylesClose(s: CssStyles): string {
let out = '';
if (s.strikethrough) out += '';
if (s.underline) out += '';
if (s.italic) out += '';
if (s.bold) out += '';
return out;
}
// Tags that may carry a text-align style in our canonical output
const ALIGN_TAGS = new Set([
'p',
'ul',
'ol',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
]);
const ALIGN_VALUES = new Set(['left', 'center', 'right', 'justify']);
function emitAlignment(el: Element, name: string): string {
if (!ALIGN_TAGS.has(name)) return '';
const align = findCssValue(el.getAttribute('style') ?? '', 'text-align');
if (!align) return '';
const lower = align.toLowerCase();
if (!ALIGN_VALUES.has(lower)) return '';
return ` style="text-align: ${lower}"`;
}
function emitOneAttr(el: Element, attr: string): string {
const val = el.getAttribute(attr);
if (val == null || val === '') return '';
const escaped = escapeText(val);
return ` ${attr}="${escaped}"`;
}
function emitAttributes(el: Element, name: string): string {
switch (name) {
case 'a':
return emitOneAttr(el, 'href');
case 'img':
return (
(el.getAttribute('src') ? emitOneAttr(el, 'src') : ' src=""') +
emitOneAttr(el, 'alt') +
emitOneAttr(el, 'width') +
emitOneAttr(el, 'height')
);
case 'ul':
return (
(isCheckboxList(el) ? ' data-type="checkbox"' : '') +
emitAlignment(el, name)
);
case 'li':
// "" is U+F0FE (MS Word checked box); often encoded as "\xEF\x83\xBE" in UTF-8.
const isChecked =
el.hasAttribute('checked') ||
el.getAttribute('data-checked') === 'true' ||
el.getAttribute('aria-checked') === 'true' ||
el.getAttribute('data-leveltext') === ''; // MS Word checked box
return isChecked ? ' checked' : '';
case 'mention':
let out = '';
for (const attr of Array.from(el.attributes)) {
out += emitOneAttr(el, attr.name);
}
return out;
default:
// preserve text-align
return emitAlignment(el, name);
}
}
function isCheckboxList(el: Element): boolean {
if (
el.getAttribute('data-type') === 'checkbox' ||
el.getAttribute('data-type') === 'checkboxList'
) {
return true;
}
// In Google Docs and MS Word the
s.
*/
function flushInlineP(
ib: { buf: string },
out: { buf: string },
attrs = ''
): boolean {
const emitted = ib.buf.length > 0 && !isWhitespaceOnly(ib.buf);
if (emitted) {
out.buf += `
so it is not silently dropped.
// With buffered inline content it just terminates the current paragraph.
if (!flushInlineP(ib, out)) {
out.buf += '
';
}
return;
}
if (isBlockProducing(node) || isBlockquoteNode(node)) {
flushInlineP(ib, out);
flattenBqChildren(node, ib, out, inherited);
// The flattened block becomes a that Google Docs uses for the display of a checkbox icon
if (role === 'checkbox') {
return;
}
}
if (isListNode(node)) {
ctx.nestedLists.push(node);
return;
}
if (isBrNode(node)) {
flushLiBuffer(ib, out, ctx);
return;
}
if (isBlockProducing(node) || isBlockquoteNode(node)) {
flushLiBuffer(ib, out, ctx);
flattenLiChildren(node, ib, out, ctx);
flushLiBuffer(ib, out, ctx);
return;
}
walkNode(node, ib, ctx.inherited);
}
// --- Main walker ---
function walkChildren(
node: Element,
out: { buf: string },
inherited: CustomStyle | null
): void {
const children = Array.from(node.childNodes);
const parentIsList = isListNode(node);
let hasBlock = false;
for (const c of children) {
if (isBlockProducing(c)) {
hasBlock = true;
break;
}
}
let i = 0;
while (i < children.length) {
const child = children[i]!;
// Flatten list-inside-list
if (parentIsList && isElement(child) && isListNode(child)) {
walkChildren(child, out, inherited);
i++;
continue;
}
// Merge consecutive blockquotes
if (isElement(child) && isBlockquoteNode(child)) {
out.buf += '
';
const bqIb = { buf: '' };
while (i < children.length) {
const cur = children[i];
if (!cur || !isElement(cur) || !isBlockquoteNode(cur)) break;
flattenBqChildren(cur, bqIb, out, inherited);
i++;
}
flushInlineP(bqIb, out);
out.buf += '
';
continue;
}
// Auto-paragraph: group inline runs into
if (!flushInlineP(ib, out)) {
out.buf += '
';
}
i++;
continue;
}
// Transparent inline wrapper for block/bq children
if (isElement(cur) && hasBlockOrBqChild(cur)) {
flushInlineP(ib, out);
walkChildren(cur, out, inherited);
i++;
continue;
}
walkNode(cur, ib, inherited);
i++;
}
flushInlineP(ib, out);
continue;
}
walkNode(child, out, inherited);
i++;
}
}
/** `
`, `
` or `
`. */
const BR_TAG_RE = /^
]/;
/** True if normalized inline HTML has a line break: a newline in text or a
*
. Newlines inside tags (attribute values) don't count. */
function hasCodeLineBreak(html: string): boolean {
let i = 0;
while (i < html.length) {
if (html[i] === '<') {
const end = html.indexOf('>', i);
if (end === -1) return false;
if (BR_TAG_RE.test(html.slice(i, end + 1))) return true;
i = end + 1;
continue;
}
if (html[i] === '\n') return true;
i++;
}
return false;
}
/**
* Emits normalized inline HTML of a code block (from or
`) is dropped, as browsers don't render it either.
*/
function emitCodeLines(html: string): string {
if (!hasCodeLineBreak(html)) return `
. Inline tags open across a break are closed
* before it and reopened after it. An empty line becomes
, and a trailing
* empty line (`a\n
';
line = openTags.join('');
hasContent = false;
};
let i = 0;
while (i < html.length) {
if (html[i] === '<') {
const end = html.indexOf('>', i);
const tag = end === -1 ? html.slice(i) : html.slice(i, end + 1);
if (BR_TAG_RE.test(tag)) {
flushLine();
} else {
line += tag;
if (tag.startsWith('')) {
openTags.pop();
} else if (tag.endsWith('/>')) {
hasContent = true; // self-closing, e.g.
} else {
openTags.push(tag);
}
}
i += tag.length;
continue;
}
if (html[i] === '\n') {
flushLine();
} else {
line += html[i];
hasContent = true;
}
i++;
}
if (hasContent) flushLine();
return out;
}
function walkNode(
node: Node,
out: { buf: string },
inherited: CustomStyle | null
): void {
if (isText(node)) {
const text = node.textContent ?? '';
const wrap = !!inherited && !isLayoutWhitespace(node);
if (wrap) out.buf += emitCustomStyleOpen(inherited);
out.buf += escapeText(text);
if (wrap) out.buf += '';
return;
}
if (!isElement(node)) return;
const name = node.tagName.toLowerCase();
if (STRIPPED_TAGS.has(name)) return;
if (isGoogleDocsWrapper(node, name)) {
walkChildren(node, out, inherited);
return;
}
const outName = canonicalName(name);
const cls = classifyTag(name);
// : CSS style → inline tags
if (name === 'span') {
const s = parseCssStyle(node.getAttribute('style'));
// own properties override the inherited ones
const own = parseCustomStyle(node);
const style: CustomStyle = {
fg: own.fg || inherited?.fg || '',
bg: own.bg || inherited?.bg || '',
fontSize: own.fontSize || inherited?.fontSize || '',
fontFamily: own.fontFamily || inherited?.fontFamily || '',
};
let childrenStyle = inherited;
let wrap = false;
if (!customStyleIsEmpty(own)) {
// if there are no nested spans deeper, we can emit a wrapper immediately,
// otherwise we hold off with that and we'll emit span tags deeper, after flattening
if (hasStyledSpanDescendant(node)) {
childrenStyle = style;
} else {
wrap = true;
childrenStyle = null;
}
}
// output everything in the correct nested order
if (wrap) out.buf += emitCustomStyleOpen(style);
out.buf += emitStylesOpen(s);
walkChildren(node, out, childrenStyle);
out.buf += emitStylesClose(s);
if (wrap) out.buf += '';
return;
}
//
or passes through if (name === 'div') { const s = parseCssStyle(node.getAttribute('style')); if (isPurelyInline(node)) { const pb = { buf: '' }; for (const dc of Array.from(node.childNodes)) { if (isElement(dc) && isBrNode(dc)) { if (pb.buf.length > 0) { out.buf += `
${emitStylesOpen(s)}${pb.buf}${emitStylesClose(s)}
`; } else { out.buf += '${emitStylesOpen(s)}${pb.buf}${emitStylesClose(s)}
`; } } else { out.buf += emitStylesOpen(s); walkChildren(node, out, inherited); out.buf += emitStylesClose(s); } return; } // Table elements if (TABLE_TAGS.has(name)) { if (name === 'td' || name === 'th') { walkChildren(node, out, inherited); // Append space if there is a next element sibling let sib: Node | null = node.nextSibling; while (sib && !isElement(sib)) sib = sib.nextSibling; if (sib) out.buf += ' '; } else if (name === 'tr') { const row = { buf: '' }; walkChildren(node, row, inherited); if (row.buf.length > 0) { out.buf += `${row.buf}
`; } } else { walkChildren(node, out, inherited); } return; } if (cls === 'pass' || cls === 'skip') { walkChildren(node, out, inherited); return; } if (cls === 'self-closing') { out.buf += `<${outName}${emitAttributes(node, outName)}`; out.buf += outName === 'img' ? ' />' : '>'; return; } // inline or block const es = extraStyles(parseCssStyle(node.getAttribute('style')), outName); // per line
if (outName === 'codeblock') {
out.buf += '