Skip to content

Build your personal knowledge base with Trilium Notes

chore(export): format exported HTML without the html package

Elian Doranaf66cf156810
diff --git a/apps/server/package.json b/apps/server/package.json
index b4de2e3f64..3e2ae3331d 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -75,7 +75,6 @@
"express-rate-limit": "8.7.1",
"express-session": "1.19.0",
"helmet": "8.3.0",
- "html": "1.0.0",
"http-proxy-agent": "9.1.0",
"https-proxy-agent": "9.1.0",
"i18next-fs-backend": "2.6.9",
diff --git a/packages/trilium-core/src/services/export/format_html.spec.ts b/packages/trilium-core/src/services/export/format_html.spec.ts
new file mode 100644
index 0000000000..bc68f9039c
--- /dev/null
+++ b/packages/trilium-core/src/services/export/format_html.spec.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from "vitest";
+
+import { formatHtml } from "./format_html.js";
+
+describe("formatHtml", () => {
+ it("puts each block on its own line, indenting the containers", () => {
+ const html = `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>T</title></head>`
+ + `<body><!-- note --><div class="ck-content"><h2>Plot</h2><p>A long paragraph stays on one line, however long it grows.</p>`
+ + `<ul><li><p>one</p><ul><li>two</li></ul></li></ul>`
+ + `<figure class="table"><table><tbody><tr><td>a</td><td>b</td></tr></tbody></table></figure></div></body></html>`;
+
+ expect(formatHtml(html)).toBe([
+ "<!DOCTYPE html>",
+ `<html lang="en">`,
+ " <head>",
+ ` <meta charset="utf-8">`,
+ " <title>T</title>",
+ " </head>",
+ " <body>",
+ " <!-- note -->",
+ ` <div class="ck-content">`,
+ " <h2>Plot</h2>",
+ " <p>A long paragraph stays on one line, however long it grows.</p>",
+ " <ul>",
+ " <li>",
+ " <p>one</p>",
+ " <ul>",
+ " <li>two</li>",
+ " </ul>",
+ " </li>",
+ " </ul>",
+ ` <figure class="table">`,
+ " <table>",
+ " <tbody>",
+ " <tr>",
+ " <td>a</td>",
+ " <td>b</td>",
+ " </tr>",
+ " </tbody>",
+ " </table>",
+ " </figure>",
+ " </div>",
+ " </body>",
+ "</html>"
+ ].join("\n"));
+ });
+
+ it("keeps a container verbatim when splitting it would add whitespace between its children", () => {
+ expect(formatHtml(`<ul><li>text<ul><li>n</li></ul></li><li><span>a</span><span>b</span></li></ul>`)).toBe([
+ "<ul>",
+ " <li>text<ul><li>n</li></ul></li>",
+ " <li><span>a</span><span>b</span></li>",
+ "</ul>"
+ ].join("\n"));
+ expect(formatHtml(`text before <p>a block</p>`)).toBe(`text before <p>a block</p>`);
+ });
+
+ it("leaves the content of every element it does not split untouched", () => {
+ const pre = `<pre><code class="language-js"> a\n\n &lt;b&gt;</code></pre>`;
+ const textarea = `<p><textarea> keep\n me</textarea></p>`;
+ const paragraph = `<p class=x data-a="1 > 2" data-b='q"'>a&nbsp;&amp; <strong>b</strong>c<img src="a.png"></p>`;
+
+ expect(formatHtml(`<div>${pre}${textarea}${paragraph}</div>`))
+ .toBe(["<div>", ` ${pre}`, ` ${textarea}`, ` ${paragraph}`, "</div>"].join("\n"));
+ });
+
+ it("separates the attributes of every tag by one space, keeping their values as written", () => {
+ expect(formatHtml(`<div id="d"\n><p>See <a\n class="reference-link" href='a b'\tdata-x = 1>x</a>.</p></div>`))
+ .toBe([ `<div id="d">`, ` <p>See <a class="reference-link" href='a b' data-x=1>x</a>.</p>`, "</div>" ].join("\n"));
+ expect(formatHtml(`<pre class="x"><code class="y"> <b >keep</b></code></pre>`))
+ .toBe(`<pre class="x"><code class="y"> <b >keep</b></code></pre>`);
+ });
+
+ it("gives the same output when run on its own output", () => {
+ const html = `<html><head><title>T</title></head><body><div><p>a</p>\n\n <p>b</p></div></body></html>`;
+ const formatted = formatHtml(html);
+
+ expect(formatted).toBe([
+ "<html>",
+ " <head>",
+ " <title>T</title>",
+ " </head>",
+ " <body>",
+ " <div>",
+ " <p>a</p>",
+ " <p>b</p>",
+ " </div>",
+ " </body>",
+ "</html>"
+ ].join("\n"));
+ expect(formatHtml(formatted)).toBe(formatted);
+ });
+});
diff --git a/packages/trilium-core/src/services/export/format_html.ts b/packages/trilium-core/src/services/export/format_html.ts
new file mode 100644
index 0000000000..e894806d4b
--- /dev/null
+++ b/packages/trilium-core/src/services/export/format_html.ts
@@ -0,0 +1,86 @@
+import { type HTMLElement, type Node, NodeType, parse } from "node-html-parser";
+
+/**
+ * Formats exported HTML with one block per line and each container indented by its depth, so an
+ * edit to one paragraph changes one line of a diff. An element is split across lines only when
+ * every child is a block, because whitespace between inline children shows on the page; every
+ * other element, and a fragment with text at its top level, keeps its content as parsed. Every tag
+ * has its attributes separated by one space.
+ */
+export function formatHtml(html: string) {
+ const root = parse(html, { comment: true });
+ for (const element of root.querySelectorAll("*")) {
+ element.rawAttrs = normalizeAttributes(element.rawAttrs);
+ }
+ return canSplit(root) ? formatChildren(root, 0).join("\n") : root.toString();
+}
+
+const INDENT = " ";
+
+const CONTAINER_TAGS = new Set([
+ "html", "head", "body", "div", "section", "article", "aside", "header", "footer", "nav", "main",
+ "figure", "blockquote", "details", "ul", "ol", "li", "dl", "table", "thead", "tbody", "tfoot",
+ "tr", "colgroup"
+]);
+
+const BLOCK_TAGS = new Set([
+ ...CONTAINER_TAGS,
+ "p", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "hr", "address", "figcaption", "summary", "dt",
+ "dd", "caption", "col", "th", "td",
+ "base", "link", "meta", "noscript", "script", "style", "title"
+]);
+
+function formatNode(node: Node, depth: number): string[] {
+ const indent = INDENT.repeat(depth);
+
+ if (node.nodeType === NodeType.ELEMENT_NODE && canSplit(node as HTMLElement)) {
+ const element = node as HTMLElement;
+ const attributes = element.rawAttrs ? ` ${element.rawAttrs}` : "";
+ return [
+ `${indent}<${element.rawTagName}${attributes}>`,
+ ...formatChildren(element, depth + 1),
+ `${indent}</${element.rawTagName}>`
+ ];
+ }
+
+ return [ indent + node.toString().trim() ];
+}
+
+function formatChildren(element: HTMLElement, depth: number) {
+ return element.childNodes
+ .filter((child) => !isWhitespace(child))
+ .flatMap((child) => formatNode(child, depth));
+}
+
+/** Whether `element` (or the parsed root, which has no tag) can have its children on separate lines. */
+function canSplit(element: HTMLElement) {
+ if (element.rawTagName && !CONTAINER_TAGS.has(element.rawTagName.toLowerCase())) {
+ return false;
+ }
+
+ const children = element.childNodes.filter((child) => !isWhitespace(child));
+ return children.length > 0 && children.every((child) => {
+ switch (child.nodeType) {
+ case NodeType.ELEMENT_NODE:
+ return BLOCK_TAGS.has((child as HTMLElement).rawTagName.toLowerCase());
+ case NodeType.COMMENT_NODE:
+ return true;
+ default:
+ return child.rawText.trimStart().startsWith("<!");
+ }
+ });
+}
+
+/** An attribute name, optionally followed by `=` and a quoted or unquoted value. */
+const ATTRIBUTE = /[^\s"'<>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>=`]+))?/g;
+
+/** Joins the attributes of `rawAttrs` with one space, without touching the text of their values. */
+function normalizeAttributes(rawAttrs: string) {
+ return Array.from(rawAttrs.matchAll(ATTRIBUTE), ([ attribute ]) => attribute.replace(/^([^=\s]+)\s*=\s*/, "$1="))
+ .join(" ");
+}
+
+/** Whitespace as HTML defines it, which leaves out the significant U+00A0 that `trim()` removes. */
+function isWhitespace(node: Node) {
+ return node.nodeType === NodeType.TEXT_NODE && /^[ \t\n\f\r]*$/.test(node.rawText);
+}
diff --git a/packages/trilium-core/src/services/export/single.ts b/packages/trilium-core/src/services/export/single.ts
index d6586738ca..a8ad21a6a1 100644
--- a/packages/trilium-core/src/services/export/single.ts
+++ b/packages/trilium-core/src/services/export/single.ts
@@ -1,7 +1,6 @@
import type { Response } from "../../http_interface";
-import html from "html";
import mimeTypes from "mime-types";
import becca from "../../becca/becca.js";
@@ -10,6 +9,7 @@ import type BNote from "../../becca/entities/bnote.js";
import { ValidationError } from "../../errors.js";
import type TaskContext from "../task_context.js";
import { escapeHtml,getContentDisposition } from "../utils/index.js";
+import { formatHtml } from "./format_html.js";
import mdService from "./markdown.js";
import { stripListItemIds } from "./strip_list_item_ids.js";
import { ExportFormat } from "../../meta.js";
@@ -81,7 +81,7 @@ export function mapByNoteType(note: BNote, content: string | Uint8Array, format:
content = `<html><head><meta charset="utf-8"></head><body>${content}</body></html>`;
}
- payload = content.length < 100_000 ? html.prettyPrint(content, { indent_size: 2 }) : content;
+ payload = formatHtml(content);
extension = "html";
mime = "text/html";
diff --git a/packages/trilium-core/src/services/export/zip/html.ts b/packages/trilium-core/src/services/export/zip/html.ts
index ec68f830b3..36e5dd4825 100644
--- a/packages/trilium-core/src/services/export/zip/html.ts
+++ b/packages/trilium-core/src/services/export/zip/html.ts
@@ -1,6 +1,5 @@
-import html from "html";
-
import { escapeHtml } from "../../utils/index";
+import { formatHtml } from "../format_html.js";
import { ZipExportProvider, ZipExportProviderData } from "./abstract_provider.js";
import { NoteMeta } from "../../../meta";
@@ -71,16 +70,7 @@ export default class HtmlExportProvider extends ZipExportProvider {
</html>`;
}
- // Rewrite before pretty-printing: `html.prettyPrint` wraps at 70 columns and counts
- // attribute text toward that budget, so printing first would place line breaks against
- // hrefs that `rewriteFn` is about to replace. The same note then exports different
- // line breaks depending on whether the editor last wrote a link as a full note path or
- // an import wrote it as a bare ID.
- content = this.rewriteFn(content, noteMeta);
- if (content.length < 100_000) {
- content = html.prettyPrint(content, { indent_size: 2 });
- }
- return content;
+ return formatHtml(this.rewriteFn(content, noteMeta));
}
return content;
@@ -138,9 +128,7 @@ export default class HtmlExportProvider extends ZipExportProvider {
<ul>${this.#saveNavigationInner(rootMeta, rootMeta)}</ul>
</body>
</html>`;
- const prettyHtml = fullHtml.length < 100_000 ? html.prettyPrint(fullHtml, { indent_size: 2 }) : fullHtml;
-
- this.archive.append(prettyHtml, { name: navigationMeta.dataFileName });
+ this.archive.append(formatHtml(fullHtml), { name: navigationMeta.dataFileName });
}
#saveIndex(rootMeta: NoteMeta, indexMeta: NoteMeta) {
diff --git a/patches/[email protected] b/patches/[email protected]
deleted file mode 100644
index 09306fb4bc..0000000000
--- a/patches/[email protected]
+++ /dev/null
@@ -1,15 +0,0 @@
-diff --git a/lib/html.js b/lib/html.js
-index 455c1ae8e1d23cb57bf71c0421d5a7430e86c3f4..8de8b08a283eea8e115c3e1545a6e8e9d77bbe06 100644
---- a/lib/html.js
-+++ b/lib/html.js
-@@ -227,8 +227,8 @@ function style_html(html_source, options) {
-
- var tag_complete = content.join('');
- var tag_index;
-- if (tag_complete.indexOf(' ') != -1) { //if there's whitespace, thats where the tag name ends
-- tag_index = tag_complete.indexOf(' ');
-+ if (tag_complete.search(/\s/) != -1) { //if there's whitespace, thats where the tag name ends
-+ tag_index = tag_complete.search(/\s/);
- }
- else { //otherwise go with the tag ending
- tag_index = tag_complete.indexOf('>');
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 394682d719..fc90b0ccd2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -85,7 +85,6 @@ overrides:
patchedDependencies:
'@excalidraw/[email protected]': c3ec98fc71b950a037705d5b29b69e8d18bcc958c8019688efaf4c07b79eb0b6
- [email protected]: 8acc288f8e9cde3c8a0c6e89f0b3796aeeb8251b88db9d1ba313e2352a591d68
[email protected]: 09dfeb6f635c52ef565ca21aec3f70eb129577661f85eb67262092e8cb9f8548
importers:
@@ -764,9 +763,6 @@ importers:
helmet:
specifier: 8.3.0
version: 8.3.0
- html:
- specifier: 1.0.0
- version: 1.0.0(patch_hash=8acc288f8e9cde3c8a0c6e89f0b3796aeeb8251b88db9d1ba313e2352a591d68)
http-proxy-agent:
specifier: 9.1.0
version: 9.1.0([email protected])
@@ -6384,9 +6380,6 @@ packages:
resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==}
- resolution: {integrity: sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==}
-
resolution: {integrity: sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==}
@@ -7912,10 +7905,6 @@ packages:
resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==}
- resolution: {integrity: sha512-lw/7YsdKiP3kk5PnR1INY17iJuzdAtJewxr14ozKJWbbR97znovZ0mh+WEMZ8rjc3lgTK+ID/htTjuyGKB52Kw==}
- hasBin: true
-
resolution: {integrity: sha512-rmow9353OK0elkub15Sbze8Nj7BYfduqoJJw4yEvHHjOcHeCazNPk0PoUbjE8SvxKgjymeRIFU/OnS8jtitRtA==}
@@ -11074,9 +11063,6 @@ packages:
resolution: {integrity: sha512-phPGCwqr2+Qo0fwniCE8e4pKnGu/yFb5nD5Y8bf0EEeiI5GklnACYA9GFy/DrAeRrKHXvHn+1SUsOWgJp6RO+g==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==}
-
resolution: {integrity: sha512-tIay6z6MRb/4+mfWgKNPR6qEM5rz9S8rTiz0JWmSb/66A6AlZIl9q+1lAFygj4n8GHH1fsqKYQNt9JbNcuE0Uw==}
peerDependencies:
@@ -17944,13 +17930,6 @@ snapshots:
- dependencies:
- buffer-from: 1.1.2
- inherits: 2.0.4
- readable-stream: 2.3.8
- typedarray: 0.0.6
-
@@ -19859,10 +19838,6 @@ snapshots:
- [email protected](patch_hash=8acc288f8e9cde3c8a0c6e89f0b3796aeeb8251b88db9d1ba313e2352a591d68):
- dependencies:
- concat-stream: 1.6.2
-
@@ -23462,8 +23437,6 @@ snapshots:
possible-typed-array-names: 1.1.0
reflect.getprototypeof: 1.0.10
-
dependencies:
typedoc: 0.28.20([email protected])
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 9fc1d0140b..ebe49f9450 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -125,7 +125,6 @@ ignoredOptionalDependencies:
patchedDependencies:
'@excalidraw/[email protected]': patches/@[email protected]
allowBuilds: