-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathexportUtils.ts
More file actions
152 lines (140 loc) · 4.46 KB
/
exportUtils.ts
File metadata and controls
152 lines (140 loc) · 4.46 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
import type { Result } from "roamjs-components/types/query-builder";
import { PullBlock, TreeNode, ViewType } from "roamjs-components/types";
import type { DiscourseNode } from "./getDiscourseNodes";
import matchDiscourseNode from "./matchDiscourseNode";
type DiscourseExportResult = Result & { type: string };
export const uniqJsonArray = <T extends Record<string, unknown>>(arr: T[]) =>
Array.from(
new Set(
arr.map((r) =>
JSON.stringify(
Object.entries(r).sort(([k], [k2]) => k.localeCompare(k2)),
),
),
),
).map((entries) => Object.fromEntries(JSON.parse(entries))) as T[];
export const getPageData = async ({
results,
allNodes,
isExportDiscourseGraph,
}: {
results: Result[];
allNodes: DiscourseNode[];
isExportDiscourseGraph?: boolean;
}): Promise<(Result & { type: string })[]> => {
const allResults = results || [];
if (isExportDiscourseGraph) return allResults as DiscourseExportResult[];
const matchedTexts = new Set();
return allNodes.flatMap((n) =>
(allResults
? allResults.flatMap((r) =>
Object.keys(r)
.filter((k) => k.endsWith(`-uid`) && k !== "text-uid")
.map((k) => ({
...r,
text: r[k.slice(0, -4)].toString(),
uid: r[k] as string,
}))
.concat({
text: r.text,
uid: r.uid,
}),
)
: (
window.roamAlphaAPI.q(
"[:find (pull ?e [:block/uid :node/title]) :where [?e :node/title _]]",
) as [Record<string, string>][]
).map(([{ title, uid }]) => ({
text: title,
uid,
}))
)
.filter(({ text }) => {
if (!text) return false;
if (matchedTexts.has(text)) return false;
const isMatch = matchDiscourseNode({ title: text, ...n });
if (isMatch) matchedTexts.add(text);
return isMatch;
})
.map((node) => ({ ...node, type: n.text })),
);
};
const getContentFromNodes = ({
title,
allNodes,
}: {
title: string;
allNodes: DiscourseNode[];
}) => {
const nodeFormat = allNodes.find((a) =>
matchDiscourseNode({ title, ...a }),
)?.format;
if (!nodeFormat) return title;
const regex = new RegExp(
`^${nodeFormat
.replace(/(\[|\]|\?|\.|\+)/g, "\\$1")
.replace("{content}", "(.*?)")
.replace(/{[^}]+}/g, "(?:.*?)")}$`,
);
return regex.exec(title)?.[1] || title;
};
export const getFilename = ({
title = "",
maxFilenameLength,
simplifiedFilename,
allNodes,
removeSpecialCharacters,
extension = ".md",
}: {
title?: string;
maxFilenameLength: number;
simplifiedFilename: boolean;
allNodes: DiscourseNode[];
removeSpecialCharacters: boolean;
extension?: string;
}) => {
const baseName = simplifiedFilename
? getContentFromNodes({ title, allNodes })
: title;
const name = `${
removeSpecialCharacters
? baseName.replace(/[<>:"/\\|\?*[\]]/g, "")
: baseName
}${extension}`;
return name.length > maxFilenameLength
? `${name.substring(
0,
Math.ceil((maxFilenameLength - 3) / 2),
)}...${name.slice(-Math.floor((maxFilenameLength - 3) / 2))}`
: name;
};
export const toLink = (filename: string, uid: string, linkType: string) => {
const extensionRemoved = filename.replace(/\.\w+$/, "");
if (linkType === "wikilinks") return `[[${extensionRemoved}]]`;
if (linkType === "alias") return `[${filename}](${filename})`;
if (linkType === "roam url")
return `[${extensionRemoved}](https://roamresearch.com/#/app/${window.roamAlphaAPI.graph.name}/page/${uid})`;
return filename;
};
export const pullBlockToTreeNode = (
n: PullBlock,
v: `:${ViewType}`,
): TreeNode => ({
text: n[":block/string"] || n[":node/title"] || "",
open: typeof n[":block/open"] === "undefined" ? true : n[":block/open"],
order: n[":block/order"] || 0,
uid: n[":block/uid"] || "",
heading: n[":block/heading"] || 0,
viewType: (n[":children/view-type"] || v).slice(1) as ViewType,
editTime: new Date(n[":edit/time"] || 0),
props: { imageResize: {}, iframe: {} },
textAlign: n[":block/text-align"] || "left",
children: (n[":block/children"] || [])
.sort(({ [":block/order"]: a = 0 }, { [":block/order"]: b = 0 }) => a - b)
.map((r) => pullBlockToTreeNode(r, n[":children/view-type"] || v)),
parents: (n[":block/parents"] || []).map((p) => p[":db/id"] || 0),
});
export const collectUids = (t: TreeNode): string[] => [
t.uid,
...t.children.flatMap(collectUids),
];