Skip to content

feat: subpages (child pages) list node - #1462

Merged
Philipinho merged 4 commits into
mainfrom
feat/subpages-node
Aug 31, 2025
Merged

Philipinho merged 4 commits into
mainfrom
feat/subpages-node

Conversation

@Philipinho

@Philipinho Philipinho commented Aug 11, 2025 •

Copy link
Copy Markdown
Member

Todo:

  • Handle subpages in shared pages where subpages are not also shared.

Summary by CodeRabbit

  • New Features

    • Subpages block: shows child pages with links, icons, loading/empty/error states and supports shared-page context.
    • Slash-menu entry and bubble menu (with delete) to insert/manage Subpages.
    • Shared-page sync and a hook to derive subpages; read-only editor now accepts pageId.
    • Added English translations for subpages-related strings.
  • Bug Fixes

    • Sidebar subpages query now waits for page or space data and authorizes by the page’s space.

@Philipinho Philipinho changed the title feat: subpages list node feat: subpages (child pages) list node Aug 11, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (13)
apps/server/src/core/page/dto/sidebar-page.dto.ts (1)

1-3: Remove unused import

SpaceIdDto is no longer used. Clean up the import.

-import { SpaceIdDto } from './page.dto';
apps/server/src/core/page/page.controller.ts (2)

266-271: Use NotFoundException for missing page (consistency with other endpoints)

Elsewhere in this controller, missing pages return NotFound. Returning Forbidden here is inconsistent.

-      if (!page) {
-        throw new ForbiddenException();
-      }
+      if (!page) {
+        throw new NotFoundException('Page not found');
+      }

If you intentionally used 403 to avoid leaking existence, add a brief comment to document that choice for future readers.


262-271: Optional: guard against mismatched spaceId/pageId inputs

If both spaceId and pageId are provided and don’t match, you currently ignore dto.spaceId by deriving from the page. Consider validating and rejecting contradictory inputs to prevent client-side confusion.

Example check:

if (dto.pageId) {
  const page = await this.pageRepo.findById(dto.pageId);
  if (!page) throw new NotFoundException('Page not found');

  if (dto.spaceId && dto.spaceId !== page.spaceId) {
    throw new BadRequestException('spaceId does not match page.spaceId');
  }
  spaceId = page.spaceId;
}
apps/client/public/locales/en-US/translation.json (1)

498-503: Terminology consistency: “subpages” vs “sub-pages”

Existing keys use “sub-pages” (with hyphen), while new ones use “Subpages”. Consider standardizing for consistency across the UI.

Possible alignment:

  • "Sub-pages"
  • "Failed to load sub-pages"
  • "No sub-pages"
  • "Sub-pages (Child pages)"
  • "List all sub-pages of the current page"
packages/editor-ext/src/lib/subpages/subpages.ts (2)

9-9: Replace empty interface with a type alias

Avoid empty interfaces. Use a type alias to satisfy Biome and improve clarity.

-export interface SubpagesAttributes {}
+export type SubpagesAttributes = Record<string, never>;

4-7: Tighten option typing for view component

view: any hides intent. Type it as the React NodeView component used by ReactNodeViewRenderer.

 export interface SubpagesOptions {
   HTMLAttributes: Record<string, any>;
-  view: any;
+  view?: React.ComponentType<NodeViewProps>;
 }

Add this import at the top of the file:

import type { NodeViewProps } from "@tiptap/react";
apps/client/src/features/editor/components/subpages/subpages-menu.tsx (2)

18-22: Prefer strong typing over any for ShouldShowProps.state

Type state as EditorState (or reuse a shared ShouldShowProps type) for consistency with other menus.

