Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(onenote): preserve table column widths on import
Elian Doranbe801dabe791
diff --git a/apps/server/src/services/import/onenote/converter.spec.ts b/apps/server/src/services/import/onenote/converter.spec.tsindex 7f728f080f..12db599f7b 100644--- a/apps/server/src/services/import/onenote/converter.spec.ts+++ b/apps/server/src/services/import/onenote/converter.spec.ts@@ -287,6 +287,36 @@ const TABLE_SAMPLE = `<html lang="en-US"></body></html>`;+// Real OneNote source (debug-captured): a column-resized table. OneNote stamps the resized width as a+// bare pixel `width` on every cell of the column (150/49/399/136 across the four columns), a form the+// sanitizer drops — so the widths are lost unless translated to CKEditor's colgroup representation.+const TABLE_RESIZE_SAMPLE = `<html lang="ro-RO">+ <body data-absolute-enabled="true" style="font-family:Calibri;font-size:11pt">+ <div style="position:absolute;left:48px;top:115px;width:689px">+ <table style="border:1px solid;border-collapse:collapse">+ <tr>+ <td style="width:150;border:1px solid"><span lang="en-US">Mid</span></td>+ <td style="width:49;border:1px solid"><span lang="en-US">SM</span></td>+ <td style="width:399;border:1px solid"><span lang="en-US">Large</span></td>+ <td style="width:136;border:1px solid"><br /></td>+ </tr>+ <tr>+ <td style="width:150;border:1px solid"><span lang="en-US">Mid</span></td>+ <td style="width:49;border:1px solid"><span lang="en-US">SM</span></td>+ <td style="width:399;border:1px solid"><span lang="en-US">Large</span></td>+ <td style="width:136;border:1px solid"><br /></td>+ </tr>+ <tr>+ <td style="width:150;border:1px solid"><br /></td>+ <td style="width:49;border:1px solid"><br /></td>+ <td style="width:399;border:1px solid"><br /></td>+ <td style="width:136;border:1px solid"><br /></td>+ </tr>+ </table>+ </div>+ </body>+</html>`;+// Tests assert the end result (the HTML actually stored on the note, i.e. after sanitization).describe("convertPageHtml", () => {it("strips OneNote's block-level <br> spacing and empty list items, keeping real content", () => {@@ -372,6 +402,44 @@ describe("convertPageHtml", () => {expect(out).not.toContain("border-collapse");});+ it("preserves OneNote per-column widths as a CKEditor resized-table colgroup", () => {+ const out = converter.convertPageHtml(TABLE_RESIZE_SAMPLE);+ const root = parse(out);++ // The table becomes a full-width table figure, tagged as column-resized, with its rows in a+ // <tbody> beneath the <colgroup> — CKEditor's resized-table shape.+ const figure = root.querySelector("figure.table");+ expect(figure?.getAttribute("style")).toContain("width:100%");+ expect(figure?.querySelector("table")?.getAttribute("class")).toContain("ck-table-resized");+ expect(root.querySelector("figure.table table colgroup")).toBeTruthy();+ expect(root.querySelectorAll("figure.table table tbody tr")).toHaveLength(3);++ // Each column's pixel width (150/49/399/136 of 734) becomes a proportional percentage in the+ // colgroup, and the set sums to exactly 100 (the rounding remainder settles on the last column).+ const cols = root.querySelectorAll("colgroup col").map((col) => col.getAttribute("style"));+ expect(cols).toEqual(["width:20.44%", "width:6.68%", "width:54.36%", "width:18.52%"]);++ // The now-redundant per-cell widths are gone, and the cell content survives.+ expect(root.querySelectorAll("td").every((td) => !(td.getAttribute("style") ?? "").includes("width"))).toBe(true);+ expect(out).toContain("Mid");+ expect(out).toContain("Large");+ });++ it("leaves a table without a full set of column widths unresized", () => {+ // Only the first column carries a width — the resize would be ambiguous, so the table is left as-is.+ const sample = `<body><div><table style="border:1px solid;border-collapse:collapse"><tr><td style="width:220;border:1px solid">A</td><td style="border:1px solid">B</td></tr></table></div></body>`;+ const root = parse(converter.convertPageHtml(sample));++ expect(root.querySelector("figure.table")).toBeFalsy();+ expect(root.querySelector("colgroup")).toBeFalsy();+ expect(root.querySelector("table")?.getAttribute("class") ?? "").not.toContain("ck-table-resized");+ });++ it("does not resize a table that merges cells (colspan/rowspan)", () => {+ const sample = `<body><div><table><tr><td colspan="2" style="width:100">A</td></tr><tr><td style="width:50">B</td><td style="width:50">C</td></tr></table></div></body>`;+ expect(parse(converter.convertPageHtml(sample)).querySelector("colgroup")).toBeFalsy();+ });+it("converts OneNote to-do tags into a Trilium task list", () => {const out = converter.convertPageHtml(TAGS_SAMPLE);const root = parse(out);diff --git a/apps/server/src/services/import/onenote/converter.ts b/apps/server/src/services/import/onenote/converter.tsindex 8dd9047cb6..cb4080b043 100644--- a/apps/server/src/services/import/onenote/converter.ts+++ b/apps/server/src/services/import/onenote/converter.ts@@ -117,6 +117,7 @@ export function convertPageHtml(rawHtml: string): string {normalizeTableBorders(scope);removeEmptyListItems(scope);removeBlockLevelBreaks(scope);+ resizeTables(scope);return sanitize.sanitizeHtml(scope.innerHTML);}@@ -521,6 +522,90 @@ function normalizeTableBorders(scope: HTMLElement) {}}+/**+ * OneNote carries a resized column's width as a bare pixel `width` on every cell of that column+ * (e.g. `<td style="width:150;…">`), a per-cell form the sanitizer drops — so column widths are lost.+ * CKEditor instead stores column widths as percentages in a <colgroup> on a `ck-table-resized` table+ * wrapped in `<figure class="table" style="width:100%;">`. When every column carries an explicit width,+ * translate OneNote's pixel widths into that representation: emit a <colgroup> of proportional+ * percentages (summing to 100), strip the now-redundant per-cell widths, tag the table resized and wrap+ * it in a table figure. Tables that don't width every column, or that merge cells (colspan/rowspan,+ * which this flat column model can't represent), are left untouched.+ */+function resizeTables(scope: HTMLElement) {+ for (const table of scope.querySelectorAll("table")) {+ const cellRows = table.querySelectorAll("tr").map((row) => row.querySelectorAll("td, th"));+ const columnCount = Math.max(0, ...cellRows.map((cells) => cells.length));+ if (columnCount === 0 || cellRows.some((cells) => cells.some(hasCellSpan))) {+ continue;+ }++ // A resized column repeats its width on every cell; take the first one seen per column. Bail+ // unless every column has one — a partial set can't be faithfully turned into a full colgroup.+ const widths: number[] = [];+ for (let column = 0; column < columnCount; column++) {+ const width = cellRows.map((cells) => columnWidth(cells[column])).find((value) => value !== undefined);+ if (width === undefined) {+ break;+ }+ widths.push(width);+ }+ if (widths.length !== columnCount) {+ continue;+ }++ for (const cells of cellRows) {+ for (const cell of cells) {+ const style = parseStyle(cell.getAttribute("style") ?? "");+ if (style.delete("width")) {+ if (style.size === 0) {+ cell.removeAttribute("style");+ } else {+ cell.setAttribute("style", serializeStyle(style));+ }+ }+ }+ }++ const colgroup = `<colgroup>${columnPercentages(widths).map((percent) => `<col style="width:${percent}%;">`).join("")}</colgroup>`;+ const existingClass = table.getAttribute("class");+ table.setAttribute("class", existingClass ? `${existingClass} ck-table-resized` : "ck-table-resized");+ table.set_content(`${colgroup}<tbody>${table.innerHTML}</tbody>`);+ table.insertAdjacentHTML("beforebegin", `<figure class="table" style="width:100%;">${table.toString()}</figure>`);+ table.remove();+ }+}++/** Whether a cell spans multiple rows/columns, which the flat column model in resizeTables can't map. */+function hasCellSpan(cell: HTMLElement): boolean {+ return cell.getAttribute("colspan") != null || cell.getAttribute("rowspan") != null;+}++/** A cell's positive pixel `width` (OneNote writes it unit-less, e.g. `width:150`), or undefined. */+function columnWidth(cell: HTMLElement | undefined): number | undefined {+ const value = cell && parseStyle(cell.getAttribute("style") ?? "").get("width");+ const pixels = value ? parseFloat(value) : NaN;+ return Number.isFinite(pixels) && pixels > 0 ? pixels : undefined;+}++/**+ * Turns pixel column widths into percentages of their total, rounded to two decimals. The last column+ * takes the remainder so the set sums to exactly 100% (matching CKEditor's normalized colgroup) rather+ * than drifting a hundredth off through independent rounding.+ */+function columnPercentages(widths: number[]): number[] {+ const total = widths.reduce((sum, width) => sum + width, 0);+ let allocated = 0;+ return widths.map((width, index) => {+ if (index === widths.length - 1) {+ return Math.round((100 - allocated) * 100) / 100;+ }+ const percent = Math.round((width / total) * 10000) / 100;+ allocated += percent;+ return percent;+ });+}+/** Drops list items that hold nothing but whitespace/<br> (OneNote's "exited the list" remnant). */function removeEmptyListItems(scope: HTMLElement) {for (const li of scope.querySelectorAll("li")) {