-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDiscourseNodeMenu.tsx
More file actions
473 lines (435 loc) · 14.7 KB
/
DiscourseNodeMenu.tsx
File metadata and controls
473 lines (435 loc) · 14.7 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
import {
Menu,
MenuItem,
Popover,
Position,
Button,
InputGroup,
getKeyCombo,
IKeyCombo,
Icon,
} from "@blueprintjs/core";
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import ReactDOM from "react-dom";
import getTextByBlockUid from "roamjs-components/queries/getTextByBlockUid";
import getUids from "roamjs-components/dom/getUids";
import updateBlock from "roamjs-components/writes/updateBlock";
import { getCoordsFromTextarea } from "roamjs-components/components/CursorMenu";
import getDiscourseNodes from "~/utils/getDiscourseNodes";
import createDiscourseNode from "~/utils/createDiscourseNode";
import { getNewDiscourseNodeText } from "~/utils/formatUtils";
import { OnloadArgs } from "roamjs-components/types";
import { formatHexColor } from "./settings/DiscourseNodeCanvasSettings";
import posthog from "posthog-js";
import { setPersonalSetting } from "~/components/settings/utils/accessors";
import { PERSONAL_KEYS } from "~/components/settings/utils/settingKeys";
import type { PersonalSettings } from "~/components/settings/utils/zodSchema";
type Props = {
textarea?: HTMLTextAreaElement;
blockUid?: string;
extensionAPI: OnloadArgs["extensionAPI"];
trigger?: JSX.Element;
isShift?: boolean;
};
const NodeMenu = ({
onClose,
textarea,
blockUid,
extensionAPI,
trigger,
isShift,
}: { onClose: () => void } & Props) => {
const isInitialTextSelected =
!!textarea && textarea.selectionStart !== textarea.selectionEnd;
const [showNodeTypes, setShowNodeTypes] = useState(
isInitialTextSelected || (isShift ?? false),
);
const userDiscourseNodes = useMemo(
() => getDiscourseNodes().filter((n) => n.backedBy === "user"),
[],
);
const discourseNodes = userDiscourseNodes.filter(
(n) => showNodeTypes || n.tag,
);
const indexBySC = useMemo(
() => Object.fromEntries(discourseNodes.map((mi, i) => [mi.shortcut, i])),
[discourseNodes],
);
const shortcuts = useMemo(() => new Set(Object.keys(indexBySC)), [indexBySC]);
const targetBlockUid = useMemo(
() => (textarea ? getUids(textarea).blockUid : blockUid || ""),
[textarea, blockUid],
);
const menuRef = useRef<HTMLUListElement>(null);
const [activeIndex, setActiveIndex] = useState(0);
const [isOpen, setIsOpen] = useState(!trigger);
const onSelect = useCallback(
(index: number) => {
const menuItem =
menuRef.current?.children[index].querySelector(".bp3-menu-item");
if (!menuItem) return;
const currentText = textarea
? textarea.value
: getTextByBlockUid(targetBlockUid);
const selectionStart = textarea
? textarea.selectionStart
: currentText.length;
const selectionEnd = textarea
? textarea.selectionEnd
: currentText.length;
if (showNodeTypes) {
const nodeUid = menuItem.getAttribute("data-node") || "";
const highlighted = textarea
? currentText.substring(selectionStart, selectionEnd)
: "";
// Remove focus from the block to ensure updateBlock works properly
// https://github.com/RoamJS/query-builder/issues/286
if (document.activeElement === textarea) document.body.click();
const createNodeAndUpdateBlock = async () => {
const pageName = await getNewDiscourseNodeText({
text: highlighted,
nodeType: nodeUid,
blockUid: targetBlockUid,
skipBlockUpdate: true,
});
if (!pageName) return;
const latestBlockText = getTextByBlockUid(targetBlockUid);
const newText = `${latestBlockText.substring(
0,
selectionStart,
)}[[${pageName}]]${latestBlockText.substring(selectionEnd)}`;
await createDiscourseNode({
text: pageName,
configPageUid: nodeUid,
extensionAPI,
});
void updateBlock({ text: newText, uid: targetBlockUid });
posthog.capture("Discourse Node: Created via Node Menu", {
nodeType: nodeUid,
text: pageName,
});
};
// timeout required to ensure the block is updated
setTimeout(() => void createNodeAndUpdateBlock(), 100);
} else {
const tag = menuItem.getAttribute("data-tag") || "";
if (!tag) return;
const addTagToBlock = () => {
const textToInsert = `${
selectionStart === 0 ? "" : " "
}#${tag.replace(/^#/, "")}`;
const newText = `${currentText.substring(
0,
selectionStart,
)}${textToInsert}${currentText.substring(selectionStart)}`;
void updateBlock({ text: newText, uid: targetBlockUid });
posthog.capture("Discourse Tag: Created via Node Menu", {
tag,
});
};
// timeout required to ensure the block is updated
setTimeout(() => void addTagToBlock(), 100);
// Remove focus from the block so user can see tag css immediately
if (document.activeElement === textarea) document.body.click();
}
onClose();
},
[menuRef, targetBlockUid, onClose, textarea, extensionAPI, showNodeTypes],
);
const keydownListener = useCallback(
(e: KeyboardEvent) => {
if (!isOpen || e.metaKey || e.ctrlKey) return;
if (e.key === "Shift") {
if (!isInitialTextSelected) setShowNodeTypes(true);
return;
}
const getActiveIndex = () => {
return Number(menuRef.current?.getAttribute("data-active-index"));
};
if (e.key === "ArrowDown") {
const index = getActiveIndex();
const count = menuRef.current?.childElementCount || 0;
setActiveIndex((index + 1) % count);
} else if (e.key === "ArrowUp") {
const index = getActiveIndex();
const count = menuRef.current?.childElementCount || 0;
setActiveIndex((index - 1 + count) % count);
} else if (e.key === "Enter") {
const index = getActiveIndex();
onSelect(index);
} else if (e.key === "Escape") {
onClose();
} else if (shortcuts.has(e.key.toUpperCase())) {
onSelect(indexBySC[e.key.toUpperCase()]);
} else {
return;
}
e.stopPropagation();
e.preventDefault();
},
[onSelect, onClose, indexBySC, isOpen, isInitialTextSelected, shortcuts],
);
const keyupListener = useCallback(
(e: KeyboardEvent) => {
if (e.key === "Shift" && !isInitialTextSelected) {
setShowNodeTypes(false);
}
},
[isInitialTextSelected],
);
useEffect(() => {
const eventTarget = trigger ? document : textarea;
if (!eventTarget) return;
const keydownHandler = (e: Event) => {
keydownListener(e as KeyboardEvent);
};
eventTarget.addEventListener("keydown", keydownHandler);
eventTarget.addEventListener("keyup", keyupListener as EventListener);
if (!trigger && textarea) {
textarea.addEventListener("input", onClose);
}
return () => {
eventTarget.removeEventListener("keydown", keydownHandler);
eventTarget.removeEventListener("keyup", keyupListener as EventListener);
if (!trigger && textarea) {
textarea.removeEventListener("input", onClose);
}
};
}, [
keydownListener,
keyupListener,
onClose,
textarea,
trigger,
isInitialTextSelected,
]);
const handlePopoverInteraction = useCallback(
(nextOpenState: boolean) => {
setIsOpen(nextOpenState);
if (!nextOpenState) {
onClose();
}
},
[onClose],
);
return (
<Popover
onClose={onClose}
isOpen={isOpen}
canEscapeKeyClose
minimal
target={trigger || <span />}
className="relative z-50"
position={Position.BOTTOM_LEFT}
modifiers={{
flip: { enabled: false },
preventOverflow: { enabled: false },
}}
autoFocus={false}
enforceFocus={false}
onInteraction={trigger ? handlePopoverInteraction : undefined}
content={
<Menu ulRef={menuRef} data-active-index={activeIndex}>
{discourseNodes.map((item, i) => {
const nodeColor =
formatHexColor(item?.canvasSettings?.color) || "#000";
return (
<MenuItem
key={item.text}
data-node={item.type}
data-tag={item.tag?.replace(/^#/, "")}
text={
showNodeTypes
? item.text
: item.tag
? `#${item.tag.replace(/^#/, "")}`
: ""
}
active={i === activeIndex}
onMouseEnter={() => setActiveIndex(i)}
onClick={() => onSelect(i)}
disabled={!showNodeTypes && !item.tag}
className="flex items-center"
icon={
<div
className="mr-2 h-4 w-4 select-none rounded-full"
style={{
backgroundColor: nodeColor,
}}
/>
}
labelElement={
<span className="font-mono">{item.shortcut}</span>
}
/>
);
})}
</Menu>
}
/>
);
};
export const render = (props: Props) => {
if (!props.textarea) return;
const parent = document.createElement("span");
const coords = getCoordsFromTextarea(props.textarea);
parent.style.position = "absolute";
parent.style.left = `${coords.left}px`;
parent.style.top = `${coords.top}px`;
props.textarea.parentElement?.insertBefore(parent, props.textarea);
ReactDOM.render(
<NodeMenu
{...props}
onClose={() => {
ReactDOM.unmountComponentAtNode(parent);
parent.remove();
}}
/>,
parent,
);
};
export const TextSelectionNodeMenu = ({
textarea,
extensionAPI,
onClose,
}: {
textarea: HTMLTextAreaElement;
extensionAPI: OnloadArgs["extensionAPI"];
onClose: () => void;
}) => {
const trigger = (
<Button
small
className="relative z-50 rounded border border-[#d3d8de] bg-white px-2 py-1 shadow-md hover:border-[#bfccd6] hover:bg-[#f7f9fc]"
icon={
<div className="flex items-center gap-1">
<svg
width="18"
height="19"
viewBox="0 0 256 264"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M156.705 252.012C140.72 267.995 114.803 267.995 98.8183 252.012L11.9887 165.182C-3.99622 149.197 -3.99622 123.28 11.9886 107.296L55.4035 63.8807C63.3959 55.8881 76.3541 55.8881 84.3467 63.8807C92.3391 71.8731 92.3391 84.8313 84.3467 92.8239L69.8751 107.296C53.8901 123.28 53.8901 149.197 69.8751 165.182L113.29 208.596C121.282 216.589 134.241 216.589 142.233 208.596C150.225 200.604 150.225 187.646 142.233 179.653L127.761 165.182C111.777 149.197 111.777 123.28 127.761 107.296C143.746 91.3105 143.746 65.3939 127.761 49.4091L113.29 34.9375C105.297 26.9452 105.297 13.9868 113.29 5.99432C121.282 -1.99811 134.241 -1.99811 142.233 5.99434L243.533 107.296C259.519 123.28 259.519 149.197 243.533 165.182L156.705 252.012ZM200.119 121.767C192.127 113.775 179.168 113.775 171.176 121.767C163.184 129.76 163.184 142.718 171.176 150.71C179.168 158.703 192.127 158.703 200.119 150.71C208.112 142.718 208.112 129.76 200.119 121.767Z"
fill="#555555"
/>
</svg>
<Icon icon="chevron-down" size={16} color="#555555" />
</div>
}
/>
);
return (
<NodeMenu
textarea={textarea}
extensionAPI={extensionAPI}
trigger={trigger}
onClose={onClose}
isShift
/>
);
};
// node_modules\@blueprintjs\core\lib\esm\components\hotkeys\hotkeyParser.js
const isMac = () => {
const platform =
typeof navigator !== "undefined" ? navigator.platform : undefined;
return platform == null ? false : /Mac|iPod|iPhone|iPad/.test(platform);
};
const MODIFIER_BIT_MASKS = {
alt: 1,
ctrl: 2,
meta: 4,
shift: 8,
};
const ALIASES: { [key: string]: string } = {
cmd: "meta",
command: "meta",
escape: "esc",
minus: "-",
mod: isMac() ? "meta" : "ctrl",
option: "alt",
plus: "+",
return: "enter",
win: "meta",
};
const normalizeKeyCombo = (combo: string) => {
const keys = combo.replace(/\s/g, "").split("+");
return keys.map(function (key) {
const keyName = ALIASES[key] != null ? ALIASES[key] : key;
return keyName === "meta" ? (isMac() ? "cmd" : "win") : keyName;
});
};
export const getModifiersFromCombo = (comboKey: IKeyCombo) => {
if (!comboKey) return [];
return [
comboKey.modifiers & MODIFIER_BIT_MASKS.alt && "alt",
comboKey.modifiers & MODIFIER_BIT_MASKS.ctrl && "ctrl",
comboKey.modifiers & MODIFIER_BIT_MASKS.shift && "shift",
comboKey.modifiers & MODIFIER_BIT_MASKS.meta && "meta",
].filter(Boolean);
};
export const comboToString = (combo: IKeyCombo): string => {
if (!combo.key) return "";
const modifiers = getModifiersFromCombo(combo);
const comboString = [...modifiers, combo.key].join("+");
return normalizeKeyCombo(comboString).join("+");
};
export const NodeMenuTriggerComponent = ({
extensionAPI,
initialValue,
}: {
extensionAPI: OnloadArgs["extensionAPI"];
initialValue: PersonalSettings["Personal node menu trigger"];
}) => {
const inputRef = useRef<HTMLInputElement>(null);
const [isActive, setIsActive] = useState(false);
const [comboKey, setComboKey] = useState<IKeyCombo>(() =>
typeof initialValue === "object" ? initialValue : { modifiers: 0, key: "" },
);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
e.stopPropagation();
e.preventDefault();
const comboObj = getKeyCombo(e.nativeEvent);
if (!comboObj.key) return;
const combo = { key: comboObj.key, modifiers: comboObj.modifiers };
setComboKey(combo);
void extensionAPI.settings.set("personal-node-menu-trigger", combo);
setPersonalSetting([PERSONAL_KEYS.personalNodeMenuTrigger], combo);
},
[extensionAPI],
);
const shortcut = useMemo(() => comboToString(comboKey), [comboKey]);
return (
<InputGroup
inputRef={inputRef}
placeholder={isActive ? "Press keys" : "Click to set trigger"}
value={shortcut}
onKeyDown={handleKeyDown}
onFocus={() => setIsActive(true)}
onBlur={() => setIsActive(false)}
rightElement={
<Button
hidden={!comboKey.key}
icon={"remove"}
onClick={() => {
setComboKey({ modifiers: 0, key: "" });
void extensionAPI.settings.set("personal-node-menu-trigger", "");
setPersonalSetting([PERSONAL_KEYS.personalNodeMenuTrigger], "");
}}
minimal
/>
}
/>
);
};
export default NodeMenu;