-interface ShouldShowProps {
-  state: any;
+interface ShouldShowProps {
+  state: EditorState;
   from?: number;
   to?: number;
 }

Add this import:

import type { EditorState } from "@tiptap/pm/state";

Alternatively, import and reuse the existing ShouldShowProps from apps/client/src/features/editor/components/table/types/types.ts to keep consistency.


39-51: Optional: Guard nodeDOM casting for safety

nodeDOM may return a Node; ensure it’s an Element before calling getBoundingClientRect.

-      if (parent) {
-        const dom = editor.view.nodeDOM(parent?.pos) as HTMLElement;
-        return dom.getBoundingClientRect();
-      }
+      if (parent) {
+        const dom = editor.view.nodeDOM(parent.pos);
+        if (dom && dom instanceof Element) {
+          return dom.getBoundingClientRect();
+        }
+      }
apps/client/src/features/editor/components/subpages/subpages-view.tsx (5)

18-22: Guard query input; pass null when pageId is not available

Helps keep the query key/intent explicit and avoids constructing an object with undefined values. Also pulls in isError for clearer error handling downstream.

Please confirm editor.storage.pageId is always set for this NodeView; otherwise this guard prevents accidental queries.

-  const currentPageId = editor.storage.pageId;
-  const { data, isLoading, error } = useGetSidebarPagesQuery({
-    pageId: currentPageId,
-  });
+  const currentPageId = editor.storage.pageId;
+  const sidebarParams = currentPageId ? { pageId: currentPageId } : null;
+  const { data, isLoading, error, isError } = useGetSidebarPagesQuery(sidebarParams);

29-31: Keep a stable NodeView DOM while loading

Returning null removes the node from the DOM and can cause selection/measure flicker. Keep the wrapper to stabilize the selection box.

-  if (isLoading) {
-    return null;
-  }
+  if (isLoading) {
+    return <NodeViewWrapper />;
+  }

33-41: Preserve stale data on error when available

TanStack returns stale data alongside errors during background refetches. Only show the error placeholder if there’s no usable data.

-  if (error) {
+  if (isError && (!data || !data.pages || data.pages.length === 0)) {
     return (
       <NodeViewWrapper>
         <Text c="dimmed" size="md" py="md">
           {t("Failed to load subpages")}
         </Text>
       </NodeViewWrapper>
     );
   }

69-81: A11y: mark decorative icon as hidden from assistive tech

The fallback icon is purely decorative. Hide it from screen readers and ensure it’s not focusable.

-              ) : (
-                <ActionIcon
+              ) : (
+                <ActionIcon
                   variant="transparent"
                   color="gray"
                   component="span"
                   size={18}
                   style={{ verticalAlign: "text-bottom" }}
+                  aria-hidden="true"
+                  tabIndex={-1}
                 >
-                  <IconFileDescription size={18} />
+                  <IconFileDescription size={18} aria-hidden="true" focusable="false" />
                 </ActionIcon>
               )}

23-27: Optional: tie-break sort and ensure robust shape

If multiple items share the same position across pages, consider a stable tie-breaker (e.g., createdAt or id). Also, guard for items possibly lacking position.

You could do:

  • allPages.sort((a, b) => a.position - b.position || a.id.localeCompare(b.id))
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5012a68 and 4f758ec.

📒 Files selected for processing (15)
  • apps/client/public/locales/en-US/translation.json (1 hunks)
  • apps/client/src/features/editor/components/slash-menu/menu-items.ts (2 hunks)
  • apps/client/src/features/editor/components/subpages/subpages-menu.tsx (1 hunks)
  • apps/client/src/features/editor/components/subpages/subpages-view.tsx (1 hunks)
  • apps/client/src/features/editor/components/subpages/subpages.module.css (1 hunks)
  • apps/client/src/features/editor/extensions/extensions.ts (3 hunks)
  • apps/client/src/features/editor/page-editor.tsx (2 hunks)
  • apps/client/src/features/page/queries/page-query.ts (1 hunks)
  • apps/client/src/features/page/types/page.types.ts (1 hunks)
  • apps/server/src/collaboration/collaboration.util.ts (2 hunks)
  • apps/server/src/core/page/dto/sidebar-page.dto.ts (1 hunks)
  • apps/server/src/core/page/page.controller.ts (1 hunks)
  • packages/editor-ext/src/index.ts (1 hunks)
  • packages/editor-ext/src/lib/subpages/index.ts (1 hunks)
  • packages/editor-ext/src/lib/subpages/subpages.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (6)
apps/client/src/features/editor/components/subpages/subpages-view.tsx (3)
apps/client/src/features/page/queries/page-query.ts (1)
  • useGetSidebarPagesQuery (250-263)
apps/client/src/features/page/tree/utils/utils.ts (1)
  • sortPositionKeys (4-10)
apps/client/src/features/page/page.utils.ts (1)
  • buildPageUrl (14-23)
apps/client/src/features/editor/page-editor.tsx (1)
apps/client/src/features/editor/components/subpages/subpages-menu.tsx (1)
  • SubpagesMenu (24-93)
