m->d: render tables

This commit is contained in:
Cadence Ember 2025-06-09 12:07:11 +12:00
parent 65a591e924
commit 890e80854f
2 changed files with 57 additions and 0 deletions

View file

@ -154,6 +154,27 @@ turndownService.addRule("listItem", {
}
})
turndownService.addRule("table", {
filter: "table",
replacement: function (content, node, options) {
const trs = node.querySelectorAll("tr").cache
/** @type {{text: string, tag: string}[][]} */
const tableText = trs.map(tr => [...tr.querySelectorAll("th, td")].map(cell => ({text: cell.textContent, tag: cell.tagName})))
const tableTextByColumn = tableText[0].map((col, i) => tableText.map(row => row[i]))
const columnWidths = tableTextByColumn.map(col => Math.max(...col.map(cell => cell.text.length)))
const resultRows = tableText.map((row, rowIndex) =>
row.map((cell, colIndex) =>
cell.text.padEnd(columnWidths[colIndex])
).join(" ")
)
const tableHasHeader = tableText[0].slice(1).some(cell => cell.tag === "TH")
if (tableHasHeader) {
resultRows.splice(1, 0, "-".repeat(columnWidths.reduce((a, c) => a + c + 2)))
}
return "```\n" + resultRows.join("\n") + "```"
}
})
/** @type {string[]} SPRITE SHEET EMOJIS FEATURE: mxc urls for the currently processing message */
let endOfMessageEmojis = []
turndownService.addRule("emoji", {

View file

@ -4537,6 +4537,42 @@ test("event2message: @room in the middle of a link is not converted", async t =>
)
})
test("event2message: table", async t => {
t.deepEqual(
await eventToMessage({
type: "m.room.message",
sender: "@cadence:cadence.moe",
content: {
msgtype: "m.text",
body: "wrong body",
format: "org.matrix.custom.html",
formatted_body: "content<table><thead><tr><th>Col 1</th><th>Col 2</th><th>Col 3</th></tr></thead><tbody><tr><th>Apple</th><td>Banana</td><td>Cherry</td></tr><tr><th>Aardvark</th><td>Bee</td><td>Crocodile</td></tr><tr><td>Argon</td><td>Boron</td><td>Carbon</td></tr></tbody></table>more content"
},
room_id: "!kLRqKKUQXcibIMtOpl:cadence.moe",
event_id: "$SiXetU9h9Dg-M9Frcw_C6ahnoXZ3QPZe3MVJR5tcB9A"
}),
{
messagesToDelete: [],
messagesToEdit: [],
messagesToSend: [{
username: "cadence [they]",
content: "content```"
+ "\nCol 1 Col 2 Col 3 "
+ "\n---------------------------"
+ "\nApple Banana Cherry "
+ "\nAardvark Bee Crocodile"
+ "\nArgon Boron Carbon ```"
+ "more content",
avatar_url: undefined,
allowed_mentions: {
parse: ["users", "roles"]
}
}],
ensureJoined: []
}
)
})
slow()("event2message: unknown emoji at the end is reuploaded as a sprite sheet", async t => {
const messages = await eventToMessage({
type: "m.room.message",