forked from NomarCub/obsidian-copy-url-in-preview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
72 lines (64 loc) · 1.64 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import {
Menu, Plugin, Notice, MenuItem
} from "obsidian";
interface Listener {
(this: Document, ev: Event): any;
}
function onElement(
el: Document,
event: keyof HTMLElementEventMap,
selector: string,
listener: Listener,
options?: { capture?: boolean; }
) {
el.on(event, selector, listener, options);
return () => el.off(event, selector, listener, options);
}
export default class CopyUrlInPreview extends Plugin {
onload() {
this.register(
onElement(
document,
"contextmenu" as keyof HTMLElementEventMap,
"a.external-link",
this.onClick.bind(this)
)
);
}
// Android gives a PointerEvent, a child to MouseEvent.
// Positions are not accurate from PointerEvent.
// There's also TouchEvent
// The event has target, path, toEvent (null on Android) for finding the link
onClick(event: MouseEvent) {
if (!(event.target instanceof HTMLAnchorElement)) {
return;
}
event.preventDefault();
let link = event.target.href;
const menu = new Menu(this.app);
menu.addItem((item: MenuItem) =>
item.setIcon("link")
.setTitle("Copy url")
.onClick(() => {
navigator.clipboard.writeText(link);
new Notice("Url copied to your clipboard");
})
);
menu.register(
onElement(
document,
"keydown" as keyof HTMLElementEventMap,
"*",
(e: KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
menu.hide();
}
}
)
);
menu.showAtPosition({ x: event.pageX, y: event.pageY });
this.app.workspace.trigger("copy-url-in-preview:contextmenu", menu);
}
}