Spaces:
Runtime error
Runtime error
File size: 9,070 Bytes
fb38ec5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | // Adapted from https://github.com/laurent22/joplin/blob/dev/packages/turndown-plugin-gfm/src/tables.js
import TurndownService from "@joplin/turndown";
import { isCodeBlock } from "./utilities.js";
var indexOf = Array.prototype.indexOf;
var every = Array.prototype.every;
var rules: Record<string, any> = {};
var alignMap = { left: ":---", right: "---:", center: ":---:" };
// We need to cache the result of tableShouldBeSkipped() as it is expensive.
// Caching it means we went from about 9000 ms for rendering down to 90 ms.
// Fixes https://github.com/laurent22/joplin/issues/6736
const tableShouldBeSkippedCache_ = new WeakMap();
function getAlignment(node) {
return node ? (node.getAttribute("align") || node.style.textAlign || "").toLowerCase() : "";
}
function getBorder(alignment) {
return alignment ? alignMap[alignment] : "---";
}
function getColumnAlignment(table, columnIndex) {
var votes = {
left: 0,
right: 0,
center: 0,
"": 0,
};
var align = "";
for (var i = 0; i < table.rows.length; ++i) {
var row = table.rows[i];
if (columnIndex < row.childNodes.length) {
var cellAlignment = getAlignment(row.childNodes[columnIndex]);
++votes[cellAlignment];
if (votes[cellAlignment] > votes[align]) {
align = cellAlignment;
}
}
}
return align;
}
function extractTextFromCell(cellNode: HTMLElement): string {
const uiComponentTags = new Set(["BUTTON", "SVG", "INPUT", "SELECT", "TEXTAREA", "FORM"]);
function getTextContent(node: Node): string {
if (node.nodeType === Node.TEXT_NODE) {
return node.textContent || "";
}
if (node.nodeType === Node.ELEMENT_NODE) {
const element = node as HTMLElement;
if (uiComponentTags.has(element.tagName)) {
return "";
}
let text = "";
for (const child of element.childNodes) {
text += getTextContent(child);
}
return text;
}
return "";
}
return getTextContent(cellNode).trim().replace(/\s+/g, " ");
}
rules.tableCell = {
filter: ["th", "td"],
replacement: function (content, node) {
if (tableShouldBeSkipped(nodeParentTable(node))) return content;
// Extract only text content from complex UI components
const cleanContent = extractTextFromCell(node as HTMLElement);
return cell(cleanContent, node);
},
};
rules.tableRow = {
filter: "tr",
replacement: function (content, node) {
const parentTable = nodeParentTable(node);
if (tableShouldBeSkipped(parentTable)) return content;
var borderCells = "";
if (isHeadingRow(node)) {
const colCount = tableColCount(parentTable);
for (var i = 0; i < colCount; i++) {
const childNode = i < node.childNodes.length ? node.childNodes[i] : null;
var border = getBorder(getColumnAlignment(parentTable, i));
borderCells += cell(border, childNode, i);
}
}
return "\n" + content + (borderCells ? "\n" + borderCells : "");
},
};
rules.table = {
filter: function (node: Node, options: any) {
return node.nodeName === "TABLE";
},
replacement: function (content: string, node: Node) {
// Only convert tables that can result in valid Markdown
// Other tables are kept as HTML using `keep` (see below).
if (tableShouldBeHtml(node)) {
return `\n\n${(node as HTMLElement).outerHTML}\n\n`;
} else {
if (tableShouldBeSkipped(node)) return content;
// Ensure there are no blank lines
content = content.replace(/\n+/g, "\n");
// If table has no heading, add an empty one so as to get a valid Markdown table
var secondLine: string[] | string = content.trim().split("\n");
if (secondLine.length >= 2) secondLine = secondLine[1];
var secondLineIsDivider = /\| :?---/.test(secondLine as string);
var columnCount = tableColCount(node);
var emptyHeader = "";
if (columnCount && !secondLineIsDivider) {
emptyHeader = "|" + " |".repeat(columnCount) + "\n" + "|";
for (var columnIndex = 0; columnIndex < columnCount; ++columnIndex) {
emptyHeader += " " + getBorder(getColumnAlignment(node, columnIndex)) + " |";
}
}
const captionContent = (node as HTMLTableElement).caption
? (node as HTMLTableElement).caption?.textContent || ""
: "";
const caption = captionContent ? `${captionContent}\n\n` : "";
const tableContent = `${emptyHeader}${content}`.trimStart();
return `\n\n${caption}${tableContent}\n\n`;
}
},
};
rules.tableCaption = {
filter: ["caption"],
replacement: () => "",
};
rules.tableColgroup = {
filter: ["colgroup", "col"],
replacement: () => "",
};
rules.tableSection = {
filter: ["thead", "tbody", "tfoot"],
replacement: function (content) {
return content;
},
};
// A tr is a heading row if:
// - the parent is a THEAD
// - or if its the first child of the TABLE or the first TBODY (possibly
// following a blank THEAD)
// - and every cell is a TH
function isHeadingRow(tr) {
var parentNode = tr.parentNode;
return (
parentNode.nodeName === "THEAD" ||
(parentNode.firstChild === tr &&
(parentNode.nodeName === "TABLE" || isFirstTbody(parentNode)) &&
every.call(tr.childNodes, function (n) {
return n.nodeName === "TH";
}))
);
}
function isFirstTbody(element) {
var previousSibling = element.previousSibling;
return (
element.nodeName === "TBODY" &&
(!previousSibling ||
(previousSibling.nodeName === "THEAD" && /^\s*$/i.test(previousSibling.textContent)))
);
}
function cell(content: string, node: Node, index: number | null = null) {
if (index === null) index = indexOf.call(node.parentNode?.childNodes, node);
var prefix = " ";
if (index === 0) prefix = "| ";
let filteredContent = content.trim().replace(/\n\r/g, "<br>").replace(/\n/g, "<br>");
filteredContent = filteredContent.replace(/\|+/g, "\\|");
while (filteredContent.length < 3) filteredContent += " ";
if (node) filteredContent = handleColSpan(filteredContent, node, " ");
return prefix + filteredContent + " |";
}
function nodeContainsTable(node) {
if (!node.childNodes) return false;
for (let i = 0; i < node.childNodes.length; i++) {
const child = node.childNodes[i];
if (child.nodeName === "TABLE") return true;
if (nodeContainsTable(child)) return true;
}
return false;
}
const nodeContains = (node: Node, types: string | string[]) => {
if (!node.childNodes) return false;
for (let i = 0; i < node.childNodes.length; i++) {
const child = node.childNodes[i];
if (types === "code" && isCodeBlock(child as HTMLElement)) return true;
if (types.includes(child.nodeName)) return true;
if (nodeContains(child, types)) return true;
}
return false;
};
const tableShouldBeHtml = (tableNode) => {
const possibleTags = ["UL", "OL", "H1", "H2", "H3", "H4", "H5", "H6", "HR", "BLOCKQUOTE"];
// In general we should leave as HTML tables that include other tables. The
// exception is with the Web Clipper when we import a web page with a layout
// that's made of HTML tables. In that case we have this logic of removing the
// outer table and keeping only the inner ones. For the Rich Text editor
// however we always want to keep nested tables.
possibleTags.push("TABLE");
return nodeContains(tableNode, "code") || nodeContains(tableNode, possibleTags);
};
// Various conditions under which a table should be skipped - i.e. each cell
// will be rendered one after the other as if they were paragraphs.
function tableShouldBeSkipped(tableNode) {
const cached = tableShouldBeSkippedCache_.get(tableNode);
if (cached !== undefined) return cached;
const result = tableShouldBeSkipped_(tableNode);
tableShouldBeSkippedCache_.set(tableNode, result);
return result;
}
function tableShouldBeSkipped_(tableNode) {
if (!tableNode) return true;
if (!tableNode.rows) return true;
if (tableNode.rows.length === 1 && tableNode.rows[0].childNodes.length <= 1) return true; // Table with only one cell
if (nodeContainsTable(tableNode)) return true;
return false;
}
function nodeParentTable(node) {
let parent = node.parentNode;
while (parent.nodeName !== "TABLE") {
parent = parent.parentNode;
if (!parent) return null;
}
return parent;
}
function handleColSpan(content, node, emptyChar) {
const colspan = node.getAttribute("colspan") || 1;
for (let i = 1; i < colspan; i++) {
content += " | " + emptyChar.repeat(3);
}
return content;
}
function tableColCount(node) {
let maxColCount = 0;
for (let i = 0; i < node.rows.length; i++) {
const row = node.rows[i];
const colCount = row.childNodes.length;
if (colCount > maxColCount) maxColCount = colCount;
}
return maxColCount;
}
export default function tables(turndownService: TurndownService) {
turndownService.keep(function (node) {
if (node.nodeName === "TABLE" && tableShouldBeHtml(node)) return true;
return false;
});
for (var key in rules) turndownService.addRule(key, rules[key]);
}
|