Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions apps/roam/src/utils/exportUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
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[];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unsafe argument of type any assigned to a parameter of type Iterable<readonly [PropertyKey, unknown]>.eslint@typescript-eslint/no-unsafe-argument


export const getPageData = ({
results,
allNodes,
isExportDiscourseGraph,
}: {
results: Result[];
allNodes: DiscourseNode[];
isExportDiscourseGraph?: boolean;
}): (Result & { type: string })[] => {
if (isExportDiscourseGraph) return results as DiscourseExportResult[];

const matchedTexts = new Set();
const mappedResults = results.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,
}),
);
return allNodes.flatMap((n) =>
mappedResults
.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, "\\$&")
.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, "")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unnecessary escape character: ?.eslintno-useless-escape

: baseName
}${extension}`;

return name.length > maxFilenameLength
? `${name.substring(
0,
Math.ceil((maxFilenameLength - 3) / 2),
)}...${name.slice(-Math.floor((maxFilenameLength - 3) / 2))}`
: name;
Comment on lines +102 to +107
Copy link
Contributor

@coderabbitai coderabbitai bot Dec 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Edge case: Very small maxFilenameLength values.

If maxFilenameLength is less than or equal to 3, the calculation (maxFilenameLength - 3) / 2 could result in 0 or negative values, potentially producing unexpected output. Consider adding a guard or minimum value check.

🔎 Suggested guard
+  const effectiveMaxLength = Math.max(maxFilenameLength, 4);
   return name.length > maxFilenameLength
     ? `${name.substring(
         0,
-        Math.ceil((maxFilenameLength - 3) / 2),
-      )}...${name.slice(-Math.floor((maxFilenameLength - 3) / 2))}`
+        Math.ceil((effectiveMaxLength - 3) / 2),
+      )}...${name.slice(-Math.floor((effectiveMaxLength - 3) / 2))}`
     : name;

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/roam/src/utils/exportUtils.ts around lines 114 to 119, the truncation
logic can produce incorrect slices when maxFilenameLength <= 3; add a guard that
handles very small maxFilenameLength values first (e.g., if maxFilenameLength <=
3) and return a string of length maxFilenameLength composed of dots or a
truncated ellipsis, otherwise compute left/right slice sizes using Math.max(0,
Math.floor/ceil((maxFilenameLength - 3) / 2)) to avoid negative values and then
perform the substring + '...' + slice as before.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Valid concern, but I think that should be done as a guard on the setting, not an adjustment downstream.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@maparent That makes sense! Validating maxFilenameLength at the settings level (e.g., ensuring it's always >= 4 or some reasonable minimum) is a cleaner approach and prevents invalid values from propagating through the system. This keeps the utility function simpler and enforces the constraint where the configuration is defined.


🧠 Learnings used
Learnt from: sid597
Repo: DiscourseGraphs/discourse-graph PR: 232
File: apps/roam/src/utils/getAllDiscourseNodesSince.ts:18-31
Timestamp: 2025-06-22T10:40:52.752Z
Learning: In apps/roam/src/utils/getAllDiscourseNodesSince.ts, the user confirmed that querying for `?title` with `:node/title` and mapping it to the `text` field in the DiscourseGraphContent type is the correct implementation for retrieving discourse node content from Roam Research, despite it appearing to query page titles rather than block text content.

Learnt from: maparent
Repo: DiscourseGraphs/discourse-graph PR: 559
File: apps/roam/src/utils/findDiscourseNode.ts:37-39
Timestamp: 2025-12-07T20:54:20.007Z
Learning: In apps/roam/src/utils/findDiscourseNode.ts, the function findDiscourseNodeByTitleAndUid accepts both uid and title parameters where uid is primarily used for cache access (as the cache key) while title is used for the actual matching via matchDiscourseNode. This design reflects the pattern where downstream, the uid is mostly used to fetch the title, so the function caches by uid but matches by title.

Learnt from: CR
Repo: DiscourseGraphs/discourse-graph PR: 0
File: .cursor/rules/roam.mdc:0-0
Timestamp: 2025-11-25T00:52:41.934Z
Learning: Applies to apps/roam/**/*.{ts,tsx,js,jsx} : Use Roam Depot/Extension API docs from https://roamresearch.com/#/app/developer-documentation/page/y31lhjIqU when implementing extension functionality

Learnt from: CR
Repo: DiscourseGraphs/discourse-graph PR: 0
File: .cursor/rules/roam.mdc:0-0
Timestamp: 2025-11-25T00:52:41.934Z
Learning: Applies to apps/roam/**/*.{ts,tsx,js,jsx} : Use the roamAlphaApi docs from https://roamresearch.com/#/app/developer-documentation/page/tIaOPdXCj when implementing Roam functionality

};

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),
];
Loading