apps/client/src/features/editor/components/subpages/subpages-menu.tsx (1)
apps/client/src/features/editor/components/table/types/types.ts (1)
  • ShouldShowProps (13-20)
apps/server/src/collaboration/collaboration.util.ts (2)
packages/editor-ext/src/lib/subpages/index.ts (1)
  • Subpages (1-1)
packages/editor-ext/src/lib/subpages/subpages.ts (1)
  • Subpages (19-68)
apps/client/src/features/editor/extensions/extensions.ts (2)
packages/editor-ext/src/lib/subpages/subpages.ts (1)
  • Subpages (19-68)
apps/client/src/features/editor/components/subpages/subpages-view.tsx (1)
  • SubpagesView (13-92)
packages/editor-ext/src/lib/subpages/subpages.ts (1)
packages/editor-ext/src/lib/subpages/index.ts (3)
  • SubpagesOptions (2-2)
  • SubpagesAttributes (2-2)
  • Subpages (1-1)
🪛 Biome (2.1.2)
packages/editor-ext/src/lib/subpages/subpages.ts

[error] 9-9: An empty interface is equivalent to {}.

Safe fix: Use a type alias instead.

(lint/suspicious/noEmptyInterface)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (9)
apps/server/src/core/page/page.controller.ts (1)

273-279: LGTM on permission check and service call

Authorizing against the derived spaceId and passing dto.pageId to scope subpages is correct.

packages/editor-ext/src/lib/subpages/subpages.ts (1)

41-50: LGTM: HTML render/parse shape is correct

Renders a div with data-type="subpages" and merges attributes; parseHTML matches the same. Consistent and minimal.

packages/editor-ext/src/index.ts (1)

22-22: Public export looks good

Re-exporting subpages from the package root enables client/server imports cleanly.

apps/client/src/features/page/queries/page-query.ts (1)

255-256: Correctly gates the query when pageId or spaceId is present

Prevents calling getSidebarPages with null params and aligns with backend changes.

apps/client/src/features/editor/components/slash-menu/menu-items.ts (1)

362-370: Slash command for Subpages is wired correctly

Uses insertSubpages() after deleting the range. Matches the new node command API.

apps/server/src/collaboration/collaboration.util.ts (1)

35-36: Server TipTap config updated appropriately

Including Subpages in the extension set keeps JSON/HTML pipelines consistent.

Also applies to: 83-84

apps/client/src/features/editor/extensions/extensions.ts (1)

41-42: Client extension registration looks good

Subpages.configure({ view: SubpagesView }) correctly wires the React NodeView.

Also applies to: 61-61, 217-219

apps/client/src/features/editor/page-editor.tsx (1)

34-34: UI integration of SubpagesMenu is correct

Menu is imported and rendered with the other bubble menus when editable.

Also applies to: 395-395

packages/editor-ext/src/lib/subpages/index.ts (1)

1-2: Public exports look good

Clean barrel exports for the node and its types; this unblocks consumer imports via the editor-ext public API.

