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
Add mobile attachment actions
tianma-iff3f61922e723
diff --git a/apps/mobile/src/components/LocalTiptapEditor.tsx b/apps/mobile/src/components/LocalTiptapEditor.tsxindex aea2ff77..292f8c1e 100644--- a/apps/mobile/src/components/LocalTiptapEditor.tsx+++ b/apps/mobile/src/components/LocalTiptapEditor.tsx@@ -8,8 +8,9 @@ import Placeholder from "@tiptap/extension-placeholder";import { TableKit } from "@tiptap/extension-table";import { EditorContent, useEditor, useEditorState } from "@tiptap/react";import StarterKit from "@tiptap/starter-kit";+import type { Mark } from "@tiptap/pm/model";import * as Clipboard from "expo-clipboard";-import { getImageReferrerPolicy, type TiptapDoc } from "@edgeever/shared";+import { getImageReferrerPolicy, getResourceIdFromUrl, type TiptapDoc } from "@edgeever/shared";import {DEFAULT_IMAGE_WIDTH_PERCENT,IMAGE_WIDTH_PRESETS,@@ -44,6 +45,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;flush: () => void;focusEnd: () => void;replaceAll: (query: DOMValue, replacement: DOMValue) => void;@@ -58,6 +61,7 @@ type LocalTiptapEditorProps = {dom?: DOMProps;onChange: (content: EditorDoc) => Promise<void>;onLoadResource: (source: string) => Promise<string | null>;+ onAttachmentPress?: (targetJson: string) => Promise<void>;onPickImage: () => Promise<void>;onReady: (startupMs: number) => Promise<void>;onSearchResult?: (count: number, index: number) => Promise<void>;@@ -78,6 +82,47 @@ const CHANGE_IDLE_MS = 500;const TRANSIENT_IMAGE_UPLOAD_META = "edgeeverImageUploadPlaceholder";const ignoreSearchResult = async () => undefined;+type EditorAttachmentTarget = {+ filename: string;+ href: string;+ resourceId: string;+};++const parseMobileAttachmentTarget = (value: string): EditorAttachmentTarget | null => {+ try {+ const parsed = JSON.parse(value) as Partial<EditorAttachmentTarget>;+ if (typeof parsed.href !== "string" || typeof parsed.filename !== "string") return null;+ const resourceId = getResourceIdFromUrl(parsed.href);+ if (!resourceId || (parsed.resourceId && parsed.resourceId !== resourceId)) return null;+ return { filename: parsed.filename, href: parsed.href, resourceId };+ } catch {+ return null;+ }+};++const normalizeEditorAttachmentFilename = (label: string, resourceId: string) =>+ label.replace(/^\s*(?:附件[::]|Attachment:)\s*/i, "").trim() || resourceId;++const handleMobileAttachmentEvent = (+ event: Event,+ onAttachmentPress?: (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;++ event.preventDefault();+ event.stopPropagation();+ void onAttachmentPress(JSON.stringify({+ filename: normalizeEditorAttachmentFilename(link.textContent ?? "", resourceId),+ href,+ resourceId,+ } satisfies EditorAttachmentTarget));+ return true;+};+const getMobileMermaidTheme = (theme: "light" | "dark") => THEMES[theme === "dark" ? "zinc-dark" : "zinc-light"];const renderWithBeautifulMermaid = (source: string, theme: "light" | "dark") => {@@ -235,12 +280,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 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;onPickImageRef.current = props.onPickImage;onReadyRef.current = props.onReady;onSearchResultRef.current = props.onSearchResult ?? ignoreSearchResult;@@ -256,7 +303,7 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {const editor = useEditor({autofocus: props.autoFocus ? "end" : false,extensions: [- StarterKit.configure({ codeBlock: false }),+ StarterKit.configure({ codeBlock: false, link: { openOnClick: false } }),mermaidCodeBlockExtension,protectedImageExtension,TableKit.configure({@@ -269,6 +316,10 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {content: resolveImageSources(props.content, props.baseUrl),editorProps: {attributes: getMobileEditorInputAttributes("edgeever-editor-content"),+ handleClick: (_view, _pos, event) => handleMobileAttachmentEvent(event, onAttachmentPressRef.current),+ handleDOMEvents: {+ contextmenu: (_view, event) => handleMobileAttachmentEvent(event, onAttachmentPressRef.current),+ },},onUpdate: ({ editor: activeEditor, transaction }) => {if (transaction.getMeta(TRANSIENT_IMAGE_UPLOAD_META)) {@@ -371,7 +422,7 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {type: "paragraph",content: [{type: "text",- text: `附件:${filenameValue}`,+ text: `${props.locale === "en-US" ? "Attachment: " : "附件:"}${filenameValue}`,marks: [{type: "link",attrs: {@@ -382,7 +433,42 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {}],}],}).run();- }, [editor, props.baseUrl]);+ }, [editor, props.baseUrl, props.locale]);++ const renameAttachment = useCallback((targetJsonValue: DOMValue, filenameValue: DOMValue) => {+ if (!editor || typeof targetJsonValue !== "string" || typeof filenameValue !== "string") return;+ const target = parseMobileAttachmentTarget(targetJsonValue);+ if (!target) return;+ const range = findMobileAttachmentRange(editor, target.resourceId);+ if (!range) return;+ editor.view.dispatch(editor.state.tr.replaceWith(+ range.from,+ range.to,+ editor.schema.text(`${props.locale === "en-US" ? "Attachment: " : "附件:"}${filenameValue}`, [...range.marks])+ ));+ }, [editor, props.locale]);++ const removeAttachment = useCallback((targetJsonValue: DOMValue) => {+ if (!editor || typeof targetJsonValue !== "string") return;+ const target = parseMobileAttachmentTarget(targetJsonValue);+ if (!target) return;+ const range = findMobileAttachmentRange(editor, target.resourceId);+ if (!range) return;+ const resolved = editor.state.doc.resolve(range.from);+ let from = range.from;+ let to = range.to;+ for (let depth = resolved.depth; depth > 0; depth -= 1) {+ const node = resolved.node(depth);+ if (node.type.name !== "paragraph") continue;+ const nodeFrom = resolved.before(depth);+ if (range.from === nodeFrom + 1 && range.to === nodeFrom + node.nodeSize - 1) {+ from = nodeFrom;+ to = nodeFrom + node.nodeSize;+ }+ break;+ }+ editor.view.dispatch(editor.state.tr.delete(from, to));+ }, [editor]);useDOMImperativeHandle(props.ref,@@ -393,10 +479,12 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {appendAttachment,flush,focusEnd: () => editor?.commands.focus("end"),+ removeAttachment,+ renameAttachment,replaceAll,search,}),- [appendAttachment, beginImageUpload, cancelImageUpload, completeImageUpload, editor, flush, replaceAll, search]+ [appendAttachment, beginImageUpload, cancelImageUpload, completeImageUpload, editor, flush, removeAttachment, renameAttachment, replaceAll, search]);useEffect(() => {@@ -1180,6 +1268,23 @@ const createProtectedImageExtension = (type TiptapEditor = NonNullable<ReturnType<typeof useEditor>>;type ImageUploadPlaceholderMatch = { nodeSize: number; pos: number };+type AttachmentRange = { from: number; marks: readonly Mark[]; to: number };++const findMobileAttachmentRange = (editor: TiptapEditor, resourceId: string): AttachmentRange | null => {+ let match: AttachmentRange | null = null;+ editor.state.doc.descendants((node, pos) => {+ if (!node.isText || !node.text) return;+ const hasResourceLink = node.marks.some((mark) =>+ mark.type.name === "link" &&+ typeof mark.attrs.href === "string" &&+ getResourceIdFromUrl(mark.attrs.href) === resourceId+ );+ if (!hasResourceLink) return;+ match = { from: pos, marks: node.marks, to: pos + node.nodeSize };+ return false;+ });+ return match;+};const findImageUploadPlaceholder = (editor: TiptapEditor,@@ -1276,6 +1381,9 @@ const getEditorStyles = (theme: "light" | "dark") => `.edgeever-editor-content pre { overflow-x: auto; border-radius: 10px; padding: 14px 90px 14px 14px; background: #0f172a; color: #e2e8f0; }.edgeever-editor-content code { border-radius: 4px; padding: 2px 4px; background: ${theme === "dark" ? "#1e293b" : "#f1f5f9"}; }.edgeever-editor-content pre code { padding: 0; background: transparent; }+ .edgeever-editor-content a.edgeever-attachment-link, .edgeever-editor-content a[href*="/api/v1/resources/"] { display: flex; min-height: 58px; align-items: center; gap: 10px; margin: 8px 0; border: 1px solid ${theme === "dark" ? "#334155" : "#cbd5e1"}; border-radius: 12px; padding: 10px 12px; background: ${theme === "dark" ? "#172033" : "#f8fafc"}; color: ${theme === "dark" ? "#f1f5f9" : "#1e293b"}; font-size: 15px; font-weight: 700; line-height: 1.35; text-decoration: none; }+ .edgeever-editor-content a.edgeever-attachment-link::before, .edgeever-editor-content a[href*="/api/v1/resources/"]::before { display: inline-flex; width: 38px; height: 38px; flex: 0 0 38px; align-items: center; justify-content: center; border-radius: 9px; background: ${theme === "dark" ? "#134e4a" : "#ecfdf5"}; content: "📎"; font-size: 18px; }+ .edgeever-editor-content a.edgeever-attachment-link::after, .edgeever-editor-content a[href*="/api/v1/resources/"]::after { margin-left: auto; color: ${theme === "dark" ? "#94a3b8" : "#64748b"}; content: "⋯"; font-size: 22px; font-weight: 700; }.edgeever-code-block, .edgeever-mermaid-code-block { position: relative; margin: 18px 0; overflow: visible; background: transparent; }.edgeever-code-copy-button { position: absolute; top: 8px; right: 8px; z-index: 1; border: 1px solid ${theme === "dark" ? "#475569" : "#cbded1"}; border-radius: 6px; padding: 5px 8px; background: ${theme === "dark" ? "rgba(30, 41, 59, 0.94)" : "rgba(247, 251, 248, 0.94)"}; color: ${theme === "dark" ? "#cbd5e1" : "#475569"}; font: inherit; font-size: 12px; line-height: 1.35; }.edgeever-code-copy-button:active { border-color: #0f766e; color: ${theme === "dark" ? "#86efac" : "#0f766e"}; }diff --git a/apps/mobile/src/components/MobileAttachmentActions.tsx b/apps/mobile/src/components/MobileAttachmentActions.tsxnew file mode 100644index 00000000..fc81746c--- /dev/null+++ b/apps/mobile/src/components/MobileAttachmentActions.tsx@@ -0,0 +1,266 @@+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 { Pressable, Text, TextInput } from "./LocalizedText";+import type { MobileAttachmentTarget } from "../lib/mobile-attachments";+import { useMobileLocale } from "../lib/mobile-locale";+import { useMobileTheme } from "../lib/mobile-theme";++type MobileAttachmentActionsProps = {+ canMutate: boolean;+ onClose: () => void;+ onDelete: (target: MobileAttachmentTarget) => Promise<void>;+ onOpen: (target: MobileAttachmentTarget) => Promise<void>;+ onRename: (target: MobileAttachmentTarget, filename: string) => Promise<void>;+ target: MobileAttachmentTarget | null;+};++const copy = {+ "zh-CN": {+ actions: "附件操作",+ cancel: "取消",+ delete: "删除",+ deleteConfirm: "附件会从存储空间和当前笔记中永久删除,此操作无法撤销。",+ deleteTitle: "删除附件",+ download: "下载 / 打开",+ failed: "附件操作失败,请重试。",+ filename: "文件名",+ rename: "重命名",+ renameTitle: "重命名附件",+ save: "保存",+ syncedOnly: "附件同步完成后才能重命名或删除。",+ },+ "en-US": {+ actions: "Attachment 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.",+ filename: "Filename",+ rename: "Rename",+ renameTitle: "Rename attachment",+ save: "Save",+ syncedOnly: "Rename and delete are available after the attachment has synced.",+ },+} as const;++export const MobileAttachmentCard = ({+ busy = false,+ onActions,+ onOpen,+ target,+}: {+ busy?: boolean;+ onActions: () => void;+ onOpen: () => void;+ target: MobileAttachmentTarget;+}) => {+ const { resolvedTheme } = useMobileTheme();+ const { resolvedLocale } = useMobileLocale();+ const extension = target.filename.includes(".") ? target.filename.split(".").pop()?.toUpperCase() : "FILE";+ const dark = resolvedTheme === "dark";+ const longPressAtRef = useRef(0);++ return (+ <View style={[styles.card, dark && styles.cardDark]}>+ <Pressable+ accessibilityHint={resolvedLocale === "en-US" ? "Downloads the attachment and opens the system file menu" : "下载附件并打开系统文件菜单"}+ accessibilityLabel={target.filename}+ accessibilityRole="button"+ disabled={busy}+ onLongPress={() => {+ longPressAtRef.current = Date.now();+ onActions();+ }}+ onPress={() => {+ if (Date.now() - longPressAtRef.current < 800) return;+ onOpen();+ }}+ style={styles.cardMain}+ >+ <View style={[styles.fileIcon, dark && styles.fileIconDark]}>+ {busy ? <ActivityIndicator color="#059669" size="small" /> : <FileText color={dark ? "#a7f3d0" : "#047857"} size={20} />}+ </View>+ <View style={styles.cardText}>+ <Text numberOfLines={2} style={[styles.filename, dark && styles.filenameDark]}>{target.filename}</Text>+ <Text style={[styles.fileType, dark && styles.fileTypeDark]}>{extension || "FILE"}</Text>+ </View>+ </Pressable>+ <Pressable+ accessibilityLabel={resolvedLocale === "en-US" ? "Attachment actions" : "附件操作"}+ accessibilityRole="button"+ disabled={busy}+ onPress={onActions}+ style={styles.moreButton}+ >+ <MoreHorizontal color={dark ? "#94a3b8" : "#64748b"} size={21} />+ </Pressable>+ </View>+ );+};++export const MobileAttachmentActions = ({+ canMutate,+ onClose,+ onDelete,+ onOpen,+ onRename,+ target,+}: MobileAttachmentActionsProps) => {+ const { resolvedLocale } = useMobileLocale();+ const labels = copy[resolvedLocale];+ const [mode, setMode] = useState<"actions" | "rename">("actions");+ const [filename, setFilename] = useState("");+ const [pending, setPending] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ if (!target) return;+ setMode("actions");+ setFilename(target.filename);+ setError(null);+ }, [target]);++ if (!target) return null;++ const run = async (action: () => Promise<void>, closeAfter = true) => {+ setPending(true);+ setError(null);+ try {+ await action();+ if (closeAfter) onClose();+ } catch (actionError) {+ setError(actionError instanceof Error ? actionError.message : labels.failed);+ } finally {+ setPending(false);+ }+ };++ const confirmDelete = () => {+ Alert.alert(labels.deleteTitle, labels.deleteConfirm, [+ { text: labels.cancel, style: "cancel" },+ { text: labels.delete, style: "destructive", onPress: () => void run(() => onDelete(target)) },+ ]);+ };++ return (+ <Modal animationType="fade" onRequestClose={pending ? undefined : onClose} transparent visible>+ <Pressable disabled={pending} onPress={onClose} style={styles.backdrop}>+ <Pressable style={styles.sheet}>+ <View style={styles.handle} />+ <View style={styles.sheetHeader}>+ <View style={styles.sheetHeaderText}>+ <Text style={styles.sheetTitle}>{mode === "rename" ? labels.renameTitle : labels.actions}</Text>+ <Text numberOfLines={1} style={styles.sheetSubtitle}>{target.filename}</Text>+ </View>+ <Pressable accessibilityLabel={labels.cancel} accessibilityRole="button" disabled={pending} onPress={onClose} style={styles.closeButton}>+ <X color="#475569" size={19} />+ </Pressable>+ </View>++ {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} />+ <View style={styles.divider} />+ <AttachmentActionRow 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>+ ) : (+ <View style={styles.renameForm}>+ <Text style={styles.inputLabel}>{labels.filename}</Text>+ <TextInput+ autoFocus+ editable={!pending}+ maxLength={160}+ onChangeText={setFilename}+ selectTextOnFocus+ style={styles.input}+ value={filename}+ />+ <View style={styles.formButtons}>+ <Pressable disabled={pending} onPress={() => setMode("actions")} style={styles.secondaryButton}>+ <Text style={styles.secondaryButtonText}>{labels.cancel}</Text>+ </Pressable>+ <Pressable+ disabled={pending || !filename.trim()}+ onPress={() => void run(() => onRename(target, filename.trim()))}+ style={[styles.primaryButton, (pending || !filename.trim()) && styles.disabled]}+ >+ {pending ? <ActivityIndicator color="#fff" size="small" /> : <Text style={styles.primaryButtonText}>{labels.save}</Text>}+ </Pressable>+ </View>+ </View>+ )}+ {error ? <Text accessibilityLiveRegion="polite" style={styles.error}>{error}</Text> : null}+ </Pressable>+ </Pressable>+ </Modal>+ );+};++const AttachmentActionRow = ({+ danger = false,+ disabled = false,+ icon,+ label,+ onPress,+ pending,+}: {+ danger?: boolean;+ disabled?: boolean;+ icon: ReactNode;+ label: string;+ onPress: () => void;+ pending: boolean;+}) => (+ <Pressable+ accessibilityRole="button"+ disabled={disabled || pending}+ onPress={onPress}+ style={[styles.actionRow, disabled && styles.disabled]}+ >+ {icon}+ <Text style={[styles.actionLabel, danger && styles.dangerText]}>{label}</Text>+ </Pressable>+);++const styles = StyleSheet.create({+ actionLabel: { color: "#0f172a", fontSize: 16, fontWeight: "600" },+ actionRow: { alignItems: "center", flexDirection: "row", gap: 14, minHeight: 52, paddingHorizontal: 6 },+ actions: { gap: 2, paddingTop: 8 },+ backdrop: { backgroundColor: "rgba(15,23,42,0.34)", flex: 1, justifyContent: "flex-end" },+ card: { alignItems: "center", backgroundColor: "#f8fafc", borderColor: "#cbd5e1", borderRadius: 12, borderWidth: 1, flexDirection: "row", marginVertical: 6, minHeight: 64 },+ cardDark: { backgroundColor: "#172033", borderColor: "#334155" },+ cardMain: { alignItems: "center", flex: 1, flexDirection: "row", gap: 12, minHeight: 62, paddingHorizontal: 12, paddingVertical: 9 },+ cardText: { flex: 1, gap: 3 },+ closeButton: { alignItems: "center", height: 40, justifyContent: "center", width: 40 },+ dangerText: { color: "#be123c" },+ disabled: { opacity: 0.45 },+ divider: { backgroundColor: "#e2e8f0", height: 1, marginVertical: 4 },+ error: { color: "#be123c", fontSize: 13, marginTop: 10 },+ fileIcon: { alignItems: "center", backgroundColor: "#ecfdf5", borderRadius: 10, height: 42, justifyContent: "center", width: 42 },+ fileIconDark: { backgroundColor: "#134e4a" },+ filename: { color: "#1e293b", fontSize: 15, fontWeight: "700" },+ filenameDark: { color: "#f1f5f9" },+ fileType: { color: "#64748b", fontSize: 11, fontWeight: "700", letterSpacing: 0.6 },+ fileTypeDark: { color: "#94a3b8" },+ formButtons: { flexDirection: "row", gap: 10, justifyContent: "flex-end", marginTop: 14 },+ handle: { alignSelf: "center", backgroundColor: "#cbd5e1", borderRadius: 999, height: 4, marginBottom: 14, width: 42 },+ hint: { color: "#64748b", fontSize: 12, lineHeight: 18, marginTop: 4 },+ input: { borderColor: "#cbd5e1", borderRadius: 9, borderWidth: 1, color: "#0f172a", fontSize: 16, minHeight: 46, paddingHorizontal: 12 },+ inputLabel: { color: "#475569", fontSize: 13, fontWeight: "600" },+ moreButton: { alignItems: "center", alignSelf: "stretch", justifyContent: "center", minWidth: 48 },+ primaryButton: { alignItems: "center", backgroundColor: "#059669", borderRadius: 9, justifyContent: "center", minHeight: 42, minWidth: 84, paddingHorizontal: 16 },+ primaryButtonText: { color: "#fff", fontSize: 14, fontWeight: "700" },+ renameForm: { gap: 8, paddingTop: 14 },+ secondaryButton: { alignItems: "center", borderColor: "#cbd5e1", borderRadius: 9, borderWidth: 1, justifyContent: "center", minHeight: 42, minWidth: 84, paddingHorizontal: 16 },+ secondaryButtonText: { color: "#475569", fontSize: 14, fontWeight: "700" },+ sheet: { backgroundColor: "#fff", borderTopLeftRadius: 20, borderTopRightRadius: 20, paddingBottom: 28, paddingHorizontal: 20, paddingTop: 10 },+ sheetHeader: { alignItems: "center", flexDirection: "row", justifyContent: "space-between" },+ sheetHeaderText: { flex: 1, gap: 3 },+ sheetSubtitle: { color: "#64748b", fontSize: 13 },+ sheetTitle: { color: "#0f172a", fontSize: 19, fontWeight: "800" },+});diff --git a/apps/mobile/src/components/icons.tsx b/apps/mobile/src/components/icons.tsxindex 7b39aab8..7abde1b6 100644--- a/apps/mobile/src/components/icons.tsx+++ b/apps/mobile/src/components/icons.tsx@@ -26,6 +26,7 @@ export const ChevronRight = createIcon("chevron-right");export const Code = createIcon("code");export const Copy = createIcon("copy");export const Database = createIcon("database");+export const Download = createIcon("download");export const ExternalLink = createIcon("external-link");export const FileArchive = createIcon("archive");export const FileSpreadsheet = createIcon("grid");diff --git a/apps/mobile/src/lib/mobile-attachments.test.mjs b/apps/mobile/src/lib/mobile-attachments.test.mjsnew file mode 100644index 00000000..450d8855--- /dev/null+++ b/apps/mobile/src/lib/mobile-attachments.test.mjs@@ -0,0 +1,49 @@+import { describe, expect, test } from "bun:test";+import {+ deleteMobileAttachmentFromDoc,+ getMobileAttachmentTarget,+ getParagraphAttachmentTarget,+ parseMobileAttachmentTargetJson,+ renameMobileAttachmentInDoc,+} from "./mobile-attachments.ts";++const href = "/api/v1/resources/res_123/blob";+const doc = {+ type: "doc",+ content: [{+ type: "paragraph",+ content: [{+ type: "text",+ text: "附件:report.pdf",+ marks: [{ type: "link", attrs: { href, class: "edgeever-attachment-link" } }],+ }],+ }],+};++describe("mobile attachments", () => {+ test("recognizes resource links and attachment paragraphs", () => {+ expect(getMobileAttachmentTarget(href, "📄 报告:report.pdf")).toEqual({ filename: "report.pdf", href, resourceId: "res_123" });+ 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" });+ });++ 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();+ });++ test("renames the linked label", () => {+ const updated = renameMobileAttachmentInDoc(doc, { filename: "report.pdf", href, resourceId: "res_123" }, "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({+ type: "doc",+ content: [{ type: "paragraph" }],+ });+ });+});diff --git a/apps/mobile/src/lib/mobile-attachments.ts b/apps/mobile/src/lib/mobile-attachments.tsnew file mode 100644index 00000000..0360e659--- /dev/null+++ b/apps/mobile/src/lib/mobile-attachments.ts@@ -0,0 +1,158 @@+import type { createEdgeEverClient } from "@edgeever/client";+import { docToMarkdown, getResourceIdFromUrl, type TiptapDoc } from "@edgeever/shared";++export type MobileAttachmentTarget = {+ filename: string;+ href: string;+ resourceId: string;+};++type AttachmentClient = Pick<ReturnType<typeof createEdgeEverClient>, "getResourceBlob">;++type MarkdownNodeLike = {+ attributes?: Record<string, unknown>;+ children?: MarkdownNodeLike[];+ content?: string;+ type?: string;+};++const normalizeAttachmentFilename = (label: string, resourceId: string) => {+ const withoutPrefix = label.replace(/^\s*(?:附件[::]|Attachment:)\s*/i, "").trim();+ const colonParts = withoutPrefix.split(/[::]\s*/).filter(Boolean);+ const candidate = (colonParts.at(-1) || withoutPrefix)+ .replace(/^[\s📎📄📦📊🗃️🗂️]+/u, "")+ .trim();+ return candidate || resourceId;+};++export const getMobileAttachmentTarget = (href: string, label: string): MobileAttachmentTarget | null => {+ const resourceId = getResourceIdFromUrl(href);+ if (!resourceId) return null;+ return {+ filename: normalizeAttachmentFilename(label, resourceId),+ href,+ resourceId,+ };+};++export const parseMobileAttachmentTargetJson = (value: string): MobileAttachmentTarget | null => {+ try {+ const parsed = JSON.parse(value) as Partial<MobileAttachmentTarget>;+ if (typeof parsed.href !== "string" || typeof parsed.filename !== "string") return null;+ const resourceId = getResourceIdFromUrl(parsed.href);+ if (!resourceId || (parsed.resourceId && parsed.resourceId !== resourceId)) return null;+ return { filename: parsed.filename, href: parsed.href, resourceId };+ } catch {+ return null;+ }+};++const getMarkdownNodeText = (node: MarkdownNodeLike): string =>+ typeof node.content === "string"+ ? node.content+ : (node.children ?? []).map(getMarkdownNodeText).join("");++export const getParagraphAttachmentTarget = (node: MarkdownNodeLike): MobileAttachmentTarget | null => {+ if (node.type !== "paragraph") return null;+ const children = node.children ?? [];+ const links = children.filter((child) => child.type === "link");+ if (links.length !== 1) return null;++ const nonLinkText = children+ .filter((child) => child.type !== "link")+ .map(getMarkdownNodeText)+ .join("")+ .trim();+ if (nonLinkText && !/^(?:附件[::]?|Attachment:?)$/i.test(nonLinkText)) return null;++ const link = links[0];+ const href = typeof link.attributes?.href === "string" ? link.attributes.href : "";+ return getMobileAttachmentTarget(href, getMarkdownNodeText(link));+};++const hasResourceLinkMark = (value: unknown, resourceId: string) =>+ Array.isArray(value) && value.some((mark) => {+ if (!mark || typeof mark !== "object") return false;+ const candidate = mark as { attrs?: { href?: unknown }; type?: unknown };+ return candidate.type === "link" &&+ typeof candidate.attrs?.href === "string" &&+ getResourceIdFromUrl(candidate.attrs.href) === resourceId;+ });++const updateAttachmentDoc = (+ doc: TiptapDoc,+ target: MobileAttachmentTarget,+ action: { type: "delete" } | { type: "rename"; filename: string; labelPrefix: string }+): TiptapDoc => {+ const visit = (value: unknown): unknown => {+ if (Array.isArray(value)) {+ return value.map(visit).filter((child) => child !== null);+ }+ if (!value || typeof value !== "object") return value;++ const node = value as Record<string, unknown>;+ if (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)) {+ const remainingText = next.content+ .map((child) => child && typeof child === "object" && "text" in child ? String(child.text ?? "") : "")+ .join("")+ .trim();+ if (next.content.length === 0 || /^(?:附件[::]?|Attachment:?)$/i.test(remainingText)) return null;+ }+ return next;+ };++ const updated = visit(doc) as TiptapDoc;+ return Array.isArray(updated.content) && updated.content.length > 0+ ? updated+ : { type: "doc", content: [{ type: "paragraph" }] };+};++export const renameMobileAttachmentInDoc = (+ doc: TiptapDoc,+ target: MobileAttachmentTarget,+ filename: string,+ labelPrefix: string+) => updateAttachmentDoc(doc, target, { type: "rename", filename, labelPrefix });++export const deleteMobileAttachmentFromDoc = (doc: TiptapDoc, target: MobileAttachmentTarget) =>+ updateAttachmentDoc(doc, target, { type: "delete" });++export const getMobileAttachmentUpdatePayload = (contentJson: TiptapDoc) => ({+ contentJson,+ contentMarkdown: docToMarkdown(contentJson),+});++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 [{ Directory, File, Paths }, Sharing] = await Promise.all([+ import("expo-file-system"),+ import("expo-sharing"),+ ]);+ // The DOM editor resolves relative links against the instance URL for display.+ // The client itself prefixes the instance base URL, so always give it the+ // canonical relative resource path here.+ const blob = await client.getResourceBlob(`/api/v1/resources/${encodeURIComponent(target.resourceId)}/blob`);+ const directory = new Directory(Paths.cache, "edgeever-attachments");+ if (!directory.exists) directory.create({ idempotent: true, intermediates: true });+ const file = new File(directory, `${target.resourceId}-${safeCacheFilename(target.filename)}`);+ if (file.exists) file.delete();+ file.create({ overwrite: true, intermediates: true });+ file.write(new Uint8Array(await blob.arrayBuffer()));++ if (!(await Sharing.isAvailableAsync())) {+ throw new Error("当前设备无法打开系统文件面板");+ }+ await Sharing.shareAsync(file.uri, {+ dialogTitle: target.filename,+ mimeType: blob.type || "application/octet-stream",+ });+ return file.uri;+};diff --git a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx b/apps/mobile/src/screens/WorkspaceMemoDetail.tsxindex fcda0441..7d5e1f2b 100644--- a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx+++ b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";+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 { Modal } from "react-native";@@ -6,8 +6,14 @@ 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 { Pressable, Text, TextInput } from "../components/LocalizedText";+import { Alert, Pressable, Text, TextInput } from "../components/LocalizedText";import { MobileMermaidDiagram, MobileMermaidProvider } from "../components/MobileMermaid";+import { MobileAttachmentActions, MobileAttachmentCard } from "../components/MobileAttachmentActions";+import {+ getParagraphAttachmentTarget,+ openMobileAttachment,+ type MobileAttachmentTarget,+} from "../lib/mobile-attachments";import { getMobileMarkdownFenceLanguage, trimMobileMarkdownFenceContent } from "../lib/mobile-mermaid";import { useMobileLocale } from "../lib/mobile-locale";import { resolveMobileThemeStyles, useMobileTheme } from "../lib/mobile-theme";@@ -199,8 +205,10 @@ export const MemoDetailModal = ({notebookName,onClose,onDelete,+ onDeleteAttachment,onRichEdit,onOpenRevisions,+ onRenameAttachment,onResolveSyncConflict,onRestore,onShare,@@ -216,15 +224,17 @@ export const MemoDetailModal = ({notebookName: string;onClose: () => void;onDelete: (memo: MemoDetail) => void;+ onDeleteAttachment: (memo: MemoDetail, target: MobileAttachmentTarget) => Promise<void>;onRichEdit: (memo: MemoDetail) => void;onOpenRevisions: (memo: MemoDetail) => void;+ onRenameAttachment: (memo: MemoDetail, target: MobileAttachmentTarget, filename: string) => Promise<void>;onResolveSyncConflict: (memo: MemoDetail) => void;onRestore: (memo: MemoDetail) => void;onShare: (memo: MemoDetail) => void;syncStatus: MobileSyncQueueItem["status"] | null;visible: boolean;}) => {- const { session } = useSession();+ const { client, session } = useSession();const { resolvedTheme } = useMobileTheme();const { resolvedLocale } = useMobileLocale();const { width: viewportWidth } = useWindowDimensions();@@ -233,7 +243,26 @@ 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 [downloadingAttachmentId, setDownloadingAttachmentId] = useState<string | null>(null);const localePreference = useMobileLocalePreference();+ const openAttachment = useCallback(async (target: MobileAttachmentTarget) => {+ if (!client) throw new Error(resolvedLocale === "en-US" ? "The attachment client is unavailable." : "当前无法读取附件。");+ setDownloadingAttachmentId(target.resourceId);+ try {+ await openMobileAttachment(client, target);+ } finally {+ setDownloadingAttachmentId(null);+ }+ }, [client, resolvedLocale]);+ const openAttachmentFromCard = useCallback((target: MobileAttachmentTarget) => {+ void openAttachment(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]);const themedDetailMarkdownStyles = useMemo(() => ({...resolveMobileThemeStyles(detailMarkdownStyles, resolvedTheme),@@ -325,7 +354,21 @@ export const MemoDetailModal = ({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) => 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={() => setAttachmentTarget(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@@ -348,7 +391,7 @@ export const MemoDetailModal = ({td: (node, children, parents, markdownStyles) => renderTableCell(node, children, parents, markdownStyles, false),th: (node, children, parents, markdownStyles) => renderTableCell(node, children, parents, markdownStyles, true),};- }, [resolvedLocale, resolvedTheme, session, viewportWidth]);+ }, [downloadingAttachmentId, openAttachmentFromCard, resolvedLocale, resolvedTheme, session, viewportWidth]);const detailText = memo? resolveMemoContentMarkdown(memo.contentJson, memo.contentMarkdown) || memo.contentText || "没有正文内容": "没有正文内容";@@ -535,6 +578,20 @@ export const MemoDetailModal = ({</Pressable></Modal>) : null}+ <MobileAttachmentActions+ canMutate={Boolean(memo && !memo.isDeleted && !memo.id.startsWith("local:"))}+ onClose={() => setAttachmentTarget(null)}+ onDelete={async (target) => {+ if (!memo) return;+ await onDeleteAttachment(memo, target);+ }}+ onOpen={openAttachment}+ onRename={async (target, filename) => {+ if (!memo) return;+ await onRenameAttachment(memo, target, filename);+ }}+ target={attachmentTarget}+ /></SafeAreaView></Modal>);diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsxindex 23a5b47f..054bdc8e 100644--- a/apps/mobile/src/screens/WorkspaceScreen.tsx+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx@@ -105,6 +105,7 @@ import EditorRuntimePrewarm from "../components/EditorRuntimePrewarm";import MobileWebClipCapture from "../components/MobileWebClipCapture";import { showEdgeEverKeyboard } from "../../modules/edgeever-keyboard";import LocalTiptapEditor, { type LocalTiptapEditorRef } from "../components/LocalTiptapEditor";+import { MobileAttachmentActions } from "../components/MobileAttachmentActions";import { resolveMobileThemeStyles, useMobileTheme } from "../lib/mobile-theme";import { useMobileUpdate } from "../lib/mobile-update";import { MobileMermaidDiagram, MobileMermaidProvider } from "../components/MobileMermaid";@@ -147,6 +148,14 @@ import { refreshWorkspaceThemeStyles, styles } from "./workspace-styles";import { NotesView } from "./WorkspaceNotesView";import { SettingsView, type MobileLocaleMode } from "./WorkspaceSettingsView";import { MemoDetailModal } from "./WorkspaceMemoDetail";+import {+ deleteMobileAttachmentFromDoc,+ getMobileAttachmentUpdatePayload,+ openMobileAttachment,+ parseMobileAttachmentTargetJson,+ renameMobileAttachmentInDoc,+ type MobileAttachmentTarget,+} from "../lib/mobile-attachments";const ALL_NOTES_ID = "all";const DEFAULT_MEMO_TITLE = "无标题笔记";@@ -175,7 +184,7 @@ export const WorkspaceScreen = ({onIncomingShareHandled?: () => void;}) => {const { resolvedTheme } = useMobileTheme();- const { preference: localePreference, setPreference: setLocalePreference } = useMobileLocale();+ const { preference: localePreference, resolvedLocale, setPreference: setLocalePreference } = useMobileLocale();refreshWorkspaceThemeStyles(resolvedTheme);const { client, session, signOut } = useSession();const queryClient = useQueryClient();@@ -915,6 +924,31 @@ export const WorkspaceScreen = ({]);};+ const handleRenameAttachment = async (memo: MemoDetail, target: MobileAttachmentTarget, filename: string) => {+ if (!client) throw new Error("当前无法连接实例,请稍后重试");+ const { resource } = await client.renameResource(target.resourceId, filename);+ const contentJson = renameMobileAttachmentInDoc(+ memo.contentJson,+ target,+ resource.filename || filename,+ resolvedLocale === "en-US" ? "Attachment: " : "附件:"+ );+ await localUpdateMemoMutation.mutateAsync({+ memo,+ payload: getMobileAttachmentUpdatePayload(contentJson),+ });+ };++ const handleDeleteAttachment = async (memo: MemoDetail, target: MobileAttachmentTarget) => {+ if (!client) throw new Error("当前无法连接实例,请稍后重试");+ await client.deleteResource(target.resourceId);+ const contentJson = deleteMobileAttachmentFromDoc(memo.contentJson, target);+ await localUpdateMemoMutation.mutateAsync({+ memo,+ payload: getMobileAttachmentUpdatePayload(contentJson),+ });+ };+const handleMemoSyncConflict = (memo: MemoDetail) => {Alert.alert("同步冲突",@@ -1061,8 +1095,10 @@ export const WorkspaceScreen = ({notebookName={notebooks.find((notebook) => notebook.id === selectedMemo?.notebookId)?.name ?? "未分类"}onClose={closeDetail}onDelete={handleDeleteMemo}+ onDeleteAttachment={handleDeleteAttachment}onRichEdit={(memo) => void openRichEditor(memo)}onOpenRevisions={setRevisionMemo}+ onRenameAttachment={handleRenameAttachment}onResolveSyncConflict={handleMemoSyncConflict}onRestore={(memo) => restoreMemoMutation.mutate(memo)}onShare={(memo) => shareMemoMutation.mutate(memo)}@@ -1583,6 +1619,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 targetNotebookId = notebookId || fallbackNotebookId;const selectedNotebookName = notebooks.find((notebook) => notebook.id === targetNotebookId)?.name ?? "选择笔记本";const titleRef = useRef(title);@@ -1875,6 +1912,28 @@ const CreateMemoModal = ({return pending;}, [client]);+ const openAttachment = useCallback(async (target: MobileAttachmentTarget) => {+ if (!client) throw new Error(resolvedLocale === "en-US" ? "The attachment client is unavailable." : "当前无法读取附件。");+ await openMobileAttachment(client, target);+ }, [client, resolvedLocale]);++ const renameAttachment = useCallback(async (target: MobileAttachmentTarget, 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);+ }, [client, resolvedLocale]);++ const deleteAttachment = useCallback(async (target: MobileAttachmentTarget) => {+ 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));+ }, [client, resolvedLocale]);++ const selectAttachment = useCallback(async (targetJson: string) => {+ const target = parseMobileAttachmentTargetJson(targetJson);+ if (target) setAttachmentTarget(target);+ }, []);+const editorElement = useMemo(() => draftLoaded && baseUrl ? (<LocalTiptapEditorautoFocus@@ -1896,6 +1955,7 @@ const CreateMemoModal = ({flushResolverRef.current?.();flushResolverRef.current = null;}}+ onAttachmentPress={selectAttachment}onLoadResource={loadEditorResource}onPickImage={pickAndUploadImage}onReady={async (elapsedMs) => {@@ -1909,7 +1969,7 @@ const CreateMemoModal = ({locale={resolvedLocale}theme={resolvedTheme}/>- ) : null, [baseUrl, draftLoaded, loadEditorResource, resolvedLocale, resolvedTheme]);+ ) : null, [baseUrl, draftLoaded, loadEditorResource, resolvedLocale, resolvedTheme, selectAttachment]);return (<Modal animationType="slide" onRequestClose={() => void requestClose()} presentationStyle="fullScreen" visible={visible}>@@ -1991,6 +2051,14 @@ const CreateMemoModal = ({}}visible={notebookPickerOpen}/>+ <MobileAttachmentActions+ canMutate={Boolean(materializedMemoRef.current)}+ onClose={() => setAttachmentTarget(null)}+ onDelete={deleteAttachment}+ onOpen={openAttachment}+ onRename={renameAttachment}+ target={attachmentTarget}+ /></SafeAreaView></Modal>);@@ -2195,6 +2263,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 notebookLabel = notebooks.find((notebook) => notebook.id === notebookId)?.name ?? "未分类";const saveLabel = error ? "保存失败" : saving ? "保存中" : uploading ? "上传中" : dirty ? (draftRestored ? "本地草稿" : "未保存") : ready ? "已保存" : "加载中";const titleRef = useRef(title);@@ -2383,6 +2452,28 @@ const RichEditorModal = ({return pending;}, [client]);+ const openAttachment = useCallback(async (target: MobileAttachmentTarget) => {+ if (!client) throw new Error(resolvedLocale === "en-US" ? "The attachment client is unavailable." : "当前无法读取附件。");+ await openMobileAttachment(client, target);+ }, [client, resolvedLocale]);++ const renameAttachment = useCallback(async (target: MobileAttachmentTarget, 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);+ }, [client, memo, resolvedLocale]);++ const deleteAttachment = useCallback(async (target: MobileAttachmentTarget) => {+ 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));+ }, [client, memo, resolvedLocale]);++ const selectAttachment = useCallback(async (targetJson: string) => {+ const target = parseMobileAttachmentTargetJson(targetJson);+ if (target) setAttachmentTarget(target);+ }, []);+const editorElement = useMemo(() => memo && baseUrl ? (<LocalTiptapEditor@@ -2397,6 +2488,7 @@ const RichEditorModal = ({style: styles.richEditorWebView,}}onChange={persistDraft}+ onAttachmentPress={selectAttachment}onLoadResource={loadEditorResource}onPickImage={pickAndUploadImage}onReady={async (elapsedMs) => {@@ -2419,7 +2511,7 @@ const RichEditorModal = ({theme={resolvedTheme}/>) : null,- [baseUrl, loadEditorResource, memo?.id, resolvedLocale, resolvedTheme]+ [baseUrl, loadEditorResource, memo?.id, resolvedLocale, resolvedTheme, selectAttachment]);useEffect(() => {@@ -2531,6 +2623,14 @@ const RichEditorModal = ({}}visible={notebookPickerOpen}/>+ <MobileAttachmentActions+ canMutate={Boolean(memo && !memo.id.startsWith("local:"))}+ onClose={() => setAttachmentTarget(null)}+ onDelete={deleteAttachment}+ onOpen={openAttachment}+ onRename={renameAttachment}+ target={attachmentTarget}+ /></SafeAreaView>);};diff --git a/apps/web/src/lib/attachment-links.ts b/apps/web/src/lib/attachment-links.tsindex 467f8e40..c8447ffc 100644--- a/apps/web/src/lib/attachment-links.ts+++ b/apps/web/src/lib/attachment-links.ts@@ -1,24 +1,4 @@-const RESOURCE_PATH_PATTERN = /\/api\/v1\/resources\/([^/]+)\/blob(?:$|[?#])/;--export const getAttachmentResourceId = (href: string): string | null => {- if (href.startsWith("edgeever-resource://")) {- try {- const parsed = new URL(href);- const resourceId = decodeURIComponent(parsed.pathname.replace(/^\//, ""));- return resourceId || null;- } catch {- return null;- }- }-- try {- const parsed = new URL(href, "http://edgeever.local");- const match = parsed.pathname.match(RESOURCE_PATH_PATTERN);- return match?.[1] ? decodeURIComponent(match[1]) : null;- } catch {- return null;- }-};--export const getAttachmentFilenameFromLabel = (label: string) =>- label.replace(/^\s*(?:附件[::]|Attachment:)\s*/i, "").trim();+export {+ getAttachmentFilenameFromLabel,+ getResourceIdFromUrl as getAttachmentResourceId,+} from "@edgeever/shared";diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex f2c2d54f..411b304b 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -8,6 +8,7 @@ export * from "./memo-content-style";export * from "./note-links";export * from "./notebooks";export * from "./revision-diff";+export * from "./resource-links";export * from "./schemas";export * from "./sharing";export * from "./sync";diff --git a/packages/shared/src/resource-links.ts b/packages/shared/src/resource-links.tsnew file mode 100644index 00000000..2558ecd5--- /dev/null+++ b/packages/shared/src/resource-links.ts@@ -0,0 +1,24 @@+const RESOURCE_PATH_PATTERN = /\/api\/v1\/resources\/([^/]+)\/blob(?:$|[?#])/;++export const getResourceIdFromUrl = (href: string): string | null => {+ if (href.startsWith("edgeever-resource://")) {+ try {+ const parsed = new URL(href);+ const resourceId = decodeURIComponent(parsed.pathname.replace(/^\//, ""));+ return resourceId || null;+ } catch {+ return null;+ }+ }++ try {+ const parsed = new URL(href, "http://edgeever.local");+ const match = parsed.pathname.match(RESOURCE_PATH_PATTERN);+ return match?.[1] ? decodeURIComponent(match[1]) : null;+ } catch {+ return null;+ }+};++export const getAttachmentFilenameFromLabel = (label: string) =>+ label.replace(/^\s*(?:附件[::]|Attachment:)\s*/i, "").trim();