Skip to content

Commit 01f8047

Browse files
committed
Paste markdown text from clipboard
Pastes markdown formatted text from the clipboard with the custom text/x-gfm mime type if available. Pairs with`@github/quote-selection` which copies the text/x-gfm data onto the clipboard.
1 parent 9475829 commit 01f8047

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

src/index.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import {install as installLink, uninstall as uninstallLink} from './paste-markdown-image-link'
44
import {install as installTable, uninstall as uninstallTable} from './paste-markdown-table'
5+
import {install as installText, uninstall as uninstallText} from './paste-markdown-text'
56

67
type Subscription = {|
78
unsubscribe: () => void
@@ -10,11 +11,13 @@ type Subscription = {|
1011
export default function subscribe(el: Element): Subscription {
1112
installTable(el)
1213
installLink(el)
14+
installText(el)
1315

1416
return {
1517
unsubscribe: () => {
1618
uninstallTable(el)
1719
uninstallLink(el)
20+
uninstallText(el)
1821
}
1922
}
2023
}

src/paste-markdown-text.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/* @flow strict */
2+
3+
import {insertText} from './text'
4+
5+
export function install(el: Element) {
6+
el.addEventListener('paste', onPaste)
7+
}
8+
9+
export function uninstall(el: Element) {
10+
el.removeEventListener('paste', onPaste)
11+
}
12+
13+
function onPaste(event: ClipboardEvent) {
14+
const transfer = event.clipboardData
15+
if (!transfer || !hasMarkdown(transfer)) return
16+
17+
const field = event.currentTarget
18+
if (!(field instanceof HTMLTextAreaElement)) return
19+
20+
const text = transfer.getData('text/x-gfm')
21+
if (!text) return
22+
23+
event.stopPropagation()
24+
event.preventDefault()
25+
26+
insertText(field, text)
27+
}
28+
29+
function hasMarkdown(transfer: DataTransfer): boolean {
30+
return Array.from(transfer.types).indexOf('text/x-gfm') >= 0
31+
}

0 commit comments

Comments
 (0)