html-serializer.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. this.serializer = this.serializer || (() => {
  21. const SELF_CLOSED_TAG_NAMES = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"];
  22. const Node_ELEMENT_NODE = 1;
  23. const Node_TEXT_NODE = 3;
  24. const Node_COMMENT_NODE = 8;
  25. // see https://www.w3.org/TR/html5/syntax.html#optional-tags
  26. const OMITTED_START_TAGS = [
  27. { tagName: "head", accept: element => !element.childNodes.length || element.childNodes[0].nodeType == Node_ELEMENT_NODE },
  28. { tagName: "body", accept: element => !element.childNodes.length }
  29. ];
  30. const OMITTED_END_TAGS = [
  31. { tagName: "html", accept: next => !next || next.nodeType != Node_COMMENT_NODE },
  32. { tagName: "head", accept: next => !next || (next.nodeType != Node_COMMENT_NODE && (next.nodeType != Node_TEXT_NODE || !startsWithSpaceChar(next.textContent))) },
  33. { tagName: "body", accept: next => !next || next.nodeType != Node_COMMENT_NODE },
  34. { tagName: "li", accept: (next, element) => (!next && element.parentElement && (element.parentElement.tagName == "UL" || element.parentElement.tagName == "OL")) || (next && ["LI"].includes(next.tagName)) },
  35. { tagName: "dt", accept: next => !next || ["DT", "DD"].includes(next.tagName) },
  36. { tagName: "p", accept: next => next && ["ADDRESS", "ARTICLE", "ASIDE", "BLOCKQUOTE", "DETAILS", "DIV", "DL", "FIELDSET", "FIGCAPTION", "FIGURE", "FOOTER", "FORM", "H1", "H2", "H3", "H4", "H5", "H6", "HEADER", "HR", "MAIN", "NAV", "OL", "P", "PRE", "SECTION", "TABLE", "UL"].includes(next.tagName) },
  37. { tagName: "dd", accept: next => !next || ["DT", "DD"].includes(next.tagName) },
  38. { tagName: "rt", accept: next => !next || ["RT", "RP"].includes(next.tagName) },
  39. { tagName: "rp", accept: next => !next || ["RT", "RP"].includes(next.tagName) },
  40. { tagName: "optgroup", accept: next => !next || ["OPTGROUP"].includes(next.tagName) },
  41. { tagName: "option", accept: next => !next || ["OPTION", "OPTGROUP"].includes(next.tagName) },
  42. { tagName: "colgroup", accept: next => !next || (next.nodeType != Node_COMMENT_NODE && (next.nodeType != Node_TEXT_NODE || !startsWithSpaceChar(next.textContent))) },
  43. { tagName: "caption", accept: next => !next || (next.nodeType != Node_COMMENT_NODE && (next.nodeType != Node_TEXT_NODE || !startsWithSpaceChar(next.textContent))) },
  44. { tagName: "thead", accept: next => !next || ["TBODY", "TFOOT"].includes(next.tagName) },
  45. { tagName: "tbody", accept: next => !next || ["TBODY", "TFOOT"].includes(next.tagName) },
  46. { tagName: "tfoot", accept: next => !next },
  47. { tagName: "tr", accept: next => !next || ["TR"].includes(next.tagName) },
  48. { tagName: "td", accept: next => !next || ["TD", "TH"].includes(next.tagName) },
  49. { tagName: "th", accept: next => !next || ["TD", "TH"].includes(next.tagName) }
  50. ];
  51. const TEXT_NODE_TAGS = ["style", "script", "xmp", "iframe", "noembed", "noframes", "plaintext", "noscript"];
  52. return {
  53. process(doc, compressHTML) {
  54. const docType = doc.doctype;
  55. let docTypeString = "";
  56. if (docType) {
  57. docTypeString = "<!DOCTYPE " + docType.nodeName;
  58. if (docType.publicId) {
  59. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  60. if (docType.systemId)
  61. docTypeString += " \"" + docType.systemId + "\"";
  62. } else if (docType.systemId)
  63. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  64. if (docType.internalSubset)
  65. docTypeString += " [" + docType.internalSubset + "]";
  66. docTypeString += "> ";
  67. }
  68. return docTypeString + (compressHTML ? serialize(doc.documentElement) : doc.documentElement.outerHTML);
  69. }
  70. };
  71. function serialize(node) {
  72. if (node.nodeType == Node_TEXT_NODE) {
  73. return serializeTextNode(node);
  74. } else if (node.nodeType == Node_COMMENT_NODE) {
  75. return serializeCommentNode(node);
  76. } else if (node.nodeType == Node_ELEMENT_NODE) {
  77. return serializeElement(node);
  78. }
  79. }
  80. function serializeTextNode(textNode) {
  81. const parentNode = textNode.parentNode;
  82. let parentTagName;
  83. if (parentNode && parentNode.nodeType == Node_ELEMENT_NODE) {
  84. parentTagName = parentNode.tagName.toLowerCase();
  85. }
  86. if (!parentTagName || TEXT_NODE_TAGS.includes(parentTagName)) {
  87. if (parentTagName == "script") {
  88. return textNode.textContent.replace(/<\//gi, "<\\/").replace(/\/>/gi, "\\/>");
  89. }
  90. return textNode.textContent;
  91. } else {
  92. return textNode.textContent.replace(/&/g, "&amp;").replace(/\u00a0/g, "&nbsp;").replace(/</g, "&lt;").replace(/</g, "&gt;");
  93. }
  94. }
  95. function serializeCommentNode(commentNode) {
  96. return "<!--" + commentNode.textContent + "-->";
  97. }
  98. function serializeElement(element) {
  99. const tagName = element.tagName.toLowerCase();
  100. const omittedStartTag = OMITTED_START_TAGS.find(omittedStartTag => tagName == omittedStartTag.tagName && omittedStartTag.accept(element));
  101. let content = "";
  102. if (!omittedStartTag || element.attributes.length) {
  103. content = "<" + tagName;
  104. Array.from(element.attributes).forEach(attribute => content += serializeAttribute(attribute, element));
  105. content += ">";
  106. }
  107. Array.from(element.childNodes).forEach(childNode => content += serialize(childNode));
  108. const omittedEndTag = OMITTED_END_TAGS.find(omittedEndTag => tagName == omittedEndTag.tagName && omittedEndTag.accept(element.nextSibling, element));
  109. if (!omittedEndTag && !SELF_CLOSED_TAG_NAMES.includes(tagName)) {
  110. content += "</" + tagName + ">";
  111. }
  112. return content;
  113. }
  114. function serializeAttribute(attribute, element) {
  115. const name = attribute.name;
  116. let content = "";
  117. if (!name.match(/["'>/=]/)) {
  118. let value = attribute.value;
  119. if (name == "class") {
  120. value = Array.from(element.classList).map(className => className.trim()).join(" ");
  121. }
  122. let simpleQuotesValue;
  123. value = value.replace(/&/g, "&amp;").replace(/\u00a0/g, "&nbsp;");
  124. if (value.includes("\"")) {
  125. if (value.includes("'")) {
  126. value = value.replace(/"/g, "&quot;");
  127. } else {
  128. simpleQuotesValue = true;
  129. }
  130. }
  131. const invalidUnquotedValue = !value.match(/^[^ \t\n\f\r'"`=<>]+$/);
  132. content += " ";
  133. if (!attribute.namespace) {
  134. content += name;
  135. } else if (attribute.namespaceURI == "http://www.w3.org/XML/1998/namespace") {
  136. content += "xml:" + name;
  137. } else if (attribute.namespaceURI == "http://www.w3.org/2000/xmlns/") {
  138. if (name !== "xmlns") {
  139. content += "xmlns:";
  140. }
  141. content += name;
  142. } else if (attribute.namespaceURI == "http://www.w3.org/1999/xlink") {
  143. content += "xlink:" + name;
  144. } else {
  145. content += name;
  146. }
  147. if (value != "") {
  148. content += "=";
  149. if (invalidUnquotedValue) {
  150. content += simpleQuotesValue ? "'" : "\"";
  151. }
  152. content += value;
  153. if (invalidUnquotedValue) {
  154. content += simpleQuotesValue ? "'" : "\"";
  155. }
  156. }
  157. }
  158. return content;
  159. }
  160. function startsWithSpaceChar(textContent) {
  161. return Boolean(textContent.match(/^[ \t\n\f\r]/));
  162. }
  163. })();