-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathDiscourseContextOverlay.tsx
More file actions
375 lines (354 loc) · 9.79 KB
/
Copy pathDiscourseContextOverlay.tsx
File metadata and controls
375 lines (354 loc) · 9.79 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
import {
Button,
Icon,
Popover,
Position,
Collapse,
Card,
} from "@blueprintjs/core";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import ReactDOM from "react-dom";
import renderWithUnmount from "roamjs-components/util/renderWithUnmount";
import { ContextContent } from "./DiscourseContext";
import useInViewport from "react-in-viewport/dist/es/lib/useInViewport";
import normalizePageTitle from "roamjs-components/queries/normalizePageTitle";
import deriveDiscourseNodeAttribute from "~/utils/deriveDiscourseNodeAttribute";
import { getDiscourseNodeSetting } from "~/components/settings/utils/accessors";
import { DISCOURSE_NODE_KEYS } from "~/components/settings/utils/settingKeys";
import { getStoredRelationsEnabled } from "~/utils/storedRelations";
import nanoid from "nanoid";
import getPageUidByPageTitle from "roamjs-components/queries/getPageUidByPageTitle";
import getDiscourseContextResults from "~/utils/getDiscourseContextResults";
import findDiscourseNode from "~/utils/findDiscourseNode";
import getDiscourseNodes from "~/utils/getDiscourseNodes";
import getDiscourseRelations from "~/utils/getDiscourseRelations";
import ExtensionApiContextProvider from "roamjs-components/components/ExtensionApiContext";
import { OnloadArgs } from "roamjs-components/types/native";
import getPageTitleByPageUid from "roamjs-components/queries/getPageTitleByPageUid";
import internalError from "~/utils/internalError";
type DiscourseData = {
results: Awaited<ReturnType<typeof getDiscourseContextResults>>;
refs: number;
};
const getOverlayInfo = async (
tag: string,
ignoreCache?: boolean,
): Promise<DiscourseData> => {
try {
const relations = getDiscourseRelations();
const nodes = getDiscourseNodes();
const [results, refs] = await Promise.all([
getDiscourseContextResults({
uid: getPageUidByPageTitle(tag),
nodes,
relations,
ignoreCache,
}),
window.roamAlphaAPI.data.backend.q(
`[:find ?a :where [?b :node/title "${normalizePageTitle(tag)}"] [?a :block/refs ?b]]`,
),
]);
return {
results,
refs: refs.length,
};
} catch (error) {
console.error(`Error getting overlay info for ${tag}:`, error);
return {
results: [],
refs: 0,
};
}
};
const OPACITY_VALUES = [
"5",
"10",
"15",
"20",
"25",
"30",
"35",
"40",
"45",
"50",
"55",
"60",
"65",
"70",
"75",
"80",
"85",
"90",
"95",
"100",
] as const;
type OpacityValue = (typeof OPACITY_VALUES)[number];
type DiscourseContextOverlayBaseProps = {
id: string;
iconColor?: string;
textColor?: string;
opacity?: OpacityValue;
};
// need tag or uid
type DiscourseContextOverlayProps = DiscourseContextOverlayBaseProps &
({ tag: string; uid?: never } | { tag?: never; uid: string });
export const ICON_SIZE = 10;
export const DiscourseContextButton = ({
id,
iconColor,
textColor,
loading,
score,
refs,
onClick,
opacity = "100",
}: DiscourseContextOverlayBaseProps & {
loading: boolean;
score: string | number;
refs: number;
onClick?: (event: React.MouseEvent) => void;
}) => {
return (
<Button
small
id={id}
className={`roamjs-discourse-context-overlay ${
loading ? "animate-pulse" : ""
}`}
style={{
minHeight: "initial",
paddingTop: ".25rem",
paddingBottom: ".25rem",
}}
minimal
disabled={loading}
onClick={onClick}
>
<div className="flex items-center gap-1.5">
<Icon
icon={"diagram-tree"}
color={iconColor}
style={{ opacity: `${Number(opacity) / 100}` }}
size={ICON_SIZE}
/>
<span
className={`mr-1 text-xs leading-none opacity-${opacity}`}
style={{ color: textColor }}
>
{loading ? "-" : score}
</span>
<Icon
icon={"link"}
color={iconColor}
style={{ opacity: `${Number(opacity) / 100}` }}
size={ICON_SIZE}
/>
<span
className={`text-xs leading-none opacity-${opacity}`}
style={{ color: textColor }}
>
{loading ? "-" : refs}
</span>
</div>
</Button>
);
};
const useDiscourseContext = (uid: string, tag: string) => {
const [loading, setLoading] = useState(true);
const [results, setResults] = useState<DiscourseData["results"]>([]);
const [refs, setRefs] = useState(0);
const [score, setScore] = useState<number | string>(0);
const getInfo = useCallback(
(ignoreCache?: boolean) =>
getOverlayInfo(tag, ignoreCache)
.then(({ refs, results }) => {
const discourseNode = findDiscourseNode({ uid: uid });
if (discourseNode) {
const numResults = results
.map(
(entry) =>
Object.keys(
(
entry as unknown as {
label: string;
results: Record<string, unknown>;
}
).results,
).length,
)
.reduce((acc, cur) => acc + cur, 0);
const attribute =
getDiscourseNodeSetting<string>(discourseNode.type, [
DISCOURSE_NODE_KEYS.overlay,
]) || "Overlay";
return deriveDiscourseNodeAttribute({
uid: uid,
attribute,
}).then((score) => {
setResults(results);
setRefs(refs);
setScore(score);
const scoreFormula =
getDiscourseNodeSetting<string>(discourseNode.type, [
DISCOURSE_NODE_KEYS.attributes,
attribute,
]) ?? "";
if (scoreFormula === "" && score !== numResults) {
internalError({
error: "DiscourseContext: Score does not match Num relations",
context: {
uid,
score,
numResults,
ignoreCache,
reified: getStoredRelationsEnabled(),
},
});
}
});
}
})
.finally(() => setLoading(false)),
[tag, uid],
);
const refresh = useCallback(() => {
setLoading(true);
void getInfo(true);
}, [getInfo]);
useEffect(() => {
void getInfo();
}, [getInfo]);
return { loading, results, refs, score, refresh };
};
const DiscourseContextPopupOverlay = ({
tag,
id,
uid,
iconColor,
textColor,
opacity = "100",
}: DiscourseContextOverlayProps) => {
const tagUid = useMemo(() => uid ?? getPageUidByPageTitle(tag), [uid, tag]);
const uidTag = tag ?? (uid ? (getPageTitleByPageUid(uid) ?? "") : "");
const { loading, results, refs, score, refresh } = useDiscourseContext(
tagUid,
uidTag,
);
return (
<Popover
autoFocus={false}
content={
<div
className={`roamjs-discourse-context-popover relative max-w-3xl p-4 ${
results.length === 0 ? "flex items-center justify-center" : ""
}`}
>
<ContextContent
uid={tagUid}
results={results}
overlayRefresh={refresh}
/>
</div>
}
target={
<DiscourseContextButton
id={id}
iconColor={iconColor}
textColor={textColor}
loading={loading}
score={score}
refs={refs}
opacity={opacity}
></DiscourseContextButton>
}
position={Position.BOTTOM}
/>
);
};
export const DiscourseContextCollapseOverlay = ({
tag,
id,
uid,
iconColor,
textColor,
opacity = "100",
}: DiscourseContextOverlayProps) => {
const [open, setOpen] = useState(false);
const tagUid = useMemo(() => uid ?? getPageUidByPageTitle(tag), [uid, tag]);
const uidTag = tag ?? (uid ? (getPageTitleByPageUid(uid) ?? "") : "");
const { loading, results, refs, score, refresh } = useDiscourseContext(
tagUid,
uidTag,
);
return (
<>
<DiscourseContextButton
id={id}
iconColor={iconColor}
textColor={textColor}
loading={loading}
score={score}
refs={refs}
opacity={opacity}
onClick={() => {
setOpen(!open);
}}
/>
<Collapse isOpen={open} keepChildrenMounted={true}>
<Card className={"my-3" + (loading ? " bp3-skeleton" : "")}>
<ContextContent
uid={tagUid}
results={results}
overlayRefresh={refresh}
/>
</Card>
</Collapse>
</>
);
};
const Wrapper = ({ parent, tag }: { parent: HTMLElement; tag: string }) => {
const id = useMemo(() => nanoid(), []);
const { inViewport } = useInViewport(
{ current: parent },
{},
{ disconnectOnLeave: false },
{},
);
return inViewport ? (
<DiscourseContextPopupOverlay tag={tag} id={id} />
) : (
<Button
small
id={id}
className={`roamjs-discourse-context-overlay`}
style={{
minHeight: "initial",
paddingTop: ".25rem",
paddingBottom: ".25rem",
}}
minimal
disabled={true}
>
<div className="flex items-center gap-1.5">
<Icon icon={"diagram-tree"} size={ICON_SIZE} />
<span className={`mr-1 text-xs leading-none`}>-</span>
<Icon icon={"link"} size={ICON_SIZE} />
<span className={`text-xs leading-none`}>-</span>
</div>
</Button>
);
};
export const render = ({
tag,
parent,
onloadArgs,
}: {
tag: string;
parent: HTMLElement;
onloadArgs: OnloadArgs;
}): void => {
parent.style.margin = "0 8px";
parent.onmousedown = (e) => e.stopPropagation();
renderWithUnmount(<Wrapper tag={tag} parent={parent} />, parent, onloadArgs);
};
export default DiscourseContextPopupOverlay;