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
This commit is contained in:
Hemachandar authored and GitHub committed 2025-08-17 23:09:49 -04:00
1 parent b8eefe4b78
commit bd5de2e185
14 files changed
+487 -38

No files matched your search

@@ -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<Document | void>;
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(
<DocumentLink
key={childNode.id}
collection={collection}
membership={membership}
node={childNode}
activeDocument={activeDocument}
prefetchDocument={prefetchDocument}
@@ -18,13 +18,17 @@ import Header from "./Header";
import PlaceholderCollections from "./PlaceholderCollections";
import Relative from "./Relative";
import SharedWithMeLink from "./SharedWithMeLink";
import SidebarContext from "./SidebarContext";
import SidebarContext, { groupSidebarContext } from "./SidebarContext";
import SidebarLink from "./SidebarLink";
import { useHistory } from "react-router-dom";
import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext";
function SharedWithMe() {
const { userMemberships, groupMemberships } = useStores();
const { ui, userMemberships, groupMemberships } = useStores();
const { t } = useTranslation();
const user = useCurrentUser();
const history = useHistory();
const locationSidebarContext = useLocationSidebarContext();
usePaginatedRequest<GroupMembership>(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<string, unknown>),
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<string, unknown>),
sidebarContext: groupSidebarContext(groupWithActiveDocument.id),
},
});
}
}, [
ui.activeDocumentId,
locationSidebarContext,
user.documentMemberships,
user.groupsWithDocumentMemberships,
]);
if (
!user.documentMemberships.length &&
!user.groupsWithDocumentMemberships.length
@@ -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}
/>
+22
View File
@@ -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.
*
+19 -2
View File
@@ -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
+19 -2
View File
@@ -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.
*/
+112
View File
@@ -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;
}
}
@@ -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);
+16
View File
@@ -140,4 +140,20 @@ export default class GroupMembershipsStore extends Store<GroupMembership> {
*/
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;
};
}
+16
View File
@@ -101,4 +101,20 @@ export default class UserMembershipsStore extends Store<UserMembership> {
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;
};
}
@@ -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",
@@ -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();
});
});
+27 -1
View File
@@ -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<T.DocumentsChildrenReq>) => {
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),
+6
View File
@@ -393,6 +393,12 @@ export const DocumentsUsersSchema = BaseSchema.extend({
export type DocumentsUsersReq = z.infer<typeof DocumentsUsersSchema>;
export const DocumentsChildrenSchema = BaseSchema.extend({
body: BaseIdSchema,
});
export type DocumentsChildrenReq = z.infer<typeof DocumentsChildrenSchema>;
export const DocumentsAddUserSchema = BaseSchema.extend({
body: BaseIdSchema.extend({
/** Id of the user who is to be added */