Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

refactor(web): extract editor document actions

tianma-if271837ed1374
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index 4dcfcd90..ec69857d 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -99,7 +99,7 @@ import { sanitizeAndScopeCss } from "@/lib/css-sandbox";
import { RevisionHistoryDialog } from "./dialogs/RevisionHistoryDialog";
import { ExternalLinkDialog } from "./dialogs/ExternalLinkDialog";
import { memoShareQueryKey, ShareMemoDialog } from "./dialogs/ShareMemoDialog";
-import { ShareNoteImageDialog, type ShareNoteImageSource } from "./dialogs/ShareNoteImageDialog";
+import { ShareNoteImageDialog } from "./dialogs/ShareNoteImageDialog";
import { AiAssistantDialog, type AiAssistantAnchor } from "./dialogs/AiAssistantDialog";
import { api } from "@/lib/api";
import { isDesktopResourceRuntime, stageDesktopResource, toDesktopResourceDownloadUrl, toDesktopResourceUrl } from "@/lib/desktop-resources";
@@ -154,15 +154,9 @@ import {
type MemoDocumentActionRequest,
type ShortcutSettings,
} from "@/lib/app-helpers";
-import { copyEditorToWeChat, copyMarkdownToWeChat } from "@/lib/wechat-copy";
import { isPaperEditorTheme, publishEditorCssVars, resolvePaperEditorTheme } from "@/lib/publish-layout";
import { ThemeBlock } from "./ThemeBlock";
import { EditorPhonePreview, PhonePreviewGlyph } from "./EditorPhonePreview";
-import { downloadMarkdownFile } from "@/lib/note-markdown-export";
-import { NOTE_HTML_FULL_STYLES } from "@/lib/note-html-export-assets";
-import { downloadNoteHtmlFile, getHtmlImageEmbedNoticeKind } from "@/lib/note-html-export";
-import { openNotePrintPreview, serializeNoteDocumentForPrint } from "@/lib/note-print";
-import type { NoteImageFormat } from "@/lib/note-image-export";
import {
applyPlainTextTab,
getAiSlashCommandStart,
@@ -225,6 +219,7 @@ import { useEditorSaveStatus } from "./editor/useEditorSaveStatus";
import { getEditorSaveChrome } from "./editor/editor-save-chrome";
import { classifyEditorSaveFailure, shouldLeaveEditorAfterSaveError } from "./editor/editor-save-failure";
import { useEditorSaveConflictActions } from "./editor/useEditorSaveConflictActions";
+import { useEditorDocumentActions } from "./editor/useEditorDocumentActions";
import { useEditorNoteSearchController } from "./editor/useEditorNoteSearchController";
import { EditorNoteLinkPicker } from "./editor/EditorNoteLinkPicker";
import { EditorResourceDialogs } from "./editor/EditorResourceDialogs";
@@ -423,9 +418,6 @@ const RichEditorPane = ({
const [imageUploadState, setImageUploadState] = useState<"idle" | "compressing" | "uploading" | "error">("idle");
const [imagePreview, setImagePreview] = useState<ImagePreviewRequestDetail | null>(null);
const [historyOpen, setHistoryOpen] = useState(false);
- const [shareOpen, setShareOpen] = useState(false);
- const [imageShareOpen, setImageShareOpen] = useState(false);
- const [imageShareSource, setImageShareSource] = useState<ShareNoteImageSource | null>(null);
const [aiAssistantOpen, setAiAssistantOpen] = useState(false);
const [aiAssistantAnchor, setAiAssistantAnchor] = useState<AiAssistantAnchor>({ left: 24, placement: "below", top: 96 });
const aiBubbleMenu = useAiBubbleMenu(aiAssistantOpen);
@@ -477,7 +469,6 @@ const RichEditorPane = ({
const [mobileToolbarOpen, setMobileToolbarOpen] = useState(false);
const [editorOutlineCollapsed, setEditorOutlineCollapsed] = useState(readEditorOutlineCollapsedPreference);
const [phonePreviewOpen, setPhonePreviewOpen] = useState(readEditorPhonePreviewPreference);
- const [wechatCopyState, setWechatCopyState] = useState<"idle" | "copying" | "copied" | "error">("idle");
const [memoIdCopyNotice, setMemoIdCopyNotice] = useState<{ status: "copied" | "error"; id: string } | null>(null);
const handledSaveAndSyncTokenRef = useRef(saveAndSyncToken);
const handledReadingProtectionToggleTokenRef = useRef(readingProtectionToggleToken);
@@ -2470,281 +2461,44 @@ const RichEditorPane = ({
markDirty();
}, [markDirty]);
- const handleCopyToWeChat = useCallback(async () => {
- if (!isEditorReady(editor)) {
- return;
- }
-
- setWechatCopyState("copying");
- try {
- if (useMarkdownSourceEditor) {
- await copyMarkdownToWeChat(markdownSource);
- } else {
- await copyEditorToWeChat(editor);
- }
- setWechatCopyState("copied");
- window.setTimeout(() => setWechatCopyState("idle"), 2200);
- } catch {
- setWechatCopyState("error");
- window.setTimeout(() => setWechatCopyState("idle"), 2600);
- }
- }, [editor, markdownSource, useMarkdownSourceEditor]);
-
- const handleCopyMemoId = useCallback(async () => {
- if (!memo || isLocalMemoId(memo.id)) {
- return;
- }
- const copied = await copyTextToClipboard(memo.id);
- setMemoIdCopyNotice({ status: copied ? "copied" : "error", id: memo.id });
- window.setTimeout(() => setMemoIdCopyNotice(null), copied ? 2200 : 3000);
- }, [memo]);
-
- const handleExportPdf = useCallback((preopenedWindow?: Window | null) => {
- if (!isEditorReady(editor) || !memo) {
- return;
- }
-
- if (preopenedWindow === null) {
- window.alert(t("editor.pdfExport.popupBlocked"));
- return;
- }
-
- const currentDocument = useMobilePlainTextEditor
- ? markdownToDoc(getMobilePlainTextValue())
- : useMarkdownSourceEditor
- ? markdownToDoc(markdownSource)
- : editor.getJSON() as TiptapDoc;
- const html = serializeNoteDocumentForPrint(editor, currentDocument);
- const opened = openNotePrintPreview(
- {
- title: title.trim() || t("common.untitledMemo"),
- notebook: notebookOptions.find((notebook) => notebook.id === memo.notebookId)?.name ?? "",
- tags: parseTagsText(tagsText),
- updatedAt: formatDateTime(memo.updatedAt),
- html,
- language: i18n.resolvedLanguage ?? i18n.language,
- labels: {
- close: t("editor.pdfExport.close"),
- error: t("editor.pdfExport.error"),
- hint: t("editor.pdfExport.hint"),
- preparing: t("editor.pdfExport.preparing"),
- print: t("editor.pdfExport.print"),
- ready: t("editor.pdfExport.ready"),
- },
- },
- preopenedWindow ?? undefined,
- );
-
- if (!opened) {
- window.alert(t("editor.pdfExport.popupBlocked"));
- }
- }, [
- editor,
- getMobilePlainTextValue,
- i18n.language,
- i18n.resolvedLanguage,
- markdownSource,
- markDirtyStatus,
- memo,
- notebookOptions,
- t,
- tagsText,
- title,
- useMarkdownSourceEditor,
- useMobilePlainTextEditor,
- ]);
-
- const handleExportMarkdown = useCallback(() => {
- if (!isEditorReady(editor) || !memo) {
- return;
- }
-
- const markdown = useMobilePlainTextEditor
- ? getMobilePlainTextValue()
- : useMarkdownSourceEditor
- ? markdownSource
- : docToMarkdown(editor.getJSON() as TiptapDoc);
- downloadMarkdownFile(
- markdown,
- title,
- t("common.untitledMemo")
- );
- }, [
- editor,
- getMobilePlainTextValue,
- markdownSource,
- memo,
- t,
- title,
- useMarkdownSourceEditor,
- useMobilePlainTextEditor,
- ]);
-
- const handleExportHtml = useCallback(async () => {
- if (!isEditorReady(editor) || !memo) {
- return;
- }
-
- const currentDocument = useMobilePlainTextEditor
- ? markdownToDoc(getMobilePlainTextValue())
- : useMarkdownSourceEditor
- ? markdownToDoc(markdownSource)
- : editor.getJSON() as TiptapDoc;
- const bodyHtml = serializeNoteDocumentForPrint(editor, currentDocument);
-
- try {
- const { images } = await downloadNoteHtmlFile({
- bodyHtml,
- title: title.trim() || t("common.untitledMemo"),
- notebook: notebookOptions.find((notebook) => notebook.id === memo.notebookId)?.name ?? "",
- tags: parseTagsText(tagsText),
- updatedAt: formatDateTime(memo.updatedAt),
- language: i18n.resolvedLanguage ?? i18n.language,
- fallbackTitle: t("common.untitledMemo"),
- styles: NOTE_HTML_FULL_STYLES,
- });
-
- const noticeKind = getHtmlImageEmbedNoticeKind(images);
- if (noticeKind === "partial") {
- window.alert(t("editor.htmlExport.imageEmbedPartial", {
- embedded: images.embedded,
- total: images.total,
- failed: images.failed,
- }));
- } else if (noticeKind === "failed-all") {
- window.alert(t("editor.htmlExport.imageEmbedFailed", {
- total: images.total,
- }));
- }
- } catch {
- window.alert(t("editor.htmlExport.error"));
- }
- }, [
- editor,
- getMobilePlainTextValue,
- i18n.language,
- i18n.resolvedLanguage,
- markdownSource,
- memo,
- notebookOptions,
- t,
- tagsText,
- title,
- useMarkdownSourceEditor,
- useMobilePlainTextEditor,
- ]);
-
- const buildImageExportOptions = useCallback((format: NoteImageFormat) => {
- if (!isEditorReady(editor) || !memo) return;
- const currentDocument = useMobilePlainTextEditor
- ? markdownToDoc(getMobilePlainTextValue())
- : useMarkdownSourceEditor
- ? markdownToDoc(markdownSource)
- : editor.getJSON() as TiptapDoc;
- return {
- bodyHtml: serializeNoteDocumentForPrint(editor, currentDocument),
- title: title.trim() || t("common.untitledMemo"),
- notebook: notebookOptions.find((notebook) => notebook.id === memo.notebookId)?.name ?? "",
- tags: parseTagsText(tagsText),
- updatedAt: formatDateTime(memo.updatedAt),
- language: i18n.resolvedLanguage ?? i18n.language,
- fallbackTitle: t("common.untitledMemo"),
- format,
- styles: NOTE_HTML_FULL_STYLES,
- };
- }, [
+ const {
+ handleCopyToWeChat,
+ handleExportHtml,
+ handleExportMarkdown,
+ handleExportPdf,
+ handleOpenImageShare,
+ handleSaveAsTemplate,
+ imageShareOpen,
+ imageShareSource,
+ setImageShareOpen,
+ setShareOpen,
+ shareOpen,
+ wechatCopyState,
+ } = useEditorDocumentActions({
+ documentActionRequest,
editor,
+ effectiveReadOnly,
getMobilePlainTextValue,
- i18n.language,
- i18n.resolvedLanguage,
+ hydratedEditorMemoId,
markdownSource,
memo,
- notebookOptions,
- t,
+ notebookName: notebookOptions.find((notebook) => notebook.id === memo?.notebookId)?.name ?? "",
+ onDocumentActionConsumed,
+ onSaveAsTemplate,
tagsText,
title,
useMarkdownSourceEditor,
useMobilePlainTextEditor,
- ]);
-
- const handleOpenImageShare = useCallback(() => {
- const options = buildImageExportOptions("png");
- if (!options) return;
- const { format: _format, ...source } = options;
- setImageShareSource(source);
- setImageShareOpen(true);
- }, [buildImageExportOptions]);
-
- const handleSaveAsTemplate = useCallback(() => {
- if (!memo || effectiveReadOnly) {
- return;
- }
-
- const name = window.prompt(t("templates.templateNamePrompt"), memo.title || "");
- if (!name?.trim()) {
- return;
- }
-
- const currentMarkdown = useMobilePlainTextEditor
- ? getMobilePlainTextValue()
- : isEditorReady(editor)
- ? docToMarkdown(editor.getJSON() as TiptapDoc)
- : memo.contentMarkdown;
- const currentTemplateMemo: MemoDetail = {
- ...memo,
- title,
- tags: parseTagsText(tagsText),
- contentJson: markdownToDoc(currentMarkdown),
- contentMarkdown: currentMarkdown,
- };
- void onSaveAsTemplate(currentTemplateMemo, name.trim());
- }, [editor, effectiveReadOnly, getMobilePlainTextValue, memo, onSaveAsTemplate, t, tagsText, title, useMobilePlainTextEditor]);
+ });
- useEffect(() => {
- if (
- !documentActionRequest ||
- documentActionRequest.memoId !== memo?.id ||
- hydratedEditorMemoId !== memo.id ||
- !isEditorReady(editor)
- ) {
+ const handleCopyMemoId = useCallback(async () => {
+ if (!memo || isLocalMemoId(memo.id)) {
return;
}
-
- onDocumentActionConsumed?.(documentActionRequest.id);
-
- switch (documentActionRequest.action) {
- case "share":
- if (!effectiveReadOnly) setShareOpen(true);
- break;
- case "export-markdown":
- handleExportMarkdown();
- break;
- case "export-html":
- void handleExportHtml();
- break;
- case "export-pdf":
- handleExportPdf(documentActionRequest.printWindow);
- break;
- case "share-image":
- handleOpenImageShare();
- break;
- case "save-as-template":
- handleSaveAsTemplate();
- break;
- }
- }, [
- documentActionRequest,
- editor,
- effectiveReadOnly,
- handleExportHtml,
- handleExportMarkdown,
- handleExportPdf,
- handleOpenImageShare,
- handleSaveAsTemplate,
- hydratedEditorMemoId,
- memo,
- onDocumentActionConsumed,
- ]);
+ const copied = await copyTextToClipboard(memo.id);
+ setMemoIdCopyNotice({ status: copied ? "copied" : "error", id: memo.id });
+ window.setTimeout(() => setMemoIdCopyNotice(null), copied ? 2200 : 3000);
+ }, [memo]);
useEffect(() => {
if (!useMobilePlainTextEditor) {
diff --git a/apps/web/src/components/editor/editor-document-actions.test.mjs b/apps/web/src/components/editor/editor-document-actions.test.mjs
new file mode 100644
index 00000000..342994bd
--- /dev/null
+++ b/apps/web/src/components/editor/editor-document-actions.test.mjs
@@ -0,0 +1,84 @@
+import { describe, expect, test } from "bun:test";
+import { dispatchMemoDocumentAction, resolveEditorExportContent } from "./editor-document-actions.ts";
+
+const richDoc = {
+ type: "doc",
+ content: [{ type: "paragraph", content: [{ type: "text", text: "hello" }] }],
+};
+
+const readyEditor = {
+ isDestroyed: false,
+ extensionManager: {},
+ getJSON: () => richDoc,
+};
+
+describe("resolveEditorExportContent", () => {
+ test("uses the live TipTap document in rich-text mode", () => {
+ expect(resolveEditorExportContent({
+ editor: readyEditor,
+ getMobilePlainTextValue: () => "plain",
+ markdownSource: "source",
+ useMarkdownSourceEditor: false,
+ useMobilePlainTextEditor: false,
+ })).toEqual({
+ document: richDoc,
+ markdown: "hello",
+ });
+ });
+
+ test("parses Markdown source when the Markdown editor is active", () => {
+ const content = resolveEditorExportContent({
+ editor: readyEditor,
+ getMobilePlainTextValue: () => "plain",
+ markdownSource: "from-source",
+ useMarkdownSourceEditor: true,
+ useMobilePlainTextEditor: false,
+ });
+ expect(content?.markdown).toBe("from-source");
+ expect(content?.document.content[0].content[0].text).toBe("from-source");
+ });
+
+ test("prefers the mobile plain-text buffer over Markdown source", () => {
+ const content = resolveEditorExportContent({
+ editor: readyEditor,
+ getMobilePlainTextValue: () => "from-plain",
+ markdownSource: "from-source",
+ useMarkdownSourceEditor: true,
+ useMobilePlainTextEditor: true,
+ });
+ expect(content?.markdown).toBe("from-plain");
+ });
+
+ test("returns null when the editor is not ready", () => {
+ expect(resolveEditorExportContent({
+ editor: null,
+ getMobilePlainTextValue: () => "plain",
+ markdownSource: "source",
+ useMarkdownSourceEditor: false,
+ useMobilePlainTextEditor: false,
+ })).toBeNull();
+ });
+});
+
+describe("dispatchMemoDocumentAction", () => {
+ test("routes each document action to a single handler", () => {
+ const calls = [];
+ const handlers = {
+ exportHtml: () => calls.push("html"),
+ exportMarkdown: () => calls.push("markdown"),
+ exportPdf: (printWindow) => calls.push(["pdf", printWindow]),
+ saveAsTemplate: () => calls.push("template"),
+ share: () => calls.push("share"),
+ shareImage: () => calls.push("image"),
+ };
+
+ dispatchMemoDocumentAction("share", handlers);
+ dispatchMemoDocumentAction("export-markdown", handlers);
+ dispatchMemoDocumentAction("export-html", handlers);
+ dispatchMemoDocumentAction("export-pdf", handlers, null);
+ dispatchMemoDocumentAction("share-image", handlers);
+ dispatchMemoDocumentAction("save-as-template", handlers);
+
+ expect(calls).toEqual(["share", "markdown", "html", ["pdf", null], "image", "template"]);
+ });
+});
diff --git a/apps/web/src/components/editor/editor-document-actions.ts b/apps/web/src/components/editor/editor-document-actions.ts
new file mode 100644
index 00000000..3a7a71bb
--- /dev/null
+++ b/apps/web/src/components/editor/editor-document-actions.ts
@@ -0,0 +1,73 @@
+import { docToMarkdown, markdownToDoc, type TiptapDoc } from "@edgeever/shared";
+import type { MemoDocumentAction } from "@/lib/app-helpers";
+import type { Editor } from "@tiptap/react";
+import { isEditorReady } from "./editor-pane-helpers";
+
+export type EditorExportContent = {
+ document: TiptapDoc;
+ markdown: string;
+};
+
+export const resolveEditorExportContent = ({
+ editor,
+ getMobilePlainTextValue,
+ markdownSource,
+ useMarkdownSourceEditor,
+ useMobilePlainTextEditor,
+}: {
+ editor: Editor | null;
+ getMobilePlainTextValue: () => string;
+ markdownSource: string;
+ useMarkdownSourceEditor: boolean;
+ useMobilePlainTextEditor: boolean;
+}): EditorExportContent | null => {
+ if (!isEditorReady(editor)) {
+ return null;
+ }
+
+ if (useMobilePlainTextEditor) {
+ const markdown = getMobilePlainTextValue();
+ return { markdown, document: markdownToDoc(markdown) };
+ }
+
+ if (useMarkdownSourceEditor) {
+ return { markdown: markdownSource, document: markdownToDoc(markdownSource) };
+ }
+
+ const document = editor.getJSON() as TiptapDoc;
+ return { markdown: docToMarkdown(document), document };
+};
+
+export const dispatchMemoDocumentAction = (
+ action: MemoDocumentAction,
+ handlers: {
+ exportHtml: () => void;
+ exportMarkdown: () => void;
+ exportPdf: (printWindow?: Window | null) => void;
+ saveAsTemplate: () => void;
+ share: () => void;
+ shareImage: () => void;
+ },
+ printWindow?: Window | null,
+) => {
+ switch (action) {
+ case "share":
+ handlers.share();
+ break;
+ case "export-markdown":
+ handlers.exportMarkdown();
+ break;
+ case "export-html":
+ handlers.exportHtml();
+ break;
+ case "export-pdf":
+ handlers.exportPdf(printWindow);
+ break;
+ case "share-image":
+ handlers.shareImage();
+ break;
+ case "save-as-template":
+ handlers.saveAsTemplate();
+ break;
+ }
+};
diff --git a/apps/web/src/components/editor/useEditorDocumentActions.ts b/apps/web/src/components/editor/useEditorDocumentActions.ts
new file mode 100644
index 00000000..a2f13c9e
--- /dev/null
+++ b/apps/web/src/components/editor/useEditorDocumentActions.ts
@@ -0,0 +1,269 @@
+import { useCallback, useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { Editor } from "@tiptap/react";
+import { docToMarkdown, markdownToDoc, type MemoDetail, type TiptapDoc } from "@edgeever/shared";
+import type { MemoDocumentActionRequest } from "@/lib/app-helpers";
+import { downloadMarkdownFile } from "@/lib/note-markdown-export";
+import { downloadNoteHtmlFile, getHtmlImageEmbedNoticeKind } from "@/lib/note-html-export";
+import { NOTE_HTML_FULL_STYLES } from "@/lib/note-html-export-assets";
+import { openNotePrintPreview, serializeNoteDocumentForPrint } from "@/lib/note-print";
+import type { NoteImageFormat } from "@/lib/note-image-export";
+import { copyEditorToWeChat, copyMarkdownToWeChat } from "@/lib/wechat-copy";
+import { formatDateTime, parseTagsText } from "@/lib/utils";
+import type { ShareNoteImageSource } from "@/components/dialogs/ShareNoteImageDialog";
+import { dispatchMemoDocumentAction, resolveEditorExportContent } from "./editor-document-actions";
+import { isEditorReady } from "./editor-pane-helpers";
+
+export type WechatCopyState = "idle" | "copying" | "copied" | "error";
+
+export const useEditorDocumentActions = ({
+ documentActionRequest,
+ editor,
+ effectiveReadOnly,
+ getMobilePlainTextValue,
+ hydratedEditorMemoId,
+ markdownSource,
+ memo,
+ notebookName,
+ onDocumentActionConsumed,
+ onSaveAsTemplate,
+ tagsText,
+ title,
+ useMarkdownSourceEditor,
+ useMobilePlainTextEditor,
+}: {
+ documentActionRequest?: MemoDocumentActionRequest | null;
+ editor: Editor | null;
+ effectiveReadOnly: boolean;
+ getMobilePlainTextValue: () => string;
+ hydratedEditorMemoId: string | null;
+ markdownSource: string;
+ memo: MemoDetail | null;
+ notebookName: string;
+ onDocumentActionConsumed?: (requestId: number) => void;
+ onSaveAsTemplate: (memo: MemoDetail, name: string) => Promise<void>;
+ tagsText: string;
+ title: string;
+ useMarkdownSourceEditor: boolean;
+ useMobilePlainTextEditor: boolean;
+}) => {
+ const { t, i18n } = useTranslation();
+ const [shareOpen, setShareOpen] = useState(false);
+ const [imageShareOpen, setImageShareOpen] = useState(false);
+ const [imageShareSource, setImageShareSource] = useState<ShareNoteImageSource | null>(null);
+ const [wechatCopyState, setWechatCopyState] = useState<WechatCopyState>("idle");
+
+ const resolveExportContent = useCallback(
+ () => resolveEditorExportContent({
+ editor,
+ getMobilePlainTextValue,
+ markdownSource,
+ useMarkdownSourceEditor,
+ useMobilePlainTextEditor,
+ }),
+ [editor, getMobilePlainTextValue, markdownSource, useMarkdownSourceEditor, useMobilePlainTextEditor],
+ );
+
+ const handleCopyToWeChat = useCallback(async () => {
+ if (!isEditorReady(editor)) {
+ return;
+ }
+
+ setWechatCopyState("copying");
+ try {
+ if (useMarkdownSourceEditor) {
+ await copyMarkdownToWeChat(markdownSource);
+ } else {
+ await copyEditorToWeChat(editor);
+ }
+ setWechatCopyState("copied");
+ window.setTimeout(() => setWechatCopyState("idle"), 2200);
+ } catch {
+ setWechatCopyState("error");
+ window.setTimeout(() => setWechatCopyState("idle"), 2600);
+ }
+ }, [editor, markdownSource, useMarkdownSourceEditor]);
+
+ const handleExportPdf = useCallback((preopenedWindow?: Window | null) => {
+ const content = resolveExportContent();
+ if (!isEditorReady(editor) || !content || !memo) {
+ return;
+ }
+
+ if (preopenedWindow === null) {
+ window.alert(t("editor.pdfExport.popupBlocked"));
+ return;
+ }
+
+ const opened = openNotePrintPreview(
+ {
+ title: title.trim() || t("common.untitledMemo"),
+ notebook: notebookName,
+ tags: parseTagsText(tagsText),
+ updatedAt: formatDateTime(memo.updatedAt),
+ html: serializeNoteDocumentForPrint(editor, content.document),
+ language: i18n.resolvedLanguage ?? i18n.language,
+ labels: {
+ close: t("editor.pdfExport.close"),
+ error: t("editor.pdfExport.error"),
+ hint: t("editor.pdfExport.hint"),
+ preparing: t("editor.pdfExport.preparing"),
+ print: t("editor.pdfExport.print"),
+ ready: t("editor.pdfExport.ready"),
+ },
+ },
+ preopenedWindow ?? undefined,
+ );
+
+ if (!opened) {
+ window.alert(t("editor.pdfExport.popupBlocked"));
+ }
+ }, [editor, i18n.language, i18n.resolvedLanguage, memo, notebookName, resolveExportContent, t, tagsText, title]);
+
+ const handleExportMarkdown = useCallback(() => {
+ const content = resolveExportContent();
+ if (!content || !memo) {
+ return;
+ }
+
+ downloadMarkdownFile(content.markdown, title, t("common.untitledMemo"));
+ }, [memo, resolveExportContent, t, title]);
+
+ const handleExportHtml = useCallback(async () => {
+ const content = resolveExportContent();
+ if (!isEditorReady(editor) || !content || !memo) {
+ return;
+ }
+
+ try {
+ const { images } = await downloadNoteHtmlFile({
+ bodyHtml: serializeNoteDocumentForPrint(editor, content.document),
+ title: title.trim() || t("common.untitledMemo"),
+ notebook: notebookName,
+ tags: parseTagsText(tagsText),
+ updatedAt: formatDateTime(memo.updatedAt),
+ language: i18n.resolvedLanguage ?? i18n.language,
+ fallbackTitle: t("common.untitledMemo"),
+ styles: NOTE_HTML_FULL_STYLES,
+ });
+
+ const noticeKind = getHtmlImageEmbedNoticeKind(images);
+ if (noticeKind === "partial") {
+ window.alert(t("editor.htmlExport.imageEmbedPartial", {
+ embedded: images.embedded,
+ total: images.total,
+ failed: images.failed,
+ }));
+ } else if (noticeKind === "failed-all") {
+ window.alert(t("editor.htmlExport.imageEmbedFailed", {
+ total: images.total,
+ }));
+ }
+ } catch {
+ window.alert(t("editor.htmlExport.error"));
+ }
+ }, [editor, i18n.language, i18n.resolvedLanguage, memo, notebookName, resolveExportContent, t, tagsText, title]);
+
+ const buildImageExportOptions = useCallback((format: NoteImageFormat) => {
+ const content = resolveExportContent();
+ if (!isEditorReady(editor) || !content || !memo) return;
+ return {
+ bodyHtml: serializeNoteDocumentForPrint(editor, content.document),
+ title: title.trim() || t("common.untitledMemo"),
+ notebook: notebookName,
+ tags: parseTagsText(tagsText),
+ updatedAt: formatDateTime(memo.updatedAt),
+ language: i18n.resolvedLanguage ?? i18n.language,
+ fallbackTitle: t("common.untitledMemo"),
+ format,
+ styles: NOTE_HTML_FULL_STYLES,
+ };
+ }, [editor, i18n.language, i18n.resolvedLanguage, memo, notebookName, resolveExportContent, t, tagsText, title]);
+
+ const handleOpenImageShare = useCallback(() => {
+ const options = buildImageExportOptions("png");
+ if (!options) return;
+ const { format: _format, ...source } = options;
+ setImageShareSource(source);
+ setImageShareOpen(true);
+ }, [buildImageExportOptions]);
+
+ const handleSaveAsTemplate = useCallback(() => {
+ if (!memo || effectiveReadOnly) {
+ return;
+ }
+
+ const name = window.prompt(t("templates.templateNamePrompt"), memo.title || "");
+ if (!name?.trim()) {
+ return;
+ }
+
+ const currentMarkdown = useMobilePlainTextEditor
+ ? getMobilePlainTextValue()
+ : isEditorReady(editor)
+ ? docToMarkdown(editor.getJSON() as TiptapDoc)
+ : memo.contentMarkdown;
+ const currentTemplateMemo: MemoDetail = {
+ ...memo,
+ title,
+ tags: parseTagsText(tagsText),
+ contentJson: markdownToDoc(currentMarkdown),
+ contentMarkdown: currentMarkdown,
+ };
+ void onSaveAsTemplate(currentTemplateMemo, name.trim());
+ }, [editor, effectiveReadOnly, getMobilePlainTextValue, memo, onSaveAsTemplate, t, tagsText, title, useMobilePlainTextEditor]);
+
+ useEffect(() => {
+ if (
+ !documentActionRequest ||
+ documentActionRequest.memoId !== memo?.id ||
+ hydratedEditorMemoId !== memo.id ||
+ !isEditorReady(editor)
+ ) {
+ return;
+ }
+
+ onDocumentActionConsumed?.(documentActionRequest.id);
+ dispatchMemoDocumentAction(
+ documentActionRequest.action,
+ {
+ exportHtml: () => void handleExportHtml(),
+ exportMarkdown: handleExportMarkdown,
+ exportPdf: handleExportPdf,
+ saveAsTemplate: handleSaveAsTemplate,
+ share: () => {
+ if (!effectiveReadOnly) setShareOpen(true);
+ },
+ shareImage: handleOpenImageShare,
+ },
+ documentActionRequest.printWindow,
+ );
+ }, [
+ documentActionRequest,
+ editor,
+ effectiveReadOnly,
+ handleExportHtml,
+ handleExportMarkdown,
+ handleExportPdf,
+ handleOpenImageShare,
+ handleSaveAsTemplate,
+ hydratedEditorMemoId,
+ memo,
+ onDocumentActionConsumed,
+ ]);
+
+ return {
+ handleCopyToWeChat,
+ handleExportHtml,
+ handleExportMarkdown,
+ handleExportPdf,
+ handleOpenImageShare,
+ handleSaveAsTemplate,
+ imageShareOpen,
+ imageShareSource,
+ setImageShareOpen,
+ setShareOpen,
+ shareOpen,
+ wechatCopyState,
+ };
+};