Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

fix: repair Notion internal links handling

Cursor Agentf58273a44d9a
diff --git a/components/view/viewer/notion-page.tsx b/components/view/viewer/notion-page.tsx
index fc2eaf61..a415bd1b 100644
--- a/components/view/viewer/notion-page.tsx
+++ b/components/view/viewer/notion-page.tsx
@@ -1,10 +1,11 @@
import dynamic from "next/dynamic";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import React from "react";
import { Slash } from "lucide-react";
import { ExtendedRecordMap } from "notion-types";
+import { parsePageId } from "notion-utils";
import { useQueryState } from "nuqs";
import { NotionRenderer } from "react-notion-x";
// core styles shared by all of react-notion-x (required)
@@ -104,22 +105,17 @@ const obfuscateNotionIds = (container: HTMLElement) => {
uuidPattern.lastIndex = 0;
});
- // Obfuscate anchor href attributes that contain hash references to Notion IDs
- // This is important for table of contents links to work after ID obfuscation
- const anchorsWithHash = container.querySelectorAll('a[href^="#"]');
- anchorsWithHash.forEach((anchor) => {
+ // Obfuscate anchor href attributes that contain Notion IDs
+ const anchors = container.querySelectorAll("a[href]");
+ anchors.forEach((anchor) => {
const href = anchor.getAttribute("href");
- if (href) {
- // Extract the hash part (remove the leading #)
- const hashId = href.slice(1);
- if (uuidPattern.test(hashId)) {
- const newHashId = hashId.replace(uuidPattern, (match) =>
- getObfuscatedId(match),
- );
- anchor.setAttribute("href", `#${newHashId}`);
- }
- uuidPattern.lastIndex = 0;
+ if (href && uuidPattern.test(href)) {
+ const newHref = href.replace(uuidPattern, (match) =>
+ getObfuscatedId(match),
+ );
+ anchor.setAttribute("href", newHref);
}
+ uuidPattern.lastIndex = 0;
});
};
@@ -278,11 +274,9 @@ export const NotionPage = ({
};
}, [screenshotProtectionEnabled]);
- // Memoize the fetchSubPage function
const fetchSubPage = useCallback(
async (pageId: string | null) => {
if (pageId) {
- // Check if the recordMap is already in the cache
if (recordMapCache.current[pageId]) {
const currentRecordMap = recordMapCache.current[pageId];
setRecordMapState(currentRecordMap);
@@ -291,7 +285,6 @@ export const NotionPage = ({
setSubTitle(
firstBlock?.value?.properties?.title?.[0]?.[0] || "Untitled",
);
- // Scroll to top when changing subpages
window.scrollTo({ top: 0, behavior: "smooth" });
return;
}
@@ -306,15 +299,13 @@ export const NotionPage = ({
},
});
const newRecordMap = await response.json();
- // Store the fetched recordMap in the cache
recordMapCache.current[pageId] = newRecordMap;
setRecordMapState(newRecordMap);
const firstBlockId = Object.keys(newRecordMap.block)[0];
- const firstBlock = recordMap.block[firstBlockId];
+ const firstBlock = newRecordMap.block[firstBlockId];
setSubTitle(
firstBlock?.value?.properties?.title?.[0]?.[0] || "Untitled",
);
- // Scroll to top after loading new subpage
window.scrollTo({ top: 0, behavior: "smooth" });
} catch (error) {
console.error("Error fetching subpage:", error);
@@ -323,19 +314,16 @@ export const NotionPage = ({
}
} else {
setRecordMapState(recordMap);
- // get the first item in the recordMap.block object
const firstBlockId = Object.keys(recordMap.block)[0];
const firstBlock = recordMap.block[firstBlockId];
setTitle(firstBlock?.value?.properties?.title?.[0]?.[0] || "Untitled");
- // Scroll to top when returning to main page
window.scrollTo({ top: 0, behavior: "smooth" });
}
},
- [subPageId, recordMap],
+ [recordMap],
);
- // Use useMemo to memoize the effect of fetching the subpage
- useMemo(() => {
+ useEffect(() => {
fetchSubPage(subPageId);
}, [subPageId, fetchSubPage]);
@@ -467,19 +455,20 @@ export const NotionPage = ({
useEffect(() => {
if (!notionContainerRef.current) return;
- // Initial obfuscation
const timeoutId = setTimeout(() => {
if (notionContainerRef.current) {
obfuscateNotionIds(notionContainerRef.current);
}
}, 100);
- // Set up MutationObserver to handle dynamically loaded content
- const observer = new MutationObserver((mutations) => {
- // Debounce the obfuscation to avoid excessive processing
- if (notionContainerRef.current) {
- obfuscateNotionIds(notionContainerRef.current);
- }
+ let debounceTimer: ReturnType<typeof setTimeout>;
+ const observer = new MutationObserver(() => {
+ clearTimeout(debounceTimer);
+ debounceTimer = setTimeout(() => {
+ if (notionContainerRef.current) {
+ obfuscateNotionIds(notionContainerRef.current);
+ }
+ }, 50);
});
observer.observe(notionContainerRef.current, {
@@ -490,6 +479,7 @@ export const NotionPage = ({
return () => {
clearTimeout(timeoutId);
+ clearTimeout(debounceTimer);
observer.disconnect();
};
}, [recordMapState]);
@@ -557,28 +547,51 @@ export const NotionPage = ({
components={{
Collection,
Code,
- PageLink: (props: {
- className: string;
- href: any;
- children:
- | string
- | number
- | boolean
- | React.ReactElement<
- any,
- string | React.JSXElementConstructor<any>
- >
- | React.ReactPortal
- | null
- | undefined;
+ PageLink: ({
+ href,
+ className,
+ children,
+ style,
+ ...rest
+ }: {
+ href?: string;
+ className?: string;
+ children?: React.ReactNode;
+ style?: React.CSSProperties;
+ [key: string]: any;
}) => {
+ const handleClick = (e: React.MouseEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (!href) return;
+
+ const pageId =
+ parsePageId(href, { uuid: false }) ??
+ href.split("/").pop()?.split("?")[0]?.split("#")[0];
+
+ if (pageId) {
+ setSubPageId(pageId);
+ }
+ };
+
return (
- <div
- className={props.className}
- onClick={() => setSubPageId(props.href.split("/")[1])}
+ <a
+ className={className}
+ style={style}
+ href={href}
+ onClick={handleClick}
+ role="link"
+ tabIndex={0}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ handleClick(
+ e as unknown as React.MouseEvent,
+ );
+ }
+ }}
>
- {props.children}
- </div>
+ {children}
+ </a>
);
},
}}
diff --git a/lib/notion/utils.ts b/lib/notion/utils.ts
index c3eec0df..287d6a93 100644
--- a/lib/notion/utils.ts
+++ b/lib/notion/utils.ts
@@ -96,38 +96,50 @@ export function normalizeRecordMap(recordMap: ExtendedRecordMap): void {
}
/**
- * Fetches missing page blocks that are referenced in rich text but not in the recordMap.
- * This fixes the issue where tables with multiple page links only show the first one.
+ * Fetches missing page blocks that are referenced in rich text or as alias
+ * targets but not present in the recordMap.
*/
export async function fetchMissingPageReferences(
recordMap: ExtendedRecordMap,
): Promise<void> {
- // Normalize first so we can safely access block.value.properties
normalizeRecordMap(recordMap);
const allPageReferenceIds = new Set<string>();
- // Iterate through all blocks to find page references in their properties
for (const blockId of Object.keys(recordMap.block)) {
- const block = recordMap.block[blockId]?.value;
- if (!block?.properties) continue;
+ const block = recordMap.block[blockId]?.value as any;
+ if (!block) continue;
+
+ // Collect page references from rich text properties
+ if (block.properties) {
+ for (const propKey of Object.keys(block.properties)) {
+ const propValue = block.properties[propKey];
+ const pageIds = extractPageReferencesFromRichText(propValue);
+ pageIds.forEach((id) => allPageReferenceIds.add(id));
+ }
+ }
- // Check all properties for page references
- for (const propKey of Object.keys(block.properties)) {
- const propValue = block.properties[propKey];
- const pageIds = extractPageReferencesFromRichText(propValue);
- pageIds.forEach((id) => allPageReferenceIds.add(id));
+ // Collect alias (link-to-page) targets
+ if (block.type === "alias" && block.format?.alias_pointer?.id) {
+ allPageReferenceIds.add(block.format.alias_pointer.id);
+ }
+
+ // Collect child page references from content array
+ if (block.content && Array.isArray(block.content)) {
+ for (const childId of block.content) {
+ if (typeof childId === "string" && !recordMap.block[childId]) {
+ allPageReferenceIds.add(childId);
+ }
+ }
}
}
- // Filter out page IDs that are already in the recordMap
const missingPageIds = Array.from(allPageReferenceIds).filter(
(id) => !recordMap.block[id],
);
if (missingPageIds.length === 0) return;
- // Fetch missing blocks in batches
try {
const newBlocks = await notion.getBlocks(missingPageIds);
if (newBlocks?.recordMap?.block) {
@@ -136,7 +148,6 @@ export async function fetchMissingPageReferences(
...newBlocks.recordMap.block,
};
}
- // Normalize again after merging new blocks (getBlocks may return double-nested format)
normalizeRecordMap(recordMap);
} catch (err) {
console.warn("Failed to fetch missing page references:", err);