Skip to content

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

feat(mobile): render note preview with read-only TipTap

tianma-if9d73865306d9
diff --git a/apps/mobile/src/components/LocalTiptapEditor.tsx b/apps/mobile/src/components/LocalTiptapEditor.tsx
index 32527cc3..d4b2802b 100644
--- a/apps/mobile/src/components/LocalTiptapEditor.tsx
+++ b/apps/mobile/src/components/LocalTiptapEditor.tsx
@@ -52,23 +52,40 @@ export interface LocalTiptapEditorRef extends DOMImperativeFactory {
search: (query: DOMValue, index: DOMValue) => void;
}
-type LocalTiptapEditorProps = {
- mode?: "editor";
- autoFocus?: boolean;
+type LocalTiptapEditorSharedProps = {
baseUrl: string;
content: EditorDoc;
dom?: DOMProps;
- onChange: (content: EditorDoc) => Promise<void>;
onLoadResource: (source: string) => Promise<string | null>;
onResourcePress?: (targetJson: string) => Promise<void>;
- onPickImage: () => Promise<void>;
- onReady: (startupMs: number) => Promise<void>;
+ onReady?: (startupMs: number) => Promise<void>;
onSearchResult?: (count: number, index: number) => Promise<void>;
ref: Ref<LocalTiptapEditorRef>;
locale: "zh-CN" | "en-US";
theme: "light" | "dark";
};
+/** Editable note body with toolbar (create / rich edit). */
+type LocalTiptapEditorModeProps = LocalTiptapEditorSharedProps & {
+ mode?: "editor";
+ autoFocus?: boolean;
+ onChange: (content: EditorDoc) => Promise<void>;
+ onPickImage: () => 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";
+ /** JSON: `{ alt: string; source: string }` for fullscreen image preview. */
+ onImagePreview?: (payloadJson: string) => Promise<void>;
+};
+
+type LocalTiptapEditorProps = LocalTiptapEditorModeProps | LocalTiptapViewerModeProps;
+
type MermaidRendererProps = {
diagramsJson: string;
dom?: DOMProps;
@@ -106,7 +123,8 @@ const normalizeEditorAttachmentFilename = (label: string, resourceId: string) =>
const handleMobileResourceEvent = (
event: Event,
- onResourcePress?: (targetJson: string) => Promise<void>
+ onResourcePress?: (targetJson: string) => Promise<void>,
+ options?: { allowImagePreview?: boolean; onImagePreview?: (payloadJson: string) => Promise<void> }
) => {
const element = event.target instanceof Element ? event.target : null;
const link = element?.closest<HTMLAnchorElement>('a.edgeever-attachment-link, a[href*="/api/v1/resources/"]');
@@ -127,18 +145,33 @@ const handleMobileResourceEvent = (
const imageFigure = element?.closest<HTMLElement>("figure.edgeever-image-node");
const imageHref = imageFigure?.dataset.resourceHref ?? "";
const imageResourceId = getResourceIdFromUrl(imageHref);
+ if (!imageFigure || !imageHref) return false;
+
const imageActionRequested = event.type === "contextmenu" || Boolean(element?.closest(".edgeever-image-actions"));
- if (!imageFigure || !imageResourceId || !imageActionRequested || !onResourcePress) return false;
-
- event.preventDefault();
- event.stopPropagation();
- void onResourcePress(JSON.stringify({
- filename: imageFigure.dataset.resourceFilename || `image-${imageResourceId}`,
- href: imageHref,
- kind: "image",
- resourceId: imageResourceId,
- } satisfies EditorResourceTarget));
- return true;
+ if (imageActionRequested && imageResourceId && onResourcePress) {
+ event.preventDefault();
+ event.stopPropagation();
+ void onResourcePress(JSON.stringify({
+ filename: imageFigure.dataset.resourceFilename || `image-${imageResourceId}`,
+ href: imageHref,
+ kind: "image",
+ resourceId: imageResourceId,
+ } satisfies EditorResourceTarget));
+ return true;
+ }
+
+ // Viewer: plain image tap opens native fullscreen preview.
+ if (options?.allowImagePreview && options.onImagePreview && !imageActionRequested) {
+ event.preventDefault();
+ event.stopPropagation();
+ void options.onImagePreview(JSON.stringify({
+ alt: imageFigure.dataset.resourceFilename || "",
+ source: imageHref,
+ }));
+ return true;
+ }
+
+ return false;
};
const getMobileMermaidTheme = (theme: "light" | "dark") => THEMES[theme === "dark" ? "zinc-dark" : "zinc-light"];
@@ -292,26 +325,35 @@ const inlineMermaidSvgStyles = (svg: string) => {
};
function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
+ const isViewer = props.mode === "viewer";
+ const autoFocus = props.mode === "viewer" ? false : Boolean(props.autoFocus);
const startedAtRef = useRef(performance.now());
const changeTimerRef = useRef<number | null>(null);
const imageUploadInFlightRef = useRef(false);
const pendingImageSelectionRef = useRef<{ from: number; to: number } | null>(null);
- const onChangeRef = useRef(props.onChange);
+ const onChangeRef = useRef(props.mode === "viewer" ? undefined : props.onChange);
const onLoadResourceRef = useRef(props.onLoadResource);
const onResourcePressRef = useRef(props.onResourcePress);
- const onPickImageRef = useRef(props.onPickImage);
- const onReadyRef = useRef(props.onReady);
+ const onImagePreviewRef = useRef(props.mode === "viewer" ? props.onImagePreview : undefined);
+ const onPickImageRef = useRef(props.mode === "viewer" ? undefined : props.onPickImage);
+ const onReadyRef = useRef(props.onReady ?? (async () => undefined));
const onSearchResultRef = useRef(props.onSearchResult ?? ignoreSearchResult);
- onChangeRef.current = props.onChange;
+ onChangeRef.current = props.mode === "viewer" ? undefined : props.onChange;
onLoadResourceRef.current = props.onLoadResource;
onResourcePressRef.current = props.onResourcePress;
- onPickImageRef.current = props.onPickImage;
- onReadyRef.current = props.onReady;
+ onImagePreviewRef.current = props.mode === "viewer" ? props.onImagePreview : undefined;
+ onPickImageRef.current = props.mode === "viewer" ? undefined : props.onPickImage;
+ onReadyRef.current = props.onReady ?? (async () => undefined);
onSearchResultRef.current = props.onSearchResult ?? ignoreSearchResult;
const protectedImageExtension = useMemo(
- () => createProtectedImageExtension(props.baseUrl, props.locale, (source) => onLoadResourceRef.current(source)),
- [props.baseUrl, props.locale]
+ () => createProtectedImageExtension(
+ props.baseUrl,
+ props.locale,
+ (source) => onLoadResourceRef.current(source),
+ { readOnly: isViewer }
+ ),
+ [isViewer, props.baseUrl, props.locale]
);
const mermaidCodeBlockExtension = useMemo(
() => createMobileCodeBlockExtension(props.locale, props.theme),
@@ -319,7 +361,8 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
);
const editor = useEditor({
- autofocus: props.autoFocus ? "end" : false,
+ editable: !isViewer,
+ autofocus: autoFocus ? "end" : false,
extensions: [
StarterKit.configure({ codeBlock: false, link: { openOnClick: false } }),
mermaidCodeBlockExtension,
@@ -327,19 +370,32 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
TableKit.configure({
table: { renderWrapper: true },
}),
- Placeholder.configure({
- placeholder: getMobileEditorPlaceholder(props.locale),
- }),
+ ...(isViewer
+ ? []
+ : [Placeholder.configure({
+ placeholder: getMobileEditorPlaceholder(props.locale),
+ })]),
],
content: resolveImageSources(props.content, props.baseUrl),
editorProps: {
- attributes: getMobileEditorInputAttributes("edgeever-editor-content"),
- handleClick: (_view, _pos, event) => handleMobileResourceEvent(event, onResourcePressRef.current),
+ attributes: getMobileEditorInputAttributes(
+ isViewer ? "edgeever-editor-content edgeever-viewer-content" : "edgeever-editor-content"
+ ),
+ handleClick: (_view, _pos, event) => handleMobileResourceEvent(event, onResourcePressRef.current, {
+ allowImagePreview: isViewer,
+ onImagePreview: onImagePreviewRef.current,
+ }),
handleDOMEvents: {
- contextmenu: (_view, event) => handleMobileResourceEvent(event, onResourcePressRef.current),
+ contextmenu: (_view, event) => handleMobileResourceEvent(event, onResourcePressRef.current, {
+ allowImagePreview: false,
+ onImagePreview: onImagePreviewRef.current,
+ }),
},
},
onUpdate: ({ editor: activeEditor, transaction }) => {
+ if (isViewer || !onChangeRef.current) {
+ return;
+ }
if (transaction.getMeta(TRANSIENT_IMAGE_UPLOAD_META)) {
return;
}
@@ -348,13 +404,13 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
}
changeTimerRef.current = window.setTimeout(() => {
changeTimerRef.current = null;
- void onChangeRef.current(getPersistableEditorDoc(activeEditor.getJSON() as EditorDoc, props.baseUrl));
+ void onChangeRef.current?.(getPersistableEditorDoc(activeEditor.getJSON() as EditorDoc, props.baseUrl));
}, CHANGE_IDLE_MS);
},
});
const flush = useCallback(() => {
- if (!editor || editor.isDestroyed) {
+ if (isViewer || !editor || editor.isDestroyed || !onChangeRef.current) {
return;
}
if (changeTimerRef.current !== null) {
@@ -362,7 +418,7 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
changeTimerRef.current = null;
}
void onChangeRef.current(getPersistableEditorDoc(editor.getJSON() as EditorDoc, props.baseUrl));
- }, [editor, props.baseUrl]);
+ }, [editor, isViewer, props.baseUrl]);
const search = useCallback((query: DOMValue, requestedIndex: DOMValue) => {
const matches = getEditorSearchMatches(editor, typeof query === "string" ? query : "");
@@ -400,7 +456,7 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
}, [editor, search]);
const beginImageUpload = useCallback((uploadIdValue: DOMValue, previewDataUrlValue: DOMValue) => {
- if (!editor || typeof uploadIdValue !== "string" || typeof previewDataUrlValue !== "string") {
+ if (isViewer || !editor || typeof uploadIdValue !== "string" || typeof previewDataUrlValue !== "string") {
return;
}
insertImageUploadPlaceholder(
@@ -410,7 +466,7 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
previewDataUrlValue,
pendingImageSelectionRef.current
);
- }, [editor, props.locale]);
+ }, [editor, isViewer, props.locale]);
const cancelImageUpload = useCallback((uploadIdValue: DOMValue) => {
if (!editor || typeof uploadIdValue !== "string") {
@@ -515,13 +571,15 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
completeImageUpload,
appendAttachment,
flush,
- focusEnd: () => editor?.commands.focus("end"),
+ focusEnd: () => {
+ if (!isViewer) editor?.commands.focus("end");
+ },
removeResource,
renameResource,
replaceAll,
search,
}),
- [appendAttachment, beginImageUpload, cancelImageUpload, completeImageUpload, editor, flush, removeResource, renameResource, replaceAll, search]
+ [appendAttachment, beginImageUpload, cancelImageUpload, completeImageUpload, editor, flush, isViewer, removeResource, renameResource, replaceAll, search]
);
useEffect(() => {
@@ -532,7 +590,7 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
void onReadyRef.current(Math.round(performance.now() - startedAtRef.current));
let focusFrame = 0;
let focusRetry: number | null = null;
- if (props.autoFocus) {
+ if (autoFocus) {
const focusAtEnd = () => {
if (!editor.isDestroyed) {
editor.commands.focus("end");
@@ -550,21 +608,38 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
flush();
}
};
- window.addEventListener("pagehide", handlePageHide);
- document.addEventListener("visibilitychange", handleVisibilityChange);
+ if (!isViewer) {
+ window.addEventListener("pagehide", handlePageHide);
+ document.addEventListener("visibilitychange", handleVisibilityChange);
+ }
return () => {
window.cancelAnimationFrame(focusFrame);
if (focusRetry !== null) {
window.clearTimeout(focusRetry);
}
- window.removeEventListener("pagehide", handlePageHide);
- document.removeEventListener("visibilitychange", handleVisibilityChange);
+ if (!isViewer) {
+ window.removeEventListener("pagehide", handlePageHide);
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
+ }
if (changeTimerRef.current !== null) {
window.clearTimeout(changeTimerRef.current);
}
};
- }, [editor, flush, props.autoFocus]);
+ }, [autoFocus, editor, flush, isViewer]);
+
+ // Keep the viewer in sync when the parent swaps memo content.
+ useEffect(() => {
+ if (!editor || editor.isDestroyed || !isViewer) {
+ return;
+ }
+ const next = resolveImageSources(props.content, props.baseUrl);
+ const current = JSON.stringify(editor.getJSON());
+ const incoming = JSON.stringify(next);
+ if (current !== incoming) {
+ editor.commands.setContent(next, { emitUpdate: false });
+ }
+ }, [editor, isViewer, props.baseUrl, props.content]);
const toolbarState = useEditorState({
editor,
@@ -575,7 +650,7 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
});
const insertImage = async () => {
- if (!editor || imageUploadInFlightRef.current) {
+ if (isViewer || !editor || imageUploadInFlightRef.current || !onPickImageRef.current) {
return;
}
@@ -613,23 +688,25 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {
};
return (
- <div className="edgeever-editor-shell">
- <style>{getEditorStyles(props.theme)}</style>
- <div aria-label={getMobileEditorToolbarLabel(props.locale)} className="edgeever-editor-toolbar" role="toolbar">
- {MOBILE_EDITOR_TOOLBAR_ACTIONS.map((action) => (
- <ToolbarButton
- key={action.id}
- active={action.activeFlag > 0 && Boolean(toolbarState & action.activeFlag)}
- disabled={(action.id === "increaseListIndent"
- && !Boolean(editor?.can().chain().focus().sinkListItem("listItem").run()))
- || (action.id === "decreaseListIndent"
- && !Boolean(editor?.can().chain().focus().liftListItem("listItem").run()))}
- icon={toolbarIcons[action.id]}
- label={getMobileEditorToolbarActionLabel(action.id, props.locale)}
- onRun={toolbarHandlers[action.id]}
- />
- ))}
- </div>
+ <div className={isViewer ? "edgeever-editor-shell edgeever-viewer-shell" : "edgeever-editor-shell"}>
+ <style>{getEditorStyles(props.theme, { viewer: isViewer })}</style>
+ {!isViewer ? (
+ <div aria-label={getMobileEditorToolbarLabel(props.locale)} className="edgeever-editor-toolbar" role="toolbar">
+ {MOBILE_EDITOR_TOOLBAR_ACTIONS.map((action) => (
+ <ToolbarButton
+ key={action.id}
+ active={action.activeFlag > 0 && Boolean(toolbarState & action.activeFlag)}
+ disabled={(action.id === "increaseListIndent"
+ && !Boolean(editor?.can().chain().focus().sinkListItem("listItem").run()))
+ || (action.id === "decreaseListIndent"
+ && !Boolean(editor?.can().chain().focus().liftListItem("listItem").run()))}
+ icon={toolbarIcons[action.id]}
+ label={getMobileEditorToolbarActionLabel(action.id, props.locale)}
+ onRun={toolbarHandlers[action.id]}
+ />
+ ))}
+ </div>
+ ) : null}
<EditorContent editor={editor} />
</div>
);
@@ -1052,7 +1129,8 @@ const createMobileImageSizeControls = (
const createProtectedImageExtension = (
baseUrl: string,
locale: "zh-CN" | "en-US",
- loadResource: (source: string) => Promise<string | null>
+ loadResource: (source: string) => Promise<string | null>,
+ options?: { readOnly?: boolean }
) => Image.extend({
addAttributes() {
return {
@@ -1070,7 +1148,11 @@ const createProtectedImageExtension = (
},
addNodeView() {
return ({ editor, getPos, node }) => {
+ const readOnly = Boolean(options?.readOnly) || !editor.isEditable;
const updateWidth = (width: number) => {
+ if (readOnly) {
+ return;
+ }
const position = getPos();
if (typeof position !== "number") {
return;
@@ -1083,6 +1165,9 @@ const createProtectedImageExtension = (
.run();
};
const sizeControls = createMobileImageSizeControls(locale, updateWidth);
+ if (readOnly) {
+ sizeControls.setVisible(false);
+ }
if (isMobileImageUploadPlaceholderSource(node.attrs.src)) {
const placeholder = document.createElement("div");
@@ -1297,7 +1382,7 @@ const createProtectedImageExtension = (
},
selectNode: () => {
wrapper.classList.add("is-selected");
- sizeControls.setVisible(true);
+ sizeControls.setVisible(!readOnly);
},
deselectNode: () => {
wrapper.classList.remove("is-selected");
@@ -1417,12 +1502,13 @@ const removeImageUploadPlaceholder = (editor: TiptapEditor, source: string) => {
}).run();
};
-const getEditorStyles = (theme: "light" | "dark") => `
+const getEditorStyles = (theme: "light" | "dark", options?: { viewer?: boolean }) => `
:root { color-scheme: ${theme}; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
* { box-sizing: border-box; }
html, body, #root { width: 100%; height: 100%; margin: 0; background: ${theme === "dark" ? "#0f172a" : "#fff"}; }
body { overflow: hidden; color: ${theme === "dark" ? "#f8fafc" : "#0f172a"}; }
.edgeever-editor-shell { display: flex; height: 100%; min-height: 100%; flex-direction: column; background: ${theme === "dark" ? "#0f172a" : "#fff"}; }
+ .edgeever-viewer-shell { -webkit-user-select: text; user-select: text; }
.edgeever-editor-toolbar { display: flex; flex: 0 0 auto; align-items: center; gap: 4px; min-height: 38px; overflow-x: auto; padding: 6px 12px; border-block: 1px solid ${theme === "dark" ? "#334155" : "#f1f5f9"}; background: ${theme === "dark" ? "#0f172a" : "#fff"}; scrollbar-width: none; }
.edgeever-editor-toolbar::-webkit-scrollbar { display: none; }
.edgeever-editor-toolbar button { display: inline-flex; flex: 0 0 auto; align-items: center; justify-content: center; width: 36px; min-height: 32px; padding: 0; border: 1px solid transparent; border-radius: 999px; background: transparent; color: ${theme === "dark" ? "#cbd5e1" : "#64748b"}; }
@@ -1430,7 +1516,8 @@ const getEditorStyles = (theme: "light" | "dark") => `
.edgeever-editor-toolbar button:disabled { opacity: 0.38; }
.tiptap { min-height: 100%; outline: none; }
.edgeever-editor-shell > div:last-child { min-height: 0; flex: 1; overflow-y: auto; overscroll-behavior: contain; -webkit-overflow-scrolling: touch; }
- .edgeever-editor-content { min-height: 100%; padding: 18px 12px 32px; font-size: 17px; line-height: ${MEMO_CONTENT_STYLE.body.lineHeight / MEMO_CONTENT_STYLE.body.fontSize}; word-break: break-word; caret-color: #0f766e; }
+ .edgeever-editor-content { min-height: 100%; padding: 18px 12px 32px; font-size: 17px; line-height: ${MEMO_CONTENT_STYLE.body.lineHeight / MEMO_CONTENT_STYLE.body.fontSize}; word-break: break-word; caret-color: ${options?.viewer ? "transparent" : "#0f766e"}; }
+ .edgeever-viewer-content { -webkit-user-select: text; user-select: text; cursor: text; }
.edgeever-editor-content > :first-child { margin-top: 0; }
.edgeever-editor-content p { margin: 0 0 ${MEMO_CONTENT_STYLE.body.paragraphSpacing}px; padding: 0; line-height: ${MEMO_CONTENT_STYLE.body.lineHeight / MEMO_CONTENT_STYLE.body.fontSize}; }
.edgeever-editor-content p.is-editor-empty:first-child::before { float: left; height: 0; color: #94a3b8; content: attr(data-placeholder); pointer-events: none; }
diff --git a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
index 4cd7aad2..46d54304 100644
--- a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
+++ b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx
@@ -1,45 +1,67 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
-import { MEMO_CONTENT_STYLE, resolveMemoContentMarkdown, type MemoDetail } from "@edgeever/shared";
-import { ActivityIndicator, Image as RNImage, Platform, ScrollView, StyleSheet, Text as RNText, useWindowDimensions, View, type ImageStyle, type StyleProp, type TextStyle, type ViewStyle } from "react-native";
+import { resolveMemoContentDoc, type MemoDetail, type TiptapDoc } from "@edgeever/shared";
+import { ActivityIndicator, Image as RNImage, Platform, StyleSheet, View, type ImageStyle, type StyleProp } from "react-native";
import { Modal } from "react-native";
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
-import Markdown, { type ASTNode, type RenderRules } from "react-native-markdown-display";
import { SvgXml } from "react-native-svg";
import { ChevronDown, ChevronLeft, ChevronRight, History, MoreHorizontal, Pencil, RotateCcw, Search, Share2, Tag, Trash2, X } from "../components/icons";
import { Alert, Pressable, Text, TextInput } from "../components/LocalizedText";
-import { MobileMermaidDiagram, MobileMermaidProvider } from "../components/MobileMermaid";
-import { MobileAttachmentCard, MobileResourceActions } from "../components/MobileResourceActions";
+import LocalTiptapEditor, { type LocalTiptapEditorRef } from "../components/LocalTiptapEditor";
+import { MobileResourceActions } from "../components/MobileResourceActions";
import {
- getMobileImageTarget,
- getParagraphAttachmentTarget,
openMobileResource,
+ parseMobileResourceTargetJson,
saveMobileResourceAs,
- type MobileAttachmentTarget,
type MobileResourceTarget,
} from "../lib/mobile-attachments";
-import { getMobileMarkdownFenceLanguage, trimMobileMarkdownFenceContent } from "../lib/mobile-mermaid";
import { useMobileLocale } from "../lib/mobile-locale";
-import { resolveMobileThemeStyles, useMobileTheme } from "../lib/mobile-theme";
+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 { formatDate, getTextSearchMatches } from "./workspace-utils";
import { styles } from "./workspace-styles";
-const DETAIL_CONTENT_HORIZONTAL_PADDING = 16;
-const DETAIL_TABLE_FIT_COLUMN_COUNT = 3;
-const DETAIL_TABLE_MIN_COLUMN_WIDTH = 132;
const ANDROID_SYSTEM_NAVIGATION_FALLBACK = 48;
const DEFAULT_MEMO_TITLE = "无标题笔记";
-const useMobileLocalePreference = () => useMobileLocale().preference;
+const RESOURCE_DATA_URL_CACHE_LIMIT = 32;
+
+type SessionLike = { baseUrl: string; token: string } | null;
+type AuthenticatedImageSource = {
+ headers?: { Authorization: string };
+ uri: string;
+};
+
+const isProtectedResourceSource = (source: string, session: SessionLike) => {
+ const baseUrl = session?.baseUrl.replace(/\/+$/, "") ?? "";
+ return source.startsWith("/api/v1/resources/")
+ || Boolean(baseUrl && (source.startsWith(`${baseUrl}/api/v1/resources/`) || source.startsWith("/api/v1/resources/")));
+};
+
+/** Ensure protected resource URLs hit the blob route the API serves. */
+const normalizeProtectedResourcePath = (source: string, session: SessionLike) => {
+ const baseUrl = session?.baseUrl.replace(/\/+$/, "") ?? "";
+ let path = source;
+ if (baseUrl && path.startsWith(`${baseUrl}/`)) {
+ path = path.slice(baseUrl.length);
+ }
+ if (!path.startsWith("/api/v1/resources/")) {
+ return path;
+ }
+ if (/\/blob(?:$|[?#])/.test(path)) {
+ return path;
+ }
+ const match = path.match(/^(\/api\/v1\/resources\/[^/?#]+)/);
+ return match ? `${match[1]}/blob` : path;
+};
const getAuthenticatedResourceSource = (
source: string,
- session: { baseUrl: string; token: string } | null
-) => {
+ session: SessionLike
+): AuthenticatedImageSource => {
const baseUrl = session?.baseUrl.replace(/\/+$/, "") ?? "";
const uri = source.startsWith("/") && baseUrl ? `${baseUrl}${source}` : source;
- const isProtectedResource = source.startsWith("/api/v1/resources/") || Boolean(baseUrl && uri.startsWith(`${baseUrl}/api/v1/resources/`));
+ const isProtectedResource = isProtectedResourceSource(source, session)
+ || Boolean(baseUrl && uri.startsWith(`${baseUrl}/api/v1/resources/`));
return {
uri,
@@ -47,6 +69,50 @@ const getAuthenticatedResourceSource = (
};
};
+const blobToDataUrl = (blob: Blob) => new Promise<string>((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onerror = () => reject(reader.error ?? new Error("资源读取失败"));
+ reader.onloadend = () => {
+ if (typeof reader.result === "string") {
+ resolve(reader.result);
+ return;
+ }
+ reject(new Error("资源读取失败"));
+ };
+ reader.readAsDataURL(blob);
+});
+
+const resourceDataUrlCache = new Map<string, Promise<string | null>>();
+const loadProtectedResourceDataUrl = (
+ source: string,
+ session: SessionLike,
+ getResourceBlob: ((resourceUrl: string) => Promise<Blob>) | null | undefined
+) => {
+ if (!getResourceBlob || !isProtectedResourceSource(source, session)) {
+ return Promise.resolve(null);
+ }
+ const path = normalizeProtectedResourcePath(source, session);
+ const cacheKey = `${session?.token ?? ""}\n${path}`;
+ const cached = resourceDataUrlCache.get(cacheKey);
+ if (cached) {
+ return cached;
+ }
+ if (resourceDataUrlCache.size >= RESOURCE_DATA_URL_CACHE_LIMIT) {
+ const oldestKey = resourceDataUrlCache.keys().next().value;
+ if (oldestKey) {
+ resourceDataUrlCache.delete(oldestKey);
+ }
+ }
+ const pending = getResourceBlob(path)
+ .then(blobToDataUrl)
+ .catch(() => {
+ resourceDataUrlCache.delete(cacheKey);
+ return null;
+ });
+ resourceDataUrlCache.set(cacheKey, pending);
+ return pending;
+};
+
type CachedSvgResource = {
aspectRatio: number | null;
xml: string;
@@ -54,9 +120,9 @@ type CachedSvgResource = {
const AUTHENTICATED_SVG_CACHE_LIMIT = 24;
const authenticatedSvgCache = new Map<string, Promise<CachedSvgResource | null>>();
-const getAuthenticatedSvgCacheKey = (source: ReturnType<typeof getAuthenticatedResourceSource>) =>
+const getAuthenticatedSvgCacheKey = (source: AuthenticatedImageSource) =>
`${source.uri}\n${source.headers?.Authorization ?? ""}`;
-const loadAuthenticatedSvg = (source: ReturnType<typeof getAuthenticatedResourceSource>) => {
+const loadAuthenticatedSvg = (source: AuthenticatedImageSource) => {
const cacheKey = getAuthenticatedSvgCacheKey(source);
const cached = authenticatedSvgCache.get(cacheKey);
if (cached) {
@@ -96,27 +162,49 @@ const loadAuthenticatedSvg = (source: ReturnType<typeof getAuthenticatedResource
const AuthenticatedResourceImage = ({
alt,
fitAspect = false,
+ href,
+ loadResourceBlob,
resizeMode = "cover",
- source,
+ session,
style,
}: {
alt: string;
fitAspect?: boolean;
+ href: string;
+ loadResourceBlob?: ((resourceUrl: string) => Promise<Blob>) | null;
resizeMode?: "center" | "contain" | "cover" | "repeat" | "stretch";
- source: ReturnType<typeof getAuthenticatedResourceSource>;
+ session: SessionLike;
style: StyleProp<ImageStyle>;
}) => {
+ const headerSource = useMemo(() => getAuthenticatedResourceSource(href, session), [href, session]);
+ const [displaySource, setDisplaySource] = useState<AuthenticatedImageSource>(headerSource);
const [aspectRatio, setAspectRatio] = useState(16 / 9);
const [svgXml, setSvgXml] = useState<string | null>(null);
const svgRequestStartedRef = useRef(false);
const svgSourceKeyRef = useRef("");
- const svgSourceKey = getAuthenticatedSvgCacheKey(source);
+ const svgSourceKey = getAuthenticatedSvgCacheKey(displaySource);
const imageStyle = fitAspect ? [style, { aspectRatio, height: undefined, width: "100%" as const }] : style;
useEffect(() => {
+ let cancelled = false;
setSvgXml(null);
setAspectRatio(16 / 9);
svgRequestStartedRef.current = false;
+ setDisplaySource(headerSource);
+
+ void loadProtectedResourceDataUrl(href, session, loadResourceBlob).then((dataUrl) => {
+ if (cancelled || !dataUrl) {
+ return;
+ }
+ setDisplaySource({ uri: dataUrl });
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [headerSource, href, loadResourceBlob, session]);
+
+ useEffect(() => {
svgSourceKeyRef.current = svgSourceKey;
const cached = authenticatedSvgCache.get(svgSourceKey);
if (cached) {
@@ -143,7 +231,7 @@ const AuthenticatedResourceImage = ({
return;
}
svgRequestStartedRef.current = true;
- void loadAuthenticatedSvg(source)
+ void loadAuthenticatedSvg(displaySource)
.then((result) => {
if (!result || svgSourceKeyRef.current !== svgSourceKey) {
return;
@@ -177,7 +265,7 @@ const AuthenticatedResourceImage = ({
onError={loadSvgFallback}
resizeMethod={Platform.OS === "android" ? "resize" : "auto"}
resizeMode={resizeMode}
- source={source}
+ source={displaySource}
style={imageStyle}
/>
);
@@ -240,203 +328,79 @@ export const MemoDetailModal = ({
const { client, session } = useSession();
const { resolvedTheme } = useMobileTheme();
const { resolvedLocale } = useMobileLocale();
- const { width: viewportWidth } = useWindowDimensions();
const safeAreaInsets = useSafeAreaInsets();
const [actionsOpen, setActionsOpen] = useState(false);
const [searchOpen, setSearchOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState("");
+ const [searchMatchCount, setSearchMatchCount] = useState(0);
const [activeMatchIndex, setActiveMatchIndex] = useState(0);
const [imagePreview, setImagePreview] = useState<{ alt: string; source: string } | null>(null);
const [resourceTarget, setResourceTarget] = useState<MobileResourceTarget | null>(null);
- const [downloadingAttachmentId, setDownloadingAttachmentId] = useState<string | null>(null);
- const imageLongPressAtRef = useRef(0);
- const localePreference = useMobileLocalePreference();
+ const [viewerReady, setViewerReady] = useState(false);
+ const viewerRef = useRef<LocalTiptapEditorRef>(null);
+ const resourceDataUrlCacheRef = useRef(new Map<string, Promise<string | null>>());
+
+ const baseUrl = session?.baseUrl.replace(/\/+$/, "") ?? "";
+ const viewerContent = useMemo<TiptapDoc>(
+ () => (memo ? resolveMemoContentDoc(memo.contentJson, memo.contentMarkdown) : { type: "doc", content: [{ type: "paragraph" }] }),
+ [memo]
+ );
+
const downloadResource = useCallback(async (target: MobileResourceTarget) => {
if (!client) throw new Error(resolvedLocale === "en-US" ? "The resource client is unavailable." : "当前无法读取资源。");
- setDownloadingAttachmentId(target.resourceId);
try {
await openMobileResource(client, target);
- } finally {
- setDownloadingAttachmentId(null);
+ } catch (error) {
+ Alert.alert(
+ resolvedLocale === "en-US" ? "Unable to open resource" : "无法打开资源",
+ error instanceof Error ? error.message : (resolvedLocale === "en-US" ? "Try again later." : "请稍后重试。")
+ );
+ throw error;
}
}, [client, resolvedLocale]);
const saveResourceAs = useCallback(async (target: MobileResourceTarget) => {
if (!client) throw new Error(resolvedLocale === "en-US" ? "The resource client is unavailable." : "当前无法读取资源。");
await saveMobileResourceAs(client, target);
}, [client, resolvedLocale]);
- const openAttachmentFromCard = useCallback((target: MobileAttachmentTarget) => {
- void downloadResource(target).catch((error) => {
- Alert.alert(
- resolvedLocale === "en-US" ? "Unable to open attachment" : "无法打开附件",
- error instanceof Error ? error.message : (resolvedLocale === "en-US" ? "Try again later." : "请稍后重试。")
- );
- });
- }, [downloadResource, resolvedLocale]);
- const themedDetailMarkdownStyles = useMemo(
- () => ({
- ...resolveMobileThemeStyles(detailMarkdownStyles, resolvedTheme),
- hr: {
- ...detailMarkdownStyles.hr,
- backgroundColor: MEMO_CONTENT_STYLE.divider.color[resolvedTheme],
- },
- }),
- [resolvedTheme]
- );
- const detailMarkdownRules = useMemo<RenderRules>(() => {
- const availableTableWidth = Math.max(0, viewportWidth - DETAIL_CONTENT_HORIZONTAL_PADDING * 2);
- const getTableColumnCount = (node: ASTNode, parents: ASTNode[]) => {
- const table = node.type === "table" ? node : parents.find((parent) => parent.type === "table");
- const tableSection = table?.children.find((child) => child.type === "thead" || child.type === "tbody");
- const firstRow = tableSection?.children.find((child) => child.type === "tr");
- return Math.max(1, firstRow?.children.filter((child) => child.type === "th" || child.type === "td").length ?? 1);
- };
- const renderTableCell = (node: ASTNode, children: ReactNode[], parents: ASTNode[], markdownStyles: Record<string, StyleProp<ViewStyle>>, isHeader: boolean) => {
- const columnCount = getTableColumnCount(node, parents);
- const row = parents.find((parent) => parent.type === "tr");
- const cellIndex = row?.children.findIndex((child) => child.key === node.key) ?? -1;
- const isLastCell = cellIndex === (row?.children.length ?? 0) - 1;
- const wideCellStyle = columnCount > DETAIL_TABLE_FIT_COLUMN_COUNT
- ? { flex: 0, width: DETAIL_TABLE_MIN_COLUMN_WIDTH }
- : undefined;
-
- return (
- <View
- key={node.key}
- style={[
- markdownStyles[isHeader ? "_VIEW_SAFE_th" : "_VIEW_SAFE_td"],
- wideCellStyle,
- !isLastCell && markdownStyles._VIEW_SAFE_tableCellDivider,
- ]}
- >
- {children}
- </View>
- );
- };
- const renderSelectableTextBlock = (
- node: ASTNode,
- children: ReactNode[],
- markdownStyles: Record<string, StyleProp<ViewStyle>>,
- ) => (
- <RNText key={node.key} selectable style={markdownStyles[node.type] as StyleProp<TextStyle>}>
- {children}
- </RNText>
- );
+ const loadViewerResource = useCallback((source: string) => {
+ if (!client) {
+ return Promise.resolve(null);
+ }
+ const path = normalizeProtectedResourcePath(source, session);
+ const cached = resourceDataUrlCacheRef.current.get(path);
+ if (cached) {
+ return cached;
+ }
+ const pending = client.getResourceBlob(path).then(blobToDataUrl).catch(() => null);
+ resourceDataUrlCacheRef.current.set(path, pending);
+ return pending;
+ }, [client, session]);
+
+ const onResourcePress = useCallback(async (targetJson: string) => {
+ const target = parseMobileResourceTargetJson(targetJson);
+ if (target) {
+ setResourceTarget(target);
+ }
+ }, []);
- // Select complete block-level text nodes instead of every inline text group.
- // Android then keeps dividers and other View-based blocks in the native layout
- // while still exposing the system copy menu for normal note text.
- return {
- code_block: (node, _children, _parents, markdownStyles, inheritedStyles = {}) => (
- <RNText key={node.key} selectable style={[inheritedStyles, markdownStyles.code_block]}>
- {node.content.endsWith("\n") ? node.content.slice(0, -1) : node.content}
- </RNText>
- ),
- fence: (node, _children, _parents, markdownStyles, inheritedStyles = {}) => {
- const language = getMobileMarkdownFenceLanguage((node as ASTNode & { sourceInfo?: string }).sourceInfo);
- const content = trimMobileMarkdownFenceContent(node.content);
- if (language === "mermaid") {
- return (
- <MobileMermaidDiagram
- key={node.key}
- locale={resolvedLocale}
- source={content}
- theme={resolvedTheme}
- />
- );
- }
- return <RNText key={node.key} selectable style={[inheritedStyles, markdownStyles.fence]}>{content}</RNText>;
- },
- image: (node, _children, _parents, markdownStyles) => {
- const source = String(node.attributes.src ?? "");
- const alt = String(node.attributes.alt ?? "");
- const target = getMobileImageTarget(source, alt);
- const image = (
- <AuthenticatedResourceImage
- alt={alt}
- fitAspect
- resizeMode="contain"
- source={getAuthenticatedResourceSource(source, session)}
- style={markdownStyles._VIEW_SAFE_image}
- />
- );
- if (!target) return <View key={node.key}>{image}</View>;
- return (
- <View key={node.key} style={resourceImageStyles.container}>
- <Pressable
- accessibilityLabel={alt || target.filename}
- accessibilityRole="imagebutton"
- onLongPress={() => {
- imageLongPressAtRef.current = Date.now();
- setResourceTarget(target);
- }}
- onPress={() => {
- if (Date.now() - imageLongPressAtRef.current < 800) return;
- setImagePreview({ alt, source });
- }}
- >
- {image}
- </Pressable>
- <Pressable
- accessibilityLabel={resolvedLocale === "en-US" ? "Image actions" : "图片操作"}
- accessibilityRole="button"
- onPress={() => setResourceTarget(target)}
- style={resourceImageStyles.actions}
- >
- <MoreHorizontal color="#334155" size={22} />
- </Pressable>
- </View>
- );
- },
- heading1: (node, children, _parents, markdownStyles) => renderSelectableTextBlock(node, children, markdownStyles),
- heading2: (node, children, _parents, markdownStyles) => renderSelectableTextBlock(node, children, markdownStyles),
- heading3: (node, children, _parents, markdownStyles) => renderSelectableTextBlock(node, children, markdownStyles),
- heading4: (node, children, _parents, markdownStyles) => renderSelectableTextBlock(node, children, markdownStyles),
- heading5: (node, children, _parents, markdownStyles) => renderSelectableTextBlock(node, children, markdownStyles),
- heading6: (node, children, _parents, markdownStyles) => renderSelectableTextBlock(node, children, markdownStyles),
- paragraph: (node, children, _parents, markdownStyles) => {
- const target = getParagraphAttachmentTarget(node);
- if (target) {
- return (
- <MobileAttachmentCard
- busy={downloadingAttachmentId === target.resourceId}
- key={node.key}
- onActions={() => setResourceTarget(target)}
- onOpen={() => openAttachmentFromCard(target)}
- target={target}
- />
- );
- }
- return renderSelectableTextBlock(node, children, markdownStyles);
- },
- table: (node, children, parents, markdownStyles) => {
- const columnCount = getTableColumnCount(node, parents);
- const tableWidth = columnCount > DETAIL_TABLE_FIT_COLUMN_COUNT
- ? columnCount * DETAIL_TABLE_MIN_COLUMN_WIDTH
- : availableTableWidth;
-
- return (
- <ScrollView
- contentContainerStyle={markdownStyles._VIEW_SAFE_tableScrollContent}
- horizontal
- key={node.key}
- nestedScrollEnabled
- showsHorizontalScrollIndicator={columnCount > DETAIL_TABLE_FIT_COLUMN_COUNT}
- style={markdownStyles._VIEW_SAFE_tableScroll}
- >
- <View style={[markdownStyles._VIEW_SAFE_table, { width: tableWidth }]}>{children}</View>
- </ScrollView>
- );
- },
- td: (node, children, parents, markdownStyles) => renderTableCell(node, children, parents, markdownStyles, false),
- th: (node, children, parents, markdownStyles) => renderTableCell(node, children, parents, markdownStyles, true),
- };
- }, [downloadingAttachmentId, openAttachmentFromCard, resolvedLocale, resolvedTheme, session, viewportWidth]);
- const detailText = memo
- ? resolveMemoContentMarkdown(memo.contentJson, memo.contentMarkdown) || memo.contentText || "没有正文内容"
- : "没有正文内容";
- const searchMatches = useMemo(() => getTextSearchMatches(detailText, searchQuery), [detailText, searchQuery]);
- const searchMatchLabel = searchQuery.trim() ? `${searchMatches.length > 0 ? activeMatchIndex + 1 : 0}/${searchMatches.length}` : "0/0";
+ const onImagePreview = useCallback(async (payloadJson: string) => {
+ try {
+ const parsed = JSON.parse(payloadJson) as { alt?: unknown; source?: unknown };
+ if (typeof parsed.source === "string" && parsed.source) {
+ setImagePreview({
+ alt: typeof parsed.alt === "string" ? parsed.alt : "",
+ source: parsed.source,
+ });
+ }
+ } catch {
+ // Ignore malformed bridge payloads.
+ }
+ }, []);
+
+ const searchMatchLabel = searchQuery.trim()
+ ? `${searchMatchCount > 0 ? activeMatchIndex + 1 : 0}/${searchMatchCount}`
+ : "0/0";
const syncStatusLabel = isSaving || syncStatus === "syncing"
? "保存中"
: syncStatus === "conflict"
@@ -452,15 +416,28 @@ export const MemoDetailModal = ({
) + 16;
useEffect(() => {
+ setViewerReady(false);
+ setSearchOpen(false);
+ setSearchQuery("");
+ setSearchMatchCount(0);
setActiveMatchIndex(0);
- }, [detailText, searchQuery]);
+ setImagePreview(null);
+ setResourceTarget(null);
+ resourceDataUrlCacheRef.current.clear();
+ }, [memo?.id]);
- const moveSearchMatch = (direction: 1 | -1) => {
- if (searchMatches.length === 0) {
+ useEffect(() => {
+ if (!viewerReady || !searchOpen) {
return;
}
+ viewerRef.current?.search(searchQuery, activeMatchIndex);
+ }, [activeMatchIndex, searchOpen, searchQuery, viewerReady]);
- setActiveMatchIndex((current) => (current + direction + searchMatches.length) % searchMatches.length);
+ const moveSearchMatch = (direction: 1 | -1) => {
+ if (searchMatchCount === 0) {
+ return;
+ }
+ setActiveMatchIndex((current) => (current + direction + searchMatchCount) % searchMatchCount);
};
const closeActionsAndRun = (action: () => void) => {
@@ -511,6 +488,16 @@ export const MemoDetailModal = ({
<History color="#475569" size={20} />
</Pressable>
) : null}
+ {memo && !memo.isDeleted ? (
+ <Pressable
+ accessibilityLabel="搜索当前笔记"
+ accessibilityRole="button"
+ onPress={() => setSearchOpen(true)}
+ style={styles.detailHeaderIconButton}
+ >
+ <Search color="#475569" size={20} />
+ </Pressable>
+ ) : null}
{memo?.isDeleted ? (
<Pressable accessibilityLabel="笔记操作" accessibilityRole="button" onPress={() => setActionsOpen(true)} style={styles.detailHeaderIconButton}>
<MoreHorizontal color="#475569" size={21} />
@@ -524,65 +511,106 @@ export const MemoDetailModal = ({
<ActivityIndicator color="#0f172a" />
</View>
) : memo ? (
- <ScrollView contentContainerStyle={styles.detailContent}>
- <Text selectable style={styles.detailTitle}>{memo.title?.trim() || DEFAULT_MEMO_TITLE}</Text>
- <View style={styles.detailMetaRow}>
- <View style={styles.detailNotebookButton}>
- <Text numberOfLines={1} selectable style={styles.detailNotebookName}>{notebookName}</Text>
- <ChevronDown color="#94a3b8" size={14} />
- </View>
- <View style={styles.detailTagsGroup}>
- <Tag color="#64748b" size={16} />
- <Text
- numberOfLines={1}
- selectable
- style={[styles.detailTagsInline, memo.tags.length === 0 && styles.detailTagsPlaceholder]}
- >
- {memo.tags.length ? memo.tags.join(", ") : "添加标签,用逗号分隔"}
- </Text>
- </View>
- </View>
- {searchOpen ? (
- <View style={styles.noteSearchPanel}>
- <View style={styles.searchBox}>
- <Search color="#64748b" size={18} />
- <TextInput
- accessibilityLabel="在当前笔记内搜索"
- autoCapitalize="none"
- autoCorrect={false}
- onChangeText={setSearchQuery}
- placeholder="在当前笔记内搜索"
- placeholderTextColor="#94a3b8"
- style={styles.searchInput}
- value={searchQuery}
- />
- <Text style={[styles.noteSearchCount, searchQuery.trim() && searchMatches.length === 0 && styles.noteSearchCountEmpty]}>{searchMatchLabel}</Text>
+ <View style={detailLayoutStyles.body}>
+ <View style={detailLayoutStyles.meta}>
+ <Text selectable style={styles.detailTitle}>{memo.title?.trim() || DEFAULT_MEMO_TITLE}</Text>
+ <View style={styles.detailMetaRow}>
+ <View style={styles.detailNotebookButton}>
+ <Text numberOfLines={1} selectable style={styles.detailNotebookName}>{notebookName}</Text>
+ <ChevronDown color="#94a3b8" size={14} />
</View>
- <View style={styles.richEditorSearchActions}>
- <DetailActionButton disabled={searchMatches.length === 0} label="上一个搜索结果" onPress={() => moveSearchMatch(-1)}>
- <ChevronLeft color={searchMatches.length === 0 ? "#cbd5e1" : "#0f172a"} size={16} />
- </DetailActionButton>
- <DetailActionButton disabled={searchMatches.length === 0} label="下一个搜索结果" onPress={() => moveSearchMatch(1)}>
- <ChevronRight color={searchMatches.length === 0 ? "#cbd5e1" : "#0f172a"} size={16} />
- </DetailActionButton>
- <DetailActionButton label="关闭搜索" onPress={() => {
- setSearchOpen(false);
- setSearchQuery("");
- }}>
- <X color="#0f172a" size={16} />
- </DetailActionButton>
+ <View style={styles.detailTagsGroup}>
+ <Tag color="#64748b" size={16} />
+ <Text
+ numberOfLines={1}
+ selectable
+ style={[styles.detailTagsInline, memo.tags.length === 0 && styles.detailTagsPlaceholder]}
+ >
+ {memo.tags.length ? memo.tags.join(", ") : "添加标签,用逗号分隔"}
+ </Text>
</View>
</View>
- ) : null}
- <View style={styles.detailDivider} />
- {searchOpen && searchQuery.trim() ? (
- <HighlightedDetailText activeIndex={activeMatchIndex} matches={searchMatches} text={detailText} />
+ {searchOpen ? (
+ <View style={styles.noteSearchPanel}>
+ <View style={styles.searchBox}>
+ <Search color="#64748b" size={18} />
+ <TextInput
+ accessibilityLabel="在当前笔记内搜索"
+ autoCapitalize="none"
+ autoCorrect={false}
+ onChangeText={(value) => {
+ setSearchQuery(value);
+ setActiveMatchIndex(0);
+ }}
+ placeholder="在当前笔记内搜索"
+ placeholderTextColor="#94a3b8"
+ style={styles.searchInput}
+ value={searchQuery}
+ />
+ <Text style={[styles.noteSearchCount, searchQuery.trim() && searchMatchCount === 0 && styles.noteSearchCountEmpty]}>{searchMatchLabel}</Text>
+ </View>
+ <View style={styles.richEditorSearchActions}>
+ <DetailActionButton disabled={searchMatchCount === 0} label="上一个搜索结果" onPress={() => moveSearchMatch(-1)}>
+ <ChevronLeft color={searchMatchCount === 0 ? "#cbd5e1" : "#0f172a"} size={16} />
+ </DetailActionButton>
+ <DetailActionButton disabled={searchMatchCount === 0} label="下一个搜索结果" onPress={() => moveSearchMatch(1)}>
+ <ChevronRight color={searchMatchCount === 0 ? "#cbd5e1" : "#0f172a"} size={16} />
+ </DetailActionButton>
+ <DetailActionButton label="关闭搜索" onPress={() => {
+ setSearchOpen(false);
+ setSearchQuery("");
+ setSearchMatchCount(0);
+ setActiveMatchIndex(0);
+ viewerRef.current?.search("", 0);
+ }}>
+ <X color="#0f172a" size={16} />
+ </DetailActionButton>
+ </View>
+ </View>
+ ) : null}
+ <View style={styles.detailDivider} />
+ </View>
+ {baseUrl ? (
+ <LocalTiptapEditor
+ key={memo.id}
+ baseUrl={baseUrl}
+ content={viewerContent}
+ dom={{
+ bounces: true,
+ contentInsetAdjustmentBehavior: "never",
+ overScrollMode: "never",
+ scrollEnabled: false,
+ style: [
+ detailLayoutStyles.viewer,
+ resolvedTheme === "dark" ? detailLayoutStyles.viewerDark : null,
+ ],
+ }}
+ locale={resolvedLocale}
+ mode="viewer"
+ onImagePreview={onImagePreview}
+ onLoadResource={loadViewerResource}
+ onReady={async () => {
+ setViewerReady(true);
+ }}
+ onResourcePress={onResourcePress}
+ onSearchResult={async (count, index) => {
+ setSearchMatchCount(count);
+ setActiveMatchIndex(count > 0 ? index : 0);
+ }}
+ ref={viewerRef}
+ theme={resolvedTheme}
+ />
) : (
- <MobileMermaidProvider theme={resolvedTheme}>
- <Markdown rules={detailMarkdownRules} style={themedDetailMarkdownStyles}>{detailText}</Markdown>
- </MobileMermaidProvider>
+ <View style={styles.centerState}>
+ <Text style={styles.errorText}>{resolvedLocale === "en-US" ? "Not signed in." : "未登录。"}</Text>
+ </View>
)}
- </ScrollView>
+ {!viewerReady ? (
+ <View pointerEvents="none" style={detailLayoutStyles.viewerLoading}>
+ <ActivityIndicator color="#0f172a" />
+ </View>
+ ) : null}
+ </View>
) : (
<View style={styles.centerState}>
<Text style={styles.errorText}>笔记加载失败</Text>
@@ -623,8 +651,10 @@ export const MemoDetailModal = ({
{imagePreview ? (
<AuthenticatedResourceImage
alt={imagePreview.alt}
+ href={imagePreview.source}
+ loadResourceBlob={client?.getResourceBlob}
resizeMode="contain"
- source={getAuthenticatedResourceSource(imagePreview.source, session)}
+ session={session}
style={resourceImageStyles.previewImage}
/>
) : null}
@@ -658,176 +688,34 @@ export const MemoDetailModal = ({
);
};
-const HighlightedDetailText = ({
- activeIndex,
- matches,
- text,
-}: {
- activeIndex: number;
- matches: Array<{ end: number; start: number }>;
- text: string;
-}) => {
- if (matches.length === 0) {
- return <Text selectable style={styles.detailMarkdown}>{text}</Text>;
- }
-
- const segments: ReactNode[] = [];
- let cursor = 0;
-
- matches.forEach((match, index) => {
- if (match.start > cursor) {
- segments.push(text.slice(cursor, match.start));
- }
-
- segments.push(
- <Text key={`${match.start}-${match.end}`} style={index === activeIndex ? styles.noteSearchHighlightActive : styles.noteSearchHighlight}>
- {text.slice(match.start, match.end)}
- </Text>
- );
- cursor = match.end;
- });
-
- if (cursor < text.length) {
- segments.push(text.slice(cursor));
- }
-
- return <Text selectable style={styles.detailMarkdown}>{segments}</Text>;
-};
-
-
-const detailMarkdownStyles = StyleSheet.create({
+const detailLayoutStyles = StyleSheet.create({
body: {
- color: "#0f172a",
- fontSize: MEMO_CONTENT_STYLE.body.fontSize,
- lineHeight: MEMO_CONTENT_STYLE.body.lineHeight,
- },
- blockquote: {
- backgroundColor: "#f8fafc",
- borderLeftColor: "#94a3b8",
- borderLeftWidth: 3,
- marginVertical: 10,
- paddingHorizontal: 14,
- paddingVertical: 8,
- },
- bullet_list: {
- marginVertical: 8,
- },
- code_inline: {
- backgroundColor: "#f1f5f9",
- borderRadius: 4,
- color: "#334155",
- fontSize: 15,
- },
- fence: {
- backgroundColor: "#0f172a",
- borderColor: "#0f172a",
- borderRadius: 8,
- color: "#e2e8f0",
- fontSize: 14,
- marginVertical: 10,
- padding: 12,
- },
- heading1: {
- color: "#0f172a",
- fontSize: 26,
- fontWeight: "800",
- lineHeight: 34,
- marginBottom: 10,
- marginTop: 14,
- },
- heading2: {
- color: "#0f172a",
- fontSize: 21,
- fontWeight: "800",
- lineHeight: 29,
- marginBottom: 8,
- marginTop: 18,
- },
- heading3: {
- color: "#0f172a",
- fontSize: 18,
- fontWeight: "800",
- lineHeight: 26,
- marginBottom: 6,
- marginTop: 14,
- },
- hr: {
- backgroundColor: MEMO_CONTENT_STYLE.divider.color.light,
- height: MEMO_CONTENT_STYLE.divider.thickness,
- marginVertical: MEMO_CONTENT_STYLE.divider.marginVertical,
- },
- link: {
- color: "#059669",
- },
- list_item: {
- marginVertical: 3,
- },
- ordered_list: {
- marginVertical: 8,
- },
- paragraph: {
- marginBottom: MEMO_CONTENT_STYLE.body.paragraphSpacing,
- marginTop: 0,
+ flex: 1,
+ minHeight: 0,
},
- strong: {
- fontWeight: "800",
+ meta: {
+ paddingBottom: 0,
+ paddingHorizontal: 16,
+ paddingTop: 16,
},
- table: {
+ viewer: {
backgroundColor: "#ffffff",
- borderColor: "#d8d8d8",
- borderRadius: 2,
- borderWidth: 1,
- overflow: "hidden",
- },
- tableCellDivider: {
- borderRightColor: "#dedede",
- borderRightWidth: 1,
- },
- tableScroll: {
- marginBottom: 10,
- marginTop: 10,
- maxWidth: "100%",
- },
- tableScrollContent: {
- flexGrow: 1,
- },
- td: {
flex: 1,
- minWidth: 0,
- paddingHorizontal: 10,
- paddingVertical: 7,
+ minHeight: 0,
},
- th: {
- backgroundColor: "#f2f2f2",
- flex: 1,
- minWidth: 0,
- paddingHorizontal: 10,
- paddingVertical: 7,
+ viewerDark: {
+ backgroundColor: "#0f172a",
},
- tr: {
- borderBottomColor: "#dedede",
- borderBottomWidth: 1,
- flexDirection: "row",
+ viewerLoading: {
+ ...StyleSheet.absoluteFill,
+ alignItems: "center",
+ backgroundColor: "rgba(248,250,252,0.72)",
+ justifyContent: "center",
+ top: 120,
},
});
const resourceImageStyles = StyleSheet.create({
- actions: {
- alignItems: "center",
- backgroundColor: "rgba(255,255,255,0.92)",
- borderColor: "#cbd5e1",
- borderRadius: 999,
- borderWidth: 1,
- height: 42,
- justifyContent: "center",
- position: "absolute",
- right: 8,
- top: 8,
- width: 42,
- },
- container: {
- position: "relative",
- },
previewBackdrop: {
alignItems: "center",
backgroundColor: "rgba(2,6,23,0.96)",
diff --git a/docs/mobile-native-parity.md b/docs/mobile-native-parity.md
index 36e558a2..f7dafd03 100644
--- a/docs/mobile-native-parity.md
+++ b/docs/mobile-native-parity.md
@@ -19,11 +19,12 @@ Build success is not a performance result. Before a Play production rollout, rec
## Architecture rules
-- Render startup, navigation, notebook selection, memo lists, search, settings, and the Markdown editor with native React Native views.
+- Render startup, navigation, notebook selection, memo lists, search, and settings with native React Native views.
- Reuse the shared API client and shared data types instead of duplicating backend contracts.
- Hydrate only the default notebook and memo-list queries at startup. Refresh stale data in the background.
- Clear persisted query data when the account changes, signs out, or becomes unauthorized.
-- Keep optional heavyweight features out of the startup path. A WebView may only be used for an explicitly selected compatibility editor, never as the App workspace.
+- Keep optional heavyweight features out of the startup path. Do not embed the PWA or a WebView as the App workspace shell (lists, navigation, settings).
+- Note body rendering may use a TipTap WebView runtime for both **read-only preview** and **edit**, so the same document schema, images, tables, and Mermaid path are shared. Native chrome owns headers, FABs, sheets, and system actions around that body.
- Use virtualized lists and stable item components for collections.
## Mobile product scope
@@ -37,6 +38,7 @@ The App follows the mobile PWA for high-frequency layouts and interactions, but
| Memo list, filters, sort, pin, and batch operations | Implemented |
| Local-cache search | Implemented |
| Local TipTap create/edit and autosave flow | Implemented |
+| Note detail body preview via read-only TipTap (same schema as edit) | Implemented |
| Attachments, image compression, and resource library | Implemented |
| Tag management | Implemented |
| Revision history and restore | Implemented |
diff --git a/tests/mobile-app-scope.test.ts b/tests/mobile-app-scope.test.ts
index c60038ec..119eeeac 100644
--- a/tests/mobile-app-scope.test.ts
+++ b/tests/mobile-app-scope.test.ts
@@ -46,4 +46,10 @@ describe("mobile app scope", () => {
expect(memoDetailSource).toContain('syncStatus === "conflict"');
expect(memoDetailSource).toContain("onResolveSyncConflict");
});
+
+ test("renders note detail body with the shared read-only TipTap viewer", () => {
+ expect(memoDetailSource).toContain('mode="viewer"');
+ expect(memoDetailSource).toContain("LocalTiptapEditor");
+ expect(memoDetailSource).not.toContain("react-native-markdown-display");
+ });
});