-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathjumpNav.tsx
More file actions
632 lines (625 loc) · 20.4 KB
/
jumpNav.tsx
File metadata and controls
632 lines (625 loc) · 20.4 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
import { get } from "../settings";
import getFirstChildUidByBlockUid from "roamjs-components/queries/getFirstChildUidByBlockUid";
import getCurrentUserUid from "roamjs-components/queries/getCurrentUserUid";
import getShallowTreeByParentUid from "roamjs-components/queries/getShallowTreeByParentUid";
import openBlockInSidebar from "roamjs-components/writes/openBlockInSidebar";
import getOrderByBlockUid from "roamjs-components/queries/getOrderByBlockUid";
import createBlock from "roamjs-components/writes/createBlock";
import getParentUidByBlockUid from "roamjs-components/queries/getParentUidByBlockUid";
import getNthChildUidByBlockUid from "roamjs-components/queries/getNthChildUidByBlockUid";
import getChildrenLengthByParentUid from "roamjs-components/queries/getChildrenLengthByParentUid";
import deleteBlock from "roamjs-components/writes/deleteBlock";
import updateBlock from "roamjs-components/writes/updateBlock";
import { render as renderToast } from "roamjs-components/components/Toast";
import createHTMLObserver from "roamjs-components/dom/createHTMLObserver";
import { BLOCK_REF_REGEX } from "roamjs-components/dom/constants";
import extractRef from "roamjs-components/util/extractRef";
import type {
InputTextNode,
OnloadArgs,
PullBlock,
RoamBasicNode,
} from "roamjs-components/types/native";
import getTextByBlockUid from "roamjs-components/queries/getTextByBlockUid";
import getBasicTreeByParentUid from "roamjs-components/queries/getBasicTreeByParentUid";
import renderOverlay, {
RoamOverlayProps,
} from "roamjs-components/util/renderOverlay";
import { Dialog, Spinner } from "@blueprintjs/core";
import React, { useMemo, useState, useEffect } from "react";
import { addCommand } from "./workBench";
const getCurrentPageUid = async () =>
(await window.roamAlphaAPI.ui.mainWindow.getOpenPageOrBlockUid()) ||
window.roamAlphaAPI.util.dateToPageUid(new Date());
const toUidTree = (tree: RoamBasicNode[]): RoamBasicNode[] =>
tree.map((t) => ({
text: `((${t.uid}))`,
children: toUidTree(t.children),
uid: window.roamAlphaAPI.util.generateUID(),
}));
const stripUid = (tree: RoamBasicNode[]): InputTextNode[] =>
tree.map(({ uid: _, children, ...t }) => ({
...t,
children: stripUid(children),
}));
const getMaxLevel = (n: RoamBasicNode[]): number => {
if (n.length)
return (
n
.map((n) => getMaxLevel(n.children))
.reduce((p, c) => (p > c ? p : c), 0) + 1
);
else return 1;
};
const ExpColDialog = ({
blockUid,
onClose,
}: RoamOverlayProps<{ blockUid: string }>) => {
const tree = useMemo(() => getBasicTreeByParentUid(blockUid), [blockUid]);
const level = getMaxLevel(tree);
const [loading, setLoading] = useState(false);
useEffect(() => {
const listener = (e: KeyboardEvent) => {
const digit = Number(e.key);
if (digit && digit <= level) {
document.removeEventListener("keydown", listener);
const getNodes = (
ns: RoamBasicNode[],
l: number
): { uid: string; within: boolean }[] => {
return ns.flatMap((n) => [
{ uid: n.uid, within: l < digit },
...getNodes(n.children, l + 1),
]);
};
const nodes = getNodes(tree, 2).concat({
uid: blockUid,
within: digit > 1,
});
setLoading(true);
Promise.all(
nodes.map((n) => updateBlock({ uid: n.uid, open: n.within }))
).then(onClose);
}
};
document.addEventListener("keydown", listener);
}, []);
return (
<Dialog
title={"Expand/Collapse all blocks to level"}
isOpen={true}
onClose={onClose}
enforceFocus={false}
autoFocus={false}
>
<div tabIndex={-1} style={{ padding: 16, minHeight: 120 }}>
<input autoFocus style={{ visibility: "hidden" }} />
<div
style={{
display: "flex",
justifyContent: "space-between",
width: "100%",
}}
>
{level &&
Array(level)
.fill(null)
.map((_, l) => (
<span
key={l}
style={{
padding: 16,
borderRadius: 8,
background: "white",
margin: "0px 16px",
}}
>
{l + 1}
</span>
))}
</div>
</div>
{loading && <Spinner />}
</Dialog>
);
};
const jumpToTheTopOfThePage = () =>
getCurrentPageUid().then((uid) => {
const blockUid = getFirstChildUidByBlockUid(uid);
setTimeout(() => {
window.roamAlphaAPI.ui.setBlockFocusAndSelection({
location: {
"block-uid": blockUid,
"window-id": `${getCurrentUserUid()}-body-outline-${uid}`,
},
});
}, 300);
});
const jumpToTheBottomOfPage = () =>
getCurrentPageUid().then((uid) => {
const blocks = getShallowTreeByParentUid(uid);
const blockUid = blocks[blocks.length - 1]?.uid;
if (blockUid)
setTimeout(() => {
window.roamAlphaAPI.ui.setBlockFocusAndSelection({
location: {
"block-uid": blockUid,
"window-id": `${getCurrentUserUid()}-body-outline-${uid}`,
},
});
}, 300);
});
const expandAllBlocksOnPage = async () => {
const uid = await getCurrentPageUid();
window.roamAlphaAPI.updateBlock({ block: { uid, open: true } });
(
window.roamAlphaAPI.q(
`[:find (pull ?p [:block/uid]) :where [?b :block/uid "${uid}"] [?p :block/parents ?b]]`
) as [{ uid: string }][]
)
.map((a) => a[0].uid)
.forEach((u) =>
window.roamAlphaAPI.updateBlock({ block: { uid: u, open: true } })
);
};
const collapseAllBlocksOnPage = async () => {
const uid = await getCurrentPageUid();
window.roamAlphaAPI.updateBlock({ block: { uid, open: false } });
(
window.roamAlphaAPI.q(
`[:find (pull ?p [:block/uid]) :where [?b :block/uid "${uid}"] [?p :block/parents ?b]]`
) as [{ uid: string }][]
)
.map((a) => a[0].uid)
.forEach((u) =>
window.roamAlphaAPI.updateBlock({
block: { uid: u, open: false },
})
);
};
const openPageInSidebar = () => getCurrentPageUid().then(openBlockInSidebar);
const toggleLinkedRefs = () => {
(
document.querySelector(".rm-reference-container .rm-caret") as HTMLElement
).click();
document.querySelector(".rm-reference-container .rm-caret").scrollIntoView();
};
const toggleUnlinkedRefs = () => {
(
document.querySelector(
".rm-reference-main > div > div:nth-child(2) > div > span > span"
) as HTMLElement
).click();
document
.querySelector(
".rm-reference-main > div > div:nth-child(2) > div > span > span"
)
.scrollIntoView();
};
const toggleReferenceParents = () =>
document
.querySelectorAll<HTMLElement>(
".rm-title-arrow-wrapper .bp3-icon-caret-down"
)
.forEach((element) => {
element.click();
});
const expandReferenceChildren = () =>
document
.querySelectorAll<HTMLElement>(".rm-reference-item .block-expand")
.forEach((element) => {
element.dispatchEvent(
new MouseEvent("contextmenu", {
bubbles: true,
})
);
const li = Array.from(
document.querySelector(".bp3-popover-content > div> ul").children
).find((e: HTMLLinkElement) => e.innerText === "Expand all");
(li?.childNodes[0] as HTMLElement).click();
});
const collapseReferenceChildren = () =>
document
.querySelectorAll<HTMLElement>(".rm-reference-item .block-expand")
.forEach((element) => {
element.dispatchEvent(
new MouseEvent("contextmenu", {
bubbles: true,
})
);
const li = Array.from(
document.querySelector(".bp3-popover-content > div> ul").children
).find((e: HTMLLinkElement) => e.innerText === "Collapse all");
(li?.childNodes[0] as HTMLElement).click();
});
const expandCurrentBlockTree = () => {
const uid = window.roamAlphaAPI.ui.getFocusedBlock()?.["block-uid"];
if (uid) {
window.roamAlphaAPI.updateBlock({ block: { uid, open: true } });
(
window.roamAlphaAPI.q(
`[:find (pull ?p [:block/uid]) :where [?b :block/uid "${uid}"] [?p :block/parents ?b]]`
) as [{ uid: string }][]
)
.map((a) => a[0].uid)
.forEach((u) =>
window.roamAlphaAPI.updateBlock({ block: { uid: u, open: true } })
);
}
};
const collapseCurrentBlockTree = () => {
const uid = window.roamAlphaAPI.ui.getFocusedBlock()?.["block-uid"];
if (uid) {
window.roamAlphaAPI.updateBlock({ block: { uid, open: false } });
(
window.roamAlphaAPI.q(
`[:find (pull ?p [:block/uid]) :where [?b :block/uid "${uid}"] [?p :block/parents ?b]]`
) as [{ uid: string }][]
)
.map((a) => a[0].uid)
.forEach((u) =>
window.roamAlphaAPI.updateBlock({
block: { uid: u, open: false },
})
);
}
};
const insertBlockAbove = () => {
const location = window.roamAlphaAPI.ui.getFocusedBlock();
const uid = location?.["block-uid"];
if (uid) {
const order = getOrderByBlockUid(uid);
createBlock({
order,
parentUid: getParentUidByBlockUid(uid),
node: { text: "" },
}).then((newUid) => {
setTimeout(() => {
window.roamAlphaAPI.ui.setBlockFocusAndSelection({
location: {
"window-id": location["window-id"],
"block-uid": newUid,
},
});
}, 300);
});
}
};
const insertBlockBelow = () => {
const location = window.roamAlphaAPI.ui.getFocusedBlock();
const uid = location?.["block-uid"];
if (uid) {
const order = getOrderByBlockUid(uid) + 1;
createBlock({
order,
parentUid: getParentUidByBlockUid(uid),
node: { text: "" },
}).then((newUid) => {
setTimeout(() => {
window.roamAlphaAPI.ui.setBlockFocusAndSelection({
location: { "window-id": location["window-id"], "block-uid": newUid },
});
}, 300);
});
}
};
const goUpBlock = () => {
const active = window.roamAlphaAPI.ui.getFocusedBlock();
if (active) {
const order = getOrderByBlockUid(active["block-uid"]);
if (order > 0) {
const parentUid = getParentUidByBlockUid(active["block-uid"]);
const newBlockUid = getNthChildUidByBlockUid({
blockUid: parentUid,
order: order - 1,
});
setTimeout(() => {
window.roamAlphaAPI.ui.setBlockFocusAndSelection({
location: {
"window-id": active["window-id"],
"block-uid": newBlockUid,
},
});
}, 300);
}
}
};
const goDownBlock = () => {
const active = window.roamAlphaAPI.ui.getFocusedBlock();
if (active) {
const order = getOrderByBlockUid(active["block-uid"]);
const parentUid = getParentUidByBlockUid(active["block-uid"]);
const len = getChildrenLengthByParentUid(parentUid);
if (order < len - 1) {
const newBlockUid = getNthChildUidByBlockUid({
blockUid: parentUid,
order: order + 1,
});
setTimeout(() => {
window.roamAlphaAPI.ui.setBlockFocusAndSelection({
location: {
"window-id": active["window-id"],
"block-uid": newBlockUid,
},
});
}, 300);
}
}
};
const goToParentBlock = () => {
const active = window.roamAlphaAPI.ui.getFocusedBlock();
if (active) {
const parentUid = getParentUidByBlockUid(active["block-uid"]);
const isPage = !window.roamAlphaAPI.pull("[:block/page]", [
":block/uid",
parentUid,
])?.[":block/page"];
if (!isPage) {
setTimeout(() => {
window.roamAlphaAPI.ui.setBlockFocusAndSelection({
location: {
"window-id": active["window-id"],
"block-uid": parentUid,
},
});
}, 300);
}
}
};
const delBlock = () => {
const active = window.roamAlphaAPI.ui.getFocusedBlock();
if (active) {
deleteBlock(active["block-uid"]);
}
};
const alignLeft = () => {
const active = window.roamAlphaAPI.ui.getFocusedBlock();
if (active) {
updateBlock({ uid: active["block-uid"], textAlign: "left" });
}
};
const center = () => {
const active = window.roamAlphaAPI.ui.getFocusedBlock();
if (active) {
updateBlock({ uid: active["block-uid"], textAlign: "center" });
}
};
const alignRight = () => {
const active = window.roamAlphaAPI.ui.getFocusedBlock();
if (active) {
updateBlock({ uid: active["block-uid"], textAlign: "right" });
}
};
const justify = () => {
const active = window.roamAlphaAPI.ui.getFocusedBlock();
if (active) {
updateBlock({ uid: active["block-uid"], textAlign: "justify" });
}
};
const toggleQueries = () =>
document
.querySelectorAll<HTMLDivElement>(".rm-query-title .bp3-icon-caret-down")
.forEach((element) => {
element.click();
});
const addShortcutToLeftSidebar = () => {
const previousElement = document.activeElement as HTMLElement;
const emptyShortcuts = document.getElementsByClassName(
"bp3-button bp3-icon-star-empty"
) as HTMLCollectionOf<HTMLSpanElement>;
const shortcuts = document.getElementsByClassName(
"bp3-button bp3-icon-star"
) as HTMLCollectionOf<HTMLSpanElement>;
if (emptyShortcuts.length) {
emptyShortcuts[0].click();
previousElement?.focus();
} else if (shortcuts.length) {
shortcuts[0]?.click();
previousElement?.focus();
}
};
const pasteBlockWithChildrenAsReferences = () => {
const uid = window.roamAlphaAPI.ui.getFocusedBlock()?.["block-uid"];
if (uid) {
window.navigator.clipboard.readText().then((clip) => {
const srcUid = extractRef(clip);
const tree = getBasicTreeByParentUid(srcUid);
window.roamAlphaAPI.updateBlock({
block: { uid, string: `${getTextByBlockUid(uid)}((${srcUid}))` },
});
toUidTree(tree).forEach((t, order) =>
createBlock({ parentUid: uid, node: t, order })
);
});
}
};
const toggleBlockViewType = () => {
const uid = window.roamAlphaAPI.ui.getFocusedBlock()?.["block-uid"];
if (uid) {
const viewType = (
window.roamAlphaAPI.data.fast.q(
`[:find (pull ?b [:children/view-type]) :where [?b :block/uid "${uid}"]]`
)[0]?.[0] as PullBlock
)?.[":children/view-type"];
const newViewType =
viewType === ":document"
? "numbered"
: viewType === ":numbered"
? "bullet"
: "document";
window.roamAlphaAPI.updateBlock({
block: { uid, "children-view-type": newViewType },
});
}
};
const replaceLastReferenceWithTextAndAlias = () => {
const uid = window.roamAlphaAPI.ui.getFocusedBlock()?.["block-uid"];
if (uid) {
const text = getTextByBlockUid(uid);
const allRefs = Array.from(text.matchAll(new RegExp(BLOCK_REF_REGEX, "g")));
if (allRefs.length) {
const latestMatch = allRefs.findIndex(
(r) =>
r.index >
(document.activeElement as HTMLTextAreaElement).selectionStart
);
const refMatch = latestMatch <= 0 ? allRefs[0] : allRefs[latestMatch - 1];
const refText = getTextByBlockUid(refMatch[1]);
const prefix = `${text.slice(0, refMatch.index)}${refText} [*](${
refMatch[0]
})`;
const location = window.roamAlphaAPI.ui.getFocusedBlock();
updateBlock({
text: `${prefix} ${text.slice(refMatch.index + refMatch[0].length)}`,
uid,
}).then(() =>
setTimeout(() => {
window.roamAlphaAPI.ui.setBlockFocusAndSelection({
location,
selection: { start: prefix.length },
});
}, 200)
);
}
}
};
const applyChildrenOfLastReferenceAsText = () => {
const uid = window.roamAlphaAPI.ui.getFocusedBlock()?.["block-uid"];
if (uid) {
const text = getTextByBlockUid(uid);
const allRefs = Array.from(text.matchAll(new RegExp(BLOCK_REF_REGEX, "g")));
if (allRefs.length) {
const latestMatch = allRefs.findIndex(
(r) =>
r.index >
(document.activeElement as HTMLTextAreaElement).selectionStart
);
const refMatch = latestMatch <= 0 ? allRefs[0] : allRefs[latestMatch - 1];
const tree = getBasicTreeByParentUid(refMatch[1]);
stripUid(tree).forEach((node, order) =>
createBlock({ parentUid: uid, order, node })
);
}
}
};
const replaceLastReferenceWithOriginal = () => {
const uid = window.roamAlphaAPI.ui.getFocusedBlock()?.["block-uid"];
if (uid) {
const text = getTextByBlockUid(uid);
const allRefs = Array.from(text.matchAll(new RegExp(BLOCK_REF_REGEX, "g")));
if (allRefs.length) {
const latestMatch = allRefs.findIndex(
(r) =>
r.index >
(document.activeElement as HTMLTextAreaElement).selectionStart
);
const refMatch = latestMatch <= 0 ? allRefs[0] : allRefs[latestMatch - 1];
const refOrder = getOrderByBlockUid(refMatch[1]);
const refParent = getParentUidByBlockUid(refMatch[1]);
const sourceOrder = getOrderByBlockUid(uid);
const sourceParent = getParentUidByBlockUid(uid);
window.roamAlphaAPI.moveBlock({
location: { "parent-uid": refParent, order: refOrder },
block: { uid },
});
window.roamAlphaAPI.moveBlock({
location: {
"parent-uid": sourceParent,
order: sourceOrder,
},
block: { uid: refMatch[1] },
});
}
}
};
const expandCollapseBlockTree = () => {
Promise.resolve(
window.roamAlphaAPI.ui.getFocusedBlock()?.["block-uid"] ||
window.roamAlphaAPI.ui.mainWindow.getOpenPageOrBlockUid()
).then((blockUid) =>
renderOverlay({
id: "exp-col-dialog",
Overlay: ExpColDialog,
props: { blockUid },
})
);
};
const commands = [
{ label: "Jump to the top of the page", callback: jumpToTheTopOfThePage },
{ label: "Jump to the bottom of page", callback: jumpToTheBottomOfPage },
{ label: "Expand all blocks on page", callback: expandAllBlocksOnPage },
{ label: "Collapse all blocks on page", callback: collapseAllBlocksOnPage },
{ label: "Open this page in sidebar", callback: openPageInSidebar },
{
label: "Add shortcut to page to left sidebar",
callback: addShortcutToLeftSidebar,
},
{ label: "Toggle Linked Refs", callback: toggleLinkedRefs },
{ label: "Toggle Unlinked Refs", callback: toggleUnlinkedRefs },
{
label: "Toggle References to page level",
callback: toggleReferenceParents,
},
{ label: "Expand Reference children", callback: expandReferenceChildren },
{ label: "Collapse Reference children", callback: collapseReferenceChildren },
{ label: "Expand current block tree", callback: expandCurrentBlockTree },
{ label: "Collapse current block tree", callback: collapseCurrentBlockTree },
{ label: "Insert block above", callback: insertBlockAbove },
{ label: "Insert block below", callback: insertBlockBelow },
{ label: "Go up a block", callback: goUpBlock },
{ label: "Go down a block", callback: goDownBlock },
{ label: "Go to parent block", callback: goToParentBlock },
{ label: "Delete block", callback: delBlock },
{ label: "Toggle Block View type", callback: toggleBlockViewType },
{
label: "Replace last reference before cursor with text and alias",
callback: replaceLastReferenceWithTextAndAlias,
},
{
label: "Apply Children of last reference before cursor as text",
callback: applyChildrenOfLastReferenceAsText,
},
{
label:
"Replace last reference before cursor with original + bring nested items along",
callback: replaceLastReferenceWithOriginal,
},
{
label: "Paste block with children as references",
callback: pasteBlockWithChildrenAsReferences,
},
{
label:
"Expand/Collapse block tree to a certain level, specified by the following numeric key press",
callback: expandCollapseBlockTree,
},
{ label: "Align left", callback: alignLeft },
{ label: "Center", callback: center },
{ label: "Align right", callback: alignRight },
{ label: "Justify", callback: justify },
{ label: "Toggle Queries", callback: toggleQueries },
];
const unloads = new Set<() => void>();
export let enabled = false;
export const toggleFeature = (
flag: boolean,
extensionAPI: OnloadArgs["extensionAPI"]
) => {
enabled = flag;
if (flag) {
const focusableObserver = createHTMLObserver({
callback: (b) => {
if (b.tabIndex < 0) {
b.tabIndex = 0;
}
},
tag: "SPAN",
className: "bp3-button",
});
unloads.add(() => focusableObserver.disconnect());
commands.forEach((cmd) => unloads.add(addCommand(cmd, extensionAPI)));
} else {
unloads.forEach((u) => u());
unloads.clear();
}
};