-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcalcCanvasNodeSizeAndImg.ts
More file actions
178 lines (157 loc) · 5.16 KB
/
calcCanvasNodeSizeAndImg.ts
File metadata and controls
178 lines (157 loc) · 5.16 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
import getFullTreeByParentUid from "roamjs-components/queries/getFullTreeByParentUid";
import { OnloadArgs, TreeNode } from "roamjs-components/types";
import { MAX_WIDTH } from "~/components/canvas/Tldraw";
import { measureCanvasNodeText } from "./measureCanvasNodeText";
import resolveQueryBuilderRef from "./resolveQueryBuilderRef";
import runQuery from "./runQuery";
import getDiscourseNodes from "./getDiscourseNodes";
import resolveRefs from "roamjs-components/dom/resolveRefs";
import { render as renderToast } from "roamjs-components/components/Toast";
import { loadImage } from "./loadImage";
import { DEFAULT_STYLE_PROPS } from "~/components/canvas/DiscourseNodeUtil";
const extractFirstImageUrl = (text: string): string | null => {
const regex = /!\[.*?\]\((https:\/\/[^)]+)\)/;
const result = text.match(regex) || resolveRefs(text).match(regex);
return result ? result[1] : null;
};
// Matches embed, embed-path, and embed-children syntax:
// {{[[embed]]: ((block-uid)) }}, {{[[embed-path]]: ((block-uid)) }}, {{[[embed-children]]: ((block-uid)) }}
// Also handles multiple parentheses: {{[[embed]]: ((((block-uid)))) }}
const EMBED_REGEX =
/{{\[\[(?:embed|embed-path|embed-children)\]\]:\s*\(\(+([^)]+?)\)+\)\s*}}/i;
const getBlockReferences = (
uid: string,
// eslint-disable-next-line @typescript-eslint/naming-convention
): { ":block/uid"?: string; ":block/string"?: string }[] => {
const result =
(window.roamAlphaAPI?.pull?.(
"[:block/uid {:block/refs [:block/uid :block/string]}]",
[":block/uid", uid],
) as {
// eslint-disable-next-line @typescript-eslint/naming-convention
[":block/refs"]?: { ":block/uid"?: string; ":block/string"?: string }[];
} | null) || {};
return result[":block/refs"] || [];
};
const findFirstImage = (
node: TreeNode,
visited = new Set<string>(),
): string | null => {
if (visited.has(node.uid)) return null;
visited.add(node.uid);
const imageUrl = extractFirstImageUrl(node.text);
if (imageUrl) return imageUrl;
const embedUid = node.text.match(EMBED_REGEX)?.[1];
if (embedUid && !visited.has(embedUid)) {
const embedTree = getFullTreeByParentUid(embedUid);
const embedImageUrl = findFirstImage(embedTree, visited);
if (embedImageUrl) return embedImageUrl;
}
const references = getBlockReferences(node.uid);
for (const reference of references) {
const referenceText = reference[":block/string"] || "";
const referenceImage = extractFirstImageUrl(referenceText);
if (referenceImage) return referenceImage;
}
if (node.children) {
for (const child of node.children) {
const childImageUrl = findFirstImage(child, visited);
if (childImageUrl) return childImageUrl;
}
}
return null;
};
const getFirstImageByUid = (uid: string): string | null => {
const tree = getFullTreeByParentUid(uid);
return findFirstImage(tree);
};
const getNodeCanvasSettings = (nodeType: string): Record<string, string> => {
const allNodes = getDiscourseNodes();
const canvasSettings = Object.fromEntries(
allNodes.map((n) => [n.type, { ...n.canvasSettings }]),
);
return canvasSettings[nodeType] || {};
};
export const getCanvasNodeKeyImageUrl = async ({
nodeText,
uid,
nodeType,
extensionAPI,
}: {
nodeText: string;
uid: string;
nodeType: string;
extensionAPI: OnloadArgs["extensionAPI"];
}): Promise<string> => {
const {
"query-builder-alias": qbAlias = "",
"key-image": isKeyImage = "",
"key-image-option": keyImageOption = "",
} = getNodeCanvasSettings(nodeType);
if (!isKeyImage) return "";
let imageUrl: string | null;
if (keyImageOption === "query-builder") {
const parentUid = resolveQueryBuilderRef({
queryRef: qbAlias,
extensionAPI,
});
const results = await runQuery({
extensionAPI,
parentUid,
// eslint-disable-next-line @typescript-eslint/naming-convention
inputs: { NODETEXT: nodeText, NODEUID: uid },
});
const resultUid = results.allProcessedResults[0]?.uid || "";
imageUrl = getFirstImageByUid(resultUid);
} else {
imageUrl = getFirstImageByUid(uid);
}
return imageUrl ?? "";
};
const calcCanvasNodeSizeAndImg = async ({
nodeText,
uid,
nodeType,
extensionAPI,
}: {
nodeText: string;
uid: string;
nodeType: string;
extensionAPI: OnloadArgs["extensionAPI"];
}) => {
const { w, h } = measureCanvasNodeText({
...DEFAULT_STYLE_PROPS,
maxWidth: MAX_WIDTH,
text: nodeText,
});
const imageUrl = await getCanvasNodeKeyImageUrl({
nodeText,
uid,
nodeType,
extensionAPI,
});
if (!imageUrl) return { w, h, imageUrl: "" };
try {
const { width, height } = await loadImage(imageUrl);
if (
!width ||
!height ||
!Number.isFinite(width) ||
!Number.isFinite(height)
) {
return { w, h, imageUrl: "" };
}
const aspectRatio = width / height;
const nodeImageHeight = w / aspectRatio;
const newHeight = h + nodeImageHeight;
return { w, h: newHeight, imageUrl };
} catch {
renderToast({
id: "tldraw-image-load-fail",
content: "Failed to load image",
intent: "warning",
});
return { w, h, imageUrl: "" };
}
};
export default calcCanvasNodeSizeAndImg;