Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.
Go dockerfossgomarkdownmemomicroblognote-takingnotesopen-sourceown-your-datareactself-hostedsqlitetimeline
fix(editor): attach pasted files instead of inlining them
johnnyjoygh8701d93fc0a5
diff --git a/web/src/components/MemoEditor/Editor/extensions.ts b/web/src/components/MemoEditor/Editor/extensions.tsindex 073b4011c..a9b8da058 100644--- a/web/src/components/MemoEditor/Editor/extensions.ts+++ b/web/src/components/MemoEditor/Editor/extensions.ts@@ -55,10 +55,13 @@ const formattingKeys: KeyBinding[] = [formattingKey("Mod-Alt-3", "heading3"),];+/** The gesture that handed files to the editor: a drop lands at a document position, a paste has none. */+export type EditorFileOrigin = { source: "paste" } | { source: "drop"; position: number };+export interface EditorExtensionsOptions {placeholder: string;onChange: (markdown: string) => void;- onFiles: (files: File[], position: number) => void;+ onFiles: (files: File[], origin: EditorFileOrigin) => void;onUpdate: () => void;onSubmit: () => void;getTags: () => string[];@@ -120,17 +123,17 @@ export function buildEditorExtensions({}),placeholderCompartment.of(cmPlaceholder(placeholder)),EditorView.domEventHandlers({- paste: (event, view) => {+ paste: (event) => {const files = clipboardFiles(event);if (files.length === 0) return false;- onFiles(files, view.state.selection.main.head);+ onFiles(files, { source: "paste" });return true;},drop: (event, view) => {const files = Array.from(event.dataTransfer?.files ?? []);if (files.length === 0) return false;const position = view.posAtCoords({ x: event.clientX, y: event.clientY }) ?? view.state.selection.main.head;- onFiles(files, position);+ onFiles(files, { source: "drop", position });return true;},}),diff --git a/web/src/components/MemoEditor/Editor/index.tsx b/web/src/components/MemoEditor/Editor/index.tsxindex 5a6fa4ba7..f583f93db 100644--- a/web/src/components/MemoEditor/Editor/index.tsx+++ b/web/src/components/MemoEditor/Editor/index.tsx@@ -6,7 +6,7 @@ import { cn } from "@/lib/utils";import type { EditorController } from "../types/editorController";import { createController } from "./controller";import "./editor.css";-import { buildEditorExtensions, placeholderCompartment } from "./extensions";+import { buildEditorExtensions, type EditorFileOrigin, placeholderCompartment } from "./extensions";import { createFormattingController } from "./formatting";interface EditorProps {@@ -16,7 +16,7 @@ interface EditorProps {placeholder: string;onContentChange: (content: string) => void;onExternalContentApplied?: (content: string) => void;- onFiles: (files: File[], position: number) => void;+ onFiles: (files: File[], origin: EditorFileOrigin) => void;/** Invoked by the in-editor save shortcut (Cmd/Ctrl+Enter). */onSubmit: () => void;isFocusMode?: boolean;@@ -81,7 +81,7 @@ const Editor = forwardRef(function Editor(props: EditorProps, ref: React.ForwardonChange: (md) => {if (!applyingExternalContentRef.current) onChangeRef.current(md);},- onFiles: (files, position) => onFilesRef.current(files, position),+ onFiles: (files, origin) => onFilesRef.current(files, origin),onUpdate: () => listenersRef.current.forEach((l) => l()),onSubmit: () => onSubmitRef.current(),getTags: () => tagsRef.current,diff --git a/web/src/components/MemoEditor/README.md b/web/src/components/MemoEditor/README.mdindex 4b742400f..eec615fe4 100644--- a/web/src/components/MemoEditor/README.md+++ b/web/src/components/MemoEditor/README.md@@ -86,7 +86,7 @@ A reducer (`state/reducer.ts`) drives an **external store**, not a `useReducer`### Editor extensions-`Editor/extensions.ts` exports `buildEditorExtensions()`, which composes the CodeMirror extension set: `@codemirror/lang-markdown` (with GFM), line wrapping, a reconfigurable placeholder, the editor theme, the `#tag`/`@mention` decoration plugin, the `#tag` autocomplete, and an update listener that pushes document changes back to the reducer via `onChange`. It also binds the save shortcut: `Meta-Enter` and `Ctrl-Enter` both call `onSubmit`, bound explicitly rather than through the platform-dependent `Mod-` so either works everywhere, and ordered ahead of `defaultKeymap`'s own `Mod-Enter` (`insertBlankLine`) so saving never also edits the document. Native CodeMirror paste/drop handlers intercept file payloads before its text insertion behavior and pass them to the attachment layer; ordinary markdown text paste/drop remains CodeMirror-owned.+`Editor/extensions.ts` exports `buildEditorExtensions()`, which composes the CodeMirror extension set: `@codemirror/lang-markdown` (with GFM), line wrapping, a reconfigurable placeholder, the editor theme, the `#tag`/`@mention` decoration plugin, the `#tag` autocomplete, and an update listener that pushes document changes back to the reducer via `onChange`. It also binds the save shortcut: `Meta-Enter` and `Ctrl-Enter` both call `onSubmit`, bound explicitly rather than through the platform-dependent `Mod-` so either works everywhere, and ordered ahead of `defaultKeymap`'s own `Mod-Enter` (`insertBlankLine`) so saving never also edits the document. Native CodeMirror paste/drop handlers intercept file payloads before its text insertion behavior: pasted files join the attachment list (a paste carries no placement gesture, so it never writes into the text), while dropped images are inserted inline at the drop point and other dropped files are attached. Ordinary markdown text paste/drop remains CodeMirror-owned.The app formatting keymap sits ahead of CodeMirror's generic `defaultKeymap`: `Mod-B`/`Mod-I` toggle bold/italic, `Mod-Shift-S` toggles strikethrough, `Mod-E` toggles inline code, `Mod-Alt-C` toggles a code block, `Mod-Alt-0` restores paragraph text, `Mod-Alt-1` through `Mod-Alt-3` select heading levels, and `Mod-Shift-7` through `Mod-Shift-9` toggle ordered, bullet, and task lists. CodeMirror's Markdown keymap remains enabled separately for structural `Enter` and `Backspace` behavior.diff --git a/web/src/components/MemoEditor/hooks/useBlobUrls.ts b/web/src/components/MemoEditor/hooks/useBlobUrls.tsindex e7a1cb89d..df20260ed 100644--- a/web/src/components/MemoEditor/hooks/useBlobUrls.ts+++ b/web/src/components/MemoEditor/hooks/useBlobUrls.ts@@ -1,4 +1,4 @@-import { useEffect, useRef } from "react";+import { useCallback, useEffect, useRef } from "react";export function useBlobUrls() {const urlsRef = useRef<Set<string>>(new Set());@@ -12,11 +12,12 @@ export function useBlobUrls() {[],);- return {- createBlobUrl: (blob: Blob | File): string => {- const url = URL.createObjectURL(blob);- urlsRef.current.add(url);- return url;- },- };+ // Stable identity so callers can hold it in useCallback dependencies.+ const createBlobUrl = useCallback((blob: Blob | File): string => {+ const url = URL.createObjectURL(blob);+ urlsRef.current.add(url);+ return url;+ }, []);++ return { createBlobUrl };}diff --git a/web/src/components/MemoEditor/index.tsx b/web/src/components/MemoEditor/index.tsxindex 28301d87d..97efda2e6 100644--- a/web/src/components/MemoEditor/index.tsx+++ b/web/src/components/MemoEditor/index.tsx@@ -10,6 +10,7 @@ import { useTranslate } from "@/utils/i18n";import { convertVisibilityFromString } from "@/utils/memo";import { AudioRecorderPanel, EditorContent, EditorMetadata, FocusModeOverlay, TimestampPopover } from "./components";import { FOCUS_MODE_STYLES, FORMATTING_TOOLBAR_STORAGE_KEY } from "./constants";+import type { EditorFileOrigin } from "./Editor/extensions";import {splitInlineLocalFiles,toLocalFiles,@@ -254,17 +255,36 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({void handleStartAudioRecording();};- /** Shared by the + menu (no position) and by editor paste/drop (drop position). */- const handleInsertImages = useCallback(- (files: File[], position?: number) => {+ /**+ * Single ingest point for files the editor receives. Inline placement writes+ * images into the text (at `position`, else the caret) and attaches the rest;+ * otherwise everything joins the attachment list.+ */+ const handleFiles = useCallback(+ (files: File[], placement: { inline: false } | { inline: true; position?: number }) => {if (getState().ui.isLoading.saving) return;- const { inline, attachments } = splitInlineLocalFiles(toLocalFiles(files, { createBlobUrl, saveMediaMetadata }));+ const localFiles = toLocalFiles(files, { createBlobUrl, saveMediaMetadata });+ const { inline, attachments } = placement.inline ? splitInlineLocalFiles(localFiles) : { inline: [], attachments: localFiles };attachments.forEach((file) => dispatch(actions.addLocalFile(file)));- inlineImageUpload.insertLocalImages(inline, position);+ if (placement.inline) inlineImageUpload.insertLocalImages(inline, placement.position);},[actions, createBlobUrl, dispatch, getState, inlineImageUpload.insertLocalImages, saveMediaMetadata],);+ /** The + menu's Insert image: inline at the caret. */+ const handleInsertImages = useCallback((files: File[]) => handleFiles(files, { inline: true }), [handleFiles]);++ /**+ * A drop inlines images where they landed. A paste carries no placement+ * gesture, so it attaches like the + menu's upload; the attachment list's+ * own Insert action is how a pasted image becomes inline.+ */+ const handleEditorFiles = useCallback(+ (files: File[], origin: EditorFileOrigin) =>+ handleFiles(files, origin.source === "drop" ? { inline: true, position: origin.position } : { inline: false }),+ [handleFiles],+ );+const handleCancelAudioRecording = () => {setIsTranscribingAudio(false);audioRecorder.resetRecording();@@ -346,7 +366,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({)}{/* Editor content grows to fill available space in focus mode */}- <EditorContent ref={editorRef} placeholder={placeholder} onSubmit={handleSave} onFiles={handleInsertImages} />+ <EditorContent ref={editorRef} placeholder={placeholder} onSubmit={handleSave} onFiles={handleEditorFiles} />{isAudioRecorderOpen && (audioRecorder.isBusy || isTranscribingAudio) && (<AudioRecorderPaneldiff --git a/web/src/components/MemoEditor/types/components.ts b/web/src/components/MemoEditor/types/components.tsindex 2570a096b..6d5734ed3 100644--- a/web/src/components/MemoEditor/types/components.ts+++ b/web/src/components/MemoEditor/types/components.ts@@ -1,5 +1,6 @@import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";import type { Location, Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb";+import type { EditorFileOrigin } from "../Editor/extensions";import type { AudioRecorderStatus } from "../hooks/useAudioRecorder";import type { LocalFile } from "./attachment";@@ -47,7 +48,7 @@ export interface EditorContentProps {placeholder?: string;/** Invoked by the in-editor save shortcut (Cmd/Ctrl+Enter). */onSubmit: () => void;- onFiles: (files: File[], position: number) => void;+ onFiles: (files: File[], origin: EditorFileOrigin) => void;}/**diff --git a/web/src/components/map/LocationPicker.tsx b/web/src/components/map/LocationPicker.tsxindex c615b3994..34889f95f 100644--- a/web/src/components/map/LocationPicker.tsx+++ b/web/src/components/map/LocationPicker.tsx@@ -6,7 +6,7 @@ import { createPortal } from "react-dom";import { MapContainer, Marker, useMap, useMapEvents } from "react-leaflet";import { cn } from "@/lib/utils";import { BasemapLayer } from "./BasemapLayer";-import { defaultMarkerIcon, MinimalAttributionControl, OpenStreetMapTileLayer } from "./map-utils";+import { defaultMarkerIcon, MinimalAttributionControl } from "./map-utils";import type { MapPoint } from "./types";const toLatLng = (point: MapPoint): LatLng => new LatLng(point.lat, point.lng);@@ -223,8 +223,7 @@ const LocationPicker = ({ readonly: readOnly = false, latlng, onChange = noopOnLattributionControl={false}><MinimalAttributionControl />- {/* A read-only preview is a glance, not worth a WebGL renderer and a style download. */}- {readOnly ? <OpenStreetMapTileLayer /> : <BasemapLayer />}+ <BasemapLayer /><LocationMarker position={markerPosition} readonly={readOnly} onChange={onChange} /><MapControls position={latlng} /><MapCleanup />diff --git a/web/tests/memo-editor-extensions.test.ts b/web/tests/memo-editor-extensions.test.tsindex 1cde9004f..6517f175f 100644--- a/web/tests/memo-editor-extensions.test.ts+++ b/web/tests/memo-editor-extensions.test.ts@@ -66,7 +66,7 @@ describe("MemoEditor CodeMirror extensions", () => {view.contentDOM.dispatchEvent(event);- expect(onFiles).toHaveBeenCalledWith([file], eventType === "paste" ? 2 : 0);+ expect(onFiles).toHaveBeenCalledWith([file], eventType === "paste" ? { source: "paste" } : { source: "drop", position: 0 });expect(event.defaultPrevented).toBe(true);expect(view.state.doc.toString()).toBe("memo");});diff --git a/web/tests/memo-editor-paste-files.test.tsx b/web/tests/memo-editor-paste-files.test.tsxnew file mode 100644index 000000000..0c6304f61--- /dev/null+++ b/web/tests/memo-editor-paste-files.test.tsx@@ -0,0 +1,70 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { render, waitFor } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import MemoEditor from "@/components/MemoEditor";+import { uploadService } from "@/components/MemoEditor/services";++vi.mock("@/utils/i18n", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/utils/i18n")>()),+ useTranslate: () => (key: string) => key,+}));+vi.mock("@/hooks/useUserQueries", () => ({ useTagCounts: () => ({ data: {} }) }));+vi.mock("@/hooks/useCurrentUser", () => ({ default: () => ({ name: "users/1" }) }));+vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ userGeneralSetting: {} }) }));+vi.mock("@/contexts/InstanceContext", () => ({+ useInstance: () => ({ aiSetting: { providers: [], transcription: undefined }, fetchSetting: vi.fn().mockResolvedValue(undefined) }),+}));+vi.mock("@/contexts/NewMemoContext", () => ({ useNewMemo: () => ({ markNewMemo: vi.fn() }) }));+vi.mock("@/connect", () => ({ attachmentServiceClient: {}, memoServiceClient: {}, userServiceClient: {} }));+vi.stubGlobal("matchMedia", () => ({ matches: false, addEventListener() {}, removeEventListener() {} }));+vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+);+// jsdom has no object URLs; local files are keyed by this value, so keep it unique per file.+URL.createObjectURL = (blob) => `blob:${(blob as File).name}`;+URL.revokeObjectURL = () => {};++const paste = (target: Element, files: File[]) => {+ const event = new Event("paste", { bubbles: true, cancelable: true });+ Object.defineProperty(event, "clipboardData", {+ value: { items: files.map((file) => ({ kind: "file", getAsFile: () => file })) },+ });+ target.dispatchEvent(event);+ return event;+};++const mount = () => {+ const client = new QueryClient();+ const result = render(+ <QueryClientProvider client={client}>+ <MemoEditor cacheKey="paste-test" />+ </QueryClientProvider>,+ );+ const content = result.container.querySelector<HTMLElement>(".cm-content");+ expect(content).not.toBeNull();+ return { ...result, content: content! };+};++describe("MemoEditor paste", () => {+ it("attaches pasted files instead of writing images into the text", async () => {+ const upload = vi.spyOn(uploadService, "uploadFile");+ const { content, container } = mount();+ const pdf = new File(["%PDF"], "notes.pdf", { type: "application/pdf" });+ const image = new File(["png"], "image.png", { type: "image/png" });++ const event = paste(content, [pdf, image]);++ expect(event.defaultPrevented).toBe(true);+ await waitFor(() => expect(container.textContent).toContain(image.name));+ expect(container.textContent).toContain(pdf.name);+ // A paste has no placement gesture: the image is attached rather than+ // inlined, so no inline upload starts and the text stays untouched.+ expect(content.textContent).toBe("");+ expect(upload).not.toHaveBeenCalled();+ });+});