-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcreateDiscourseNode.ts
More file actions
194 lines (179 loc) · 5.98 KB
/
createDiscourseNode.ts
File metadata and controls
194 lines (179 loc) · 5.98 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
import { render as renderToast } from "roamjs-components/components/Toast";
import createBlock from "roamjs-components/writes/createBlock";
import stripUid from "roamjs-components/util/stripUid";
import getPageUidByPageTitle from "roamjs-components/queries/getPageUidByPageTitle";
import createPage from "roamjs-components/writes/createPage";
import getFullTreeByParentUid from "roamjs-components/queries/getFullTreeByParentUid";
import getSubTree from "roamjs-components/util/getSubTree";
import openBlockInSidebar from "roamjs-components/writes/openBlockInSidebar";
import getDiscourseNodes from "./getDiscourseNodes";
import resolveQueryBuilderRef from "./resolveQueryBuilderRef";
import { OnloadArgs, RoamBasicNode } from "roamjs-components/types";
import runQuery from "./runQuery";
import updateBlock from "roamjs-components/writes/updateBlock";
import posthog from "posthog-js";
type Props = {
text: string;
configPageUid: string;
newPageUid?: string;
imageUrl?: string;
extensionAPI?: OnloadArgs["extensionAPI"];
};
const createDiscourseNode = async ({
text,
configPageUid,
newPageUid,
imageUrl,
extensionAPI,
}: Props) => {
posthog.capture("Discourse Node: Created", {
text: text,
});
const handleOpenInSidebar = (uid: string) => {
if (extensionAPI?.settings.get("disable-sidebar-open")) return;
openBlockInSidebar(uid);
setTimeout(() => {
const sidebarTitle = document.querySelector(
".rm-sidebar-outline .rm-title-display",
);
sidebarTitle?.dispatchEvent(
new MouseEvent("mousedown", { bubbles: true }),
);
setTimeout(() => {
const ta = document.activeElement as HTMLTextAreaElement;
if (ta.tagName === "TEXTAREA") {
const index = ta.value.length;
ta.setSelectionRange(index, index);
}
}, 1);
}, 100);
};
const handleImageCreation = async (pageUid: string) => {
const canvasSettings = Object.fromEntries(
discourseNodes.map((n) => [n.type, { ...n.canvasSettings }]),
);
const {
"query-builder-alias": qbAlias = "",
"key-image": isKeyImage = "",
"key-image-option": keyImageOption = "",
} = canvasSettings[configPageUid] || {};
if (isKeyImage && imageUrl) {
const createOrUpdateImageBlock = async (imagePlaceholderUid?: string) => {
const imageMarkdown = ``;
if (imagePlaceholderUid) {
await updateBlock({
uid: imagePlaceholderUid,
text: imageMarkdown,
});
} else {
await createBlock({
node: { text: imageMarkdown },
order: 0,
parentUid: pageUid,
});
}
};
if (keyImageOption === "query-builder") {
if (!extensionAPI) return;
const parentUid = resolveQueryBuilderRef({
queryRef: qbAlias,
extensionAPI,
});
const results = await runQuery({
extensionAPI,
parentUid,
inputs: { NODETEXT: text, NODEUID: pageUid },
});
const imagePlaceholderUid = results.allProcessedResults[0]?.uid;
await createOrUpdateImageBlock(imagePlaceholderUid);
} else {
await createOrUpdateImageBlock();
}
}
};
const discourseNodes = getDiscourseNodes();
const specification = discourseNodes?.find(
(n) => n.type === configPageUid,
)?.specification;
// This handles blck-type and creates block in the DNP
// but could have unintended consequences for other defined discourse nodes
if (
specification?.find(
(spec) => spec.type === "clause" && spec.relation === "is in page",
)
) {
const blockUid = await createBlock({
// TODO: for canvas, create in `Auto generated from ${title}`
parentUid: window.roamAlphaAPI.util.dateToPageUid(new Date()),
node: { text, uid: newPageUid },
});
handleOpenInSidebar(blockUid);
return blockUid;
}
let pageUid: string;
let isNewPage = false;
if (newPageUid) {
await createPage({ title: text, uid: newPageUid });
pageUid = newPageUid;
isNewPage = true;
} else {
const existingPageUid = getPageUidByPageTitle(text);
if (existingPageUid) {
pageUid = existingPageUid;
isNewPage = false;
} else {
pageUid = await createPage({ title: text });
isNewPage = true;
}
}
// Skip template creation if the page already exists and has children
const existingChildren = getFullTreeByParentUid(pageUid).children || [];
if (!isNewPage && existingChildren.length > 0) {
handleOpenInSidebar(pageUid);
return pageUid;
}
const nodeTree = getFullTreeByParentUid(configPageUid).children;
const templateNode = getSubTree({
tree: nodeTree,
key: "template",
});
const createBlocksFromTemplate = async () => {
await Promise.all(
stripUid(templateNode.children).map(({ uid, ...node }, order) =>
createBlock({
node,
order,
parentUid: pageUid,
}),
),
);
// Add image to page if imageUrl is provided
await handleImageCreation(pageUid);
};
const hasSmartBlockSyntax = (node: RoamBasicNode): boolean => {
if (node.text.includes("<%")) return true;
if (node.children) return node.children.some(hasSmartBlockSyntax);
return false;
};
const useSmartBlocks = hasSmartBlockSyntax(templateNode);
if (useSmartBlocks && !window.roamjs?.extension?.smartblocks) {
renderToast({
content:
"This template requires SmartBlocks. Enable SmartBlocks in Roam Depot to use this template.",
id: "smartblocks-extension-disabled",
intent: "warning",
});
await createBlocksFromTemplate();
} else if (useSmartBlocks && window.roamjs?.extension?.smartblocks) {
window.roamjs.extension.smartblocks?.triggerSmartblock({
srcUid: templateNode.uid,
targetUid: pageUid,
});
await handleImageCreation(pageUid);
} else {
await createBlocksFromTemplate();
}
handleOpenInSidebar(pageUid);
return pageUid;
};
export default createDiscourseNode;