Skip to content

Commit 8e5dd7c

Browse files
committed
Copy Markdown text to clipboard
1 parent cbeb9b7 commit 8e5dd7c

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

quote-selection.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ export function install(container: Element) {
2222
installed += containers.has(container) ? 0 : 1
2323
containers.set(container, 1)
2424
document.addEventListener('keydown', quoteSelection)
25+
container.addEventListener('copy', onCopy)
2526
}
2627

2728
export function uninstall(container: Element) {
@@ -30,6 +31,29 @@ export function uninstall(container: Element) {
3031
if (!installed) {
3132
document.removeEventListener('keydown', quoteSelection)
3233
}
34+
container.removeEventListener('copy', onCopy)
35+
}
36+
37+
function onCopy(event: ClipboardEvent) {
38+
const target = event.target
39+
if (!(target instanceof HTMLElement)) return
40+
if (isFormField(target)) return
41+
42+
const transfer = event.clipboardData
43+
if (!transfer) return
44+
45+
const selection = window.getSelection()
46+
let range
47+
try {
48+
range = selection.getRangeAt(0)
49+
} catch (err) {
50+
return
51+
}
52+
const quoted = extractQuote(selection.toString(), range)
53+
if (!quoted) return
54+
55+
transfer.setData('text/plain', quoted.selectionText)
56+
event.preventDefault()
3357
}
3458

3559
function eventIsNotRelevant(event: KeyboardEvent): boolean {

0 commit comments

Comments
 (0)