Comment on lines +52 to +60
const deleteNode = useCallback(() => {
const { selection } = editor.state;
editor
.chain()
.focus()
.setNodeSelection(selection.from)
.deleteSelection()
.run();
}, [editor]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Delete the exact Subpages node reliably

Using selection.from may fail if the selection isn’t a node selection. Resolve the parent “subpages” node and delete that selection.

-    const deleteNode = useCallback(() => {
-      const { selection } = editor.state;
-      editor
-        .chain()
-        .focus()
-        .setNodeSelection(selection.from)
-        .deleteSelection()
-        .run();
-    }, [editor]);
+    const deleteNode = useCallback(() => {
+      const { state } = editor;
+      const predicate = (node: PMNode) => node.type.name === "subpages";
+      const parent = findParentNode(predicate)(state.selection);
+      if (parent) {
+        editor.chain().focus().setNodeSelection(parent.pos).deleteSelection().run();
+      } else {
+        editor.chain().focus().deleteSelection().run();
+      }
+    }, [editor]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const deleteNode = useCallback(() => {
const { selection } = editor.state;
editor
.chain()
.focus()
.setNodeSelection(selection.from)
.deleteSelection()
.run();
}, [editor]);
const deleteNode = useCallback(() => {
const { state } = editor;
const predicate = (node: PMNode) => node.type.name === "subpages";
const parent = findParentNode(predicate)(state.selection);
if (parent) {
editor.chain().focus().setNodeSelection(parent.pos).deleteSelection().run();
} else {
editor.chain().focus().deleteSelection().run();
}
}, [editor]);
🤖 Prompt for AI Agents
In apps/client/src/features/editor/components/subpages-menu.tsx around lines 52
to 60, the deleteNode callback uses selection.from which can be wrong if the
selection isn't a node selection; instead resolve the parent "subpages" node and
delete that node selection. Update the callback to: get the current
editor.state.selection, find the parent node (by type name or predicate) for the
subpages container (using resolvePosition/findParentNode/findParentNodeOfType),
compute its node position, set a node selection at that position (or
setNodeSelection with the node's pos), then call deleteSelection and run; handle
the case where the parent isn't found by no-op or showing feedback.

return (
<BaseBubbleMenu
editor={editor}
pluginKey={`subpages-menu}`}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix BubbleMenu pluginKey typo

Remove the stray closing brace to avoid unexpected plugin key and potential collisions.

-        pluginKey={`subpages-menu}`}
+        pluginKey="subpages-menu"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pluginKey={`subpages-menu}`}
pluginKey="subpages-menu"
🤖 Prompt for AI Agents
In apps/client/src/features/editor/components/subpages/subpages-menu.tsx around
line 65, there's a typo in the BubbleMenu prop: the pluginKey includes a stray
closing brace ("subpages-menu}") which creates an unintended plugin key; remove
the extra brace so the pluginKey is "subpages-menu" (i.e., correct the string
literal to not include the trailing '}') and save.

Comment on lines +1 to +8
.container {
margin: 0;
padding-left: 4px;

a {
border: none !important;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Avoid nested CSS in .module.css unless nesting is configured; flatten selector

The nested a { ... } inside .container {} will be invalid CSS unless you have CSS nesting enabled. Prefer a flat selector and avoid !important where possible.

Apply this change:

 .container {
   margin: 0;
   padding-left: 4px;
-
-  a {
-    border: none !important;
-  }
 }
+
+/* Style anchors inside the container without nesting */
+.container a {
+  border: 0;
+  /* Consider also removing underlines if that's the goal */
+  /* text-decoration: none; */
+}

If you intended to use CSS Nesting, confirm it’s enabled. You can verify quickly:


🏁 Script executed:

#!/bin/bash
# Check for PostCSS config and nesting usage
fd -a -t f -E node_modules -E dist -E build 'postcss.config.*' | xargs -r -I{} sh -c 'echo "--- {} ---"; cat "{}"'
rg -n "postcss-nesting|nesting-rules|postcss-preset-env|nesting" -S

Length of output: 701


Flatten nested selectors in CSS module and remove !important

Nested rules aren’t supported—your PostCSS config doesn’t include a nesting plugin—so the a { … } block will be dropped at build time. Please flatten the selector and avoid !important.

• File: apps/client/src/features/editor/components/subpages/subpages.module.css
• Lines: 1–8

 .container {
   margin: 0;
   padding-left: 4px;
-  a {
-    border: none !important;
-  }
 }
 
+/* Flat selector for anchors inside the container */
+.container a {
+  border: none;
+  /* If you also want to remove underlines:
+     text-decoration: none; */
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
.container {
margin: 0;
padding-left: 4px;
a {
border: none !important;
}
}
.container {
margin: 0;
padding-left: 4px;
}
/* Flat selector for anchors inside the container */
.container a {
border: none;
/* If you also want to remove underlines:
text-decoration: none; */
}
🤖 Prompt for AI Agents
In apps/client/src/features/editor/components/subpages/subpages.module.css
around lines 1 to 8, the nested `a { ... }` block is unsupported by your PostCSS
config and will be dropped and the use of `!important` should be avoided;
replace the nested rule with a flattened selector like `.container a { border:
none; }` (or a more specific class if needed) and remove the `!important` flag
so the rule can be applied reliably by specificity instead.

Comment on lines 62 to 66
export interface SidebarPagesParams {
spaceId: string;
spaceId?: string;
pageId?: string;
page?: number; // pagination
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Express “either spaceId or pageId” at the type level

Making spaceId optional is fine, but you can prevent invalid calls at compile time by using a union that enforces at least one of spaceId or pageId.

-export interface SidebarPagesParams {
-  spaceId?: string;
-  pageId?: string;
-  page?: number; // pagination
-}
+export type SidebarPagesParams =
+  | { spaceId: string; pageId?: string; page?: number }
+  | { pageId: string; spaceId?: string; page?: number };

This mirrors the server contract (either identifier is required) and reduces runtime errors.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export interface SidebarPagesParams {
spaceId: string;
spaceId?: string;
pageId?: string;
page?: number; // pagination
}
export type SidebarPagesParams =
| { spaceId: string; pageId?: string; page?: number }
| { pageId: string; spaceId?: string; page?: number };
🤖 Prompt for AI Agents
In apps/client/src/features/page/types/page.types.ts around lines 62 to 66, the
current SidebarPagesParams allows both spaceId and pageId to be omitted; change
the type to enforce at the type level that at least one identifier is present by
replacing the loose optional properties with a union that requires either
spaceId or pageId (while keeping page optional). Implement this as a union of
two object shapes (one with required spaceId and the other with required pageId,
marking the opposite field as absent/never to prevent both being set
simultaneously) so callers must provide one of the identifiers at compile time.

Comment on lines 9 to 11
@IsOptional()
@IsString()
pageId: string;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Validate pageId as UUID for consistency

pageId is looked up via findById, so it should be a UUID. Align with other DTOs that use @IsUUID().

-  @IsOptional()
-  @IsString()
-  pageId: string;
+  @IsOptional()
+  @IsUUID()
+  pageId: string;

Optional enhancement: enforce “at least one of spaceId or pageId” at DTO level with class-validator (custom constraint or ValidateIf), so requests fail early before controller logic.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@IsOptional()
@IsString()
pageId: string;
@IsOptional()
@IsUUID()
pageId: string;

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
apps/client/src/features/editor/components/subpages/subpages.module.css (1)

6-8: Flatten selector and remove !important; nesting likely unsupported here

Replace the nested anchor rule with a flat selector to avoid dropped CSS and remove the unnecessary !important.

   user-select: none;
 
-  a {
-    border: none !important;
-  }
 }
 
+.container a {
+  border: none;
+}
🧹 Nitpick comments (2)
apps/client/src/features/editor/components/subpages/subpages.module.css (2)

4-4: Reconsider user-select: none on the whole container

Preventing text selection can hurt UX (copy/paste). If needed, scope it to specific interactive elements instead.

-  user-select: none;

3-3: Use logical property for RTL/i18n friendliness

Prefer padding-inline-start over padding-left.

-  padding-left: 4px;
+  padding-inline-start: 4px;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 4f758ec and 785a722.

📒 Files selected for processing (1)
  • apps/client/src/features/editor/components/subpages/subpages.module.css (1 hunks)

@Philipinho
Philipinho merged commit 73ee6ee into main Aug 31, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (9)
apps/client/src/features/editor/readonly-page-editor.tsx (2)

57-59: Avoid polluting global editor.storage; namespace and type it.

Setting editor.storage.pageId at the root risks clashes with other extensions and is untyped. Prefer a namespaced bucket and declare types.

Apply:

-            if (pageId) {
-              editor.storage.pageId = pageId;
-            }
+            if (pageId) {
+              // namespace to avoid collisions
+              // eslint-disable-next-line @typescript-eslint/no-explicit-any
+              const ns = ((editor.storage as any).docmost ??= {});
+              ns.pageId = pageId;
+            }

And add a module augmentation (anywhere in a .d.ts you own, e.g. types/tiptap.d.ts):

import '@tiptap/core';
declare module '@tiptap/core' {
  interface EditorStorage {
    docmost?: { pageId?: string };
  }
}

60-61: Remove ts-ignore by aligning the atom type and add cleanup.

Type the atom to TipTap’s Editor and clear it on unmount so TableOfContents doesn’t hold a destroyed instance.

Apply in your atom file (apps/client/src/features/editor/atoms/editor-atoms.ts):

+import type { Editor } from '@tiptap/core';
-export const readOnlyEditorAtom = atom(null)
+export const readOnlyEditorAtom = atom<Editor | null>(null);

Then add a cleanup effect here:

-import React, { useMemo } from "react";
+import React, { useEffect, useMemo } from "react";
...
   const [, setReadOnlyEditor] = useAtom(readOnlyEditorAtom);
+  useEffect(() => () => setReadOnlyEditor(null), [setReadOnlyEditor]);
apps/client/src/features/share/hooks/use-shared-page-subpages.ts (1)

12-28: Consider signaling “not found” vs “no children”.

Today both cases return [], which may block UX that needs to tell “subpages exist but aren’t shared” vs “page has no children” (see PR TODO). Optionally return a tuple/shape with a found flag.

Example:

-export function useSharedPageSubpages(pageId: string | undefined) {
+export function useSharedPageSubpages(pageId: string | undefined) {
   const treeData = useAtomValue(sharedTreeDataAtom);
 
-  return useMemo(() => {
-    if (!treeData || !pageId) return [];
+  return useMemo(() => {
+    if (!treeData || !pageId) return { subpages: [], found: false };
 
-    function findSubpages(nodes: SharedPageTreeNode[]): SharedPageTreeNode[] {
+    function findSubpages(nodes: SharedPageTreeNode[]): { subpages: SharedPageTreeNode[]; found: boolean } {
       for (const node of nodes) {
         if (node.value === pageId || node.slugId === pageId) {
-          return node.children || [];
+          return { subpages: node.children ?? [], found: true };
         }
         if (node.children && node.children.length > 0) {
           const subpages = findSubpages(node.children);
-          if (subpages.length > 0) {
-            return subpages;
+          if (subpages.found) {
+            return subpages;
           }
         }
       }
-      return [];
+      return { subpages: [], found: false };
     }
 
-    return findSubpages(treeData);
+    return findSubpages(treeData);
   }, [treeData, pageId]);
 }
apps/client/src/features/share/components/share-shell.tsx (1)

74-77: Clear shared atoms on unmount to avoid stale cross-route state.

Without cleanup, old tree data can leak after leaving the share view.

Apply:

 useEffect(() => {
   setSharedPageTree(data || null);
   setSharedTreeData(treeData);
-}, [data, treeData, setSharedPageTree, setSharedTreeData]);
+  return () => {
+    setSharedPageTree(null);
+    setSharedTreeData(null);
+  };
+}, [data, treeData, setSharedPageTree, setSharedTreeData]);
apps/client/src/features/editor/components/subpages/subpages-view.tsx (5)

12-12: Drop .ts extension from import path

Prevents resolver/test flakiness across tooling; keep imports extensionless.

-} from "@/features/page/page.utils.ts";
+} from "@/features/page/page.utils";

19-29: Don’t fetch sidebar pages in shared context

Avoids an unnecessary network call when rendering inside a share. Introduces an isShared flag and disables the query.

-  const { spaceSlug, shareId } = useParams();
-  const { t } = useTranslation();
+  const { spaceSlug, shareId } = useParams();
+  const { t } = useTranslation();
+  const isShared = Boolean(shareId);
@@
-  const { data, isLoading, error } = useGetSidebarPagesQuery({
-    pageId: currentPageId,
-  });
+  const { data, isLoading, error } = useGetSidebarPagesQuery(
+    isShared ? null : { pageId: currentPageId },
+  );

31-47: Normalize and sort shared subpages; use the shared source deterministically

Ensures consistent ordering with API-derived data and simplifies the branch.

-  const subpages = useMemo(() => {
-    // If we're in a shared context, use the shared subpages
-    if (shareId && sharedSubpages) {
-      return sharedSubpages.map((node) => ({
-        id: node.value,
-        slugId: node.slugId,
-        title: node.name,
-        icon: node.icon,
-        position: node.position,
-      }));
-    }
-
-    // Otherwise use the API data
-    if (!data?.pages) return [];
-    const allPages = data.pages.flatMap((page) => page.items);
-    return sortPositionKeys(allPages);
-  }, [data, shareId, sharedSubpages]);
+  const subpages = useMemo(() => {
+    if (isShared) {
+      return sortPositionKeys(
+        sharedSubpages.map((node) => ({
+          id: node.value,
+          slugId: node.slugId,
+          title: node.name,
+          icon: node.icon,
+          position: node.position,
+        })),
+      );
+    }
+    if (!data?.pages) return [];
+    const allPages = data.pages.flatMap((page) => page.items);
+    return sortPositionKeys(allPages);
+  }, [data, isShared, sharedSubpages]);

49-51: Gate loading state off shared mode

Prevents unnecessary null render checks when shared mode is active.

-if (isLoading && !shareId) {
+if (!isShared && isLoading) {
   return null;
 }

61-66: Avoid “No subpages” flash while shared tree is hydrating

In shared mode, the atom may be empty until hydrated; defer the empty state to reduce flicker.

   }
 
-  if (subpages.length === 0) {
+  if (isShared && sharedSubpages.length === 0) {
+    return null;
+  }
+
+  if (subpages.length === 0) {
     return (
       <NodeViewWrapper>
         <div className={classes.container}>
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 785a722 and 6fc520e.

📒 Files selected for processing (6)
  • apps/client/src/features/editor/components/subpages/subpages-view.tsx (1 hunks)
  • apps/client/src/features/editor/readonly-page-editor.tsx (2 hunks)
  • apps/client/src/features/share/atoms/shared-page-atom.ts (1 hunks)
  • apps/client/src/features/share/components/share-shell.tsx (3 hunks)
  • apps/client/src/features/share/hooks/use-shared-page-subpages.ts (1 hunks)
  • apps/client/src/pages/share/shared-page.tsx (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-08-07T21:44:49.482Z
Learnt from: lukasbach
PR: docmost/docmost#1457
File: apps/client/src/features/page/tree/components/space-tree.tsx:520-525
Timestamp: 2025-08-07T21:44:49.482Z
Learning: In the Docmost headless tree implementation (apps/client/src/features/page/tree/components/space-tree.tsx), the useEffect in the PageArrow component intentionally omits the dependency array. This allows isFolder() to run on subsequent renders as needed, since the item reference is stable and wouldn't trigger re-runs when required. This pattern is intentional for performance reasons in the tree component.

Applied to files:

  • apps/client/src/features/share/components/share-shell.tsx
🧬 Code graph analysis (4)
apps/client/src/features/share/hooks/use-shared-page-subpages.ts (2)
apps/client/src/features/share/atoms/shared-page-atom.ts (1)
  • sharedTreeDataAtom (6-6)
apps/client/src/features/share/utils.ts (1)
  • SharedPageTreeNode (4-16)
apps/client/src/features/share/atoms/shared-page-atom.ts (2)
apps/client/src/features/share/types/share.types.ts (1)
  • ISharedPageTree (71-75)
apps/client/src/features/share/utils.ts (1)
  • SharedPageTreeNode (4-16)
apps/client/src/features/share/components/share-shell.tsx (2)
apps/client/src/features/share/atoms/shared-page-atom.ts (2)
  • sharedPageTreeAtom (5-5)
  • sharedTreeDataAtom (6-6)
apps/client/src/features/share/utils.ts (1)
  • buildSharedPageTree (18-68)
apps/client/src/features/editor/components/subpages/subpages-view.tsx (4)
apps/client/src/features/share/hooks/use-shared-page-subpages.ts (1)
  • useSharedPageSubpages (6-29)
apps/client/src/features/page/queries/page-query.ts (1)
  • useGetSidebarPagesQuery (250-263)
apps/client/src/features/page/tree/utils/utils.ts (1)
  • sortPositionKeys (4-10)
apps/client/src/features/page/page.utils.ts (2)
  • buildSharedPageUrl (25-36)
  • buildPageUrl (14-23)
🔇 Additional comments (7)
apps/client/src/features/editor/readonly-page-editor.tsx (2)

9-11: Import path fix looks good.

Switching to jotai’s root entry is correct and avoids deep import pitfalls.


15-16: Prop threading for pageId is reasonable; confirm identity semantics.

Optional: confirm that consumers read the same identifier (data.page.id) you place into storage, not slugId, to avoid mismatches. The key={data.page.id} on the caller will remount the editor, so onCreate will run per page as intended.

Also applies to: 21-22

apps/client/src/pages/share/shared-page.tsx (1)

55-56: Passing pageId is correct and matches tree node “value”.

This aligns with buildSharedPageTree where node.value = page.id, so lookups by id will work.

If any consumer expects slugId instead, adjust accordingly.

apps/client/src/features/share/components/share-shell.tsx (1)

69-73: Memoization is appropriate.

buildSharedPageTree can be non-trivial; guarding with useMemo keyed by data.pageTree is good.

apps/client/src/features/share/atoms/shared-page-atom.ts (1)

5-6: Atom additions look good.

Null defaults are sensible; names are clear.

apps/client/src/features/editor/components/subpages/subpages-view.tsx (2)

57-58: i18n keys exist
The keys "Failed to load subpages", "No subpages", and "untitled" are already defined in translation.json across all locales; no action needed.


85-93: Verify router param typing with URL builders
Make sure you’re using useParams<{ shareId: string; spaceSlug: string }>() (so TS knows both keys are always strings), or else update buildPageUrl/buildSharedPageUrl to accept string | undefined. Confirm there are no type errors when calling those utils.

This was referenced Aug 31, 2025
github-actions Bot added a commit to antiagingrecord/docmost that referenced this pull request Oct 9, 2025
4231ba9 Merge commit '042836cb6d7cc1f71af3ce44c7957f8abbbf8f25' into feat/aar_edition
042836c sync
4f1f0ba fix
3164b69 feat: api keys management (EE) (docmost#1665)
16c1e86 fix comment space
c9b1cad sync
bf8cf62 feat: Typesense search driver (EE) (docmost#1664)
5a2e16a Merge commit '31350303760163384113bf49d07127e886f94907' into feat/aar_edition
3bc710d Adds CLAUDE.md documentation
16914f1 Block search for non-indexed shares
ca75e29 Set default page mode to Read
3135030 fix editor converter (docmost#1647)
3fae41a fix: editor performance improvements (docmost#1648)
b50e256 sync
1f3b0c7 cloud fix
3c4cab0 v0.23.2
4de25a8 invalidate queries on space deletion
cf5bbb1 fix import html processing
ac17521 sync
9ac180f fix: enhance page import (docmost#1570)
46669fe (cloud) disable page sharing in trial mode
fe6ecdf fix: update combobox props in SpaceSelect component (docmost#1564)
04ae1d7 Allow lastColumnResizable in table
1280f96 feat: implement space and workspace icons (docmost#1558)
61d1cf8 fix: reset file inputs after import
f413720 - sync - reinstantiate S3 client to fix file upload errors during import - delete import zip file after use
8e16ad9 v0.23.1
7ada3cb fix: page import task (docmost#1551)
47c5417 sync
dc06502 sync
091e790 fix attachment search in cloud
ae24ea2 v0.23.0
9df6061 lock file
31053e2 update mermaid
eb8e850 use debug
c99bfb8 make print better
26ea04e sync
6cc58c5 sync
7d2ff34 UI fixes
b08d37f fix
d43ee77 remove debug log
5d91eb4 feat: queue imported attachments for indexing
3e9f6b1 Remove version from docker-compose.yml [deprecated] (docmost#1011)
db55de9 feat: progressive web app (docmost#614)
1919eba New Crowdin updates (docmost#1522)
7951b2e New Crowdin updates (docmost#1509)
73b78f6 more translations
cf7534d fix version display
adec36d fix: adjust margins - use default browser highlight background
f9e1080 sync
00e499b Fixing extra page bug on print (docmost#1478)
5ee6e46 checkbox aligned to text (docmost#1486)
1f797c3 fix: confluence drawio import (docmost#1518)
f12866c feat(EE): full-text search in attachments (docmost#1502)
dcbb65d feat(EE): LDAP integration (docmost#1515)
5968764 feat: emoji callout icon (docmost#1323)
242fb6b fix: set mermaid theme based on computed color scheme (docmost#1438)
74cd890 feat(EE): implement SSO group sync for SAML and OIDC (docmost#1452)
509622a ignore type error
937386e fix: hide table handles in readonly mode
60a373f fix: readonly editor table responsiveness
73ee6ee feat: subpages (child pages) list node (docmost#1462)
7d1e5bc feat: table row/column drag and drop (docmost#1467)
aa58e27 fix: exclude deleted pages (docmost#1494)
08135a2 sync
d92a942 sync
5012a68 sync
5a33777 feat: debug mode env variable (docmost#1450)
3b85f4b fix: enforce C collation for page position ordering to ensure consistent behavior in Postgres 17+ (docmost#1446)
cb2a039 fix: invalidate trashed page from tree state
95b7be6 fix: hide trash from can view permission (docmost#1445)
b0c5572 fix nested taskList in markdown export (docmost#1443)
dddfd48 feat: add attachments support for single page exports (docmost#1440)
aa6eec7 fix: exclude trashed pages from position generation
97a7701 fix local storage copy function (docmost#1442)
b97eb85 sync

git-subtree-dir: vendor/app
git-subtree-split: 4231ba9
@Philipinho
Philipinho deleted the feat/subpages-node branch December 14, 2025 19:07
nulluserid pushed a commit to N2con-Inc/docmost that referenced this pull request Dec 17, 2025
* feat: subpages list node

* disable user-select

* support subpages node list in public pages
@docmost docmost deleted a comment from coderabbitai Bot Mar 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant