mirror of
https://github.com/docmost/docmost.git
synced 2026-05-15 05:04:06 +08:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 425924cb4d |
@@ -71,7 +71,6 @@
|
|||||||
"Export": "Export",
|
"Export": "Export",
|
||||||
"Failed to create page": "Failed to create page",
|
"Failed to create page": "Failed to create page",
|
||||||
"Failed to delete page": "Failed to delete page",
|
"Failed to delete page": "Failed to delete page",
|
||||||
"Failed to restore page": "Failed to restore page",
|
|
||||||
"Failed to fetch recent pages": "Failed to fetch recent pages",
|
"Failed to fetch recent pages": "Failed to fetch recent pages",
|
||||||
"Failed to import pages": "Failed to import pages",
|
"Failed to import pages": "Failed to import pages",
|
||||||
"Failed to load page. An error occurred.": "Failed to load page. An error occurred.",
|
"Failed to load page. An error occurred.": "Failed to load page. An error occurred.",
|
||||||
@@ -582,8 +581,6 @@
|
|||||||
"Move to trash": "Move to trash",
|
"Move to trash": "Move to trash",
|
||||||
"Move this page to trash?": "Move this page to trash?",
|
"Move this page to trash?": "Move this page to trash?",
|
||||||
"Restore page": "Restore page",
|
"Restore page": "Restore page",
|
||||||
"Permanently delete": "Permanently delete",
|
|
||||||
"<b>{{name}}</b> moved this page to Trash {{time}}.": "<b>{{name}}</b> moved this page to Trash {{time}}.",
|
|
||||||
"Page moved to trash": "Page moved to trash",
|
"Page moved to trash": "Page moved to trash",
|
||||||
"Page restored successfully": "Page restored successfully",
|
"Page restored successfully": "Page restored successfully",
|
||||||
"Deleted by": "Deleted by",
|
"Deleted by": "Deleted by",
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { ActionIcon, Box, Group, ScrollArea, Text, Tooltip } from "@mantine/core";
|
import { Box, ScrollArea, Text } from "@mantine/core";
|
||||||
import { IconX } from "@tabler/icons-react";
|
|
||||||
import CommentListWithTabs from "@/features/comment/components/comment-list-with-tabs.tsx";
|
import CommentListWithTabs from "@/features/comment/components/comment-list-with-tabs.tsx";
|
||||||
import { useAtom } from "jotai";
|
import { useAtom } from "jotai";
|
||||||
import { asideStateAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
|
import { asideStateAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
|
||||||
@@ -12,10 +11,9 @@ import AsideChatPanel from "@/ee/ai-chat/components/aside-chat-panel";
|
|||||||
import { PageDetailsAside } from "@/features/page-details/components/page-details-aside.tsx";
|
import { PageDetailsAside } from "@/features/page-details/components/page-details-aside.tsx";
|
||||||
|
|
||||||
export default function Aside() {
|
export default function Aside() {
|
||||||
const [{ tab }, setAsideState] = useAtom(asideStateAtom);
|
const [{ tab }] = useAtom(asideStateAtom);
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const pageEditor = useAtomValue(pageEditorAtom);
|
const pageEditor = useAtomValue(pageEditorAtom);
|
||||||
const closeAside = () => setAsideState((s) => ({ ...s, isAsideOpen: false }));
|
|
||||||
|
|
||||||
let title: string;
|
let title: string;
|
||||||
let component: ReactNode;
|
let component: ReactNode;
|
||||||
@@ -47,19 +45,9 @@ export default function Aside() {
|
|||||||
{component && (
|
{component && (
|
||||||
<>
|
<>
|
||||||
{tab !== "chat" && (
|
{tab !== "chat" && (
|
||||||
<Group justify="space-between" wrap="nowrap" mb="md">
|
<Text mb="md" fw={500}>
|
||||||
<Text fw={500}>{t(title)}</Text>
|
{t(title)}
|
||||||
<Tooltip label={t("Close")} withArrow>
|
</Text>
|
||||||
<ActionIcon
|
|
||||||
variant="subtle"
|
|
||||||
color="gray"
|
|
||||||
onClick={closeAside}
|
|
||||||
aria-label={t("Close")}
|
|
||||||
>
|
|
||||||
<IconX size={18} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
</Group>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{tab === "comments" || tab === "chat" ? (
|
{tab === "comments" || tab === "chat" ? (
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { atom } from "jotai";
|
import { atom } from "jotai";
|
||||||
import { Editor } from "@tiptap/core";
|
import { Editor } from "@tiptap/core";
|
||||||
import { PageEditMode } from "@/features/user/types/user.types.ts";
|
|
||||||
|
|
||||||
export const pageEditorAtom = atom<Editor | null>(null);
|
export const pageEditorAtom = atom<Editor | null>(null);
|
||||||
|
|
||||||
@@ -13,7 +12,3 @@ export const yjsConnectionStatusAtom = atom<string>("");
|
|||||||
export const showAiMenuAtom = atom(false);
|
export const showAiMenuAtom = atom(false);
|
||||||
|
|
||||||
export const showLinkMenuAtom = atom(false);
|
export const showLinkMenuAtom = atom(false);
|
||||||
|
|
||||||
// Current page's edit mode — initialized from the user's saved preference on
|
|
||||||
// first load, can be toggled locally without persisting to the server.
|
|
||||||
export const currentPageEditModeAtom = atom<PageEditMode>(PageEditMode.Edit);
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import classes from "@/features/editor/styles/editor.module.css";
|
import classes from "@/features/editor/styles/editor.module.css";
|
||||||
import React, { useEffect } from "react";
|
import React from "react";
|
||||||
import { TitleEditor } from "@/features/editor/title-editor";
|
import { TitleEditor } from "@/features/editor/title-editor";
|
||||||
import PageEditor from "@/features/editor/page-editor";
|
import PageEditor from "@/features/editor/page-editor";
|
||||||
import {
|
import {
|
||||||
@@ -23,25 +23,17 @@ import { IContributor } from "@/features/page/types/page.types.ts";
|
|||||||
import { FixedToolbar } from "@/features/editor/components/fixed-toolbar/fixed-toolbar";
|
import { FixedToolbar } from "@/features/editor/components/fixed-toolbar/fixed-toolbar";
|
||||||
import { PageEditMode } from "@/features/user/types/user.types.ts";
|
import { PageEditMode } from "@/features/user/types/user.types.ts";
|
||||||
import useToggleAside from "@/hooks/use-toggle-aside.tsx";
|
import useToggleAside from "@/hooks/use-toggle-aside.tsx";
|
||||||
import { DeletedPageBanner } from "@/features/page/trash/components/deleted-page-banner.tsx";
|
|
||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
import { currentPageEditModeAtom } from "@/features/editor/atoms/editor-atoms.ts";
|
|
||||||
|
|
||||||
const MemoizedTitleEditor = React.memo(TitleEditor);
|
const MemoizedTitleEditor = React.memo(TitleEditor);
|
||||||
const MemoizedPageEditor = React.memo(PageEditor);
|
const MemoizedPageEditor = React.memo(PageEditor);
|
||||||
const MemoizedFixedToolbar = React.memo(FixedToolbar);
|
|
||||||
const MemoizedDeletedPageBanner = React.memo(DeletedPageBanner);
|
|
||||||
|
|
||||||
type PageUser = {
|
type PageCreator = {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
avatarUrl: string;
|
avatarUrl: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Module-level flag: survives component unmount/remount on page navigation,
|
|
||||||
// reset only on full page reload (i.e. a new app session).
|
|
||||||
let defaultEditModeApplied = false;
|
|
||||||
|
|
||||||
export interface FullEditorProps {
|
export interface FullEditorProps {
|
||||||
pageId: string;
|
pageId: string;
|
||||||
slugId: string;
|
slugId: string;
|
||||||
@@ -49,7 +41,7 @@ export interface FullEditorProps {
|
|||||||
content: string;
|
content: string;
|
||||||
spaceSlug: string;
|
spaceSlug: string;
|
||||||
editable: boolean;
|
editable: boolean;
|
||||||
creator?: PageUser;
|
creator?: PageCreator;
|
||||||
contributors?: IContributor[];
|
contributors?: IContributor[];
|
||||||
canComment?: boolean;
|
canComment?: boolean;
|
||||||
}
|
}
|
||||||
@@ -69,21 +61,9 @@ export function FullEditor({
|
|||||||
const fullPageWidth = user.settings?.preferences?.fullPageWidth;
|
const fullPageWidth = user.settings?.preferences?.fullPageWidth;
|
||||||
const editorToolbarEnabled =
|
const editorToolbarEnabled =
|
||||||
user.settings?.preferences?.editorToolbar ?? false;
|
user.settings?.preferences?.editorToolbar ?? false;
|
||||||
const [currentPageEditMode, setCurrentPageEditMode] = useAtom(
|
|
||||||
currentPageEditModeAtom,
|
|
||||||
);
|
|
||||||
const userPageEditMode =
|
const userPageEditMode =
|
||||||
user.settings?.preferences?.pageEditMode ?? PageEditMode.Edit;
|
user.settings?.preferences?.pageEditMode ?? PageEditMode.Edit;
|
||||||
const isEditMode = currentPageEditMode === PageEditMode.Edit;
|
const isEditMode = userPageEditMode === PageEditMode.Edit;
|
||||||
|
|
||||||
// Apply the user's saved preference only once on initial load, not on every
|
|
||||||
// page navigation — so the mode sticks across navigations within a session.
|
|
||||||
useEffect(() => {
|
|
||||||
if (!defaultEditModeApplied) {
|
|
||||||
setCurrentPageEditMode(userPageEditMode as PageEditMode);
|
|
||||||
defaultEditModeApplied = true;
|
|
||||||
}
|
|
||||||
}, [userPageEditMode, setCurrentPageEditMode]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container
|
<Container
|
||||||
@@ -91,10 +71,7 @@ export function FullEditor({
|
|||||||
size={!fullPageWidth && 900}
|
size={!fullPageWidth && 900}
|
||||||
className={classes.editor}
|
className={classes.editor}
|
||||||
>
|
>
|
||||||
{editorToolbarEnabled && editable && isEditMode && (
|
{editorToolbarEnabled && editable && isEditMode && <FixedToolbar />}
|
||||||
<MemoizedFixedToolbar />
|
|
||||||
)}
|
|
||||||
<MemoizedDeletedPageBanner slugId={slugId} />
|
|
||||||
<MemoizedTitleEditor
|
<MemoizedTitleEditor
|
||||||
pageId={pageId}
|
pageId={pageId}
|
||||||
slugId={slugId}
|
slugId={slugId}
|
||||||
@@ -118,12 +95,16 @@ export function FullEditor({
|
|||||||
}
|
}
|
||||||
|
|
||||||
type PageBylineProps = {
|
type PageBylineProps = {
|
||||||
creator?: PageUser;
|
creator?: PageCreator;
|
||||||
contributors?: IContributor[];
|
contributors?: IContributor[];
|
||||||
readOnly?: boolean;
|
readOnly?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
function PageByline({ creator, contributors, readOnly }: PageBylineProps) {
|
function PageByline({
|
||||||
|
creator,
|
||||||
|
contributors,
|
||||||
|
readOnly,
|
||||||
|
}: PageBylineProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const toggleAside = useToggleAside();
|
const toggleAside = useToggleAside();
|
||||||
|
|
||||||
|
|||||||
@@ -26,11 +26,10 @@ import {
|
|||||||
collabExtensions,
|
collabExtensions,
|
||||||
mainExtensions,
|
mainExtensions,
|
||||||
} from "@/features/editor/extensions/extensions";
|
} from "@/features/editor/extensions/extensions";
|
||||||
import { useAtom, useAtomValue } from "jotai";
|
import { useAtom } from "jotai";
|
||||||
import useCollaborationUrl from "@/features/editor/hooks/use-collaboration-url";
|
import useCollaborationUrl from "@/features/editor/hooks/use-collaboration-url";
|
||||||
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
|
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
|
||||||
import {
|
import {
|
||||||
currentPageEditModeAtom,
|
|
||||||
pageEditorAtom,
|
pageEditorAtom,
|
||||||
yjsConnectionStatusAtom,
|
yjsConnectionStatusAtom,
|
||||||
} from "@/features/editor/atoms/editor-atoms";
|
} from "@/features/editor/atoms/editor-atoms";
|
||||||
@@ -113,7 +112,8 @@ export default function PageEditor({
|
|||||||
const documentState = useDocumentVisibility();
|
const documentState = useDocumentVisibility();
|
||||||
const { pageSlug } = useParams();
|
const { pageSlug } = useParams();
|
||||||
const slugId = extractPageSlugId(pageSlug);
|
const slugId = extractPageSlugId(pageSlug);
|
||||||
const currentPageEditMode = useAtomValue(currentPageEditModeAtom);
|
const userPageEditMode =
|
||||||
|
currentUser?.user?.settings?.preferences?.pageEditMode ?? PageEditMode.Edit;
|
||||||
const canScroll = useCallback(
|
const canScroll = useCallback(
|
||||||
() => Boolean(isComponentMounted.current && editorRef.current),
|
() => Boolean(isComponentMounted.current && editorRef.current),
|
||||||
[isComponentMounted],
|
[isComponentMounted],
|
||||||
@@ -373,9 +373,19 @@ export default function PageEditor({
|
|||||||
return () => clearTimeout(timeout);
|
return () => clearTimeout(timeout);
|
||||||
}, [yjsConnectionStatus, isSynced]);
|
}, [yjsConnectionStatus, isSynced]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!editor) return;
|
// Only honor user default page edit mode preference and permissions
|
||||||
editor.setEditable(editable && currentPageEditMode === PageEditMode.Edit);
|
if (editor) {
|
||||||
}, [currentPageEditMode, editor, editable]);
|
if (userPageEditMode && editable) {
|
||||||
|
if (userPageEditMode === PageEditMode.Edit) {
|
||||||
|
editor.setEditable(true);
|
||||||
|
} else if (userPageEditMode === PageEditMode.Read) {
|
||||||
|
editor.setEditable(false);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
editor.setEditable(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [userPageEditMode, editor, editable]);
|
||||||
|
|
||||||
const hasConnectedOnceRef = useRef(false);
|
const hasConnectedOnceRef = useRef(false);
|
||||||
const [showStatic, setShowStatic] = useState(true);
|
const [showStatic, setShowStatic] = useState(true);
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import { Text } from "@tiptap/extension-text";
|
|||||||
import { Placeholder } from "@tiptap/extension-placeholder";
|
import { Placeholder } from "@tiptap/extension-placeholder";
|
||||||
import { useAtomValue } from "jotai";
|
import { useAtomValue } from "jotai";
|
||||||
import {
|
import {
|
||||||
currentPageEditModeAtom,
|
|
||||||
pageEditorAtom,
|
pageEditorAtom,
|
||||||
titleEditorAtom,
|
titleEditorAtom,
|
||||||
} from "@/features/editor/atoms/editor-atoms";
|
} from "@/features/editor/atoms/editor-atoms";
|
||||||
@@ -25,6 +24,7 @@ import { useTranslation } from "react-i18next";
|
|||||||
import EmojiCommand from "@/features/editor/extensions/emoji-command.ts";
|
import EmojiCommand from "@/features/editor/extensions/emoji-command.ts";
|
||||||
import { UpdateEvent } from "@/features/websocket/types";
|
import { UpdateEvent } from "@/features/websocket/types";
|
||||||
import localEmitter from "@/lib/local-emitter.ts";
|
import localEmitter from "@/lib/local-emitter.ts";
|
||||||
|
import { currentUserAtom } from "@/features/user/atoms/current-user-atom.ts";
|
||||||
import { PageEditMode } from "@/features/user/types/user.types.ts";
|
import { PageEditMode } from "@/features/user/types/user.types.ts";
|
||||||
import { searchSpotlight } from "@/features/search/constants.ts";
|
import { searchSpotlight } from "@/features/search/constants.ts";
|
||||||
import { platformModifierKey } from "@/lib";
|
import { platformModifierKey } from "@/lib";
|
||||||
@@ -52,7 +52,9 @@ export function TitleEditor({
|
|||||||
const emit = useQueryEmit();
|
const emit = useQueryEmit();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [activePageId, setActivePageId] = useState(pageId);
|
const [activePageId, setActivePageId] = useState(pageId);
|
||||||
const currentPageEditMode = useAtomValue(currentPageEditModeAtom);
|
const [currentUser] = useAtom(currentUserAtom);
|
||||||
|
const userPageEditMode =
|
||||||
|
currentUser?.user?.settings?.preferences?.pageEditMode ?? PageEditMode.Edit;
|
||||||
|
|
||||||
const titleEditor = useEditor({
|
const titleEditor = useEditor({
|
||||||
extensions: [
|
extensions: [
|
||||||
@@ -170,9 +172,18 @@ export function TitleEditor({
|
|||||||
}, [pageId]);
|
}, [pageId]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!titleEditor) return;
|
if (titleEditor) {
|
||||||
titleEditor.setEditable(editable && currentPageEditMode === PageEditMode.Edit);
|
if (userPageEditMode && editable) {
|
||||||
}, [currentPageEditMode, titleEditor, editable]);
|
if (userPageEditMode === PageEditMode.Edit) {
|
||||||
|
titleEditor.setEditable(true);
|
||||||
|
} else if (userPageEditMode === PageEditMode.Read) {
|
||||||
|
titleEditor.setEditable(false);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
titleEditor.setEditable(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [userPageEditMode, titleEditor, editable]);
|
||||||
|
|
||||||
const openSearchDialog = () => {
|
const openSearchDialog = () => {
|
||||||
const event = new CustomEvent("openFindDialogFromEditor", {});
|
const event = new CustomEvent("openFindDialogFromEditor", {});
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ import {
|
|||||||
yjsConnectionStatusAtom,
|
yjsConnectionStatusAtom,
|
||||||
} from "@/features/editor/atoms/editor-atoms.ts";
|
} from "@/features/editor/atoms/editor-atoms.ts";
|
||||||
import { formattedDate } from "@/lib/time.ts";
|
import { formattedDate } from "@/lib/time.ts";
|
||||||
import { PageEditModeToggle } from "@/features/user/components/page-state-pref.tsx";
|
import { PageStateSegmentedControl } from "@/features/user/components/page-state-pref.tsx";
|
||||||
import MovePageModal from "@/features/page/components/move-page-modal.tsx";
|
import MovePageModal from "@/features/page/components/move-page-modal.tsx";
|
||||||
import { useTimeAgo } from "@/hooks/use-time-ago.tsx";
|
import { useTimeAgo } from "@/hooks/use-time-ago.tsx";
|
||||||
import { PageShareModal } from "@/ee/page-permission";
|
import { PageShareModal } from "@/ee/page-permission";
|
||||||
@@ -65,11 +65,6 @@ interface PageHeaderMenuProps {
|
|||||||
export default function PageHeaderMenu({ readOnly }: PageHeaderMenuProps) {
|
export default function PageHeaderMenu({ readOnly }: PageHeaderMenuProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const toggleAside = useToggleAside();
|
const toggleAside = useToggleAside();
|
||||||
const { pageSlug } = useParams();
|
|
||||||
const { data: page } = usePageQuery({
|
|
||||||
pageId: extractPageSlugId(pageSlug),
|
|
||||||
});
|
|
||||||
const isDeleted = !!page?.deletedAt;
|
|
||||||
|
|
||||||
useHotkeys(
|
useHotkeys(
|
||||||
[
|
[
|
||||||
@@ -92,15 +87,11 @@ export default function PageHeaderMenu({ readOnly }: PageHeaderMenuProps) {
|
|||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
|
|
||||||
if (isDeleted) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<ConnectionWarning />
|
<ConnectionWarning />
|
||||||
|
|
||||||
{!readOnly && <PageEditModeToggle size="xs" />}
|
{!readOnly && <PageStateSegmentedControl size="xs" />}
|
||||||
|
|
||||||
<PageShareModal readOnly={readOnly} />
|
<PageShareModal readOnly={readOnly} />
|
||||||
|
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
import { modals } from "@mantine/modals";
|
|
||||||
import { Text } from "@mantine/core";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
|
|
||||||
type UseRestoreModalProps = {
|
|
||||||
title?: string | null;
|
|
||||||
onConfirm: () => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function useRestorePageModal() {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const openRestoreModal = ({ title, onConfirm }: UseRestoreModalProps) => {
|
|
||||||
modals.openConfirmModal({
|
|
||||||
title: t("Restore page"),
|
|
||||||
children: (
|
|
||||||
<Text size="sm">
|
|
||||||
{t("Restore '{{title}}' and its sub-pages?", {
|
|
||||||
title: title || t("Untitled"),
|
|
||||||
})}
|
|
||||||
</Text>
|
|
||||||
),
|
|
||||||
centered: true,
|
|
||||||
labels: { confirm: t("Restore"), cancel: t("Cancel") },
|
|
||||||
confirmProps: { color: "blue" },
|
|
||||||
onConfirm,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
return { openRestoreModal } as const;
|
|
||||||
}
|
|
||||||
@@ -117,20 +117,10 @@ export function useUpdatePageMutation() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useRemovePageMutation() {
|
export function useRemovePageMutation() {
|
||||||
const { t } = useTranslation();
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (pageId: string) => deletePage(pageId, false),
|
mutationFn: (pageId: string) => deletePage(pageId, false),
|
||||||
onSuccess: (_, pageId) => {
|
onSuccess: (_, pageId) => {
|
||||||
notifications.show({ message: t("Page moved to trash") });
|
notifications.show({ message: "Page moved to trash" });
|
||||||
|
|
||||||
// Stamp deletedAt so a re-visit shows the trash banner, not stale state.
|
|
||||||
const cached = queryClient.getQueryData<IPage>(["pages", pageId]);
|
|
||||||
if (cached) {
|
|
||||||
const stamped = { ...cached, deletedAt: new Date() };
|
|
||||||
queryClient.setQueryData(["pages", cached.id], stamped);
|
|
||||||
queryClient.setQueryData(["pages", cached.slugId], stamped);
|
|
||||||
}
|
|
||||||
|
|
||||||
invalidateOnDeletePage(pageId);
|
invalidateOnDeletePage(pageId);
|
||||||
queryClient.invalidateQueries({
|
queryClient.invalidateQueries({
|
||||||
predicate: (item) =>
|
predicate: (item) =>
|
||||||
@@ -138,7 +128,7 @@ export function useRemovePageMutation() {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
onError: (error) => {
|
onError: (error) => {
|
||||||
notifications.show({ message: t("Failed to delete page"), color: "red" });
|
notifications.show({ message: "Failed to delete page", color: "red" });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -172,14 +162,13 @@ export function useMovePageMutation() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useRestorePageMutation() {
|
export function useRestorePageMutation() {
|
||||||
const { t } = useTranslation();
|
|
||||||
const [treeData, setTreeData] = useAtom(treeDataAtom);
|
const [treeData, setTreeData] = useAtom(treeDataAtom);
|
||||||
const emit = useQueryEmit();
|
const emit = useQueryEmit();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (pageId: string) => restorePage(pageId),
|
mutationFn: (pageId: string) => restorePage(pageId),
|
||||||
onSuccess: async (restoredPage) => {
|
onSuccess: async (restoredPage) => {
|
||||||
notifications.show({ message: t("Page restored successfully") });
|
notifications.show({ message: "Page restored successfully" });
|
||||||
|
|
||||||
// Check if the page already exists in the tree (it shouldn't)
|
// Check if the page already exists in the tree (it shouldn't)
|
||||||
if (!treeModel.find(treeData, restoredPage.id)) {
|
if (!treeModel.find(treeData, restoredPage.id)) {
|
||||||
@@ -233,16 +222,9 @@ export function useRestorePageMutation() {
|
|||||||
await queryClient.invalidateQueries({
|
await queryClient.invalidateQueries({
|
||||||
queryKey: ["trash-list", restoredPage.spaceId],
|
queryKey: ["trash-list", restoredPage.spaceId],
|
||||||
});
|
});
|
||||||
|
|
||||||
// Merge — restore endpoint returns a skinny page;
|
|
||||||
// Replace would strip space/permissions/content and break the editor.
|
|
||||||
const merge = (cached: IPage | undefined) =>
|
|
||||||
cached ? { ...cached, ...restoredPage } : cached;
|
|
||||||
queryClient.setQueryData<IPage>(["pages", restoredPage.id], merge);
|
|
||||||
queryClient.setQueryData<IPage>(["pages", restoredPage.slugId], merge);
|
|
||||||
},
|
},
|
||||||
onError: (error) => {
|
onError: (error) => {
|
||||||
notifications.show({ message: t("Failed to restore page"), color: "red" });
|
notifications.show({ message: "Failed to restore page", color: "red" });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,140 +0,0 @@
|
|||||||
import { ActionIcon, Button, Group, Paper, Text, Tooltip } from "@mantine/core";
|
|
||||||
import { IconRestore, IconTrash } from "@tabler/icons-react";
|
|
||||||
import { useNavigate } from "react-router-dom";
|
|
||||||
import { Trans, useTranslation } from "react-i18next";
|
|
||||||
import { useTimeAgo } from "@/hooks/use-time-ago.tsx";
|
|
||||||
import { useRestorePageModal } from "@/features/page/hooks/use-restore-page-modal.tsx";
|
|
||||||
import { useDeletePageModal } from "@/features/page/hooks/use-delete-page-modal.tsx";
|
|
||||||
import {
|
|
||||||
useDeletePageMutation,
|
|
||||||
usePageQuery,
|
|
||||||
useRestorePageMutation,
|
|
||||||
} from "@/features/page/queries/page-query.ts";
|
|
||||||
import { getSpaceUrl } from "@/lib/config.ts";
|
|
||||||
import { useGetSpaceBySlugQuery } from "@/features/space/queries/space-query.ts";
|
|
||||||
import { useSpaceAbility } from "@/features/space/permissions/use-space-ability.ts";
|
|
||||||
import {
|
|
||||||
SpaceCaslAction,
|
|
||||||
SpaceCaslSubject,
|
|
||||||
} from "@/features/space/permissions/permissions.type.ts";
|
|
||||||
|
|
||||||
type DeletedPageBannerProps = {
|
|
||||||
slugId: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function DeletedPageBanner({ slugId }: DeletedPageBannerProps) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const navigate = useNavigate();
|
|
||||||
const { data: page } = usePageQuery({ pageId: slugId });
|
|
||||||
const { data: space } = useGetSpaceBySlugQuery(page?.space?.slug);
|
|
||||||
const spaceAbility = useSpaceAbility(space?.membership?.permissions);
|
|
||||||
const deletedTimeAgo = useTimeAgo(page?.deletedAt);
|
|
||||||
const restorePageMutation = useRestorePageMutation();
|
|
||||||
const deletePageMutation = useDeletePageMutation();
|
|
||||||
const { openRestoreModal } = useRestorePageModal();
|
|
||||||
const { openDeleteModal } = useDeletePageModal();
|
|
||||||
|
|
||||||
if (!page?.deletedAt) return null;
|
|
||||||
|
|
||||||
const canRestore = spaceAbility.can(
|
|
||||||
SpaceCaslAction.Edit,
|
|
||||||
SpaceCaslSubject.Page,
|
|
||||||
);
|
|
||||||
const canPermanentlyDelete = spaceAbility.can(
|
|
||||||
SpaceCaslAction.Manage,
|
|
||||||
SpaceCaslSubject.Settings,
|
|
||||||
);
|
|
||||||
const actorName = page.deletedBy?.name ?? t("Someone");
|
|
||||||
|
|
||||||
const handleRestore = () => {
|
|
||||||
openRestoreModal({
|
|
||||||
title: page.title,
|
|
||||||
onConfirm: () => restorePageMutation.mutate(page.id),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const handlePermanentDelete = () => {
|
|
||||||
openDeleteModal({
|
|
||||||
isPermanent: true,
|
|
||||||
onConfirm: async () => {
|
|
||||||
await deletePageMutation.mutateAsync(page.id);
|
|
||||||
navigate(getSpaceUrl(page.space?.slug));
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const hasAnyAction = canRestore || canPermanentlyDelete;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Paper radius="sm" mb="md" px="md" py="xs" bg="red.0">
|
|
||||||
<Group justify="space-between" wrap="wrap" gap="sm">
|
|
||||||
<Text size="sm" style={{ flex: 1, minWidth: 0 }}>
|
|
||||||
<Trans
|
|
||||||
i18nKey="<b>{{name}}</b> moved this page to Trash {{time}}."
|
|
||||||
values={{ name: actorName, time: deletedTimeAgo }}
|
|
||||||
components={{ b: <Text span fw={600} inherit /> }}
|
|
||||||
/>
|
|
||||||
</Text>
|
|
||||||
{hasAnyAction && (
|
|
||||||
<>
|
|
||||||
<Group gap="xs" wrap="nowrap" visibleFrom="sm">
|
|
||||||
{canRestore && (
|
|
||||||
<Button
|
|
||||||
size="xs"
|
|
||||||
variant="light"
|
|
||||||
color="red"
|
|
||||||
leftSection={<IconRestore size={16} />}
|
|
||||||
onClick={handleRestore}
|
|
||||||
loading={restorePageMutation.isPending}
|
|
||||||
>
|
|
||||||
{t("Restore page")}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{canPermanentlyDelete && (
|
|
||||||
<Button
|
|
||||||
size="xs"
|
|
||||||
variant="light"
|
|
||||||
color="red"
|
|
||||||
leftSection={<IconTrash size={16} />}
|
|
||||||
onClick={handlePermanentDelete}
|
|
||||||
loading={deletePageMutation.isPending}
|
|
||||||
>
|
|
||||||
{t("Permanently delete")}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
<Group gap="xs" wrap="nowrap" hiddenFrom="sm">
|
|
||||||
{canRestore && (
|
|
||||||
<Tooltip label={t("Restore page")} withArrow>
|
|
||||||
<ActionIcon
|
|
||||||
size="lg"
|
|
||||||
variant="default"
|
|
||||||
onClick={handleRestore}
|
|
||||||
loading={restorePageMutation.isPending}
|
|
||||||
aria-label={t("Restore page")}
|
|
||||||
>
|
|
||||||
<IconRestore size={18} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
)}
|
|
||||||
{canPermanentlyDelete && (
|
|
||||||
<Tooltip label={t("Permanently delete")} withArrow>
|
|
||||||
<ActionIcon
|
|
||||||
size="lg"
|
|
||||||
variant="light"
|
|
||||||
color="red"
|
|
||||||
onClick={handlePermanentDelete}
|
|
||||||
loading={deletePageMutation.isPending}
|
|
||||||
aria-label={t("Permanently delete")}
|
|
||||||
>
|
|
||||||
<IconTrash size={18} />
|
|
||||||
</ActionIcon>
|
|
||||||
</Tooltip>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
</Paper>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import { Alert, Text } from "@mantine/core";
|
|
||||||
import { IconInfoCircle } from "@tabler/icons-react";
|
|
||||||
import { useAtomValue } from "jotai";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { workspaceAtom } from "@/features/user/atoms/current-user-atom.ts";
|
|
||||||
|
|
||||||
export function TrashBanner() {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const workspace = useAtomValue(workspaceAtom);
|
|
||||||
const retentionDays = workspace?.trashRetentionDays ?? 30;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Alert icon={<IconInfoCircle size={16} />} variant="light" color="red">
|
|
||||||
<Text size="sm" lh={1.35}>
|
|
||||||
{t("Pages in trash will be permanently deleted after {{count}} days.", {
|
|
||||||
count: retentionDays,
|
|
||||||
})}
|
|
||||||
</Text>
|
|
||||||
</Alert>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -7,16 +7,17 @@ import {
|
|||||||
Group,
|
Group,
|
||||||
ActionIcon,
|
ActionIcon,
|
||||||
Text,
|
Text,
|
||||||
|
Alert,
|
||||||
Stack,
|
Stack,
|
||||||
Menu,
|
Menu,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
import {
|
import {
|
||||||
|
IconInfoCircle,
|
||||||
IconDots,
|
IconDots,
|
||||||
IconRestore,
|
IconRestore,
|
||||||
IconTrash,
|
IconTrash,
|
||||||
IconFileDescription,
|
IconFileDescription,
|
||||||
} from "@tabler/icons-react";
|
} from "@tabler/icons-react";
|
||||||
import { TrashBanner } from "@/features/page/trash/components/trash-banner.tsx";
|
|
||||||
import {
|
import {
|
||||||
useDeletedPagesQuery,
|
useDeletedPagesQuery,
|
||||||
useRestorePageMutation,
|
useRestorePageMutation,
|
||||||
@@ -30,10 +31,12 @@ import TrashPageContentModal from "@/features/page/trash/components/trash-page-c
|
|||||||
import { UserInfo } from "@/components/common/user-info.tsx";
|
import { UserInfo } from "@/components/common/user-info.tsx";
|
||||||
import Paginate from "@/components/common/paginate.tsx";
|
import Paginate from "@/components/common/paginate.tsx";
|
||||||
import { useCursorPaginate } from "@/hooks/use-cursor-paginate";
|
import { useCursorPaginate } from "@/hooks/use-cursor-paginate";
|
||||||
import { useRestorePageModal } from "@/features/page/hooks/use-restore-page-modal.tsx";
|
import { useAtom } from "jotai";
|
||||||
|
import { workspaceAtom } from "@/features/user/atoms/current-user-atom.ts";
|
||||||
|
|
||||||
export default function Trash() {
|
export default function Trash() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const [workspace] = useAtom(workspaceAtom);
|
||||||
const { spaceSlug } = useParams();
|
const { spaceSlug } = useParams();
|
||||||
const { cursor, goNext, goPrev } = useCursorPaginate();
|
const { cursor, goNext, goPrev } = useCursorPaginate();
|
||||||
const { data: space } = useGetSpaceBySlugQuery(spaceSlug);
|
const { data: space } = useGetSpaceBySlugQuery(spaceSlug);
|
||||||
@@ -42,7 +45,6 @@ export default function Trash() {
|
|||||||
});
|
});
|
||||||
const restorePageMutation = useRestorePageMutation();
|
const restorePageMutation = useRestorePageMutation();
|
||||||
const deletePageMutation = useDeletePageMutation();
|
const deletePageMutation = useDeletePageMutation();
|
||||||
const { openRestoreModal } = useRestorePageModal();
|
|
||||||
|
|
||||||
const [selectedPage, setSelectedPage] = useState<{
|
const [selectedPage, setSelectedPage] = useState<{
|
||||||
title: string;
|
title: string;
|
||||||
@@ -76,6 +78,23 @@ export default function Trash() {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const openRestoreModal = (pageId: string, pageTitle: string) => {
|
||||||
|
modals.openConfirmModal({
|
||||||
|
title: t("Restore page"),
|
||||||
|
children: (
|
||||||
|
<Text size="sm">
|
||||||
|
{t("Restore '{{title}}' and its sub-pages?", {
|
||||||
|
title: pageTitle || "Untitled",
|
||||||
|
})}
|
||||||
|
</Text>
|
||||||
|
),
|
||||||
|
centered: true,
|
||||||
|
labels: { confirm: t("Restore"), cancel: t("Cancel") },
|
||||||
|
confirmProps: { color: "blue" },
|
||||||
|
onConfirm: () => handleRestorePage(pageId),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const hasPages = deletedPages && deletedPages.items.length > 0;
|
const hasPages = deletedPages && deletedPages.items.length > 0;
|
||||||
|
|
||||||
const handlePageClick = (page: any) => {
|
const handlePageClick = (page: any) => {
|
||||||
@@ -90,7 +109,11 @@ export default function Trash() {
|
|||||||
<Title order={2}>{t("Trash")}</Title>
|
<Title order={2}>{t("Trash")}</Title>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
<TrashBanner />
|
<Alert icon={<IconInfoCircle size={16} />} variant="light" color="red">
|
||||||
|
<Text size="sm">
|
||||||
|
{t("Pages in trash will be permanently deleted after {{count}} days.", { count: workspace?.trashRetentionDays ?? 30 })}
|
||||||
|
</Text>
|
||||||
|
</Alert>
|
||||||
|
|
||||||
{isLoading || !deletedPages ? (
|
{isLoading || !deletedPages ? (
|
||||||
<></>
|
<></>
|
||||||
@@ -158,10 +181,7 @@ export default function Trash() {
|
|||||||
<Menu.Item
|
<Menu.Item
|
||||||
leftSection={<IconRestore size={16} />}
|
leftSection={<IconRestore size={16} />}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
openRestoreModal({
|
openRestoreModal(page.id, page.title)
|
||||||
title: page.title,
|
|
||||||
onConfirm: () => handleRestorePage(page.id),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
{t("Restore")}
|
{t("Restore")}
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import React, { useCallback, useEffect, useState } from "react";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { PageEditMode } from "@/features/user/types/user.types.ts";
|
import { PageEditMode } from "@/features/user/types/user.types.ts";
|
||||||
import { ResponsiveSettingsRow, ResponsiveSettingsContent, ResponsiveSettingsControl } from "@/components/ui/responsive-settings-row";
|
import { ResponsiveSettingsRow, ResponsiveSettingsContent, ResponsiveSettingsControl } from "@/components/ui/responsive-settings-row";
|
||||||
import { currentPageEditModeAtom } from "@/features/editor/atoms/editor-atoms.ts";
|
|
||||||
|
|
||||||
export default function PageStatePref() {
|
export default function PageStatePref() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -72,24 +71,3 @@ export function PageStateSegmentedControl({
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Header variant: updates the current page's mode locally without persisting
|
|
||||||
// the preference to the server.
|
|
||||||
export function PageEditModeToggle({ size }: { size?: MantineSize }) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const [currentPageEditMode, setCurrentPageEditMode] = useAtom(
|
|
||||||
currentPageEditModeAtom,
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<SegmentedControl
|
|
||||||
size={size}
|
|
||||||
value={currentPageEditMode}
|
|
||||||
onChange={(v) => setCurrentPageEditMode(v as PageEditMode)}
|
|
||||||
data={[
|
|
||||||
{ label: t("Edit"), value: PageEditMode.Edit },
|
|
||||||
{ label: t("Read"), value: PageEditMode.Read },
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ function PageContent({ pageSlug }: { pageSlug: string | undefined }) {
|
|||||||
} = usePageQuery({ pageId: extractPageSlugId(pageSlug) });
|
} = usePageQuery({ pageId: extractPageSlugId(pageSlug) });
|
||||||
const { data: space } = useGetSpaceBySlugQuery(page?.space?.slug);
|
const { data: space } = useGetSpaceBySlugQuery(page?.space?.slug);
|
||||||
|
|
||||||
const canEdit = !page?.deletedAt && (page?.permissions?.canEdit ?? false);
|
const canEdit = page?.permissions?.canEdit ?? false;
|
||||||
const canComment =
|
const canComment =
|
||||||
canEdit ||
|
canEdit ||
|
||||||
(space?.settings?.comments?.allowViewerComments === true);
|
(space?.settings?.comments?.allowViewerComments === true);
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { Module } from '@nestjs/common';
|
|||||||
import { AppController } from '../../app.controller';
|
import { AppController } from '../../app.controller';
|
||||||
import { AppService } from '../../app.service';
|
import { AppService } from '../../app.service';
|
||||||
import { EnvironmentModule } from '../../integrations/environment/environment.module';
|
import { EnvironmentModule } from '../../integrations/environment/environment.module';
|
||||||
import { EnvironmentService } from '../../integrations/environment/environment.service';
|
|
||||||
import { CollaborationModule } from '../collaboration.module';
|
import { CollaborationModule } from '../collaboration.module';
|
||||||
import { DatabaseModule } from '@docmost/db/database.module';
|
import { DatabaseModule } from '@docmost/db/database.module';
|
||||||
import { QueueModule } from '../../integrations/queue/queue.module';
|
import { QueueModule } from '../../integrations/queue/queue.module';
|
||||||
@@ -13,8 +12,6 @@ import { LoggerModule } from '../../common/logger/logger.module';
|
|||||||
import { RedisModule } from '@nestjs-labs/nestjs-ioredis';
|
import { RedisModule } from '@nestjs-labs/nestjs-ioredis';
|
||||||
import { RedisConfigService } from '../../integrations/redis/redis-config.service';
|
import { RedisConfigService } from '../../integrations/redis/redis-config.service';
|
||||||
import { CaslModule } from '../../core/casl/casl.module';
|
import { CaslModule } from '../../core/casl/casl.module';
|
||||||
import { CacheModule } from '@nestjs/cache-manager';
|
|
||||||
import KeyvRedis from '@keyv/redis';
|
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -29,18 +26,6 @@ import KeyvRedis from '@keyv/redis';
|
|||||||
RedisModule.forRootAsync({
|
RedisModule.forRootAsync({
|
||||||
useClass: RedisConfigService,
|
useClass: RedisConfigService,
|
||||||
}),
|
}),
|
||||||
CacheModule.registerAsync({
|
|
||||||
isGlobal: true,
|
|
||||||
useFactory: async (environmentService: EnvironmentService) => {
|
|
||||||
const redisUrl = environmentService.getRedisUrl();
|
|
||||||
|
|
||||||
return {
|
|
||||||
ttl: 5 * 1000,
|
|
||||||
stores: [new KeyvRedis(redisUrl)],
|
|
||||||
};
|
|
||||||
},
|
|
||||||
inject: [EnvironmentService],
|
|
||||||
}),
|
|
||||||
],
|
],
|
||||||
controllers: [
|
controllers: [
|
||||||
AppController,
|
AppController,
|
||||||
|
|||||||
@@ -1,11 +1,3 @@
|
|||||||
export const CacheKey = {
|
export const CacheKey = {
|
||||||
LICENSE_VALID: (workspaceId: string) => `license:valid:${workspaceId}`,
|
LICENSE_VALID: (workspaceId: string) => `license:valid:${workspaceId}`,
|
||||||
SPACE_ROLES: (userId: string, spaceId: string) =>
|
|
||||||
`perm:space-roles:${userId}:${spaceId}`,
|
|
||||||
PAGE_CAN_EDIT: (userId: string, pageId: string) =>
|
|
||||||
`perm:can-edit:${userId}:${pageId}`,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Permission caches dedupe repeated checks within and across short request bursts.
|
|
||||||
// 5s keeps staleness on revocations bounded.
|
|
||||||
export const PERMISSION_CACHE_TTL_MS = 5_000;
|
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
import { Cache } from 'cache-manager';
|
|
||||||
|
|
||||||
export async function withCache<T>(
|
|
||||||
cacheManager: Cache,
|
|
||||||
key: string,
|
|
||||||
ttlMs: number,
|
|
||||||
fn: () => Promise<T>,
|
|
||||||
): Promise<T> {
|
|
||||||
try {
|
|
||||||
const cached = await cacheManager.get<{ v: T }>(key);
|
|
||||||
if (cached !== undefined && cached !== null) {
|
|
||||||
return cached.v;
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.warn(`[withCache] get failed for "${key}", falling back to source`, err);
|
|
||||||
}
|
|
||||||
|
|
||||||
const value = await fn();
|
|
||||||
|
|
||||||
try {
|
|
||||||
await cacheManager.set(key, { v: value }, ttlMs);
|
|
||||||
} catch (err) {
|
|
||||||
console.warn(`[withCache] set failed for "${key}"`, err);
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
@@ -76,7 +76,6 @@ export class PageController {
|
|||||||
includeCreator: true,
|
includeCreator: true,
|
||||||
includeLastUpdatedBy: true,
|
includeLastUpdatedBy: true,
|
||||||
includeContributors: true,
|
includeContributors: true,
|
||||||
includeDeletedBy: true,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!page) {
|
if (!page) {
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
import { Inject, Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { CACHE_MANAGER } from '@nestjs/cache-manager';
|
|
||||||
import { Cache } from 'cache-manager';
|
|
||||||
import { InjectKysely } from 'nestjs-kysely';
|
import { InjectKysely } from 'nestjs-kysely';
|
||||||
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
||||||
import { dbOrTx } from '@docmost/db/utils';
|
import { dbOrTx } from '@docmost/db/utils';
|
||||||
@@ -19,11 +17,6 @@ import {
|
|||||||
executeWithCursorPagination,
|
executeWithCursorPagination,
|
||||||
} from '@docmost/db/pagination/cursor-pagination';
|
} from '@docmost/db/pagination/cursor-pagination';
|
||||||
import { PagePermissionMember } from './types/page-permission.types';
|
import { PagePermissionMember } from './types/page-permission.types';
|
||||||
import { withCache } from '../../../common/helpers/with-cache';
|
|
||||||
import {
|
|
||||||
CacheKey,
|
|
||||||
PERMISSION_CACHE_TTL_MS,
|
|
||||||
} from '../../../common/helpers/cache-keys';
|
|
||||||
|
|
||||||
export { PagePermissionMember } from './types/page-permission.types';
|
export { PagePermissionMember } from './types/page-permission.types';
|
||||||
|
|
||||||
@@ -32,7 +25,6 @@ export class PagePermissionRepo {
|
|||||||
constructor(
|
constructor(
|
||||||
@InjectKysely() private readonly db: KyselyDB,
|
@InjectKysely() private readonly db: KyselyDB,
|
||||||
private readonly groupRepo: GroupRepo,
|
private readonly groupRepo: GroupRepo,
|
||||||
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async findPageAccessByPageId(
|
async findPageAccessByPageId(
|
||||||
@@ -369,8 +361,40 @@ export class PagePermissionRepo {
|
|||||||
* Check if user can access a page by verifying they have permission on ALL restricted ancestors.
|
* Check if user can access a page by verifying they have permission on ALL restricted ancestors.
|
||||||
*/
|
*/
|
||||||
async canUserAccessPage(userId: string, pageId: string): Promise<boolean> {
|
async canUserAccessPage(userId: string, pageId: string): Promise<boolean> {
|
||||||
const { canAccess } = await this.canUserEditPage(userId, pageId);
|
const deniedAncestor = await this.db
|
||||||
return canAccess;
|
.withRecursive('ancestors', (qb) =>
|
||||||
|
qb
|
||||||
|
.selectFrom('pages')
|
||||||
|
.select(['pages.id as ancestorId', 'pages.parentPageId'])
|
||||||
|
.where('pages.id', '=', pageId)
|
||||||
|
.unionAll((eb) =>
|
||||||
|
eb
|
||||||
|
.selectFrom('pages')
|
||||||
|
.innerJoin('ancestors', 'ancestors.parentPageId', 'pages.id')
|
||||||
|
.select(['pages.id as ancestorId', 'pages.parentPageId']),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.selectFrom('ancestors')
|
||||||
|
.innerJoin('pageAccess', 'pageAccess.pageId', 'ancestors.ancestorId')
|
||||||
|
.leftJoin('pagePermissions', (join) =>
|
||||||
|
join
|
||||||
|
.onRef('pagePermissions.pageAccessId', '=', 'pageAccess.id')
|
||||||
|
.on((eb) =>
|
||||||
|
eb.or([
|
||||||
|
eb('pagePermissions.userId', '=', userId),
|
||||||
|
eb(
|
||||||
|
'pagePermissions.groupId',
|
||||||
|
'in',
|
||||||
|
this.userGroupIdsSubquery(eb, userId),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.select('pageAccess.pageId')
|
||||||
|
.where('pagePermissions.id', 'is', null)
|
||||||
|
.executeTakeFirst();
|
||||||
|
|
||||||
|
return !deniedAncestor;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -388,50 +412,43 @@ export class PagePermissionRepo {
|
|||||||
canAccess: boolean;
|
canAccess: boolean;
|
||||||
canEdit: boolean;
|
canEdit: boolean;
|
||||||
}> {
|
}> {
|
||||||
return withCache(
|
const result = await sql<{
|
||||||
this.cacheManager,
|
canAccess: boolean | null;
|
||||||
CacheKey.PAGE_CAN_EDIT(userId, pageId),
|
canEdit: boolean | null;
|
||||||
PERMISSION_CACHE_TTL_MS,
|
}>`
|
||||||
async () => {
|
WITH RECURSIVE ancestors AS (
|
||||||
const result = await sql<{
|
SELECT id AS ancestor_id, parent_page_id, 0 AS depth
|
||||||
canAccess: boolean | null;
|
FROM pages
|
||||||
canEdit: boolean | null;
|
WHERE id = ${pageId}::uuid
|
||||||
}>`
|
UNION ALL
|
||||||
WITH RECURSIVE ancestors AS (
|
SELECT p.id, p.parent_page_id, a.depth + 1
|
||||||
SELECT id AS ancestor_id, parent_page_id, 0 AS depth
|
FROM pages p
|
||||||
FROM pages
|
JOIN ancestors a ON a.parent_page_id = p.id
|
||||||
WHERE id = ${pageId}::uuid
|
)
|
||||||
UNION ALL
|
SELECT
|
||||||
SELECT p.id, p.parent_page_id, a.depth + 1
|
bool_and(pp.id IS NOT NULL) AS "canAccess",
|
||||||
FROM pages p
|
-- nearest restricted ancestor's highest role wins (DESC: 'writer' > 'reader', NULLS LAST: no-permission after real roles)
|
||||||
JOIN ancestors a ON a.parent_page_id = p.id
|
(array_agg(pp.role ORDER BY a.depth ASC, pp.role DESC NULLS LAST))[1] = 'writer' AS "canEdit"
|
||||||
|
FROM ancestors a
|
||||||
|
JOIN page_access pa ON pa.page_id = a.ancestor_id
|
||||||
|
LEFT JOIN page_permissions pp ON pp.page_access_id = pa.id
|
||||||
|
AND (
|
||||||
|
pp.user_id = ${userId}::uuid
|
||||||
|
OR pp.group_id IN (
|
||||||
|
SELECT gu.group_id FROM group_users gu WHERE gu.user_id = ${userId}::uuid
|
||||||
)
|
)
|
||||||
SELECT
|
)
|
||||||
bool_and(pp.id IS NOT NULL) AS "canAccess",
|
`.execute(this.db);
|
||||||
-- nearest restricted ancestor's highest role wins (DESC: 'writer' > 'reader', NULLS LAST: no-permission after real roles)
|
|
||||||
(array_agg(pp.role ORDER BY a.depth ASC, pp.role DESC NULLS LAST))[1] = 'writer' AS "canEdit"
|
|
||||||
FROM ancestors a
|
|
||||||
JOIN page_access pa ON pa.page_id = a.ancestor_id
|
|
||||||
LEFT JOIN page_permissions pp ON pp.page_access_id = pa.id
|
|
||||||
AND (
|
|
||||||
pp.user_id = ${userId}::uuid
|
|
||||||
OR pp.group_id IN (
|
|
||||||
SELECT gu.group_id FROM group_users gu WHERE gu.user_id = ${userId}::uuid
|
|
||||||
)
|
|
||||||
)
|
|
||||||
`.execute(this.db);
|
|
||||||
|
|
||||||
const row = result.rows[0];
|
const row = result.rows[0];
|
||||||
if (!row || row.canAccess === null) {
|
if (!row || row.canAccess === null) {
|
||||||
return { hasAnyRestriction: false, canAccess: true, canEdit: true };
|
return { hasAnyRestriction: false, canAccess: true, canEdit: true };
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
hasAnyRestriction: true,
|
hasAnyRestriction: true,
|
||||||
canAccess: row.canAccess,
|
canAccess: row.canAccess,
|
||||||
canEdit: row.canAccess && (row.canEdit ?? false),
|
canEdit: row.canAccess && (row.canEdit ?? false),
|
||||||
};
|
};
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -54,7 +54,6 @@ export class PageRepo {
|
|||||||
includeCreator?: boolean;
|
includeCreator?: boolean;
|
||||||
includeLastUpdatedBy?: boolean;
|
includeLastUpdatedBy?: boolean;
|
||||||
includeContributors?: boolean;
|
includeContributors?: boolean;
|
||||||
includeDeletedBy?: boolean;
|
|
||||||
includeHasChildren?: boolean;
|
includeHasChildren?: boolean;
|
||||||
withLock?: boolean;
|
withLock?: boolean;
|
||||||
trx?: KyselyTransaction;
|
trx?: KyselyTransaction;
|
||||||
@@ -84,10 +83,6 @@ export class PageRepo {
|
|||||||
query = query.select((eb) => this.withContributors(eb));
|
query = query.select((eb) => this.withContributors(eb));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (opts?.includeDeletedBy) {
|
|
||||||
query = query.select((eb) => this.withDeletedBy(eb));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (opts?.includeSpace) {
|
if (opts?.includeSpace) {
|
||||||
query = query.select((eb) => this.withSpace(eb));
|
query = query.select((eb) => this.withSpace(eb));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
import { BadRequestException, Inject, Injectable } from '@nestjs/common';
|
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||||
import { CACHE_MANAGER } from '@nestjs/cache-manager';
|
|
||||||
import { Cache } from 'cache-manager';
|
|
||||||
import { InjectKysely } from 'nestjs-kysely';
|
import { InjectKysely } from 'nestjs-kysely';
|
||||||
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
||||||
import { dbOrTx } from '@docmost/db/utils';
|
import { dbOrTx } from '@docmost/db/utils';
|
||||||
@@ -15,11 +13,6 @@ import { MemberInfo, UserSpaceRole } from './types';
|
|||||||
import { executeWithCursorPagination } from '@docmost/db/pagination/cursor-pagination';
|
import { executeWithCursorPagination } from '@docmost/db/pagination/cursor-pagination';
|
||||||
import { GroupRepo } from '@docmost/db/repos/group/group.repo';
|
import { GroupRepo } from '@docmost/db/repos/group/group.repo';
|
||||||
import { SpaceRepo } from '@docmost/db/repos/space/space.repo';
|
import { SpaceRepo } from '@docmost/db/repos/space/space.repo';
|
||||||
import { withCache } from '../../../common/helpers/with-cache';
|
|
||||||
import {
|
|
||||||
CacheKey,
|
|
||||||
PERMISSION_CACHE_TTL_MS,
|
|
||||||
} from '../../../common/helpers/cache-keys';
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SpaceMemberRepo {
|
export class SpaceMemberRepo {
|
||||||
@@ -27,7 +20,6 @@ export class SpaceMemberRepo {
|
|||||||
@InjectKysely() private readonly db: KyselyDB,
|
@InjectKysely() private readonly db: KyselyDB,
|
||||||
private readonly groupRepo: GroupRepo,
|
private readonly groupRepo: GroupRepo,
|
||||||
private readonly spaceRepo: SpaceRepo,
|
private readonly spaceRepo: SpaceRepo,
|
||||||
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async insertSpaceMember(
|
async insertSpaceMember(
|
||||||
@@ -222,36 +214,25 @@ export class SpaceMemberRepo {
|
|||||||
userId: string,
|
userId: string,
|
||||||
spaceId: string,
|
spaceId: string,
|
||||||
): Promise<UserSpaceRole[]> {
|
): Promise<UserSpaceRole[]> {
|
||||||
return withCache(
|
const roles = await this.db
|
||||||
this.cacheManager,
|
.selectFrom('spaceMembers')
|
||||||
CacheKey.SPACE_ROLES(userId, spaceId),
|
.select(['userId', 'role'])
|
||||||
PERMISSION_CACHE_TTL_MS,
|
.where('userId', '=', userId)
|
||||||
async () => {
|
.where('spaceId', '=', spaceId)
|
||||||
const roles = await this.db
|
.unionAll(
|
||||||
|
this.db
|
||||||
.selectFrom('spaceMembers')
|
.selectFrom('spaceMembers')
|
||||||
.select(['userId', 'role'])
|
.innerJoin('groupUsers', 'groupUsers.groupId', 'spaceMembers.groupId')
|
||||||
.where('userId', '=', userId)
|
.select(['groupUsers.userId', 'spaceMembers.role'])
|
||||||
.where('spaceId', '=', spaceId)
|
.where('groupUsers.userId', '=', userId)
|
||||||
.unionAll(
|
.where('spaceMembers.spaceId', '=', spaceId),
|
||||||
this.db
|
)
|
||||||
.selectFrom('spaceMembers')
|
.execute();
|
||||||
.innerJoin(
|
|
||||||
'groupUsers',
|
|
||||||
'groupUsers.groupId',
|
|
||||||
'spaceMembers.groupId',
|
|
||||||
)
|
|
||||||
.select(['groupUsers.userId', 'spaceMembers.role'])
|
|
||||||
.where('groupUsers.userId', '=', userId)
|
|
||||||
.where('spaceMembers.spaceId', '=', spaceId),
|
|
||||||
)
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
if (!roles || roles.length === 0) {
|
if (!roles || roles.length === 0) {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
return roles;
|
return roles;
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async getUserIdsWithSpaceAccess(
|
async getUserIdsWithSpaceAccess(
|
||||||
|
|||||||
Reference in New Issue
Block a user