Skip to content

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

Add attachment hover actions

tianma-ifa31a8e263e0c
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 09756b8f..74d36396 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -27,6 +27,7 @@ import {
UserUpdateSchema,
RestoreJsonMemosSchema,
RestoreJsonNotebooksSchema,
+ ResourceUpdateSchema,
type ApiToken,
type CreatedApiToken,
type MemoDetail,
@@ -2306,6 +2307,77 @@ app.get("/api/v1/resources/:id/blob", async (c) => {
return new Response(object.body, { headers });
});
+app.patch("/api/v1/resources/:id", zValidator("json", ResourceUpdateSchema), async (c) => {
+ const denied = requireScopes(c, "write:resources");
+
+ if (denied) {
+ return denied;
+ }
+
+ const resourceId = c.req.param("id");
+ const resource = await getResourceRow(c.env.storage.db, getWorkspaceId(c), resourceId);
+
+ if (!resource) {
+ return notFound(c, "Resource not found");
+ }
+
+ const filename = normalizeFilename(c.req.valid("json").filename);
+ if (!filename) {
+ return badRequest(c, "Resource filename is required.");
+ }
+
+ const now = isoNow();
+ const actor = getAuditActor(c);
+ await c.env.storage.db.batch([
+ c.env.storage.db.prepare(
+ `UPDATE resources SET filename = ?, updated_at = ? WHERE id = ?`
+ ).bind(filename, now, resourceId),
+ auditStatement(c.env.storage.db, actor.actorType, actor.actorId, "resource.rename", "resource", resourceId, {
+ memoId: resource.memo_id,
+ previousFilename: resource.filename,
+ filename,
+ }),
+ ]);
+
+ const updated = await getResourceRow(c.env.storage.db, getWorkspaceId(c), resourceId);
+ if (!updated) {
+ return notFound(c, "Resource not found");
+ }
+
+ return c.json({ resource: mapResource(updated) });
+});
+
+app.delete("/api/v1/resources/:id", async (c) => {
+ const denied = requireScopes(c, "write:resources");
+
+ if (denied) {
+ return denied;
+ }
+
+ const resourceId = c.req.param("id");
+ const resource = await getResourceRow(c.env.storage.db, getWorkspaceId(c), resourceId);
+
+ if (!resource) {
+ return notFound(c, "Resource not found");
+ }
+
+ const now = isoNow();
+ const actor = getAuditActor(c);
+ await c.env.storage.db.batch([
+ c.env.storage.db.prepare(
+ `UPDATE resources SET is_deleted = 1, deleted_at = ?, updated_at = ? WHERE id = ?`
+ ).bind(now, now, resourceId),
+ auditStatement(c.env.storage.db, actor.actorType, actor.actorId, "resource.delete", "resource", resourceId, {
+ memoId: resource.memo_id,
+ filename: resource.filename,
+ byteSize: resource.byte_size,
+ }),
+ ]);
+ await c.env.storage.resources.delete(resource.object_key);
+
+ return c.json({ ok: true });
+});
+
app.post("/api/v1/demo/reset", async (c) => {
if (!isDemoMode(c.env) && !isLocalDemoSeedEnabled(c.env)) {
return c.json(
diff --git a/apps/desktop/src/main/index.mjs b/apps/desktop/src/main/index.mjs
index 1aa13d33..9aae9d2d 100644
--- a/apps/desktop/src/main/index.mjs
+++ b/apps/desktop/src/main/index.mjs
@@ -619,7 +619,15 @@ app.whenReady().then(async () => {
ipcMain.handle("desktop:sidecar-request", async (_event, method, params) => {
if (!sidecar) throw new Error("EdgeEver sidecar is unavailable");
- return sidecar.request(method, params);
+ const result = await sidecar.request(method, params);
+ if (method === "resource.delete" && isSafeResourceId(params?.resourceId)) {
+ const directory = resourceCacheDirectory();
+ await Promise.all([
+ unlink(join(directory, `${params.resourceId}.bin`)).catch(() => {}),
+ unlink(join(directory, `${params.resourceId}.json`)).catch(() => {}),
+ ]);
+ }
+ return result;
});
ipcMain.handle("desktop:sidecar-status", () => ({ available: Boolean(sidecar), path: sidecarPath, scope: sidecarScopeKey }));
ipcMain.handle("desktop:set-account-scope", async (_event, accountId) => {
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index b005b2b7..f1b91969 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -4,6 +4,7 @@ import { useQuery, useQueryClient, useMutation } from "@tanstack/react-query";
import { NodeViewWrapper, ReactNodeViewRenderer, useEditor, EditorContent, type Editor, type NodeViewProps } from "@tiptap/react";
import { Plugin, PluginKey } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
+import type { Mark } from "@tiptap/pm/model";
import StarterKit from "@tiptap/starter-kit";
import Image from "@tiptap/extension-image";
import { mergeAttributes } from "@tiptap/core";
@@ -64,6 +65,14 @@ import {
} from "@/components/ui/dropdown-menu";
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "@/components/ui/select";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
import { EditorToolbar } from "./EditorToolbar";
import { EditorOutline } from "./EditorOutline";
import { WeChatIcon } from "./WeChatIcon";
@@ -122,6 +131,7 @@ import { processFilesSequentially } from "@/lib/file-batch";
import { MEMO_ID_REMAPPED_EVENT } from "@/lib/sync-events";
import { useStandaloneMobileEditor } from "@/hooks/useStandaloneMobileEditor";
import { statusSettleMotion } from "@/lib/motion";
+import { getAttachmentFilenameFromLabel, getAttachmentResourceId } from "@/lib/attachment-links";
const SUPPORTED_PASTE_IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"]);
const MOBILE_EDITOR_QUERY = "(max-width: 639px)";
@@ -156,6 +166,25 @@ type NoteLinkHintPosition = {
placement: "above" | "below";
};
+type AttachmentMenuTarget = {
+ href: string;
+ filename: string;
+ resourceId: string | null;
+ position: NoteLinkHintPosition;
+};
+
+type AttachmentDialogState = {
+ action: "rename" | "delete";
+ target: AttachmentMenuTarget;
+};
+
+const getAttachmentLinkFromEventTarget = (target: EventTarget | null) =>
+ target instanceof Element
+ ? target.closest<HTMLAnchorElement>(
+ 'a.edgeever-attachment-link, a[href*="/api/v1/resources/"], a[href^="edgeever-resource://"]'
+ )
+ : null;
+
const getNoteLinkFromEventTarget = (target: EventTarget | null) =>
target instanceof Element
? target.closest<HTMLAnchorElement>('a.edgeever-note-link, a[href^="#memo="]')
@@ -193,6 +222,90 @@ const NoteLinkInteractionHint = ({
document.body
);
+const AttachmentActionMenu = ({
+ target,
+ canMutate,
+ labels,
+ onDownload,
+ onRename,
+ onDelete,
+ onMouseEnter,
+ onMouseLeave,
+}: {
+ target: AttachmentMenuTarget;
+ canMutate: boolean;
+ labels: { download: string; rename: string; delete: string; unavailable: string };
+ onDownload: () => void;
+ onRename: () => void;
+ onDelete: () => void;
+ onMouseEnter: () => void;
+ onMouseLeave: (event: ReactMouseEvent<HTMLDivElement>) => void;
+}) => createPortal(
+ <div
+ data-edgeever-attachment-menu
+ role="toolbar"
+ aria-label={labels.download}
+ className="fixed z-[110] flex items-center gap-1 rounded-lg border border-slate-200 bg-white p-1 shadow-lg"
+ style={{
+ left: target.position.left,
+ top: target.position.top,
+ transform: target.position.placement === "above" ? "translate(-50%, -100%)" : "translateX(-50%)",
+ }}
+ onMouseEnter={onMouseEnter}
+ onMouseLeave={onMouseLeave}
+ >
+ <Button type="button" size="sm" variant="ghost" title={labels.download} onClick={onDownload}>
+ <FileDown className="h-3.5 w-3.5" />
+ {labels.download}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ title={canMutate ? labels.rename : labels.unavailable}
+ disabled={!canMutate}
+ onClick={onRename}
+ >
+ <Pencil className="h-3.5 w-3.5" />
+ {labels.rename}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ className="text-slate-600 hover:bg-rose-50 hover:text-rose-600"
+ title={canMutate ? labels.delete : labels.unavailable}
+ disabled={!canMutate}
+ onClick={onDelete}
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ {labels.delete}
+ </Button>
+ </div>,
+ document.body
+);
+
+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 NoteSearchMatch = {
from: number;
to: number;
@@ -707,6 +820,11 @@ const RichEditorPane = ({
const [noteLinkPickerOpen, setNoteLinkPickerOpen] = useState(false);
const [noteLinkQuery, setNoteLinkQuery] = useState("");
const [noteLinkHintPosition, setNoteLinkHintPosition] = useState<NoteLinkHintPosition | null>(null);
+ const [attachmentMenuTarget, setAttachmentMenuTarget] = useState<AttachmentMenuTarget | null>(null);
+ const [attachmentDialog, setAttachmentDialog] = useState<AttachmentDialogState | null>(null);
+ const [attachmentFilename, setAttachmentFilename] = useState("");
+ const [attachmentActionPending, setAttachmentActionPending] = useState(false);
+ const [attachmentActionError, setAttachmentActionError] = useState<string | null>(null);
const [isMobileViewport, setIsMobileViewport] = useState(() =>
typeof window === "undefined" ? false : window.matchMedia(MOBILE_EDITOR_QUERY).matches
);
@@ -785,6 +903,7 @@ const RichEditorPane = ({
const hasUnsavedChangesRef = useRef(false);
const editingMemoIdRef = useRef<string | null>(memo?.id ?? null);
const imageCompressionEnabledRef = useRef(imageCompressionEnabled);
+ const attachmentMenuHideTimerRef = useRef<number | null>(null);
useEffect(() => {
const handleMemoIdRemapped = (event: Event) => {
@@ -1113,6 +1232,38 @@ const RichEditorPane = ({
setNoteLinkQuery("");
}, [editor, effectiveReadOnly, memo?.id, t]);
+ const cancelAttachmentMenuHide = useCallback(() => {
+ if (attachmentMenuHideTimerRef.current !== null) {
+ window.clearTimeout(attachmentMenuHideTimerRef.current);
+ attachmentMenuHideTimerRef.current = null;
+ }
+ }, []);
+
+ const scheduleAttachmentMenuHide = useCallback(() => {
+ cancelAttachmentMenuHide();
+ attachmentMenuHideTimerRef.current = window.setTimeout(() => {
+ attachmentMenuHideTimerRef.current = null;
+ setAttachmentMenuTarget(null);
+ }, 120);
+ }, [cancelAttachmentMenuHide]);
+
+ const showAttachmentMenu = useCallback((target: EventTarget | null) => {
+ if (isMobileViewport) return false;
+ const link = getAttachmentLinkFromEventTarget(target);
+ if (!link) return false;
+
+ const href = link.getAttribute("href") || "";
+ cancelAttachmentMenuHide();
+ setNoteLinkHintPosition(null);
+ setAttachmentMenuTarget({
+ href,
+ filename: getAttachmentFilenameFromLabel(link.textContent || "") || getAttachmentResourceId(href) || "attachment",
+ resourceId: getAttachmentResourceId(href),
+ position: getNoteLinkHintPosition(link),
+ });
+ return true;
+ }, [cancelAttachmentMenuHide, isMobileViewport]);
+
const showNoteLinkHint = useCallback((target: EventTarget | null) => {
if (!editor?.isEditable || isMobileViewport) {
return;
@@ -1125,16 +1276,31 @@ const RichEditorPane = ({
}, [editor?.isEditable, isMobileViewport]);
const handleEditorMouseOver = useCallback((event: ReactMouseEvent<HTMLDivElement>) => {
+ if (showAttachmentMenu(event.target)) return;
showNoteLinkHint(event.target);
- }, [showNoteLinkHint]);
+ }, [showAttachmentMenu, showNoteLinkHint]);
const handleEditorMouseOut = useCallback((event: ReactMouseEvent<HTMLDivElement>) => {
+ const attachmentLink = getAttachmentLinkFromEventTarget(event.target);
+ if (attachmentLink) {
+ const relatedTarget = event.relatedTarget;
+ if (
+ relatedTarget instanceof Node &&
+ (attachmentLink.contains(relatedTarget) ||
+ (relatedTarget instanceof Element && relatedTarget.closest("[data-edgeever-attachment-menu]")))
+ ) {
+ return;
+ }
+ scheduleAttachmentMenuHide();
+ return;
+ }
+
const link = getNoteLinkFromEventTarget(event.target);
if (!link || (event.relatedTarget instanceof Node && link.contains(event.relatedTarget))) {
return;
}
setNoteLinkHintPosition(null);
- }, []);
+ }, [scheduleAttachmentMenuHide]);
const handleEditorClickCapture = useCallback((event: ReactMouseEvent<HTMLDivElement>) => {
if (event.button === 0 && !event.ctrlKey && !event.metaKey) {
@@ -1143,8 +1309,9 @@ const RichEditorPane = ({
}, [showNoteLinkHint]);
const handleEditorFocusCapture = useCallback((event: ReactFocusEvent<HTMLDivElement>) => {
+ if (showAttachmentMenu(event.target)) return;
showNoteLinkHint(event.target);
- }, [showNoteLinkHint]);
+ }, [showAttachmentMenu, showNoteLinkHint]);
const handleEditorBlurCapture = useCallback((event: ReactFocusEvent<HTMLDivElement>) => {
if (!getNoteLinkFromEventTarget(event.relatedTarget)) {
@@ -1166,10 +1333,29 @@ const RichEditorPane = ({
};
}, [noteLinkHintPosition]);
+ useEffect(() => {
+ if (!attachmentMenuTarget) return;
+ const hideMenu = () => setAttachmentMenuTarget(null);
+ window.addEventListener("resize", hideMenu);
+ window.addEventListener("scroll", hideMenu, true);
+ return () => {
+ window.removeEventListener("resize", hideMenu);
+ window.removeEventListener("scroll", hideMenu, true);
+ };
+ }, [attachmentMenuTarget]);
+
useEffect(() => {
setNoteLinkHintPosition(null);
+ setAttachmentMenuTarget(null);
+ setAttachmentDialog(null);
}, [memo?.id, isMarkdownMode]);
+ useEffect(() => () => {
+ if (attachmentMenuHideTimerRef.current !== null) {
+ window.clearTimeout(attachmentMenuHideTimerRef.current);
+ }
+ }, []);
+
useEffect(() => {
imageCompressionEnabledRef.current = imageCompressionEnabled;
}, [imageCompressionEnabled]);
@@ -2025,6 +2211,103 @@ const RichEditorPane = ({
},
});
+ const replaceAttachmentLabel = useCallback((target: AttachmentMenuTarget, filename: string) => {
+ const activeEditor = editorRef.current;
+ if (!isEditorReady(activeEditor)) return;
+ const range = findAttachmentLinkRange(activeEditor, target.href);
+ if (!range) return;
+ activeEditor.view.dispatch(
+ activeEditor.state.tr.replaceWith(
+ range.from,
+ range.to,
+ activeEditor.schema.text(t("editor.attachmentLabel", { filename }), [...range.marks])
+ )
+ );
+ }, [t]);
+
+ const removeAttachmentLink = useCallback((target: AttachmentMenuTarget) => {
+ const activeEditor = editorRef.current;
+ if (!isEditorReady(activeEditor)) return;
+ const range = findAttachmentLinkRange(activeEditor, target.href);
+ 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));
+ }, []);
+
+ const handleAttachmentDownload = useCallback(async (target: AttachmentMenuTarget) => {
+ setAttachmentMenuTarget(null);
+ setAttachmentActionError(null);
+ try {
+ const blob = await api.getResourceBlob(target.href);
+ const objectUrl = URL.createObjectURL(blob);
+ const anchor = document.createElement("a");
+ anchor.href = objectUrl;
+ anchor.download = target.filename || target.resourceId || "attachment";
+ anchor.click();
+ window.setTimeout(() => URL.revokeObjectURL(objectUrl), 0);
+ } catch (error) {
+ setAttachmentActionError(error instanceof Error ? error.message : t("editor.attachmentActions.failed"));
+ }
+ }, [t]);
+
+ const openAttachmentDialog = useCallback((action: AttachmentDialogState["action"], target: AttachmentMenuTarget) => {
+ setAttachmentMenuTarget(null);
+ setAttachmentActionError(null);
+ setAttachmentFilename(target.filename);
+ setAttachmentDialog({ action, target });
+ }, []);
+
+ const handleAttachmentRename = useCallback(async () => {
+ const target = attachmentDialog?.action === "rename" ? attachmentDialog.target : null;
+ const filename = attachmentFilename.trim();
+ if (!target?.resourceId || !filename || attachmentActionPending) return;
+
+ setAttachmentActionPending(true);
+ setAttachmentActionError(null);
+ try {
+ const result = await repository.renameResource(target.resourceId, filename);
+ replaceAttachmentLabel(target, result.resource.filename || filename);
+ await queryClient.invalidateQueries({ queryKey: ["resources"] });
+ setAttachmentDialog(null);
+ } catch (error) {
+ setAttachmentActionError(error instanceof Error ? error.message : t("editor.attachmentActions.failed"));
+ } finally {
+ setAttachmentActionPending(false);
+ }
+ }, [attachmentActionPending, attachmentDialog, attachmentFilename, queryClient, replaceAttachmentLabel, repository, t]);
+
+ const handleAttachmentDelete = useCallback(async () => {
+ const target = attachmentDialog?.action === "delete" ? attachmentDialog.target : null;
+ if (!target?.resourceId || attachmentActionPending) return;
+
+ setAttachmentActionPending(true);
+ setAttachmentActionError(null);
+ try {
+ await repository.deleteResource(target.resourceId);
+ removeAttachmentLink(target);
+ await queryClient.invalidateQueries({ queryKey: ["resources"] });
+ setAttachmentDialog(null);
+ } catch (error) {
+ setAttachmentActionError(error instanceof Error ? error.message : t("editor.attachmentActions.failed"));
+ } finally {
+ setAttachmentActionPending(false);
+ }
+ }, [attachmentActionPending, attachmentDialog, queryClient, removeAttachmentLink, repository, t]);
+
const clearMobileEditorTimers = useCallback(() => {
if (mobileDraftTimerRef.current !== null) {
window.clearTimeout(mobileDraftTimerRef.current);
@@ -3078,6 +3361,112 @@ const RichEditorPane = ({
/>
)}
+ {attachmentMenuTarget && (
+ <AttachmentActionMenu
+ target={attachmentMenuTarget}
+ canMutate={Boolean(
+ attachmentMenuTarget.resourceId &&
+ !attachmentMenuTarget.resourceId.startsWith("local_resource_") &&
+ editor?.isEditable &&
+ !effectiveReadOnly
+ )}
+ labels={{
+ download: t("editor.attachmentActions.download"),
+ rename: t("editor.attachmentActions.rename"),
+ delete: t("editor.attachmentActions.delete"),
+ unavailable: t("editor.attachmentActions.unavailableUntilSynced"),
+ }}
+ onDownload={() => void handleAttachmentDownload(attachmentMenuTarget)}
+ onRename={() => openAttachmentDialog("rename", attachmentMenuTarget)}
+ onDelete={() => openAttachmentDialog("delete", attachmentMenuTarget)}
+ onMouseEnter={cancelAttachmentMenuHide}
+ onMouseLeave={(event) => {
+ if (getAttachmentLinkFromEventTarget(event.relatedTarget)) {
+ cancelAttachmentMenuHide();
+ return;
+ }
+ scheduleAttachmentMenuHide();
+ }}
+ />
+ )}
+
+ <Dialog
+ open={attachmentDialog?.action === "rename"}
+ onOpenChange={(open) => {
+ if (!open && !attachmentActionPending) setAttachmentDialog(null);
+ }}
+ >
+ <DialogContent>
+ <form
+ className="contents"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void handleAttachmentRename();
+ }}
+ >
+ <DialogHeader>
+ <DialogTitle>{t("editor.attachmentActions.renameTitle")}</DialogTitle>
+ <DialogDescription>{t("editor.attachmentActions.renameDescription")}</DialogDescription>
+ </DialogHeader>
+ <label className="grid gap-2 text-sm font-medium text-slate-700">
+ {t("editor.attachmentActions.filenameLabel")}
+ <Input
+ autoFocus
+ value={attachmentFilename}
+ maxLength={160}
+ disabled={attachmentActionPending}
+ onChange={(event) => setAttachmentFilename(event.target.value)}
+ />
+ </label>
+ {attachmentActionError && (
+ <p className="text-sm text-rose-600" role="alert">{attachmentActionError}</p>
+ )}
+ <DialogFooter>
+ <Button type="button" variant="ghost" disabled={attachmentActionPending} onClick={() => setAttachmentDialog(null)}>
+ {t("common.cancel")}
+ </Button>
+ <Button type="submit" variant="solid" disabled={attachmentActionPending || !attachmentFilename.trim()}>
+ {attachmentActionPending ? t("common.saving") : t("common.save")}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog
+ open={attachmentDialog?.action === "delete"}
+ onOpenChange={(open) => {
+ if (!open && !attachmentActionPending) setAttachmentDialog(null);
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t("editor.attachmentActions.deleteTitle")}</DialogTitle>
+ <DialogDescription>{t("editor.attachmentActions.deleteDescription")}</DialogDescription>
+ </DialogHeader>
+ <p className="truncate rounded-md bg-slate-50 px-3 py-2 text-sm font-medium text-slate-700">
+ {attachmentDialog?.target.filename}
+ </p>
+ {attachmentActionError && (
+ <p className="text-sm text-rose-600" role="alert">{attachmentActionError}</p>
+ )}
+ <DialogFooter>
+ <Button type="button" variant="ghost" disabled={attachmentActionPending} onClick={() => setAttachmentDialog(null)}>
+ {t("common.cancel")}
+ </Button>
+ <Button type="button" variant="danger" disabled={attachmentActionPending} onClick={() => void handleAttachmentDelete()}>
+ {attachmentActionPending ? t("common.processing") : t("common.delete")}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ {attachmentActionError && !attachmentDialog && (
+ <div className="fixed bottom-5 left-1/2 z-[120] -translate-x-1/2 rounded-md bg-rose-600 px-3 py-2 text-sm font-medium text-white shadow-lg" role="alert">
+ {attachmentActionError}
+ </div>
+ )}
+
{false && useMobilePlainTextEditor && (
<div className="fixed left-2 right-2 top-[max(3.5rem,env(safe-area-inset-top))] z-[70] rounded-md border border-amber-200 bg-amber-50/95 p-2 text-[11px] text-slate-800 shadow-lg backdrop-blur sm:hidden">
<div className="flex items-center justify-between gap-2">
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 3c028e5c..99ed6977 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -562,6 +562,17 @@ export const api = {
listResources: () => request<ListResourcesResponse>("/api/v1/resources"),
+ renameResource: (resourceId: string, filename: string) =>
+ request<ResourceResponse>(`/api/v1/resources/${encodeURIComponent(resourceId)}`, {
+ method: "PATCH",
+ body: JSON.stringify({ filename }),
+ }),
+
+ deleteResource: (resourceId: string) =>
+ request<{ ok: true }>(`/api/v1/resources/${encodeURIComponent(resourceId)}`, {
+ method: "DELETE",
+ }),
+
getMarkdownExportPage: (offset = 0, limit = 50) =>
request<MarkdownExportPage>(`/api/v1/exports/markdown?offset=${offset}&limit=${limit}`),
diff --git a/apps/web/src/lib/attachment-links.test.mjs b/apps/web/src/lib/attachment-links.test.mjs
new file mode 100644
index 00000000..9070f614
--- /dev/null
+++ b/apps/web/src/lib/attachment-links.test.mjs
@@ -0,0 +1,23 @@
+import { describe, expect, test } from "bun:test";
+import {
+ getAttachmentFilenameFromLabel,
+ getAttachmentResourceId,
+} from "./attachment-links.ts";
+
+describe("attachment links", () => {
+ test("extracts resource ids from API and desktop URLs", () => {
+ expect(getAttachmentResourceId("/api/v1/resources/res_123/blob")).toBe("res_123");
+ expect(getAttachmentResourceId("https://notes.example.com/api/v1/resources/res%20one/blob?download=1")).toBe("res one");
+ expect(getAttachmentResourceId("edgeever-resource://resource/res_456")).toBe("res_456");
+ });
+
+ test("ignores unrelated and staged URLs", () => {
+ expect(getAttachmentResourceId("https://example.com/file.zip")).toBeNull();
+ expect(getAttachmentResourceId("edgeever-staged://stage_1")).toBeNull();
+ });
+
+ test("extracts filenames from localized attachment labels", () => {
+ expect(getAttachmentFilenameFromLabel("附件:archive.zip")).toBe("archive.zip");
+ expect(getAttachmentFilenameFromLabel("Attachment: report.pdf")).toBe("report.pdf");
+ });
+});
diff --git a/apps/web/src/lib/attachment-links.ts b/apps/web/src/lib/attachment-links.ts
new file mode 100644
index 00000000..467f8e40
--- /dev/null
+++ b/apps/web/src/lib/attachment-links.ts
@@ -0,0 +1,24 @@
+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();
diff --git a/apps/web/src/lib/desktop-repository.ts b/apps/web/src/lib/desktop-repository.ts
index f4aaae47..246e277f 100644
--- a/apps/web/src/lib/desktop-repository.ts
+++ b/apps/web/src/lib/desktop-repository.ts
@@ -162,6 +162,16 @@ export const createDesktopRepository = (): EdgeEverRepository => ({
throw error;
}
},
+ renameResource: async (resourceId, filename) => {
+ const result = await api.renameResource(resourceId, filename);
+ await request("resource.cache", { resource: result.resource });
+ return { resource: { ...result.resource, url: toDesktopResourceUrl(result.resource.url) } };
+ },
+ deleteResource: async (resourceId) => {
+ const result = await api.deleteResource(resourceId);
+ await request("resource.delete", { resourceId });
+ return result;
+ },
listTags: () => request("tag.list", {}),
renameTag: (tag, name) => request("tag.rename", { tag, name }).then((result) => {
window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed"));
diff --git a/apps/web/src/lib/local-mirror.ts b/apps/web/src/lib/local-mirror.ts
index 062d90df..ac83f029 100644
--- a/apps/web/src/lib/local-mirror.ts
+++ b/apps/web/src/lib/local-mirror.ts
@@ -363,6 +363,19 @@ export const putLocalResource = async (scope: string, resource: ResourceListItem
await localDb.resources.put({ ...resource, scope });
};
+export const renameLocalResource = async (scope: string, resourceId: string, filename: string) => {
+ const resource = await localDb.resources.get([scope, resourceId]);
+ if (!resource) return;
+ await localDb.resources.put({ ...resource, filename, updatedAt: new Date().toISOString() });
+};
+
+export const deleteLocalResource = async (scope: string, resourceId: string) => {
+ const resource = await localDb.resources.get([scope, resourceId]);
+ if (!resource) return;
+ await localDb.resources.delete([scope, resourceId]);
+ await removeCachedLocalResourceBytes(resource.url);
+};
+
export const createLocalResource = async (scope: string, memoId: string, file: File) => {
const now = new Date().toISOString();
const id = `local_resource_${crypto.randomUUID()}`;
diff --git a/apps/web/src/lib/repository.ts b/apps/web/src/lib/repository.ts
index ac752fc1..885d512f 100644
--- a/apps/web/src/lib/repository.ts
+++ b/apps/web/src/lib/repository.ts
@@ -28,6 +28,8 @@ import {
listLocalResources,
replaceLocalResources,
putLocalResource,
+ renameLocalResource,
+ deleteLocalResource,
createLocalResource,
putLocalMemo,
putLocalNotebook,
@@ -56,6 +58,8 @@ export type EdgeEverRepository = {
useTemplate(templateId: string, notebookId: string): Promise<{ memo: MemoDetail }>;
uploadMemoResource(memoId: string, file: File): Promise<{ resource: Resource }>;
listResources(): Promise<{ resources: ResourceListItem[]; summary: ResourceStorageSummary }>;
+ renameResource(resourceId: string, filename: string): Promise<{ resource: Resource }>;
+ deleteResource(resourceId: string): Promise<{ ok: true }>;
listTags(): Promise<{ tags: TagSummary[] }>;
renameTag(tag: string, name: string): Promise<{ ok: true; updated: number }>;
deleteTag(tag: string): Promise<{ ok: true; updated: number }>;
@@ -229,6 +233,22 @@ export const createWebRepository = (scope: string): EdgeEverRepository => {
await replaceLocalResources(scope, remote.resources);
return remote;
},
+ async renameResource(resourceId, filename) {
+ if (isOffline() || resourceId.startsWith("local_resource_")) {
+ throw new Error("Attachments can only be renamed after they are synced.");
+ }
+ const result = await api.renameResource(resourceId, filename);
+ await renameLocalResource(scope, resourceId, result.resource.filename || filename);
+ return result;
+ },
+ async deleteResource(resourceId) {
+ if (isOffline() || resourceId.startsWith("local_resource_")) {
+ throw new Error("Attachments can only be deleted after they are synced.");
+ }
+ const result = await api.deleteResource(resourceId);
+ await deleteLocalResource(scope, resourceId);
+ return result;
+ },
async listTags() {
const local = await listLocalTags(scope);
if (local.tags.length > 0 || isOffline()) return local;
diff --git a/crates/desktop-sidecar/src/main.rs b/crates/desktop-sidecar/src/main.rs
index c3ef0ebf..42dfd4c9 100644
--- a/crates/desktop-sidecar/src/main.rs
+++ b/crates/desktop-sidecar/src/main.rs
@@ -559,6 +559,14 @@ fn cache_resource(database: &Connection, params: &Value) -> Result<Value, String
Ok(json!({ "ok": true }))
}
+fn delete_cached_resource(database: &Connection, params: &Value) -> Result<Value, String> {
+ let resource_id = string_param(params, "resourceId")?;
+ database
+ .execute("DELETE FROM resources WHERE id = ?1", [&resource_id])
+ .map_err(|e| e.to_string())?;
+ Ok(json!({ "ok": true }))
+}
+
fn list_tags(database: &Connection) -> Result<Value, String> {
let mut statement = database.prepare(
"SELECT trim(j.value) AS name, COUNT(DISTINCT m.id) AS memo_count, MAX(m.updated_at) AS updated_at
@@ -1515,6 +1523,7 @@ fn handle(
"template.delete" => delete_template(database, &request.params),
"resource.list" => list_resources(database, &request.params),
"resource.cache" => cache_resource(database, &request.params),
+ "resource.delete" => delete_cached_resource(database, &request.params),
"tag.list" => list_tags(database),
"tag.rename" => rewrite_tag(database, &request.params, false),
"tag.delete" => rewrite_tag(database, &request.params, true),
diff --git a/docs/openapi.json b/docs/openapi.json
index 4cd62646..87c6824c 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -1263,6 +1263,53 @@
}
}
},
+ "/api/v1/resources/{id}": {
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string" }
+ }
+ ],
+ "patch": {
+ "summary": "Rename a resource",
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": { "filename": { "type": "string", "minLength": 1, "maxLength": 160 } },
+ "required": ["filename"]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Renamed resource",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": { "resource": { "$ref": "#/components/schemas/Resource" } },
+ "required": ["resource"]
+ }
+ }
+ }
+ },
+ "404": { "$ref": "#/components/responses/Error" }
+ }
+ },
+ "delete": {
+ "summary": "Delete a resource",
+ "responses": {
+ "200": { "$ref": "#/components/responses/Ok" },
+ "404": { "$ref": "#/components/responses/Error" }
+ }
+ }
+ },
"/api/v1/resources/{id}/blob": {
"parameters": [
{
diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts
index ef40003b..de0ee63b 100644
--- a/packages/client/src/index.ts
+++ b/packages/client/src/index.ts
@@ -399,6 +399,17 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {
listResources: () => request<ListResourcesResponse>("/api/v1/resources"),
+ renameResource: (resourceId: string, filename: string) =>
+ request<ResourceResponse>(`/api/v1/resources/${encodeURIComponent(resourceId)}`, {
+ method: "PATCH",
+ body: JSON.stringify({ filename }),
+ }),
+
+ deleteResource: (resourceId: string) =>
+ request<{ ok: true }>(`/api/v1/resources/${encodeURIComponent(resourceId)}`, {
+ method: "DELETE",
+ }),
+
getMarkdownExportPage: (offset = 0, limit = 50) =>
request<MarkdownExportPage>(`/api/v1/exports/markdown?offset=${offset}&limit=${limit}`),
diff --git a/packages/shared/src/desktop-rpc.ts b/packages/shared/src/desktop-rpc.ts
index 19283c30..3068cef1 100644
--- a/packages/shared/src/desktop-rpc.ts
+++ b/packages/shared/src/desktop-rpc.ts
@@ -21,6 +21,7 @@ export type DesktopRpcMethod =
| "template.delete"
| "resource.list"
| "resource.cache"
+ | "resource.delete"
| "tag.list"
| "tag.rename"
| "tag.delete"
@@ -86,6 +87,7 @@ export type DesktopRpcResponses = {
"template.delete": { ok: true };
"resource.list": { resources: ResourceListItem[]; summary: ResourceStorageSummary };
"resource.cache": { ok: true };
+ "resource.delete": { ok: true };
"tag.list": { tags: import("./types").TagSummary[] };
"tag.rename": { ok: true; updated: number };
"tag.delete": { ok: true; updated: number };
@@ -131,6 +133,7 @@ export type DesktopRpcParams = {
"template.delete": { templateId: string };
"resource.list": { limit?: number };
"resource.cache": { resource: import("./types").Resource };
+ "resource.delete": { resourceId: string };
"tag.list": Record<string, never>;
"tag.rename": { tag: string; name: string };
"tag.delete": { tag: string };
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index a7a936ce..1a9b2f61 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -589,6 +589,18 @@ export const enUS = {
switchToNotebook: "Switch to {{name}}",
attachmentLabel: "Attachment: {{filename}}",
attachmentInsertText: "Attachment: {{filename}} {{url}}",
+ attachmentActions: {
+ download: "Download",
+ rename: "Rename",
+ delete: "Delete",
+ renameTitle: "Rename attachment",
+ renameDescription: "The new filename will be synced to the attachment and the current note.",
+ filenameLabel: "Filename",
+ deleteTitle: "Delete attachment",
+ deleteDescription: "The attachment will be permanently removed from storage and this note. This cannot be undone.",
+ unavailableUntilSynced: "This action is available after the attachment has synced",
+ failed: "The attachment action failed. Try again.",
+ },
placeholder: "Start writing...",
noteBodyAria: "Note body",
markdownSourceAria: "Markdown source",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 476be80e..98e8ee1f 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -589,6 +589,18 @@ export const zhCN = {
switchToNotebook: "切换到 {{name}}",
attachmentLabel: "附件:{{filename}}",
attachmentInsertText: "附件:{{filename}} {{url}}",
+ attachmentActions: {
+ download: "下载",
+ rename: "重命名",
+ delete: "删除",
+ renameTitle: "重命名附件",
+ renameDescription: "新的文件名会同步到附件和当前笔记。",
+ filenameLabel: "文件名",
+ deleteTitle: "删除附件",
+ deleteDescription: "附件会从存储空间和当前笔记中永久删除,此操作无法撤销。",
+ unavailableUntilSynced: "附件同步完成后才能执行此操作",
+ failed: "附件操作失败,请重试。",
+ },
placeholder: "开始记录...",
noteBodyAria: "笔记正文",
markdownSourceAria: "Markdown 源码",
diff --git a/packages/shared/src/schemas.ts b/packages/shared/src/schemas.ts
index 989abf7d..cfae9ab4 100644
--- a/packages/shared/src/schemas.ts
+++ b/packages/shared/src/schemas.ts
@@ -119,6 +119,10 @@ export const TagRenameSchema = z.object({
name: z.string().trim().min(1).max(80),
});
+export const ResourceUpdateSchema = z.object({
+ filename: z.string().trim().min(1).max(160),
+});
+
export type NotebookCreateInput = z.infer<typeof NotebookCreateSchema>;
export type NotebookUpdateInput = z.infer<typeof NotebookUpdateSchema>;
export type MemoCreateInput = z.infer<typeof MemoCreateSchema>;
@@ -135,3 +139,4 @@ export type UserCreateInput = z.infer<typeof UserCreateSchema>;
export type UserUpdateInput = z.infer<typeof UserUpdateSchema>;
export type ApiTokenCreateInput = z.infer<typeof ApiTokenCreateSchema>;
export type TagRenameInput = z.infer<typeof TagRenameSchema>;
+export type ResourceUpdateInput = z.infer<typeof ResourceUpdateSchema>;