mirror of
https://github.com/THU-MAIC/OpenMAIC.git
synced 2026-10-31 07:43:18 +08:00
formatAttributes is a reduce; the empty-style branch returned '' instead of the accumulator, so every attribute emitted before an empty `style=""` attribute was dropped on stringify (e.g. `<div class="x" style=""> -> <div>`). Return `attrs` to omit the empty style while keeping the rest. Closes #682 Co-authored-by: ly-wang19 <ly-wang19@users.noreply.github.com> Co-authored-by: wyuc <wang-yc24@mails.tsinghua.edu.cn>
31 lines
1.2 KiB
TypeScript
31 lines
1.2 KiB
TypeScript
import type { AST, ElementAST, ElementAttribute } from './types';
|
|
import { voidTags } from './tags';
|
|
|
|
export const formatAttributes = (attributes: ElementAttribute[]) => {
|
|
return attributes.reduce((attrs, attribute) => {
|
|
const { key, value } = attribute;
|
|
if (value === null) return `${attrs} ${key}`;
|
|
// Omit an empty style attribute, but keep the attributes accumulated so far.
|
|
// Returning '' here dropped every earlier attribute (this is a reduce).
|
|
if (key === 'style' && !value) return attrs;
|
|
|
|
const quoteEscape = value.indexOf("'") !== -1;
|
|
const quote = quoteEscape ? '"' : "'";
|
|
return `${attrs} ${key}=${quote}${value}${quote}`;
|
|
}, '');
|
|
};
|
|
|
|
export const toHTML = (tree: AST[]) => {
|
|
const htmlStrings: string[] = tree.map((node) => {
|
|
if (node.type === 'text') return node.content;
|
|
if (node.type === 'comment') return `<!--${node.content}-->`;
|
|
|
|
const { tagName, attributes, children } = node as ElementAST;
|
|
const isSelfClosing = voidTags.includes(tagName.toLowerCase());
|
|
|
|
if (isSelfClosing) return `<${tagName}${formatAttributes(attributes)}>`;
|
|
return `<${tagName}${formatAttributes(attributes)}>${toHTML(children)}</${tagName}>`;
|
|
});
|
|
return htmlStrings.join('');
|
|
};
|