Skip to content

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

fix(mobile): enter note editing without remounting the viewer

tianma-if8e2dfec1b4f0
diff --git a/apps/mobile/src/components/LocalTiptapEditor.tsx b/apps/mobile/src/components/LocalTiptapEditor.tsx
index 46a3046b..e031af0c 100644
--- a/apps/mobile/src/components/LocalTiptapEditor.tsx
+++ b/apps/mobile/src/components/LocalTiptapEditor.tsx
@@ -142,37 +142,21 @@ type LocalTiptapEditorSharedProps = {
ref: Ref<LocalTiptapEditorRef>;
locale: "zh-CN" | "en-US";
theme: "light" | "dark";
-};
-
-/** Editable note body with toolbar (create / rich edit). */
-type LocalTiptapEditorModeProps = LocalTiptapEditorSharedProps & {
- mode?: "editor";
+ /** Live-switchable. The same DomWebView stays mounted across viewer → editor. */
+ mode?: "editor" | "viewer";
aiPromptsJson?: string;
autoFocus?: boolean;
- onChange: (content: EditorDoc) => Promise<void>;
- onPickImage: () => Promise<void>;
+ onChange?: (content: EditorDoc) => Promise<void>;
+ onPickImage?: () => Promise<void>;
onAiRequest?: (requestJson: string) => Promise<void>;
onAiCancel?: (requestId: string) => Promise<void>;
- onReady: (startupMs: number) => Promise<void>;
-};
-
-/**
- * Read-only note body that reuses the same TipTap schema / image loading as the
- * editor. Used by the native memo detail chrome (scheme C).
- */
-type LocalTiptapViewerModeProps = LocalTiptapEditorSharedProps & {
- mode: "viewer";
- /** Parsed visual diagram IR for the native X6 read-only viewer. */
visualDiagramJson?: string;
- /** Hides code affordances when a damaged diagram falls back to Mermaid. */
visualDiagramNote?: boolean;
- /** JSON: `{ alt: string; source: string }` for fullscreen image preview. */
onImagePreview?: (payloadJson: string) => Promise<void>;
- /** Enter note editing after a deliberate double tap on ordinary body content. */
onDoublePress?: () => Promise<void>;
};
-type LocalTiptapEditorProps = LocalTiptapEditorModeProps | LocalTiptapViewerModeProps;
+type LocalTiptapEditorProps = LocalTiptapEditorSharedProps;
type MermaidRendererProps = {
diagramsJson: string;
@@ -649,6 +633,8 @@ const scrollEditorPositionIntoView = (
function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
const isViewer = props.mode === "viewer";
+ const isViewerRef = useRef(isViewer);
+ isViewerRef.current = isViewer;
const visualDiagram = useMemo(() => {
if (props.mode !== "viewer" || !props.visualDiagramJson) return null;
try {
@@ -751,22 +737,19 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
props.locale,
(source) => onLoadResourceRef.current(source),
{
- readOnly: isViewer,
+ readOnly: () => isViewerRef.current,
// NodeView binds ⋯ / image taps directly — Android WebView often drops
// click after pointerdown preventDefault, so PM handleClick is not enough.
onResourcePress: (targetJson) => onResourcePressRef.current?.(targetJson),
onImagePreview: (payloadJson) => onImagePreviewRef.current?.(payloadJson),
}
),
- [isViewer, props.baseUrl, props.locale]
+ [props.baseUrl, props.locale]
);
+ const diagramViewer = isViewer && Boolean(props.mode === "viewer" && props.visualDiagramNote);
const mermaidCodeBlockExtension = useMemo(
- () => createMobileCodeBlockExtension(
- props.locale,
- props.theme,
- props.mode === "viewer" && Boolean(props.visualDiagramNote),
- ),
- [props.locale, props.mode, props.theme, props.mode === "viewer" ? props.visualDiagramNote : undefined]
+ () => createMobileCodeBlockExtension(props.locale, props.theme, diagramViewer),
+ [diagramViewer, props.locale, props.theme]
);
const searchHighlightExtension = useMemo(
() => Extension.create({
@@ -804,11 +787,9 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
table: { renderWrapper: true },
}),
...createNativeUnsupportedContentExtensions(),
- ...(isViewer
- ? []
- : [Placeholder.configure({
- placeholder: getMobileEditorPlaceholder(props.locale),
- })]),
+ Placeholder.configure({
+ placeholder: () => isViewerRef.current ? "" : getMobileEditorPlaceholder(props.locale),
+ }),
],
content: prepareNativeEditorContent(
resolveImageSources(resolveMobileAttachmentContent(props.content), props.baseUrl),
@@ -822,7 +803,7 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
// Intercept attachment anchors before ProseMirror's later click phase so
// the embedded file:// WebView never follows relative resource URLs.
click: (_view, event) => handleMobileResourceEvent(event, onResourcePressRef.current, {
- allowImagePreview: isViewer,
+ allowImagePreview: isViewerRef.current,
onImagePreview: onImagePreviewRef.current,
}),
contextmenu: (_view, event) => handleMobileResourceEvent(event, onResourcePressRef.current, {
@@ -830,7 +811,7 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
onImagePreview: onImagePreviewRef.current,
}),
dblclick: (_view, event) => {
- if (!isViewer || !onDoublePressRef.current) return false;
+ if (!isViewerRef.current || !onDoublePressRef.current) return false;
const target = event.target as HTMLElement | null;
if (!target || target.closest("a, button, img, input, textarea, select, .edgeever-image-node")) {
return false;
@@ -843,7 +824,7 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
},
},
onUpdate: ({ editor: activeEditor, transaction }) => {
- if (isViewer || !onChangeRef.current) {
+ if (isViewerRef.current || !onChangeRef.current) {
return;
}
if (transaction.getMeta(TRANSIENT_IMAGE_UPLOAD_META)) {
@@ -860,7 +841,7 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
});
const flush = useCallback(() => {
- if (isViewer || !editor || editor.isDestroyed || !onChangeRef.current) {
+ if (isViewerRef.current || !editor || editor.isDestroyed || !onChangeRef.current) {
return;
}
if (changeTimerRef.current !== null) {
@@ -868,7 +849,7 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
changeTimerRef.current = null;
}
void onChangeRef.current(getPersistableEditorDoc(editor.getJSON() as EditorDoc, props.baseUrl));
- }, [editor, isViewer, props.baseUrl]);
+ }, [editor, props.baseUrl]);
const setContent = useCallback((contentJsonSerialized: DOMValue) => {
if (!editor || editor.isDestroyed || typeof contentJsonSerialized !== "string") {
@@ -1395,46 +1376,32 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
[appendAttachment, beginImageUpload, cancelImageUpload, completeImageUpload, finishImageBatch, editor, exportImage, flush, isViewer, pushAiStreamEvent, removeResource, renameResource, replaceAll, search, setContent]
);
+ useEffect(() => {
+ if (!editor || editor.isDestroyed) {
+ return;
+ }
+ editor.setEditable(!isViewer);
+ editor.view.dom.classList.toggle("edgeever-viewer-content", isViewer);
+ }, [editor, isViewer]);
+
useEffect(() => {
if (!editor) {
return;
}
void onReadyRef.current(Math.round(performance.now() - startedAtRef.current));
- let focusFrame = 0;
- let focusRetry: number | null = null;
- if (autoFocus) {
- const focusAtEnd = () => {
- if (!editor.isDestroyed) {
- editor.commands.focus("end");
- }
- };
- focusFrame = window.requestAnimationFrame(focusAtEnd);
- // The DOM view can report ready one bridge turn before Android attaches
- // its input connection. Keep the HTML selection ready for the native IME
- // handoff without delaying the editor's first visible frame.
- focusRetry = window.setTimeout(focusAtEnd, 120);
- }
const handlePageHide = () => flush();
const handleVisibilityChange = () => {
if (document.visibilityState === "hidden") {
flush();
}
};
- if (!isViewer) {
- window.addEventListener("pagehide", handlePageHide);
- document.addEventListener("visibilitychange", handleVisibilityChange);
- }
+ window.addEventListener("pagehide", handlePageHide);
+ document.addEventListener("visibilitychange", handleVisibilityChange);
return () => {
- window.cancelAnimationFrame(focusFrame);
- if (focusRetry !== null) {
- window.clearTimeout(focusRetry);
- }
- if (!isViewer) {
- window.removeEventListener("pagehide", handlePageHide);
- document.removeEventListener("visibilitychange", handleVisibilityChange);
- }
+ window.removeEventListener("pagehide", handlePageHide);
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
if (changeTimerRef.current !== null) {
window.clearTimeout(changeTimerRef.current);
}
@@ -1445,7 +1412,27 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
window.clearTimeout(aiUndoTimerRef.current);
}
};
- }, [autoFocus, editor, flush, isViewer]);
+ }, [editor, flush]);
+
+ useEffect(() => {
+ if (!editor || editor.isDestroyed || isViewer || !autoFocus) {
+ return;
+ }
+ const focusAtEnd = () => {
+ if (!editor.isDestroyed) {
+ editor.commands.focus("end");
+ }
+ };
+ const focusFrame = window.requestAnimationFrame(focusAtEnd);
+ // The DOM view can report ready one bridge turn before Android attaches
+ // its input connection. Keep the HTML selection ready for the native IME
+ // handoff without delaying the editor's first visible frame.
+ const focusRetry = window.setTimeout(focusAtEnd, 120);
+ return () => {
+ window.cancelAnimationFrame(focusFrame);
+ window.clearTimeout(focusRetry);
+ };
+ }, [autoFocus, editor, isViewer]);
// Keep the viewer in sync when the parent swaps memo content.
useEffect(() => {
@@ -2460,7 +2447,7 @@ const createProtectedImageExtension = (
locale: "zh-CN" | "en-US",
loadResource: (source: string) => Promise<string | null>,
options?: {
- readOnly?: boolean;
+ readOnly?: boolean | (() => boolean);
onResourcePress?: (targetJson: string) => void | Promise<void>;
onImagePreview?: (payloadJson: string) => void | Promise<void>;
}
@@ -2481,9 +2468,14 @@ const createProtectedImageExtension = (
},
addNodeView() {
return ({ editor, getPos, node }) => {
- const readOnly = Boolean(options?.readOnly) || !editor.isEditable;
+ const isReadOnly = () => {
+ const option = options?.readOnly;
+ const fromOption = typeof option === "function" ? option() : Boolean(option);
+ return fromOption || !editor.isEditable;
+ };
+ const readOnly = isReadOnly();
const updateWidth = (width: number) => {
- if (readOnly) {
+ if (isReadOnly()) {
return;
}
const position = getPos();
@@ -2708,18 +2700,18 @@ const createProtectedImageExtension = (
actionButton.setAttribute("aria-label", locale === "en-US" ? "Image actions" : "图片操作");
actionButton.textContent = "⋯";
bindImageActionButton(wrapper, actionButton);
- if (readOnly) {
- image.style.cursor = "zoom-in";
- image.addEventListener("click", (event) => {
- // Ignore taps that originated on the ⋯ control (event target would be button).
- if (event.target instanceof Element && event.target.closest(".edgeever-image-actions")) {
- return;
- }
- event.preventDefault();
- event.stopPropagation();
- emitImagePreview(wrapper);
- });
- }
+ image.addEventListener("click", (event) => {
+ if (!isReadOnly()) {
+ return;
+ }
+ // Ignore taps that originated on the ⋯ control (event target would be button).
+ if (event.target instanceof Element && event.target.closest(".edgeever-image-actions")) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ emitImagePreview(wrapper);
+ });
wrapper.append(loading, image, actionButton, sizeControls.dom);
const imageType = node.type;
let requestId = 0;
@@ -2856,7 +2848,7 @@ const createProtectedImageExtension = (
},
selectNode: () => {
wrapper.classList.add("is-selected");
- sizeControls.setVisible(!readOnly && displayReady);
+ sizeControls.setVisible(!isReadOnly() && displayReady);
},
deselectNode: () => {
wrapper.classList.remove("is-selected");
diff --git a/apps/mobile/src/hooks/mobile-editor-close.test.ts b/apps/mobile/src/hooks/mobile-editor-close.test.ts
new file mode 100644
index 00000000..42506497
--- /dev/null
+++ b/apps/mobile/src/hooks/mobile-editor-close.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, test } from "bun:test";
+import { resolveEditorCloseAction } from "./mobile-editor-close";
+
+describe("resolveEditorCloseAction", () => {
+ test("runs close immediately when idle", () => {
+ expect(resolveEditorCloseAction({ closeInFlight: false, saving: false, uploading: false })).toBe("run");
+ });
+
+ test("remembers a back tap while a save is already in flight", () => {
+ expect(resolveEditorCloseAction({ closeInFlight: false, saving: true, uploading: false })).toBe("defer");
+ });
+
+ test("ignores duplicate taps while close is already running", () => {
+ expect(resolveEditorCloseAction({ closeInFlight: true, saving: false, uploading: false })).toBe("defer");
+ expect(resolveEditorCloseAction({ closeInFlight: true, saving: true, uploading: false })).toBe("defer");
+ });
+
+ test("does not leave while an upload is in progress", () => {
+ expect(resolveEditorCloseAction({ closeInFlight: false, saving: false, uploading: true })).toBe("block");
+ });
+});
diff --git a/apps/mobile/src/hooks/mobile-editor-close.ts b/apps/mobile/src/hooks/mobile-editor-close.ts
new file mode 100644
index 00000000..b5df17ec
--- /dev/null
+++ b/apps/mobile/src/hooks/mobile-editor-close.ts
@@ -0,0 +1,18 @@
+export type EditorCloseGate = {
+ closeInFlight: boolean;
+ saving: boolean;
+ uploading: boolean;
+};
+
+export type EditorCloseAction = "block" | "defer" | "run";
+
+/** Decide whether a back/done tap can close now, wait for an in-flight save, or must stay. */
+export const resolveEditorCloseAction = ({
+ closeInFlight,
+ saving,
+ uploading,
+}: EditorCloseGate): EditorCloseAction => {
+ if (uploading) return "block";
+ if (saving || closeInFlight) return "defer";
+ return "run";
+};
diff --git a/apps/mobile/src/hooks/useMobileRichEditor.ts b/apps/mobile/src/hooks/useMobileRichEditor.ts
new file mode 100644
index 00000000..a6522f11
--- /dev/null
+++ b/apps/mobile/src/hooks/useMobileRichEditor.ts
@@ -0,0 +1,507 @@
+import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
+import type { UseMutationResult } from "@tanstack/react-query";
+import { File as ExpoFile } from "expo-file-system";
+import { BackHandler, Platform } from "react-native";
+import {
+ DEFAULT_MEMO_TITLE,
+ docToMarkdown,
+ markdownToDoc,
+ resolveMemoContentDoc,
+ type MemoDetail,
+ type Notebook,
+ type TiptapDoc,
+} from "@edgeever/shared";
+import { Alert } from "../components/LocalizedText";
+import type { LocalTiptapEditorRef } from "../components/LocalTiptapEditor";
+import {
+ applyMobileEditorUpload,
+ cancelMobileEditorUpload,
+ flushMobileEditor,
+} from "../lib/mobile-editor-controller";
+import { clearMobileMemoDraft, writeMobileMemoDraft, type MobileMemoDraft } from "../lib/mobile-drafts";
+import { prepareUploadAsset } from "../lib/mobile-image-upload";
+import { useMobileLocale } from "../lib/mobile-locale";
+import { useSession } from "../lib/session";
+import { recordEditorStartup } from "../lib/startup-performance";
+import { safeDomCall } from "../lib/safe-dom-call";
+import { showEdgeEverKeyboard } from "../../modules/edgeever-keyboard";
+import { parseTags } from "../screens/workspace-utils";
+import type { MobileMemoUpdatePayload } from "../screens/workspace-memo-cache";
+import { resolveEditorCloseAction } from "./mobile-editor-close";
+import { useMobileEditorResourceActions } from "./useMobileEditorResourceActions";
+import { useMobileEditorUploadAsset } from "./useMobileEditorUploadAsset";
+import { useMobileSelectionAi } from "./useMobileSelectionAi";
+import {
+ createOnceProtectedResourceFailureNotifier,
+ type ProtectedResourceLoadFailure,
+} from "../lib/mobile-protected-resources";
+import type { MobileResourceTarget } from "../lib/mobile-attachments";
+
+export type MobileMemoUpdateMutation = UseMutationResult<
+ MemoDetail,
+ Error,
+ { memo: MemoDetail; payload: MobileMemoUpdatePayload }
+>;
+
+export const resolveEditableMemoTitle = (title?: string | null) => {
+ const trimmedTitle = title?.trim() ?? "";
+ return trimmedTitle === DEFAULT_MEMO_TITLE ? "" : trimmedTitle;
+};
+
+const createMobileImageUploadId = () =>
+ `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
+
+const createLocalImagePreviewDataUrl = async (asset: { mimeType?: string | null; uri: string }) => {
+ const file = new ExpoFile(asset.uri);
+ const mimeType = asset.mimeType || file.type || "application/octet-stream";
+ return `data:${mimeType};base64,${await file.base64()}`;
+};
+
+const alertProtectedImageLoadFailure = (
+ locale: "zh-CN" | "en-US",
+ failure: ProtectedResourceLoadFailure
+) => {
+ const statusLabel = failure.status != null
+ ? String(failure.status)
+ : locale === "en-US"
+ ? "network error"
+ : "网络错误";
+ Alert.alert(
+ locale === "en-US" ? "Image failed to load" : "图片加载失败",
+ locale === "en-US"
+ ? `Could not load a note image (${statusLabel}). Check the network and try again.`
+ : `笔记中的图片未能加载(${statusLabel})。请检查网络后重试。`
+ );
+};
+
+const restoreDraft = (memo: MemoDetail | null, initialDraft: MobileMemoDraft | null) =>
+ initialDraft?.expectedRevision === memo?.revision ? initialDraft : null;
+
+export const useMobileRichEditor = ({
+ active,
+ alreadyReady = false,
+ baseUrl,
+ editorRef,
+ handleHardwareBack = true,
+ imageCompressionEnabled,
+ initialDraft,
+ initialFocus = "body",
+ memo,
+ notebooks,
+ onClose,
+ updateMutation,
+}: {
+ active: boolean;
+ alreadyReady?: boolean;
+ baseUrl: string;
+ editorRef: RefObject<LocalTiptapEditorRef | null>;
+ handleHardwareBack?: boolean;
+ imageCompressionEnabled: boolean;
+ initialDraft: MobileMemoDraft | null;
+ initialFocus?: "body" | "title";
+ memo: MemoDetail | null;
+ notebooks: Notebook[];
+ onClose: () => void;
+ updateMutation: MobileMemoUpdateMutation;
+}) => {
+ const { client, session } = useSession();
+ const { resolvedLocale } = useMobileLocale();
+ const restoredDraft = restoreDraft(memo, initialDraft);
+ const initialContentJson = restoredDraft
+ ? markdownToDoc(restoredDraft.contentMarkdown)
+ : resolveMemoContentDoc(memo?.contentJson, memo?.contentMarkdown);
+ const resourceDataUrlCacheRef = useRef(new Map<string, Promise<string | null>>());
+ const imageLoadFailureNotifier = useMemo(
+ () =>
+ createOnceProtectedResourceFailureNotifier((failure) => {
+ alertProtectedImageLoadFailure(resolvedLocale, failure);
+ }),
+ [memo?.id, resolvedLocale]
+ );
+ const initialFocusTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const sessionKeyRef = useRef<string | null>(null);
+ const contentJsonRef = useRef<TiptapDoc>(initialContentJson);
+ const contentMarkdownRef = useRef(restoredDraft?.contentMarkdown ?? memo?.contentMarkdown ?? "");
+ const contentSnapshotRef = useRef(JSON.stringify(contentJsonRef.current));
+ const dirtyRef = useRef(Boolean(restoredDraft));
+ const flushResolverRef = useRef<(() => void) | null>(null);
+ const savingRef = useRef(false);
+ const uploadingRef = useRef(false);
+ const closingRef = useRef(false);
+ const closeInFlightRef = useRef(false);
+ const requestCloseRef = useRef<() => Promise<void>>(async () => undefined);
+ const memoBaseRef = useRef(memo);
+ const [title, setTitle] = useState(resolveEditableMemoTitle(restoredDraft?.title ?? memo?.title));
+ const [tagsText, setTagsText] = useState(restoredDraft?.tagsText ?? memo?.tags.join(", ") ?? "");
+ const [notebookId, setNotebookId] = useState(restoredDraft?.notebookId ?? memo?.notebookId ?? "");
+ const [notebookPickerOpen, setNotebookPickerOpen] = useState(false);
+ const [tagPickerOpen, setTagPickerOpen] = useState(false);
+ const [draftRestored, setDraftRestored] = useState(Boolean(restoredDraft));
+ const [ready, setReady] = useState(alreadyReady);
+ const [dirty, setDirty] = useState(Boolean(restoredDraft));
+ const [saving, setSaving] = useState(false);
+ const [uploading, setUploading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [resourceTarget, setResourceTarget] = useState<MobileResourceTarget | null>(null);
+ const { pickUploadAssets, uploadSourcePicker } = useMobileEditorUploadAsset();
+ const notebookLabel = notebooks.find((notebook) => notebook.id === notebookId)?.name ?? "未分类";
+ const saveLabel = error
+ ? "保存失败"
+ : saving
+ ? "保存中"
+ : uploading
+ ? "上传中"
+ : dirty
+ ? (draftRestored ? "本地草稿" : "未保存")
+ : ready
+ ? "已保存"
+ : "加载中";
+ const titleRef = useRef(title);
+ const tagsTextRef = useRef(tagsText);
+ const notebookIdRef = useRef(notebookId);
+ titleRef.current = title;
+ tagsTextRef.current = tagsText;
+ notebookIdRef.current = notebookId;
+ memoBaseRef.current = memoBaseRef.current ?? memo;
+
+ useEffect(() => () => {
+ if (initialFocusTimerRef.current !== null) {
+ clearTimeout(initialFocusTimerRef.current);
+ initialFocusTimerRef.current = null;
+ }
+ }, []);
+
+ useEffect(() => {
+ if (!active || !memo) {
+ sessionKeyRef.current = null;
+ return;
+ }
+ const sessionKey = `${memo.id}:${initialFocus}`;
+ if (sessionKeyRef.current === sessionKey) {
+ if (alreadyReady) {
+ setReady(true);
+ }
+ return;
+ }
+ sessionKeyRef.current = sessionKey;
+ memoBaseRef.current = memo;
+ const nextDraft = restoreDraft(memo, initialDraft);
+ const nextContentJson = nextDraft
+ ? markdownToDoc(nextDraft.contentMarkdown)
+ : resolveMemoContentDoc(memo.contentJson, memo.contentMarkdown);
+ contentJsonRef.current = nextContentJson;
+ contentMarkdownRef.current = nextDraft?.contentMarkdown ?? memo.contentMarkdown ?? "";
+ contentSnapshotRef.current = JSON.stringify(nextContentJson);
+ dirtyRef.current = Boolean(nextDraft);
+ setTitle(resolveEditableMemoTitle(nextDraft?.title ?? memo.title));
+ setTagsText(nextDraft?.tagsText ?? memo.tags.join(", ") ?? "");
+ setNotebookId(nextDraft?.notebookId ?? memo.notebookId ?? "");
+ setNotebookPickerOpen(false);
+ setTagPickerOpen(false);
+ setDraftRestored(Boolean(nextDraft));
+ setDirty(Boolean(nextDraft));
+ setSaving(false);
+ setUploading(false);
+ closingRef.current = false;
+ closeInFlightRef.current = false;
+ setError(null);
+ setResourceTarget(null);
+ if (alreadyReady) {
+ setReady(true);
+ recordEditorStartup(0);
+ if (nextDraft) {
+ safeDomCall(() => editorRef.current?.setContent(JSON.stringify(nextContentJson)));
+ }
+ if (Platform.OS === "android" && initialFocus === "body") {
+ if (initialFocusTimerRef.current !== null) {
+ clearTimeout(initialFocusTimerRef.current);
+ }
+ initialFocusTimerRef.current = setTimeout(() => {
+ initialFocusTimerRef.current = null;
+ showEdgeEverKeyboard();
+ }, 180);
+ }
+ } else {
+ setReady(false);
+ }
+ }, [active, alreadyReady, editorRef, initialDraft, initialFocus, memo]);
+
+ const persistDraft = async (contentJson: TiptapDoc) => {
+ const currentMemo = memoBaseRef.current;
+ if (!active || !currentMemo) {
+ return;
+ }
+ const contentSnapshot = JSON.stringify(contentJson);
+ if (contentSnapshot === contentSnapshotRef.current) {
+ flushResolverRef.current?.();
+ flushResolverRef.current = null;
+ return;
+ }
+ contentSnapshotRef.current = contentSnapshot;
+ contentJsonRef.current = contentJson;
+ contentMarkdownRef.current = docToMarkdown(contentJson);
+ dirtyRef.current = true;
+ setDirty(true);
+ setError(null);
+ flushResolverRef.current?.();
+ flushResolverRef.current = null;
+ await writeMobileMemoDraft({
+ memoId: currentMemo.id,
+ expectedRevision: currentMemo.revision,
+ title: titleRef.current.trim(),
+ contentMarkdown: contentMarkdownRef.current,
+ notebookId: notebookIdRef.current,
+ tagsText: tagsTextRef.current,
+ updatedAt: new Date().toISOString(),
+ });
+ };
+
+ const save = async () => {
+ const currentMemo = memoBaseRef.current;
+ if (!currentMemo || savingRef.current || !notebookIdRef.current) {
+ return null;
+ }
+ if (!dirtyRef.current) {
+ return currentMemo;
+ }
+ const dirtyGenerationAtStart = contentSnapshotRef.current;
+ savingRef.current = true;
+ setSaving(true);
+ setError(null);
+
+ try {
+ const savedMemo = await updateMutation.mutateAsync({
+ memo: currentMemo,
+ payload: {
+ title: titleRef.current.trim() || DEFAULT_MEMO_TITLE,
+ contentJson: contentJsonRef.current,
+ contentMarkdown: contentMarkdownRef.current,
+ notebookId: notebookIdRef.current,
+ tags: parseTags(tagsTextRef.current),
+ },
+ });
+ memoBaseRef.current = savedMemo;
+ await clearMobileMemoDraft(currentMemo.id);
+ if (contentSnapshotRef.current === dirtyGenerationAtStart) {
+ dirtyRef.current = false;
+ setDirty(false);
+ } else {
+ dirtyRef.current = true;
+ setDirty(true);
+ }
+ setDraftRestored(false);
+ return savedMemo;
+ } catch (saveError) {
+ closingRef.current = false;
+ setError(saveError instanceof Error ? saveError.message : "保存失败");
+ return null;
+ } finally {
+ savingRef.current = false;
+ setSaving(false);
+ // A back/done tap during autosave is remembered and finished here.
+ if (closingRef.current && !closeInFlightRef.current) {
+ void requestCloseRef.current();
+ }
+ }
+ };
+
+ const flushEditor = () => flushMobileEditor(editorRef, flushResolverRef);
+ const { aiPromptsJson, cancelSelectionAi, requestSelectionAi } = useMobileSelectionAi({
+ client,
+ editorRef,
+ resolvedLocale,
+ titleRef,
+ });
+
+ const onCloseRef = useRef(onClose);
+ onCloseRef.current = onClose;
+ const requestClose = async () => {
+ const action = resolveEditorCloseAction({
+ closeInFlight: closeInFlightRef.current,
+ saving: savingRef.current,
+ uploading: uploadingRef.current,
+ });
+ if (action === "block") {
+ return;
+ }
+ closingRef.current = true;
+ if (action === "defer") {
+ return;
+ }
+ closeInFlightRef.current = true;
+ if (initialFocusTimerRef.current !== null) {
+ clearTimeout(initialFocusTimerRef.current);
+ initialFocusTimerRef.current = null;
+ }
+ try {
+ await flushEditor();
+ if (!closingRef.current) {
+ return;
+ }
+ const savedMemo = await save();
+ if (savedMemo && closingRef.current) {
+ onCloseRef.current();
+ return;
+ }
+ // Keep the close queued when another save is still in flight.
+ if (!savedMemo && !savingRef.current) {
+ closingRef.current = false;
+ }
+ } finally {
+ closeInFlightRef.current = false;
+ }
+ };
+ requestCloseRef.current = requestClose;
+
+ useEffect(() => {
+ if (!active || !handleHardwareBack) {
+ return;
+ }
+ const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
+ void requestCloseRef.current();
+ return true;
+ });
+ return () => subscription.remove();
+ }, [active, handleHardwareBack]);
+
+ const pickAndUploadImage = async () => {
+ const currentMemo = memoBaseRef.current;
+ if (!client || !currentMemo || uploadingRef.current) {
+ return;
+ }
+ if (currentMemo.id.startsWith("local:")) {
+ Alert.alert("正在同步新笔记", "首次同步完成后即可上传本地图片;图片链接现在就可以直接粘贴到正文。");
+ return;
+ }
+ const assets = await pickUploadAssets();
+ if (!assets.length) {
+ return;
+ }
+
+ let uploadId: string | null = null;
+ const sources: string[] = [];
+ uploadingRef.current = true;
+ setUploading(true);
+ setError(null);
+ try {
+ for (const asset of assets) {
+ const isImage = asset.mimeType?.startsWith("image/") ?? false;
+ uploadId = isImage ? createMobileImageUploadId() : null;
+ if (isImage && uploadId) {
+ const previewDataUrl = await createLocalImagePreviewDataUrl(asset);
+ safeDomCall(() => editorRef.current?.beginImageUpload(uploadId, previewDataUrl));
+ }
+ const uploadAsset = await prepareUploadAsset(asset, imageCompressionEnabled);
+ const { resource } = await client.uploadMemoResource(currentMemo.id, new ExpoFile(uploadAsset.uri));
+ applyMobileEditorUpload(editorRef, resource, uploadId, uploadAsset.name || (resource.kind === "image" ? "图片" : "附件"));
+ if (resource.kind === "image") sources.push(resource.url);
+ uploadId = null;
+ }
+ } catch (uploadError) {
+ cancelMobileEditorUpload(editorRef, uploadId);
+ setError(uploadError instanceof Error ? uploadError.message : "附件上传失败");
+ } finally {
+ safeDomCall(() => editorRef.current?.finishImageBatch(sources));
+ uploadingRef.current = false;
+ setUploading(false);
+ }
+ };
+
+ const canMutateEditorResource = useCallback(
+ () => Boolean(memoBaseRef.current && !memoBaseRef.current.id.startsWith("local:")),
+ []
+ );
+ const {
+ deleteResource,
+ downloadResource,
+ loadEditorResource,
+ renameResource,
+ saveResourceAs,
+ selectResource,
+ } = useMobileEditorResourceActions({
+ baseUrl,
+ canMutate: canMutateEditorResource,
+ client,
+ editorRef,
+ onLoadFailure: imageLoadFailureNotifier,
+ onSelect: setResourceTarget,
+ resolvedLocale,
+ resourceCacheRef: resourceDataUrlCacheRef,
+ sessionBaseUrl: session?.baseUrl,
+ token: session?.token,
+ });
+
+ useEffect(() => {
+ const currentMemo = memoBaseRef.current;
+ if (!active || !currentMemo || !dirty) {
+ return;
+ }
+ const timeout = setTimeout(() => {
+ void writeMobileMemoDraft({
+ memoId: currentMemo.id,
+ expectedRevision: currentMemo.revision,
+ title: titleRef.current.trim(),
+ contentMarkdown: contentMarkdownRef.current,
+ notebookId: notebookIdRef.current,
+ tagsText: tagsTextRef.current,
+ updatedAt: new Date().toISOString(),
+ });
+ }, 350);
+ return () => clearTimeout(timeout);
+ }, [active, dirty, memo, notebookId, tagsText, title]);
+
+ useEffect(() => {
+ if (!active || !memoBaseRef.current || !dirty || !ready || savingRef.current || uploadingRef.current || closingRef.current) {
+ return;
+ }
+ const timeout = setTimeout(() => {
+ void flushEditor().then(save);
+ }, 1200);
+ return () => clearTimeout(timeout);
+ }, [active, dirty, memo, notebookId, ready, tagsText, title]);
+
+ const markDirty = () => {
+ dirtyRef.current = true;
+ setDirty(true);
+ };
+
+ return {
+ aiPromptsJson,
+ cancelSelectionAi,
+ contentMarkdown: contentMarkdownRef.current,
+ deleteResource,
+ dirty,
+ downloadResource,
+ draftRestored,
+ error,
+ loadEditorResource,
+ markDirty,
+ notebookId,
+ notebookLabel,
+ notebookPickerOpen,
+ persistDraft,
+ pickAndUploadImage,
+ ready,
+ renameResource,
+ requestClose,
+ requestSelectionAi,
+ resourceTarget,
+ saveLabel,
+ saveResourceAs,
+ saving,
+ selectResource,
+ setNotebookId,
+ setNotebookPickerOpen,
+ setResourceTarget,
+ setTagPickerOpen,
+ setTagsText,
+ setTitle,
+ tagPickerOpen,
+ tagsText,
+ title,
+ uploadSourcePicker,
+ uploading,
+ };
+};
+
+export type UseMobileRichEditorResult = ReturnType<typeof useMobileRichEditor>;
diff --git a/apps/mobile/src/screens/WorkspaceEditors.tsx b/apps/mobile/src/screens/WorkspaceEditors.tsx
index 3f865012..7ed5eb27 100644
--- a/apps/mobile/src/screens/WorkspaceEditors.tsx
+++ b/apps/mobile/src/screens/WorkspaceEditors.tsx
@@ -802,6 +802,7 @@ export const CreateMemoModal = ({
);
};
+/** Full-tree editor for paths that do not already have a mounted viewer WebView. Existing notes edit in place on the detail viewer. */
export const RichEditorModal = ({
baseUrl,
initialDraft,
diff --git a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
index 282ef50b..cf7df324 100644
--- a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
+++ b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
-import { DEFAULT_MEMO_TITLE, parseDiagramDocument, type MemoDetail, type TiptapDoc } from "@edgeever/shared";
+import { DEFAULT_MEMO_TITLE, parseDiagramDocument, type MemoDetail, type Notebook, type TiptapDoc } from "@edgeever/shared";
import {
type NoteImageTheme,
type NoteImageFontStyle,
@@ -7,7 +7,7 @@ import {
type NoteImageCardWidth,
} from "@edgeever/shared/note-image-card";
import * as Clipboard from "expo-clipboard";
-import { Image as RNImage, Platform, ScrollView, StyleSheet, Text as RNText, View, type ImageStyle, type StyleProp, type TextStyle } from "react-native";
+import { Image as RNImage, KeyboardAvoidingView, Platform, ScrollView, StyleSheet, Text as RNText, View, type ImageStyle, type StyleProp, type TextStyle } from "react-native";
import { Modal } from "react-native";
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
import { SvgXml } from "react-native-svg";
@@ -34,12 +34,16 @@ import {
loadProtectedResourceDataUrl,
type ProtectedResourceLoadFailure,
} from "../lib/mobile-protected-resources";
+import { useMobileRichEditor, type MobileMemoUpdateMutation } from "../hooks/useMobileRichEditor";
+import type { MobileMemoDraft } from "../lib/mobile-drafts";
+import { createMobileDataScope } from "../lib/local-mirror";
import { useMobileTheme } from "../lib/mobile-theme";
import { useSession } from "../lib/session";
import { beginEditorStartup } from "../lib/startup-performance";
import type { MobileSyncQueueItem } from "../lib/sync-queue";
-import { formatMemoDetailDate, getTextSearchMatches } from "./workspace-utils";
+import { formatMemoDetailDate, getTextSearchMatches, parseTags } from "./workspace-utils";
import { styles } from "./workspace-styles";
+import { NotebookPickerModal, SmartTagButton, TagPickerModal } from "./WorkspacePickers";
const ANDROID_SYSTEM_NAVIGATION_FALLBACK = 48;
const RESOURCE_DATA_URL_CACHE_LIMIT = 32;
@@ -406,6 +410,8 @@ const HighlightedMetadataText = ({
};
export const MemoDetailModal = ({
+ editingSession,
+ imageCompressionEnabled,
initialSearchQuery,
isDeleting,
isLoading,
@@ -414,9 +420,11 @@ export const MemoDetailModal = ({
isSharing,
memo,
notebookName,
+ notebooks,
onAdoptCloudVersion,
onApplyAiDraft,
onClose,
+ onCloseEditor,
onCopyLocalDraft,
onDelete,
onDeleteResource,
@@ -429,8 +437,15 @@ export const MemoDetailModal = ({
onShare,
syncError,
syncStatus,
+ updateMutation,
visible,
}: {
+ editingSession: {
+ draft: MobileMemoDraft | null;
+ initialFocus: "body" | "title";
+ memo: MemoDetail;
+ } | null;
+ imageCompressionEnabled: boolean;
initialSearchQuery: string;
isDeleting: boolean;
isLoading: boolean;
@@ -439,9 +454,11 @@ export const MemoDetailModal = ({
isSharing: boolean;
memo: MemoDetail | null;
notebookName: string;
+ notebooks: Notebook[];
onAdoptCloudVersion: (memo: MemoDetail) => void;
onApplyAiDraft: (memo: MemoDetail, draft: string, mode: "append" | "replace") => Promise<void>;
onClose: () => void;
+ onCloseEditor: () => void;
onCopyLocalDraft: (memo: MemoDetail) => void;
onDelete: (memo: MemoDetail) => void;
onDeleteResource: (memo: MemoDetail, target: MobileResourceTarget) => Promise<void>;
@@ -454,6 +471,7 @@ export const MemoDetailModal = ({
onShare: (memo: MemoDetail) => void;
syncError: string | null;
syncStatus: MobileSyncQueueItem["status"] | null;
+ updateMutation: MobileMemoUpdateMutation;
visible: boolean;
}) => {
const { client, session } = useSession();
@@ -509,6 +527,32 @@ export const MemoDetailModal = ({
const diagram = memo ? parseDiagramDocument(memo.contentMarkdown) : null;
return diagram ? JSON.stringify(diagram) : undefined;
}, [memo]);
+ const isEditing = Boolean(editingSession);
+ const noteBodyDom = useMemo(() => ({
+ ...SAFE_DOM_WEBVIEW_PROPS,
+ bounces: true,
+ contentInsetAdjustmentBehavior: "never" as const,
+ overScrollMode: "never" as const,
+ scrollEnabled: false,
+ style: [
+ detailLayoutStyles.viewer,
+ resolvedTheme === "dark" ? detailLayoutStyles.viewerDark : null,
+ ],
+ }), [resolvedTheme]);
+ const editor = useMobileRichEditor({
+ active: isEditing,
+ alreadyReady: viewerReady,
+ baseUrl,
+ editorRef: viewerRef,
+ handleHardwareBack: false,
+ imageCompressionEnabled,
+ initialDraft: editingSession?.draft ?? null,
+ initialFocus: editingSession?.initialFocus ?? "body",
+ memo: editingSession?.memo ?? memo,
+ notebooks,
+ onClose: onCloseEditor,
+ updateMutation,
+ });
const downloadResource = useCallback(async (target: MobileResourceTarget) => {
if (!client) throw new Error(resolvedLocale === "en-US" ? "The resource client is unavailable." : "当前无法读取资源。");
@@ -613,6 +657,20 @@ export const MemoDetailModal = ({
Platform.OS === "android" ? ANDROID_SYSTEM_NAVIGATION_FALLBACK : 0
) + 16;
+ useEffect(() => {
+ if (!isEditing) {
+ return;
+ }
+ setActionsOpen(false);
+ setSearchOpen(false);
+ setSearchQuery("");
+ setBodySearchMatchCount(0);
+ setActiveMatchIndex(0);
+ setImagePreview(null);
+ setAiAssistantOpen(false);
+ safeDomCall(() => viewerRef.current?.search("", -1));
+ }, [isEditing]);
+
useEffect(() => {
const normalizedInitialSearchQuery = initialSearchQuery.trim();
setViewerReady(false);
@@ -826,8 +884,35 @@ export const MemoDetailModal = ({
}, [resolvedLocale]);
return (
- <Modal animationType="slide" onRequestClose={onClose} presentationStyle="fullScreen" visible={visible}>
- <SafeAreaView style={styles.modalSafeArea}>
+ <Modal animationType="slide" onRequestClose={isEditing ? () => void editor.requestClose() : onClose} presentationStyle="fullScreen" visible={visible}>
+ {/* Unmount the DomWebView with the modal. Updating its props after RN hides
+ the native view rejects injectJavaScript as an uncaught promise. */}
+ {visible ? (
+ <SafeAreaView style={isEditing ? styles.richEditorSafeArea : styles.modalSafeArea}>
+ <KeyboardAvoidingView
+ behavior="height"
+ enabled={Platform.OS === "android" && isEditing}
+ style={styles.richEditorKeyboardAvoiding}
+ >
+ {isEditing ? (
+ <View style={styles.createMemoHeader}>
+ <Pressable accessibilityLabel="返回" accessibilityRole="button" disabled={editor.uploading} onPress={() => void editor.requestClose()} style={styles.createMemoBackButton}>
+ <ChevronLeft color={editor.uploading ? "#cbd5e1" : "#0f172a"} size={30} />
+ </Pressable>
+ <View style={styles.createMemoHeaderActions}>
+ <Text numberOfLines={1} style={[styles.createMemoStatus, styles.richEditorHeaderStatus, (editor.saving || editor.uploading || editor.dirty) && styles.createMemoStatusActive, editor.error && styles.richEditorStatusError]}>{editor.saveLabel}</Text>
+ <Pressable
+ accessibilityLabel="完成编辑"
+ accessibilityRole="button"
+ disabled={editor.uploading || !editor.ready}
+ onPress={() => void editor.requestClose()}
+ style={[styles.createMemoDoneButton, (editor.uploading || !editor.ready) && styles.createMemoDoneButtonDisabled]}
+ >
+ {editor.saving ? <ActivityIndicator color="#64748b" size="small" /> : <Text style={[styles.createMemoDoneText, (editor.uploading || !editor.ready) && styles.createMemoDoneTextDisabled]}>完成</Text>}
+ </Pressable>
+ </View>
+ </View>
+ ) : (
<View style={styles.detailHeader}>
<Pressable accessibilityLabel="返回列表" accessibilityRole="button" onPress={onClose} style={styles.detailHeaderButton}>
<ChevronLeft color="#475569" size={21} />
@@ -896,8 +981,9 @@ export const MemoDetailModal = ({
) : null}
</View>
</View>
+ )}
- {syncStatus === "conflict" && memo ? (
+ {!isEditing && syncStatus === "conflict" && memo ? (
<View style={styles.conflictBanner}>
<Text style={styles.conflictBannerText}>
云端笔记已在其他标签页、设备,或离线期间被更新。可先复制本地草稿,再采用云端版本后继续编辑。
@@ -932,7 +1018,7 @@ export const MemoDetailModal = ({
</View>
) : null}
- {(syncStatus === "error" || syncStatus === "pending") && memo ? (
+ {!isEditing && (syncStatus === "error" || syncStatus === "pending") && memo ? (
<View style={syncStatus === "error" ? styles.syncErrorBanner : styles.syncPendingBanner}>
<Text style={syncStatus === "error" ? styles.syncErrorBannerText : styles.syncPendingBannerText}>
{syncStatus === "error"
@@ -968,6 +1054,47 @@ export const MemoDetailModal = ({
</View>
) : memo ? (
<View style={detailLayoutStyles.body}>
+ {isEditing ? (
+ <View style={{ paddingHorizontal: 12, paddingTop: 8 }}>
+ <TextInput
+ autoFocus={editingSession?.initialFocus === "title"}
+ onChangeText={(value) => {
+ editor.setTitle(value);
+ editor.markDirty();
+ }}
+ placeholder={DEFAULT_MEMO_TITLE}
+ placeholderTextColor="#94a3b8"
+ selectTextOnFocus={editingSession?.initialFocus === "title"}
+ style={styles.createMemoTitleInput}
+ value={editor.title}
+ />
+ <View style={[styles.createMemoMetaRow, styles.richStandaloneMetaRow]}>
+ <Pressable accessibilityLabel="所在笔记本" accessibilityRole="button" onPress={() => editor.setNotebookPickerOpen(true)} style={styles.createMemoNotebookButton}>
+ <Text numberOfLines={1} style={styles.createMemoNotebookText}>{editor.notebookLabel}</Text>
+ <ChevronDown color="#64748b" size={14} />
+ </Pressable>
+ <Pressable accessibilityLabel="选择笔记标签" accessibilityRole="button" onPress={() => editor.setTagPickerOpen(true)} style={[styles.createMemoTagsButton, styles.richStandaloneTagsInput]}>
+ <Text numberOfLines={1} style={[styles.createMemoTagsInput, !editor.tagsText && styles.createMemoTagsPlaceholder]}>
+ {editor.tagsText || "添加标签"}
+ </Text>
+ <ChevronDown color="#94a3b8" size={14} />
+ </Pressable>
+ <SmartTagButton
+ client={client}
+ contentMarkdown={editor.contentMarkdown}
+ disabled={editor.saving || editor.uploading}
+ onChange={(nextTags) => {
+ editor.setTagsText(nextTags.join(", "));
+ editor.markDirty();
+ }}
+ selectedTags={parseTags(editor.tagsText)}
+ title={editor.title}
+ />
+ </View>
+ {editor.draftRestored ? <Text style={styles.richEditorDraftNotice}>已恢复上次未完成的本地草稿</Text> : null}
+ {editor.error ? <Text style={styles.richEditorInlineError}>{editor.error}</Text> : null}
+ </View>
+ ) : (
<View style={detailLayoutStyles.meta}>
{!memo.isDeleted && !isVisualDiagram ? (
<Pressable
@@ -1059,35 +1186,32 @@ export const MemoDetailModal = ({
) : null}
<View style={styles.detailDivider} />
</View>
+ )}
{baseUrl ? (
<LocalTiptapEditor
key={memo.id}
+ aiPromptsJson={isEditing ? editor.aiPromptsJson : undefined}
+ autoFocus={isEditing && editingSession?.initialFocus === "body"}
baseUrl={baseUrl}
content={viewerContent}
- dom={{
- ...SAFE_DOM_WEBVIEW_PROPS,
- bounces: true,
- contentInsetAdjustmentBehavior: "never",
- overScrollMode: "never",
- scrollEnabled: false,
- style: [
- detailLayoutStyles.viewer,
- resolvedTheme === "dark" ? detailLayoutStyles.viewerDark : null,
- ],
- }}
+ dom={noteBodyDom}
locale={resolvedLocale}
- mode="viewer"
- onImagePreview={onImagePreview}
- onDoublePress={isVisualDiagram ? undefined : async () => {
+ mode={isEditing ? "editor" : "viewer"}
+ onAiCancel={isEditing ? editor.cancelSelectionAi : undefined}
+ onAiRequest={isEditing ? editor.requestSelectionAi : undefined}
+ onChange={isEditing ? editor.persistDraft : undefined}
+ onImagePreview={isEditing ? undefined : onImagePreview}
+ onDoublePress={isEditing || isVisualDiagram ? undefined : async () => {
beginEditorStartup();
onRichEdit(memo, "body");
}}
onImageExportEvent={handleImageExportEvent}
- onLoadResource={loadViewerResource}
+ onLoadResource={isEditing ? editor.loadEditorResource : loadViewerResource}
+ onPickImage={isEditing ? editor.pickAndUploadImage : undefined}
onReady={async () => {
setViewerReady(true);
}}
- onResourcePress={onResourcePress}
+ onResourcePress={isEditing ? editor.selectResource : onResourcePress}
onSearchResult={async (count, _index, resultQuery) => {
if (resultQuery === searchQuery) {
setBodySearchMatchCount(count);
@@ -1095,8 +1219,8 @@ export const MemoDetailModal = ({
}}
ref={viewerRef}
theme={resolvedTheme}
- visualDiagramJson={visualDiagramJson}
- visualDiagramNote={isVisualDiagram}
+ visualDiagramJson={isEditing ? undefined : visualDiagramJson}
+ visualDiagramNote={!isEditing && isVisualDiagram}
/>
) : (
<View style={styles.centerState}>
@@ -1114,7 +1238,7 @@ export const MemoDetailModal = ({
<Text style={styles.errorText}>笔记加载失败</Text>
</View>
)}
- {memo && !memo.isDeleted && !isVisualDiagram ? (
+ {memo && !memo.isDeleted && !isVisualDiagram && !isEditing ? (
<Pressable
accessibilityLabel="编辑笔记"
accessibilityRole="button"
@@ -1127,6 +1251,7 @@ export const MemoDetailModal = ({
<Pencil color="#ffffff" size={20} />
</Pressable>
) : null}
+ </KeyboardAvoidingView>
{memo ? (
<Modal animationType="fade" onRequestClose={() => setActionsOpen(false)} transparent visible={actionsOpen}>
<Pressable onPress={() => setActionsOpen(false)} style={styles.actionSheetBackdrop}>
@@ -1420,20 +1545,55 @@ export const MemoDetailModal = ({
</Modal>
<MobileResourceActions
canMutate={Boolean(memo && !memo.isDeleted && !memo.id.startsWith("local:"))}
- onClose={() => setResourceTarget(null)}
+ onClose={() => isEditing ? editor.setResourceTarget(null) : setResourceTarget(null)}
onDelete={async (target) => {
+ if (isEditing) {
+ await editor.deleteResource(target);
+ return;
+ }
if (!memo) return;
await onDeleteResource(memo, target);
}}
- onDownload={downloadResource}
+ onDownload={isEditing ? editor.downloadResource : downloadResource}
onRename={async (target, filename) => {
+ if (isEditing) {
+ await editor.renameResource(target, filename);
+ return;
+ }
if (!memo) return;
await onRenameResource(memo, target, filename);
}}
- onSaveAs={saveResourceAs}
- target={resourceTarget}
+ onSaveAs={isEditing ? editor.saveResourceAs : saveResourceAs}
+ target={isEditing ? editor.resourceTarget : resourceTarget}
/>
+ {isEditing ? (
+ <>
+ <NotebookPickerModal
+ activeNotebookId={editor.notebookId}
+ notebooks={notebooks}
+ onClose={() => editor.setNotebookPickerOpen(false)}
+ onSelect={(nextNotebookId) => {
+ editor.setNotebookId(nextNotebookId);
+ editor.setNotebookPickerOpen(false);
+ editor.markDirty();
+ }}
+ visible={editor.notebookPickerOpen}
+ />
+ <TagPickerModal
+ dataScope={createMobileDataScope(session?.baseUrl ?? baseUrl, session?.user?.id)}
+ onChange={(nextTags) => {
+ editor.setTagsText(nextTags.join(", "));
+ editor.markDirty();
+ }}
+ onClose={() => editor.setTagPickerOpen(false)}
+ selectedTags={parseTags(editor.tagsText)}
+ visible={editor.tagPickerOpen}
+ />
+ {editor.uploadSourcePicker}
+ </>
+ ) : null}
</SafeAreaView>
+ ) : null}
</Modal>
);
};
diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsx
index ebfd6778..7e1854b4 100644
--- a/apps/mobile/src/screens/WorkspaceScreen.tsx
+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx
@@ -105,7 +105,7 @@ import {
TagPickerModal,
} from "./WorkspacePickers";
import { RevisionHistoryModal } from "./WorkspaceRevisionHistory";
-import { CreateMemoModal, RichEditorModal } from "./WorkspaceEditors";
+import { CreateMemoModal } from "./WorkspaceEditors";
import {
NotesActionsModal,
SelectionActionBar,
@@ -188,6 +188,7 @@ export const WorkspaceScreen = ({
toggleVisibleSelection,
} = useMobileWorkspaceSelection();
const memoDraftPrefetchRef = useRef(new Map<string, Promise<MobileMemoDraft | null>>());
+ const memoDraftValueRef = useRef(new Map<string, MobileMemoDraft | null>());
const processedShareUrlRef = useRef<string | null>(null);
const onIncomingShareHandledRef = useRef(onIncomingShareHandled);
onIncomingShareHandledRef.current = onIncomingShareHandled;
@@ -454,12 +455,15 @@ export const WorkspaceScreen = ({
if (cached) {
return cached;
}
- const pending = readMobileMemoDraft(memoId);
+ const pending = readMobileMemoDraft(memoId).then((draft) => {
+ memoDraftValueRef.current.set(memoId, draft);
+ return draft;
+ });
memoDraftPrefetchRef.current.set(memoId, pending);
return pending;
}, []);
- const openRichEditor = useCallback(async (memo: MemoDetail, initialFocus: "body" | "title" = "body") => {
+ const openRichEditor = useCallback((memo: MemoDetail, initialFocus: "body" | "title" = "body") => {
if (hasDiagramDocumentMarker(memo.contentMarkdown)) {
Alert.alert(
resolvedLocale === "en-US" ? "View-only diagram" : "图表暂为只读",
@@ -469,28 +473,19 @@ export const WorkspaceScreen = ({
);
return;
}
- // Unmount detail DomWebView before the editable instance mounts (Android IME).
+ // Keep the detail DomWebView mounted and switch it in place. Remounting the
+ // editor costs ~1s, and waiting on a network refresh made tap-to-edit feel like 2-3s.
beginEditorStartup();
- let editingMemo = memo;
- const queuedItem = (await listMobileSyncQueueItems(syncQueueScope)).find((item) => item.memoId === memo.id);
-
- if (!queuedItem && client && !memo.id.startsWith("local:")) {
- try {
- const response = await client.getMemo(memo.id);
- editingMemo = response.memo;
- await upsertLocalMemo(dataScope, editingMemo);
- queryClient.setQueryData(["mobile", "memo", "notebook", editingMemo.id], { memo: editingMemo });
- queryClient.setQueryData(["mobile", "memo", "trash", editingMemo.id], { memo: editingMemo });
- } catch {
- // The local mirror remains editable while offline.
- }
+ const open = (draft: MobileMemoDraft | null) => {
+ memoDraftPrefetchRef.current.delete(memo.id);
+ setRichEditingSession({ draft, initialFocus, memo });
+ };
+ if (memoDraftValueRef.current.has(memo.id)) {
+ open(memoDraftValueRef.current.get(memo.id) ?? null);
+ return;
}
-
- const draft = await loadMemoDraft(editingMemo.id);
- memoDraftPrefetchRef.current.delete(memo.id);
- setSelectedMemoId(null);
- setRichEditingSession({ draft, initialFocus, memo: editingMemo });
- }, [client, dataScope, loadMemoDraft, queryClient, resolvedLocale, syncQueueScope]);
+ void loadMemoDraft(memo.id).then(open);
+ }, [loadMemoDraft, resolvedLocale]);
const memos = useMemo(() => memosQuery.data?.pages.flatMap((page) => page.memos) ?? [], [memosQuery.data]);
const searchResults = useMemo(() => searchQuery.data?.pages.flatMap((page) => page.memos) ?? [], [searchQuery.data]);
@@ -1171,21 +1166,9 @@ export const WorkspaceScreen = ({
]);
};
- if (richEditingSession) {
- return <RichEditorModal
- baseUrl={session?.baseUrl ?? ""}
- initialDraft={richEditingSession.draft}
- initialFocus={richEditingSession.initialFocus}
- imageCompressionEnabled={imageCompressionEnabled}
- memo={richEditingSession.memo}
- notebooks={notebooks}
- onClose={closeRichEditor}
- updateMutation={localUpdateMemoMutation}
- />;
- }
-
- // Full-tree create (same as rich edit) — never stack DomWebView inside RN Modal over
+ // Full-tree create — never stack a second DomWebView inside an RN Modal over
// list/detail WebViews; that breaks Android soft-input attachment.
+ // Existing-note edits stay on the detail viewer and switch it in place.
if (createOpen) {
return (
<CreateMemoModal
@@ -1285,6 +1268,8 @@ export const WorkspaceScreen = ({
) : null}
<MemoDetailModal
+ editingSession={richEditingSession}
+ imageCompressionEnabled={imageCompressionEnabled}
initialSearchQuery={selectedMemoId ? searchText.trim() : ""}
isDeleting={deleteMemoMutation.isPending}
isLoading={memoDetailQuery.isLoading}
@@ -1293,10 +1278,12 @@ export const WorkspaceScreen = ({
isSharing={shareMemoMutation.isPending}
memo={selectedMemo}
notebookName={notebooks.find((notebook) => notebook.id === selectedMemo?.notebookId)?.name ?? "未分类"}
+ notebooks={notebooks}
onClose={closeDetail}
+ onCloseEditor={closeRichEditor}
onDelete={handleDeleteMemo}
onDeleteResource={handleDeleteResource}
- onRichEdit={(memo, initialFocus) => void openRichEditor(memo, initialFocus)}
+ onRichEdit={openRichEditor}
onOpenRevisions={setRevisionMemo}
onRenameResource={handleRenameResource}
onAdoptCloudVersion={(memo) => void handleAdoptCloudVersion(memo)}
@@ -1310,6 +1297,7 @@ export const WorkspaceScreen = ({
onShare={(memo) => shareMemoMutation.mutate(memo)}
syncError={selectedMemoSyncError}
syncStatus={selectedMemoSyncStatus}
+ updateMutation={localUpdateMemoMutation}
visible={Boolean(selectedMemoId)}
/>
diff --git a/tests/mobile-app-scope.test.ts b/tests/mobile-app-scope.test.ts
index f41babad..f1c3d84d 100644
--- a/tests/mobile-app-scope.test.ts
+++ b/tests/mobile-app-scope.test.ts
@@ -90,11 +90,28 @@ describe("mobile app scope", () => {
});
test("renders note detail body with the shared read-only TipTap viewer", () => {
- expect(memoDetailSource).toContain('mode="viewer"');
+ expect(memoDetailSource).toContain('mode={isEditing ? "editor" : "viewer"}');
expect(memoDetailSource).toContain("LocalTiptapEditor");
expect(memoDetailSource).not.toContain("react-native-markdown-display");
});
+ test("opens existing-note editing in place without a blocking getMemo", () => {
+ const openRichEditorSource = workspaceSource.slice(
+ workspaceSource.indexOf("const openRichEditor ="),
+ workspaceSource.indexOf("const memos = useMemo"),
+ );
+ expect(openRichEditorSource).not.toContain("client.getMemo");
+ expect(openRichEditorSource).not.toContain("listMobileSyncQueueItems");
+ expect(openRichEditorSource).not.toContain("setSelectedMemoId(null)");
+ expect(openRichEditorSource).toContain("setRichEditingSession");
+ expect(workspaceSource).not.toContain("return <RichEditorModal");
+ expect(memoDetailSource).toContain("useMobileRichEditor");
+ expect(localTiptapEditorSource).toContain("editor.setEditable(!isViewer)");
+ expect(memoDetailSource).toContain("{visible ? (");
+ expect(memoDetailSource).toContain(") : null}");
+ expect(memoDetailSource).toContain('accessibilityLabel="返回" accessibilityRole="button" disabled={editor.uploading}');
+ });
+
test("carries workspace search into note detail and scrolls active matches", () => {
expect(workspaceSource).toContain('initialSearchQuery={selectedMemoId ? searchText.trim() : ""}');
expect(memoDetailSource).toContain("metadataSearchMatchCount + bodySearchMatchCount");