Compare commits

..

1 Commits

Author SHA1 Message Date
Philipinho 425924cb4d feat(editor): add page break node 2026-05-14 03:47:27 +01:00
68 changed files with 196 additions and 2437 deletions
@@ -71,7 +71,6 @@
"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.",
@@ -582,8 +581,6 @@
"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",
-5
View File
@@ -46,7 +46,6 @@ 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();
@@ -126,10 +125,6 @@ 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,5 +1,4 @@
import { ActionIcon, Box, Group, ScrollArea, Text, Tooltip } from "@mantine/core";
import { IconX } from "@tabler/icons-react";
import { Box, ScrollArea, Text } from "@mantine/core";
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";
@@ -12,10 +11,9 @@ import AsideChatPanel from "@/ee/ai-chat/components/aside-chat-panel";
import { PageDetailsAside } from "@/features/page-details/components/page-details-aside.tsx";
export default function Aside() {
const [{ tab }, setAsideState] = useAtom(asideStateAtom);
const [{ tab }] = useAtom(asideStateAtom);
const { t } = useTranslation();
const pageEditor = useAtomValue(pageEditorAtom);
const closeAside = () => setAsideState((s) => ({ ...s, isAsideOpen: false }));
let title: string;
let component: ReactNode;
@@ -47,19 +45,9 @@ export default function Aside() {
{component && (
<>
{tab !== "chat" && (
<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>
<Text mb="md" fw={500}>
{t(title)}
</Text>
)}
{tab === "comments" || tab === "chat" ? (
@@ -15,7 +15,6 @@ import {
IconSparkles,
IconHistory,
IconShieldCheck,
IconFileImport,
} from "@tabler/icons-react";
import { Link, useLocation } from "react-router-dom";
import classes from "./settings.module.css";
@@ -126,13 +125,6 @@ const groupedData: DataGroup[] = [
role: "owner",
env: "selfhosted",
},
{
label: "Import",
icon: IconFileImport,
path: "/settings/import/confluence",
feature: Feature.CONFLUENCE_IMPORT,
role: "admin",
},
],
},
{
@@ -1,229 +0,0 @@
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>
);
}
@@ -1,441 +0,0 @@
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>
);
}
@@ -1,67 +0,0 @@
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} />
</>
);
}
@@ -1,17 +0,0 @@
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;
},
});
}
@@ -1,64 +0,0 @@
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;
}
@@ -1,82 +0,0 @@
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,18 +166,6 @@ 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,8 +1,6 @@
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";
@@ -49,8 +47,6 @@ const CommentEditor = forwardRef(
placeholder: placeholder || t("Reply..."),
}),
LinkExtension,
TextStyle,
Color,
EmojiCommand,
Mention.configure({
suggestion: {
@@ -1,6 +1,5 @@
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);
@@ -13,7 +12,3 @@ 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,7 +2,6 @@ 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,
@@ -47,7 +46,7 @@ export function AudioMenu({ editor }: EditorMenuProps) {
);
const getReferencedVirtualElement = useCallback(() => {
if (!isEditorReady(editor)) return;
if (!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, isEditorReady, isTextSelected } from "@docmost/editor-ext";
import { CalloutType, 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 (!isEditorReady(editor)) return;
if (!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 { isEditorReady, isTextSelected } from "@docmost/editor-ext";
import { 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 || !isEditorReady(editor)) return false;
if (!state) 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 (!isEditorReady(editor)) return;
if (!editor) return;
const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "columns";
const parent = findParentNode(predicate)(selection);
@@ -2,7 +2,6 @@ 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,
@@ -82,7 +81,7 @@ export function DrawioMenu({ editor }: EditorMenuProps) {
);
const getReferencedVirtualElement = useCallback(() => {
if (!isEditorReady(editor)) return;
if (!editor) return;
const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "drawio";
const parent = findParentNode(predicate)(selection);
@@ -1,14 +0,0 @@
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,7 +2,6 @@ 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,
@@ -95,7 +94,7 @@ export function ExcalidrawMenu({ editor }: EditorMenuProps) {
);
const getReferencedVirtualElement = useCallback(() => {
if (!isEditorReady(editor)) return;
if (!editor) return;
const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "excalidraw";
const parent = findParentNode(predicate)(selection);
@@ -1,14 +0,0 @@
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>
);
}
@@ -2,7 +2,6 @@ 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,
@@ -57,7 +56,7 @@ export function ImageMenu({ editor }: EditorMenuProps) {
);
const getReferencedVirtualElement = useCallback(() => {
if (!isEditorReady(editor)) return;
if (!editor) return;
const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "image";
const parent = findParentNode(predicate)(selection);
@@ -2,7 +2,6 @@ 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,
@@ -38,8 +37,9 @@ export function PdfMenu({ editor }: EditorMenuProps) {
const shouldShow = useCallback(
({ state }: ShouldShowProps) => {
if (!state || !isEditorReady(editor)) return false;
if (!editor.isActive("pdf")) return false;
if (!state || !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 (!isEditorReady(editor)) return;
if (!editor) return;
const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "pdf";
const parent = findParentNode(predicate)(selection);
@@ -6,7 +6,6 @@ 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;
@@ -34,7 +33,6 @@ 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,12 +31,7 @@ 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.
// `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 lookupCellDom = editor.view.nodeDOM(anchorPos) as HTMLElement | null;
const [cellDom, setCellDom] = useState<HTMLElement | null>(lookupCellDom);
const lastCellDomRef = useRef<HTMLElement | null>(lookupCellDom);
useEffect(() => {
@@ -29,12 +29,7 @@ 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.
// `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 lookupCellDom = editor.view.nodeDOM(anchorPos) as HTMLElement | 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, isEditorReady, isTextSelected } from "@docmost/editor-ext";
import { isCellSelection, isTextSelected } from "@docmost/editor-ext";
import { useTranslation } from "react-i18next";
import classes from "../common/toolbar-menu.module.css";
@@ -38,7 +38,6 @@ 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,7 +2,6 @@ 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,
@@ -54,7 +53,7 @@ export function VideoMenu({ editor }: EditorMenuProps) {
);
const getReferencedVirtualElement = useCallback(() => {
if (!isEditorReady(editor)) return;
if (!editor) return;
const { selection } = editor.state;
const predicate = (node: PMNode) => node.type.name === "video";
const parent = findParentNode(predicate)(selection);
@@ -85,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-lazy.tsx";
import ExcalidrawView from "@/features/editor/components/excalidraw/excalidraw-view.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";
+11 -30
View File
@@ -1,5 +1,5 @@
import classes from "@/features/editor/styles/editor.module.css";
import React, { useEffect } from "react";
import React from "react";
import { TitleEditor } from "@/features/editor/title-editor";
import PageEditor from "@/features/editor/page-editor";
import {
@@ -23,25 +23,17 @@ import { IContributor } from "@/features/page/types/page.types.ts";
import { FixedToolbar } from "@/features/editor/components/fixed-toolbar/fixed-toolbar";
import { 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 PageUser = {
type PageCreator = {
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;
@@ -49,7 +41,7 @@ export interface FullEditorProps {
content: string;
spaceSlug: string;
editable: boolean;
creator?: PageUser;
creator?: PageCreator;
contributors?: IContributor[];
canComment?: boolean;
}
@@ -69,21 +61,9 @@ 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 = 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]);
const isEditMode = userPageEditMode === PageEditMode.Edit;
return (
<Container
@@ -91,10 +71,7 @@ export function FullEditor({
size={!fullPageWidth && 900}
className={classes.editor}
>
{editorToolbarEnabled && editable && isEditMode && (
<MemoizedFixedToolbar />
)}
<MemoizedDeletedPageBanner slugId={slugId} />
{editorToolbarEnabled && editable && isEditMode && <FixedToolbar />}
<MemoizedTitleEditor
pageId={pageId}
slugId={slugId}
@@ -118,12 +95,16 @@ export function FullEditor({
}
type PageBylineProps = {
creator?: PageUser;
creator?: PageCreator;
contributors?: IContributor[];
readOnly?: boolean;
};
function PageByline({ creator, contributors, readOnly }: PageBylineProps) {
function PageByline({
creator,
contributors,
readOnly,
}: PageBylineProps) {
const { t } = useTranslation();
const toggleAside = useToggleAside();
@@ -26,11 +26,10 @@ import {
collabExtensions,
mainExtensions,
} from "@/features/editor/extensions/extensions";
import { useAtom, useAtomValue } from "jotai";
import { useAtom } 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";
@@ -55,7 +54,7 @@ import {
handleFileDrop,
handlePaste,
} from "@/features/editor/components/common/editor-paste-handler.tsx";
import ExcalidrawMenu from "./components/excalidraw/excalidraw-menu-lazy";
import ExcalidrawMenu from "./components/excalidraw/excalidraw-menu";
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";
@@ -113,7 +112,8 @@ export default function PageEditor({
const documentState = useDocumentVisibility();
const { pageSlug } = useParams();
const slugId = extractPageSlugId(pageSlug);
const currentPageEditMode = useAtomValue(currentPageEditModeAtom);
const userPageEditMode =
currentUser?.user?.settings?.preferences?.pageEditMode ?? PageEditMode.Edit;
const canScroll = useCallback(
() => Boolean(isComponentMounted.current && editorRef.current),
[isComponentMounted],
@@ -373,9 +373,19 @@ export default function PageEditor({
return () => clearTimeout(timeout);
}, [yjsConnectionStatus, isSynced]);
useEffect(() => {
if (!editor) return;
editor.setEditable(editable && currentPageEditMode === PageEditMode.Edit);
}, [currentPageEditMode, editor, editable]);
// 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]);
const hasConnectedOnceRef = useRef(false);
const [showStatic, setShowStatic] = useState(true);
@@ -7,7 +7,6 @@ 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";
@@ -25,6 +24,7 @@ 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,7 +52,9 @@ export function TitleEditor({
const emit = useQueryEmit();
const navigate = useNavigate();
const [activePageId, setActivePageId] = useState(pageId);
const currentPageEditMode = useAtomValue(currentPageEditModeAtom);
const [currentUser] = useAtom(currentUserAtom);
const userPageEditMode =
currentUser?.user?.settings?.preferences?.pageEditMode ?? PageEditMode.Edit;
const titleEditor = useEditor({
extensions: [
@@ -170,9 +172,18 @@ export function TitleEditor({
}, [pageId]);
useEffect(() => {
if (!titleEditor) return;
titleEditor.setEditable(editable && currentPageEditMode === PageEditMode.Edit);
}, [currentPageEditMode, titleEditor, editable]);
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]);
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 { PageEditModeToggle } from "@/features/user/components/page-state-pref.tsx";
import { PageStateSegmentedControl } from "@/features/user/components/page-state-pref.tsx";
import MovePageModal from "@/features/page/components/move-page-modal.tsx";
import { useTimeAgo } from "@/hooks/use-time-ago.tsx";
import { PageShareModal } from "@/ee/page-permission";
@@ -65,11 +65,6 @@ 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(
[
@@ -92,15 +87,11 @@ export default function PageHeaderMenu({ readOnly }: PageHeaderMenuProps) {
[],
);
if (isDeleted) {
return null;
}
return (
<>
<ConnectionWarning />
{!readOnly && <PageEditModeToggle size="xs" />}
{!readOnly && <PageStateSegmentedControl size="xs" />}
<PageShareModal readOnly={readOnly} />
@@ -1,30 +0,0 @@
import { modals } from "@mantine/modals";
import { Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
type UseRestoreModalProps = {
title?: string | null;
onConfirm: () => void;
};
export function useRestorePageModal() {
const { t } = useTranslation();
const openRestoreModal = ({ title, onConfirm }: UseRestoreModalProps) => {
modals.openConfirmModal({
title: t("Restore page"),
children: (
<Text size="sm">
{t("Restore '{{title}}' and its sub-pages?", {
title: title || t("Untitled"),
})}
</Text>
),
centered: true,
labels: { confirm: t("Restore"), cancel: t("Cancel") },
confirmProps: { color: "blue" },
onConfirm,
});
};
return { openRestoreModal } as const;
}
@@ -117,20 +117,10 @@ export function useUpdatePageMutation() {
}
export function useRemovePageMutation() {
const { t } = useTranslation();
return useMutation({
mutationFn: (pageId: string) => deletePage(pageId, false),
onSuccess: (_, pageId) => {
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);
}
notifications.show({ message: "Page moved to trash" });
invalidateOnDeletePage(pageId);
queryClient.invalidateQueries({
predicate: (item) =>
@@ -138,7 +128,7 @@ export function useRemovePageMutation() {
});
},
onError: (error) => {
notifications.show({ message: t("Failed to delete page"), color: "red" });
notifications.show({ message: "Failed to delete page", color: "red" });
},
});
}
@@ -172,14 +162,13 @@ export function useMovePageMutation() {
}
export function useRestorePageMutation() {
const { t } = useTranslation();
const [treeData, setTreeData] = useAtom(treeDataAtom);
const emit = useQueryEmit();
return useMutation({
mutationFn: (pageId: string) => restorePage(pageId),
onSuccess: async (restoredPage) => {
notifications.show({ message: t("Page restored successfully") });
notifications.show({ message: "Page restored successfully" });
// Check if the page already exists in the tree (it shouldn't)
if (!treeModel.find(treeData, restoredPage.id)) {
@@ -233,16 +222,9 @@ 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: t("Failed to restore page"), color: "red" });
notifications.show({ message: "Failed to restore page", color: "red" });
},
});
}
@@ -1,140 +0,0 @@
import { ActionIcon, Button, Group, Paper, Text, Tooltip } from "@mantine/core";
import { IconRestore, IconTrash } from "@tabler/icons-react";
import { useNavigate } from "react-router-dom";
import { Trans, useTranslation } from "react-i18next";
import { useTimeAgo } from "@/hooks/use-time-ago.tsx";
import { useRestorePageModal } from "@/features/page/hooks/use-restore-page-modal.tsx";
import { useDeletePageModal } from "@/features/page/hooks/use-delete-page-modal.tsx";
import {
useDeletePageMutation,
usePageQuery,
useRestorePageMutation,
} from "@/features/page/queries/page-query.ts";
import { getSpaceUrl } from "@/lib/config.ts";
import { useGetSpaceBySlugQuery } from "@/features/space/queries/space-query.ts";
import { useSpaceAbility } from "@/features/space/permissions/use-space-ability.ts";
import {
SpaceCaslAction,
SpaceCaslSubject,
} from "@/features/space/permissions/permissions.type.ts";
type DeletedPageBannerProps = {
slugId: string;
};
export function DeletedPageBanner({ slugId }: DeletedPageBannerProps) {
const { t } = useTranslation();
const navigate = useNavigate();
const { data: page } = usePageQuery({ pageId: slugId });
const { data: space } = useGetSpaceBySlugQuery(page?.space?.slug);
const spaceAbility = useSpaceAbility(space?.membership?.permissions);
const deletedTimeAgo = useTimeAgo(page?.deletedAt);
const restorePageMutation = useRestorePageMutation();
const deletePageMutation = useDeletePageMutation();
const { openRestoreModal } = useRestorePageModal();
const { openDeleteModal } = useDeletePageModal();
if (!page?.deletedAt) return null;
const canRestore = spaceAbility.can(
SpaceCaslAction.Edit,
SpaceCaslSubject.Page,
);
const canPermanentlyDelete = spaceAbility.can(
SpaceCaslAction.Manage,
SpaceCaslSubject.Settings,
);
const actorName = page.deletedBy?.name ?? t("Someone");
const handleRestore = () => {
openRestoreModal({
title: page.title,
onConfirm: () => restorePageMutation.mutate(page.id),
});
};
const handlePermanentDelete = () => {
openDeleteModal({
isPermanent: true,
onConfirm: async () => {
await deletePageMutation.mutateAsync(page.id);
navigate(getSpaceUrl(page.space?.slug));
},
});
};
const hasAnyAction = canRestore || canPermanentlyDelete;
return (
<Paper radius="sm" mb="md" px="md" py="xs" bg="red.0">
<Group justify="space-between" wrap="wrap" gap="sm">
<Text size="sm" style={{ flex: 1, minWidth: 0 }}>
<Trans
i18nKey="<b>{{name}}</b> moved this page to Trash {{time}}."
values={{ name: actorName, time: deletedTimeAgo }}
components={{ b: <Text span fw={600} inherit /> }}
/>
</Text>
{hasAnyAction && (
<>
<Group gap="xs" wrap="nowrap" visibleFrom="sm">
{canRestore && (
<Button
size="xs"
variant="light"
color="red"
leftSection={<IconRestore size={16} />}
onClick={handleRestore}
loading={restorePageMutation.isPending}
>
{t("Restore page")}
</Button>
)}
{canPermanentlyDelete && (
<Button
size="xs"
variant="light"
color="red"
leftSection={<IconTrash size={16} />}
onClick={handlePermanentDelete}
loading={deletePageMutation.isPending}
>
{t("Permanently delete")}
</Button>
)}
</Group>
<Group gap="xs" wrap="nowrap" hiddenFrom="sm">
{canRestore && (
<Tooltip label={t("Restore page")} withArrow>
<ActionIcon
size="lg"
variant="default"
onClick={handleRestore}
loading={restorePageMutation.isPending}
aria-label={t("Restore page")}
>
<IconRestore size={18} />
</ActionIcon>
</Tooltip>
)}
{canPermanentlyDelete && (
<Tooltip label={t("Permanently delete")} withArrow>
<ActionIcon
size="lg"
variant="light"
color="red"
onClick={handlePermanentDelete}
loading={deletePageMutation.isPending}
aria-label={t("Permanently delete")}
>
<IconTrash size={18} />
</ActionIcon>
</Tooltip>
)}
</Group>
</>
)}
</Group>
</Paper>
);
}
@@ -1,21 +0,0 @@
import { Alert, Text } from "@mantine/core";
import { IconInfoCircle } from "@tabler/icons-react";
import { useAtomValue } from "jotai";
import { useTranslation } from "react-i18next";
import { workspaceAtom } from "@/features/user/atoms/current-user-atom.ts";
export function TrashBanner() {
const { t } = useTranslation();
const workspace = useAtomValue(workspaceAtom);
const retentionDays = workspace?.trashRetentionDays ?? 30;
return (
<Alert icon={<IconInfoCircle size={16} />} variant="light" color="red">
<Text size="sm" lh={1.35}>
{t("Pages in trash will be permanently deleted after {{count}} days.", {
count: retentionDays,
})}
</Text>
</Alert>
);
}
@@ -7,16 +7,17 @@ import {
Group,
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,
@@ -30,10 +31,12 @@ 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 { useRestorePageModal } from "@/features/page/hooks/use-restore-page-modal.tsx";
import { useAtom } from "jotai";
import { workspaceAtom } from "@/features/user/atoms/current-user-atom.ts";
export default function Trash() {
const { t } = useTranslation();
const [workspace] = useAtom(workspaceAtom);
const { spaceSlug } = useParams();
const { cursor, goNext, goPrev } = useCursorPaginate();
const { data: space } = useGetSpaceBySlugQuery(spaceSlug);
@@ -42,7 +45,6 @@ export default function Trash() {
});
const restorePageMutation = useRestorePageMutation();
const deletePageMutation = useDeletePageMutation();
const { openRestoreModal } = useRestorePageModal();
const [selectedPage, setSelectedPage] = useState<{
title: string;
@@ -76,6 +78,23 @@ export default function Trash() {
});
};
const openRestoreModal = (pageId: string, pageTitle: string) => {
modals.openConfirmModal({
title: t("Restore page"),
children: (
<Text size="sm">
{t("Restore '{{title}}' and its sub-pages?", {
title: pageTitle || "Untitled",
})}
</Text>
),
centered: true,
labels: { confirm: t("Restore"), cancel: t("Cancel") },
confirmProps: { color: "blue" },
onConfirm: () => handleRestorePage(pageId),
});
};
const hasPages = deletedPages && deletedPages.items.length > 0;
const handlePageClick = (page: any) => {
@@ -90,7 +109,11 @@ export default function Trash() {
<Title order={2}>{t("Trash")}</Title>
</Group>
<TrashBanner />
<Alert icon={<IconInfoCircle size={16} />} variant="light" color="red">
<Text size="sm">
{t("Pages in trash will be permanently deleted after {{count}} days.", { count: workspace?.trashRetentionDays ?? 30 })}
</Text>
</Alert>
{isLoading || !deletedPages ? (
<></>
@@ -158,10 +181,7 @@ export default function Trash() {
<Menu.Item
leftSection={<IconRestore size={16} />}
onClick={() =>
openRestoreModal({
title: page.title,
onConfirm: () => handleRestorePage(page.id),
})
openRestoreModal(page.id, page.title)
}
>
{t("Restore")}
@@ -6,7 +6,6 @@ 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();
@@ -72,24 +71,3 @@ export function PageStateSegmentedControl({
/>
);
}
// Header variant: updates the current page's mode locally without persisting
// the preference to the server.
export function PageEditModeToggle({ size }: { size?: MantineSize }) {
const { t } = useTranslation();
const [currentPageEditMode, setCurrentPageEditMode] = useAtom(
currentPageEditModeAtom,
);
return (
<SegmentedControl
size={size}
value={currentPageEditMode}
onChange={(v) => setCurrentPageEditMode(v as PageEditMode)}
data={[
{ label: t("Edit"), value: PageEditMode.Edit },
{ label: t("Read"), value: PageEditMode.Read },
]}
/>
);
}
+1 -1
View File
@@ -52,7 +52,7 @@ function PageContent({ pageSlug }: { pageSlug: string | undefined }) {
} = usePageQuery({ pageId: extractPageSlugId(pageSlug) });
const { data: space } = useGetSpaceBySlugQuery(page?.space?.slug);
const canEdit = !page?.deletedAt && (page?.permissions?.canEdit ?? false);
const canEdit = page?.permissions?.canEdit ?? false;
const canComment =
canEdit ||
(space?.settings?.comments?.allowViewerComments === true);
+5 -6
View File
@@ -38,12 +38,12 @@ export default defineConfig(({ mode }) => {
build: {
rolldownOptions: {
output: {
advancedChunks: {
codeSplitting: {
groups: [
{
name: "vendor-mantine",
test: /[\\/]node_modules[\\/]@mantine[\\/]/,
},
{ name: "vendor-mantine", test: /@mantine/ },
{ name: "vendor-mermaid", test: /mermaid|cytoscape|elkjs/ },
{ name: "vendor-excalidraw", test: /excalidraw/ },
{ name: "vendor-katex", test: /katex/ },
],
},
},
@@ -55,7 +55,6 @@ export default defineConfig(({ mode }) => {
},
},
server: {
allowedHosts: ['docmost.nz'],
proxy: {
"/api": {
target: APP_URL,
-2
View File
@@ -27,7 +27,6 @@ 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 {
@@ -54,7 +53,6 @@ try {
CoreModule,
DatabaseModule,
EnvironmentModule,
EncryptionModule,
RedisModule.forRootAsync({
useClass: RedisConfigService,
}),
@@ -2,7 +2,6 @@ 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';
@@ -13,8 +12,6 @@ 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: [
@@ -29,18 +26,6 @@ import KeyvRedis from '@keyv/redis';
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,11 +1,3 @@
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;
@@ -1,27 +0,0 @@
import { Cache } from 'cache-manager';
export async function withCache<T>(
cacheManager: Cache,
key: string,
ttlMs: number,
fn: () => Promise<T>,
): Promise<T> {
try {
const cached = await cacheManager.get<{ v: T }>(key);
if (cached !== undefined && cached !== null) {
return cached.v;
}
} catch (err) {
console.warn(`[withCache] get failed for "${key}", falling back to source`, err);
}
const value = await fn();
try {
await cacheManager.set(key, { v: value }, ttlMs);
} catch (err) {
console.warn(`[withCache] set failed for "${key}"`, err);
}
return value;
}
@@ -76,7 +76,6 @@ export class PageController {
includeCreator: true,
includeLastUpdatedBy: true,
includeContributors: true,
includeDeletedBy: true,
});
if (!page) {
@@ -1,6 +1,4 @@
import { Inject, Injectable } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { Injectable } from '@nestjs/common';
import { InjectKysely } from 'nestjs-kysely';
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
import { dbOrTx } from '@docmost/db/utils';
@@ -19,11 +17,6 @@ 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';
@@ -32,7 +25,6 @@ export class PagePermissionRepo {
constructor(
@InjectKysely() private readonly db: KyselyDB,
private readonly groupRepo: GroupRepo,
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache,
) {}
async findPageAccessByPageId(
@@ -369,8 +361,40 @@ export class PagePermissionRepo {
* Check if user can access a page by verifying they have permission on ALL restricted ancestors.
*/
async canUserAccessPage(userId: string, pageId: string): Promise<boolean> {
const { canAccess } = await this.canUserEditPage(userId, pageId);
return canAccess;
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;
}
/**
@@ -388,50 +412,43 @@ export class PagePermissionRepo {
canAccess: boolean;
canEdit: boolean;
}> {
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
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
)
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);
)
`.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,7 +54,6 @@ export class PageRepo {
includeCreator?: boolean;
includeLastUpdatedBy?: boolean;
includeContributors?: boolean;
includeDeletedBy?: boolean;
includeHasChildren?: boolean;
withLock?: boolean;
trx?: KyselyTransaction;
@@ -84,10 +83,6 @@ 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,6 +1,4 @@
import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectKysely } from 'nestjs-kysely';
import { KyselyDB, KyselyTransaction } from '@docmost/db/types/kysely.types';
import { dbOrTx } from '@docmost/db/utils';
@@ -15,11 +13,6 @@ 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 {
@@ -27,7 +20,6 @@ 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(
@@ -222,36 +214,25 @@ export class SpaceMemberRepo {
userId: string,
spaceId: string,
): Promise<UserSpaceRole[]> {
return withCache(
this.cacheManager,
CacheKey.SPACE_ROLES(userId, spaceId),
PERMISSION_CACHE_TTL_MS,
async () => {
const roles = await this.db
const roles = await this.db
.selectFrom('spaceMembers')
.select(['userId', 'role'])
.where('userId', '=', userId)
.where('spaceId', '=', spaceId)
.unionAll(
this.db
.selectFrom('spaceMembers')
.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();
.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(
@@ -1,30 +0,0 @@
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,8 +1,6 @@
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,13 +0,0 @@
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';
}
}
@@ -1,9 +0,0 @@
import { Global, Module } from '@nestjs/common';
import { EncryptionService } from './encryption.service';
@Global()
@Module({
providers: [EncryptionService],
exports: [EncryptionService],
})
export class EncryptionModule {}
@@ -1,184 +0,0 @@
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);
});
});
});
@@ -1,108 +0,0 @@
// 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,9 +28,6 @@ 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;
@@ -52,19 +49,6 @@ 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);
@@ -90,8 +74,6 @@ 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);
}
}
@@ -1,32 +0,0 @@
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}$/);
});
});
@@ -1,28 +0,0 @@
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;
}
@@ -1,46 +0,0 @@
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();
});
});
@@ -1,28 +0,0 @@
/**
* 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;
}
}
@@ -1,149 +0,0 @@
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>');
});
});
});
@@ -1,76 +0,0 @@
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,7 +11,6 @@ export enum FileImportSource {
Generic = 'generic',
Notion = 'notion',
Confluence = 'confluence',
ConfluenceApi = 'confluence-api'
}
export enum FileTaskStatus {
@@ -97,21 +97,14 @@ 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);
@@ -127,21 +120,6 @@ 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,7 +30,6 @@ 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',
@@ -162,28 +162,6 @@ 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
@@ -229,56 +207,6 @@ 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,7 +1,5 @@
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';
@@ -21,11 +19,7 @@ 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 {
@@ -41,86 +35,8 @@ 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;
@@ -168,7 +84,6 @@ export const CustomCodeBlock = CodeBlock.extend<CodeBlockLowlightOptions>({
},
addProseMirrorPlugins() {
const codeBlockType = this.type;
return [
...(this.parent?.() || []),
LowlightPlugin({
@@ -176,60 +91,6 @@ 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;
},
},
}),
];
},
});
-9
View File
@@ -338,15 +338,6 @@ 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: {