AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat: add mobile image resource actions
tianma-if8603258d4ce5
diff --git a/apps/mobile/src/components/LocalTiptapEditor.tsx b/apps/mobile/src/components/LocalTiptapEditor.tsxindex c0a8f88e..02ccf807 100644--- a/apps/mobile/src/components/LocalTiptapEditor.tsx+++ b/apps/mobile/src/components/LocalTiptapEditor.tsx@@ -44,8 +44,8 @@ export interface LocalTiptapEditorRef extends DOMImperativeFactory {cancelImageUpload: (uploadId: DOMValue) => void;completeImageUpload: (uploadId: DOMValue, imageUrl: DOMValue, alt: DOMValue) => void;appendAttachment: (attachmentUrl: DOMValue, filename: DOMValue) => void;- removeAttachment: (targetJson: DOMValue) => void;- renameAttachment: (targetJson: DOMValue, filename: DOMValue) => void;+ removeResource: (targetJson: DOMValue) => void;+ renameResource: (targetJson: DOMValue, filename: DOMValue) => void;flush: () => void;focusEnd: () => void;replaceAll: (query: DOMValue, replacement: DOMValue) => void;@@ -60,7 +60,7 @@ type LocalTiptapEditorProps = {dom?: DOMProps;onChange: (content: EditorDoc) => Promise<void>;onLoadResource: (source: string) => Promise<string | null>;- onAttachmentPress?: (targetJson: string) => Promise<void>;+ onResourcePress?: (targetJson: string) => Promise<void>;onPickImage: () => Promise<void>;onReady: (startupMs: number) => Promise<void>;onSearchResult?: (count: number, index: number) => Promise<void>;@@ -81,19 +81,21 @@ const CHANGE_IDLE_MS = 500;const TRANSIENT_IMAGE_UPLOAD_META = "edgeeverImageUploadPlaceholder";const ignoreSearchResult = async () => undefined;-type EditorAttachmentTarget = {+type EditorResourceTarget = {filename: string;href: string;+ kind: "attachment" | "image";resourceId: string;};-const parseMobileAttachmentTarget = (value: string): EditorAttachmentTarget | null => {+const parseMobileResourceTarget = (value: string): EditorResourceTarget | null => {try {- const parsed = JSON.parse(value) as Partial<EditorAttachmentTarget>;+ const parsed = JSON.parse(value) as Partial<EditorResourceTarget>;if (typeof parsed.href !== "string" || typeof parsed.filename !== "string") return null;+ if (parsed.kind !== "attachment" && parsed.kind !== "image") return null;const resourceId = getResourceIdFromUrl(parsed.href);if (!resourceId || (parsed.resourceId && parsed.resourceId !== resourceId)) return null;- return { filename: parsed.filename, href: parsed.href, resourceId };+ return { filename: parsed.filename, href: parsed.href, kind: parsed.kind, resourceId };} catch {return null;}@@ -102,23 +104,40 @@ const parseMobileAttachmentTarget = (value: string): EditorAttachmentTarget | nuconst normalizeEditorAttachmentFilename = (label: string, resourceId: string) =>label.replace(/^\s*(?:附件[::]|Attachment:)\s*/i, "").trim() || resourceId;-const handleMobileAttachmentEvent = (+const handleMobileResourceEvent = (event: Event,- onAttachmentPress?: (targetJson: string) => Promise<void>+ onResourcePress?: (targetJson: 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/"]');const href = link?.getAttribute("href") ?? "";const resourceId = getResourceIdFromUrl(href);- if (!link || !resourceId || !onAttachmentPress) return false;+ if (link && resourceId && onResourcePress) {+ event.preventDefault();+ event.stopPropagation();+ void onResourcePress(JSON.stringify({+ filename: normalizeEditorAttachmentFilename(link.textContent ?? "", resourceId),+ href,+ kind: "attachment",+ resourceId,+ } satisfies EditorResourceTarget));+ return true;+ }++ const imageFigure = element?.closest<HTMLElement>("figure.edgeever-image-node");+ const imageHref = imageFigure?.dataset.resourceHref ?? "";+ const imageResourceId = getResourceIdFromUrl(imageHref);+ const imageActionRequested = event.type === "contextmenu" || Boolean(element?.closest(".edgeever-image-actions"));+ if (!imageFigure || !imageResourceId || !imageActionRequested || !onResourcePress) return false;event.preventDefault();event.stopPropagation();- void onAttachmentPress(JSON.stringify({- filename: normalizeEditorAttachmentFilename(link.textContent ?? "", resourceId),- href,- resourceId,- } satisfies EditorAttachmentTarget));+ void onResourcePress(JSON.stringify({+ filename: imageFigure.dataset.resourceFilename || `image-${imageResourceId}`,+ href: imageHref,+ kind: "image",+ resourceId: imageResourceId,+ } satisfies EditorResourceTarget));return true;};@@ -279,14 +298,14 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {const pendingImageSelectionRef = useRef<{ from: number; to: number } | null>(null);const onChangeRef = useRef(props.onChange);const onLoadResourceRef = useRef(props.onLoadResource);- const onAttachmentPressRef = useRef(props.onAttachmentPress);+ const onResourcePressRef = useRef(props.onResourcePress);const onPickImageRef = useRef(props.onPickImage);const onReadyRef = useRef(props.onReady);const onSearchResultRef = useRef(props.onSearchResult ?? ignoreSearchResult);onChangeRef.current = props.onChange;onLoadResourceRef.current = props.onLoadResource;- onAttachmentPressRef.current = props.onAttachmentPress;+ onResourcePressRef.current = props.onResourcePress;onPickImageRef.current = props.onPickImage;onReadyRef.current = props.onReady;onSearchResultRef.current = props.onSearchResult ?? ignoreSearchResult;@@ -315,9 +334,9 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {content: resolveImageSources(props.content, props.baseUrl),editorProps: {attributes: getMobileEditorInputAttributes("edgeever-editor-content"),- handleClick: (_view, _pos, event) => handleMobileAttachmentEvent(event, onAttachmentPressRef.current),+ handleClick: (_view, _pos, event) => handleMobileResourceEvent(event, onResourcePressRef.current),handleDOMEvents: {- contextmenu: (_view, event) => handleMobileAttachmentEvent(event, onAttachmentPressRef.current),+ contextmenu: (_view, event) => handleMobileResourceEvent(event, onResourcePressRef.current),},},onUpdate: ({ editor: activeEditor, transaction }) => {@@ -434,10 +453,22 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {}).run();}, [editor, props.baseUrl, props.locale]);- const renameAttachment = useCallback((targetJsonValue: DOMValue, filenameValue: DOMValue) => {+ const renameResource = useCallback((targetJsonValue: DOMValue, filenameValue: DOMValue) => {if (!editor || typeof targetJsonValue !== "string" || typeof filenameValue !== "string") return;- const target = parseMobileAttachmentTarget(targetJsonValue);+ const target = parseMobileResourceTarget(targetJsonValue);if (!target) return;+ if (target.kind === "image") {+ const match = findMobileImageRange(editor, target.resourceId);+ if (!match) return;+ const imageNode = editor.state.doc.nodeAt(match.pos);+ if (!imageNode) return;+ editor.view.dispatch(editor.state.tr.setNodeMarkup(match.pos, imageNode.type, {+ ...imageNode.attrs,+ alt: filenameValue,+ title: filenameValue,+ }));+ return;+ }const range = findMobileAttachmentRange(editor, target.resourceId);if (!range) return;const linkMark = editor.schema.marks.link?.create(range.linkAttrs);@@ -449,10 +480,15 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {));}, [editor, props.locale]);- const removeAttachment = useCallback((targetJsonValue: DOMValue) => {+ const removeResource = useCallback((targetJsonValue: DOMValue) => {if (!editor || typeof targetJsonValue !== "string") return;- const target = parseMobileAttachmentTarget(targetJsonValue);+ const target = parseMobileResourceTarget(targetJsonValue);if (!target) return;+ if (target.kind === "image") {+ const match = findMobileImageRange(editor, target.resourceId);+ if (match) editor.view.dispatch(editor.state.tr.delete(match.pos, match.pos + match.nodeSize));+ return;+ }const range = findMobileAttachmentRange(editor, target.resourceId);if (!range) return;const resolved = editor.state.doc.resolve(range.from);@@ -480,12 +516,12 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {appendAttachment,flush,focusEnd: () => editor?.commands.focus("end"),- removeAttachment,- renameAttachment,+ removeResource,+ renameResource,replaceAll,search,}),- [appendAttachment, beginImageUpload, cancelImageUpload, completeImageUpload, editor, flush, removeAttachment, renameAttachment, replaceAll, search]+ [appendAttachment, beginImageUpload, cancelImageUpload, completeImageUpload, editor, flush, removeResource, renameResource, replaceAll, search]);useEffect(() => {@@ -1191,7 +1227,17 @@ const createProtectedImageExtension = (wrapper.className = "edgeever-image-node";wrapper.contentEditable = "false";const image = document.createElement("img");- wrapper.append(image, sizeControls.dom);+ const actionButton = document.createElement("button");+ actionButton.type = "button";+ actionButton.className = "edgeever-image-actions";+ actionButton.contentEditable = "false";+ actionButton.setAttribute("aria-label", locale === "en-US" ? "Image actions" : "图片操作");+ actionButton.textContent = "⋯";+ actionButton.addEventListener("pointerdown", (event) => {+ event.preventDefault();+ event.stopPropagation();+ });+ wrapper.append(image, actionButton, sizeControls.dom);const imageType = node.type;let requestId = 0;@@ -1205,6 +1251,8 @@ const createProtectedImageExtension = (const source = String(attributes.src ?? "");const alt = String(attributes.alt ?? "");const title = String(attributes.title ?? "");+ wrapper.dataset.resourceHref = source;+ wrapper.dataset.resourceFilename = alt || title;image.alt = alt;const referrerPolicy = getImageReferrerPolicy(source);if (referrerPolicy) {@@ -1287,6 +1335,17 @@ const findMobileAttachmentRange = (editor: TiptapEditor, resourceId: string): Atreturn match;};+const findMobileImageRange = (editor: TiptapEditor, resourceId: string): ImageUploadPlaceholderMatch | null => {+ let match: ImageUploadPlaceholderMatch | null = null;+ editor.state.doc.descendants((node, pos) => {+ if (node.type.name === "image" && typeof node.attrs.src === "string" && getResourceIdFromUrl(node.attrs.src) === resourceId) {+ match = { nodeSize: node.nodeSize, pos };+ return false;+ }+ });+ return match;+};+const findImageUploadPlaceholder = (editor: TiptapEditor,source: string@@ -1416,6 +1475,7 @@ const getEditorStyles = (theme: "light" | "dark") => `.edgeever-image-node, .edgeever-image-upload-result { position: relative; display: block; max-width: 100%; margin: 14px auto; line-height: 0; }.edgeever-image-node > img, .edgeever-image-upload-result > img { width: 100%; margin: 0; }.edgeever-image-node.is-selected > img, .edgeever-image-upload-result.is-selected > img { outline: 2px solid #0f766e; outline-offset: 3px; }+ .edgeever-image-actions { position: absolute; top: 8px; right: 8px; z-index: 3; display: inline-flex; width: 42px; height: 42px; appearance: none; align-items: center; justify-content: center; border: 1px solid ${theme === "dark" ? "#475569" : "#cbd5e1"}; border-radius: 999px; background: ${theme === "dark" ? "rgba(15, 23, 42, 0.9)" : "rgba(255, 255, 255, 0.92)"}; color: ${theme === "dark" ? "#e2e8f0" : "#334155"}; font-size: 24px; font-weight: 700; line-height: 1; box-shadow: 0 3px 12px rgba(15, 23, 42, 0.2); }.edgeever-image-size-controls { position: absolute; left: 50%; bottom: 8px; z-index: 2; display: flex; width: max-content; max-width: calc(100vw - 40px); align-items: center; gap: 3px; transform: translateX(-50%); border: 1px solid ${theme === "dark" ? "#475569" : "#bbf7d0"}; border-radius: 9px; padding: 4px; background: ${theme === "dark" ? "rgba(15, 23, 42, 0.96)" : "rgba(255, 255, 255, 0.96)"}; box-shadow: 0 8px 24px rgba(15, 23, 42, 0.2); line-height: 1.15; }.edgeever-image-size-controls[hidden] { display: none; }.edgeever-image-size-button { display: inline-flex; min-width: 52px; min-height: 44px; appearance: none; flex-direction: column; align-items: center; justify-content: center; gap: 2px; border: 0; border-radius: 7px; padding: 4px 7px; background: transparent; color: ${theme === "dark" ? "#cbd5e1" : "#475569"}; font: inherit; font-size: 12px; font-weight: 700; }diff --git a/apps/mobile/src/components/MobileAttachmentActions.tsx b/apps/mobile/src/components/MobileResourceActions.tsxsimilarity index 75%rename from apps/mobile/src/components/MobileAttachmentActions.tsxrename to apps/mobile/src/components/MobileResourceActions.tsxindex fc81746c..5d01347c 100644--- a/apps/mobile/src/components/MobileAttachmentActions.tsx+++ b/apps/mobile/src/components/MobileResourceActions.tsx@@ -1,48 +1,59 @@import { useEffect, useRef, useState, type ReactNode } from "react";import { ActivityIndicator, Alert, Modal, StyleSheet, View } from "react-native";-import { Download, FileText, MoreHorizontal, Pencil, Trash2, X } from "./icons";+import { Download, FileText, HardDrive, MoreHorizontal, Pencil, Trash2, X } from "./icons";import { Pressable, Text, TextInput } from "./LocalizedText";-import type { MobileAttachmentTarget } from "../lib/mobile-attachments";+import type { MobileAttachmentTarget, MobileResourceTarget } from "../lib/mobile-attachments";import { useMobileLocale } from "../lib/mobile-locale";import { useMobileTheme } from "../lib/mobile-theme";-type MobileAttachmentActionsProps = {+type MobileResourceActionsProps = {canMutate: boolean;onClose: () => void;- onDelete: (target: MobileAttachmentTarget) => Promise<void>;- onOpen: (target: MobileAttachmentTarget) => Promise<void>;- onRename: (target: MobileAttachmentTarget, filename: string) => Promise<void>;- target: MobileAttachmentTarget | null;+ onDelete: (target: MobileResourceTarget) => Promise<void>;+ onDownload: (target: MobileResourceTarget) => Promise<void>;+ onRename: (target: MobileResourceTarget, filename: string) => Promise<void>;+ onSaveAs: (target: MobileResourceTarget) => Promise<void>;+ target: MobileResourceTarget | null;};const copy = {"zh-CN": {- actions: "附件操作",+ attachmentActions: "附件操作",+ imageActions: "图片操作",cancel: "取消",delete: "删除",- deleteConfirm: "附件会从存储空间和当前笔记中永久删除,此操作无法撤销。",- deleteTitle: "删除附件",- download: "下载 / 打开",- failed: "附件操作失败,请重试。",+ attachmentDeleteConfirm: "附件会从存储空间和当前笔记中永久删除,此操作无法撤销。",+ attachmentDeleteTitle: "删除附件",+ download: "下载",+ failed: "资源操作失败,请重试。",filename: "文件名",rename: "重命名",- renameTitle: "重命名附件",+ attachmentRenameTitle: "重命名附件",+ imageDeleteConfirm: "图片会从存储空间和当前笔记中永久删除,此操作无法撤销。",+ imageDeleteTitle: "删除图片",+ imageRenameTitle: "重命名图片",+ saveAs: "导出",save: "保存",- syncedOnly: "附件同步完成后才能重命名或删除。",+ syncedOnly: "资源同步完成后才能重命名或删除。",},"en-US": {- actions: "Attachment actions",+ attachmentActions: "Attachment actions",+ imageActions: "Image actions",cancel: "Cancel",delete: "Delete",- deleteConfirm: "The attachment will be permanently removed from storage and this note. This cannot be undone.",- deleteTitle: "Delete attachment",- download: "Download / open",- failed: "The attachment action failed. Try again.",+ attachmentDeleteConfirm: "The attachment will be permanently removed from storage and this note. This cannot be undone.",+ attachmentDeleteTitle: "Delete attachment",+ download: "Download",+ failed: "The resource action failed. Try again.",filename: "Filename",rename: "Rename",- renameTitle: "Rename attachment",+ attachmentRenameTitle: "Rename attachment",+ imageDeleteConfirm: "The image will be permanently removed from storage and this note. This cannot be undone.",+ imageDeleteTitle: "Delete image",+ imageRenameTitle: "Rename image",+ saveAs: "Export",save: "Save",- syncedOnly: "Rename and delete are available after the attachment has synced.",+ syncedOnly: "Rename and delete are available after the resource has synced.",},} as const;@@ -101,14 +112,15 @@ export const MobileAttachmentCard = ({);};-export const MobileAttachmentActions = ({+export const MobileResourceActions = ({canMutate,onClose,onDelete,- onOpen,+ onDownload,onRename,+ onSaveAs,target,-}: MobileAttachmentActionsProps) => {+}: MobileResourceActionsProps) => {const { resolvedLocale } = useMobileLocale();const labels = copy[resolvedLocale];const [mode, setMode] = useState<"actions" | "rename">("actions");@@ -125,6 +137,12 @@ export const MobileAttachmentActions = ({if (!target) return null;+ const isImage = target.kind === "image";+ const actionsTitle = isImage ? labels.imageActions : labels.attachmentActions;+ const deleteTitle = isImage ? labels.imageDeleteTitle : labels.attachmentDeleteTitle;+ const deleteConfirm = isImage ? labels.imageDeleteConfirm : labels.attachmentDeleteConfirm;+ const renameTitle = isImage ? labels.imageRenameTitle : labels.attachmentRenameTitle;+const run = async (action: () => Promise<void>, closeAfter = true) => {setPending(true);setError(null);@@ -139,7 +157,7 @@ export const MobileAttachmentActions = ({};const confirmDelete = () => {- Alert.alert(labels.deleteTitle, labels.deleteConfirm, [+ Alert.alert(deleteTitle, deleteConfirm, [{ text: labels.cancel, style: "cancel" },{ text: labels.delete, style: "destructive", onPress: () => void run(() => onDelete(target)) },]);@@ -152,7 +170,7 @@ export const MobileAttachmentActions = ({<View style={styles.handle} /><View style={styles.sheetHeader}><View style={styles.sheetHeaderText}>- <Text style={styles.sheetTitle}>{mode === "rename" ? labels.renameTitle : labels.actions}</Text>+ <Text style={styles.sheetTitle}>{mode === "rename" ? renameTitle : actionsTitle}</Text><Text numberOfLines={1} style={styles.sheetSubtitle}>{target.filename}</Text></View><Pressable accessibilityLabel={labels.cancel} accessibilityRole="button" disabled={pending} onPress={onClose} style={styles.closeButton}>@@ -162,10 +180,11 @@ export const MobileAttachmentActions = ({{mode === "actions" ? (<View style={styles.actions}>- <AttachmentActionRow icon={<Download color="#0f172a" size={19} />} label={labels.download} onPress={() => void run(() => onOpen(target))} pending={pending} />- <AttachmentActionRow disabled={!canMutate} icon={<Pencil color={canMutate ? "#0f172a" : "#94a3b8"} size={19} />} label={labels.rename} onPress={() => setMode("rename")} pending={pending} />+ <ResourceActionRow icon={<Download color="#0f172a" size={19} />} label={labels.download} onPress={() => void run(() => onDownload(target))} pending={pending} />+ <ResourceActionRow icon={<HardDrive color="#0f172a" size={19} />} label={labels.saveAs} onPress={() => void run(() => onSaveAs(target))} pending={pending} />+ <ResourceActionRow disabled={!canMutate} icon={<Pencil color={canMutate ? "#0f172a" : "#94a3b8"} size={19} />} label={labels.rename} onPress={() => setMode("rename")} pending={pending} /><View style={styles.divider} />- <AttachmentActionRow danger disabled={!canMutate} icon={<Trash2 color={canMutate ? "#be123c" : "#94a3b8"} size={19} />} label={labels.delete} onPress={confirmDelete} pending={pending} />+ <ResourceActionRow danger disabled={!canMutate} icon={<Trash2 color={canMutate ? "#be123c" : "#94a3b8"} size={19} />} label={labels.delete} onPress={confirmDelete} pending={pending} />{!canMutate ? <Text style={styles.hint}>{labels.syncedOnly}</Text> : null}</View>) : (@@ -201,7 +220,7 @@ export const MobileAttachmentActions = ({);};-const AttachmentActionRow = ({+const ResourceActionRow = ({danger = false,disabled = false,icon,diff --git a/apps/mobile/src/lib/mobile-attachments.test.mjs b/apps/mobile/src/lib/mobile-attachments.test.mjsindex 450d8855..aadc2297 100644--- a/apps/mobile/src/lib/mobile-attachments.test.mjs+++ b/apps/mobile/src/lib/mobile-attachments.test.mjs@@ -1,13 +1,18 @@import { describe, expect, test } from "bun:test";import {deleteMobileAttachmentFromDoc,+ deleteMobileResourceFromDoc,getMobileAttachmentTarget,+ getMobileImageTarget,getParagraphAttachmentTarget,parseMobileAttachmentTargetJson,+ parseMobileResourceTargetJson,renameMobileAttachmentInDoc,+ renameMobileResourceInDoc,} from "./mobile-attachments.ts";const href = "/api/v1/resources/res_123/blob";+const attachmentTarget = { filename: "report.pdf", href, kind: "attachment", resourceId: "res_123" };const doc = {type: "doc",content: [{@@ -22,26 +27,49 @@ const doc = {describe("mobile attachments", () => {test("recognizes resource links and attachment paragraphs", () => {- expect(getMobileAttachmentTarget(href, "📄 报告:report.pdf")).toEqual({ filename: "report.pdf", href, resourceId: "res_123" });+ expect(getMobileAttachmentTarget(href, "📄 报告:report.pdf")).toEqual(attachmentTarget);expect(getParagraphAttachmentTarget({type: "paragraph",children: [{ type: "text", content: "附件:" }, { type: "link", attributes: { href }, children: [{ type: "text", content: "report.pdf" }] }],- })).toEqual({ filename: "report.pdf", href, resourceId: "res_123" });+ })).toEqual(attachmentTarget);});test("validates attachment targets received from the DOM editor", () => {- expect(parseMobileAttachmentTargetJson(JSON.stringify({ filename: "report.pdf", href, resourceId: "res_123" })))- .toEqual({ filename: "report.pdf", href, resourceId: "res_123" });- expect(parseMobileAttachmentTargetJson(JSON.stringify({ filename: "report.pdf", href, resourceId: "different" }))).toBeNull();+ expect(parseMobileAttachmentTargetJson(JSON.stringify(attachmentTarget))).toEqual(attachmentTarget);+ expect(parseMobileAttachmentTargetJson(JSON.stringify({ ...attachmentTarget, resourceId: "different" }))).toBeNull();+ expect(parseMobileAttachmentTargetJson(JSON.stringify({ ...attachmentTarget, kind: "image" }))).toBeNull();});test("renames the linked label", () => {- const updated = renameMobileAttachmentInDoc(doc, { filename: "report.pdf", href, resourceId: "res_123" }, "final.pdf", "附件:");+ const updated = renameMobileAttachmentInDoc(doc, attachmentTarget, "final.pdf", "附件:");expect(updated.content[0].content[0].text).toBe("附件:final.pdf");});test("removes a standalone attachment paragraph", () => {- expect(deleteMobileAttachmentFromDoc(doc, { filename: "report.pdf", href, resourceId: "res_123" })).toEqual({+ expect(deleteMobileAttachmentFromDoc(doc, attachmentTarget)).toEqual({+ type: "doc",+ content: [{ type: "paragraph" }],+ });+ });++ test("recognizes and validates image resources", () => {+ const target = { filename: "photo.jpg", href, kind: "image", resourceId: "res_123" };+ expect(getMobileImageTarget(href, "photo.jpg")).toEqual(target);+ expect(parseMobileResourceTargetJson(JSON.stringify(target))).toEqual(target);+ expect(getMobileImageTarget("https://example.com/photo.jpg", "photo.jpg")).toBeNull();+ });++ test("renames and removes image nodes", () => {+ const target = { filename: "photo.jpg", href, kind: "image", resourceId: "res_123" };+ const imageDoc = {+ type: "doc",+ content: [{ type: "image", attrs: { alt: "photo.jpg", src: href, title: null } }],+ };+ expect(renameMobileResourceInDoc(imageDoc, target, "passport.jpg", "附件:")).toEqual({+ type: "doc",+ content: [{ type: "image", attrs: { alt: "passport.jpg", src: href, title: "passport.jpg" } }],+ });+ expect(deleteMobileResourceFromDoc(imageDoc, target)).toEqual({type: "doc",content: [{ type: "paragraph" }],});diff --git a/apps/mobile/src/lib/mobile-attachments.ts b/apps/mobile/src/lib/mobile-attachments.tsindex 0360e659..e2383715 100644--- a/apps/mobile/src/lib/mobile-attachments.ts+++ b/apps/mobile/src/lib/mobile-attachments.ts@@ -1,12 +1,16 @@import type { createEdgeEverClient } from "@edgeever/client";import { docToMarkdown, getResourceIdFromUrl, type TiptapDoc } from "@edgeever/shared";-export type MobileAttachmentTarget = {+export type MobileResourceTarget = {filename: string;href: string;+ kind: "attachment" | "image";resourceId: string;};+export type MobileAttachmentTarget = MobileResourceTarget & { kind: "attachment" };+export type MobileImageTarget = MobileResourceTarget & { kind: "image" };+type AttachmentClient = Pick<ReturnType<typeof createEdgeEverClient>, "getResourceBlob">;type MarkdownNodeLike = {@@ -31,22 +35,40 @@ export const getMobileAttachmentTarget = (href: string, label: string): MobileAtreturn {filename: normalizeAttachmentFilename(label, resourceId),href,+ kind: "attachment",resourceId,};};-export const parseMobileAttachmentTargetJson = (value: string): MobileAttachmentTarget | null => {+export const getMobileImageTarget = (href: string, label: string): MobileImageTarget | null => {+ const resourceId = getResourceIdFromUrl(href);+ if (!resourceId) return null;+ return {+ filename: label.trim() || `image-${resourceId}`,+ href,+ kind: "image",+ resourceId,+ };+};++export const parseMobileResourceTargetJson = (value: string): MobileResourceTarget | null => {try {- const parsed = JSON.parse(value) as Partial<MobileAttachmentTarget>;+ const parsed = JSON.parse(value) as Partial<MobileResourceTarget>;if (typeof parsed.href !== "string" || typeof parsed.filename !== "string") return null;+ if (parsed.kind !== "attachment" && parsed.kind !== "image") return null;const resourceId = getResourceIdFromUrl(parsed.href);if (!resourceId || (parsed.resourceId && parsed.resourceId !== resourceId)) return null;- return { filename: parsed.filename, href: parsed.href, resourceId };+ return { filename: parsed.filename, href: parsed.href, kind: parsed.kind, resourceId };} catch {return null;}};+export const parseMobileAttachmentTargetJson = (value: string): MobileAttachmentTarget | null => {+ const target = parseMobileResourceTargetJson(value);+ return target?.kind === "attachment" ? { ...target, kind: "attachment" } : null;+};+const getMarkdownNodeText = (node: MarkdownNodeLike): string =>typeof node.content === "string"? node.content@@ -79,9 +101,9 @@ const hasResourceLinkMark = (value: unknown, resourceId: string) =>getResourceIdFromUrl(candidate.attrs.href) === resourceId;});-const updateAttachmentDoc = (+const updateResourceDoc = (doc: TiptapDoc,- target: MobileAttachmentTarget,+ target: MobileResourceTarget,action: { type: "delete" } | { type: "rename"; filename: string; labelPrefix: string }): TiptapDoc => {const visit = (value: unknown): unknown => {@@ -91,13 +113,21 @@ const updateAttachmentDoc = (if (!value || typeof value !== "object") return value;const node = value as Record<string, unknown>;- if (node.type === "text" && hasResourceLinkMark(node.marks, target.resourceId)) {+ if (target.kind === "image" && node.type === "image") {+ const attrs = node.attrs && typeof node.attrs === "object" ? node.attrs as Record<string, unknown> : {};+ const source = typeof attrs.src === "string" ? attrs.src : "";+ if (getResourceIdFromUrl(source) === target.resourceId) {+ if (action.type === "delete") return null;+ return { ...node, attrs: { ...attrs, alt: action.filename, title: action.filename } };+ }+ }+ if (target.kind === "attachment" && node.type === "text" && hasResourceLinkMark(node.marks, target.resourceId)) {if (action.type === "delete") return null;return { ...node, text: `${action.labelPrefix}${action.filename}` };}const next = Object.fromEntries(Object.entries(node).map(([key, child]) => [key, key === "content" ? visit(child) : child]));- if (action.type === "delete" && next.type === "paragraph" && Array.isArray(next.content)) {+ if (target.kind === "attachment" && action.type === "delete" && next.type === "paragraph" && Array.isArray(next.content)) {const remainingText = next.content.map((child) => child && typeof child === "object" && "text" in child ? String(child.text ?? "") : "").join("")@@ -118,20 +148,32 @@ export const renameMobileAttachmentInDoc = (target: MobileAttachmentTarget,filename: string,labelPrefix: string-) => updateAttachmentDoc(doc, target, { type: "rename", filename, labelPrefix });+) => updateResourceDoc(doc, target, { type: "rename", filename, labelPrefix });export const deleteMobileAttachmentFromDoc = (doc: TiptapDoc, target: MobileAttachmentTarget) =>- updateAttachmentDoc(doc, target, { type: "delete" });+ updateResourceDoc(doc, target, { type: "delete" });++export const renameMobileResourceInDoc = (+ doc: TiptapDoc,+ target: MobileResourceTarget,+ filename: string,+ labelPrefix: string+) => updateResourceDoc(doc, target, { type: "rename", filename, labelPrefix });++export const deleteMobileResourceFromDoc = (doc: TiptapDoc, target: MobileResourceTarget) =>+ updateResourceDoc(doc, target, { type: "delete" });export const getMobileAttachmentUpdatePayload = (contentJson: TiptapDoc) => ({contentJson,contentMarkdown: docToMarkdown(contentJson),});+export const getMobileResourceUpdatePayload = getMobileAttachmentUpdatePayload;+const safeCacheFilename = (filename: string) =>filename.trim().replace(/[\\/]/g, "-").replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 160) || "attachment";-export const openMobileAttachment = async (client: AttachmentClient, target: MobileAttachmentTarget) => {+const cacheMobileResource = async (client: AttachmentClient, target: MobileResourceTarget) => {const [{ Directory, File, Paths }, Sharing] = await Promise.all([import("expo-file-system"),import("expo-sharing"),@@ -147,6 +189,12 @@ export const openMobileAttachment = async (client: AttachmentClient, target: Mobfile.create({ overwrite: true, intermediates: true });file.write(new Uint8Array(await blob.arrayBuffer()));+ return { blob, file, Sharing };+};++export const openMobileResource = async (client: AttachmentClient, target: MobileResourceTarget) => {+ const { blob, file, Sharing } = await cacheMobileResource(client, target);+if (!(await Sharing.isAvailableAsync())) {throw new Error("当前设备无法打开系统文件面板");}@@ -156,3 +204,32 @@ export const openMobileAttachment = async (client: AttachmentClient, target: Mob});return file.uri;};++export const saveMobileResourceAs = async (client: AttachmentClient, target: MobileResourceTarget) => {+ const { blob, file, Sharing } = await cacheMobileResource(client, target);+ const { Platform } = await import("react-native");+ if (Platform.OS === "android") {+ const FileSystem = await import("expo-file-system/legacy");+ const permission = await FileSystem.StorageAccessFramework.requestDirectoryPermissionsAsync();+ if (!permission.granted) return null;+ const destination = await FileSystem.StorageAccessFramework.createFileAsync(+ permission.directoryUri,+ target.filename,+ blob.type || "application/octet-stream"+ );+ await FileSystem.StorageAccessFramework.writeAsStringAsync(destination, await file.base64(), {+ encoding: FileSystem.EncodingType.Base64,+ });+ return destination;+ }+ if (!(await Sharing.isAvailableAsync())) {+ throw new Error("当前设备无法打开系统导出面板");+ }+ await Sharing.shareAsync(file.uri, {+ dialogTitle: `导出 ${target.filename}`,+ mimeType: blob.type || "application/octet-stream",+ });+ return file.uri;+};++export const openMobileAttachment = openMobileResource;diff --git a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx b/apps/mobile/src/screens/WorkspaceMemoDetail.tsxindex 6fab2168..4cd7aad2 100644--- a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx+++ b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx@@ -8,11 +8,14 @@ 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 { MobileAttachmentActions, MobileAttachmentCard } from "../components/MobileAttachmentActions";+import { MobileAttachmentCard, MobileResourceActions } from "../components/MobileResourceActions";import {+ getMobileImageTarget,getParagraphAttachmentTarget,- openMobileAttachment,+ openMobileResource,+ saveMobileResourceAs,type MobileAttachmentTarget,+ type MobileResourceTarget,} from "../lib/mobile-attachments";import { getMobileMarkdownFenceLanguage, trimMobileMarkdownFenceContent } from "../lib/mobile-mermaid";import { useMobileLocale } from "../lib/mobile-locale";@@ -205,10 +208,10 @@ export const MemoDetailModal = ({notebookName,onClose,onDelete,- onDeleteAttachment,+ onDeleteResource,onRichEdit,onOpenRevisions,- onRenameAttachment,+ onRenameResource,onResolveSyncConflict,onRestore,onShare,@@ -224,10 +227,10 @@ export const MemoDetailModal = ({notebookName: string;onClose: () => void;onDelete: (memo: MemoDetail) => void;- onDeleteAttachment: (memo: MemoDetail, target: MobileAttachmentTarget) => Promise<void>;+ onDeleteResource: (memo: MemoDetail, target: MobileResourceTarget) => Promise<void>;onRichEdit: (memo: MemoDetail) => void;onOpenRevisions: (memo: MemoDetail) => void;- onRenameAttachment: (memo: MemoDetail, target: MobileAttachmentTarget, filename: string) => Promise<void>;+ onRenameResource: (memo: MemoDetail, target: MobileResourceTarget, filename: string) => Promise<void>;onResolveSyncConflict: (memo: MemoDetail) => void;onRestore: (memo: MemoDetail) => void;onShare: (memo: MemoDetail) => void;@@ -243,26 +246,32 @@ export const MemoDetailModal = ({const [searchOpen, setSearchOpen] = useState(false);const [searchQuery, setSearchQuery] = useState("");const [activeMatchIndex, setActiveMatchIndex] = useState(0);- const [attachmentTarget, setAttachmentTarget] = useState<MobileAttachmentTarget | null>(null);+ 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 openAttachment = useCallback(async (target: MobileAttachmentTarget) => {- if (!client) throw new Error(resolvedLocale === "en-US" ? "The attachment client is unavailable." : "当前无法读取附件。");+ const downloadResource = useCallback(async (target: MobileResourceTarget) => {+ if (!client) throw new Error(resolvedLocale === "en-US" ? "The resource client is unavailable." : "当前无法读取资源。");setDownloadingAttachmentId(target.resourceId);try {- await openMobileAttachment(client, target);+ await openMobileResource(client, target);} finally {setDownloadingAttachmentId(null);}}, [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 openAttachment(target).catch((error) => {+ 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." : "请稍后重试。"));});- }, [openAttachment, resolvedLocale]);+ }, [downloadResource, resolvedLocale]);const themedDetailMarkdownStyles = useMemo(() => ({...resolveMobileThemeStyles(detailMarkdownStyles, resolvedTheme),@@ -338,16 +347,47 @@ export const MemoDetailModal = ({}return <RNText key={node.key} selectable style={[inheritedStyles, markdownStyles.fence]}>{content}</RNText>;},- image: (node, _children, _parents, markdownStyles) => (- <AuthenticatedResourceImage- alt={String(node.attributes.alt ?? "")}- fitAspect- key={node.key}- resizeMode="contain"- source={getAuthenticatedResourceSource(String(node.attributes.src ?? ""), session)}- style={markdownStyles._VIEW_SAFE_image}- />- ),+ 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),@@ -361,7 +401,7 @@ export const MemoDetailModal = ({<MobileAttachmentCardbusy={downloadingAttachmentId === target.resourceId}key={node.key}- onActions={() => setAttachmentTarget(target)}+ onActions={() => setResourceTarget(target)}onOpen={() => openAttachmentFromCard(target)}target={target}/>@@ -578,19 +618,40 @@ export const MemoDetailModal = ({</Pressable></Modal>) : null}- <MobileAttachmentActions+ <Modal animationType="fade" onRequestClose={() => setImagePreview(null)} transparent visible={Boolean(imagePreview)}>+ <View style={resourceImageStyles.previewBackdrop}>+ {imagePreview ? (+ <AuthenticatedResourceImage+ alt={imagePreview.alt}+ resizeMode="contain"+ source={getAuthenticatedResourceSource(imagePreview.source, session)}+ style={resourceImageStyles.previewImage}+ />+ ) : null}+ <Pressable+ accessibilityLabel={resolvedLocale === "en-US" ? "Close image preview" : "关闭图片预览"}+ accessibilityRole="button"+ onPress={() => setImagePreview(null)}+ style={resourceImageStyles.previewClose}+ >+ <X color="#ffffff" size={24} />+ </Pressable>+ </View>+ </Modal>+ <MobileResourceActionscanMutate={Boolean(memo && !memo.isDeleted && !memo.id.startsWith("local:"))}- onClose={() => setAttachmentTarget(null)}+ onClose={() => setResourceTarget(null)}onDelete={async (target) => {if (!memo) return;- await onDeleteAttachment(memo, target);+ await onDeleteResource(memo, target);}}- onOpen={openAttachment}+ onDownload={downloadResource}onRename={async (target, filename) => {if (!memo) return;- await onRenameAttachment(memo, target, filename);+ await onRenameResource(memo, target, filename);}}- target={attachmentTarget}+ onSaveAs={saveResourceAs}+ target={resourceTarget}/></SafeAreaView></Modal>@@ -749,3 +810,44 @@ const detailMarkdownStyles = StyleSheet.create({flexDirection: "row",},});++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)",+ flex: 1,+ justifyContent: "center",+ padding: 16,+ },+ previewClose: {+ alignItems: "center",+ backgroundColor: "rgba(15,23,42,0.78)",+ borderRadius: 999,+ height: 46,+ justifyContent: "center",+ position: "absolute",+ right: 18,+ top: 54,+ width: 46,+ },+ previewImage: {+ height: "100%",+ width: "100%",+ },+});diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsxindex 9a4605d9..9ed3c195 100644--- a/apps/mobile/src/screens/WorkspaceScreen.tsx+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx@@ -104,7 +104,7 @@ import { prepareUploadAsset } from "../lib/mobile-image-upload";import MobileWebClipCapture from "../components/MobileWebClipCapture";import { showEdgeEverKeyboard } from "../../modules/edgeever-keyboard";import LocalTiptapEditor, { type LocalTiptapEditorRef } from "../components/LocalTiptapEditor";-import { MobileAttachmentActions } from "../components/MobileAttachmentActions";+import { MobileResourceActions } from "../components/MobileResourceActions";import { resolveMobileThemeStyles, useMobileTheme } from "../lib/mobile-theme";import { useMobileUpdate } from "../lib/mobile-update";import { MobileMermaidDiagram, MobileMermaidProvider } from "../components/MobileMermaid";@@ -148,12 +148,13 @@ import { NotesView } from "./WorkspaceNotesView";import { SettingsView, type MobileLocaleMode } from "./WorkspaceSettingsView";import { MemoDetailModal } from "./WorkspaceMemoDetail";import {- deleteMobileAttachmentFromDoc,- getMobileAttachmentUpdatePayload,- openMobileAttachment,- parseMobileAttachmentTargetJson,- renameMobileAttachmentInDoc,- type MobileAttachmentTarget,+ deleteMobileResourceFromDoc,+ getMobileResourceUpdatePayload,+ openMobileResource,+ parseMobileResourceTargetJson,+ renameMobileResourceInDoc,+ saveMobileResourceAs,+ type MobileResourceTarget,} from "../lib/mobile-attachments";const ALL_NOTES_ID = "all";@@ -902,10 +903,10 @@ export const WorkspaceScreen = ({]);};- const handleRenameAttachment = async (memo: MemoDetail, target: MobileAttachmentTarget, filename: string) => {+ const handleRenameResource = async (memo: MemoDetail, target: MobileResourceTarget, filename: string) => {if (!client) throw new Error("当前无法连接实例,请稍后重试");const { resource } = await client.renameResource(target.resourceId, filename);- const contentJson = renameMobileAttachmentInDoc(+ const contentJson = renameMobileResourceInDoc(memo.contentJson,target,resource.filename || filename,@@ -913,17 +914,17 @@ export const WorkspaceScreen = ({);await localUpdateMemoMutation.mutateAsync({memo,- payload: getMobileAttachmentUpdatePayload(contentJson),+ payload: getMobileResourceUpdatePayload(contentJson),});};- const handleDeleteAttachment = async (memo: MemoDetail, target: MobileAttachmentTarget) => {+ const handleDeleteResource = async (memo: MemoDetail, target: MobileResourceTarget) => {if (!client) throw new Error("当前无法连接实例,请稍后重试");await client.deleteResource(target.resourceId);- const contentJson = deleteMobileAttachmentFromDoc(memo.contentJson, target);+ const contentJson = deleteMobileResourceFromDoc(memo.contentJson, target);await localUpdateMemoMutation.mutateAsync({memo,- payload: getMobileAttachmentUpdatePayload(contentJson),+ payload: getMobileResourceUpdatePayload(contentJson),});};@@ -1073,10 +1074,10 @@ export const WorkspaceScreen = ({notebookName={notebooks.find((notebook) => notebook.id === selectedMemo?.notebookId)?.name ?? "未分类"}onClose={closeDetail}onDelete={handleDeleteMemo}- onDeleteAttachment={handleDeleteAttachment}+ onDeleteResource={handleDeleteResource}onRichEdit={(memo) => void openRichEditor(memo)}onOpenRevisions={setRevisionMemo}- onRenameAttachment={handleRenameAttachment}+ onRenameResource={handleRenameResource}onResolveSyncConflict={handleMemoSyncConflict}onRestore={(memo) => restoreMemoMutation.mutate(memo)}onShare={(memo) => shareMemoMutation.mutate(memo)}@@ -1587,7 +1588,7 @@ const CreateMemoModal = ({const [dirty, setDirty] = useState(false);const [editorReady, setEditorReady] = useState(false);const [imageOperation, setImageOperation] = useState<"idle" | "creating" | "uploading">("idle");- const [attachmentTarget, setAttachmentTarget] = useState<MobileAttachmentTarget | null>(null);+ const [resourceTarget, setResourceTarget] = useState<MobileResourceTarget | null>(null);const targetNotebookId = notebookId || fallbackNotebookId;const selectedNotebookName = notebooks.find((notebook) => notebook.id === targetNotebookId)?.name ?? "选择笔记本";const titleRef = useRef(title);@@ -1880,26 +1881,31 @@ const CreateMemoModal = ({return pending;}, [client]);- const openAttachment = useCallback(async (target: MobileAttachmentTarget) => {+ const downloadResource = useCallback(async (target: MobileResourceTarget) => {if (!client) throw new Error(resolvedLocale === "en-US" ? "The attachment client is unavailable." : "当前无法读取附件。");- await openMobileAttachment(client, target);+ await openMobileResource(client, target);}, [client, resolvedLocale]);- const renameAttachment = useCallback(async (target: MobileAttachmentTarget, filename: string) => {+ 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 renameResource = useCallback(async (target: MobileResourceTarget, filename: string) => {if (!client || !materializedMemoRef.current) throw new Error(resolvedLocale === "en-US" ? "Wait for this note to sync first." : "请等待笔记同步完成。");const { resource } = await client.renameResource(target.resourceId, filename);- editorRef.current?.renameAttachment(JSON.stringify(target), resource.filename || filename);+ editorRef.current?.renameResource(JSON.stringify(target), resource.filename || filename);}, [client, resolvedLocale]);- const deleteAttachment = useCallback(async (target: MobileAttachmentTarget) => {+ const deleteResource = useCallback(async (target: MobileResourceTarget) => {if (!client || !materializedMemoRef.current) throw new Error(resolvedLocale === "en-US" ? "Wait for this note to sync first." : "请等待笔记同步完成。");await client.deleteResource(target.resourceId);- editorRef.current?.removeAttachment(JSON.stringify(target));+ editorRef.current?.removeResource(JSON.stringify(target));}, [client, resolvedLocale]);- const selectAttachment = useCallback(async (targetJson: string) => {- const target = parseMobileAttachmentTargetJson(targetJson);- if (target) setAttachmentTarget(target);+ const selectResource = useCallback(async (targetJson: string) => {+ const target = parseMobileResourceTargetJson(targetJson);+ if (target) setResourceTarget(target);}, []);const editorElement = useMemo(() => draftLoaded && baseUrl ? (@@ -1923,7 +1929,7 @@ const CreateMemoModal = ({flushResolverRef.current?.();flushResolverRef.current = null;}}- onAttachmentPress={selectAttachment}+ onResourcePress={selectResource}onLoadResource={loadEditorResource}onPickImage={pickAndUploadImage}onReady={async (elapsedMs) => {@@ -1937,7 +1943,7 @@ const CreateMemoModal = ({locale={resolvedLocale}theme={resolvedTheme}/>- ) : null, [baseUrl, draftLoaded, loadEditorResource, resolvedLocale, resolvedTheme, selectAttachment]);+ ) : null, [baseUrl, draftLoaded, loadEditorResource, resolvedLocale, resolvedTheme, selectResource]);return (<Modal animationType="slide" onRequestClose={() => void requestClose()} presentationStyle="fullScreen" visible={visible}>@@ -2019,13 +2025,14 @@ const CreateMemoModal = ({}}visible={notebookPickerOpen}/>- <MobileAttachmentActions+ <MobileResourceActionscanMutate={Boolean(materializedMemoRef.current)}- onClose={() => setAttachmentTarget(null)}- onDelete={deleteAttachment}- onOpen={openAttachment}- onRename={renameAttachment}- target={attachmentTarget}+ onClose={() => setResourceTarget(null)}+ onDelete={deleteResource}+ onDownload={downloadResource}+ onRename={renameResource}+ onSaveAs={saveResourceAs}+ target={resourceTarget}/></SafeAreaView></Modal>@@ -2231,7 +2238,7 @@ const RichEditorModal = ({const [uploading, setUploading] = useState(false);const [error, setError] = useState<string | null>(null);const [startupMs, setStartupMs] = useState<number | null>(null);- const [attachmentTarget, setAttachmentTarget] = useState<MobileAttachmentTarget | null>(null);+ const [resourceTarget, setResourceTarget] = useState<MobileResourceTarget | null>(null);const notebookLabel = notebooks.find((notebook) => notebook.id === notebookId)?.name ?? "未分类";const saveLabel = error ? "保存失败" : saving ? "保存中" : uploading ? "上传中" : dirty ? (draftRestored ? "本地草稿" : "未保存") : ready ? "已保存" : "加载中";const titleRef = useRef(title);@@ -2420,26 +2427,31 @@ const RichEditorModal = ({return pending;}, [client]);- const openAttachment = useCallback(async (target: MobileAttachmentTarget) => {+ const downloadResource = useCallback(async (target: MobileResourceTarget) => {if (!client) throw new Error(resolvedLocale === "en-US" ? "The attachment client is unavailable." : "当前无法读取附件。");- await openMobileAttachment(client, target);+ await openMobileResource(client, target);+ }, [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 renameAttachment = useCallback(async (target: MobileAttachmentTarget, filename: string) => {+ const renameResource = useCallback(async (target: MobileResourceTarget, filename: string) => {if (!client || !memo || memo.id.startsWith("local:")) throw new Error(resolvedLocale === "en-US" ? "Wait for this note to sync first." : "请等待笔记同步完成。");const { resource } = await client.renameResource(target.resourceId, filename);- editorRef.current?.renameAttachment(JSON.stringify(target), resource.filename || filename);+ editorRef.current?.renameResource(JSON.stringify(target), resource.filename || filename);}, [client, memo, resolvedLocale]);- const deleteAttachment = useCallback(async (target: MobileAttachmentTarget) => {+ const deleteResource = useCallback(async (target: MobileResourceTarget) => {if (!client || !memo || memo.id.startsWith("local:")) throw new Error(resolvedLocale === "en-US" ? "Wait for this note to sync first." : "请等待笔记同步完成。");await client.deleteResource(target.resourceId);- editorRef.current?.removeAttachment(JSON.stringify(target));+ editorRef.current?.removeResource(JSON.stringify(target));}, [client, memo, resolvedLocale]);- const selectAttachment = useCallback(async (targetJson: string) => {- const target = parseMobileAttachmentTargetJson(targetJson);- if (target) setAttachmentTarget(target);+ const selectResource = useCallback(async (targetJson: string) => {+ const target = parseMobileResourceTargetJson(targetJson);+ if (target) setResourceTarget(target);}, []);const editorElement = useMemo(@@ -2456,7 +2468,7 @@ const RichEditorModal = ({style: styles.richEditorWebView,}}onChange={persistDraft}- onAttachmentPress={selectAttachment}+ onResourcePress={selectResource}onLoadResource={loadEditorResource}onPickImage={pickAndUploadImage}onReady={async (elapsedMs) => {@@ -2479,7 +2491,7 @@ const RichEditorModal = ({theme={resolvedTheme}/>) : null,- [baseUrl, loadEditorResource, memo?.id, resolvedLocale, resolvedTheme, selectAttachment]+ [baseUrl, loadEditorResource, memo?.id, resolvedLocale, resolvedTheme, selectResource]);useEffect(() => {@@ -2591,13 +2603,14 @@ const RichEditorModal = ({}}visible={notebookPickerOpen}/>- <MobileAttachmentActions+ <MobileResourceActionscanMutate={Boolean(memo && !memo.id.startsWith("local:"))}- onClose={() => setAttachmentTarget(null)}- onDelete={deleteAttachment}- onOpen={openAttachment}- onRename={renameAttachment}- target={attachmentTarget}+ onClose={() => setResourceTarget(null)}+ onDelete={deleteResource}+ onDownload={downloadResource}+ onRename={renameResource}+ onSaveAs={saveResourceAs}+ target={resourceTarget}/></SafeAreaView>);