mirror of
https://github.com/docmost/docmost.git
synced 2026-05-19 07:54:05 +08:00
Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 812d0765b5 | |||
| 234bd13453 | |||
| affd2e6740 | |||
| 37e652ade5 | |||
| 38a847f305 | |||
| 7c80688698 | |||
| 0320e07bb1 | |||
| 1982a0ed1e | |||
| fcb2b08cf3 | |||
| e5ff58a73a | |||
| d3bb105366 | |||
| bbb1b5eb26 | |||
| 3e66aff1e2 | |||
| 89442f5154 | |||
| 12ef426541 | |||
| b7b99cb3b2 | |||
| 03c1e8c4ed | |||
| e41518a93d | |||
| 932c1ad5b7 | |||
| 82d065669d | |||
| f758091b2a | |||
| f4af4c3fc0 | |||
| 3b983a27f6 | |||
| 299a9ca3c8 | |||
| 93ff3f43b7 | |||
| cbf03fc956 | |||
| 68309247b5 | |||
| 474ff6c629 | |||
| c5e9be6b36 | |||
| 00e8c53852 |
@@ -71,6 +71,7 @@
|
||||
"Export": "Export",
|
||||
"Failed to create page": "Failed to create 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 import pages": "Failed to import pages",
|
||||
"Failed to load page. An error occurred.": "Failed to load page. An error occurred.",
|
||||
@@ -361,6 +362,8 @@
|
||||
"Create block quote.": "Create block quote.",
|
||||
"Insert code snippet.": "Insert code snippet.",
|
||||
"Insert horizontal rule divider": "Insert horizontal rule divider",
|
||||
"Page break": "Page break",
|
||||
"Insert a page break for printing.": "Insert a page break for printing.",
|
||||
"Upload any image from your device.": "Upload any image from your device.",
|
||||
"Upload any video from your device.": "Upload any video from your device.",
|
||||
"Upload any audio from your device.": "Upload any audio from your device.",
|
||||
@@ -579,6 +582,8 @@
|
||||
"Move to trash": "Move to trash",
|
||||
"Move this page to trash?": "Move this page to trash?",
|
||||
"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 restored successfully": "Page restored successfully",
|
||||
"Deleted by": "Deleted by",
|
||||
|
||||
@@ -46,6 +46,7 @@ import FavoritesPage from "@/pages/favorites/favorites-page";
|
||||
import AiChat from "@/ee/ai-chat/pages/ai-chat.tsx";
|
||||
import VerifyEmail from "@/ee/pages/verify-email.tsx";
|
||||
import LabelPage from "@/pages/label/label-page";
|
||||
import ConfluenceImportPage from "@/ee/confluence-import/pages/confluence-import.tsx";
|
||||
|
||||
export default function App() {
|
||||
const { t } = useTranslation();
|
||||
@@ -125,6 +126,10 @@ export default function App() {
|
||||
<Route path={"ai/mcp"} element={<AiSettings />} />
|
||||
<Route path={"audit"} element={<AuditLogs />} />
|
||||
<Route path={"verifications"} element={<VerifiedPages />} />
|
||||
<Route
|
||||
path={"import/confluence"}
|
||||
element={<ConfluenceImportPage />}
|
||||
/>
|
||||
{!isCloud() && <Route path={"license"} element={<License />} />}
|
||||
{isCloud() && <Route path={"billing"} element={<Billing />} />}
|
||||
</Route>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Box, ScrollArea, Text } from "@mantine/core";
|
||||
import { ActionIcon, Box, Group, ScrollArea, Text, Tooltip } from "@mantine/core";
|
||||
import { IconX } from "@tabler/icons-react";
|
||||
import CommentListWithTabs from "@/features/comment/components/comment-list-with-tabs.tsx";
|
||||
import { useAtom } from "jotai";
|
||||
import { asideStateAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
|
||||
@@ -11,9 +12,10 @@ import AsideChatPanel from "@/ee/ai-chat/components/aside-chat-panel";
|
||||
import { PageDetailsAside } from "@/features/page-details/components/page-details-aside.tsx";
|
||||
|
||||
export default function Aside() {
|
||||
const [{ tab }] = useAtom(asideStateAtom);
|
||||
const [{ tab }, setAsideState] = useAtom(asideStateAtom);
|
||||
const { t } = useTranslation();
|
||||
const pageEditor = useAtomValue(pageEditorAtom);
|
||||
const closeAside = () => setAsideState((s) => ({ ...s, isAsideOpen: false }));
|
||||
|
||||
let title: string;
|
||||
let component: ReactNode;
|
||||
@@ -45,9 +47,19 @@ export default function Aside() {
|
||||
{component && (
|
||||
<>
|
||||
{tab !== "chat" && (
|
||||
<Text mb="md" fw={500}>
|
||||
{t(title)}
|
||||
</Text>
|
||||
<Group justify="space-between" wrap="nowrap" mb="md">
|
||||
<Text fw={500}>{t(title)}</Text>
|
||||
<Tooltip label={t("Close")} withArrow>
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
color="gray"
|
||||
onClick={closeAside}
|
||||
aria-label={t("Close")}
|
||||
>
|
||||
<IconX size={18} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
)}
|
||||
|
||||
{tab === "comments" || tab === "chat" ? (
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
IconSparkles,
|
||||
IconHistory,
|
||||
IconShieldCheck,
|
||||
IconFileImport,
|
||||
} from "@tabler/icons-react";
|
||||
import { Link, useLocation } from "react-router-dom";
|
||||
import classes from "./settings.module.css";
|
||||
@@ -125,6 +126,13 @@ const groupedData: DataGroup[] = [
|
||||
role: "owner",
|
||||
env: "selfhosted",
|
||||
},
|
||||
{
|
||||
label: "Import",
|
||||
icon: IconFileImport,
|
||||
path: "/settings/import/confluence",
|
||||
feature: Feature.CONFLUENCE_IMPORT,
|
||||
role: "admin",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
Badge,
|
||||
Group,
|
||||
Loader,
|
||||
Progress,
|
||||
Skeleton,
|
||||
Stack,
|
||||
Table,
|
||||
Text,
|
||||
Tooltip,
|
||||
} from "@mantine/core";
|
||||
import { IconAlertCircle, IconCheck, IconX } from "@tabler/icons-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
ConfluenceImportHistoryItem,
|
||||
ConfluenceImportStatus,
|
||||
} from "@/ee/confluence-import/types/confluence-import.types";
|
||||
import { CustomAvatar } from "@/components/ui/custom-avatar";
|
||||
import { formattedDate } from "@/lib/time";
|
||||
import NoTableResults from "@/components/common/no-table-results";
|
||||
import { useConfluenceImportsQuery } from "@/ee/confluence-import/queries/confluence-import-queries";
|
||||
|
||||
const BADGE_STYLES = {
|
||||
root: { flexShrink: 0 },
|
||||
label: { overflow: "visible" as const },
|
||||
};
|
||||
|
||||
function statusBadge(status: ConfluenceImportStatus, cancelled: boolean) {
|
||||
if (cancelled) {
|
||||
return (
|
||||
<Badge
|
||||
color="gray"
|
||||
variant="light"
|
||||
leftSection={<IconX size={12} />}
|
||||
styles={BADGE_STYLES}
|
||||
>
|
||||
Cancelled
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
if (status === "processing") {
|
||||
return (
|
||||
<Badge
|
||||
color="blue"
|
||||
variant="light"
|
||||
leftSection={<Loader size={10} />}
|
||||
styles={BADGE_STYLES}
|
||||
>
|
||||
Running
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
if (status === "success") {
|
||||
return (
|
||||
<Badge
|
||||
color="teal"
|
||||
variant="light"
|
||||
leftSection={<IconCheck size={12} />}
|
||||
styles={BADGE_STYLES}
|
||||
>
|
||||
Completed
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Badge
|
||||
color="red"
|
||||
variant="light"
|
||||
leftSection={<IconAlertCircle size={12} />}
|
||||
styles={BADGE_STYLES}
|
||||
>
|
||||
Failed
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
function phaseLabel(phase: string | null): string {
|
||||
if (!phase) return "—";
|
||||
return phase.charAt(0).toUpperCase() + phase.slice(1);
|
||||
}
|
||||
|
||||
function progressValue(item: ConfluenceImportHistoryItem) {
|
||||
if (item.status === "success") return 100;
|
||||
if (item.totalPages > 0) {
|
||||
return Math.min(
|
||||
100,
|
||||
Math.round((item.importedPages / item.totalPages) * 100),
|
||||
);
|
||||
}
|
||||
return item.status === "processing" ? 5 : 0;
|
||||
}
|
||||
|
||||
function ProgressCell({ item }: { item: ConfluenceImportHistoryItem }) {
|
||||
const value = progressValue(item);
|
||||
const color =
|
||||
item.status === "failed"
|
||||
? "red"
|
||||
: item.status === "success"
|
||||
? "teal"
|
||||
: "blue";
|
||||
|
||||
return (
|
||||
<Stack gap={4}>
|
||||
<Progress value={value} color={color} size="xs" animated={item.status === "processing"} />
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Text fz="xs" c="dimmed" style={{ whiteSpace: "nowrap" }}>
|
||||
{item.importedPages}/{item.totalPages || "?"} pages
|
||||
</Text>
|
||||
<Text fz="xs" c="dimmed" style={{ whiteSpace: "nowrap" }}>
|
||||
· {item.importedSpaces}/{item.totalSpaces || "?"} spaces
|
||||
</Text>
|
||||
<Text fz="xs" c="dimmed" style={{ whiteSpace: "nowrap" }}>
|
||||
· {item.importedUsers}/{item.totalUsers || "?"} users
|
||||
</Text>
|
||||
</Group>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function TableSkeleton() {
|
||||
return (
|
||||
<>
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<Table.Tr key={i}>
|
||||
<Table.Td>
|
||||
<Skeleton height={14} width={120} />
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Skeleton height={14} width={180} />
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Skeleton height={14} width={80} />
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Skeleton height={14} width={140} />
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Skeleton height={14} width={120} />
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Skeleton height={14} width={120} />
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ConfluenceImportHistory() {
|
||||
const { t } = useTranslation();
|
||||
const { data, isLoading } = useConfluenceImportsQuery();
|
||||
|
||||
const items = useMemo(() => data?.items ?? [], [data]);
|
||||
|
||||
return (
|
||||
<Table.ScrollContainer minWidth={720}>
|
||||
<Table verticalSpacing="xs" highlightOnHover>
|
||||
<Table.Thead>
|
||||
<Table.Tr>
|
||||
<Table.Th>{t("Status")}</Table.Th>
|
||||
<Table.Th>{t("Site")}</Table.Th>
|
||||
<Table.Th>{t("Phase")}</Table.Th>
|
||||
<Table.Th>{t("Progress")}</Table.Th>
|
||||
<Table.Th>{t("Started by")}</Table.Th>
|
||||
<Table.Th>{t("Started at")}</Table.Th>
|
||||
</Table.Tr>
|
||||
</Table.Thead>
|
||||
|
||||
<Table.Tbody>
|
||||
{isLoading ? (
|
||||
<TableSkeleton />
|
||||
) : items.length > 0 ? (
|
||||
items.map((item) => (
|
||||
<Table.Tr key={item.fileTaskId}>
|
||||
<Table.Td>
|
||||
{statusBadge(item.status, item.cancelled)}
|
||||
{item.status === "failed" && item.errorMessage && (
|
||||
<Tooltip label={item.errorMessage} multiline w={320}>
|
||||
<Text fz="xs" c="red" lineClamp={1} maw={180}>
|
||||
{item.errorMessage}
|
||||
</Text>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text fz="sm" lineClamp={1} maw={240}>
|
||||
{item.siteUrl}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text fz="sm">{phaseLabel(item.currentPhase)}</Text>
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<ProgressCell item={item} />
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
{item.creatorName ? (
|
||||
<Group gap="sm" wrap="nowrap">
|
||||
<CustomAvatar
|
||||
avatarUrl={item.creatorAvatarUrl}
|
||||
name={item.creatorName}
|
||||
size={24}
|
||||
/>
|
||||
<Text fz="sm" lineClamp={1}>
|
||||
{item.creatorName}
|
||||
</Text>
|
||||
</Group>
|
||||
) : (
|
||||
<Text fz="sm" c="dimmed">
|
||||
—
|
||||
</Text>
|
||||
)}
|
||||
</Table.Td>
|
||||
<Table.Td>
|
||||
<Text fz="sm" style={{ whiteSpace: "nowrap" }}>
|
||||
{formattedDate(new Date(item.createdAt))}
|
||||
</Text>
|
||||
</Table.Td>
|
||||
</Table.Tr>
|
||||
))
|
||||
) : (
|
||||
<NoTableResults colSpan={6} />
|
||||
)}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</Table.ScrollContainer>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Checkbox,
|
||||
Group,
|
||||
Modal,
|
||||
PasswordInput,
|
||||
ScrollArea,
|
||||
SegmentedControl,
|
||||
Stack,
|
||||
Stepper,
|
||||
Text,
|
||||
TextInput,
|
||||
} from "@mantine/core";
|
||||
import {
|
||||
IconAlertCircle,
|
||||
IconCheck,
|
||||
IconCloudCheck,
|
||||
IconPlug,
|
||||
} from "@tabler/icons-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useForm } from "@mantine/form";
|
||||
import { notifications } from "@mantine/notifications";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
listConfluenceSpaces,
|
||||
startConfluenceImport,
|
||||
testConfluenceConnection,
|
||||
} from "@/ee/confluence-import/services/confluence-import-service";
|
||||
import {
|
||||
ConfluenceAuthType,
|
||||
ConfluenceCredentials,
|
||||
ConfluenceSpaceSummary,
|
||||
} from "@/ee/confluence-import/types/confluence-import.types";
|
||||
import { confluenceImportsQueryKey } from "@/ee/confluence-import/queries/confluence-import-queries";
|
||||
|
||||
type ConfluenceEditionChoice = "cloud" | "server";
|
||||
|
||||
type CredentialsFormValues = {
|
||||
edition: ConfluenceEditionChoice;
|
||||
authType: ConfluenceAuthType;
|
||||
siteUrl: string;
|
||||
email: string;
|
||||
token: string;
|
||||
username: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
type Props = {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
export default function ConfluenceImportModal({ opened, onClose }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const [active, setActive] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [spaces, setSpaces] = useState<ConfluenceSpaceSummary[]>([]);
|
||||
const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
|
||||
const [importAll, setImportAll] = useState(true);
|
||||
|
||||
const form = useForm<CredentialsFormValues>({
|
||||
initialValues: {
|
||||
edition: "server",
|
||||
authType: "pat",
|
||||
siteUrl: "",
|
||||
email: "",
|
||||
token: "",
|
||||
username: "",
|
||||
password: "",
|
||||
},
|
||||
validate: {
|
||||
siteUrl: (value) =>
|
||||
!value?.trim()
|
||||
? t("Site URL is required")
|
||||
: !/^https?:\/\//i.test(value.trim())
|
||||
? t("Site URL must start with http:// or https://")
|
||||
: null,
|
||||
email: (value, values) =>
|
||||
values.edition === "cloud" && !value?.trim()
|
||||
? t("Email is required")
|
||||
: null,
|
||||
token: (value, values) =>
|
||||
(values.authType === "cloud_token" || values.authType === "pat") &&
|
||||
!value?.trim()
|
||||
? t("API token is required")
|
||||
: null,
|
||||
username: (value, values) =>
|
||||
values.authType === "basic" && !value?.trim()
|
||||
? t("Username is required")
|
||||
: null,
|
||||
password: (value, values) =>
|
||||
values.authType === "basic" && !value?.trim()
|
||||
? t("Password is required")
|
||||
: null,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!opened) {
|
||||
setActive(0);
|
||||
setError(null);
|
||||
setSpaces([]);
|
||||
setSelectedKeys([]);
|
||||
setImportAll(true);
|
||||
setLoading(false);
|
||||
form.reset();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [opened]);
|
||||
|
||||
const credentials: ConfluenceCredentials = useMemo(() => {
|
||||
const values = form.values;
|
||||
return {
|
||||
siteUrl: values.siteUrl.trim().replace(/\/+$/, ""),
|
||||
authType: values.authType,
|
||||
email: values.email?.trim() || undefined,
|
||||
token: values.token?.trim() || undefined,
|
||||
username: values.username?.trim() || undefined,
|
||||
password: values.password || undefined,
|
||||
};
|
||||
}, [form.values]);
|
||||
|
||||
const handleEditionChange = (edition: ConfluenceEditionChoice) => {
|
||||
form.setFieldValue("edition", edition);
|
||||
if (edition === "cloud") {
|
||||
form.setFieldValue("authType", "cloud_token");
|
||||
} else if (form.values.authType === "cloud_token") {
|
||||
form.setFieldValue("authType", "pat");
|
||||
}
|
||||
};
|
||||
|
||||
const handleNextFromCredentials = async () => {
|
||||
if (form.validate().hasErrors) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const test = await testConfluenceConnection(credentials);
|
||||
if (!test.success) {
|
||||
setError(test.error || t("Connection failed"));
|
||||
return;
|
||||
}
|
||||
const list = await listConfluenceSpaces(credentials);
|
||||
if (!list.success || !list.spaces) {
|
||||
setError(list.error || t("Failed to load spaces"));
|
||||
return;
|
||||
}
|
||||
setSpaces(list.spaces);
|
||||
setSelectedKeys(list.spaces.map((s) => s.key));
|
||||
setImportAll(true);
|
||||
setActive(1);
|
||||
} catch (err: any) {
|
||||
setError(err?.response?.data?.message || err?.message || t("Unexpected error"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleSpace = (key: string, checked: boolean) => {
|
||||
setSelectedKeys((prev) =>
|
||||
checked ? Array.from(new Set([...prev, key])) : prev.filter((k) => k !== key),
|
||||
);
|
||||
};
|
||||
|
||||
const toggleAll = (checked: boolean) => {
|
||||
setImportAll(checked);
|
||||
setSelectedKeys(checked ? spaces.map((s) => s.key) : []);
|
||||
};
|
||||
|
||||
const handleStartImport = async () => {
|
||||
const spaceKeys = importAll ? [] : selectedKeys;
|
||||
if (!importAll && spaceKeys.length === 0) {
|
||||
setError(t("Select at least one space to import"));
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await startConfluenceImport({
|
||||
...credentials,
|
||||
spaceKeys,
|
||||
});
|
||||
if (!result.success || !result.fileTaskId) {
|
||||
setError(result.error || t("Failed to start import"));
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: confluenceImportsQueryKey,
|
||||
});
|
||||
|
||||
notifications.show({
|
||||
title: t("Confluence import started"),
|
||||
message: t("Track progress below. This runs in the background."),
|
||||
color: "blue",
|
||||
icon: <IconCheck size={18} />,
|
||||
autoClose: 4000,
|
||||
});
|
||||
|
||||
onClose();
|
||||
} catch (err: any) {
|
||||
setError(
|
||||
err?.response?.data?.message || err?.message || t("Unexpected error"),
|
||||
);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancelFlow = async () => {
|
||||
onClose();
|
||||
};
|
||||
|
||||
const editionSegment = (
|
||||
<SegmentedControl
|
||||
value={form.values.edition}
|
||||
onChange={(val) => handleEditionChange(val as ConfluenceEditionChoice)}
|
||||
data={[
|
||||
{ value: "server", label: t("Data Center / Server") },
|
||||
{ value: "cloud", label: t("Cloud") },
|
||||
]}
|
||||
fullWidth
|
||||
/>
|
||||
);
|
||||
|
||||
const authTypeSegment = form.values.edition === "server" && (
|
||||
<SegmentedControl
|
||||
value={form.values.authType}
|
||||
onChange={(val) =>
|
||||
form.setFieldValue("authType", val as ConfluenceAuthType)
|
||||
}
|
||||
data={[
|
||||
{ value: "pat", label: t("Personal Access Token") },
|
||||
{ value: "basic", label: t("Username + password") },
|
||||
]}
|
||||
fullWidth
|
||||
/>
|
||||
);
|
||||
|
||||
const selectedCount = importAll ? spaces.length : selectedKeys.length;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
title={t("Import from Confluence")}
|
||||
size={720}
|
||||
centered
|
||||
closeOnClickOutside={!loading}
|
||||
closeOnEscape={!loading}
|
||||
>
|
||||
<Stepper active={active} size="sm" mb="md" allowNextStepsSelect={false}>
|
||||
<Stepper.Step
|
||||
label={t("Connect")}
|
||||
description={t("Credentials")}
|
||||
icon={<IconPlug size={18} />}
|
||||
/>
|
||||
<Stepper.Step
|
||||
label={t("Select spaces")}
|
||||
description={t("Choose what to import")}
|
||||
icon={<IconCloudCheck size={18} />}
|
||||
/>
|
||||
</Stepper>
|
||||
|
||||
{active === 0 && (
|
||||
<Stack>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t(
|
||||
"Enter your Confluence URL and credentials. We'll validate the connection before continuing.",
|
||||
)}
|
||||
</Text>
|
||||
{editionSegment}
|
||||
{authTypeSegment}
|
||||
<TextInput
|
||||
label={t("Site URL")}
|
||||
placeholder={
|
||||
form.values.edition === "cloud"
|
||||
? "https://your-site.atlassian.net/wiki"
|
||||
: "https://confluence.example.com"
|
||||
}
|
||||
required
|
||||
{...form.getInputProps("siteUrl")}
|
||||
/>
|
||||
|
||||
{form.values.edition === "cloud" && (
|
||||
<>
|
||||
<TextInput
|
||||
label={t("Email")}
|
||||
placeholder="you@company.com"
|
||||
required
|
||||
{...form.getInputProps("email")}
|
||||
/>
|
||||
<PasswordInput
|
||||
label={t("API token")}
|
||||
description={t(
|
||||
"Create at id.atlassian.com/manage-profile/security/api-tokens",
|
||||
)}
|
||||
required
|
||||
{...form.getInputProps("token")}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{form.values.edition === "server" &&
|
||||
form.values.authType === "pat" && (
|
||||
<>
|
||||
<TextInput
|
||||
label={t("Email")}
|
||||
placeholder="you@company.com"
|
||||
{...form.getInputProps("email")}
|
||||
/>
|
||||
<PasswordInput
|
||||
label={t("Personal Access Token")}
|
||||
required
|
||||
{...form.getInputProps("token")}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{form.values.edition === "server" &&
|
||||
form.values.authType === "basic" && (
|
||||
<>
|
||||
<TextInput
|
||||
label={t("Username")}
|
||||
required
|
||||
{...form.getInputProps("username")}
|
||||
/>
|
||||
<PasswordInput
|
||||
label={t("Password")}
|
||||
required
|
||||
{...form.getInputProps("password")}
|
||||
/>
|
||||
<TextInput
|
||||
label={t("Email (optional)")}
|
||||
placeholder="you@company.com"
|
||||
{...form.getInputProps("email")}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert color="red" icon={<IconAlertCircle size={18} />}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Group justify="flex-end">
|
||||
<Button variant="default" onClick={handleCancelFlow} disabled={loading}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleNextFromCredentials}
|
||||
loading={loading}
|
||||
>
|
||||
{t("Test & continue")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
{active === 1 && (
|
||||
<Stack>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t(
|
||||
"Choose the spaces to import. Users, groups and permissions will be imported for the selected spaces.",
|
||||
)}
|
||||
</Text>
|
||||
|
||||
<Checkbox
|
||||
label={t("Import all spaces ({{count}})", {
|
||||
count: spaces.length,
|
||||
})}
|
||||
checked={importAll}
|
||||
onChange={(e) => toggleAll(e.currentTarget.checked)}
|
||||
/>
|
||||
|
||||
<ScrollArea h={320} type="auto" offsetScrollbars>
|
||||
<Stack gap="xs">
|
||||
{spaces.map((space) => (
|
||||
<Checkbox
|
||||
key={space.id}
|
||||
label={
|
||||
<Group gap={6} wrap="nowrap">
|
||||
<Text fw={500}>{space.name}</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
({space.key})
|
||||
</Text>
|
||||
</Group>
|
||||
}
|
||||
checked={importAll || selectedKeys.includes(space.key)}
|
||||
disabled={importAll}
|
||||
onChange={(e) =>
|
||||
toggleSpace(space.key, e.currentTarget.checked)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
{spaces.length === 0 && (
|
||||
<Text c="dimmed" ta="center" py="lg">
|
||||
{t("No spaces found for this account.")}
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
</ScrollArea>
|
||||
|
||||
{error && (
|
||||
<Alert color="red" icon={<IconAlertCircle size={18} />}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Group justify="space-between">
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("{{count}} selected", { count: selectedCount })}
|
||||
</Text>
|
||||
<Group>
|
||||
<Button
|
||||
variant="default"
|
||||
onClick={() => setActive(0)}
|
||||
disabled={loading}
|
||||
>
|
||||
{t("Back")}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleStartImport}
|
||||
loading={loading}
|
||||
disabled={!importAll && selectedKeys.length === 0}
|
||||
>
|
||||
{t("Start import")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Group>
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Helmet } from "react-helmet-async";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Button,
|
||||
Divider,
|
||||
Group,
|
||||
Paper,
|
||||
Stack,
|
||||
Text,
|
||||
Tooltip,
|
||||
} from "@mantine/core";
|
||||
import { useDisclosure } from "@mantine/hooks";
|
||||
import SettingsTitle from "@/components/settings/settings-title";
|
||||
import { ConfluenceIcon } from "@/components/icons/confluence-icon";
|
||||
import ConfluenceImportModal from "@/ee/confluence-import/components/confluence-import-modal";
|
||||
import ConfluenceImportHistory from "@/ee/confluence-import/components/confluence-import-history";
|
||||
import { getAppName } from "@/lib/config";
|
||||
import { useHasFeature } from "@/ee/hooks/use-feature";
|
||||
import { Feature } from "@/ee/features";
|
||||
import { useUpgradeLabel } from "@/ee/hooks/use-upgrade-label";
|
||||
|
||||
export default function ConfluenceImportPage() {
|
||||
const { t } = useTranslation();
|
||||
const [opened, { open, close }] = useDisclosure(false);
|
||||
const hasConfluenceImport = useHasFeature(Feature.CONFLUENCE_IMPORT);
|
||||
const upgradeLabel = useUpgradeLabel();
|
||||
|
||||
return (
|
||||
<>
|
||||
<Helmet>
|
||||
<title>
|
||||
{t("Import from Confluence")} - {getAppName()}
|
||||
</title>
|
||||
</Helmet>
|
||||
|
||||
<SettingsTitle title={t("Import from Confluence")} />
|
||||
|
||||
<Paper withBorder p="lg" radius="md" mb="lg">
|
||||
<Group align="flex-start" justify="space-between" wrap="nowrap">
|
||||
<Group align="flex-start" wrap="nowrap">
|
||||
<ConfluenceIcon size={32} />
|
||||
<Stack gap={4}>
|
||||
<Text fw={600}>{t("Confluence API import")}</Text>
|
||||
<Text size="sm" c="dimmed" maw={560}>
|
||||
{t(
|
||||
"Connect to Confluence Cloud or Data Center to import spaces, pages, attachments, comments, users, groups and permissions directly via the API.",
|
||||
)}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
|
||||
<Tooltip label={upgradeLabel} disabled={hasConfluenceImport}>
|
||||
<Button onClick={open} disabled={!hasConfluenceImport}>
|
||||
{t("Start import")}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
</Paper>
|
||||
|
||||
<Divider my="md" label={t("Import history")} labelPosition="left" />
|
||||
|
||||
<ConfluenceImportHistory />
|
||||
|
||||
<ConfluenceImportModal opened={opened} onClose={close} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { listConfluenceImports } from "@/ee/confluence-import/services/confluence-import-service";
|
||||
|
||||
export const confluenceImportsQueryKey = ["confluence-imports"] as const;
|
||||
|
||||
export function useConfluenceImportsQuery() {
|
||||
return useQuery({
|
||||
queryKey: confluenceImportsQueryKey,
|
||||
queryFn: listConfluenceImports,
|
||||
refetchInterval: (query) => {
|
||||
const hasRunning = query.state.data?.items?.some(
|
||||
(i) => i.status === "processing",
|
||||
);
|
||||
return hasRunning ? 3000 : false;
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import api from "@/lib/api-client";
|
||||
import {
|
||||
ConfluenceCredentials,
|
||||
ImportStatusResponse,
|
||||
ListImportsResponse,
|
||||
ListSpacesResponse,
|
||||
StartImportResponse,
|
||||
TestConnectionResponse,
|
||||
} from "@/ee/confluence-import/types/confluence-import.types";
|
||||
|
||||
export async function testConfluenceConnection(
|
||||
data: ConfluenceCredentials,
|
||||
): Promise<TestConnectionResponse> {
|
||||
const req = await api.post<TestConnectionResponse>(
|
||||
"/confluence-import/test-connection",
|
||||
data,
|
||||
);
|
||||
return req.data;
|
||||
}
|
||||
|
||||
export async function listConfluenceSpaces(
|
||||
data: ConfluenceCredentials,
|
||||
): Promise<ListSpacesResponse> {
|
||||
const req = await api.post<ListSpacesResponse>(
|
||||
"/confluence-import/spaces",
|
||||
data,
|
||||
);
|
||||
return req.data;
|
||||
}
|
||||
|
||||
export async function startConfluenceImport(
|
||||
data: ConfluenceCredentials & { spaceKeys?: string[] },
|
||||
): Promise<StartImportResponse> {
|
||||
const req = await api.post<StartImportResponse>(
|
||||
"/confluence-import/start",
|
||||
data,
|
||||
);
|
||||
return req.data;
|
||||
}
|
||||
|
||||
export async function getConfluenceImportStatus(
|
||||
fileTaskId: string,
|
||||
): Promise<ImportStatusResponse> {
|
||||
const req = await api.post<ImportStatusResponse>(
|
||||
"/confluence-import/status",
|
||||
{ fileTaskId },
|
||||
);
|
||||
return req.data;
|
||||
}
|
||||
|
||||
export async function listConfluenceImports(): Promise<ListImportsResponse> {
|
||||
const req = await api.post<ListImportsResponse>("/confluence-import/history");
|
||||
return req.data;
|
||||
}
|
||||
|
||||
export async function cancelConfluenceImport(
|
||||
fileTaskId: string,
|
||||
): Promise<{ success: boolean }> {
|
||||
const req = await api.post<{ success: boolean }>(
|
||||
"/confluence-import/cancel",
|
||||
{ fileTaskId },
|
||||
);
|
||||
return req.data;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
export type ConfluenceAuthType = "cloud_token" | "pat" | "basic";
|
||||
|
||||
export type ConfluenceCredentials = {
|
||||
siteUrl: string;
|
||||
authType: ConfluenceAuthType;
|
||||
email?: string;
|
||||
token?: string;
|
||||
username?: string;
|
||||
password?: string;
|
||||
};
|
||||
|
||||
export type ConfluenceSpaceSummary = {
|
||||
id: string;
|
||||
key: string;
|
||||
name: string;
|
||||
type?: string;
|
||||
status?: string;
|
||||
};
|
||||
|
||||
export type TestConnectionResponse = {
|
||||
success: boolean;
|
||||
edition?: string;
|
||||
spaceCount?: number;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type ListSpacesResponse = {
|
||||
success: boolean;
|
||||
spaces?: ConfluenceSpaceSummary[];
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type StartImportResponse = {
|
||||
success: boolean;
|
||||
fileTaskId?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type ConfluenceImportStatus = "processing" | "success" | "failed";
|
||||
|
||||
export type ImportStatusResponse = {
|
||||
fileTaskId?: string;
|
||||
status?: ConfluenceImportStatus;
|
||||
errorMessage?: string | null;
|
||||
currentPhase?: string | null;
|
||||
totalSpaces?: number;
|
||||
importedSpaces?: number;
|
||||
totalPages?: number;
|
||||
importedPages?: number;
|
||||
totalUsers?: number;
|
||||
importedUsers?: number;
|
||||
warnings?: string[];
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type ConfluenceImportHistoryItem = {
|
||||
fileTaskId: string;
|
||||
siteUrl: string;
|
||||
status: ConfluenceImportStatus;
|
||||
errorMessage: string | null;
|
||||
currentPhase: string | null;
|
||||
totalSpaces: number;
|
||||
importedSpaces: number;
|
||||
totalPages: number;
|
||||
importedPages: number;
|
||||
totalUsers: number;
|
||||
importedUsers: number;
|
||||
cancelled: boolean;
|
||||
spaceKeys: string[];
|
||||
warnings: string[];
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
creatorId: string | null;
|
||||
creatorName: string | null;
|
||||
creatorAvatarUrl: string | null;
|
||||
};
|
||||
|
||||
export type ListImportsResponse = {
|
||||
items: ConfluenceImportHistoryItem[];
|
||||
};
|
||||
@@ -166,6 +166,18 @@ export default function useAuth() {
|
||||
const handleLogout = async () => {
|
||||
setCurrentUser(RESET);
|
||||
await logout();
|
||||
|
||||
try {
|
||||
if (typeof indexedDB?.databases === "function") {
|
||||
const dbs = await indexedDB.databases();
|
||||
dbs
|
||||
.filter((db) => db.name?.startsWith("page."))
|
||||
.forEach((db) => indexedDB.deleteDatabase(db.name!));
|
||||
}
|
||||
} catch {
|
||||
//
|
||||
}
|
||||
|
||||
window.location.replace(`${APP_ROUTE.AUTH.LOGIN}?logout=1`);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { EditorContent, ReactNodeViewRenderer, useEditor } from "@tiptap/react";
|
||||
import { Placeholder } from "@tiptap/extension-placeholder";
|
||||
import { StarterKit } from "@tiptap/starter-kit";
|
||||
import { TextStyle } from "@tiptap/extension-text-style";
|
||||
import { Color } from "@tiptap/extension-color";
|
||||
import { Mention, LinkExtension } from "@docmost/editor-ext";
|
||||
import classes from "./comment.module.css";
|
||||
import { useFocusWithin } from "@mantine/hooks";
|
||||
@@ -47,6 +49,8 @@ const CommentEditor = forwardRef(
|
||||
placeholder: placeholder || t("Reply..."),
|
||||
}),
|
||||
LinkExtension,
|
||||
TextStyle,
|
||||
Color,
|
||||
EmojiCommand,
|
||||
Mention.configure({
|
||||
suggestion: {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { atom } from "jotai";
|
||||
import { Editor } from "@tiptap/core";
|
||||
import { PageEditMode } from "@/features/user/types/user.types.ts";
|
||||
|
||||
export const pageEditorAtom = atom<Editor | null>(null);
|
||||
|
||||
@@ -12,3 +13,7 @@ export const yjsConnectionStatusAtom = atom<string>("");
|
||||
export const showAiMenuAtom = 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);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { BubbleMenu as BaseBubbleMenu } from "@tiptap/react/menus";
|
||||
import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react";
|
||||
import { useCallback } from "react";
|
||||
import { Node as PMNode } from "@tiptap/pm/model";
|
||||
import { isEditorReady } from "@docmost/editor-ext";
|
||||
import {
|
||||
EditorMenuProps,
|
||||
ShouldShowProps,
|
||||
@@ -46,7 +47,7 @@ export function AudioMenu({ editor }: EditorMenuProps) {
|
||||
);
|
||||
|
||||
const getReferencedVirtualElement = useCallback(() => {
|
||||
if (!editor) return;
|
||||
if (!isEditorReady(editor)) return;
|
||||
const { selection } = editor.state;
|
||||
const predicate = (node: PMNode) => node.type.name === "audio";
|
||||
const parent = findParentNode(predicate)(selection);
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
IconMoodSmile,
|
||||
IconNotes,
|
||||
} from "@tabler/icons-react";
|
||||
import { CalloutType, isTextSelected } from "@docmost/editor-ext";
|
||||
import { CalloutType, isEditorReady, isTextSelected } from "@docmost/editor-ext";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import EmojiPicker from "@/components/ui/emoji-picker.tsx";
|
||||
import classes from "../common/toolbar-menu.module.css";
|
||||
@@ -55,7 +55,7 @@ export function CalloutMenu({ editor }: EditorMenuProps) {
|
||||
});
|
||||
|
||||
const getReferencedVirtualElement = useCallback(() => {
|
||||
if (!editor) return;
|
||||
if (!isEditorReady(editor)) return;
|
||||
const { selection } = editor.state;
|
||||
const predicate = (node: PMNode) => node.type.name === "callout";
|
||||
const parent = findParentNode(predicate)(selection);
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
IconCopy,
|
||||
IconTrash,
|
||||
} from "@tabler/icons-react";
|
||||
import { isTextSelected } from "@docmost/editor-ext";
|
||||
import { isEditorReady, isTextSelected } from "@docmost/editor-ext";
|
||||
import type { WidthMode, ColumnsLayout } from "@docmost/editor-ext";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import classes from "../common/toolbar-menu.module.css";
|
||||
@@ -82,7 +82,7 @@ export function ColumnsMenu({ editor }: EditorMenuProps) {
|
||||
|
||||
const shouldShow = useCallback(
|
||||
({ state }: ShouldShowProps) => {
|
||||
if (!state) return false;
|
||||
if (!state || !isEditorReady(editor)) return false;
|
||||
if (!editor.isActive("columns")) return false;
|
||||
if (isTextSelected(editor)) return false;
|
||||
if (nodesWithMenus.some((name) => editor.isActive(name))) return false;
|
||||
@@ -121,7 +121,7 @@ export function ColumnsMenu({ editor }: EditorMenuProps) {
|
||||
});
|
||||
|
||||
const getReferencedVirtualElement = useCallback(() => {
|
||||
if (!editor) return;
|
||||
if (!isEditorReady(editor)) return;
|
||||
const { selection } = editor.state;
|
||||
const predicate = (node: PMNode) => node.type.name === "columns";
|
||||
const parent = findParentNode(predicate)(selection);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { BubbleMenu as BaseBubbleMenu } from "@tiptap/react/menus";
|
||||
import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Node as PMNode } from "@tiptap/pm/model";
|
||||
import { isEditorReady } from "@docmost/editor-ext";
|
||||
import {
|
||||
EditorMenuProps,
|
||||
ShouldShowProps,
|
||||
@@ -81,7 +82,7 @@ export function DrawioMenu({ editor }: EditorMenuProps) {
|
||||
);
|
||||
|
||||
const getReferencedVirtualElement = useCallback(() => {
|
||||
if (!editor) return;
|
||||
if (!isEditorReady(editor)) return;
|
||||
const { selection } = editor.state;
|
||||
const predicate = (node: PMNode) => node.type.name === "drawio";
|
||||
const parent = findParentNode(predicate)(selection);
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { lazy, Suspense } from "react";
|
||||
import { EditorMenuProps } from "@/features/editor/components/table/types/types.ts";
|
||||
|
||||
const ExcalidrawMenu = lazy(
|
||||
() => import("@/features/editor/components/excalidraw/excalidraw-menu.tsx"),
|
||||
);
|
||||
|
||||
export default function ExcalidrawMenuLazy(props: EditorMenuProps) {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<ExcalidrawMenu {...props} />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { BubbleMenu as BaseBubbleMenu } from "@tiptap/react/menus";
|
||||
import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react";
|
||||
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Node as PMNode } from "@tiptap/pm/model";
|
||||
import { isEditorReady } from "@docmost/editor-ext";
|
||||
import {
|
||||
EditorMenuProps,
|
||||
ShouldShowProps,
|
||||
@@ -94,7 +95,7 @@ export function ExcalidrawMenu({ editor }: EditorMenuProps) {
|
||||
);
|
||||
|
||||
const getReferencedVirtualElement = useCallback(() => {
|
||||
if (!editor) return;
|
||||
if (!isEditorReady(editor)) return;
|
||||
const { selection } = editor.state;
|
||||
const predicate = (node: PMNode) => node.type.name === "excalidraw";
|
||||
const parent = findParentNode(predicate)(selection);
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { lazy, Suspense } from "react";
|
||||
import { NodeViewProps } from "@tiptap/react";
|
||||
|
||||
const ExcalidrawView = lazy(
|
||||
() => import("@/features/editor/components/excalidraw/excalidraw-view.tsx"),
|
||||
);
|
||||
|
||||
export default function ExcalidrawViewLazy(props: NodeViewProps) {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<ExcalidrawView {...props} />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
IconH2,
|
||||
IconH3,
|
||||
IconMenu4,
|
||||
IconPageBreak,
|
||||
IconTypography,
|
||||
} from "@tabler/icons-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -102,6 +103,12 @@ export const BlockTypeGroup: FC<Props> = ({ editor }) => {
|
||||
>
|
||||
{t("Divider")}
|
||||
</Menu.Item>
|
||||
<Menu.Item
|
||||
leftSection={<IconPageBreak size={16} />}
|
||||
onClick={() => editor.chain().focus().setPageBreak().run()}
|
||||
>
|
||||
{t("Page break")}
|
||||
</Menu.Item>
|
||||
</Menu.Dropdown>
|
||||
</Menu>
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { BubbleMenu as BaseBubbleMenu } from "@tiptap/react/menus";
|
||||
import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react";
|
||||
import React, { useCallback, useRef } from "react";
|
||||
import { Node as PMNode } from "@tiptap/pm/model";
|
||||
import { isEditorReady } from "@docmost/editor-ext";
|
||||
import {
|
||||
EditorMenuProps,
|
||||
ShouldShowProps,
|
||||
@@ -56,7 +57,7 @@ export function ImageMenu({ editor }: EditorMenuProps) {
|
||||
);
|
||||
|
||||
const getReferencedVirtualElement = useCallback(() => {
|
||||
if (!editor) return;
|
||||
if (!isEditorReady(editor)) return;
|
||||
const { selection } = editor.state;
|
||||
const predicate = (node: PMNode) => node.type.name === "image";
|
||||
const parent = findParentNode(predicate)(selection);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { BubbleMenu as BaseBubbleMenu } from "@tiptap/react/menus";
|
||||
import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react";
|
||||
import { useCallback } from "react";
|
||||
import { Node as PMNode } from "@tiptap/pm/model";
|
||||
import { isEditorReady } from "@docmost/editor-ext";
|
||||
import {
|
||||
EditorMenuProps,
|
||||
ShouldShowProps,
|
||||
@@ -37,9 +38,8 @@ export function PdfMenu({ editor }: EditorMenuProps) {
|
||||
|
||||
const shouldShow = useCallback(
|
||||
({ state }: ShouldShowProps) => {
|
||||
if (!state || !editor.isActive("pdf")) {
|
||||
return false;
|
||||
}
|
||||
if (!state || !isEditorReady(editor)) return false;
|
||||
if (!editor.isActive("pdf")) return false;
|
||||
|
||||
const { selection } = state;
|
||||
const dom = editor.view.nodeDOM(selection.from) as HTMLElement | null;
|
||||
@@ -51,7 +51,7 @@ export function PdfMenu({ editor }: EditorMenuProps) {
|
||||
);
|
||||
|
||||
const getReferencedVirtualElement = useCallback(() => {
|
||||
if (!editor) return;
|
||||
if (!isEditorReady(editor)) return;
|
||||
const { selection } = editor.state;
|
||||
const predicate = (node: PMNode) => node.type.name === "pdf";
|
||||
const parent = findParentNode(predicate)(selection);
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
IconTable,
|
||||
IconTypography,
|
||||
IconMenu4,
|
||||
IconPageBreak,
|
||||
IconCalendar,
|
||||
IconAppWindow,
|
||||
IconSitemap,
|
||||
@@ -164,6 +165,14 @@ const CommandGroups: SlashMenuGroupedItemsType = {
|
||||
command: ({ editor, range }: CommandProps) =>
|
||||
editor.chain().focus().deleteRange(range).setHorizontalRule().run(),
|
||||
},
|
||||
{
|
||||
title: "Page break",
|
||||
description: "Insert a page break for printing.",
|
||||
searchTerms: ["page", "break", "pagebreak", "print"],
|
||||
icon: IconPageBreak,
|
||||
command: ({ editor, range }: CommandProps) =>
|
||||
editor.chain().focus().deleteRange(range).setPageBreak().run(),
|
||||
},
|
||||
{
|
||||
title: "Image",
|
||||
description: "Upload any image from your device.",
|
||||
|
||||
@@ -6,6 +6,7 @@ import { ActionIcon, Tooltip } from "@mantine/core";
|
||||
import { IconTrash } from "@tabler/icons-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Editor } from "@tiptap/core";
|
||||
import { isEditorReady } from "@docmost/editor-ext";
|
||||
|
||||
interface SubpagesMenuProps {
|
||||
editor: Editor;
|
||||
@@ -33,6 +34,7 @@ export const SubpagesMenu = React.memo(
|
||||
);
|
||||
|
||||
const getReferenceClientRect = useCallback(() => {
|
||||
if (!isEditorReady(editor)) return new DOMRect();
|
||||
const { selection } = editor.state;
|
||||
const predicate = (node: PMNode) => node.type.name === "subpages";
|
||||
const parent = findParentNode(predicate)(selection);
|
||||
|
||||
@@ -31,7 +31,12 @@ export const ColumnHandle = React.memo(function ColumnHandle({
|
||||
// (the plugin re-emits `hoveringCell` with the mapped pos a tick later);
|
||||
// unmounting the source element here would make pragmatic-dnd silently
|
||||
// abort the active drag.
|
||||
const lookupCellDom = editor.view.nodeDOM(anchorPos) as HTMLElement | null;
|
||||
// `nodeDOM` is typed as `Node | null` — when `anchorPos` goes stale (e.g.
|
||||
// an external drop reflows the doc before the plugin re-emits
|
||||
// hoveringCell), it can resolve to a Text node, on which `.closest` is
|
||||
// undefined. Filter to HTMLElement so downstream consumers stay safe.
|
||||
const lookupDom = editor.view.nodeDOM(anchorPos);
|
||||
const lookupCellDom = lookupDom instanceof HTMLElement ? lookupDom : null;
|
||||
const [cellDom, setCellDom] = useState<HTMLElement | null>(lookupCellDom);
|
||||
const lastCellDomRef = useRef<HTMLElement | null>(lookupCellDom);
|
||||
useEffect(() => {
|
||||
|
||||
@@ -29,7 +29,12 @@ export const RowHandle = React.memo(function RowHandle({
|
||||
// See ColumnHandle for the rationale: keep the last valid cell DOM cached
|
||||
// so the handle div stays mounted across stale-anchor renders, otherwise
|
||||
// pragmatic-dnd silently aborts an in-flight drag.
|
||||
const lookupCellDom = editor.view.nodeDOM(anchorPos) as HTMLElement | null;
|
||||
// `nodeDOM` is typed as `Node | null` — when `anchorPos` goes stale (e.g.
|
||||
// an external drop reflows the doc before the plugin re-emits
|
||||
// hoveringCell), it can resolve to a Text node, on which `.closest` is
|
||||
// undefined. Filter to HTMLElement so downstream consumers stay safe.
|
||||
const lookupDom = editor.view.nodeDOM(anchorPos);
|
||||
const lookupCellDom = lookupDom instanceof HTMLElement ? lookupDom : null;
|
||||
const [cellDom, setCellDom] = useState<HTMLElement | null>(lookupCellDom);
|
||||
const lastCellDomRef = useRef<HTMLElement | null>(lookupCellDom);
|
||||
useEffect(() => {
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
IconTrashX,
|
||||
} from "@tabler/icons-react";
|
||||
import { BubbleMenu } from "@tiptap/react/menus";
|
||||
import { isCellSelection, isTextSelected } from "@docmost/editor-ext";
|
||||
import { isCellSelection, isEditorReady, isTextSelected } from "@docmost/editor-ext";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import classes from "../common/toolbar-menu.module.css";
|
||||
|
||||
@@ -38,6 +38,7 @@ export const TableMenu = React.memo(
|
||||
);
|
||||
|
||||
const getReferencedVirtualElement = useCallback(() => {
|
||||
if (!isEditorReady(editor)) return;
|
||||
const { selection } = editor.state;
|
||||
const predicate = (node: PMNode) => node.type.name === "table";
|
||||
const parent = findParentNode(predicate)(selection);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { BubbleMenu as BaseBubbleMenu } from "@tiptap/react/menus";
|
||||
import { findParentNode, posToDOMRect, useEditorState } from "@tiptap/react";
|
||||
import { useCallback } from "react";
|
||||
import { Node as PMNode } from "@tiptap/pm/model";
|
||||
import { isEditorReady } from "@docmost/editor-ext";
|
||||
import {
|
||||
EditorMenuProps,
|
||||
ShouldShowProps,
|
||||
@@ -53,7 +54,7 @@ export function VideoMenu({ editor }: EditorMenuProps) {
|
||||
);
|
||||
|
||||
const getReferencedVirtualElement = useCallback(() => {
|
||||
if (!editor) return;
|
||||
if (!isEditorReady(editor)) return;
|
||||
const { selection } = editor.state;
|
||||
const predicate = (node: PMNode) => node.type.name === "video";
|
||||
const parent = findParentNode(predicate)(selection);
|
||||
|
||||
@@ -42,6 +42,7 @@ import {
|
||||
Excalidraw,
|
||||
Embed,
|
||||
TiptapPdf,
|
||||
PageBreak,
|
||||
SearchAndReplace,
|
||||
Mention,
|
||||
TableDndExtension,
|
||||
@@ -84,7 +85,7 @@ import AudioView from "@/features/editor/components/audio/audio-view.tsx";
|
||||
import AttachmentView from "@/features/editor/components/attachment/attachment-view.tsx";
|
||||
import CodeBlockView from "@/features/editor/components/code-block/code-block-view.tsx";
|
||||
import DrawioView from "../components/drawio/drawio-view";
|
||||
import ExcalidrawView from "@/features/editor/components/excalidraw/excalidraw-view.tsx";
|
||||
import ExcalidrawView from "@/features/editor/components/excalidraw/excalidraw-view-lazy.tsx";
|
||||
import EmbedView from "@/features/editor/components/embed/embed-view.tsx";
|
||||
import PdfView from "@/features/editor/components/pdf/pdf-view.tsx";
|
||||
import SubpagesView from "@/features/editor/components/subpages/subpages-view.tsx";
|
||||
@@ -366,6 +367,7 @@ export const mainExtensions = [
|
||||
TiptapPdf.configure({
|
||||
view: PdfView,
|
||||
}),
|
||||
PageBreak,
|
||||
Subpages.configure({
|
||||
view: SubpagesView,
|
||||
}),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import classes from "@/features/editor/styles/editor.module.css";
|
||||
import React from "react";
|
||||
import React, { useEffect } from "react";
|
||||
import { TitleEditor } from "@/features/editor/title-editor";
|
||||
import PageEditor from "@/features/editor/page-editor";
|
||||
import {
|
||||
@@ -23,17 +23,25 @@ import { IContributor } from "@/features/page/types/page.types.ts";
|
||||
import { FixedToolbar } from "@/features/editor/components/fixed-toolbar/fixed-toolbar";
|
||||
import { PageEditMode } from "@/features/user/types/user.types.ts";
|
||||
import useToggleAside from "@/hooks/use-toggle-aside.tsx";
|
||||
import { DeletedPageBanner } from "@/features/page/trash/components/deleted-page-banner.tsx";
|
||||
import clsx from "clsx";
|
||||
import { currentPageEditModeAtom } from "@/features/editor/atoms/editor-atoms.ts";
|
||||
|
||||
const MemoizedTitleEditor = React.memo(TitleEditor);
|
||||
const MemoizedPageEditor = React.memo(PageEditor);
|
||||
const MemoizedFixedToolbar = React.memo(FixedToolbar);
|
||||
const MemoizedDeletedPageBanner = React.memo(DeletedPageBanner);
|
||||
|
||||
type PageCreator = {
|
||||
type PageUser = {
|
||||
id: string;
|
||||
name: 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 {
|
||||
pageId: string;
|
||||
slugId: string;
|
||||
@@ -41,7 +49,7 @@ export interface FullEditorProps {
|
||||
content: string;
|
||||
spaceSlug: string;
|
||||
editable: boolean;
|
||||
creator?: PageCreator;
|
||||
creator?: PageUser;
|
||||
contributors?: IContributor[];
|
||||
canComment?: boolean;
|
||||
}
|
||||
@@ -61,9 +69,21 @@ export function FullEditor({
|
||||
const fullPageWidth = user.settings?.preferences?.fullPageWidth;
|
||||
const editorToolbarEnabled =
|
||||
user.settings?.preferences?.editorToolbar ?? false;
|
||||
const [currentPageEditMode, setCurrentPageEditMode] = useAtom(
|
||||
currentPageEditModeAtom,
|
||||
);
|
||||
const userPageEditMode =
|
||||
user.settings?.preferences?.pageEditMode ?? PageEditMode.Edit;
|
||||
const isEditMode = userPageEditMode === PageEditMode.Edit;
|
||||
const isEditMode = currentPageEditMode === 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 (
|
||||
<Container
|
||||
@@ -71,7 +91,10 @@ export function FullEditor({
|
||||
size={!fullPageWidth && 900}
|
||||
className={classes.editor}
|
||||
>
|
||||
{editorToolbarEnabled && editable && isEditMode && <FixedToolbar />}
|
||||
{editorToolbarEnabled && editable && isEditMode && (
|
||||
<MemoizedFixedToolbar />
|
||||
)}
|
||||
<MemoizedDeletedPageBanner slugId={slugId} />
|
||||
<MemoizedTitleEditor
|
||||
pageId={pageId}
|
||||
slugId={slugId}
|
||||
@@ -95,16 +118,12 @@ export function FullEditor({
|
||||
}
|
||||
|
||||
type PageBylineProps = {
|
||||
creator?: PageCreator;
|
||||
creator?: PageUser;
|
||||
contributors?: IContributor[];
|
||||
readOnly?: boolean;
|
||||
};
|
||||
|
||||
function PageByline({
|
||||
creator,
|
||||
contributors,
|
||||
readOnly,
|
||||
}: PageBylineProps) {
|
||||
function PageByline({ creator, contributors, readOnly }: PageBylineProps) {
|
||||
const { t } = useTranslation();
|
||||
const toggleAside = useToggleAside();
|
||||
|
||||
|
||||
@@ -26,10 +26,11 @@ import {
|
||||
collabExtensions,
|
||||
mainExtensions,
|
||||
} from "@/features/editor/extensions/extensions";
|
||||
import { useAtom } from "jotai";
|
||||
import { useAtom, useAtomValue } from "jotai";
|
||||
import useCollaborationUrl from "@/features/editor/hooks/use-collaboration-url";
|
||||
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
|
||||
import {
|
||||
currentPageEditModeAtom,
|
||||
pageEditorAtom,
|
||||
yjsConnectionStatusAtom,
|
||||
} from "@/features/editor/atoms/editor-atoms";
|
||||
@@ -54,7 +55,7 @@ import {
|
||||
handleFileDrop,
|
||||
handlePaste,
|
||||
} from "@/features/editor/components/common/editor-paste-handler.tsx";
|
||||
import ExcalidrawMenu from "./components/excalidraw/excalidraw-menu";
|
||||
import ExcalidrawMenu from "./components/excalidraw/excalidraw-menu-lazy";
|
||||
import DrawioMenu from "./components/drawio/drawio-menu";
|
||||
import { useCollabToken } from "@/features/auth/queries/auth-query.tsx";
|
||||
import SearchAndReplaceDialog from "@/features/editor/components/search-and-replace/search-and-replace-dialog.tsx";
|
||||
@@ -112,8 +113,7 @@ export default function PageEditor({
|
||||
const documentState = useDocumentVisibility();
|
||||
const { pageSlug } = useParams();
|
||||
const slugId = extractPageSlugId(pageSlug);
|
||||
const userPageEditMode =
|
||||
currentUser?.user?.settings?.preferences?.pageEditMode ?? PageEditMode.Edit;
|
||||
const currentPageEditMode = useAtomValue(currentPageEditModeAtom);
|
||||
const canScroll = useCallback(
|
||||
() => Boolean(isComponentMounted.current && editorRef.current),
|
||||
[isComponentMounted],
|
||||
@@ -373,19 +373,9 @@ export default function PageEditor({
|
||||
return () => clearTimeout(timeout);
|
||||
}, [yjsConnectionStatus, isSynced]);
|
||||
useEffect(() => {
|
||||
// Only honor user default page edit mode preference and permissions
|
||||
if (editor) {
|
||||
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]);
|
||||
if (!editor) return;
|
||||
editor.setEditable(editable && currentPageEditMode === PageEditMode.Edit);
|
||||
}, [currentPageEditMode, editor, editable]);
|
||||
|
||||
const hasConnectedOnceRef = useRef(false);
|
||||
const [showStatic, setShowStatic] = useState(true);
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
@import "./media.css";
|
||||
@import "./code.css";
|
||||
@import "./print.css";
|
||||
@import "./page-break.css";
|
||||
@import "./find.css";
|
||||
@import "./mention.css";
|
||||
@import "./ordered-list.css";
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
.ProseMirror .page-break {
|
||||
position: relative;
|
||||
margin: 1.5rem 0;
|
||||
border-top: 1px dashed var(--mantine-color-default-border);
|
||||
height: 0;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.ProseMirror[contenteditable="false"] .page-break {
|
||||
margin: 0;
|
||||
border: none;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
.ProseMirror[contenteditable="false"] .page-break::after {
|
||||
content: none;
|
||||
}
|
||||
|
||||
.ProseMirror .page-break::after {
|
||||
content: "Page break";
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
padding: 0 0.5rem;
|
||||
background: var(--mantine-color-body);
|
||||
color: var(--mantine-color-dimmed);
|
||||
font-size: 0.75rem;
|
||||
line-height: 1;
|
||||
letter-spacing: 0.02em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.ProseMirror .page-break.ProseMirror-selectednode {
|
||||
border-top-color: var(--mantine-primary-color-filled);
|
||||
}
|
||||
|
||||
@media print {
|
||||
.ProseMirror .page-break {
|
||||
break-before: always;
|
||||
page-break-before: always;
|
||||
visibility: hidden;
|
||||
border: none;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.ProseMirror .page-break::after {
|
||||
content: none;
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { Text } from "@tiptap/extension-text";
|
||||
import { Placeholder } from "@tiptap/extension-placeholder";
|
||||
import { useAtomValue } from "jotai";
|
||||
import {
|
||||
currentPageEditModeAtom,
|
||||
pageEditorAtom,
|
||||
titleEditorAtom,
|
||||
} from "@/features/editor/atoms/editor-atoms";
|
||||
@@ -24,7 +25,6 @@ import { useTranslation } from "react-i18next";
|
||||
import EmojiCommand from "@/features/editor/extensions/emoji-command.ts";
|
||||
import { UpdateEvent } from "@/features/websocket/types";
|
||||
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 { searchSpotlight } from "@/features/search/constants.ts";
|
||||
import { platformModifierKey } from "@/lib";
|
||||
@@ -52,9 +52,7 @@ export function TitleEditor({
|
||||
const emit = useQueryEmit();
|
||||
const navigate = useNavigate();
|
||||
const [activePageId, setActivePageId] = useState(pageId);
|
||||
const [currentUser] = useAtom(currentUserAtom);
|
||||
const userPageEditMode =
|
||||
currentUser?.user?.settings?.preferences?.pageEditMode ?? PageEditMode.Edit;
|
||||
const currentPageEditMode = useAtomValue(currentPageEditModeAtom);
|
||||
|
||||
const titleEditor = useEditor({
|
||||
extensions: [
|
||||
@@ -172,18 +170,9 @@ export function TitleEditor({
|
||||
}, [pageId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (titleEditor) {
|
||||
if (userPageEditMode && editable) {
|
||||
if (userPageEditMode === PageEditMode.Edit) {
|
||||
titleEditor.setEditable(true);
|
||||
} else if (userPageEditMode === PageEditMode.Read) {
|
||||
titleEditor.setEditable(false);
|
||||
}
|
||||
} else {
|
||||
titleEditor.setEditable(false);
|
||||
}
|
||||
}
|
||||
}, [userPageEditMode, titleEditor, editable]);
|
||||
if (!titleEditor) return;
|
||||
titleEditor.setEditable(editable && currentPageEditMode === PageEditMode.Edit);
|
||||
}, [currentPageEditMode, titleEditor, editable]);
|
||||
|
||||
const openSearchDialog = () => {
|
||||
const event = new CustomEvent("openFindDialogFromEditor", {});
|
||||
|
||||
@@ -40,7 +40,7 @@ import {
|
||||
yjsConnectionStatusAtom,
|
||||
} from "@/features/editor/atoms/editor-atoms.ts";
|
||||
import { formattedDate } from "@/lib/time.ts";
|
||||
import { PageStateSegmentedControl } from "@/features/user/components/page-state-pref.tsx";
|
||||
import { PageEditModeToggle } from "@/features/user/components/page-state-pref.tsx";
|
||||
import MovePageModal from "@/features/page/components/move-page-modal.tsx";
|
||||
import { useTimeAgo } from "@/hooks/use-time-ago.tsx";
|
||||
import { PageShareModal } from "@/ee/page-permission";
|
||||
@@ -65,6 +65,11 @@ interface PageHeaderMenuProps {
|
||||
export default function PageHeaderMenu({ readOnly }: PageHeaderMenuProps) {
|
||||
const { t } = useTranslation();
|
||||
const toggleAside = useToggleAside();
|
||||
const { pageSlug } = useParams();
|
||||
const { data: page } = usePageQuery({
|
||||
pageId: extractPageSlugId(pageSlug),
|
||||
});
|
||||
const isDeleted = !!page?.deletedAt;
|
||||
|
||||
useHotkeys(
|
||||
[
|
||||
@@ -87,11 +92,15 @@ export default function PageHeaderMenu({ readOnly }: PageHeaderMenuProps) {
|
||||
[],
|
||||
);
|
||||
|
||||
if (isDeleted) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<ConnectionWarning />
|
||||
|
||||
{!readOnly && <PageStateSegmentedControl size="xs" />}
|
||||
{!readOnly && <PageEditModeToggle size="xs" />}
|
||||
|
||||
<PageShareModal readOnly={readOnly} />
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
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,10 +117,20 @@ export function useUpdatePageMutation() {
|
||||
}
|
||||
|
||||
export function useRemovePageMutation() {
|
||||
const { t } = useTranslation();
|
||||
return useMutation({
|
||||
mutationFn: (pageId: string) => deletePage(pageId, false),
|
||||
onSuccess: (_, pageId) => {
|
||||
notifications.show({ message: "Page moved to trash" });
|
||||
notifications.show({ message: t("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);
|
||||
queryClient.invalidateQueries({
|
||||
predicate: (item) =>
|
||||
@@ -128,7 +138,7 @@ export function useRemovePageMutation() {
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
notifications.show({ message: "Failed to delete page", color: "red" });
|
||||
notifications.show({ message: t("Failed to delete page"), color: "red" });
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -162,13 +172,14 @@ export function useMovePageMutation() {
|
||||
}
|
||||
|
||||
export function useRestorePageMutation() {
|
||||
const { t } = useTranslation();
|
||||
const [treeData, setTreeData] = useAtom(treeDataAtom);
|
||||
const emit = useQueryEmit();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (pageId: string) => restorePage(pageId),
|
||||
onSuccess: async (restoredPage) => {
|
||||
notifications.show({ message: "Page restored successfully" });
|
||||
notifications.show({ message: t("Page restored successfully") });
|
||||
|
||||
// Check if the page already exists in the tree (it shouldn't)
|
||||
if (!treeModel.find(treeData, restoredPage.id)) {
|
||||
@@ -222,9 +233,16 @@ export function useRestorePageMutation() {
|
||||
await queryClient.invalidateQueries({
|
||||
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) => {
|
||||
notifications.show({ message: "Failed to restore page", color: "red" });
|
||||
notifications.show({ message: t("Failed to restore page"), color: "red" });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
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,17 +7,16 @@ import {
|
||||
Group,
|
||||
ActionIcon,
|
||||
Text,
|
||||
Alert,
|
||||
Stack,
|
||||
Menu,
|
||||
} from "@mantine/core";
|
||||
import {
|
||||
IconInfoCircle,
|
||||
IconDots,
|
||||
IconRestore,
|
||||
IconTrash,
|
||||
IconFileDescription,
|
||||
} from "@tabler/icons-react";
|
||||
import { TrashBanner } from "@/features/page/trash/components/trash-banner.tsx";
|
||||
import {
|
||||
useDeletedPagesQuery,
|
||||
useRestorePageMutation,
|
||||
@@ -31,12 +30,10 @@ import TrashPageContentModal from "@/features/page/trash/components/trash-page-c
|
||||
import { UserInfo } from "@/components/common/user-info.tsx";
|
||||
import Paginate from "@/components/common/paginate.tsx";
|
||||
import { useCursorPaginate } from "@/hooks/use-cursor-paginate";
|
||||
import { useAtom } from "jotai";
|
||||
import { workspaceAtom } from "@/features/user/atoms/current-user-atom.ts";
|
||||
import { useRestorePageModal } from "@/features/page/hooks/use-restore-page-modal.tsx";
|
||||
|
||||
export default function Trash() {
|
||||
const { t } = useTranslation();
|
||||
const [workspace] = useAtom(workspaceAtom);
|
||||
const { spaceSlug } = useParams();
|
||||
const { cursor, goNext, goPrev } = useCursorPaginate();
|
||||
const { data: space } = useGetSpaceBySlugQuery(spaceSlug);
|
||||
@@ -45,6 +42,7 @@ export default function Trash() {
|
||||
});
|
||||
const restorePageMutation = useRestorePageMutation();
|
||||
const deletePageMutation = useDeletePageMutation();
|
||||
const { openRestoreModal } = useRestorePageModal();
|
||||
|
||||
const [selectedPage, setSelectedPage] = useState<{
|
||||
title: string;
|
||||
@@ -78,23 +76,6 @@ 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 handlePageClick = (page: any) => {
|
||||
@@ -109,11 +90,7 @@ export default function Trash() {
|
||||
<Title order={2}>{t("Trash")}</Title>
|
||||
</Group>
|
||||
|
||||
<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>
|
||||
<TrashBanner />
|
||||
|
||||
{isLoading || !deletedPages ? (
|
||||
<></>
|
||||
@@ -181,7 +158,10 @@ export default function Trash() {
|
||||
<Menu.Item
|
||||
leftSection={<IconRestore size={16} />}
|
||||
onClick={() =>
|
||||
openRestoreModal(page.id, page.title)
|
||||
openRestoreModal({
|
||||
title: page.title,
|
||||
onConfirm: () => handleRestorePage(page.id),
|
||||
})
|
||||
}
|
||||
>
|
||||
{t("Restore")}
|
||||
|
||||
@@ -6,6 +6,7 @@ import React, { useCallback, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PageEditMode } from "@/features/user/types/user.types.ts";
|
||||
import { ResponsiveSettingsRow, ResponsiveSettingsContent, ResponsiveSettingsControl } from "@/components/ui/responsive-settings-row";
|
||||
import { currentPageEditModeAtom } from "@/features/editor/atoms/editor-atoms.ts";
|
||||
|
||||
export default function PageStatePref() {
|
||||
const { t } = useTranslation();
|
||||
@@ -71,3 +72,24 @@ 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) });
|
||||
const { data: space } = useGetSpaceBySlugQuery(page?.space?.slug);
|
||||
|
||||
const canEdit = page?.permissions?.canEdit ?? false;
|
||||
const canEdit = !page?.deletedAt && (page?.permissions?.canEdit ?? false);
|
||||
const canComment =
|
||||
canEdit ||
|
||||
(space?.settings?.comments?.allowViewerComments === true);
|
||||
|
||||
@@ -38,12 +38,12 @@ export default defineConfig(({ mode }) => {
|
||||
build: {
|
||||
rolldownOptions: {
|
||||
output: {
|
||||
codeSplitting: {
|
||||
advancedChunks: {
|
||||
groups: [
|
||||
{ name: "vendor-mantine", test: /@mantine/ },
|
||||
{ name: "vendor-mermaid", test: /mermaid|cytoscape|elkjs/ },
|
||||
{ name: "vendor-excalidraw", test: /excalidraw/ },
|
||||
{ name: "vendor-katex", test: /katex/ },
|
||||
{
|
||||
name: "vendor-mantine",
|
||||
test: /[\\/]node_modules[\\/]@mantine[\\/]/,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
@@ -55,6 +55,7 @@ export default defineConfig(({ mode }) => {
|
||||
},
|
||||
},
|
||||
server: {
|
||||
allowedHosts: ['docmost.nz'],
|
||||
proxy: {
|
||||
"/api": {
|
||||
target: APP_URL,
|
||||
|
||||
@@ -81,7 +81,7 @@
|
||||
"ioredis": "^5.10.1",
|
||||
"js-tiktoken": "^1.0.21",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"kysely": "^0.29.0",
|
||||
"kysely": "^0.28.17",
|
||||
"kysely-migration-cli": "^0.4.2",
|
||||
"kysely-postgres-js": "^3.0.0",
|
||||
"ldapts": "^8.1.7",
|
||||
|
||||
@@ -27,6 +27,7 @@ import { LoggerModule } from './common/logger/logger.module';
|
||||
import { ClsModule } from 'nestjs-cls';
|
||||
import { NoopAuditModule } from './integrations/audit/audit.module';
|
||||
import { ThrottleModule } from './integrations/throttle/throttle.module';
|
||||
import { EncryptionModule } from './integrations/encryption/encryption.module';
|
||||
|
||||
const enterpriseModules = [];
|
||||
try {
|
||||
@@ -53,6 +54,7 @@ try {
|
||||
CoreModule,
|
||||
DatabaseModule,
|
||||
EnvironmentModule,
|
||||
EncryptionModule,
|
||||
RedisModule.forRootAsync({
|
||||
useClass: RedisConfigService,
|
||||
}),
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
TiptapVideo,
|
||||
TiptapAudio,
|
||||
TiptapPdf,
|
||||
PageBreak,
|
||||
TrailingNode,
|
||||
Attachment,
|
||||
Drawio,
|
||||
@@ -94,6 +95,7 @@ export const tiptapExtensions = [
|
||||
TiptapVideo,
|
||||
TiptapAudio,
|
||||
TiptapPdf,
|
||||
PageBreak,
|
||||
Callout,
|
||||
Attachment,
|
||||
CustomCodeBlock,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
|
||||
import { AppController } from '../../app.controller';
|
||||
import { AppService } from '../../app.service';
|
||||
import { EnvironmentModule } from '../../integrations/environment/environment.module';
|
||||
import { EnvironmentService } from '../../integrations/environment/environment.service';
|
||||
import { CollaborationModule } from '../collaboration.module';
|
||||
import { DatabaseModule } from '@docmost/db/database.module';
|
||||
import { QueueModule } from '../../integrations/queue/queue.module';
|
||||
@@ -12,6 +13,8 @@ import { LoggerModule } from '../../common/logger/logger.module';
|
||||
import { RedisModule } from '@nestjs-labs/nestjs-ioredis';
|
||||
import { RedisConfigService } from '../../integrations/redis/redis-config.service';
|
||||
import { CaslModule } from '../../core/casl/casl.module';
|
||||
import { CacheModule } from '@nestjs/cache-manager';
|
||||
import KeyvRedis from '@keyv/redis';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -26,6 +29,18 @@ import { CaslModule } from '../../core/casl/casl.module';
|
||||
RedisModule.forRootAsync({
|
||||
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: [
|
||||
AppController,
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
export const CacheKey = {
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
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,6 +76,7 @@ export class PageController {
|
||||
includeCreator: true,
|
||||
includeLastUpdatedBy: true,
|
||||
includeContributors: true,
|
||||
includeDeletedBy: true,
|
||||
});
|
||||
|
||||
if (!page) {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { CACHE_MANAGER } from '@nestjs/cache-manager';
|
||||
import { Cache } from 'cache-manager';
|
||||
import { InjectKysely } from 'nestjs-kysely';
|
||||
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
||||
import { dbOrTx } from '@docmost/db/utils';
|
||||
@@ -17,6 +19,11 @@ import {
|
||||
executeWithCursorPagination,
|
||||
} from '@docmost/db/pagination/cursor-pagination';
|
||||
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';
|
||||
|
||||
@@ -25,6 +32,7 @@ export class PagePermissionRepo {
|
||||
constructor(
|
||||
@InjectKysely() private readonly db: KyselyDB,
|
||||
private readonly groupRepo: GroupRepo,
|
||||
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
|
||||
) {}
|
||||
|
||||
async findPageAccessByPageId(
|
||||
@@ -361,40 +369,8 @@ export class PagePermissionRepo {
|
||||
* Check if user can access a page by verifying they have permission on ALL restricted ancestors.
|
||||
*/
|
||||
async canUserAccessPage(userId: string, pageId: string): Promise<boolean> {
|
||||
const deniedAncestor = await this.db
|
||||
.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;
|
||||
const { canAccess } = await this.canUserEditPage(userId, pageId);
|
||||
return canAccess;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -412,43 +388,50 @@ export class PagePermissionRepo {
|
||||
canAccess: boolean;
|
||||
canEdit: boolean;
|
||||
}> {
|
||||
const result = await sql<{
|
||||
canAccess: boolean | null;
|
||||
canEdit: boolean | null;
|
||||
}>`
|
||||
WITH RECURSIVE ancestors AS (
|
||||
SELECT id AS ancestor_id, parent_page_id, 0 AS depth
|
||||
FROM pages
|
||||
WHERE id = ${pageId}::uuid
|
||||
UNION ALL
|
||||
SELECT p.id, p.parent_page_id, a.depth + 1
|
||||
FROM pages p
|
||||
JOIN ancestors a ON a.parent_page_id = p.id
|
||||
)
|
||||
SELECT
|
||||
bool_and(pp.id IS NOT NULL) AS "canAccess",
|
||||
-- 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
|
||||
return withCache(
|
||||
this.cacheManager,
|
||||
CacheKey.PAGE_CAN_EDIT(userId, pageId),
|
||||
PERMISSION_CACHE_TTL_MS,
|
||||
async () => {
|
||||
const result = await sql<{
|
||||
canAccess: boolean | null;
|
||||
canEdit: boolean | null;
|
||||
}>`
|
||||
WITH RECURSIVE ancestors AS (
|
||||
SELECT id AS ancestor_id, parent_page_id, 0 AS depth
|
||||
FROM pages
|
||||
WHERE id = ${pageId}::uuid
|
||||
UNION ALL
|
||||
SELECT p.id, p.parent_page_id, a.depth + 1
|
||||
FROM pages p
|
||||
JOIN ancestors a ON a.parent_page_id = p.id
|
||||
)
|
||||
)
|
||||
`.execute(this.db);
|
||||
SELECT
|
||||
bool_and(pp.id IS NOT NULL) AS "canAccess",
|
||||
-- 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];
|
||||
if (!row || row.canAccess === null) {
|
||||
return { hasAnyRestriction: false, canAccess: true, canEdit: true };
|
||||
}
|
||||
return {
|
||||
hasAnyRestriction: true,
|
||||
canAccess: row.canAccess,
|
||||
canEdit: row.canAccess && (row.canEdit ?? false),
|
||||
};
|
||||
const row = result.rows[0];
|
||||
if (!row || row.canAccess === null) {
|
||||
return { hasAnyRestriction: false, canAccess: true, canEdit: true };
|
||||
}
|
||||
return {
|
||||
hasAnyRestriction: true,
|
||||
canAccess: row.canAccess,
|
||||
canEdit: row.canAccess && (row.canEdit ?? false),
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -54,6 +54,7 @@ export class PageRepo {
|
||||
includeCreator?: boolean;
|
||||
includeLastUpdatedBy?: boolean;
|
||||
includeContributors?: boolean;
|
||||
includeDeletedBy?: boolean;
|
||||
includeHasChildren?: boolean;
|
||||
withLock?: boolean;
|
||||
trx?: KyselyTransaction;
|
||||
@@ -83,6 +84,10 @@ export class PageRepo {
|
||||
query = query.select((eb) => this.withContributors(eb));
|
||||
}
|
||||
|
||||
if (opts?.includeDeletedBy) {
|
||||
query = query.select((eb) => this.withDeletedBy(eb));
|
||||
}
|
||||
|
||||
if (opts?.includeSpace) {
|
||||
query = query.select((eb) => this.withSpace(eb));
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { BadRequestException, Inject, Injectable } from '@nestjs/common';
|
||||
import { CACHE_MANAGER } from '@nestjs/cache-manager';
|
||||
import { Cache } from 'cache-manager';
|
||||
import { InjectKysely } from 'nestjs-kysely';
|
||||
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
|
||||
import { dbOrTx } from '@docmost/db/utils';
|
||||
@@ -13,6 +15,11 @@ import { MemberInfo, UserSpaceRole } from './types';
|
||||
import { executeWithCursorPagination } from '@docmost/db/pagination/cursor-pagination';
|
||||
import { GroupRepo } from '@docmost/db/repos/group/group.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()
|
||||
export class SpaceMemberRepo {
|
||||
@@ -20,6 +27,7 @@ export class SpaceMemberRepo {
|
||||
@InjectKysely() private readonly db: KyselyDB,
|
||||
private readonly groupRepo: GroupRepo,
|
||||
private readonly spaceRepo: SpaceRepo,
|
||||
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
|
||||
) {}
|
||||
|
||||
async insertSpaceMember(
|
||||
@@ -214,25 +222,36 @@ export class SpaceMemberRepo {
|
||||
userId: string,
|
||||
spaceId: string,
|
||||
): Promise<UserSpaceRole[]> {
|
||||
const roles = await this.db
|
||||
.selectFrom('spaceMembers')
|
||||
.select(['userId', 'role'])
|
||||
.where('userId', '=', userId)
|
||||
.where('spaceId', '=', spaceId)
|
||||
.unionAll(
|
||||
this.db
|
||||
return withCache(
|
||||
this.cacheManager,
|
||||
CacheKey.SPACE_ROLES(userId, spaceId),
|
||||
PERMISSION_CACHE_TTL_MS,
|
||||
async () => {
|
||||
const roles = await this.db
|
||||
.selectFrom('spaceMembers')
|
||||
.innerJoin('groupUsers', 'groupUsers.groupId', 'spaceMembers.groupId')
|
||||
.select(['groupUsers.userId', 'spaceMembers.role'])
|
||||
.where('groupUsers.userId', '=', userId)
|
||||
.where('spaceMembers.spaceId', '=', spaceId),
|
||||
)
|
||||
.execute();
|
||||
.select(['userId', 'role'])
|
||||
.where('userId', '=', userId)
|
||||
.where('spaceId', '=', spaceId)
|
||||
.unionAll(
|
||||
this.db
|
||||
.selectFrom('spaceMembers')
|
||||
.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) {
|
||||
return undefined;
|
||||
}
|
||||
return roles;
|
||||
if (!roles || roles.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return roles;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async getUserIdsWithSpaceAccess(
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Json, Timestamp, Generated } from '@docmost/db/types/db';
|
||||
|
||||
export interface ConfluenceApiImports {
|
||||
id: Generated<string>;
|
||||
fileTaskId: string;
|
||||
siteUrl: string;
|
||||
authType: string;
|
||||
authEmail: string | null;
|
||||
authToken: string | null;
|
||||
authUsername: string | null;
|
||||
totalSpaces: Generated<number>;
|
||||
importedSpaces: Generated<number>;
|
||||
totalPages: Generated<number>;
|
||||
importedPages: Generated<number>;
|
||||
totalUsers: Generated<number>;
|
||||
importedUsers: Generated<number>;
|
||||
totalAttachments: Generated<number>;
|
||||
importedAttachments: Generated<number>;
|
||||
totalLabels: Generated<number>;
|
||||
importedLabels: Generated<number>;
|
||||
idMapping: Generated<Json>;
|
||||
warnings: Generated<Json>;
|
||||
currentPhase: string | null;
|
||||
cancelled: Generated<boolean>;
|
||||
spaceKeys: Generated<Json>;
|
||||
workspaceId: string;
|
||||
creatorId: string | null;
|
||||
createdAt: Generated<Timestamp>;
|
||||
updatedAt: Generated<Timestamp>;
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { DB } from '@docmost/db/types/db';
|
||||
import { PageEmbeddings } from '@docmost/db/types/embeddings.types';
|
||||
import { ConfluenceApiImports } from './custom.types';
|
||||
|
||||
export interface DbInterface extends DB {
|
||||
pageEmbeddings: PageEmbeddings;
|
||||
confluenceApiImports: ConfluenceApiImports;
|
||||
}
|
||||
|
||||
+1
-1
Submodule apps/server/src/ee updated: 71844c0972...c2d2c373c6
@@ -0,0 +1,13 @@
|
||||
export class UnableToInitialize extends Error {
|
||||
constructor(message: string) {
|
||||
super(`Unable to initialize the encryption service: ${message}`);
|
||||
this.name = 'UnableToInitialize';
|
||||
}
|
||||
}
|
||||
|
||||
export class UnableToDecrypt extends Error {
|
||||
constructor(reason: string) {
|
||||
super(`Unable to decrypt the ciphertext: ${reason}`);
|
||||
this.name = 'UnableToDecrypt';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { EncryptionService } from './encryption.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [EncryptionService],
|
||||
exports: [EncryptionService],
|
||||
})
|
||||
export class EncryptionModule {}
|
||||
@@ -0,0 +1,184 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { EncryptionService } from './encryption.service';
|
||||
import { UnableToDecrypt, UnableToInitialize } from './encryption.errors';
|
||||
import { EnvironmentService } from '../environment/environment.service';
|
||||
|
||||
const APP_SECRET = 'test-app-secret-with-plenty-of-entropy-1234567890';
|
||||
|
||||
const buildService = (appSecret: string | undefined) => {
|
||||
const env = { getAppSecret: () => appSecret } as EnvironmentService;
|
||||
return new EncryptionService(env);
|
||||
};
|
||||
|
||||
const decodeEnvelope = (encrypted: string) =>
|
||||
JSON.parse(Buffer.from(encrypted, 'base64').toString()) as {
|
||||
iv: string;
|
||||
authTag: string;
|
||||
cipherText: string;
|
||||
};
|
||||
|
||||
const encodeEnvelope = (envelope: {
|
||||
iv: string;
|
||||
authTag: string;
|
||||
cipherText: string;
|
||||
}) => Buffer.from(JSON.stringify(envelope)).toString('base64');
|
||||
|
||||
describe('EncryptionService', () => {
|
||||
let service: EncryptionService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
EncryptionService,
|
||||
{
|
||||
provide: EnvironmentService,
|
||||
useValue: { getAppSecret: () => APP_SECRET },
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<EncryptionService>(EncryptionService);
|
||||
});
|
||||
|
||||
describe('initialization', () => {
|
||||
it('compiles via Nest DI', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
it('throws UnableToInitialize when APP_SECRET is missing', () => {
|
||||
expect(() => buildService(undefined)).toThrow(UnableToInitialize);
|
||||
expect(() => buildService('')).toThrow(UnableToInitialize);
|
||||
});
|
||||
});
|
||||
|
||||
describe('encrypt + decrypt round-trip', () => {
|
||||
it('decrypts back to the original plaintext', () => {
|
||||
const plaintext = 'hello world';
|
||||
const encrypted = service.encrypt(plaintext);
|
||||
expect(service.decrypt(encrypted)).toBe(plaintext);
|
||||
});
|
||||
|
||||
it('handles empty string', () => {
|
||||
const encrypted = service.encrypt('');
|
||||
expect(service.decrypt(encrypted)).toBe('');
|
||||
});
|
||||
|
||||
it('handles unicode (multi-byte UTF-8)', () => {
|
||||
const plaintext = 'héllo 🔐 世界';
|
||||
const encrypted = service.encrypt(plaintext);
|
||||
expect(service.decrypt(encrypted)).toBe(plaintext);
|
||||
});
|
||||
|
||||
it('handles long plaintext (>1 block)', () => {
|
||||
const plaintext = 'a'.repeat(10_000);
|
||||
const encrypted = service.encrypt(plaintext);
|
||||
expect(service.decrypt(encrypted)).toBe(plaintext);
|
||||
});
|
||||
|
||||
it('produces distinct ciphertexts for the same plaintext (random IV)', () => {
|
||||
const plaintext = 'same input';
|
||||
const a = service.encrypt(plaintext);
|
||||
const b = service.encrypt(plaintext);
|
||||
expect(a).not.toBe(b);
|
||||
expect(service.decrypt(a)).toBe(plaintext);
|
||||
expect(service.decrypt(b)).toBe(plaintext);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cross-key isolation', () => {
|
||||
it('cannot decrypt ciphertext produced under a different APP_SECRET', () => {
|
||||
const other = buildService('totally-different-secret-value-9876543210');
|
||||
const encrypted = service.encrypt('secret');
|
||||
expect(() => other.decrypt(encrypted)).toThrow(UnableToDecrypt);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tamper detection', () => {
|
||||
it('rejects modified ciphertext', () => {
|
||||
const encrypted = service.encrypt('hello');
|
||||
const env = decodeEnvelope(encrypted);
|
||||
const tamperedCipher = Buffer.from(env.cipherText, 'base64');
|
||||
tamperedCipher[0] ^= 0x01;
|
||||
const tampered = encodeEnvelope({
|
||||
...env,
|
||||
cipherText: tamperedCipher.toString('base64'),
|
||||
});
|
||||
expect(() => service.decrypt(tampered)).toThrow(UnableToDecrypt);
|
||||
});
|
||||
|
||||
it('rejects modified auth tag', () => {
|
||||
const encrypted = service.encrypt('hello');
|
||||
const env = decodeEnvelope(encrypted);
|
||||
const tamperedTag = Buffer.from(env.authTag, 'base64');
|
||||
tamperedTag[0] ^= 0x01;
|
||||
const tampered = encodeEnvelope({
|
||||
...env,
|
||||
authTag: tamperedTag.toString('base64'),
|
||||
});
|
||||
expect(() => service.decrypt(tampered)).toThrow(UnableToDecrypt);
|
||||
});
|
||||
|
||||
it('rejects modified IV', () => {
|
||||
const encrypted = service.encrypt('hello');
|
||||
const env = decodeEnvelope(encrypted);
|
||||
const tamperedIV = Buffer.from(env.iv, 'base64');
|
||||
tamperedIV[0] ^= 0x01;
|
||||
const tampered = encodeEnvelope({
|
||||
...env,
|
||||
iv: tamperedIV.toString('base64'),
|
||||
});
|
||||
expect(() => service.decrypt(tampered)).toThrow(UnableToDecrypt);
|
||||
});
|
||||
});
|
||||
|
||||
describe('malformed payloads', () => {
|
||||
it('rejects non-base64 garbage', () => {
|
||||
expect(() => service.decrypt('!!!not-valid-base64!!!')).toThrow(
|
||||
UnableToDecrypt,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects base64 of non-JSON', () => {
|
||||
const garbage = Buffer.from('not json at all').toString('base64');
|
||||
expect(() => service.decrypt(garbage)).toThrow(UnableToDecrypt);
|
||||
});
|
||||
|
||||
it('rejects JSON missing required fields', () => {
|
||||
const partial = encodeEnvelope({
|
||||
iv: Buffer.alloc(12).toString('base64'),
|
||||
authTag: Buffer.alloc(16).toString('base64'),
|
||||
} as never);
|
||||
expect(() => service.decrypt(partial)).toThrow(UnableToDecrypt);
|
||||
});
|
||||
|
||||
it('rejects wrong-length IV', () => {
|
||||
const encrypted = service.encrypt('hello');
|
||||
const env = decodeEnvelope(encrypted);
|
||||
const bad = encodeEnvelope({
|
||||
...env,
|
||||
iv: Buffer.alloc(8).toString('base64'),
|
||||
});
|
||||
expect(() => service.decrypt(bad)).toThrow(UnableToDecrypt);
|
||||
});
|
||||
|
||||
it('rejects wrong-length auth tag', () => {
|
||||
const encrypted = service.encrypt('hello');
|
||||
const env = decodeEnvelope(encrypted);
|
||||
const bad = encodeEnvelope({
|
||||
...env,
|
||||
authTag: Buffer.alloc(8).toString('base64'),
|
||||
});
|
||||
expect(() => service.decrypt(bad)).toThrow(UnableToDecrypt);
|
||||
});
|
||||
});
|
||||
|
||||
describe('envelope format', () => {
|
||||
it('returns base64 of JSON envelope with iv (12B), authTag (16B), cipherText', () => {
|
||||
const encrypted = service.encrypt('hello');
|
||||
const env = decodeEnvelope(encrypted);
|
||||
expect(Buffer.from(env.iv, 'base64')).toHaveLength(12);
|
||||
expect(Buffer.from(env.authTag, 'base64')).toHaveLength(16);
|
||||
expect(Buffer.from(env.cipherText, 'base64').length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
// https://github.com/nhedger/nestjs-encryption - MIT
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
createCipheriv,
|
||||
createDecipheriv,
|
||||
createHash,
|
||||
randomBytes,
|
||||
} from 'node:crypto';
|
||||
import { UnableToDecrypt, UnableToInitialize } from './encryption.errors';
|
||||
import { EnvironmentService } from '../environment/environment.service';
|
||||
|
||||
const ALGORITHM = 'aes-256-gcm';
|
||||
const KEY_DOMAIN = 'docmost:encryption:v1';
|
||||
const IV_LENGTH = 12;
|
||||
const AUTH_TAG_LENGTH = 16;
|
||||
|
||||
type AEADPayload<TFormat = string | Buffer> = {
|
||||
iv: TFormat;
|
||||
authTag: TFormat;
|
||||
cipherText: TFormat;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class EncryptionService {
|
||||
private readonly key: Buffer;
|
||||
|
||||
constructor(environmentService: EnvironmentService) {
|
||||
const appSecret = environmentService.getAppSecret();
|
||||
if (!appSecret) {
|
||||
throw new UnableToInitialize('APP_SECRET is not set.');
|
||||
}
|
||||
this.key = createHash('sha256')
|
||||
.update(KEY_DOMAIN)
|
||||
.update(appSecret)
|
||||
.digest();
|
||||
}
|
||||
|
||||
public encrypt(plaintext: string): string {
|
||||
const iv = randomBytes(IV_LENGTH);
|
||||
const cipher = createCipheriv(ALGORITHM, this.key, iv);
|
||||
const cipherText = Buffer.concat([
|
||||
cipher.update(plaintext, 'utf8'),
|
||||
cipher.final(),
|
||||
]);
|
||||
const authTag = cipher.getAuthTag();
|
||||
|
||||
const aead: AEADPayload<string> = {
|
||||
iv: iv.toString('base64'),
|
||||
authTag: authTag.toString('base64'),
|
||||
cipherText: cipherText.toString('base64'),
|
||||
};
|
||||
|
||||
return Buffer.from(JSON.stringify(aead)).toString('base64');
|
||||
}
|
||||
|
||||
public decrypt(encrypted: string): string {
|
||||
try {
|
||||
const { iv, authTag, cipherText } = this.decodeAEADPayload(encrypted);
|
||||
const decipher = createDecipheriv(ALGORITHM, this.key, iv);
|
||||
decipher.setAuthTag(authTag);
|
||||
const decrypted = Buffer.concat([
|
||||
decipher.update(cipherText),
|
||||
decipher.final(),
|
||||
]);
|
||||
return decrypted.toString('utf8');
|
||||
} catch (e: unknown) {
|
||||
throw new UnableToDecrypt((e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
private decodeAEADPayload(encodedPayload: string): AEADPayload<Buffer> {
|
||||
const payload = Buffer.from(encodedPayload, 'base64');
|
||||
|
||||
let deserializedPkg: Record<string, unknown>;
|
||||
try {
|
||||
deserializedPkg = JSON.parse(payload.toString());
|
||||
} catch {
|
||||
throw new Error('The decoded AEAD payload is not a valid JSON string.');
|
||||
}
|
||||
|
||||
for (const field of ['iv', 'authTag', 'cipherText']) {
|
||||
if (!Object.prototype.hasOwnProperty.call(deserializedPkg, field)) {
|
||||
throw new Error(`The AEAD payload is missing the ${field} field.`);
|
||||
}
|
||||
}
|
||||
|
||||
const iv = Buffer.from(deserializedPkg.iv as string, 'base64');
|
||||
if (iv.length !== IV_LENGTH) {
|
||||
throw new Error(
|
||||
`The decoded IV is not the correct length. Expected ${IV_LENGTH} bytes, got ${iv.length} bytes.`,
|
||||
);
|
||||
}
|
||||
|
||||
const authTag = Buffer.from(deserializedPkg.authTag as string, 'base64');
|
||||
if (authTag.length !== AUTH_TAG_LENGTH) {
|
||||
throw new Error(
|
||||
`The decoded auth tag is not the correct length. Expected ${AUTH_TAG_LENGTH} bytes, got ${authTag.length} bytes.`,
|
||||
);
|
||||
}
|
||||
|
||||
const cipherText = Buffer.from(
|
||||
deserializedPkg.cipherText as string,
|
||||
'base64',
|
||||
);
|
||||
|
||||
return { iv, authTag, cipherText };
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,9 @@ export class FileTaskProcessor extends WorkerHost implements OnModuleDestroy {
|
||||
case QueueJob.IMPORT_TASK:
|
||||
await this.fileTaskService.processZIpImport(job.data.fileTaskId);
|
||||
break;
|
||||
case QueueJob.CONFLUENCE_API_IMPORT:
|
||||
await this.processConfluenceApiImport(job.data.fileTaskId);
|
||||
break;
|
||||
case QueueJob.PDF_EXPORT_TASK:
|
||||
await this.processExportTask(job.data.fileTaskId);
|
||||
break;
|
||||
@@ -49,6 +52,19 @@ export class FileTaskProcessor extends WorkerHost implements OnModuleDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
private getConfluenceApiImportService() {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const mod = require('./../../../ee/confluence-api-import/confluence-api-import.service');
|
||||
return this.moduleRef.get(mod.ConfluenceApiImportService, {
|
||||
strict: false,
|
||||
});
|
||||
}
|
||||
|
||||
private async processConfluenceApiImport(fileTaskId: string): Promise<void> {
|
||||
const service = this.getConfluenceApiImportService();
|
||||
await service.processImport(fileTaskId);
|
||||
}
|
||||
|
||||
private async processExportTask(fileTaskId: string): Promise<void> {
|
||||
const pdfExportService = this.getPdfExportService();
|
||||
await pdfExportService.generateAndStorePdf(fileTaskId);
|
||||
@@ -74,6 +90,8 @@ export class FileTaskProcessor extends WorkerHost implements OnModuleDestroy {
|
||||
await this.handleFailedImportJob(job);
|
||||
} else if (job.name === QueueJob.PDF_EXPORT_TASK) {
|
||||
await this.handleFailedExportJob(job);
|
||||
} else if (job.name === QueueJob.CONFLUENCE_API_IMPORT) {
|
||||
await this.handleFailedExportJob(job);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { nodeIdFromConfluenceAnchor } from './confluence-anchor-id';
|
||||
|
||||
describe('nodeIdFromConfluenceAnchor', () => {
|
||||
it('is deterministic for the same (pageId, anchorName)', () => {
|
||||
const a = nodeIdFromConfluenceAnchor('page-1', 'My Anchor');
|
||||
const b = nodeIdFromConfluenceAnchor('page-1', 'My Anchor');
|
||||
expect(a).toBe(b);
|
||||
});
|
||||
|
||||
it('returns different ids when the anchor name differs', () => {
|
||||
const a = nodeIdFromConfluenceAnchor('page-1', 'one');
|
||||
const b = nodeIdFromConfluenceAnchor('page-1', 'two');
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
|
||||
it('returns different ids when the pageId differs', () => {
|
||||
const a = nodeIdFromConfluenceAnchor('page-1', 'same');
|
||||
const b = nodeIdFromConfluenceAnchor('page-2', 'same');
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
|
||||
it('returns exactly 12 lowercase a-z characters', () => {
|
||||
const id = nodeIdFromConfluenceAnchor('page-xyz', 'Section · 1');
|
||||
expect(id).toHaveLength(12);
|
||||
expect(id).toMatch(/^[a-z]{12}$/);
|
||||
});
|
||||
|
||||
it('treats an empty anchor name as a valid input', () => {
|
||||
const id = nodeIdFromConfluenceAnchor('page-1', '');
|
||||
expect(id).toMatch(/^[a-z]{12}$/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
// Matches the alphabet used by generateNodeId() in
|
||||
// packages/editor-ext/src/lib/utils.ts (customAlphabet from nanoid).
|
||||
const ALPHABET = 'abcdefghijklmnopqrstuvwxyz';
|
||||
const NODE_ID_LENGTH = 12;
|
||||
|
||||
/**
|
||||
* Returns a deterministic 12-character nodeId for a Confluence anchor.
|
||||
* The same (pageId, anchorName) pair always produces the same result, so
|
||||
* cross-page anchor links resolve to the anchor target without a
|
||||
* precomputed map. The output uses the same alphabet and length as
|
||||
* generateNodeId() from @docmost/editor-ext, so it is interchangeable
|
||||
* with editor-generated nodeIds.
|
||||
*/
|
||||
export function nodeIdFromConfluenceAnchor(
|
||||
pageId: string,
|
||||
anchorName: string,
|
||||
): string {
|
||||
const digest = createHash('sha256')
|
||||
.update(`${pageId}#${anchorName}`)
|
||||
.digest();
|
||||
let out = '';
|
||||
for (let i = 0; i < NODE_ID_LENGTH; i++) {
|
||||
out += ALPHABET[digest[i] % ALPHABET.length];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { parseConfluenceEmojiId } from './confluence-emoji';
|
||||
|
||||
describe('parseConfluenceEmojiId', () => {
|
||||
it('parses a single code point id', () => {
|
||||
expect(parseConfluenceEmojiId('1f600')).toBe('😀');
|
||||
expect(parseConfluenceEmojiId('1F600')).toBe('😀');
|
||||
});
|
||||
|
||||
it('parses a country flag (two regional indicator code points)', () => {
|
||||
expect(parseConfluenceEmojiId('1f1f3-1f1ec')).toBe('🇳🇬');
|
||||
expect(parseConfluenceEmojiId('1f1fa-1f1f8')).toBe('🇺🇸');
|
||||
});
|
||||
|
||||
it('parses a ZWJ sequence (three code points)', () => {
|
||||
expect(parseConfluenceEmojiId('1f468-200d-1f4bb')).toBe('👨💻');
|
||||
});
|
||||
|
||||
it('parses a five-component family ZWJ sequence', () => {
|
||||
// 👨👩👧👦 = man, ZWJ, woman, ZWJ, girl, ZWJ, boy
|
||||
expect(parseConfluenceEmojiId('1f468-200d-1f469-200d-1f467-200d-1f466')).toBe(
|
||||
'👨👩👧👦',
|
||||
);
|
||||
});
|
||||
|
||||
it('returns null for missing input', () => {
|
||||
expect(parseConfluenceEmojiId(undefined)).toBeNull();
|
||||
expect(parseConfluenceEmojiId(null)).toBeNull();
|
||||
expect(parseConfluenceEmojiId('')).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when any segment is not pure hex', () => {
|
||||
expect(parseConfluenceEmojiId('1f600-NG')).toBeNull();
|
||||
expect(parseConfluenceEmojiId('not-hex')).toBeNull();
|
||||
expect(parseConfluenceEmojiId('1f600--1f1ec')).toBeNull();
|
||||
expect(parseConfluenceEmojiId('1f600 1f1ec')).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when a segment parses to a non-positive value', () => {
|
||||
expect(parseConfluenceEmojiId('0')).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for code points outside the valid Unicode range', () => {
|
||||
// 0x110000 is one past the highest valid code point.
|
||||
expect(parseConfluenceEmojiId('110000')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Parse a Confluence emoji id (hex code points joined by hyphens) into a
|
||||
* Unicode string. Confluence emits ids in both single- and multi-code-point
|
||||
* forms:
|
||||
*
|
||||
* "1f600" → "😀"
|
||||
* "1f1f3-1f1ec" → "🇳🇬" (flag: Nigeria)
|
||||
* "1f468-200d-1f4bb" → "👨💻" (man technologist, ZWJ sequence)
|
||||
*
|
||||
* Returns null when the input is missing, empty, or doesn't parse cleanly as
|
||||
* hyphen-separated hex code points.
|
||||
*/
|
||||
export function parseConfluenceEmojiId(
|
||||
raw: string | undefined | null,
|
||||
): string | null {
|
||||
if (!raw) return null;
|
||||
const parts = raw.split('-');
|
||||
if (parts.length === 0) return null;
|
||||
if (!parts.every((p) => /^[0-9a-fA-F]+$/.test(p))) return null;
|
||||
const codePoints = parts.map((p) => parseInt(p, 16));
|
||||
if (codePoints.some((cp) => !Number.isFinite(cp) || cp <= 0)) return null;
|
||||
try {
|
||||
return String.fromCodePoint(...codePoints);
|
||||
} catch {
|
||||
// Out-of-range code points throw RangeError on String.fromCodePoint.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { load } from 'cheerio';
|
||||
import { applyConfluenceMarginLeftIndent } from './confluence-indent';
|
||||
|
||||
function run(html: string): string {
|
||||
const $ = load(html);
|
||||
applyConfluenceMarginLeftIndent($, $.root());
|
||||
// cheerio's html() includes <html><body>; return the body's inner HTML so
|
||||
// tests can assert on the meaningful portion.
|
||||
return $('body').html() ?? $.html();
|
||||
}
|
||||
|
||||
describe('applyConfluenceMarginLeftIndent', () => {
|
||||
describe('Confluence Cloud (30 px per level, max 6)', () => {
|
||||
it('maps 30/60/90/120/150/180 px to data-indent 1..6', () => {
|
||||
const html =
|
||||
'<p style="margin-left: 30.0px;">L1</p>' +
|
||||
'<p style="margin-left: 60.0px;">L2</p>' +
|
||||
'<p style="margin-left: 90.0px;">L3</p>' +
|
||||
'<p style="margin-left: 120.0px;">L4</p>' +
|
||||
'<p style="margin-left: 150.0px;">L5</p>' +
|
||||
'<p style="margin-left: 180.0px;">L6</p>';
|
||||
const out = run(html);
|
||||
expect(out).toContain('<p data-indent="1">L1</p>');
|
||||
expect(out).toContain('<p data-indent="2">L2</p>');
|
||||
expect(out).toContain('<p data-indent="3">L3</p>');
|
||||
expect(out).toContain('<p data-indent="4">L4</p>');
|
||||
expect(out).toContain('<p data-indent="5">L5</p>');
|
||||
expect(out).toContain('<p data-indent="6">L6</p>');
|
||||
expect(out).not.toContain('margin-left');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Confluence Data Center (40 px per level, no upper bound)', () => {
|
||||
it('maps 40/80/120/160/200/240 px to data-indent 1..6', () => {
|
||||
const html =
|
||||
'<p style="margin-left: 40.0px;">one</p>' +
|
||||
'<p style="margin-left: 80.0px;">two</p>' +
|
||||
'<p style="margin-left: 120.0px;">three</p>' +
|
||||
'<p style="margin-left: 160.0px;">four</p>' +
|
||||
'<p style="margin-left: 200.0px;">five</p>' +
|
||||
'<p style="margin-left: 240.0px;">six</p>';
|
||||
const out = run(html);
|
||||
expect(out).toContain('<p data-indent="1">one</p>');
|
||||
expect(out).toContain('<p data-indent="2">two</p>');
|
||||
expect(out).toContain('<p data-indent="3">three</p>');
|
||||
expect(out).toContain('<p data-indent="4">four</p>');
|
||||
expect(out).toContain('<p data-indent="5">five</p>');
|
||||
expect(out).toContain('<p data-indent="6">six</p>');
|
||||
expect(out).not.toContain('margin-left');
|
||||
});
|
||||
|
||||
it('clamps DC levels above 8 down to 8', () => {
|
||||
const html =
|
||||
'<p style="margin-left: 320.0px;">L8</p>' +
|
||||
'<p style="margin-left: 360.0px;">L9</p>' +
|
||||
'<p style="margin-left: 600.0px;">L15</p>';
|
||||
const out = run(html);
|
||||
expect(out).toContain('<p data-indent="8">L8</p>');
|
||||
expect(out).toContain('<p data-indent="8">L9</p>');
|
||||
expect(out).toContain('<p data-indent="8">L15</p>');
|
||||
});
|
||||
});
|
||||
|
||||
describe('headings', () => {
|
||||
it('handles indent on h1-h6 the same way as paragraphs', () => {
|
||||
const html =
|
||||
'<h1 style="margin-left: 30px;">a</h1>' +
|
||||
'<h6 style="margin-left: 90px;">b</h6>';
|
||||
const out = run(html);
|
||||
expect(out).toContain('<h1 data-indent="1">a</h1>');
|
||||
expect(out).toContain('<h6 data-indent="3">b</h6>');
|
||||
});
|
||||
});
|
||||
|
||||
describe('style attribute handling', () => {
|
||||
it('strips margin-left but preserves other inline styles', () => {
|
||||
const html =
|
||||
'<p style="color: red; margin-left: 30px; font-weight: bold;">x</p>';
|
||||
const out = run(html);
|
||||
expect(out).toMatch(/<p style="color: red;\s+font-weight: bold;?" data-indent="1">x<\/p>/);
|
||||
expect(out).not.toContain('margin-left');
|
||||
});
|
||||
|
||||
it('removes the style attribute entirely when only margin-left was set', () => {
|
||||
// Two values so GCD detection sees a real unit (60 px) instead of
|
||||
// collapsing to the lone value. The point of this test is the style
|
||||
// attribute being stripped, not the level number.
|
||||
const html =
|
||||
'<p style="margin-left: 60px;">x</p>' +
|
||||
'<p style="margin-left: 120px;">y</p>';
|
||||
const out = run(html);
|
||||
expect(out).toContain('<p data-indent="1">x</p>');
|
||||
expect(out).toContain('<p data-indent="2">y</p>');
|
||||
expect(out).not.toContain('style=');
|
||||
});
|
||||
});
|
||||
|
||||
describe('scope and edge cases', () => {
|
||||
it('leaves elements without margin-left untouched', () => {
|
||||
const html = '<p>plain</p><h2>heading</h2>';
|
||||
const out = run(html);
|
||||
expect(out).toBe('<p>plain</p><h2>heading</h2>');
|
||||
});
|
||||
|
||||
it('does not touch divs, spans, or list items', () => {
|
||||
const html =
|
||||
'<div style="margin-left: 30px;">div</div>' +
|
||||
'<li style="margin-left: 30px;">li</li>' +
|
||||
'<span style="margin-left: 30px;">span</span>';
|
||||
const out = run(html);
|
||||
expect(out).not.toContain('data-indent');
|
||||
expect(out).toContain('margin-left: 30px');
|
||||
});
|
||||
|
||||
it('ignores zero, negative, and unparseable margin-left values', () => {
|
||||
const html =
|
||||
'<p style="margin-left: 0px;">zero</p>' +
|
||||
'<p style="margin-left: -30px;">neg</p>' +
|
||||
'<p style="margin-left: auto;">auto</p>';
|
||||
const out = run(html);
|
||||
expect(out).not.toContain('data-indent');
|
||||
});
|
||||
|
||||
it('honors an explicit pxPerLevel override', () => {
|
||||
// Mixed Cloud-and-DC nominal values forced to 40 px/level interpretation.
|
||||
const $ = load(
|
||||
'<p style="margin-left: 40px;">a</p>' +
|
||||
'<p style="margin-left: 80px;">b</p>',
|
||||
);
|
||||
applyConfluenceMarginLeftIndent($, $.root(), { pxPerLevel: 40 });
|
||||
const out = $('body').html() ?? '';
|
||||
expect(out).toContain('<p data-indent="1">a</p>');
|
||||
expect(out).toContain('<p data-indent="2">b</p>');
|
||||
});
|
||||
|
||||
it('returns a no-op when no indented elements are present', () => {
|
||||
const html = '<p>hi</p>';
|
||||
const out = run(html);
|
||||
expect(out).toBe('<p>hi</p>');
|
||||
});
|
||||
|
||||
it('handles a single ambiguous value by clamping to level 1', () => {
|
||||
// GCD of a single value is the value itself, so 120 / 120 = 1.
|
||||
const html = '<p style="margin-left: 120px;">only</p>';
|
||||
const out = run(html);
|
||||
expect(out).toContain('<p data-indent="1">only</p>');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Cheerio, CheerioAPI } from 'cheerio';
|
||||
|
||||
// Maximum indent level supported by the Indent editor extension (see
|
||||
// packages/editor-ext/src/lib/indent.ts). Values above this clamp down.
|
||||
const MAX_INDENT_LEVEL = 8;
|
||||
const MARGIN_LEFT_RE = /margin-left\s*:\s*(-?\d*\.?\d+)\s*px/i;
|
||||
const MARGIN_LEFT_STRIP_RE = /margin-left\s*:\s*-?\d*\.?\d+\s*px\s*;?/i;
|
||||
|
||||
/**
|
||||
* Confluence encodes paragraph indent as inline `style="margin-left: Npx"`.
|
||||
* The per-level pixel value differs by edition: Cloud uses 30 (max 6 levels),
|
||||
* Data Center uses 40 (no upper limit). The HTML-export ZIP path has no
|
||||
* edition information available, so we auto-detect the per-level unit from
|
||||
* the GCD of all margin-left values in the document. The API converter can
|
||||
* pass `pxPerLevel` explicitly when the edition is known.
|
||||
*
|
||||
* Levels are written to `data-indent` for the TipTap Indent extension to
|
||||
* pick up; the margin-left style is stripped from the element so the
|
||||
* normalized indent doesn't double up with the editor's own indent padding.
|
||||
*/
|
||||
export function applyConfluenceMarginLeftIndent(
|
||||
$: CheerioAPI,
|
||||
$root: Cheerio<any>,
|
||||
options?: { pxPerLevel?: number },
|
||||
): void {
|
||||
const $els = $root.find('p, h1, h2, h3, h4, h5, h6');
|
||||
|
||||
const values: number[] = [];
|
||||
$els.each((_, el) => {
|
||||
const style = $(el).attr('style');
|
||||
if (!style) return;
|
||||
const match = MARGIN_LEFT_RE.exec(style);
|
||||
if (!match) return;
|
||||
const px = parseFloat(match[1]);
|
||||
if (Number.isFinite(px) && px > 0) values.push(px);
|
||||
});
|
||||
if (values.length === 0) return;
|
||||
|
||||
const unit = options?.pxPerLevel ?? detectIndentUnit(values);
|
||||
if (!unit || unit <= 0) return;
|
||||
|
||||
$els.each((_, el) => {
|
||||
const $el = $(el);
|
||||
const style = $el.attr('style');
|
||||
if (!style) return;
|
||||
const match = MARGIN_LEFT_RE.exec(style);
|
||||
if (!match) return;
|
||||
const px = parseFloat(match[1]);
|
||||
if (!Number.isFinite(px) || px <= 0) return;
|
||||
const level = Math.min(
|
||||
MAX_INDENT_LEVEL,
|
||||
Math.max(1, Math.round(px / unit)),
|
||||
);
|
||||
$el.attr('data-indent', String(level));
|
||||
const remaining = style.replace(MARGIN_LEFT_STRIP_RE, '').trim();
|
||||
if (remaining) {
|
||||
$el.attr('style', remaining);
|
||||
} else {
|
||||
$el.removeAttr('style');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function detectIndentUnit(values: number[]): number {
|
||||
// Confluence emits floats like "30.0"; round to ints for a clean GCD.
|
||||
const ints = values.map((v) => Math.round(v)).filter((v) => v > 0);
|
||||
if (ints.length === 0) return 0;
|
||||
return ints.reduce((a, b) => gcd(a, b));
|
||||
}
|
||||
|
||||
function gcd(a: number, b: number): number {
|
||||
while (b !== 0) {
|
||||
[a, b] = [b, a % b];
|
||||
}
|
||||
return a;
|
||||
}
|
||||
@@ -11,6 +11,7 @@ export enum FileImportSource {
|
||||
Generic = 'generic',
|
||||
Notion = 'notion',
|
||||
Confluence = 'confluence',
|
||||
ConfluenceApi = 'confluence-api'
|
||||
}
|
||||
|
||||
export enum FileTaskStatus {
|
||||
|
||||
@@ -97,14 +97,21 @@ export function xwikiFormatter($: CheerioAPI, $root: Cheerio<any>) {
|
||||
}
|
||||
}
|
||||
|
||||
import { applyConfluenceMarginLeftIndent } from './confluence-indent';
|
||||
export { applyConfluenceMarginLeftIndent };
|
||||
|
||||
export function defaultHtmlFormatter($: CheerioAPI, $root: Cheerio<any>) {
|
||||
normalizeTableColumnWidths($, $root);
|
||||
applyConfluenceMarginLeftIndent($, $root);
|
||||
|
||||
// Auto-embed only when the <a> is the sole meaningful child of its parent
|
||||
// block. A link mixed with surrounding text stays an inline link.
|
||||
$root.find('a[href]').each((_, el) => {
|
||||
const $el = $(el);
|
||||
const url = $el.attr('href')!;
|
||||
const { provider } = getEmbedUrlAndProvider(url);
|
||||
if (provider === 'iframe') return;
|
||||
if (!isSoleMeaningfulChild($el, el)) return;
|
||||
|
||||
const embed = `<div data-type=\"embed\" data-src=\"${url}\" data-provider=\"${provider}\" data-align=\"center\" data-width=\"640\" data-height=\"480\"></div>`;
|
||||
$el.replaceWith(embed);
|
||||
@@ -120,6 +127,21 @@ export function defaultHtmlFormatter($: CheerioAPI, $root: Cheerio<any>) {
|
||||
});
|
||||
}
|
||||
|
||||
function isSoleMeaningfulChild(
|
||||
$el: Cheerio<any>,
|
||||
rawEl: any,
|
||||
): boolean {
|
||||
const $parent = $el.parent();
|
||||
if ($parent.length === 0) return true;
|
||||
const others = $parent.contents().toArray().filter((n: any) => {
|
||||
if (n === rawEl) return false;
|
||||
if (n.type === 'text') return (n.data ?? '').trim() !== '';
|
||||
if (n.type === 'tag' && n.name === 'br') return false;
|
||||
return true;
|
||||
});
|
||||
return others.length === 0;
|
||||
}
|
||||
|
||||
const COLUMN_LAYOUTS = [
|
||||
'',
|
||||
'',
|
||||
|
||||
@@ -30,6 +30,7 @@ export enum QueueJob {
|
||||
FIRST_PAYMENT_EMAIL = 'first-payment-email',
|
||||
|
||||
IMPORT_TASK = 'import-task',
|
||||
CONFLUENCE_API_IMPORT = 'confluence-api-import-task',
|
||||
EXPORT_TASK = 'export-task',
|
||||
|
||||
SEARCH_INDEX_PAGE = 'search-index-page',
|
||||
|
||||
@@ -31,5 +31,6 @@ export * from "./lib/recreate-transform";
|
||||
export * from "./lib/columns";
|
||||
export * from "./lib/status";
|
||||
export * from "./lib/pdf";
|
||||
export * from "./lib/page-break";
|
||||
export * from "./lib/resizable-nodeview";
|
||||
|
||||
|
||||
@@ -162,6 +162,28 @@ export const Callout = Node.create<CalloutOptions>({
|
||||
return false;
|
||||
}
|
||||
|
||||
// Empty callout: delete the whole node so Backspace inside it isn't
|
||||
// a no-op (isolating: true blocks the default join with the block
|
||||
// above).
|
||||
const calloutDepth = $from.depth - 1;
|
||||
if (calloutDepth >= 0) {
|
||||
const calloutNode = $from.node(calloutDepth);
|
||||
if (
|
||||
calloutNode.type === this.type &&
|
||||
calloutNode.childCount === 1 &&
|
||||
calloutNode.firstChild?.content.size === 0
|
||||
) {
|
||||
const calloutPos = $from.before(calloutDepth);
|
||||
const { tr } = state;
|
||||
tr.delete(calloutPos, calloutPos + calloutNode.nodeSize);
|
||||
tr.setSelection(
|
||||
TextSelection.near(tr.doc.resolve(calloutPos), -1),
|
||||
);
|
||||
view.dispatch(tr);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
const previousPosition = $from.before($from.depth) - 1;
|
||||
|
||||
// If nothing above to join with
|
||||
@@ -207,6 +229,56 @@ export const Callout = Node.create<CalloutOptions>({
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
// Exit the callout into a fresh paragraph below when the cursor sits
|
||||
// in an empty trailing child. An empty callout (single empty
|
||||
// paragraph) exits on the first Enter and keeps the empty callout
|
||||
// intact; a callout with content needs the double-Enter pattern
|
||||
// (first Enter splits, second Enter on the new trailing empty exits
|
||||
// and removes that trailing paragraph).
|
||||
Enter: ({ editor }) => {
|
||||
const { state, view } = editor;
|
||||
const { selection } = state;
|
||||
if (!selection.empty) return false;
|
||||
|
||||
const { $from } = selection;
|
||||
const calloutDepth = $from.depth - 1;
|
||||
if (calloutDepth < 0) return false;
|
||||
|
||||
const calloutNode = $from.node(calloutDepth);
|
||||
if (calloutNode.type !== this.type) return false;
|
||||
if ($from.parent.content.size !== 0) return false;
|
||||
if ($from.index(calloutDepth) !== calloutNode.childCount - 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const paragraphType = state.schema.nodes.paragraph;
|
||||
const containerDepth = calloutDepth - 1;
|
||||
const container = $from.node(containerDepth);
|
||||
const indexAfter = $from.indexAfter(containerDepth);
|
||||
if (
|
||||
!container.canReplaceWith(indexAfter, indexAfter, paragraphType)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const calloutEnd = $from.after(calloutDepth);
|
||||
const paragraph = paragraphType.create();
|
||||
const { tr } = state;
|
||||
|
||||
if (calloutNode.childCount === 1) {
|
||||
tr.insert(calloutEnd, paragraph);
|
||||
tr.setSelection(TextSelection.create(tr.doc, calloutEnd + 1));
|
||||
} else {
|
||||
tr.delete($from.before(), $from.after());
|
||||
const insertPos = tr.mapping.map(calloutEnd);
|
||||
tr.insert(insertPos, paragraph);
|
||||
tr.setSelection(TextSelection.create(tr.doc, insertPos + 1));
|
||||
}
|
||||
|
||||
view.dispatch(tr);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { CodeBlockOptions } from '@tiptap/extension-code-block';
|
||||
import CodeBlock from '@tiptap/extension-code-block';
|
||||
import { Plugin, Selection, TextSelection } from '@tiptap/pm/state';
|
||||
import { GapCursor } from '@tiptap/pm/gapcursor';
|
||||
|
||||
import { LowlightPlugin } from './lowlight-plugin.js';
|
||||
import { ReactNodeViewRenderer } from '@tiptap/react';
|
||||
@@ -19,7 +21,11 @@ const TAB_CHAR = '\u00A0\u00A0';
|
||||
* @see https://tiptap.dev/api/nodes/code-block-lowlight
|
||||
*/
|
||||
export const CustomCodeBlock = CodeBlock.extend<CodeBlockLowlightOptions>({
|
||||
// Run ahead of Gapcursor (100) so the mermaid arrow-into-source plugin
|
||||
// can intercept before gapcursor takes over.
|
||||
priority: 101,
|
||||
selectable: true,
|
||||
isolating: true,
|
||||
|
||||
addOptions() {
|
||||
return {
|
||||
@@ -35,8 +41,86 @@ export const CustomCodeBlock = CodeBlock.extend<CodeBlockLowlightOptions>({
|
||||
},
|
||||
|
||||
addKeyboardShortcuts() {
|
||||
const isMermaid = (node: any) =>
|
||||
node?.type === this.type && node.attrs.language === 'mermaid';
|
||||
|
||||
return {
|
||||
...this.parent?.(),
|
||||
// Stop at the gap (or enter mermaid source) instead of jumping
|
||||
// straight into the next block, so the user can place a cursor
|
||||
// between two adjacent isolating blocks.
|
||||
ArrowDown: ({ editor }) => {
|
||||
const { state } = editor;
|
||||
const { selection, doc } = state;
|
||||
const { $from, empty } = selection;
|
||||
|
||||
if (!empty || $from.parent.type !== this.type) return false;
|
||||
if ($from.parentOffset !== $from.parent.nodeSize - 2) return false;
|
||||
|
||||
const after = $from.after();
|
||||
if (after >= doc.content.size) {
|
||||
return editor.commands.exitCode();
|
||||
}
|
||||
|
||||
const $after = doc.resolve(after);
|
||||
const nodeAfter = $after.nodeAfter;
|
||||
|
||||
if (isMermaid(nodeAfter)) {
|
||||
return editor.commands.command(({ tr }) => {
|
||||
tr.setSelection(TextSelection.create(tr.doc, after + 1));
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
nodeAfter?.type.spec.isolating &&
|
||||
!nodeAfter.type.spec.atom
|
||||
) {
|
||||
return editor.commands.command(({ tr }) => {
|
||||
tr.setSelection(new GapCursor(tr.doc.resolve(after)));
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
return editor.commands.command(({ tr }) => {
|
||||
tr.setSelection(Selection.near(tr.doc.resolve(after)));
|
||||
return true;
|
||||
});
|
||||
},
|
||||
// Mirror of ArrowDown; upstream has no ArrowUp handler.
|
||||
ArrowUp: ({ editor }) => {
|
||||
const { state } = editor;
|
||||
const { selection, doc } = state;
|
||||
const { $from, empty } = selection;
|
||||
|
||||
if (!empty || $from.parent.type !== this.type) return false;
|
||||
if ($from.parentOffset !== 0) return false;
|
||||
|
||||
const before = $from.before();
|
||||
if (before <= 0) return false;
|
||||
|
||||
const $before = doc.resolve(before);
|
||||
const nodeBefore = $before.nodeBefore;
|
||||
|
||||
if (isMermaid(nodeBefore)) {
|
||||
return editor.commands.command(({ tr }) => {
|
||||
tr.setSelection(TextSelection.create(tr.doc, before - 1));
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
nodeBefore?.type.spec.isolating &&
|
||||
!nodeBefore.type.spec.atom
|
||||
) {
|
||||
return editor.commands.command(({ tr }) => {
|
||||
tr.setSelection(new GapCursor(tr.doc.resolve(before)));
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
'Mod-a': () => {
|
||||
if (this.editor.isActive('codeBlock')) {
|
||||
const { state } = this.editor;
|
||||
@@ -84,6 +168,7 @@ export const CustomCodeBlock = CodeBlock.extend<CodeBlockLowlightOptions>({
|
||||
},
|
||||
|
||||
addProseMirrorPlugins() {
|
||||
const codeBlockType = this.type;
|
||||
return [
|
||||
...(this.parent?.() || []),
|
||||
LowlightPlugin({
|
||||
@@ -91,6 +176,60 @@ export const CustomCodeBlock = CodeBlock.extend<CodeBlockLowlightOptions>({
|
||||
lowlight: this.options.lowlight,
|
||||
defaultLanguage: this.options.defaultLanguage,
|
||||
}),
|
||||
// Mermaid hides its <pre> when unselected, so the browser's native
|
||||
// vertical caret movement skips past it. Land the cursor inside the
|
||||
// source explicitly.
|
||||
new Plugin({
|
||||
props: {
|
||||
handleKeyDown: (view, event) => {
|
||||
if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') {
|
||||
return false;
|
||||
}
|
||||
const { state } = view;
|
||||
const { selection } = state;
|
||||
if (
|
||||
!selection.empty ||
|
||||
!(selection instanceof TextSelection)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const { $from } = selection;
|
||||
if ($from.depth === 0 || $from.parent.type === codeBlockType) {
|
||||
return false;
|
||||
}
|
||||
const dir = event.key === 'ArrowUp' ? 'up' : 'down';
|
||||
if (!view.endOfTextblock(dir)) return false;
|
||||
|
||||
const isMermaid = (node: any) =>
|
||||
node?.type === codeBlockType && node.attrs.language === 'mermaid';
|
||||
|
||||
if (event.key === 'ArrowUp') {
|
||||
if ($from.parentOffset !== 0) return false;
|
||||
const beforePos = $from.before();
|
||||
const prev = state.doc.resolve(beforePos).nodeBefore;
|
||||
if (!isMermaid(prev)) return false;
|
||||
const endPos = beforePos - 1;
|
||||
view.dispatch(
|
||||
state.tr.setSelection(
|
||||
TextSelection.create(state.doc, endPos),
|
||||
),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
if ($from.parentOffset !== $from.parent.nodeSize - 2) return false;
|
||||
const afterPos = $from.after();
|
||||
const next = state.doc.resolve(afterPos).nodeAfter;
|
||||
if (!isMermaid(next)) return false;
|
||||
const startPos = afterPos + 1;
|
||||
view.dispatch(
|
||||
state.tr.setSelection(
|
||||
TextSelection.create(state.doc, startPos),
|
||||
),
|
||||
);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./page-break";
|
||||
@@ -0,0 +1,60 @@
|
||||
import { mergeAttributes, Node } from "@tiptap/core";
|
||||
|
||||
export interface PageBreakOptions {
|
||||
HTMLAttributes: Record<string, any>;
|
||||
}
|
||||
|
||||
declare module "@tiptap/core" {
|
||||
interface Commands<ReturnType> {
|
||||
pageBreak: {
|
||||
setPageBreak: () => ReturnType;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const PageBreak = Node.create<PageBreakOptions>({
|
||||
name: "pageBreak",
|
||||
|
||||
group: "block",
|
||||
|
||||
atom: true,
|
||||
|
||||
selectable: true,
|
||||
|
||||
addOptions() {
|
||||
return {
|
||||
HTMLAttributes: {},
|
||||
};
|
||||
},
|
||||
|
||||
parseHTML() {
|
||||
return [
|
||||
{
|
||||
tag: `div[data-type="${this.name}"]`,
|
||||
},
|
||||
];
|
||||
},
|
||||
|
||||
renderHTML({ HTMLAttributes }) {
|
||||
return [
|
||||
"div",
|
||||
mergeAttributes(
|
||||
{ "data-type": this.name, class: "page-break" },
|
||||
this.options.HTMLAttributes,
|
||||
HTMLAttributes,
|
||||
),
|
||||
];
|
||||
},
|
||||
|
||||
addCommands() {
|
||||
return {
|
||||
setPageBreak:
|
||||
() =>
|
||||
({ chain }) =>
|
||||
chain()
|
||||
.insertContent({ type: this.name })
|
||||
.focus()
|
||||
.run(),
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -338,6 +338,15 @@ export const isRowGripSelected = ({
|
||||
return !!gripRow;
|
||||
};
|
||||
|
||||
// TipTap's `editor.view` proxy throws if accessed before mount or after destroy.
|
||||
// Guard floating-menu callbacks (getReferencedVirtualElement, shouldShow) with
|
||||
// this before touching `editor.view.nodeDOM(...)`.
|
||||
export function isEditorReady(
|
||||
editor: Editor | null | undefined,
|
||||
): editor is Editor {
|
||||
return !!editor && editor.isInitialized;
|
||||
}
|
||||
|
||||
export function isTextSelected(editor: Editor) {
|
||||
const {
|
||||
state: {
|
||||
|
||||
Generated
+15
-15
@@ -637,14 +637,14 @@ importers:
|
||||
specifier: ^9.0.3
|
||||
version: 9.0.3
|
||||
kysely:
|
||||
specifier: ^0.29.0
|
||||
version: 0.29.0
|
||||
specifier: ^0.28.17
|
||||
version: 0.28.17
|
||||
kysely-migration-cli:
|
||||
specifier: ^0.4.2
|
||||
version: 0.4.2
|
||||
kysely-postgres-js:
|
||||
specifier: ^3.0.0
|
||||
version: 3.0.0(kysely@0.29.0)(postgres@3.4.8)
|
||||
version: 3.0.0(kysely@0.28.17)(postgres@3.4.8)
|
||||
ldapts:
|
||||
specifier: ^8.1.7
|
||||
version: 8.1.7
|
||||
@@ -668,7 +668,7 @@ importers:
|
||||
version: 6.2.0(@nestjs/common@11.1.19(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.19)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||
nestjs-kysely:
|
||||
specifier: ^3.1.2
|
||||
version: 3.1.2(@nestjs/common@11.1.19(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.19)(kysely@0.29.0)(reflect-metadata@0.2.2)
|
||||
version: 3.1.2(@nestjs/common@11.1.19(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.19)(kysely@0.28.17)(reflect-metadata@0.2.2)
|
||||
nestjs-pino:
|
||||
specifier: ^4.6.1
|
||||
version: 4.6.1(@nestjs/common@11.1.19(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(pino-http@11.0.0)(pino@10.1.0)(rxjs@7.8.2)
|
||||
@@ -819,7 +819,7 @@ importers:
|
||||
version: 30.3.0(@types/node@25.5.0)(babel-plugin-macros@3.1.0)(ts-node@10.9.2(@swc/core@1.5.25(@swc/helpers@0.5.5))(@types/node@25.5.0)(typescript@5.9.3))
|
||||
kysely-codegen:
|
||||
specifier: ^0.20.0
|
||||
version: 0.20.0(kysely@0.29.0)(pg@8.16.3)(typescript@5.9.3)
|
||||
version: 0.20.0(kysely@0.28.17)(pg@8.16.3)(typescript@5.9.3)
|
||||
prettier:
|
||||
specifier: ^3.8.1
|
||||
version: 3.8.1
|
||||
@@ -7815,9 +7815,9 @@ packages:
|
||||
postgres:
|
||||
optional: true
|
||||
|
||||
kysely@0.29.0:
|
||||
resolution: {integrity: sha512-LrQfPUeTW7MXbMvT62moEMnpMTuj9TO3lqjCeLKjM975PJ4Alrl/43f2tlDX7xOsNptKgH4LSNGwIbXwEkLg4g==}
|
||||
engines: {node: '>=22.0.0'}
|
||||
kysely@0.28.17:
|
||||
resolution: {integrity: sha512-nbD8lB9EB3wNdMhOCdx5Li8DxnLbvKByylRLcJ1h+4SkrowVeECAyZlyiKMThF7xFdRz0jSQ2MoJr+wXux2y0Q==}
|
||||
engines: {node: '>=20.0.0'}
|
||||
|
||||
langium@3.3.1:
|
||||
resolution: {integrity: sha512-QJv/h939gDpvT+9SiLVlY7tZC3xB2qK57v0J04Sh9wpMb6MP1q8gB21L3WIo8T5P1MSMg3Ep14L7KkDCFG3y4w==}
|
||||
@@ -18686,14 +18686,14 @@ snapshots:
|
||||
|
||||
klona@2.0.6: {}
|
||||
|
||||
kysely-codegen@0.20.0(kysely@0.29.0)(pg@8.16.3)(typescript@5.9.3):
|
||||
kysely-codegen@0.20.0(kysely@0.28.17)(pg@8.16.3)(typescript@5.9.3):
|
||||
dependencies:
|
||||
chalk: 4.1.2
|
||||
cosmiconfig: 9.0.0(typescript@5.9.3)
|
||||
diff: 8.0.3
|
||||
dotenv: 17.2.4
|
||||
dotenv-expand: 12.0.3
|
||||
kysely: 0.29.0
|
||||
kysely: 0.28.17
|
||||
micromatch: 4.0.8
|
||||
minimist: 1.2.8
|
||||
pluralize: 8.0.0
|
||||
@@ -18708,13 +18708,13 @@ snapshots:
|
||||
'@commander-js/extra-typings': 11.1.0(commander@11.1.0)
|
||||
commander: 11.1.0
|
||||
|
||||
kysely-postgres-js@3.0.0(kysely@0.29.0)(postgres@3.4.8):
|
||||
kysely-postgres-js@3.0.0(kysely@0.28.17)(postgres@3.4.8):
|
||||
dependencies:
|
||||
kysely: 0.29.0
|
||||
kysely: 0.28.17
|
||||
optionalDependencies:
|
||||
postgres: 3.4.8
|
||||
|
||||
kysely@0.29.0: {}
|
||||
kysely@0.28.17: {}
|
||||
|
||||
langium@3.3.1:
|
||||
dependencies:
|
||||
@@ -19142,11 +19142,11 @@ snapshots:
|
||||
reflect-metadata: 0.2.2
|
||||
rxjs: 7.8.2
|
||||
|
||||
nestjs-kysely@3.1.2(@nestjs/common@11.1.19(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.19)(kysely@0.29.0)(reflect-metadata@0.2.2):
|
||||
nestjs-kysely@3.1.2(@nestjs/common@11.1.19(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@11.1.19)(kysely@0.28.17)(reflect-metadata@0.2.2):
|
||||
dependencies:
|
||||
'@nestjs/common': 11.1.19(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||
'@nestjs/core': 11.1.19(@nestjs/common@11.1.19(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/websockets@11.1.19)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||
kysely: 0.29.0
|
||||
kysely: 0.28.17
|
||||
reflect-metadata: 0.2.2
|
||||
|
||||
nestjs-pino@4.6.1(@nestjs/common@11.1.19(class-transformer@0.5.1)(class-validator@0.15.1)(reflect-metadata@0.2.2)(rxjs@7.8.2))(pino-http@11.0.0)(pino@10.1.0)(rxjs@7.8.2):
|
||||
|
||||
Reference in New Issue
Block a user