stringify.ts 1.0 KB

12345678910111213141516171819202122232425262728
  1. import type { AST, ElementAST, ElementAttribute } from './types';
  2. import { voidTags } from './tags';
  3. export const formatAttributes = (attributes: ElementAttribute[]) => {
  4. return attributes.reduce((attrs, attribute) => {
  5. const { key, value } = attribute;
  6. if (value === null) return `${attrs} ${key}`;
  7. if (key === 'style' && !value) return '';
  8. const quoteEscape = value.indexOf("'") !== -1;
  9. const quote = quoteEscape ? '"' : "'";
  10. return `${attrs} ${key}=${quote}${value}${quote}`;
  11. }, '');
  12. };
  13. export const toHTML = (tree: AST[]) => {
  14. const htmlStrings: string[] = tree.map((node) => {
  15. if (node.type === 'text') return node.content;
  16. if (node.type === 'comment') return `<!--${node.content}-->`;
  17. const { tagName, attributes, children } = node as ElementAST;
  18. const isSelfClosing = voidTags.includes(tagName.toLowerCase());
  19. if (isSelfClosing) return `<${tagName}${formatAttributes(attributes)}>`;
  20. return `<${tagName}${formatAttributes(attributes)}>${toHTML(children)}</${tagName}>`;
  21. });
  22. return htmlStrings.join('');
  23. };