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
refactor(turndown-plugin-gfm): convert plugin to TypeScript
Elian Doran60b57e021999
diff --git a/packages/turndown-plugin-gfm/package.json b/packages/turndown-plugin-gfm/package.jsonindex 8108fdebf5..1d0c0c7889 100644--- a/packages/turndown-plugin-gfm/package.json+++ b/packages/turndown-plugin-gfm/package.json@@ -5,7 +5,7 @@"author": "Dom Christie","private": true,"type": "module",- "main": "./src/index.js",+ "main": "./src/index.ts","gitHead": "05a29b450962bf05a8642bbd39446a1f679a96ba","license": "MIT","repository": {@@ -27,6 +27,7 @@"devDependencies": {"happy-dom": "20.10.6","turndown": "7.2.4",+ "turnish": "1.12.2","vitest": "4.1.9"}}diff --git a/packages/turndown-plugin-gfm/src/index.js b/packages/turndown-plugin-gfm/src/index.tssimilarity index 100%rename from packages/turndown-plugin-gfm/src/index.jsrename to packages/turndown-plugin-gfm/src/index.tsdiff --git a/packages/turndown-plugin-gfm/src/lib/gfm.js b/packages/turndown-plugin-gfm/src/lib/gfm.tssimilarity index 82%rename from packages/turndown-plugin-gfm/src/lib/gfm.jsrename to packages/turndown-plugin-gfm/src/lib/gfm.tsindex 826b506590..984f1413d4 100644--- a/packages/turndown-plugin-gfm/src/lib/gfm.js+++ b/packages/turndown-plugin-gfm/src/lib/gfm.ts@@ -1,9 +1,11 @@+import type Turnish from "turnish";+import highlightedCodeBlock from './highlighted-code-block.js'import strikethrough from './strikethrough.js'import tables from './tables.js'import taskListItems from './task-list-items.js'-function gfm (turndownService) {+function gfm (turndownService: Turnish) {turndownService.use([highlightedCodeBlock,strikethrough,diff --git a/packages/turndown-plugin-gfm/src/lib/highlighted-code-block.js b/packages/turndown-plugin-gfm/src/lib/highlighted-code-block.tssimilarity index 75%rename from packages/turndown-plugin-gfm/src/lib/highlighted-code-block.jsrename to packages/turndown-plugin-gfm/src/lib/highlighted-code-block.tsindex 97052de574..4b7ec9c45a 100644--- a/packages/turndown-plugin-gfm/src/lib/highlighted-code-block.js+++ b/packages/turndown-plugin-gfm/src/lib/highlighted-code-block.ts@@ -1,17 +1,19 @@+import type Turnish from "turnish";+var highlightRegExp = /highlight-(?:text|source)-([a-z0-9]+)/-export default function highlightedCodeBlock (turndownService) {+export default function highlightedCodeBlock (turndownService: Turnish) {turndownService.addRule('highlightedCodeBlock', {filter: function (node) {var firstChild = node.firstChildreturn (node.nodeName === 'DIV' &&highlightRegExp.test(node.className) &&- firstChild &&+ firstChild != null &&firstChild.nodeName === 'PRE')},- replacement: function (content, node, options) {+ replacement: function (content: string, node, options) {var className = node.className || ''var language = (className.match(highlightRegExp) || [null, ''])[1]diff --git a/packages/turndown-plugin-gfm/src/lib/strikethrough.js b/packages/turndown-plugin-gfm/src/lib/strikethrough.jsdeleted file mode 100644index 9dfb9d7bb2..0000000000--- a/packages/turndown-plugin-gfm/src/lib/strikethrough.js+++ /dev/null@@ -1,8 +0,0 @@-export default function strikethrough (turndownService) {- turndownService.addRule('strikethrough', {- filter: ['del', 's', 'strike'],- replacement: function (content) {- return '~~' + content + '~~'- }- })-}diff --git a/packages/turndown-plugin-gfm/src/lib/strikethrough.ts b/packages/turndown-plugin-gfm/src/lib/strikethrough.tsnew file mode 100644index 0000000000..250c567f5e--- /dev/null+++ b/packages/turndown-plugin-gfm/src/lib/strikethrough.ts@@ -0,0 +1,10 @@+import type Turnish from "turnish";++export default function strikethrough (turndownService: Turnish) {+ turndownService.addRule('strikethrough', {+ filter: ['del', 's', 'strike'],+ replacement: function (content: string) {+ return '~~' + content + '~~'+ }+ })+}diff --git a/packages/turndown-plugin-gfm/src/lib/tables.js b/packages/turndown-plugin-gfm/src/lib/tables.tssimilarity index 78%rename from packages/turndown-plugin-gfm/src/lib/tables.jsrename to packages/turndown-plugin-gfm/src/lib/tables.tsindex c53db57b6a..cf5e95eb71 100644--- a/packages/turndown-plugin-gfm/src/lib/tables.js+++ b/packages/turndown-plugin-gfm/src/lib/tables.ts@@ -1,26 +1,29 @@+import type Turnish from "turnish";+import type { Rule, TurnishOptions } from "turnish";+var indexOf = Array.prototype.indexOfvar every = Array.prototype.every-var rules = {}-var alignMap = { left: ':---', right: '---:', center: ':---:' };+var rules: Record<string, Rule> = {}+var alignMap: Record<string, string> = { left: ':---', right: '---:', center: ':---:' };-let isCodeBlock_ = null;-let options_ = null;+let isCodeBlock_: ((node: Node) => boolean) | null = null;+let options_: TurnishOptions | null = null;// 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();+const tableShouldBeSkippedCache_ = new WeakMap<HTMLTableElement, boolean>();-function getAlignment(node) {+function getAlignment(node: HTMLElement | null): string {return node ? (node.getAttribute('align') || node.style.textAlign || '').toLowerCase() : '';}-function getBorder(alignment) {+function getBorder(alignment: string): string {return alignment ? alignMap[alignment] : '---';}-function getColumnAlignment(table, columnIndex) {- var votes = {+function getColumnAlignment(table: HTMLTableElement, columnIndex: number): string {+ var votes: Record<string, number> = {left: 0,right: 0,center: 0,@@ -32,7 +35,7 @@ function getColumnAlignment(table, columnIndex) {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]);+ var cellAlignment = getAlignment(row.childNodes[columnIndex] as HTMLElement);++votes[cellAlignment];if (votes[cellAlignment] > votes[align]) {@@ -46,7 +49,7 @@ function getColumnAlignment(table, columnIndex) {rules.tableCell = {filter: ['th', 'td'],- replacement: function (content, node) {+ replacement: function (content: string, node) {if (tableShouldBeSkipped(nodeParentTable(node))) return content;return cell(content, node)}@@ -54,9 +57,9 @@ rules.tableCell = {rules.tableRow = {filter: 'tr',- replacement: function (content, node) {+ replacement: function (content: string, node) {const parentTable = nodeParentTable(node);- if (tableShouldBeSkipped(parentTable)) return content;+ if (!parentTable || tableShouldBeSkipped(parentTable)) return content;var borderCells = ''@@ -73,11 +76,11 @@ rules.tableRow = {}rules.table = {- filter: function (node, options) {+ filter: function (node) {return node.nodeName === 'TABLE';},- replacement: function (content, node) {+ replacement: function (content: string, node) {// Only convert tables that can result in valid Markdown// Other tables are kept as HTML using `keep` (see below).if (tableShouldBeHtml(node, options_)) {@@ -111,7 +114,7 @@ rules.tableColgroup = {rules.tableSection = {filter: ['thead', 'tbody', 'tfoot'],- replacement: function (content) {+ replacement: function (content: string) {return content}}@@ -121,8 +124,9 @@ rules.tableSection = {// - 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) {+function isHeadingRow (tr: Node): boolean {var parentNode = tr.parentNode+ if (!parentNode) return false;return (parentNode.nodeName === 'THEAD' ||(@@ -133,14 +137,14 @@ function isHeadingRow (tr) {)}-function isFirstTbody (element) {+function isFirstTbody (element: Node): boolean {var previousSibling = element.previousSiblingreturn (element.nodeName === 'TBODY' && (!previousSibling ||(previousSibling.nodeName === 'THEAD' &&- /^\s*$/i.test(previousSibling.textContent)+ /^\s*$/i.test(previousSibling.textContent || ''))))@@ -149,7 +153,7 @@ function isFirstTbody (element) {// Format table cells following MD060 compact style:// Each cell has 1 space padding on left and right (prefix + content + ' |').// Empty cells result in 2 spaces between pipes (1 left + 1 right padding).-function cell (content, node = null, index = null) {+function cell (content: string, node: any = null, index: number | null = null): string {if (index === null) index = indexOf.call(node.parentNode.childNodes, node)var prefix = ' 'if (index === 0) prefix = '| '@@ -159,7 +163,7 @@ function cell (content, node = null, index = null) {return prefix + filteredContent + ' |'}-function nodeContainsTable(node) {+function nodeContainsTable(node: Node): boolean {if (!node.childNodes) return false;for (let i = 0; i < node.childNodes.length; i++) {@@ -170,7 +174,7 @@ function nodeContainsTable(node) {return false;}-const nodeContains = (node, types) => {+const nodeContains = (node: Node, types: string | string[]): boolean => {if (!node.childNodes) return false;for (let i = 0; i < node.childNodes.length; i++) {@@ -183,7 +187,7 @@ const nodeContains = (node, types) => {return false;}-const tableShouldBeHtml = (tableNode, options) => {+const tableShouldBeHtml = (tableNode: any, options: TurnishOptions | null): boolean => {const possibleTags = ['UL','OL',@@ -203,7 +207,7 @@ const tableShouldBeHtml = (tableNode, options) => {// 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.- if (options.preserveNestedTables) possibleTags.push('TABLE');+ if (options?.preserveNestedTables) possibleTags.push('TABLE');return nodeContains(tableNode, 'code') ||nodeContains(tableNode, possibleTags) ||@@ -219,13 +223,15 @@ const tableShouldBeHtml = (tableNode, options) => {// parent is a THEAD, or it is the first row and every cell is a TH). This is the// row that produces the Markdown divider line; without it the table has no// header and must be kept as HTML.-function tableHasHeadingRow(tableNode) {+function tableHasHeadingRow(tableNode: HTMLTableElement): boolean {return !!tableNode.rows && tableNode.rows.length > 0 && isHeadingRow(tableNode.rows[0]);}// 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) {+function tableShouldBeSkipped(tableNode: HTMLTableElement | null): boolean {+ if (!tableNode) return true;+const cached = tableShouldBeSkippedCache_.get(tableNode);if (cached !== undefined) return cached;@@ -235,7 +241,7 @@ function tableShouldBeSkipped(tableNode) {return result;}-function tableShouldBeSkipped_(tableNode) {+function tableShouldBeSkipped_(tableNode: HTMLTableElement | null): boolean {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@@ -243,25 +249,23 @@ function tableShouldBeSkipped_(tableNode) {return false;}-function nodeParentDiv(node) {+function nodeParentDiv(node: Node): HTMLElement | null {let parent = node.parentNode;- while (parent.nodeName !== 'DIV') {+ while (parent && parent.nodeName !== 'DIV') {parent = parent.parentNode;- if (!parent) return null;}- return parent;+ return parent as HTMLElement | null;}-function nodeParentTable(node) {+function nodeParentTable(node: Node): HTMLTableElement | null {let parent = node.parentNode;- while (parent.nodeName !== 'TABLE') {+ while (parent && parent.nodeName !== 'TABLE') {parent = parent.parentNode;- if (!parent) return null;}- return parent;+ return parent as HTMLTableElement | null;}-function handleColSpan(content, node, emptyChar) {+function handleColSpan(content: string, node: any, emptyChar: string): string {const colspan = node.getAttribute('colspan') || 1;for (let i = 1; i < colspan; i++) {content += ' |' + emptyChar;@@ -269,7 +273,7 @@ function handleColSpan(content, node, emptyChar) {return content}-function tableColCount(node) {+function tableColCount(node: HTMLTableElement): number {let maxColCount = 0;for (let i = 0; i < node.rows.length; i++) {const row = node.rows[i]@@ -291,18 +295,18 @@ var TABLE_CONTAINER_TAGS = ['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR', 'COLGROUP'// lines are produced, so the result stays a single raw-HTML block on reimport.// Inter-element whitespace text nodes are dropped, which makes the output stable// across repeated export/import cycles.-function prettyPrintTable(node) {+function prettyPrintTable(node: Element): string {return serializeStructuralNode(node, 0);}-function serializeStructuralNode(node, depth) {+function serializeStructuralNode(node: Element, depth: number): string {const indent = ' '.repeat(depth);const closeTag = '</' + node.nodeName.toLowerCase() + '>';// Use the DOM's own serializer for the opening tag so attribute quoting/escaping// matches the rest of the output. A shallow clone has no children, so its// outerHTML is exactly the opening tag plus (for non-void elements) the closing tag.- const shallowHtml = node.cloneNode(false).outerHTML;+ const shallowHtml = (node.cloneNode(false) as Element).outerHTML;const isVoid = !shallowHtml.endsWith(closeTag);const openTag = isVoid ? shallowHtml : shallowHtml.slice(0, shallowHtml.length - closeTag.length);@@ -315,15 +319,15 @@ function serializeStructuralNode(node, depth) {for (let i = 0; i < node.childNodes.length; i++) {const child = node.childNodes[i];if (child.nodeType === 1) { // ELEMENT_NODE — whitespace-only text nodes are skipped- lines.push(serializeStructuralNode(child, depth + 1));+ lines.push(serializeStructuralNode(child as Element, depth + 1));}}lines.push(indent + closeTag);return lines.join('\n');}-export default function tables (turndownService) {- isCodeBlock_ = turndownService.isCodeBlock;+export default function tables (turndownService: Turnish) {+ isCodeBlock_ = (turndownService as any).isCodeBlock ?? null;options_ = turndownService.options;turndownService.keep(function (node) {diff --git a/packages/turndown-plugin-gfm/src/lib/task-list-items.js b/packages/turndown-plugin-gfm/src/lib/task-list-items.jsdeleted file mode 100644index 55d4b853b9..0000000000--- a/packages/turndown-plugin-gfm/src/lib/task-list-items.js+++ /dev/null@@ -1,10 +0,0 @@-export default function taskListItems (turndownService) {- turndownService.addRule('taskListItems', {- filter: function (node) {- return node.type === 'checkbox' && node.parentNode.nodeName === 'LI'- },- replacement: function (content, node) {- return (node.checked ? '[x]' : '[ ]') + ' '- }- })-}diff --git a/packages/turndown-plugin-gfm/src/lib/task-list-items.ts b/packages/turndown-plugin-gfm/src/lib/task-list-items.tsnew file mode 100644index 0000000000..a1e6fe5843--- /dev/null+++ b/packages/turndown-plugin-gfm/src/lib/task-list-items.ts@@ -0,0 +1,12 @@+import type Turnish from "turnish";++export default function taskListItems (turndownService: Turnish) {+ turndownService.addRule('taskListItems', {+ filter: function (node) {+ return (node as HTMLInputElement).type === 'checkbox' && node.parentNode?.nodeName === 'LI'+ },+ replacement: function (content: string, node) {+ return (node.checked ? '[x]' : '[ ]') + ' '+ }+ })+}diff --git a/packages/turndown-plugin-gfm/src/lib/turndown-plugin-gfm.js b/packages/turndown-plugin-gfm/src/lib/turndown-plugin-gfm.jsdeleted file mode 100644index f8218690c1..0000000000--- a/packages/turndown-plugin-gfm/src/lib/turndown-plugin-gfm.js+++ /dev/null@@ -1,3 +0,0 @@-export function turndownPluginGfm() {- return 'turndown-plugin-gfm';-}diff --git a/packages/turndown-plugin-gfm/src/lib/turndown-plugin-gfm.ts b/packages/turndown-plugin-gfm/src/lib/turndown-plugin-gfm.tsnew file mode 100644index 0000000000..3dc83b6d51--- /dev/null+++ b/packages/turndown-plugin-gfm/src/lib/turndown-plugin-gfm.ts@@ -0,0 +1,3 @@+export function turndownPluginGfm(): string {+ return 'turndown-plugin-gfm';+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e468ac2c42..392b87efd6 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1705,6 +1705,9 @@ importers:turndown:specifier: 7.2.4version: 7.2.4+ turnish:+ specifier: 1.12.2+ version: 1.12.2vitest:specifier: 4.1.9version: 4.1.9(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))