From 6d1d398593ed05b742b6f5c4778be8e049ec160f Mon Sep 17 00:00:00 2001 From: Try Ajitiono Date: Sun, 30 Oct 2022 11:29:12 +0700 Subject: [PATCH] fix: fix pasting not working for invalid tables and fix pasting table when there is a trailing newline (#20) --- src/components/Editor/MarkdownEditor.tsx | 2 +- src/utils/parsers/table.test.ts | 18 +++++++++++++++--- src/utils/parsers/table.ts | 6 +++--- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/components/Editor/MarkdownEditor.tsx b/src/components/Editor/MarkdownEditor.tsx index f8625e9..648c999 100644 --- a/src/components/Editor/MarkdownEditor.tsx +++ b/src/components/Editor/MarkdownEditor.tsx @@ -194,10 +194,10 @@ export const MarkdownEditor = () => { setMarkdown(nextValue); }} onPaste={(e) => { - e.preventDefault(); const pasted = e.clipboardData?.getData('text/plain'); const parseResult = parseTableFromTabbedText(pasted); if (parseResult) { + e.preventDefault(); const selectionStart = e.currentTarget.selectionStart; setMarkdown((prev) => prev.slice(0, selectionStart).concat(parseResult).concat(prev.slice(selectionStart)) diff --git a/src/utils/parsers/table.test.ts b/src/utils/parsers/table.test.ts index fbc4017..613eece 100644 --- a/src/utils/parsers/table.test.ts +++ b/src/utils/parsers/table.test.ts @@ -18,7 +18,7 @@ describe('parseTableFromTabbedText', () => { const str = ` hello\tworld this is an invalid table - `.trim() + ` expect(parseTableFromTabbedText(str)).toBe(undefined) }) @@ -27,7 +27,19 @@ this is an invalid table const str = ` hello\tworld this is a valid table\they! - `.trim() + ` + + expect(parseTableFromTabbedText(str)).toBe(` +|hello|world| +|this is a valid table|hey!| + `.trim()) + }) + + test('valid case: with trailing newline', () => { + const str = ` +hello\tworld +this is a valid table\they! + ` expect(parseTableFromTabbedText(str)).toBe(` |hello|world| @@ -39,7 +51,7 @@ this is a valid table\they! const str = ` hello\tworld this is a | valid table\they! - `.trim() + ` expect(parseTableFromTabbedText(str)).toBe(` |hello|world| diff --git a/src/utils/parsers/table.ts b/src/utils/parsers/table.ts index d6c7714..efe1c95 100644 --- a/src/utils/parsers/table.ts +++ b/src/utils/parsers/table.ts @@ -1,10 +1,10 @@ export function parseTableFromTabbedText(text: string | undefined): string | undefined { if (!text) return undefined - const lines = text.split('\n') - const tabCountPerLine = lines.map(line => line.match(/\t/g)?.length || 0) + const lines = text.trim().split('\n') + const tabCountPerLine = lines.map(line => line.match(/\t+/g)?.length || 0) const allLinesHaveEqualTabCount = tabCountPerLine.every(tabCount => tabCount === tabCountPerLine[0] && tabCount > 0) if (!allLinesHaveEqualTabCount) return undefined - return lines.map(line => `|${line.replace(/\|/g, '\\|').replace(/\t/g, '|')}|`).join('\n') + return lines.map(line => `|${line.replace(/\|/g, '\\|').replace(/\t+/g, '|')}|`).join('\n') } \ No newline at end of file