forked from oschmid/roam-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
random-page-plugin.js
86 lines (75 loc) · 2.72 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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;
// insert button into topbar
const topbar = document.querySelector('.roam-topbar .flex-h-box');
const dots = document.querySelector('.roam-topbar div[style="margin-left: 4px;"]');
topbar.insertBefore(randomButton, dots);
}
function addKeyboardShortcut() {
document.onkeyup = 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) goToRandomPage(e);
}
}
function goToRandomPage(e) {
if (isAllPages()) {
clickRandomPageLink(e.shiftKey);
} else if (e.shiftKey) {
goToAllPagesThen(function() {
clickRandomPageLink(e.shiftKey);
history.back();
});
} else {
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];
location.assign('/#/app/' + db + '/page/' + uid);
}
}
function isAllPages() {
return location.hash.endsWith('/search');
}
function goToAllPagesThen(f) {
document.querySelector('.bp3-icon-list').parentNode.parentNode.click();
setTimeout(f, 0);
}
function clickRandomPageLink(shift) {
// https://forum.roamresearch.com/t/what-would-be-your-top-3-tips-for-beginners/255/9
var allPages = document.querySelectorAll('div.rm-pages-title-col a');
var pageLink = getRandomElement(allPages);
getEventHandlers(pageLink).onClick({ shiftKey: shift });
}
function getRandomElement(array) {
return array[Math.floor(Math.random() * array.length)];
}
function getEventHandlers(element) {
for (var prop in element) {
if (prop.includes('reactEventHandlers')) {
return element[prop];
}
}
}
addButton();
addKeyboardShortcut();
}
setTimeout(randomPagePlugin, 1000);