Skip to content

Commit

Permalink
fix: fix pasting not working for invalid tables and fix pasting table…
Browse files Browse the repository at this point in the history
… when there is a trailing newline (#20)
  • Loading branch information
imballinst authored Oct 30, 2022
1 parent 458d5d7 commit 6d1d398
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/components/Editor/MarkdownEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
18 changes: 15 additions & 3 deletions src/utils/parsers/table.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ describe('parseTableFromTabbedText', () => {
const str = `
hello\tworld
this is an invalid table
`.trim()
`

expect(parseTableFromTabbedText(str)).toBe(undefined)
})
Expand All @@ -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|
Expand All @@ -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|
Expand Down
6 changes: 3 additions & 3 deletions src/utils/parsers/table.ts
Original file line number Diff line number Diff line change
@@ -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')
}

0 comments on commit 6d1d398

Please sign in to comment.