|
| 1 | +export async function copyTableToClipboard(table: string[][]) { |
| 2 | + const textData = table.map(row => row.map(s => s.replace(/[\t\r\n]/g, '')).join('\t')).join('\n') |
| 3 | + |
| 4 | + const htmlTable = document.createElement('table') |
| 5 | + for (const row of table) { |
| 6 | + const htmlRow = document.createElement('tr') |
| 7 | + htmlTable.appendChild(htmlRow) |
| 8 | + for (const cell of row) { |
| 9 | + const htmlCell = document.createElement('td') |
| 10 | + htmlRow.appendChild(htmlCell) |
| 11 | + htmlCell.innerText = cell |
| 12 | + } |
| 13 | + } |
| 14 | + const htmlData = htmlTable.outerHTML |
| 15 | + |
| 16 | + const textBlob = new Blob([textData], { type: 'text/plain' }) |
| 17 | + const htmlBlob = new Blob([htmlData], { type: 'text/html' }) |
| 18 | + |
| 19 | + const clipboardItem = new ClipboardItem({ |
| 20 | + 'text/plain': textBlob, |
| 21 | + 'text/html': htmlBlob, |
| 22 | + }) |
| 23 | + |
| 24 | + await navigator.clipboard.write([clipboardItem]) |
| 25 | +} |
| 26 | + |
| 27 | +export async function pasteTableFromClipboard(): Promise<string[][] | null> { |
| 28 | + try { |
| 29 | + const clipboardItems = await navigator.clipboard.read() |
| 30 | + |
| 31 | + for (const item of clipboardItems) { |
| 32 | + if (item.types.includes('text/html')) { |
| 33 | + const blob = await item.getType('text/html') |
| 34 | + const html = await blob.text() |
| 35 | + return parseHtmlTable(html) |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + for (const item of clipboardItems) { |
| 40 | + if (item.types.includes('text/plain')) { |
| 41 | + const blob = await item.getType('text/plain') |
| 42 | + const text = await blob.text() |
| 43 | + return parseTextTable(text) |
| 44 | + } |
| 45 | + } |
| 46 | + } catch (e) { |
| 47 | + // Ignore error, try readText |
| 48 | + } |
| 49 | + |
| 50 | + try { |
| 51 | + const text = await navigator.clipboard.readText() |
| 52 | + return parseTextTable(text) |
| 53 | + } catch (e) { |
| 54 | + console.error('Failed to read clipboard', e) |
| 55 | + return null |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +function parseHtmlTable(html: string): string[][] { |
| 60 | + const parser = new DOMParser() |
| 61 | + const doc = parser.parseFromString(html, 'text/html') |
| 62 | + const table = doc.querySelector('table') |
| 63 | + |
| 64 | + if (!table) return [] |
| 65 | + |
| 66 | + const data: string[][] = [] |
| 67 | + for (const row of Array.from(table.rows)) { |
| 68 | + const rowData: string[] = [] |
| 69 | + for (const cell of Array.from(row.cells)) { |
| 70 | + rowData.push(cell.innerText) |
| 71 | + } |
| 72 | + data.push(rowData) |
| 73 | + } |
| 74 | + return data |
| 75 | +} |
| 76 | + |
| 77 | +function parseTextTable(text: string): string[][] { |
| 78 | + const rows = text.split(/\r\n|\n|\r/) |
| 79 | + if (rows[rows.length - 1] === '') { |
| 80 | + rows.pop() |
| 81 | + } |
| 82 | + return rows.map(row => row.split('\t')) |
| 83 | +} |
0 commit comments