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
fix(web): delete in-note video and file attachment cards
tianma-if7cd8de64e422
diff --git a/apps/mobile/src/lib/mobile-attachments.test.mjs b/apps/mobile/src/lib/mobile-attachments.test.mjsindex 229fb096..06d489bc 100644--- a/apps/mobile/src/lib/mobile-attachments.test.mjs+++ b/apps/mobile/src/lib/mobile-attachments.test.mjs@@ -66,6 +66,66 @@ describe("mobile attachments", () => {});});+ test("removes and renames file and PDF attachment nodes", () => {+ const videoTarget = {+ filename: "clip.mp4",+ href: "/api/v1/resources/res_video/blob",+ kind: "attachment",+ resourceId: "res_video",+ };+ const nodeDoc = {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [{+ type: "edgeeverFileAttachment",+ attrs: {+ url: "edgeever-resource://resource/res_video",+ label: "附件:clip.mp4",+ filename: "clip.mp4",+ mimeType: "video/mp4",+ },+ }],+ },+ {+ type: "paragraph",+ content: [{+ type: "edgeeverPdfAttachment",+ attrs: {+ url: href,+ label: "附件:report.pdf",+ filename: "report.pdf",+ },+ }],+ },+ ],+ };++ const renamed = renameMobileAttachmentInDoc(nodeDoc, videoTarget, "final.mp4", "附件:");+ expect(renamed.content[0].content[0]).toEqual({+ type: "edgeeverFileAttachment",+ attrs: {+ url: "edgeever-resource://resource/res_video",+ label: "附件:final.mp4",+ filename: "final.mp4",+ mimeType: "video/mp4",+ },+ });+ expect(renamed.content[1].content[0].type).toBe("edgeeverPdfAttachment");+ expect(deleteMobileAttachmentFromDoc(nodeDoc, videoTarget).content).toEqual([{+ type: "paragraph",+ content: [{+ type: "edgeeverPdfAttachment",+ attrs: {+ url: href,+ label: "附件:report.pdf",+ filename: "report.pdf",+ },+ }],+ }]);+ });+test("recognizes and validates image resources", () => {const target = { filename: "photo.jpg", href, kind: "image", resourceId: "res_123" };expect(getMobileImageTarget(href, "photo.jpg")).toEqual(target);diff --git a/apps/mobile/src/lib/mobile-attachments.ts b/apps/mobile/src/lib/mobile-attachments.tsindex 92d4e48d..971fd07d 100644--- a/apps/mobile/src/lib/mobile-attachments.ts+++ b/apps/mobile/src/lib/mobile-attachments.ts@@ -1,5 +1,12 @@import type { createEdgeEverClient } from "@edgeever/client";-import { docToMarkdown, getResourceIdFromUrl, type TiptapDoc } from "@edgeever/shared";+import {+ docToMarkdown,+ FILE_ATTACHMENT_NODE_TYPE,+ getResourceIdFromUrl,+ PDF_ATTACHMENT_NODE_TYPE,+ resourceUrlsReferToSameAttachment,+ type TiptapDoc,+} from "@edgeever/shared";export type MobileResourceTarget = {filename: string;@@ -161,6 +168,17 @@ const updateResourceDoc = (if (action.type === "delete") return null;return { ...node, text: `${action.labelPrefix}${action.filename}` };}+ if (+ target.kind === "attachment"+ && (node.type === FILE_ATTACHMENT_NODE_TYPE || node.type === PDF_ATTACHMENT_NODE_TYPE)+ ) {+ const attrs = node.attrs && typeof node.attrs === "object" ? node.attrs as Record<string, unknown> : {};+ const url = typeof attrs.url === "string" ? attrs.url : "";+ if (getResourceIdFromUrl(url) === target.resourceId || resourceUrlsReferToSameAttachment(url, target.href)) {+ if (action.type === "delete") return null;+ return { ...node, attrs: { ...attrs, filename: action.filename, label: `${action.labelPrefix}${action.filename}` } };+ }+ }const next = Object.fromEntries(Object.entries(node).map(([key, child]) => [key, key === "content" ? visit(child) : child]));if (target.kind === "attachment" && action.type === "delete" && next.type === "paragraph" && Array.isArray(next.content)) {diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex 8c9dbb59..8a7dacbf 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -2,7 +2,6 @@ import { useRef, useState, useEffect, useCallback, useMemo, lazy, Suspense, typeimport { useQuery, useQueryClient, useMutation } from "@tanstack/react-query";import { useEditor, EditorContent, type Editor } from "@tiptap/react";import { BubbleMenu } from "@tiptap/react/menus";-import type { Mark } from "@tiptap/pm/model";import StarterKit from "@tiptap/starter-kit";import { TaskItem, TaskList } from "@tiptap/extension-list";import Placeholder from "@tiptap/extension-placeholder";@@ -205,11 +204,12 @@ import {getRichTextAiSelectionReplacement,normalizeAiSelectionReplacement,} from "@/lib/ai-selection-replacement";-import { getAttachmentFilenameFromLabel, getAttachmentResourceId } from "@/lib/attachment-links";+import { getAttachmentResourceId } from "@/lib/attachment-links";import {getAttachmentHoverTarget,getAttachmentLinkFromEventTarget,isInsideAttachmentHoverRegion,+ resolveAttachmentMenuFilename,} from "./editor/attachment-resource-menu";import {IMAGE_MENU_HIDE_EVENT,@@ -250,6 +250,7 @@ import {type ResourceDialogState,type ResourceMenuTarget,} from "./editor/useEditorResourceActions";+import { removeAttachmentAt, renameAttachmentAt } from "./editor/attachment-editor-range";const SUPPORTED_PASTE_IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"]);const MOBILE_EDITOR_QUERY = "(max-width: 639px)";@@ -316,27 +317,6 @@ const getNoteLinkHintPosition = (link: HTMLAnchorElement): NoteLinkHintPosition};};-const findAttachmentLinkRange = (- editor: Editor,- href: string-): { from: number; to: number; marks: readonly Mark[] } | null => {- let from: number | null = null;- let to: number | null = null;- let marks: readonly Mark[] = [];-- editor.state.doc.descendants((node, pos) => {- if (!node.isText || !node.text) return;- const linkMark = node.marks.find((mark) => mark.type.name === "link" && mark.attrs.href === href);- if (!linkMark) return;- from = from === null ? pos : Math.min(from, pos);- to = to === null ? pos + node.nodeSize : Math.max(to, pos + node.nodeSize);- marks = node.marks;- });-- if (from === null || to === null) return null;- return { from: from as number, to: to as number, marks };-};-type MobilePlainTextElement = HTMLTextAreaElement | HTMLDivElement;const isEditorReady = (editor: Editor | null | undefined): editor is Editor =>@@ -1617,7 +1597,7 @@ const RichEditorPane = ({kind: "attachment",element: hover.toolbar ?? undefined,url: href,- filename: getAttachmentFilenameFromLabel(hover.link.textContent || "") || getAttachmentResourceId(href) || "attachment",+ filename: resolveAttachmentMenuFilename(hover, href),resourceId: getAttachmentResourceId(href),position: hover.toolbar ? { left: 0, top: 0, placement: "above" } : getNoteLinkHintPosition(hover.link),});@@ -3173,38 +3153,13 @@ const RichEditorPane = ({const replaceAttachmentLabel = useCallback((target: AttachmentMenuTarget, filename: string) => {const activeEditor = editorRef.current;if (!isEditorReady(activeEditor)) return;- const range = findAttachmentLinkRange(activeEditor, target.url);- if (!range) return;- activeEditor.view.dispatch(- activeEditor.state.tr.replaceWith(- range.from,- range.to,- activeEditor.schema.text(t("editor.attachmentLabel", { filename }), [...range.marks])- )- );+ renameAttachmentAt(activeEditor, target, filename, t("editor.attachmentLabel", { filename }));}, [t]);const removeAttachmentLink = useCallback((target: AttachmentMenuTarget) => {const activeEditor = editorRef.current;if (!isEditorReady(activeEditor)) return;- const range = findAttachmentLinkRange(activeEditor, target.url);- if (!range) return;-- const resolved = activeEditor.state.doc.resolve(range.from);- let deleteFrom = range.from;- let deleteTo = 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) {- deleteFrom = nodeFrom;- deleteTo = nodeFrom + node.nodeSize;- }- break;- }-- activeEditor.view.dispatch(activeEditor.state.tr.delete(deleteFrom, deleteTo));+ removeAttachmentAt(activeEditor, target);}, []);const getResourceActionFailure = useCallback((target: ResourceMenuTarget) =>diff --git a/apps/web/src/components/editor/FileAttachment.tsx b/apps/web/src/components/editor/FileAttachment.tsxindex a2ffbe43..1e638309 100644--- a/apps/web/src/components/editor/FileAttachment.tsx+++ b/apps/web/src/components/editor/FileAttachment.tsx@@ -47,7 +47,13 @@ const FileAttachmentNodeView = ({ node, updateAttributes }: NodeViewProps) => {);return (- <NodeViewWrapper as="span" className="edgeever-file-attachment-node" contentEditable={false}>+ <NodeViewWrapper+ as="span"+ className="edgeever-file-attachment-node"+ data-file-name={filename || label}+ data-file-url={url}+ contentEditable={false}+ ><span className={cn("edgeever-file-viewer flex min-h-12 flex-col overflow-hidden rounded-xl border border-slate-200 bg-card shadow-sm", COMPACT_ATTACHMENT_WIDTH_CLASS)}><span data-edgeever-resource-toolbar className="flex min-h-12 items-center gap-2 px-3">{isVideo ? (diff --git a/apps/web/src/components/editor/PdfAttachment.tsx b/apps/web/src/components/editor/PdfAttachment.tsxindex 302110ec..23001fb0 100644--- a/apps/web/src/components/editor/PdfAttachment.tsx+++ b/apps/web/src/components/editor/PdfAttachment.tsx@@ -1,14 +1,27 @@-import { PdfAttachment as BasePdfAttachment, resolvePdfDisplayMode } from "@edgeever/shared";+import {+ getAttachmentFilenameFromLabel,+ PdfAttachment as BasePdfAttachment,+ resolvePdfDisplayMode,+} from "@edgeever/shared";import { NodeViewWrapper, ReactNodeViewRenderer, type NodeViewProps } from "@tiptap/react";import { PdfViewer } from "@/components/pdf/PdfViewer";const PdfAttachmentNodeView = ({ node, updateAttributes }: NodeViewProps) => {const url = typeof node.attrs.url === "string" ? node.attrs.url : "";const label = typeof node.attrs.label === "string" ? node.attrs.label : "PDF";+ const filename = typeof node.attrs.filename === "string" && node.attrs.filename+ ? node.attrs.filename+ : getAttachmentFilenameFromLabel(label);const displayMode = resolvePdfDisplayMode(node.attrs.displayMode);return (- <NodeViewWrapper as="span" className="edgeever-pdf-attachment-node" contentEditable={false}>+ <NodeViewWrapper+ as="span"+ className="edgeever-pdf-attachment-node"+ data-file-name={filename || label}+ data-file-url={url}+ contentEditable={false}+ ><PdfViewerurl={url}label={label}diff --git a/apps/web/src/components/editor/attachment-editor-range.test.mjs b/apps/web/src/components/editor/attachment-editor-range.test.mjsnew file mode 100644index 00000000..d434b6ae--- /dev/null+++ b/apps/web/src/components/editor/attachment-editor-range.test.mjs@@ -0,0 +1,112 @@+import { describe, expect, test } from "bun:test";+import { Editor } from "@tiptap/core";+import StarterKit from "@tiptap/starter-kit";+import { FileAttachment, PdfAttachment } from "@edgeever/shared";+import { findAttachmentRange, removeAttachmentAt, renameAttachmentAt } from "./attachment-editor-range.ts";++const videoUrl = "edgeever-resource://resource/res_video";+const videoApiUrl = "/api/v1/resources/res_video/blob";+const pdfUrl = "/api/v1/resources/res_pdf/blob";+const otherUrl = "/api/v1/resources/res_other/blob";++const fileNode = (url, filename, mimeType) => ({+ type: "edgeeverFileAttachment",+ attrs: {+ url,+ label: `附件:${filename}`,+ filename,+ mimeType,+ byteSize: 4096,+ displayMode: "inline",+ },+});++const pdfNode = (url, filename) => ({+ type: "edgeeverPdfAttachment",+ attrs: {+ url,+ label: `附件:${filename}`,+ filename,+ mimeType: "application/pdf",+ byteSize: 8192,+ displayMode: "compact",+ },+});++const paragraph = (...content) => ({ type: "paragraph", content });++const makeEditor = (content) => new Editor({+ extensions: [StarterKit, FileAttachment, PdfAttachment],+ content: { type: "doc", content },+});++describe("attachment editor range", () => {+ test("removes a video file-attachment node whose hover URL is the API blob path", () => {+ const editor = makeEditor([+ paragraph(fileNode(videoUrl, "clip.mp4", "video/mp4")),+ paragraph({ type: "text", text: "keep" }),+ ]);+ const target = { url: videoApiUrl, resourceId: "res_video" };++ expect(findAttachmentRange(editor, target)?.kind).toBe("node");+ expect(removeAttachmentAt(editor, target)).toBe(true);+ expect(editor.getJSON().content).toEqual([+ paragraph({ type: "text", text: "keep" }),+ ]);+ editor.destroy();+ });++ test("removes a standalone PDF node and leaves a valid empty document", () => {+ const editor = makeEditor([paragraph(pdfNode(pdfUrl, "report.pdf"))]);+ expect(removeAttachmentAt(editor, { url: pdfUrl, resourceId: "res_pdf" })).toBe(true);+ expect(editor.getJSON().content).toEqual([{ type: "paragraph" }]);+ editor.destroy();+ });++ test("still removes a legacy attachment link and leaves surrounding copy", () => {+ const editor = makeEditor([+ paragraph(+ { type: "text", text: "before " },+ {+ type: "text",+ text: "附件:notes.zip",+ marks: [{ type: "link", attrs: { href: otherUrl } }],+ },+ { type: "text", text: " after" },+ ),+ ]);+ expect(removeAttachmentAt(editor, { url: otherUrl, resourceId: "res_other" })).toBe(true);+ expect(editor.getJSON().content[0].content.map((node) => node.text).join("")).toBe("before after");+ editor.destroy();+ });++ test("renames file-attachment attrs instead of replacing the node with text", () => {+ const editor = makeEditor([paragraph(fileNode(videoApiUrl, "clip.mp4", "video/mp4"))]);+ expect(renameAttachmentAt(+ editor,+ { url: videoUrl, resourceId: "res_video" },+ "final.mp4",+ "附件:final.mp4",+ )).toBe(true);+ expect(editor.getJSON().content[0].content[0]).toMatchObject({+ type: "edgeeverFileAttachment",+ attrs: {+ url: videoApiUrl,+ filename: "final.mp4",+ label: "附件:final.mp4",+ mimeType: "video/mp4",+ },+ });+ editor.destroy();+ });++ test("does not touch an unrelated attachment", () => {+ const editor = makeEditor([+ paragraph(fileNode(videoUrl, "clip.mp4", "video/mp4")),+ paragraph(pdfNode(pdfUrl, "report.pdf")),+ ]);+ expect(removeAttachmentAt(editor, { url: otherUrl, resourceId: "res_other" })).toBe(false);+ expect(editor.getJSON().content).toHaveLength(2);+ editor.destroy();+ });+});diff --git a/apps/web/src/components/editor/attachment-editor-range.ts b/apps/web/src/components/editor/attachment-editor-range.tsnew file mode 100644index 00000000..d6b7b31a--- /dev/null+++ b/apps/web/src/components/editor/attachment-editor-range.ts@@ -0,0 +1,126 @@+import type { Editor } from "@tiptap/core";+import type { Mark, Node as PMNode } from "@tiptap/pm/model";+import {+ FILE_ATTACHMENT_NODE_TYPE,+ PDF_ATTACHMENT_NODE_TYPE,+ getResourceIdFromUrl,+ resourceUrlsReferToSameAttachment,+} from "@edgeever/shared";++const ATTACHMENT_NODE_TYPES = new Set<string>([FILE_ATTACHMENT_NODE_TYPE, PDF_ATTACHMENT_NODE_TYPE]);++export type AttachmentRangeTarget = {+ url: string;+ resourceId?: string | null;+};++export type AttachmentLinkRange = {+ kind: "link";+ from: number;+ to: number;+ marks: readonly Mark[];+};++export type AttachmentNodeRange = {+ kind: "node";+ from: number;+ to: number;+ node: PMNode;+};++export type AttachmentRange = AttachmentLinkRange | AttachmentNodeRange;++export const attachmentCandidateMatches = (candidateUrl: string, target: AttachmentRangeTarget) => {+ if (resourceUrlsReferToSameAttachment(candidateUrl, target.url)) return true;+ return Boolean(target.resourceId && getResourceIdFromUrl(candidateUrl) === target.resourceId);+};++const expandStandaloneParagraphRange = (editor: Editor, from: number, to: number) => {+ const resolved = editor.state.doc.resolve(from);+ 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 (from === nodeFrom + 1 && to === nodeFrom + node.nodeSize - 1) {+ return { from: nodeFrom, to: nodeFrom + node.nodeSize };+ }+ break;+ }+ return { from, to };+};++export const findAttachmentRange = (+ editor: Editor,+ target: AttachmentRangeTarget,+): AttachmentRange | null => {+ let linkFrom: number | null = null;+ let linkTo: number | null = null;+ let marks: readonly Mark[] = [];+ let nodeRange: AttachmentNodeRange | null = null;++ editor.state.doc.descendants((node, pos) => {+ if (nodeRange) return false;+ if (ATTACHMENT_NODE_TYPES.has(node.type.name)) {+ const url = typeof node.attrs.url === "string" ? node.attrs.url : "";+ if (!attachmentCandidateMatches(url, target)) return;+ nodeRange = { kind: "node", from: pos, to: pos + node.nodeSize, node };+ return false;+ }+ if (!node.isText || !node.text) return;+ const linkMark = node.marks.find((mark) =>+ mark.type.name === "link"+ && typeof mark.attrs.href === "string"+ && attachmentCandidateMatches(mark.attrs.href, target)+ );+ if (!linkMark) return;+ linkFrom = linkFrom === null ? pos : Math.min(linkFrom, pos);+ linkTo = linkTo === null ? pos + node.nodeSize : Math.max(linkTo, pos + node.nodeSize);+ marks = node.marks;+ });++ if (nodeRange) return nodeRange;+ if (linkFrom === null || linkTo === null) return null;+ return { kind: "link", from: linkFrom, to: linkTo, marks };+};++const dispatchDeleteRange = (editor: Editor, from: number, to: number) => {+ const tr = editor.state.tr.delete(from, to);+ if (tr.doc.childCount === 0 && editor.schema.nodes.paragraph) {+ tr.insert(0, editor.schema.nodes.paragraph.create());+ }+ editor.view.dispatch(tr);+};++export const removeAttachmentAt = (editor: Editor, target: AttachmentRangeTarget) => {+ const range = findAttachmentRange(editor, target);+ if (!range) return false;+ const next = expandStandaloneParagraphRange(editor, range.from, range.to);+ dispatchDeleteRange(editor, next.from, next.to);+ return true;+};++export const renameAttachmentAt = (+ editor: Editor,+ target: AttachmentRangeTarget,+ filename: string,+ label: string,+) => {+ const range = findAttachmentRange(editor, target);+ if (!range) return false;+ if (range.kind === "node") {+ editor.view.dispatch(editor.state.tr.setNodeMarkup(range.from, undefined, {+ ...range.node.attrs,+ filename,+ label,+ }));+ return true;+ }+ editor.view.dispatch(+ editor.state.tr.replaceWith(+ range.from,+ range.to,+ editor.schema.text(label, [...range.marks]),+ ),+ );+ return true;+};diff --git a/apps/web/src/components/editor/attachment-resource-menu.test.mjs b/apps/web/src/components/editor/attachment-resource-menu.test.mjsindex e52a6763..6ab177c9 100644--- a/apps/web/src/components/editor/attachment-resource-menu.test.mjs+++ b/apps/web/src/components/editor/attachment-resource-menu.test.mjs@@ -1,6 +1,9 @@import { describe, expect, test } from "bun:test";import { computePosition } from "@floating-ui/react-dom";-import { attachmentResourceMenuPosition } from "./attachment-resource-menu.ts";+import {+ attachmentResourceMenuPosition,+ resolveAttachmentMenuFilename,+} from "./attachment-resource-menu.ts";const menuSize = { width: 300, height: 42 };const viewport = { x: 0, y: 0, width: 1024, height: 768 };@@ -53,3 +56,49 @@ describe("attachment resource menu positioning", () => {}});});++describe("attachment menu filename", () => {+ const hover = ({ filename, download, text, href }) => ({+ card: filename == null ? null : {+ closest: () => ({ getAttribute: () => filename }),+ getAttribute: () => filename,+ },+ link: {+ getAttribute: (name) => name === "download" ? download ?? null : name === "href" ? href : null,+ textContent: text ?? "",+ },+ toolbar: null,+ });++ test("uses the card filename when the hover target is a video action link", () => {+ expect(resolveAttachmentMenuFilename(+ hover({+ filename: "clip.mp4",+ download: "clip.mp4",+ href: "/api/v1/resources/res_video/blob",+ }),+ "/api/v1/resources/res_video/blob",+ )).toBe("clip.mp4");+ });++ test("falls back to the download attribute when the card has no filename", () => {+ expect(resolveAttachmentMenuFilename(+ hover({+ filename: "",+ download: "walkthrough.mp4",+ href: "/api/v1/resources/res_video/blob",+ }),+ "/api/v1/resources/res_video/blob",+ )).toBe("walkthrough.mp4");+ });++ test("still reads a legacy attachment link label", () => {+ expect(resolveAttachmentMenuFilename(+ hover({+ text: "附件:notes.zip",+ href: "/api/v1/resources/res_zip/blob",+ }),+ "/api/v1/resources/res_zip/blob",+ )).toBe("notes.zip");+ });+});diff --git a/apps/web/src/components/editor/attachment-resource-menu.ts b/apps/web/src/components/editor/attachment-resource-menu.tsindex ef064653..ae1a6d34 100644--- a/apps/web/src/components/editor/attachment-resource-menu.ts+++ b/apps/web/src/components/editor/attachment-resource-menu.ts@@ -1,9 +1,12 @@import { flip, offset, shift, type ComputePositionConfig } from "@floating-ui/react-dom";+import { getAttachmentFilenameFromLabel, getResourceIdFromUrl } from "@edgeever/shared";/** File/PDF cards own in-card download and open-external controls. */export const ATTACHMENT_CARD_SELECTOR = ".edgeever-file-viewer, .edgeever-pdf-viewer";export const ATTACHMENT_TOOLBAR_SELECTOR = "[data-edgeever-resource-toolbar]";export const ATTACHMENT_ACTION_SELECTOR = ".pdf-viewer-action";+export const ATTACHMENT_FILE_NAME_ATTR = "data-file-name";+export const ATTACHMENT_FILE_URL_ATTR = "data-file-url";const ATTACHMENT_LINK_SELECTOR ='a.edgeever-attachment-link, a[href*="/api/v1/resources/"], a[href^="edgeever-resource://"]';@@ -56,6 +59,19 @@ export const getAttachmentHoverTarget = (target: EventTarget | null): Attachmentexport const getAttachmentLinkFromEventTarget = (target: EventTarget | null) =>getAttachmentHoverTarget(target)?.link ?? null;+export const resolveAttachmentMenuFilename = (hover: AttachmentHoverTarget, href: string) => {+ const namedHost = hover.card?.closest(`[${ATTACHMENT_FILE_NAME_ATTR}]`) ?? hover.card;+ const named = namedHost?.getAttribute(ATTACHMENT_FILE_NAME_ATTR)?.trim();+ if (named) return getAttachmentFilenameFromLabel(named) || named;++ const download = hover.link.getAttribute("download")?.trim();+ if (download) return getAttachmentFilenameFromLabel(download) || download;++ return getAttachmentFilenameFromLabel(hover.link.textContent || "")+ || getResourceIdFromUrl(href)+ || "attachment";+};+export const isInsideAttachmentHoverRegion = (origin: AttachmentHoverTarget,related: EventTarget | null,diff --git a/packages/shared/src/resource-links.test.mjs b/packages/shared/src/resource-links.test.mjsnew file mode 100644index 00000000..b9de80ef--- /dev/null+++ b/packages/shared/src/resource-links.test.mjs@@ -0,0 +1,33 @@+import { describe, expect, test } from "bun:test";+import {+ getAttachmentFilenameFromLabel,+ getResourceIdFromUrl,+ resourceUrlsReferToSameAttachment,+} from "./resource-links.ts";++describe("resource link identity", () => {+ test("extracts resource ids from API and desktop URLs", () => {+ expect(getResourceIdFromUrl("/api/v1/resources/res_123/blob")).toBe("res_123");+ expect(getResourceIdFromUrl("https://notes.example.com/api/v1/resources/res%20one/blob?download=1")).toBe("res one");+ expect(getResourceIdFromUrl("edgeever-resource://resource/res_456")).toBe("res_456");+ });++ test("treats API and desktop URLs for the same resource as one attachment", () => {+ expect(resourceUrlsReferToSameAttachment(+ "edgeever-resource://resource/res_video",+ "/api/v1/resources/res_video/blob",+ )).toBe(true);+ expect(resourceUrlsReferToSameAttachment(+ "/api/v1/resources/res_video/blob",+ "/api/v1/resources/res_other/blob",+ )).toBe(false);+ expect(resourceUrlsReferToSameAttachment("edgeever-staged://stage_1", "edgeever-staged://stage_1")).toBe(true);+ expect(resourceUrlsReferToSameAttachment("edgeever-staged://stage_1", "edgeever-staged://stage_2")).toBe(false);+ expect(resourceUrlsReferToSameAttachment("", "")).toBe(false);+ });++ test("extracts filenames from localized attachment labels", () => {+ expect(getAttachmentFilenameFromLabel("附件:clip.mp4")).toBe("clip.mp4");+ expect(getAttachmentFilenameFromLabel("Attachment: report.pdf")).toBe("report.pdf");+ });+});diff --git a/packages/shared/src/resource-links.ts b/packages/shared/src/resource-links.tsindex 2558ecd5..207f2577 100644--- a/packages/shared/src/resource-links.ts+++ b/packages/shared/src/resource-links.ts@@ -22,3 +22,12 @@ export const getResourceIdFromUrl = (href: string): string | null => {export const getAttachmentFilenameFromLabel = (label: string) =>label.replace(/^\s*(?:附件[::]|Attachment:)\s*/i, "").trim();++/** Match API, desktop protocol, and identical staged URLs for the same stored file. */+export const resourceUrlsReferToSameAttachment = (left: string, right: string) => {+ if (!left || !right) return false;+ if (left === right) return true;+ const leftId = getResourceIdFromUrl(left);+ const rightId = getResourceIdFromUrl(right);+ return Boolean(leftId && rightId && leftId === rightId);+};