2025-11-23 10:55:04 +08:00
|
|
|
"use client";
|
|
|
|
|
|
|
|
|
|
import dynamic from "next/dynamic";
|
2026-01-24 12:32:51 +08:00
|
|
|
import { useCallback, useEffect, useMemo, useRef, useState, type ChangeEvent, type KeyboardEvent as ReactKeyboardEvent } from "react";
|
2026-02-01 08:47:40 +08:00
|
|
|
import type { BooleanPageOptionKey, DocumentStats, PageOptionsState, PageFont, PageLayoutDensity } from "@/types/page-options";
|
2025-11-23 10:55:04 +08:00
|
|
|
import { PageOptionsSidebar } from "@/components/editor/page-options-sidebar";
|
|
|
|
|
import { PageBacklinksPanel } from "@/components/editor/page-backlinks-panel";
|
|
|
|
|
import { useEditorBridgeStore } from "@/store/editor-bridge";
|
|
|
|
|
import { usePageLayoutStore } from "@/store/page-layout";
|
2026-01-24 12:32:51 +08:00
|
|
|
import { useCurrentDocumentStore } from "@/store/current-document";
|
2025-11-23 10:55:04 +08:00
|
|
|
import type { Json } from "@/types/supabase";
|
|
|
|
|
import { DocumentHistoryDrawer } from "@/components/editor/document-history-drawer";
|
2026-02-01 08:47:40 +08:00
|
|
|
import { DocumentCommentsDrawer } from "@/components/editor/document-comments-drawer";
|
2025-11-23 10:55:04 +08:00
|
|
|
import type { DocumentSnapshot } from "@/types/document";
|
|
|
|
|
import { useDebouncedCallback } from "@/hooks/use-debounced-callback";
|
|
|
|
|
import { ImagePickerProvider } from "@/components/media/image-picker-context";
|
2026-01-10 10:35:21 +08:00
|
|
|
import { useRouter } from "next/navigation";
|
2026-01-10 23:08:56 +08:00
|
|
|
import { DocumentAiAgentPanel } from "./DocumentAiAgentPanel";
|
2026-01-21 18:21:10 +08:00
|
|
|
import { CONTENT_LOADING_DELAY_MS } from "@/lib/constants";
|
2026-02-01 08:47:40 +08:00
|
|
|
import { useCommentsUiStore } from "@/store/comments-ui";
|
|
|
|
|
import { useAppPreferencesStore } from "@/store/app-preferences";
|
|
|
|
|
import { useMoveEmbedPickerStore } from "@/store/move-embed-picker";
|
|
|
|
|
import { cn } from "@/lib/utils";
|
2025-11-23 10:55:04 +08:00
|
|
|
|
|
|
|
|
const BlockNoteEditor = dynamic(
|
|
|
|
|
() => import("@/components/editor/blocknote-editor").then((mod) => mod.BlockNoteEditor),
|
|
|
|
|
{
|
|
|
|
|
ssr: false,
|
|
|
|
|
loading: () => (
|
|
|
|
|
<div className="flex h-64 items-center justify-center text-sm text-gray-400">编辑器加载中...</div>
|
|
|
|
|
),
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
export interface DocumentContentProps {
|
|
|
|
|
documentId: string;
|
|
|
|
|
workspaceId: string;
|
|
|
|
|
title: string | null;
|
|
|
|
|
updatedAt: string | null;
|
|
|
|
|
initialContent: unknown;
|
2026-04-15 03:06:29 +08:00
|
|
|
initialContentRevision?: number | null;
|
|
|
|
|
initialConflictDetectionKey?: string | null;
|
2025-11-23 10:55:04 +08:00
|
|
|
initialOptions: PageOptionsState;
|
|
|
|
|
initialStats: DocumentStats | null;
|
2026-01-10 10:35:21 +08:00
|
|
|
openTableId?: string | null;
|
2026-01-22 18:53:20 +08:00
|
|
|
readOnly?: boolean;
|
2026-01-24 12:32:51 +08:00
|
|
|
disableDownload?: boolean;
|
|
|
|
|
disableCopy?: boolean;
|
2025-11-23 10:55:04 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const defaultOptions: PageOptionsState = {
|
|
|
|
|
wideLayout: false,
|
|
|
|
|
smallText: false,
|
|
|
|
|
showHeadingNumbers: true,
|
|
|
|
|
showToc: false,
|
|
|
|
|
showStructure: false,
|
|
|
|
|
protectEditing: false,
|
|
|
|
|
showWordCount: true,
|
2026-02-01 08:47:40 +08:00
|
|
|
collapseBacklinks: false,
|
|
|
|
|
pageFont: "default",
|
|
|
|
|
layoutDensity: "normal",
|
|
|
|
|
hideChildPages: false,
|
|
|
|
|
showBlockRefCount: false,
|
|
|
|
|
embedDefaultBlockId: null,
|
2025-11-23 10:55:04 +08:00
|
|
|
};
|
2026-02-01 08:47:40 +08:00
|
|
|
const defaultStats: DocumentStats = { wordCount: 0, characterCount: 0, blockCount: 0, todoTotal: 0, todoDone: 0 };
|
2025-11-23 10:55:04 +08:00
|
|
|
|
|
|
|
|
export function DocumentContent({
|
|
|
|
|
documentId,
|
|
|
|
|
workspaceId,
|
|
|
|
|
title,
|
|
|
|
|
updatedAt,
|
|
|
|
|
initialContent,
|
2026-04-15 03:06:29 +08:00
|
|
|
initialContentRevision = null,
|
|
|
|
|
initialConflictDetectionKey = null,
|
2025-11-23 10:55:04 +08:00
|
|
|
initialOptions,
|
|
|
|
|
initialStats,
|
2026-01-10 10:35:21 +08:00
|
|
|
openTableId,
|
2026-01-22 18:53:20 +08:00
|
|
|
readOnly = false,
|
2026-01-24 12:32:51 +08:00
|
|
|
disableDownload = false,
|
|
|
|
|
disableCopy = false,
|
2025-11-23 10:55:04 +08:00
|
|
|
}: DocumentContentProps) {
|
2026-01-24 12:32:51 +08:00
|
|
|
const setCurrentDocument = useCurrentDocumentStore((state) => state.setCurrent);
|
|
|
|
|
const clearIfMatch = useCurrentDocumentStore((state) => state.clearIfMatch);
|
2025-11-23 10:55:04 +08:00
|
|
|
const [options, setOptions] = useState<PageOptionsState>(initialOptions ?? defaultOptions);
|
|
|
|
|
const [stats, setStats] = useState<DocumentStats>(initialStats ?? defaultStats);
|
|
|
|
|
const [history, setHistory] = useState<DocumentSnapshot[]>([]);
|
|
|
|
|
const [historyOpen, setHistoryOpen] = useState(false);
|
|
|
|
|
const editorBridge = useEditorBridgeStore((state) => state.bridge);
|
2026-01-10 10:35:21 +08:00
|
|
|
const router = useRouter();
|
2025-11-23 10:55:04 +08:00
|
|
|
const showInspector = usePageLayoutStore((state) => state.showInspector);
|
2026-02-01 08:47:40 +08:00
|
|
|
const openCommentsForPage = useCommentsUiStore((s) => s.openForPage);
|
|
|
|
|
const spellCheck = useAppPreferencesStore((s) => s.spellCheck);
|
|
|
|
|
const openMoveEmbedPicker = useMoveEmbedPickerStore((s) => s.openPicker);
|
2025-11-23 10:55:04 +08:00
|
|
|
const [pageTitle, setPageTitle] = useState(title ?? "无标题");
|
2026-01-10 10:35:21 +08:00
|
|
|
const [content, setContent] = useState<unknown>(initialContent);
|
2026-04-15 03:06:29 +08:00
|
|
|
const [contentRevision, setContentRevision] = useState<number | null>(initialContentRevision);
|
|
|
|
|
const [conflictDetectionKey, setConflictDetectionKey] = useState<string | null>(initialConflictDetectionKey);
|
2026-01-10 10:35:21 +08:00
|
|
|
const [contentLoading, setContentLoading] = useState(() => initialContent == null);
|
|
|
|
|
const [contentError, setContentError] = useState<string | null>(null);
|
|
|
|
|
const [contentReloadKey, setContentReloadKey] = useState(0);
|
|
|
|
|
const [showContentLoadingIndicator, setShowContentLoadingIndicator] = useState(false);
|
|
|
|
|
const contentLoadingTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
|
|
|
const pendingOpenTableRef = useRef<string | null>(null);
|
2026-01-10 23:08:56 +08:00
|
|
|
const latestBlocksRef = useRef<Json | null>(null);
|
2026-01-24 12:32:51 +08:00
|
|
|
const pageRootRef = useRef<HTMLDivElement>(null);
|
|
|
|
|
const lastCopyBlockedAtRef = useRef<number>(0);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
setCurrentDocument(documentId, readOnly, disableDownload, disableCopy);
|
|
|
|
|
return () => {
|
|
|
|
|
clearIfMatch(documentId);
|
|
|
|
|
};
|
|
|
|
|
}, [clearIfMatch, disableCopy, disableDownload, documentId, readOnly, setCurrentDocument]);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
if (!disableCopy) return;
|
|
|
|
|
|
|
|
|
|
const isEventInsidePage = () => {
|
|
|
|
|
const root = pageRootRef.current;
|
|
|
|
|
if (!root) return false;
|
|
|
|
|
const selection = typeof window !== "undefined" ? window.getSelection() : null;
|
|
|
|
|
const anchor = selection?.anchorNode ?? null;
|
|
|
|
|
const focus = selection?.focusNode ?? null;
|
|
|
|
|
const anchorEl =
|
|
|
|
|
anchor && "nodeType" in anchor && anchor.nodeType === Node.TEXT_NODE
|
|
|
|
|
? anchor.parentElement
|
|
|
|
|
: (anchor as any as Element | null);
|
|
|
|
|
const focusEl =
|
|
|
|
|
focus && "nodeType" in focus && focus.nodeType === Node.TEXT_NODE
|
|
|
|
|
? focus.parentElement
|
|
|
|
|
: (focus as any as Element | null);
|
|
|
|
|
return Boolean((anchorEl && root.contains(anchorEl)) || (focusEl && root.contains(focusEl)));
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const notifyBlocked = () => {
|
|
|
|
|
const now = Date.now();
|
|
|
|
|
if (now - lastCopyBlockedAtRef.current < 1200) return;
|
|
|
|
|
lastCopyBlockedAtRef.current = now;
|
|
|
|
|
window.alert("该页面已禁止复制");
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const onCopy = (event: ClipboardEvent) => {
|
|
|
|
|
if (!isEventInsidePage()) return;
|
|
|
|
|
event.preventDefault();
|
|
|
|
|
event.stopPropagation();
|
|
|
|
|
notifyBlocked();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const onCut = (event: ClipboardEvent) => {
|
|
|
|
|
if (!isEventInsidePage()) return;
|
|
|
|
|
event.preventDefault();
|
|
|
|
|
event.stopPropagation();
|
|
|
|
|
notifyBlocked();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const onKeyDown = (event: KeyboardEvent) => {
|
|
|
|
|
if (!isEventInsidePage()) return;
|
|
|
|
|
const key = String(event.key ?? "").toLowerCase();
|
|
|
|
|
const ctrlOrMeta = event.ctrlKey || event.metaKey;
|
|
|
|
|
if (!ctrlOrMeta) return;
|
|
|
|
|
if (key === "c" || key === "x" || key === "insert") {
|
|
|
|
|
event.preventDefault();
|
|
|
|
|
event.stopPropagation();
|
|
|
|
|
notifyBlocked();
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
document.addEventListener("copy", onCopy, true);
|
|
|
|
|
document.addEventListener("cut", onCut, true);
|
|
|
|
|
document.addEventListener("keydown", onKeyDown, true);
|
|
|
|
|
return () => {
|
|
|
|
|
document.removeEventListener("copy", onCopy, true);
|
|
|
|
|
document.removeEventListener("cut", onCut, true);
|
|
|
|
|
document.removeEventListener("keydown", onKeyDown, true);
|
|
|
|
|
};
|
|
|
|
|
}, [disableCopy]);
|
2026-01-10 10:35:21 +08:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
const tableId = (openTableId ?? "").trim();
|
|
|
|
|
if (!tableId) return;
|
|
|
|
|
if (!editorBridge?.openTableFullScreen) return;
|
|
|
|
|
if (pendingOpenTableRef.current === tableId) return;
|
|
|
|
|
pendingOpenTableRef.current = tableId;
|
|
|
|
|
|
|
|
|
|
editorBridge.openTableFullScreen(tableId);
|
|
|
|
|
|
|
|
|
|
// 清理 URL 参数,避免刷新/回退时重复触发
|
|
|
|
|
if (typeof window !== "undefined") {
|
|
|
|
|
try {
|
|
|
|
|
const url = new URL(window.location.href);
|
|
|
|
|
url.searchParams.delete("openTableId");
|
|
|
|
|
window.history.replaceState({}, "", url.toString());
|
|
|
|
|
} catch {
|
|
|
|
|
// fallback:不影响主流程
|
|
|
|
|
router.replace(`/documents/${documentId}`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}, [documentId, editorBridge, openTableId, router]);
|
2025-11-23 10:55:04 +08:00
|
|
|
|
2026-01-21 18:21:10 +08:00
|
|
|
|
2025-11-23 10:55:04 +08:00
|
|
|
useEffect(() => {
|
|
|
|
|
setPageTitle(title ?? "无标题");
|
|
|
|
|
}, [title]);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
setOptions(initialOptions ?? defaultOptions);
|
|
|
|
|
}, [initialOptions]);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
setStats(initialStats ?? defaultStats);
|
|
|
|
|
}, [initialStats]);
|
2026-04-15 03:06:29 +08:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
setContentRevision(initialContentRevision);
|
|
|
|
|
}, [initialContentRevision]);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
setConflictDetectionKey(initialConflictDetectionKey);
|
|
|
|
|
}, [initialConflictDetectionKey]);
|
2026-01-21 18:21:10 +08:00
|
|
|
|
2025-11-23 10:55:04 +08:00
|
|
|
|
2026-01-10 10:35:21 +08:00
|
|
|
useEffect(() => {
|
|
|
|
|
let canceled = false;
|
|
|
|
|
const controller = new AbortController();
|
|
|
|
|
|
|
|
|
|
const load = async () => {
|
|
|
|
|
setContentError(null);
|
|
|
|
|
setContentLoading(initialContent == null);
|
|
|
|
|
setContent(initialContent);
|
|
|
|
|
setShowContentLoadingIndicator(false);
|
|
|
|
|
|
|
|
|
|
if (initialContent != null) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (contentLoadingTimerRef.current) {
|
|
|
|
|
clearTimeout(contentLoadingTimerRef.current);
|
|
|
|
|
contentLoadingTimerRef.current = null;
|
|
|
|
|
}
|
2026-01-21 18:21:10 +08:00
|
|
|
// 避免"秒闪"的加载提示:只有当加载超过短阈值时才显示提示
|
2026-01-10 10:35:21 +08:00
|
|
|
contentLoadingTimerRef.current = setTimeout(() => {
|
|
|
|
|
if (!canceled) {
|
|
|
|
|
setShowContentLoadingIndicator(true);
|
|
|
|
|
}
|
2026-01-21 18:21:10 +08:00
|
|
|
}, CONTENT_LOADING_DELAY_MS);
|
2026-01-10 10:35:21 +08:00
|
|
|
|
|
|
|
|
try {
|
2026-04-14 13:22:29 +08:00
|
|
|
const response = await fetch(
|
|
|
|
|
`/api/documents/content?documentId=${encodeURIComponent(documentId)}&workspaceId=${encodeURIComponent(workspaceId)}`,
|
|
|
|
|
{
|
2026-01-10 10:35:21 +08:00
|
|
|
method: "GET",
|
|
|
|
|
credentials: "include",
|
|
|
|
|
signal: controller.signal,
|
2026-04-14 13:22:29 +08:00
|
|
|
},
|
|
|
|
|
);
|
2026-01-10 10:35:21 +08:00
|
|
|
if (!response.ok) {
|
|
|
|
|
const payload = await response.json().catch(() => ({}));
|
|
|
|
|
throw new Error(payload?.error ?? "加载页面内容失败");
|
|
|
|
|
}
|
2026-04-15 03:06:29 +08:00
|
|
|
const payload = (await response.json()) as {
|
|
|
|
|
content?: unknown;
|
|
|
|
|
revision?: number | null;
|
|
|
|
|
conflictDetectionKey?: string | null;
|
|
|
|
|
};
|
2026-01-10 10:35:21 +08:00
|
|
|
if (canceled) return;
|
|
|
|
|
setContent(payload.content ?? null);
|
2026-04-15 03:06:29 +08:00
|
|
|
setContentRevision(
|
|
|
|
|
typeof payload.revision === "number" && Number.isInteger(payload.revision)
|
|
|
|
|
? payload.revision
|
|
|
|
|
: 0,
|
|
|
|
|
);
|
|
|
|
|
setConflictDetectionKey(
|
|
|
|
|
typeof payload.conflictDetectionKey === "string" && payload.conflictDetectionKey.trim()
|
|
|
|
|
? payload.conflictDetectionKey
|
|
|
|
|
: `${documentId}:0`,
|
|
|
|
|
);
|
2026-01-10 10:35:21 +08:00
|
|
|
} catch (error) {
|
|
|
|
|
if (canceled) return;
|
|
|
|
|
if ((error as { name?: string })?.name === "AbortError") return;
|
|
|
|
|
setContentError(error instanceof Error ? error.message : "加载页面内容失败");
|
|
|
|
|
} finally {
|
|
|
|
|
if (!canceled) {
|
|
|
|
|
setContentLoading(false);
|
|
|
|
|
setShowContentLoadingIndicator(false);
|
|
|
|
|
}
|
|
|
|
|
if (contentLoadingTimerRef.current) {
|
|
|
|
|
clearTimeout(contentLoadingTimerRef.current);
|
|
|
|
|
contentLoadingTimerRef.current = null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
void load();
|
|
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
|
canceled = true;
|
|
|
|
|
controller.abort();
|
|
|
|
|
if (contentLoadingTimerRef.current) {
|
|
|
|
|
clearTimeout(contentLoadingTimerRef.current);
|
|
|
|
|
contentLoadingTimerRef.current = null;
|
|
|
|
|
}
|
|
|
|
|
};
|
2026-04-14 13:22:29 +08:00
|
|
|
}, [documentId, initialContent, contentReloadKey, workspaceId]);
|
2026-01-10 10:35:21 +08:00
|
|
|
|
2025-11-23 10:55:04 +08:00
|
|
|
const persistTitle = useCallback(
|
|
|
|
|
async (nextTitle: string) => {
|
2026-01-22 18:53:20 +08:00
|
|
|
if (readOnly) return;
|
2025-11-23 10:55:04 +08:00
|
|
|
const payload = nextTitle.trim() || "无标题";
|
|
|
|
|
await fetch("/api/documents/title", {
|
|
|
|
|
method: "POST",
|
|
|
|
|
headers: { "Content-Type": "application/json" },
|
2026-04-14 13:22:29 +08:00
|
|
|
body: JSON.stringify({ documentId, workspaceId, title: payload }),
|
2025-11-23 10:55:04 +08:00
|
|
|
});
|
|
|
|
|
},
|
2026-04-14 13:22:29 +08:00
|
|
|
[documentId, readOnly, workspaceId],
|
2025-11-23 10:55:04 +08:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const debouncedPersistTitle = useDebouncedCallback((value: string) => {
|
|
|
|
|
void persistTitle(value);
|
|
|
|
|
}, 600);
|
|
|
|
|
|
|
|
|
|
const handleTitleChange = (event: ChangeEvent<HTMLInputElement>) => {
|
2026-01-22 18:53:20 +08:00
|
|
|
if (readOnly) return;
|
2025-11-23 10:55:04 +08:00
|
|
|
const value = event.target.value;
|
|
|
|
|
setPageTitle(value);
|
|
|
|
|
debouncedPersistTitle(value);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const handleTitleBlur = () => {
|
2026-01-22 18:53:20 +08:00
|
|
|
if (readOnly) return;
|
2025-11-23 10:55:04 +08:00
|
|
|
void persistTitle(pageTitle);
|
|
|
|
|
};
|
|
|
|
|
|
2026-01-24 12:32:51 +08:00
|
|
|
const handleTitleKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
|
2025-11-23 10:55:04 +08:00
|
|
|
if (event.key === "Enter") {
|
|
|
|
|
event.preventDefault();
|
|
|
|
|
event.currentTarget.blur();
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const persistOptions = useCallback(
|
|
|
|
|
async (patch: Partial<PageOptionsState>) => {
|
2026-01-22 18:53:20 +08:00
|
|
|
if (readOnly) return;
|
2025-11-23 10:55:04 +08:00
|
|
|
try {
|
|
|
|
|
const response = await fetch("/api/documents/options", {
|
|
|
|
|
method: "POST",
|
|
|
|
|
headers: { "Content-Type": "application/json" },
|
2026-04-14 13:22:29 +08:00
|
|
|
body: JSON.stringify({ documentId, workspaceId, options: patch }),
|
2025-11-23 10:55:04 +08:00
|
|
|
});
|
|
|
|
|
if (!response.ok) {
|
|
|
|
|
const payload = await response.json().catch(() => null);
|
|
|
|
|
console.error(payload?.error ?? "更新页面选项失败");
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error(error);
|
|
|
|
|
}
|
|
|
|
|
},
|
2026-04-14 13:22:29 +08:00
|
|
|
[documentId, readOnly, workspaceId],
|
2025-11-23 10:55:04 +08:00
|
|
|
);
|
|
|
|
|
|
2026-02-01 08:47:40 +08:00
|
|
|
const toggleOption = useCallback(
|
|
|
|
|
(key: BooleanPageOptionKey) => {
|
|
|
|
|
if (readOnly) return;
|
|
|
|
|
setOptions((prev) => {
|
|
|
|
|
const nextValue = !prev[key];
|
|
|
|
|
const next = { ...prev, [key]: nextValue };
|
|
|
|
|
void persistOptions({ [key]: nextValue } as Partial<PageOptionsState>);
|
|
|
|
|
return next;
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
[persistOptions, readOnly],
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const setOptionPatch = useCallback(
|
|
|
|
|
(patch: Partial<PageOptionsState>) => {
|
|
|
|
|
if (readOnly) return;
|
|
|
|
|
setOptions((prev) => {
|
|
|
|
|
const next = { ...prev, ...patch };
|
|
|
|
|
void persistOptions(patch);
|
|
|
|
|
return next;
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
[persistOptions, readOnly],
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const closeToc = useCallback(() => {
|
2026-01-22 18:53:20 +08:00
|
|
|
if (readOnly) return;
|
2025-11-23 10:55:04 +08:00
|
|
|
setOptions((prev) => {
|
2026-02-01 08:47:40 +08:00
|
|
|
if (!prev.showToc) return prev;
|
|
|
|
|
const next = { ...prev, showToc: false };
|
|
|
|
|
void persistOptions({ showToc: false });
|
2025-11-23 10:55:04 +08:00
|
|
|
return next;
|
|
|
|
|
});
|
2026-02-01 08:47:40 +08:00
|
|
|
}, [persistOptions, readOnly]);
|
|
|
|
|
|
|
|
|
|
const handleSetPageFont = useCallback(
|
|
|
|
|
(font: PageFont) => {
|
|
|
|
|
setOptionPatch({ pageFont: font });
|
|
|
|
|
},
|
|
|
|
|
[setOptionPatch],
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const handleSetLayoutDensity = useCallback(
|
|
|
|
|
(density: PageLayoutDensity) => {
|
|
|
|
|
setOptionPatch({ layoutDensity: density });
|
|
|
|
|
},
|
|
|
|
|
[setOptionPatch],
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const handleSetEmbedDefaultToCursor = useCallback(() => {
|
|
|
|
|
if (readOnly) return;
|
|
|
|
|
const blockId = editorBridge?.getCursorBlockId?.() ?? null;
|
|
|
|
|
if (!blockId) {
|
|
|
|
|
window.alert("未找到当前光标所在块,请先在编辑器中点击任意块");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
setOptionPatch({ embedDefaultBlockId: blockId });
|
|
|
|
|
window.alert("已设置“嵌入默认位置”");
|
|
|
|
|
}, [editorBridge, readOnly, setOptionPatch]);
|
|
|
|
|
|
|
|
|
|
const handleClearEmbedDefault = useCallback(() => {
|
|
|
|
|
if (readOnly) return;
|
|
|
|
|
setOptionPatch({ embedDefaultBlockId: null });
|
|
|
|
|
window.alert("已清除“嵌入默认位置”");
|
|
|
|
|
}, [readOnly, setOptionPatch]);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
const onKeyDown = (event: KeyboardEvent) => {
|
|
|
|
|
const root = pageRootRef.current;
|
|
|
|
|
if (root) {
|
|
|
|
|
const target = event.target;
|
|
|
|
|
if (target && target instanceof Node && !root.contains(target)) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
const ctrlOrMeta = event.ctrlKey || event.metaKey;
|
|
|
|
|
if (!ctrlOrMeta) return;
|
|
|
|
|
if (!event.shiftKey) return;
|
|
|
|
|
const key = String(event.key ?? "").toLowerCase();
|
|
|
|
|
if (key === "l") {
|
|
|
|
|
event.preventDefault();
|
|
|
|
|
toggleOption("showToc");
|
|
|
|
|
} else if (key === "c") {
|
|
|
|
|
event.preventDefault();
|
|
|
|
|
toggleOption("protectEditing");
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
window.addEventListener("keydown", onKeyDown);
|
|
|
|
|
return () => window.removeEventListener("keydown", onKeyDown);
|
|
|
|
|
}, [toggleOption]);
|
|
|
|
|
|
|
|
|
|
const buildDocumentUrl = useCallback((id: string): string => {
|
|
|
|
|
if (typeof window === "undefined" || !window.location) {
|
|
|
|
|
return `/documents/${id}`;
|
|
|
|
|
}
|
|
|
|
|
return `${window.location.origin}/documents/${id}`;
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
const copyText = useCallback(async (text: string, successMessage: string) => {
|
|
|
|
|
if (typeof navigator !== "undefined" && navigator.clipboard) {
|
|
|
|
|
try {
|
|
|
|
|
await navigator.clipboard.writeText(text);
|
|
|
|
|
window.alert(successMessage);
|
|
|
|
|
return;
|
|
|
|
|
} catch {
|
|
|
|
|
// ignore and fallback
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
window.prompt("复制失败,请手动复制内容", text);
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
const handleCopyPageLink = useCallback(
|
|
|
|
|
async (includeTitle: boolean) => {
|
|
|
|
|
const url = buildDocumentUrl(documentId);
|
|
|
|
|
if (includeTitle) {
|
|
|
|
|
const text = `${pageTitle || "无标题"}\n${url}`;
|
|
|
|
|
await copyText(text, "标题 + 链接已复制");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
await copyText(url, "页面链接已复制");
|
|
|
|
|
},
|
|
|
|
|
[buildDocumentUrl, copyText, documentId, pageTitle],
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const handleCopyPageReference = useCallback(
|
|
|
|
|
async (mode: "inline" | "embed") => {
|
|
|
|
|
const template = mode === "inline" ? `((${documentId}))` : `{{${documentId}}}`;
|
|
|
|
|
await copyText(template, mode === "inline" ? "行内引用已复制" : "嵌入引用已复制");
|
|
|
|
|
},
|
|
|
|
|
[copyText, documentId],
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const handleUndo = useCallback(() => {
|
|
|
|
|
editorBridge?.undo?.();
|
|
|
|
|
}, [editorBridge]);
|
|
|
|
|
|
|
|
|
|
const handleRedo = useCallback(() => {
|
|
|
|
|
editorBridge?.redo?.();
|
|
|
|
|
}, [editorBridge]);
|
|
|
|
|
|
|
|
|
|
const handleDeletePage = useCallback(async () => {
|
|
|
|
|
if (readOnly) return;
|
|
|
|
|
const ok = window.confirm("确定删除该页面吗?删除后会进入垃圾桶。");
|
|
|
|
|
if (!ok) return;
|
|
|
|
|
const resp = await fetch("/api/documents/delete", {
|
|
|
|
|
method: "POST",
|
|
|
|
|
headers: { "Content-Type": "application/json" },
|
|
|
|
|
body: JSON.stringify({ documentId }),
|
|
|
|
|
});
|
|
|
|
|
if (!resp.ok) {
|
|
|
|
|
const payload = await resp.json().catch(() => ({}));
|
|
|
|
|
window.alert(payload?.error ?? "删除失败");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
router.push("/");
|
|
|
|
|
router.refresh();
|
|
|
|
|
}, [documentId, readOnly, router]);
|
|
|
|
|
|
|
|
|
|
const handleOpenMoveEmbed = useCallback(() => {
|
|
|
|
|
if (readOnly) return;
|
|
|
|
|
openMoveEmbedPicker({
|
|
|
|
|
workspaceId,
|
|
|
|
|
defaultMode: "move",
|
|
|
|
|
modes: ["move", "embed"],
|
|
|
|
|
allowRoot: true,
|
|
|
|
|
excludeIds: [documentId],
|
|
|
|
|
onPick: async (mode, targetId) => {
|
|
|
|
|
if (mode === "move") {
|
|
|
|
|
const resp = await fetch("/api/documents/move", {
|
|
|
|
|
method: "POST",
|
|
|
|
|
headers: { "Content-Type": "application/json" },
|
|
|
|
|
body: JSON.stringify({ documentId, parentId: targetId ?? null, position: 999999 }),
|
|
|
|
|
});
|
|
|
|
|
if (!resp.ok) {
|
|
|
|
|
const payload = await resp.json().catch(() => ({}));
|
|
|
|
|
window.alert(payload?.error ?? "移动失败");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
window.alert("移动成功");
|
|
|
|
|
router.refresh();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const resp = await fetch("/api/documents/embed", {
|
|
|
|
|
method: "POST",
|
|
|
|
|
headers: { "Content-Type": "application/json" },
|
|
|
|
|
body: JSON.stringify({ sourceId: documentId, targetId }),
|
|
|
|
|
});
|
|
|
|
|
if (!resp.ok) {
|
|
|
|
|
const payload = await resp.json().catch(() => ({}));
|
|
|
|
|
window.alert(payload?.error ?? "嵌入失败");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
window.alert("已嵌入到目标页面");
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}, [documentId, openMoveEmbedPicker, readOnly, router, workspaceId]);
|
|
|
|
|
|
|
|
|
|
const handleAddToTemplates = useCallback(async () => {
|
|
|
|
|
if (readOnly) return;
|
|
|
|
|
const ok = window.confirm("将该页面添加为模板?");
|
|
|
|
|
if (!ok) return;
|
|
|
|
|
const resp = await fetch("/api/documents/template", {
|
|
|
|
|
method: "POST",
|
|
|
|
|
headers: { "Content-Type": "application/json" },
|
|
|
|
|
body: JSON.stringify({ documentId, isTemplate: true }),
|
|
|
|
|
});
|
|
|
|
|
if (!resp.ok) {
|
|
|
|
|
const payload = await resp.json().catch(() => ({}));
|
|
|
|
|
window.alert(payload?.error ?? "设置模板失败");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
window.alert("已添加为模板");
|
|
|
|
|
router.refresh();
|
|
|
|
|
}, [documentId, readOnly, router]);
|
2025-11-23 10:55:04 +08:00
|
|
|
|
|
|
|
|
const formattedUpdatedAt = useMemo(() => {
|
|
|
|
|
if (!updatedAt) return "";
|
|
|
|
|
return new Date(updatedAt).toLocaleString();
|
|
|
|
|
}, [updatedAt]);
|
|
|
|
|
|
|
|
|
|
const handleExport = useCallback(() => {
|
2026-01-24 12:32:51 +08:00
|
|
|
if (disableDownload) {
|
|
|
|
|
window.alert("该页面已禁止下载");
|
|
|
|
|
return;
|
|
|
|
|
}
|
2025-11-23 10:55:04 +08:00
|
|
|
const latest = history[0];
|
|
|
|
|
if (!latest) {
|
|
|
|
|
window.alert("暂无可导出的内容");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
const payload = JSON.stringify(latest.blocks, null, 2);
|
|
|
|
|
const blob = new Blob([payload], { type: "application/json" });
|
|
|
|
|
const url = URL.createObjectURL(blob);
|
|
|
|
|
const anchor = document.createElement("a");
|
|
|
|
|
anchor.href = url;
|
|
|
|
|
anchor.download = `${title ?? "未命名页面"}-${new Date(latest.timestamp).toISOString()}.json`;
|
|
|
|
|
anchor.click();
|
|
|
|
|
URL.revokeObjectURL(url);
|
2026-01-24 12:32:51 +08:00
|
|
|
}, [disableDownload, history, title]);
|
2025-11-23 10:55:04 +08:00
|
|
|
|
2026-02-01 08:47:40 +08:00
|
|
|
const pageRootClass = cn(
|
|
|
|
|
"flex h-full overflow-hidden bg-wolai-bg",
|
|
|
|
|
options.pageFont === "song" && "wolai-page-font-song",
|
|
|
|
|
options.pageFont === "kai" && "wolai-page-font-kai",
|
|
|
|
|
options.layoutDensity === "compact" && "wolai-page-density-compact",
|
|
|
|
|
options.layoutDensity === "spacious" && "wolai-page-density-spacious",
|
|
|
|
|
options.smallText && "wolai-small-text",
|
|
|
|
|
options.hideChildPages && "wolai-hide-child-pages",
|
|
|
|
|
);
|
|
|
|
|
|
2025-11-23 10:55:04 +08:00
|
|
|
const handleSnapshot = useCallback((payload: { blocks: Json; stats: DocumentStats }) => {
|
2026-01-10 23:08:56 +08:00
|
|
|
latestBlocksRef.current = payload.blocks;
|
2025-11-23 10:55:04 +08:00
|
|
|
setHistory((prev) => {
|
|
|
|
|
const now = Date.now();
|
|
|
|
|
if (prev.length > 0 && now - prev[0].timestamp < 4000) {
|
|
|
|
|
return prev;
|
|
|
|
|
}
|
|
|
|
|
const snapshot: DocumentSnapshot = {
|
|
|
|
|
id: `${now}-${Math.random().toString(36).slice(2, 8)}`,
|
|
|
|
|
timestamp: now,
|
|
|
|
|
blocks: payload.blocks,
|
|
|
|
|
stats: payload.stats,
|
|
|
|
|
};
|
|
|
|
|
return [snapshot, ...prev].slice(0, 15);
|
|
|
|
|
});
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
const persistStatsRequest = useCallback((next: DocumentStats) => {
|
|
|
|
|
void fetch("/api/documents/stats", {
|
|
|
|
|
method: "POST",
|
|
|
|
|
headers: { "Content-Type": "application/json" },
|
2026-04-14 13:22:29 +08:00
|
|
|
body: JSON.stringify({ documentId, workspaceId, stats: next }),
|
2025-11-23 10:55:04 +08:00
|
|
|
}).catch((error) => console.error(error));
|
2026-04-14 13:22:29 +08:00
|
|
|
}, [documentId, workspaceId]);
|
2025-11-23 10:55:04 +08:00
|
|
|
|
|
|
|
|
const persistStats = useDebouncedCallback(persistStatsRequest, 1500);
|
|
|
|
|
|
|
|
|
|
const handleStatsChange = useCallback(
|
|
|
|
|
(nextStats: DocumentStats) => {
|
|
|
|
|
setStats(nextStats);
|
|
|
|
|
persistStats(nextStats);
|
|
|
|
|
},
|
|
|
|
|
[persistStats],
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const handleRestoreSnapshot = useCallback(
|
|
|
|
|
(snapshot: DocumentSnapshot) => {
|
|
|
|
|
if (!editorBridge) {
|
|
|
|
|
window.alert("编辑器尚未准备好,无法恢复历史版本");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
editorBridge.replaceWithSnapshot(snapshot.blocks);
|
|
|
|
|
setHistoryOpen(false);
|
|
|
|
|
},
|
|
|
|
|
[editorBridge],
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return (
|
2026-01-18 19:01:31 +08:00
|
|
|
<ImagePickerProvider documentId={documentId} workspaceId={workspaceId}>
|
2026-02-01 08:47:40 +08:00
|
|
|
<div className={pageRootClass} ref={pageRootRef}>
|
2025-11-23 10:55:04 +08:00
|
|
|
<div className="flex h-full flex-1 flex-col overflow-hidden">
|
2026-01-18 19:01:31 +08:00
|
|
|
<div className="border-b border-wolai-border px-12 pb-6 pt-8">
|
2025-11-23 10:55:04 +08:00
|
|
|
<div className="relative">
|
|
|
|
|
<input
|
|
|
|
|
value={pageTitle}
|
|
|
|
|
onChange={handleTitleChange}
|
|
|
|
|
onBlur={handleTitleBlur}
|
|
|
|
|
onKeyDown={handleTitleKeyDown}
|
|
|
|
|
placeholder="无标题"
|
2026-01-18 19:01:31 +08:00
|
|
|
className="w-full border-none bg-transparent text-3xl font-semibold text-wolai-text-primary outline-none focus:ring-0"
|
2025-11-23 10:55:04 +08:00
|
|
|
aria-label="页面标题"
|
2026-01-22 18:53:20 +08:00
|
|
|
disabled={options.protectEditing || readOnly}
|
2026-02-01 08:47:40 +08:00
|
|
|
spellCheck={spellCheck}
|
2025-11-23 10:55:04 +08:00
|
|
|
/>
|
|
|
|
|
</div>
|
2026-01-22 18:53:20 +08:00
|
|
|
{readOnly ? (
|
|
|
|
|
<p className="mt-1 text-sm text-gray-500">该页面为只读共享,无法编辑。</p>
|
|
|
|
|
) : options.protectEditing ? (
|
2025-11-23 10:55:04 +08:00
|
|
|
<p className="mt-1 text-sm text-[#b91c1c]">当前页面已开启编辑保护,关闭后方可修改内容。</p>
|
2026-01-22 18:53:20 +08:00
|
|
|
) : null}
|
2026-01-18 19:01:31 +08:00
|
|
|
<p className="text-sm text-wolai-text-secondary">最近更新:{formattedUpdatedAt}</p>
|
2025-11-23 10:55:04 +08:00
|
|
|
</div>
|
|
|
|
|
<div className="flex-1 overflow-y-auto px-12 py-6">
|
2026-01-10 10:35:21 +08:00
|
|
|
{contentLoading ? (
|
|
|
|
|
showContentLoadingIndicator ? (
|
|
|
|
|
<div className="flex h-64 items-center justify-center text-sm text-gray-400">
|
|
|
|
|
页面内容加载中...
|
|
|
|
|
</div>
|
|
|
|
|
) : (
|
|
|
|
|
<div className="h-64" />
|
|
|
|
|
)
|
|
|
|
|
) : contentError ? (
|
|
|
|
|
<div className="flex h-64 flex-col items-center justify-center gap-2 text-sm text-red-600">
|
|
|
|
|
<div>{contentError}</div>
|
|
|
|
|
<button
|
|
|
|
|
type="button"
|
|
|
|
|
className="rounded-md border border-red-200 bg-red-50 px-3 py-1 text-sm text-red-700 hover:bg-red-100"
|
|
|
|
|
onClick={() => {
|
|
|
|
|
setContentError(null);
|
|
|
|
|
setContentLoading(true);
|
|
|
|
|
setContentReloadKey((prev) => prev + 1);
|
|
|
|
|
}}
|
|
|
|
|
>
|
|
|
|
|
重试
|
|
|
|
|
</button>
|
|
|
|
|
</div>
|
|
|
|
|
) : (
|
|
|
|
|
<BlockNoteEditor
|
|
|
|
|
documentId={documentId}
|
|
|
|
|
workspaceId={workspaceId}
|
|
|
|
|
initialContent={content}
|
2026-04-15 03:06:29 +08:00
|
|
|
initialRevision={contentRevision}
|
|
|
|
|
initialConflictDetectionKey={conflictDetectionKey}
|
2026-01-10 10:35:21 +08:00
|
|
|
pageOptions={options}
|
2026-01-22 18:53:20 +08:00
|
|
|
readOnly={readOnly}
|
2026-01-10 10:35:21 +08:00
|
|
|
onStatsChange={handleStatsChange}
|
|
|
|
|
onSnapshot={handleSnapshot}
|
2026-02-01 08:47:40 +08:00
|
|
|
onCloseToc={closeToc}
|
2026-04-15 03:06:29 +08:00
|
|
|
onPersistedMetaChange={({ revision, conflictDetectionKey: nextConflictDetectionKey }) => {
|
|
|
|
|
setContentRevision(revision);
|
|
|
|
|
setConflictDetectionKey(nextConflictDetectionKey);
|
|
|
|
|
}}
|
2026-01-10 10:35:21 +08:00
|
|
|
/>
|
|
|
|
|
)}
|
2026-02-01 08:47:40 +08:00
|
|
|
<PageBacklinksPanel
|
|
|
|
|
className="mt-10"
|
|
|
|
|
workspaceId={workspaceId}
|
|
|
|
|
documentId={documentId}
|
|
|
|
|
defaultCollapsed={options.collapseBacklinks}
|
|
|
|
|
/>
|
2025-11-23 10:55:04 +08:00
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
{showInspector && (
|
|
|
|
|
<PageOptionsSidebar
|
|
|
|
|
documentId={documentId}
|
|
|
|
|
options={options}
|
|
|
|
|
stats={stats}
|
|
|
|
|
onToggle={toggleOption}
|
2026-02-01 08:47:40 +08:00
|
|
|
onSetPageFont={handleSetPageFont}
|
|
|
|
|
onSetLayoutDensity={handleSetLayoutDensity}
|
|
|
|
|
onSetEmbedDefaultToCursor={handleSetEmbedDefaultToCursor}
|
|
|
|
|
onClearEmbedDefault={handleClearEmbedDefault}
|
2025-11-23 10:55:04 +08:00
|
|
|
onExport={handleExport}
|
|
|
|
|
onOpenHistory={() => setHistoryOpen(true)}
|
2026-02-01 08:47:40 +08:00
|
|
|
onOpenComments={() => openCommentsForPage({ workspaceId, documentId })}
|
|
|
|
|
onUndo={handleUndo}
|
|
|
|
|
onRedo={handleRedo}
|
|
|
|
|
onDeletePage={handleDeletePage}
|
|
|
|
|
onOpenMoveEmbedPicker={handleOpenMoveEmbed}
|
|
|
|
|
onCopyPageLink={handleCopyPageLink}
|
|
|
|
|
onCopyPageReference={handleCopyPageReference}
|
|
|
|
|
onAddToTemplates={handleAddToTemplates}
|
2025-11-23 10:55:04 +08:00
|
|
|
/>
|
|
|
|
|
)}
|
|
|
|
|
</div>
|
|
|
|
|
<DocumentHistoryDrawer
|
|
|
|
|
open={historyOpen}
|
|
|
|
|
onOpenChange={setHistoryOpen}
|
|
|
|
|
history={history}
|
|
|
|
|
onRestore={handleRestoreSnapshot}
|
|
|
|
|
/>
|
2026-02-01 08:47:40 +08:00
|
|
|
<DocumentCommentsDrawer />
|
2026-01-10 23:08:56 +08:00
|
|
|
<DocumentAiAgentPanel documentId={documentId} getLatestBlocks={() => latestBlocksRef.current} />
|
2025-11-23 10:55:04 +08:00
|
|
|
</ImagePickerProvider>
|
|
|
|
|
);
|
|
|
|
|
}
|