From bd5de2e18569032829a85a7ee8f6cb412b764900 Mon Sep 17 00:00:00 2001 From: Hemachandar <132386067+hmacr@users.noreply.github.com> Date: Mon, 18 Aug 2025 08:39:49 +0530 Subject: [PATCH] Display correct child document structure & auto open share section (#9854) * Show correct child structure for shared documents * useMemo dep * auto open tree, show child docs in references * document.children --- .../Sidebar/components/DocumentLink.tsx | 40 +++-- .../Sidebar/components/SharedWithMe.tsx | 56 ++++++- .../Sidebar/components/SharedWithMeLink.tsx | 27 ++-- app/models/Document.ts | 22 +++ app/models/GroupMembership.ts | 21 ++- app/models/UserMembership.ts | 21 ++- app/models/base/NavigableModel.ts | 112 ++++++++++++++ app/scenes/Document/components/References.tsx | 5 +- app/stores/GroupMembershipsStore.ts | 16 ++ app/stores/UserMembershipsStore.ts | 16 ++ .../__snapshots__/documents.test.ts.snap | 18 +++ server/routes/api/documents/documents.test.ts | 137 ++++++++++++++++++ server/routes/api/documents/documents.ts | 28 +++- server/routes/api/documents/schema.ts | 6 + 14 files changed, 487 insertions(+), 38 deletions(-) create mode 100644 app/models/base/NavigableModel.ts diff --git a/app/components/Sidebar/components/DocumentLink.tsx b/app/components/Sidebar/components/DocumentLink.tsx index 5b08a06665..72a8f44ee8 100644 --- a/app/components/Sidebar/components/DocumentLink.tsx +++ b/app/components/Sidebar/components/DocumentLink.tsx @@ -33,10 +33,13 @@ import Folder from "./Folder"; import Relative from "./Relative"; import { SidebarContextType, useSidebarContext } from "./SidebarContext"; import SidebarLink from "./SidebarLink"; +import UserMembership from "~/models/UserMembership"; +import GroupMembership from "~/models/GroupMembership"; type Props = { node: NavigationNode; collection?: Collection; + membership?: UserMembership | GroupMembership; activeDocument: Document | null | undefined; prefetchDocument?: (documentId: string) => Promise; isDraft?: boolean; @@ -49,6 +52,7 @@ function InnerDocumentLink( { node, collection, + membership, activeDocument, prefetchDocument, isDraft, @@ -87,20 +91,27 @@ function InnerDocumentLink( isActiveDocument, ]); - const showChildren = React.useMemo( - () => - !!( - hasChildDocuments && - activeDocument && - collection && - (collection - .pathToDocument(activeDocument.id) - .map((entry) => entry.id) - .includes(node.id) || - isActiveDocument) - ), - [hasChildDocuments, activeDocument, isActiveDocument, node, collection] - ); + const showChildren = React.useMemo(() => { + if (!hasChildDocuments || !activeDocument) { + return false; + } + + const pathToDocument = + collection?.pathToDocument(activeDocument.id) ?? + membership?.pathToDocument(activeDocument.id); + + return !!( + pathToDocument?.map((entry) => entry.id).includes(node.id) || + isActiveDocument + ); + }, [ + hasChildDocuments, + activeDocument, + isActiveDocument, + node, + collection, + membership, + ]); const [expanded, setExpanded, setCollapsed] = useBoolean(showChildren); @@ -404,6 +415,7 @@ function InnerDocumentLink( (groupMemberships.fetchAll); @@ -44,6 +48,54 @@ function SharedWithMe() { } }, [error, t]); + useEffect(() => { + const isContextInSharedSection = + locationSidebarContext === "shared" || + locationSidebarContext?.startsWith("group"); + + if (!ui.activeDocumentId || isContextInSharedSection) { + return; + } + + const isActiveDocSharedDirectly = user.documentMemberships.find( + (m) => m.pathToDocument(ui.activeDocumentId!).length > 0 + ); + + if (isActiveDocSharedDirectly) { + history.push({ + ...history.location, + state: { + ...(history.location.state as Record), + sidebarContext: "shared", + }, + }); + + return; + } + + const groupWithActiveDocument = user.groupsWithDocumentMemberships.find( + (group) => + group.documentMemberships.some( + (m) => m.pathToDocument(ui.activeDocumentId!).length > 0 + ) + ); + + if (groupWithActiveDocument) { + history.push({ + ...history.location, + state: { + ...(history.location.state as Record), + sidebarContext: groupSidebarContext(groupWithActiveDocument.id), + }, + }); + } + }, [ + ui.activeDocumentId, + locationSidebarContext, + user.documentMemberships, + user.groupsWithDocumentMemberships, + ]); + if ( !user.documentMemberships.length && !user.groupsWithDocumentMemberships.length diff --git a/app/components/Sidebar/components/SharedWithMeLink.tsx b/app/components/Sidebar/components/SharedWithMeLink.tsx index 054299fa32..6ffd08b560 100644 --- a/app/components/Sidebar/components/SharedWithMeLink.tsx +++ b/app/components/Sidebar/components/SharedWithMeLink.tsx @@ -40,21 +40,20 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { const sidebarContext = useSidebarContext(); const document = documentId ? documents.get(documentId) : undefined; + const isActiveDocumentInPath = ui.activeDocumentId + ? membership.pathToDocument(ui.activeDocumentId).length > 0 + : false; + const [expanded, setExpanded, setCollapsed] = useBoolean( - membership.documentId === ui.activeDocumentId && - locationSidebarContext === sidebarContext + isActiveDocumentInPath && locationSidebarContext === sidebarContext ); React.useEffect(() => { - if ( - membership.documentId === ui.activeDocumentId && - locationSidebarContext === sidebarContext - ) { + if (isActiveDocumentInPath && locationSidebarContext === sidebarContext) { setExpanded(); } }, [ - membership.documentId, - ui.activeDocumentId, + isActiveDocumentInPath, sidebarContext, locationSidebarContext, setExpanded, @@ -63,6 +62,7 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { React.useEffect(() => { if (documentId) { void documents.fetch(documentId); + void membership.fetchDocuments(); } }, [documentId, documents]); @@ -118,9 +118,7 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { ? collections.get(document.collectionId) : undefined; - const node = document.asNavigationNode; - const childDocuments = node.children; - const hasChildDocuments = childDocuments.length > 0; + const childDocuments = membership.documents ?? []; return ( <> @@ -139,7 +137,9 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { state: { sidebarContext }, }} expanded={ - hasChildDocuments && !isDragging ? expanded : undefined + childDocuments.length > 0 && !isDragging + ? expanded + : undefined } onDisclosureClick={handleDisclosureClick} icon={icon} @@ -180,8 +180,9 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { key={childNode.id} node={childNode} collection={collection} + membership={membership} activeDocument={documents.active} - isDraft={node.isDraft} + isDraft={childNode.isDraft} depth={2} index={index} /> diff --git a/app/models/Document.ts b/app/models/Document.ts index 4c4b9f182f..357f05670f 100644 --- a/app/models/Document.ts +++ b/app/models/Document.ts @@ -665,6 +665,28 @@ export default class Document extends ArchivableModel implements Searchable { }; } + /** + * Returns all children of the document. + * This is determined by the collection structure, or the user/group memberships in case it's a shared document. + * + * @returns An array of NavigationNode objects. + */ + @computed + get children(): NavigationNode[] { + const { userMemberships, groupMemberships } = this.store.rootStore; + const collection = this.collection; + + const membership = + userMemberships.getByDocumentId(this.id) ?? + groupMemberships.getByDocumentId(this.id); + + return ( + collection?.getChildrenForDocument(this.id) ?? + membership?.getChildrenForDocument(this.id) ?? + [] + ); + } + /** * Returns the markdown representation of the document derived from the ProseMirror data. * diff --git a/app/models/GroupMembership.ts b/app/models/GroupMembership.ts index e9ff597c41..3d9b14cc31 100644 --- a/app/models/GroupMembership.ts +++ b/app/models/GroupMembership.ts @@ -3,14 +3,14 @@ import { CollectionPermission, DocumentPermission } from "@shared/types"; import Collection from "./Collection"; import Document from "./Document"; import Group from "./Group"; -import Model from "./base/Model"; import { AfterRemove } from "./decorators/Lifecycle"; import Relation from "./decorators/Relation"; +import NavigableModel from "./base/NavigableModel"; /** * Represents a groups's membership to a collection or document. */ -class GroupMembership extends Model { +class GroupMembership extends NavigableModel { static modelName = "GroupMembership"; /** The group ID that this membership is granted to. */ @@ -45,6 +45,23 @@ class GroupMembership extends Model { @observable permission: CollectionPermission | DocumentPermission; + // methods + + /** + * Fetches the child documents structure from the server. + */ + async fetchDocuments(options: { force?: boolean } = {}) { + if (!this.documentId) { + return; + } + + await super.fetchDocuments({ + path: "/documents.documents", + params: { id: this.documentId }, + ...options, + }); + } + // hooks @AfterRemove diff --git a/app/models/UserMembership.ts b/app/models/UserMembership.ts index 49305dcabb..0ab32181e6 100644 --- a/app/models/UserMembership.ts +++ b/app/models/UserMembership.ts @@ -3,12 +3,12 @@ import { DocumentPermission } from "@shared/types"; import type UserMembershipsStore from "~/stores/UserMembershipsStore"; import Document from "./Document"; import User from "./User"; -import Model from "./base/Model"; import Field from "./decorators/Field"; import { AfterRemove } from "./decorators/Lifecycle"; import Relation from "./decorators/Relation"; +import NavigableModel from "./base/NavigableModel"; -class UserMembership extends Model { +class UserMembership extends NavigableModel { static modelName = "UserMembership"; /** The sort order of the membership (In users sidebar) */ @@ -50,6 +50,23 @@ class UserMembership extends Model { store: UserMembershipsStore; + // methods + + /** + * Fetches the child documents structure from the server. + */ + async fetchDocuments(options: { force?: boolean } = {}) { + if (!this.documentId) { + return; + } + + await super.fetchDocuments({ + path: "/documents.documents", + params: { id: this.documentId }, + ...options, + }); + } + /** * Returns the next membership for the same user in the list, or undefined if this is the last. */ diff --git a/app/models/base/NavigableModel.ts b/app/models/base/NavigableModel.ts new file mode 100644 index 0000000000..1244c74cd6 --- /dev/null +++ b/app/models/base/NavigableModel.ts @@ -0,0 +1,112 @@ +import { computed, observable, runInAction } from "mobx"; +import { JSONObject, type NavigationNode } from "@shared/types"; +import { client } from "~/utils/ApiClient"; +import ParanoidModel from "./ParanoidModel"; + +export default abstract class NavigableModel extends ParanoidModel { + private isFetching = false; + + @observable + node?: NavigationNode; + + /** + * Fetches the child documents structure from the server. + */ + async fetchDocuments(options: { + path: string; + params: JSONObject; + force?: boolean; + }) { + if (this.isFetching) { + return; + } + + if (this.documents && options.force !== true) { + return; + } + + try { + this.isFetching = true; + const res = await client.post(options.path, options.params); + + runInAction(`${NavigableModel.modelName}#fetchDocuments`, () => { + this.node = res.data; + }); + } finally { + this.isFetching = false; + } + } + + /** + * Child documents structure of the document shared with this membership. + */ + @computed + get documents(): NavigationNode[] | undefined { + return this.node?.children; + } + + /** + * Returns the document path from the original document shared with this membership. + */ + pathToDocument(documentId: string) { + let path: NavigationNode[] | undefined = []; + const document = this.store.rootStore.documents.get(documentId); + if (!document) { + return path; + } + + const travelNodes = ( + nodes: NavigationNode[], + previousPath: NavigationNode[] + ) => { + nodes.forEach((node) => { + const newPath = [...previousPath, node]; + + if (node.id === documentId) { + path = newPath; + return; + } + + if ( + document.parentDocumentId && + node.id === document.parentDocumentId + ) { + path = [...newPath, document.asNavigationNode]; + return; + } + + return travelNodes(node.children, newPath); + }); + }; + + if (this.node) { + travelNodes([this.node], path); + } + + return path; + } + + /** + * Returns the child documents structure for the document. + */ + getChildrenForDocument(documentId: string) { + let result: NavigationNode[] = []; + + const travelNodes = (nodes: NavigationNode[]) => { + nodes.forEach((node) => { + if (node.id === documentId) { + result = node.children; + return; + } + + return travelNodes(node.children); + }); + }; + + if (this.node) { + travelNodes([this.node]); + } + + return result; + } +} diff --git a/app/scenes/Document/components/References.tsx b/app/scenes/Document/components/References.tsx index a9c6d723a2..fdf23bb231 100644 --- a/app/scenes/Document/components/References.tsx +++ b/app/scenes/Document/components/References.tsx @@ -28,10 +28,7 @@ function References({ document }: Props) { }, [documents, document.id]); const backlinks = document.backlinks; - const collection = document.collection; - const children = collection - ? collection.getChildrenForDocument(document.id) - : []; + const children = document.children; const showBacklinks = !!backlinks.length; const showChildDocuments = !!children.length; const shouldFade = useRef(!showBacklinks && !showChildDocuments); diff --git a/app/stores/GroupMembershipsStore.ts b/app/stores/GroupMembershipsStore.ts index 88356cdd4d..2f8f03eea9 100644 --- a/app/stores/GroupMembershipsStore.ts +++ b/app/stores/GroupMembershipsStore.ts @@ -140,4 +140,20 @@ export default class GroupMembershipsStore extends Store { */ inDocument = (documentId: string) => this.orderedData.filter((cgm) => cgm.documentId === documentId); + + /** + * Returns the group membership associated with the document. + */ + getByDocumentId = (documentId: string): GroupMembership | undefined => { + const membership = this.find({ documentId }); + + if (membership) { + return membership; + } + + const document = this.rootStore.documents.get(documentId); + return document?.parentDocumentId + ? this.getByDocumentId(document.parentDocumentId) + : undefined; + }; } diff --git a/app/stores/UserMembershipsStore.ts b/app/stores/UserMembershipsStore.ts index ea8281bb52..125402d4bd 100644 --- a/app/stores/UserMembershipsStore.ts +++ b/app/stores/UserMembershipsStore.ts @@ -101,4 +101,20 @@ export default class UserMembershipsStore extends Store { return a.index < b.index ? -1 : 1; }); } + + /** + * Returns the user membership associated with the document. + */ + getByDocumentId = (documentId: string): UserMembership | undefined => { + const membership = this.find({ documentId }); + + if (membership) { + return membership; + } + + const document = this.rootStore.documents.get(documentId); + return document?.parentDocumentId + ? this.getByDocumentId(document.parentDocumentId) + : undefined; + }; } diff --git a/server/routes/api/documents/__snapshots__/documents.test.ts.snap b/server/routes/api/documents/__snapshots__/documents.test.ts.snap index d1eaf5ed78..7421c547b4 100644 --- a/server/routes/api/documents/__snapshots__/documents.test.ts.snap +++ b/server/routes/api/documents/__snapshots__/documents.test.ts.snap @@ -18,6 +18,24 @@ exports[`#documents.delete should require authentication 1`] = ` } `; +exports[`#documents.documents should require authentication 1`] = ` +{ + "error": "authentication_required", + "message": "Authentication required", + "ok": false, + "status": 401, +} +`; + +exports[`#documents.documents should return 403 if user does not have access to the document 1`] = ` +{ + "error": "authorization_error", + "message": "Authorization error", + "ok": false, + "status": 403, +} +`; + exports[`#documents.empty_trash should not allow non-admin users 1`] = ` { "error": "authorization_error", diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index 2c72c3228f..b982b9ff4d 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -5323,3 +5323,140 @@ describe("#documents.empty_trash", () => { expect(body).toMatchSnapshot(); }); }); + +describe("#documents.documents", () => { + it("should return document tree for a document in a collection", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + userId: user.id, + teamId: user.teamId, + }); + const parent = await buildDocument({ + userId: user.id, + collectionId: collection.id, + teamId: user.teamId, + }); + const child1 = await buildDocument({ + userId: user.id, + collectionId: collection.id, + teamId: user.teamId, + parentDocumentId: parent.id, + title: "Child 1", + }); + const child2 = await buildDocument({ + userId: user.id, + collectionId: collection.id, + teamId: user.teamId, + parentDocumentId: parent.id, + title: "Child 2", + }); + + const res = await server.post("/api/documents.documents", { + body: { + token: user.getJwtToken(), + id: parent.id, + }, + }); + const body = await res.json(); + + expect(res.status).toBe(200); + expect(body.data.id).toBe(parent.id); + const childIds = body.data.children.map((node: any) => node.id); + expect(childIds).toContain(child1.id); + expect(childIds).toContain(child2.id); + }); + + it("should have empty children nodes if document has no children", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + userId: user.id, + teamId: user.teamId, + }); + const parent = await buildDocument({ + userId: user.id, + collectionId: collection.id, + teamId: user.teamId, + }); + + const res = await server.post("/api/documents.documents", { + body: { + token: user.getJwtToken(), + id: parent.id, + }, + }); + const body = await res.json(); + + expect(res.status).toBe(200); + expect(body.data.id).toBe(parent.id); + expect(body.data.children.length).toBe(0); + }); + + it("should return undefined if document is not part of a collection", async () => { + const user = await buildUser(); + const doc = await buildDocument({ + userId: user.id, + teamId: user.teamId, + collectionId: null, + }); + + const res = await server.post("/api/documents.documents", { + body: { + token: user.getJwtToken(), + id: doc.id, + }, + }); + const body = await res.json(); + + expect(res.status).toBe(200); + expect(body.data).toBeUndefined(); + }); + + it("should require authentication", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + userId: user.id, + teamId: user.teamId, + }); + const parent = await buildDocument({ + userId: user.id, + collectionId: collection.id, + teamId: user.teamId, + }); + + const res = await server.post("/api/documents.documents", { + body: { + id: parent.id, + }, + }); + const body = await res.json(); + + expect(res.status).toBe(401); + expect(body).toMatchSnapshot(); + }); + + it("should return 403 if user does not have access to the document", async () => { + const user = await buildUser(); + const otherUser = await buildUser(); + const collection = await buildCollection({ + userId: otherUser.id, + teamId: otherUser.teamId, + permission: null, + }); + const parent = await buildDocument({ + userId: otherUser.id, + collectionId: collection.id, + teamId: otherUser.teamId, + }); + + const res = await server.post("/api/documents.documents", { + body: { + token: user.getJwtToken(), + id: parent.id, + }, + }); + const body = await res.json(); + + expect(res.status).toBe(403); + expect(body).toMatchSnapshot(); + }); +}); diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index 0360ecf15b..fa00ac96d6 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -13,7 +13,7 @@ import uniq from "lodash/uniq"; import mime from "mime-types"; import { Op, ScopeOptions, Sequelize, WhereOptions } from "sequelize"; import { v4 as uuidv4 } from "uuid"; -import { StatusFilter, UserRole } from "@shared/types"; +import { NavigationNode, StatusFilter, UserRole } from "@shared/types"; import { subtractDate } from "@shared/utils/date"; import slugify from "@shared/utils/slugify"; import documentCreator from "@server/commands/documentCreator"; @@ -714,6 +714,32 @@ router.post( } ); +router.post( + "documents.documents", + auth(), + validate(T.DocumentsChildrenSchema), + async (ctx: APIContext) => { + const { id } = ctx.input.body; + const { user } = ctx.state.auth; + const document = await Document.findByPk(id, { userId: user.id }); + + authorize(user, "read", document); + + let documentTree: NavigationNode | undefined; + + if (document.collectionId) { + const collection = await Collection.findByPk(document.collectionId, { + includeDocumentStructure: true, + }); + documentTree = collection?.getDocumentTree(document.id) ?? undefined; + } + + ctx.body = { + data: documentTree, + }; + } +); + router.post( "documents.export", rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), diff --git a/server/routes/api/documents/schema.ts b/server/routes/api/documents/schema.ts index ed9733b9d8..a70a00a872 100644 --- a/server/routes/api/documents/schema.ts +++ b/server/routes/api/documents/schema.ts @@ -393,6 +393,12 @@ export const DocumentsUsersSchema = BaseSchema.extend({ export type DocumentsUsersReq = z.infer; +export const DocumentsChildrenSchema = BaseSchema.extend({ + body: BaseIdSchema, +}); + +export type DocumentsChildrenReq = z.infer; + export const DocumentsAddUserSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ /** Id of the user who is to be added */