-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrandom-page-plugin.js
68 lines (60 loc) · 2.3 KB
/
random-page-plugin.js
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
function randomPagePlugin() {
function isMac() {
return window.navigator.platform.startsWith('Mac');
}
// settings
const title = 'Go to random page';
const icon = 'bp3-button bp3-minimal bp3-icon-random pointer bp3-small';
const shortcut = isMac() ? {ctrlKey: true, key: "r"} : {altKey: true, key: "r"};
function addButton() {
// cleanup old versions of the button
var randomButton = document.querySelector('#random-button');
if (randomButton != null) {
randomButton.parentNode.removeChild(randomButton);
}
// create button
var template = document.createElement('template');
template.innerHTML = '<span id="random-button" title="' + title + '" class="' + icon + '"></span>';
template.content.firstChild.onclick = goToRandomPage;
randomButton = template.content.firstChild;
// create spacer
var spacer = document.querySelector('#random-spacer');
if (spacer != null) {
spacer.parentNode.removeChild(spacer);
}
template.innerHTML = '<div id="random-spacer" class="rm-topbar__spacer-sm"></div>';
spacer = template.content.firstChild;
// insert button into topbar
const search = document.querySelector('.rm-topbar .rm-find-or-create-wrapper');
search.insertAdjacentElement('afterend', randomButton);
search.insertAdjacentElement('afterend', spacer);
}
function addKeyboardShortcut() {
document.onkeydown = function(e) {
if (shortcut.ctrlKey && !e.ctrlKey) return;
if (shortcut.shiftKey && !e.shiftKey) return;
if (shortcut.altKey && !e.altKey) return;
if (shortcut.key === e.key.toLowerCase()) {
e.preventDefault();
goToRandomPage(e);
}
}
}
function goToRandomPage(e) {
const allPages = roamAlphaAPI.q('[ :find (pull ?e [:block/uid]) :where [?e :node/title]]');
const page = getRandomElement(allPages);
const uid = page[0].uid;
const db = location.hash.split('/')[2];
if (e.shiftKey) {
roamAlphaAPI.ui.rightSidebar.addWindow({window:{type:'block','block-uid':uid}});
} else {
setTimeout(function(){location.assign('/#/app/' + db + '/page/' + uid);}, 0);
}
}
function getRandomElement(array) {
return array[Math.floor(Math.random() * array.length)];
}
addButton();
addKeyboardShortcut();
}
setTimeout(randomPagePlugin, 0);