This repository has been archived by the owner on Mar 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
paste.jsx
53 lines (40 loc) · 1.44 KB
/
paste.jsx
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
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
export function parseTable(html) {
const el = document.createElement('div');
el.innerHTML = html;
return el.querySelector('table');
}
export function getTable(clipboardData) {
if (Array.from(clipboardData.types).indexOf('text/html') === -1) {
return false;
}
const html = clipboardData.getData('text/html');
if (!(/<table/i).test(html)) {
return false;
}
const table = parseTable(html);
if (!table) {
return false;
}
return table;
}
function columnText(column) {
const noBreakSpace = '\u00A0';
const text = column.textContent.trim().replace(/\|/g, '\\|').replace(/\n/g, ' ');
return text || noBreakSpace;
}
function tableHeaders(row) {
return Array.from(row.querySelectorAll('td, th')).map(columnText);
}
export function formatMarkdownTableMessage(table, message) {
const rows = Array.from(table.querySelectorAll('tr'));
const headers = tableHeaders(rows.shift());
const spacers = headers.map(() => '---');
const header = `|${headers.join(' | ')}|\n|${spacers.join(' | ')}|\n`;
const body = rows.map((row) => {
return `|${Array.from(row.querySelectorAll('td')).map(columnText).join(' | ')}|`;
}).join('\n');
const formattedTable = `${header}${body}\n`;
return message ? `${message}\n\n${formattedTable}` : formattedTable;
}