Skip to content

armgit / memos

Public Imported from GitHub
0

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.

feat: insert attachment images into memo content (#6172)

Johnny9a928c286861
diff --git a/web/src/components/MemoActionMenu/MemoShareImagePreview.tsx b/web/src/components/MemoActionMenu/MemoShareImagePreview.tsx
index b29acc1e8..09913345c 100644
--- a/web/src/components/MemoActionMenu/MemoShareImagePreview.tsx
+++ b/web/src/components/MemoActionMenu/MemoShareImagePreview.tsx
@@ -39,7 +39,12 @@ const MemoShareImagePreview = forwardRef<HTMLDivElement, { width: number }>(({ w
<div className="mt-4">
<div className={cn("pointer-events-none", blurred && !showBlurredContent && "blur-lg")}>
- <MemoContent content={memo.content} compact={false} contentClassName="text-[14px] leading-6.5 sm:text-[15px]" />
+ <MemoContent
+ content={memo.content}
+ attachments={memo.attachments}
+ compact={false}
+ contentClassName="text-[14px] leading-6.5 sm:text-[15px]"
+ />
</div>
</div>
diff --git a/web/src/components/MemoActionMenu/memoShareImagePreviewModel.ts b/web/src/components/MemoActionMenu/memoShareImagePreviewModel.ts
index 5d5b2c981..73391d9eb 100644
--- a/web/src/components/MemoActionMenu/memoShareImagePreviewModel.ts
+++ b/web/src/components/MemoActionMenu/memoShareImagePreviewModel.ts
@@ -2,6 +2,7 @@ import { timestampDate } from "@bufbuild/protobuf/wkt";
import { separateAttachments } from "@/components/MemoMetadata/Attachment/attachmentHelpers";
import type { Memo } from "@/types/proto/api/v1/memo_service_pb";
import type { User } from "@/types/proto/api/v1/user_service_pb";
+import { filterInlineManagedAttachments } from "@/utils/managed-attachment";
import { type AttachmentVisualItem, buildAttachmentVisualItems, countLogicalAttachmentItems } from "@/utils/media-item";
import { getMemoSharePreviewAvatarUrl } from "./memoShareImage";
@@ -41,9 +42,10 @@ export const buildMemoShareImagePreviewModel = ({
timeStyle: "short",
});
- const attachmentGroups = separateAttachments(memo.attachments);
+ const attachmentOnlyItems = filterInlineManagedAttachments(memo.content, memo.attachments);
+ const attachmentGroups = separateAttachments(attachmentOnlyItems);
const visualItems = buildAttachmentVisualItems(attachmentGroups.visual);
- const attachmentCount = countLogicalAttachmentItems(memo.attachments);
+ const attachmentCount = countLogicalAttachmentItems(attachmentOnlyItems);
const nonVisualAttachmentCount = Math.max(attachmentCount - visualItems.length, 0);
const footerBadges: MemoShareImageFooterBadge[] =
nonVisualAttachmentCount > 0 ? [{ type: "attachment-summary", count: attachmentCount }] : [];
diff --git a/web/src/components/MemoContent/MemoMarkdownRenderer.tsx b/web/src/components/MemoContent/MemoMarkdownRenderer.tsx
index 18989e70c..7159710ea 100644
--- a/web/src/components/MemoContent/MemoMarkdownRenderer.tsx
+++ b/web/src/components/MemoContent/MemoMarkdownRenderer.tsx
@@ -4,7 +4,9 @@ import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import { buildRehypePlugins, buildRemarkPlugins } from "@/components/MemoContent/pipeline";
import { isMentionElement, isTagElement, isTaskListItemElement } from "@/types/markdown";
+import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
import { lazyWithReload } from "@/utils/lazy";
+import { resolveManagedAttachmentImageSource } from "@/utils/managed-attachment";
import { CodeBlock } from "./CodeBlock";
import { MarkdownRenderContext, rootMarkdownRenderContext } from "./MarkdownRenderContext";
import { Mention } from "./Mention";
@@ -17,6 +19,7 @@ import { TrustedIframe } from "./TrustedIframe";
export interface MemoMarkdownRendererProps {
content: string;
+ attachments?: Attachment[];
resolvedMentionUsernames: Set<string>;
/** Resource name of the memo (e.g. `memos/abc123`), used to target footnote links at the detail page. */
memoName?: string;
@@ -56,6 +59,7 @@ function getMentionUsername(node: Element, children?: ReactNode): string {
export const MemoMarkdownRendererCore = ({
content,
+ attachments = [],
resolvedMentionUsernames,
memoName,
compact,
@@ -137,7 +141,7 @@ export const MemoMarkdownRendererCore = ({
},
code: ({ children, ...props }) => <InlineCode {...props}>{children}</InlineCode>,
iframe: TrustedIframe,
- img: (props) => <Image {...props} />,
+ img: ({ src, ...props }) => <Image {...props} src={resolveManagedAttachmentImageSource(src, attachments)} />,
pre: CodeBlock,
table: ({ children, ...props }) => <Table {...props}>{children}</Table>,
thead: ({ children, ...props }) => <TableHead {...props}>{children}</TableHead>,
@@ -182,6 +186,7 @@ export const MemoMarkdownRenderer = memo(
MemoMarkdownRendererComponent,
(previous, next) =>
previous.content === next.content &&
+ previous.attachments === next.attachments &&
previous.memoName === next.memoName &&
previous.compact === next.compact &&
haveEqualResolvedMentions(previous.resolvedMentionUsernames, next.resolvedMentionUsernames),
diff --git a/web/src/components/MemoContent/index.tsx b/web/src/components/MemoContent/index.tsx
index 9fa7062c9..177c73e6b 100644
--- a/web/src/components/MemoContent/index.tsx
+++ b/web/src/components/MemoContent/index.tsx
@@ -9,7 +9,7 @@ import type { MemoContentProps } from "./types";
// the renderer (e.g. footnote links navigate to the detail page instead of scrolling,
// since a collapsed card may hide the target).
const MemoContent = (props: MemoContentProps) => {
- const { className, contentClassName, content, onClick, onDoubleClick } = props;
+ const { className, contentClassName, content, attachments, onClick, onDoubleClick } = props;
const resolvedMentionUsernames = useResolvedMentionUsernames(content);
return (
@@ -36,6 +36,7 @@ const MemoContent = (props: MemoContentProps) => {
>
<MemoMarkdownRenderer
content={content}
+ attachments={attachments}
resolvedMentionUsernames={resolvedMentionUsernames}
memoName={props.memoName}
compact={Boolean(props.compact)}
diff --git a/web/src/components/MemoContent/types.ts b/web/src/components/MemoContent/types.ts
index 05ac21526..4cf408683 100644
--- a/web/src/components/MemoContent/types.ts
+++ b/web/src/components/MemoContent/types.ts
@@ -1,7 +1,10 @@
import type React from "react";
+import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
export interface MemoContentProps {
content: string;
+ /** Attachments bound to this memo, used to resolve managed image URLs in share/S3 modes. */
+ attachments?: Attachment[];
/** Resource name of the memo (e.g. `memos/abc123`). Enables footnote links to target the memo detail page. */
memoName?: string;
/** The card renders collapsed (ClampedSection), so footnote links navigate instead of scrolling. */
diff --git a/web/src/components/MemoEditor/Editor/controller.ts b/web/src/components/MemoEditor/Editor/controller.ts
index ee7f2384b..c50ec05fc 100644
--- a/web/src/components/MemoEditor/Editor/controller.ts
+++ b/web/src/components/MemoEditor/Editor/controller.ts
@@ -1,6 +1,13 @@
import { EditorSelection, type EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { EditorController, FormattingController } from "../types/editorController";
+import {
+ cancelUploadAnchor,
+ createUploadAnchor,
+ getUploadAnchorPosition,
+ removeUploadAnchorEffect,
+ setUploadAnchor,
+} from "./uploadAnchors";
const isEmptyDoc = (state: EditorState) => state.doc.toString().trim() === "";
@@ -22,14 +29,38 @@ export function createController(view: EditorView, formatting: FormattingControl
},
insertMarkdown: (markdown) => {
if (!markdown) return;
- const { from, to } = view.state.selection.main;
+ // Insert at the caret without consuming the selection: callers live outside
+ // the editor (attachment list, audio recorder), and CodeMirror keeps its
+ // selection across blur, so replacing the range would delete text the user
+ // merely had highlighted.
+ const { head } = view.state.selection.main;
const doc = view.state.doc.toString();
- const { prefix, suffix } = blockPad(doc.slice(0, from), doc.slice(to));
+ const { prefix, suffix } = blockPad(doc.slice(0, head), doc.slice(head));
const insert = prefix + markdown + suffix;
- const caret = from + insert.length;
- view.dispatch({ changes: { from, to, insert }, selection: { anchor: caret }, scrollIntoView: true });
+ view.dispatch({ changes: { from: head, insert }, selection: { anchor: head + insert.length }, scrollIntoView: true });
view.focus();
},
+ createUploadAnchor: (descriptor, position) => createUploadAnchor(view, descriptor, position),
+ updateUploadAnchor: (descriptor) => setUploadAnchor(view, descriptor),
+ resolveUploadAnchor: (id, markdown) => {
+ const position = getUploadAnchorPosition(view.state, id);
+ if (position === undefined) return;
+ if (!markdown) {
+ cancelUploadAnchor(view, id);
+ return;
+ }
+ const doc = view.state.doc.toString();
+ const { prefix, suffix } = blockPad(doc.slice(0, position), doc.slice(position));
+ const insert = prefix + markdown + suffix;
+ view.dispatch({
+ changes: { from: position, insert },
+ effects: removeUploadAnchorEffect(id),
+ selection: { anchor: position + insert.length },
+ scrollIntoView: true,
+ });
+ view.focus();
+ },
+ cancelUploadAnchor: (id) => cancelUploadAnchor(view, id),
getCursor: () => view.state.selection.main.head,
setCursor: (position: number) => {
const cursor = Math.min(Math.max(position, 0), view.state.doc.length);
diff --git a/web/src/components/MemoEditor/Editor/editor.css b/web/src/components/MemoEditor/Editor/editor.css
index de71c2ce9..27de1845b 100644
--- a/web/src/components/MemoEditor/Editor/editor.css
+++ b/web/src/components/MemoEditor/Editor/editor.css
@@ -127,3 +127,86 @@
color: inherit;
}
}
+.cm-upload-anchor {
+ position: relative;
+ display: flex;
+ min-height: 2.25rem;
+ align-items: center;
+ gap: 0.375rem;
+ margin: 0.375rem 0;
+ padding-left: 1rem;
+ font-family: inherit;
+ font-size: 0.6875rem;
+}
+
+.cm-upload-anchor-rail {
+ position: absolute;
+ inset-block: 0;
+ left: 0;
+ width: 2px;
+ border-radius: 999px;
+ background: var(--primary);
+}
+
+.cm-upload-anchor-rail::after {
+ position: absolute;
+ top: 50%;
+ left: -3px;
+ width: 8px;
+ height: 8px;
+ border: 2px solid var(--card);
+ border-radius: 999px;
+ background: var(--primary);
+ content: "";
+ transform: translateY(-50%);
+}
+
+.cm-upload-anchor-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.375rem;
+ border-radius: calc(var(--radius) - 2px);
+ background: color-mix(in oklab, var(--primary) 8%, transparent);
+ padding: 0.25rem 0.5rem;
+ color: var(--primary);
+ font-weight: 500;
+}
+
+.cm-upload-anchor[data-status="failed"] .cm-upload-anchor-badge {
+ background: color-mix(in oklab, var(--destructive) 8%, transparent);
+ color: var(--destructive);
+}
+
+.cm-upload-anchor-spinner {
+ width: 0.75rem;
+ height: 0.75rem;
+ border: 1.5px solid currentColor;
+ border-right-color: transparent;
+ border-radius: 999px;
+ animation: spin 1s linear infinite;
+}
+
+.cm-upload-anchor-actions {
+ display: inline-flex;
+ gap: 0.25rem;
+}
+
+.cm-upload-anchor-action {
+ border-radius: calc(var(--radius) - 2px);
+ padding: 0.25rem 0.5rem;
+ color: var(--muted-foreground);
+ font-weight: 500;
+}
+
+.cm-upload-anchor-action:hover,
+.cm-upload-anchor-action:focus-visible {
+ background: var(--accent);
+ color: var(--accent-foreground);
+ outline: none;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .cm-upload-anchor-spinner {
+ animation: none;
+ }
+}
diff --git a/web/src/components/MemoEditor/Editor/extensions.ts b/web/src/components/MemoEditor/Editor/extensions.ts
index 5e098dfa9..e3077d53f 100644
--- a/web/src/components/MemoEditor/Editor/extensions.ts
+++ b/web/src/components/MemoEditor/Editor/extensions.ts
@@ -9,6 +9,7 @@ import { liftListItem, sinkListItem } from "./listIndent";
import { tagAutocomplete } from "./tagAutocomplete";
import { tagMentionDecorations } from "./tagMentionDecorations";
import { memoEditorTheme } from "./theme";
+import { uploadAnchorField } from "./uploadAnchors";
// Key bindings layered below the autocomplete keymap so the completion popup's
// own Tab/Escape win while it is open. On a list item, Tab/Shift-Tab nest /
@@ -30,7 +31,7 @@ const editorKeys: KeyBinding[] = [
export interface EditorExtensionsOptions {
placeholder: string;
onChange: (markdown: string) => void;
- onFiles: (files: File[]) => void;
+ onFiles: (files: File[], position: number) => void;
onUpdate: () => void;
onSubmit: () => void;
getTags: () => string[];
@@ -88,21 +89,23 @@ export function buildEditorExtensions({
EditorView.contentAttributes.of({ autocorrect: "on" }),
placeholderCompartment.of(cmPlaceholder(placeholder)),
EditorView.domEventHandlers({
- paste: (event) => {
+ paste: (event, view) => {
const files = clipboardFiles(event);
if (files.length === 0) return false;
- onFiles(files);
+ onFiles(files, view.state.selection.main.head);
return true;
},
- drop: (event) => {
+ drop: (event, view) => {
const files = Array.from(event.dataTransfer?.files ?? []);
if (files.length === 0) return false;
- onFiles(files);
+ const position = view.posAtCoords({ x: event.clientX, y: event.clientY }) ?? view.state.selection.main.head;
+ onFiles(files, position);
return true;
},
}),
tagMentionDecorations,
headingDecorations,
+ uploadAnchorField,
// tagAutocomplete must precede the editing keymap so the completion popup's
// Enter/Tab/arrow bindings win while it is open.
tagAutocomplete(getTags),
diff --git a/web/src/components/MemoEditor/Editor/index.tsx b/web/src/components/MemoEditor/Editor/index.tsx
index 54359e964..1ce289d0b 100644
--- a/web/src/components/MemoEditor/Editor/index.tsx
+++ b/web/src/components/MemoEditor/Editor/index.tsx
@@ -14,7 +14,7 @@ interface EditorProps {
initialContent: string;
placeholder: string;
onContentChange: (content: string) => void;
- onFiles: (files: File[]) => void;
+ onFiles: (files: File[], position: number) => void;
/** Invoked by the in-editor save shortcut (Cmd/Ctrl+Enter). */
onSubmit: () => void;
isFocusMode?: boolean;
@@ -51,7 +51,7 @@ const Editor = forwardRef(function Editor(props: EditorProps, ref: React.Forward
extensions: buildEditorExtensions({
placeholder,
onChange: (md) => onChangeRef.current(md),
- onFiles: (files) => onFilesRef.current(files),
+ onFiles: (files, position) => onFilesRef.current(files, position),
onUpdate: () => listenersRef.current.forEach((l) => l()),
onSubmit: () => onSubmitRef.current(),
getTags: () => tagsRef.current,
diff --git a/web/src/components/MemoEditor/Editor/uploadAnchors.ts b/web/src/components/MemoEditor/Editor/uploadAnchors.ts
new file mode 100644
index 000000000..0a96e93c9
--- /dev/null
+++ b/web/src/components/MemoEditor/Editor/uploadAnchors.ts
@@ -0,0 +1,158 @@
+import { type EditorState, StateEffect, StateField } from "@codemirror/state";
+import { Decoration, type DecorationSet, EditorView, WidgetType } from "@codemirror/view";
+
+export type UploadAnchorStatus = "uploading" | "failed";
+
+export interface UploadAnchorDescriptor {
+ id: string;
+ status: UploadAnchorStatus;
+ completed: number;
+ total: number;
+ message: string;
+ retryLabel: string;
+ keepLabel: string;
+ onRetry?: () => void;
+ onKeepAttachments?: () => void;
+}
+
+const addUploadAnchor = StateEffect.define<{ position: number; descriptor: UploadAnchorDescriptor }>();
+const updateUploadAnchor = StateEffect.define<UploadAnchorDescriptor>();
+const removeUploadAnchor = StateEffect.define<string>();
+
+class UploadAnchorWidget extends WidgetType {
+ constructor(readonly descriptor: UploadAnchorDescriptor) {
+ super();
+ }
+
+ // Every field below is rendered by toDOM — the labels as text, the callbacks as
+ // click listeners baked into the reused element — so all of them have to take
+ // part in the comparison. Returning true for a descriptor that differs only in
+ // its callbacks would leave the previous handlers wired to the old DOM.
+ eq(other: UploadAnchorWidget): boolean {
+ const [a, b] = [this.descriptor, other.descriptor];
+ return (
+ a.id === b.id &&
+ a.status === b.status &&
+ a.completed === b.completed &&
+ a.total === b.total &&
+ a.message === b.message &&
+ a.retryLabel === b.retryLabel &&
+ a.keepLabel === b.keepLabel &&
+ a.onRetry === b.onRetry &&
+ a.onKeepAttachments === b.onKeepAttachments
+ );
+ }
+
+ toDOM(): HTMLElement {
+ const root = document.createElement("div");
+ root.className = "cm-upload-anchor";
+ root.dataset.status = this.descriptor.status;
+ root.setAttribute("role", "status");
+ root.setAttribute("aria-live", "polite");
+
+ const rail = document.createElement("span");
+ rail.className = "cm-upload-anchor-rail";
+ root.appendChild(rail);
+
+ const badge = document.createElement("span");
+ badge.className = "cm-upload-anchor-badge";
+ if (this.descriptor.status === "uploading") {
+ const spinner = document.createElement("span");
+ spinner.className = "cm-upload-anchor-spinner";
+ spinner.setAttribute("aria-hidden", "true");
+ badge.appendChild(spinner);
+ badge.append(this.descriptor.message);
+ } else {
+ badge.append(this.descriptor.message);
+ }
+ root.appendChild(badge);
+
+ if (this.descriptor.status === "failed") {
+ const actions = document.createElement("span");
+ actions.className = "cm-upload-anchor-actions";
+ if (this.descriptor.onRetry) {
+ const retry = document.createElement("button");
+ retry.type = "button";
+ retry.className = "cm-upload-anchor-action";
+ retry.textContent = this.descriptor.retryLabel;
+ retry.addEventListener("click", this.descriptor.onRetry);
+ actions.appendChild(retry);
+ }
+ if (this.descriptor.onKeepAttachments) {
+ const keep = document.createElement("button");
+ keep.type = "button";
+ keep.className = "cm-upload-anchor-action";
+ keep.textContent = this.descriptor.keepLabel;
+ keep.addEventListener("click", this.descriptor.onKeepAttachments);
+ actions.appendChild(keep);
+ }
+ root.appendChild(actions);
+ }
+
+ return root;
+ }
+
+ ignoreEvent(): boolean {
+ return true;
+ }
+}
+
+const anchorIdOf = (value: Decoration): string | undefined =>
+ value.spec.widget instanceof UploadAnchorWidget ? value.spec.widget.descriptor.id : undefined;
+
+const findAnchorPosition = (decorations: DecorationSet, id: string): number | undefined => {
+ let position: number | undefined;
+ decorations.between(0, Number.MAX_SAFE_INTEGER, (from, _to, value) => {
+ if (anchorIdOf(value) === id) {
+ position = from;
+ }
+ });
+ return position;
+};
+
+export const uploadAnchorField = StateField.define<DecorationSet>({
+ create: () => Decoration.none,
+ update: (anchors, transaction) => {
+ let next = anchors.map(transaction.changes);
+ for (const effect of transaction.effects) {
+ if (effect.is(addUploadAnchor)) {
+ const position = Math.min(Math.max(effect.value.position, 0), transaction.state.doc.length);
+ next = next.update({
+ add: [Decoration.widget({ widget: new UploadAnchorWidget(effect.value.descriptor), side: 1, block: true }).range(position)],
+ sort: true,
+ });
+ } else if (effect.is(updateUploadAnchor)) {
+ const position = findAnchorPosition(next, effect.value.id);
+ if (position === undefined) continue;
+ next = next.update({
+ filter: (_from, _to, value) => anchorIdOf(value) !== effect.value.id,
+ add: [Decoration.widget({ widget: new UploadAnchorWidget(effect.value), side: 1, block: true }).range(position)],
+ sort: true,
+ });
+ } else if (effect.is(removeUploadAnchor)) {
+ next = next.update({
+ filter: (_from, _to, value) => anchorIdOf(value) !== effect.value,
+ });
+ }
+ }
+ return next;
+ },
+ provide: (field) => EditorView.decorations.from(field),
+});
+
+export const createUploadAnchor = (view: EditorView, descriptor: UploadAnchorDescriptor, position?: number): void => {
+ view.dispatch({ effects: addUploadAnchor.of({ position: position ?? view.state.selection.main.head, descriptor }) });
+};
+
+export const setUploadAnchor = (view: EditorView, descriptor: UploadAnchorDescriptor): void => {
+ view.dispatch({ effects: updateUploadAnchor.of(descriptor) });
+};
+
+export const cancelUploadAnchor = (view: EditorView, id: string): void => {
+ view.dispatch({ effects: removeUploadAnchor.of(id) });
+};
+
+export const getUploadAnchorPosition = (state: EditorState, id: string): number | undefined =>
+ findAnchorPosition(state.field(uploadAnchorField, false) ?? Decoration.none, id);
+
+export const removeUploadAnchorEffect = (id: string): StateEffect<string> => removeUploadAnchor.of(id);
diff --git a/web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx b/web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx
index ee9145fd2..55205b107 100644
--- a/web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx
+++ b/web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx
@@ -1,5 +1,6 @@
import type { FC } from "react";
import { Button } from "@/components/ui/button";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { Location, Visibility } from "@/types/proto/api/v1/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
import { validationService } from "../services";
@@ -15,6 +16,7 @@ export const EditorToolbar: FC<EditorToolbarProps> = ({
onAudioRecorderClick,
isFormattingToolbarVisible,
onToggleFormattingToolbar,
+ onInsertImages,
}) => {
const t = useTranslate();
const { actions, dispatch } = useEditorContext();
@@ -22,10 +24,17 @@ export const EditorToolbar: FC<EditorToolbarProps> = ({
// doesn't re-render the toolbar or the heavy InsertMenu it hosts. `valid`
// flips only on empty↔non-empty / loading transitions, not per keystroke.
const valid = useEditorSelector((s) => validationService.canSave(s).valid);
+ const blockedReason = useEditorSelector((s) => validationService.canSave(s).reason);
+ const blockedReasonDetail = useEditorSelector((s) => validationService.canSave(s).detail);
const isSaving = useEditorSelector((s) => s.ui.isLoading.saving);
const isUploading = useEditorSelector((s) => s.ui.isLoading.uploading);
const location = useEditorSelector((s) => s.metadata.location);
const visibility = useEditorSelector((s) => s.metadata.visibility);
+ const blockedMessage = valid
+ ? undefined
+ : blockedReason
+ ? t(blockedReason, blockedReasonDetail ? { url: blockedReasonDetail } : undefined)
+ : t("editor.validation.cannot-save");
const handleLocationChange = (next?: Location) => {
dispatch(actions.setMetadata({ location: next }));
@@ -44,6 +53,7 @@ export const EditorToolbar: FC<EditorToolbarProps> = ({
<div className="flex flex-row justify-start items-center gap-1">
<InsertMenu
isUploading={isUploading}
+ isSaving={isSaving}
location={location}
onLocationChange={handleLocationChange}
onToggleFocusMode={handleToggleFocusMode}
@@ -51,6 +61,7 @@ export const EditorToolbar: FC<EditorToolbarProps> = ({
onAudioRecorderClick={onAudioRecorderClick}
isFormattingToolbarVisible={isFormattingToolbarVisible}
onToggleFormattingToolbar={onToggleFormattingToolbar}
+ onInsertImages={onInsertImages}
/>
<VisibilitySelector value={visibility} onChange={handleVisibilityChange} />
</div>
@@ -62,9 +73,20 @@ export const EditorToolbar: FC<EditorToolbarProps> = ({
</Button>
)}
- <Button onClick={onSave} disabled={!valid || isSaving}>
- {isSaving ? t("editor.saving") : t("editor.save")}
- </Button>
+ {!valid && !isSaving && blockedMessage ? (
+ <Tooltip>
+ <TooltipTrigger render={<span className="inline-flex" tabIndex={0} aria-label={blockedMessage} />}>
+ <Button onClick={onSave} disabled>
+ {t("editor.save")}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="top">{blockedMessage}</TooltipContent>
+ </Tooltip>
+ ) : (
+ <Button onClick={onSave} disabled={isSaving}>
+ {isSaving ? t("editor.saving") : t("editor.save")}
+ </Button>
+ )}
</div>
</div>
);
diff --git a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx
index 7320c23ed..ed6bbe995 100644
--- a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx
+++ b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx
@@ -1,6 +1,17 @@
import { uniqBy } from "lodash-es";
-import { CheckIcon, FileIcon, ImageIcon, LinkIcon, LoaderIcon, MapPinIcon, Maximize2Icon, MicIcon, PlusIcon, TypeIcon } from "lucide-react";
-import { useCallback, useEffect, useState } from "react";
+import {
+ CheckIcon,
+ ImageIcon,
+ LinkIcon,
+ LoaderIcon,
+ MapPinIcon,
+ Maximize2Icon,
+ MicIcon,
+ PaperclipIcon,
+ PlusIcon,
+ TypeIcon,
+} from "lucide-react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { LinkMemoDialog, LocationDialog } from "@/components/MemoMetadata";
import type { MapPoint } from "@/components/map/types";
import { useReverseGeocoding } from "@/components/map/useReverseGeocoding";
@@ -22,7 +33,7 @@ import type { LocalFile } from "../types/attachment";
const InsertMenu = (props: InsertMenuProps) => {
const t = useTranslate();
- const { actions, dispatch } = useEditorContext();
+ const { actions, dispatch, getState } = useEditorContext();
const relations = useEditorSelector((s) => s.metadata.relations);
const {
location: initialLocation,
@@ -35,8 +46,10 @@ const InsertMenu = (props: InsertMenuProps) => {
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
const [locationDialogOpen, setLocationDialogOpen] = useState(false);
+ const inlineImageInputRef = useRef<HTMLInputElement>(null);
const { fileInputRef, selectingFlag, handleFileInputChange, handleUploadClick } = useFileUpload((newFiles: LocalFile[]) => {
+ if (getState().ui.isLoading.saving) return;
newFiles.forEach((file) => dispatch(actions.addLocalFile(file)));
});
@@ -80,6 +93,7 @@ const InsertMenu = (props: InsertMenuProps) => {
}, [displayName, setPlaceholder]);
const isUploading = selectingFlag || isUploadingProp;
+ const insertionDisabled = isUploading || props.isSaving;
const handleOpenLinkDialog = useCallback(() => {
setLinkDialogOpen(true);
@@ -114,19 +128,30 @@ const InsertMenu = (props: InsertMenuProps) => {
setLocationDialogOpen(false);
}, [locationReset]);
- const handleMediaUploadClick = useCallback(() => {
- handleUploadClick("image/*,video/*");
- }, [handleUploadClick]);
-
- const handleFileUploadClick = useCallback(() => {
+ const handleAttachmentUploadClick = useCallback(() => {
+ if (getState().ui.isLoading.saving) return;
handleUploadClick();
- }, [handleUploadClick]);
+ }, [getState, handleUploadClick]);
+
+ const handleInlineImageUploadClick = useCallback(() => {
+ if (getState().ui.isLoading.saving) return;
+ inlineImageInputRef.current?.click();
+ }, [getState]);
+
+ const handleInlineImageInputChange = useCallback(
+ (event: React.ChangeEvent<HTMLInputElement>) => {
+ const files = Array.from(event.target.files ?? []);
+ if (files.length > 0) props.onInsertImages(files);
+ event.target.value = "";
+ },
+ [props.onInsertImages],
+ );
// Insert actions (add content).
const insertItems = [
- { key: "media", label: t("attachment-library.tabs.media"), icon: ImageIcon, onClick: handleMediaUploadClick },
+ { key: "attachment", label: t("editor.insert-menu.add-attachment"), icon: PaperclipIcon, onClick: handleAttachmentUploadClick },
+ { key: "inline-image", label: t("editor.insert-menu.insert-image"), icon: ImageIcon, onClick: handleInlineImageUploadClick },
{ key: "audio", label: t("editor.audio-recorder.trigger"), icon: MicIcon, onClick: props.onAudioRecorderClick },
- { key: "file", label: t("common.file"), icon: FileIcon, onClick: handleFileUploadClick },
{ key: "link", label: t("editor.insert-menu.link-memo"), icon: LinkIcon, onClick: handleOpenLinkDialog },
{ key: "location", label: t("editor.insert-menu.add-location"), icon: MapPinIcon, onClick: handleLocationClick },
];
@@ -134,12 +159,12 @@ const InsertMenu = (props: InsertMenuProps) => {
return (
<>
<DropdownMenu>
- <DropdownMenuTrigger render={<Button variant="secondary" size="icon" disabled={isUploading} />}>
+ <DropdownMenuTrigger render={<Button variant="secondary" size="icon" disabled={insertionDisabled} aria-label={t("common.add")} />}>
{isUploading ? <LoaderIcon className="size-4 animate-spin" /> : <PlusIcon className="size-4" />}
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
{insertItems.map((item) => (
- <DropdownMenuItem key={item.key} onClick={item.onClick}>
+ <DropdownMenuItem key={item.key} onClick={item.onClick} disabled={props.isSaving}>
<item.icon className="w-4 h-4" />
{item.label}
</DropdownMenuItem>
@@ -162,11 +187,21 @@ const InsertMenu = (props: InsertMenuProps) => {
<input
className="hidden"
ref={fileInputRef}
- disabled={isUploading}
+ disabled={insertionDisabled}
onChange={handleFileInputChange}
type="file"
multiple={true}
- accept="*"
+ accept=""
+ />
+
+ <input
+ className="hidden"
+ ref={inlineImageInputRef}
+ disabled={insertionDisabled}
+ onChange={handleInlineImageInputChange}
+ type="file"
+ multiple={true}
+ accept="image/*"
/>
<LinkMemoDialog
diff --git a/web/src/components/MemoEditor/components/EditorContent.tsx b/web/src/components/MemoEditor/components/EditorContent.tsx
index f87e71a32..5bcdac59c 100644
--- a/web/src/components/MemoEditor/components/EditorContent.tsx
+++ b/web/src/components/MemoEditor/components/EditorContent.tsx
@@ -1,9 +1,7 @@
import { forwardRef } from "react";
import Editor from "../Editor";
-import { useBlobUrls } from "../hooks";
import { useEditorContext, useEditorSelector } from "../state";
import type { EditorContentProps } from "../types";
-import type { LocalFile } from "../types/attachment";
import type { EditorController } from "../types/editorController";
// Imported eagerly (not React.lazy): the editor is the always-present compose
@@ -16,21 +14,11 @@ import type { EditorController } from "../types/editorController";
* editor serializes into state.content on every change and exposes its
* formatting capability for the focus-mode toolbar.
*/
-export const EditorContent = forwardRef<EditorController, EditorContentProps>(({ placeholder, onSubmit }, ref) => {
+export const EditorContent = forwardRef<EditorController, EditorContentProps>(({ placeholder, onSubmit, onFiles }, ref) => {
const { actions, dispatch } = useEditorContext();
- const { createBlobUrl } = useBlobUrls();
const content = useEditorSelector((s) => s.content);
const isFocusMode = useEditorSelector((s) => s.ui.isFocusMode);
- const handleFiles = (files: File[]) => {
- const localFiles: LocalFile[] = files.map((file) => ({
- file,
- previewUrl: createBlobUrl(file),
- origin: "upload",
- }));
- localFiles.forEach((localFile) => dispatch(actions.addLocalFile(localFile)));
- };
-
const handleContentChange = (content: string) => {
dispatch(actions.updateContent(content));
};
@@ -44,7 +32,7 @@ export const EditorContent = forwardRef<EditorController, EditorContentProps>(({
placeholder={placeholder || ""}
isFocusMode={isFocusMode}
onContentChange={handleContentChange}
- onFiles={handleFiles}
+ onFiles={onFiles}
onSubmit={onSubmit}
/>
</div>
diff --git a/web/src/components/MemoEditor/components/EditorMetadata.tsx b/web/src/components/MemoEditor/components/EditorMetadata.tsx
index da89d25e0..65cb43d34 100644
--- a/web/src/components/MemoEditor/components/EditorMetadata.tsx
+++ b/web/src/components/MemoEditor/components/EditorMetadata.tsx
@@ -1,14 +1,20 @@
import type { FC } from "react";
import { AttachmentListEditor, LocationDisplayEditor, RelationListEditor } from "@/components/MemoMetadata";
+import { extractManagedAttachmentUIDs } from "@/utils/managed-attachment";
import { useEditorContext, useEditorSelector } from "../state";
import type { EditorMetadataProps } from "../types";
-export const EditorMetadata: FC<EditorMetadataProps> = ({ memoName }) => {
+export const EditorMetadata: FC<EditorMetadataProps> = ({ memoName, uploadingLocalFileURLs, onInsertAttachments, onInsertLocalFiles }) => {
const { actions, dispatch } = useEditorContext();
const attachments = useEditorSelector((s) => s.metadata.attachments);
const localFiles = useEditorSelector((s) => s.localFiles);
const relations = useEditorSelector((s) => s.metadata.relations);
const location = useEditorSelector((s) => s.metadata.location);
+ const content = useEditorSelector((s) => s.content);
+ const placementActionsDisabled = useEditorSelector(
+ (s) => s.ui.isLoading.saving || s.ui.isLoading.uploading || s.ui.pendingInlineImageInsertions > 0,
+ );
+ const inlineAttachmentUIDs = extractManagedAttachmentUIDs(content);
return (
<div className="w-full flex flex-col gap-2">
@@ -18,6 +24,11 @@ export const EditorMetadata: FC<EditorMetadataProps> = ({ memoName }) => {
onAttachmentsChange={(next) => dispatch(actions.setMetadata({ attachments: next }))}
onLocalFilesChange={(next) => dispatch(actions.setLocalFiles(next))}
onRemoveLocalFile={(previewUrl) => dispatch(actions.removeLocalFile(previewUrl))}
+ inlineAttachmentUIDs={inlineAttachmentUIDs}
+ onInsertAttachments={onInsertAttachments}
+ onInsertLocalFiles={onInsertLocalFiles}
+ placementActionsDisabled={placementActionsDisabled}
+ uploadingLocalFileURLs={uploadingLocalFileURLs}
/>
<RelationListEditor
diff --git a/web/src/components/MemoEditor/hooks/index.ts b/web/src/components/MemoEditor/hooks/index.ts
index 4c203a3d9..aa76e4289 100644
--- a/web/src/components/MemoEditor/hooks/index.ts
+++ b/web/src/components/MemoEditor/hooks/index.ts
@@ -6,8 +6,9 @@ export { useAutoSave } from "./useAutoSave";
export { useBlobUrls } from "./useBlobUrls";
export { useEditorActiveState } from "./useEditorActiveState";
export { COMPACT_TOOLBAR_WIDTH, isCompactWidth, useElementWidth } from "./useElementWidth";
-export { useFileUpload } from "./useFileUpload";
+export { pairAppleLivePhotoFiles, useFileUpload } from "./useFileUpload";
export { useFocusMode } from "./useFocusMode";
+export { splitInlineLocalFiles, useInlineImageUpload } from "./useInlineImageUpload";
export { useLinkMemo } from "./useLinkMemo";
export { useLocation } from "./useLocation";
export { useMemoInit } from "./useMemoInit";
diff --git a/web/src/components/MemoEditor/hooks/useAutoSave.ts b/web/src/components/MemoEditor/hooks/useAutoSave.ts
index 6b4ef4e4a..109459a1d 100644
--- a/web/src/components/MemoEditor/hooks/useAutoSave.ts
+++ b/web/src/components/MemoEditor/hooks/useAutoSave.ts
@@ -1,35 +1,49 @@
+import { equals } from "@bufbuild/protobuf";
import { useCallback, useEffect, useRef } from "react";
-import { cacheService } from "../services";
+import { AttachmentSchema } from "@/types/proto/api/v1/attachment_service_pb";
+import { cacheService, type EditorDraft } from "../services";
import { useEditorStore } from "../state";
+const sameDraft = (left: EditorDraft, right: EditorDraft): boolean =>
+ left.content === right.content &&
+ left.attachments.length === right.attachments.length &&
+ left.attachments.every((attachment, index) => {
+ const other = right.attachments[index];
+ return other !== undefined && equals(AttachmentSchema, attachment, other);
+ });
+
/**
- * Persists the editor's content to localStorage as a draft. Subscribes to the
- * editor store directly for content rather than taking it as a prop, so the
- * component that mounts this hook does not re-render on every keystroke.
+ * Persists the editor's content and already-uploaded attachments to localStorage
+ * as a draft. Subscribes to the editor store directly rather than taking draft
+ * state as props, so the component that mounts this hook does not re-render on
+ * every keystroke.
*/
export const useAutoSave = (username: string, cacheKey: string | undefined, enabled = true) => {
const store = useEditorStore();
- const latestContentRef = useRef(store.getState().content);
- const discardedContentRef = useRef<string | undefined>(undefined);
+ const initialState = store.getState();
+ const latestDraftRef = useRef<EditorDraft>({ content: initialState.content, attachments: initialState.metadata.attachments });
+ const discardedDraftRef = useRef<EditorDraft | undefined>(undefined);
useEffect(() => {
if (!enabled) return;
const key = cacheService.key(username, cacheKey);
- const persist = (content: string) => {
- latestContentRef.current = content;
- if (discardedContentRef.current !== undefined && discardedContentRef.current !== content) {
- discardedContentRef.current = undefined;
+ const persist = (draft: EditorDraft) => {
+ latestDraftRef.current = draft;
+ if (discardedDraftRef.current !== undefined && !sameDraft(discardedDraftRef.current, draft)) {
+ discardedDraftRef.current = undefined;
}
- cacheService.save(key, content);
+ cacheService.save(key, draft.content, draft.attachments);
};
- // Persist the current content on mount/enable, then on every change.
- persist(store.getState().content);
+ // Persist the current draft on mount/enable, then on every relevant change.
+ const state = store.getState();
+ persist({ content: state.content, attachments: state.metadata.attachments });
return store.subscribe(() => {
- const content = store.getState().content;
- if (content !== latestContentRef.current) {
- persist(content);
+ const nextState = store.getState();
+ const draft = { content: nextState.content, attachments: nextState.metadata.attachments };
+ if (!sameDraft(draft, latestDraftRef.current)) {
+ persist(draft);
}
});
}, [store, username, cacheKey, enabled]);
@@ -39,11 +53,11 @@ export const useAutoSave = (username: string, cacheKey: string | undefined, enab
const key = cacheService.key(username, cacheKey);
const flushDraft = () => {
- if (discardedContentRef.current === latestContentRef.current) {
+ if (discardedDraftRef.current && sameDraft(discardedDraftRef.current, latestDraftRef.current)) {
return;
}
- cacheService.saveNow(key, latestContentRef.current);
+ cacheService.saveNow(key, latestDraftRef.current.content, latestDraftRef.current.attachments);
};
const handleVisibilityChange = () => {
if (document.visibilityState === "hidden") {
@@ -65,7 +79,7 @@ export const useAutoSave = (username: string, cacheKey: string | undefined, enab
const discardDraft = useCallback(() => {
const key = cacheService.key(username, cacheKey);
- discardedContentRef.current = latestContentRef.current;
+ discardedDraftRef.current = latestDraftRef.current;
cacheService.clear(key);
}, [username, cacheKey]);
diff --git a/web/src/components/MemoEditor/hooks/useFileUpload.ts b/web/src/components/MemoEditor/hooks/useFileUpload.ts
index 142968a97..5a03210ed 100644
--- a/web/src/components/MemoEditor/hooks/useFileUpload.ts
+++ b/web/src/components/MemoEditor/hooks/useFileUpload.ts
@@ -30,7 +30,7 @@ export const useFileUpload = (onFilesSelected: (localFiles: LocalFile[]) => void
if (fileInputRef.current) fileInputRef.current.value = "";
};
- const handleUploadClick = (accept = "*") => {
+ const handleUploadClick = (accept = "") => {
if (!fileInputRef.current) {
return;
}
@@ -47,7 +47,7 @@ export const useFileUpload = (onFilesSelected: (localFiles: LocalFile[]) => void
};
};
-const pairAppleLivePhotoFiles = (localFiles: LocalFile[]): LocalFile[] => {
+export const pairAppleLivePhotoFiles = (localFiles: LocalFile[]): LocalFile[] => {
const stemMap = new Map<string, LocalFile[]>();
for (const localFile of localFiles) {
const stem = normalizeFilenameStem(localFile.file.name);
diff --git a/web/src/components/MemoEditor/hooks/useInlineImageUpload.ts b/web/src/components/MemoEditor/hooks/useInlineImageUpload.ts
new file mode 100644
index 000000000..1de4043b3
--- /dev/null
+++ b/web/src/components/MemoEditor/hooks/useInlineImageUpload.ts
@@ -0,0 +1,235 @@
+import { uniqBy } from "lodash-es";
+import { type RefObject, useCallback, useEffect, useRef, useState } from "react";
+import { toast } from "react-hot-toast";
+import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
+import { isImage } from "@/utils/attachment";
+import { useTranslate } from "@/utils/i18n";
+import { buildManagedAttachmentMarkdown, canInlineAttachment } from "@/utils/managed-attachment";
+import { errorService, uploadService } from "../services";
+import { useEditorContext } from "../state";
+import type { LocalFile } from "../types/attachment";
+import type { EditorController } from "../types/editorController";
+
+interface UploadEntry {
+ localFile: LocalFile;
+ attachment?: Attachment;
+}
+
+interface UploadJob {
+ id: string;
+ entries: UploadEntry[];
+ representativeIndexes: number[];
+ active: boolean;
+}
+
+interface InlineLocalFileSplit {
+ /** Files that become inline Markdown images; motion groups stay contiguous. */
+ inline: LocalFile[];
+ /** Indexes into `inline` of the file each reference is written for (the still of a motion group). */
+ representativeIndexes: number[];
+ /** Everything else, which stays in the attachment list. */
+ attachments: LocalFile[];
+}
+
+/** Single source of truth for which picked files can be inlined and which file represents a motion group. */
+export const splitInlineLocalFiles = (localFiles: LocalFile[]): InlineLocalFileSplit => {
+ const inline: LocalFile[] = [];
+ const representativeIndexes: number[] = [];
+ const attachments: LocalFile[] = [];
+ const consumedGroups = new Set<string>();
+
+ for (const localFile of localFiles) {
+ const groupID = localFile.motionMedia?.groupId;
+ if (!groupID) {
+ if (isImage(localFile.file.type)) {
+ representativeIndexes.push(inline.length);
+ inline.push(localFile);
+ } else {
+ attachments.push(localFile);
+ }
+ continue;
+ }
+
+ if (consumedGroups.has(groupID)) continue;
+ consumedGroups.add(groupID);
+ const group = localFiles.filter((candidate) => candidate.motionMedia?.groupId === groupID);
+ const representative = group.find((candidate) => isImage(candidate.file.type));
+ if (!representative) {
+ attachments.push(...group);
+ continue;
+ }
+ representativeIndexes.push(inline.length + group.indexOf(representative));
+ inline.push(...group);
+ }
+
+ return { inline, representativeIndexes, attachments };
+};
+
+const createJob = (localFiles: LocalFile[]): UploadJob | undefined => {
+ const { inline, representativeIndexes } = splitInlineLocalFiles(localFiles);
+ if (inline.length === 0) return undefined;
+ return {
+ id: crypto.randomUUID(),
+ entries: inline.map((localFile) => ({ localFile })),
+ representativeIndexes,
+ active: false,
+ };
+};
+
+export const useInlineImageUpload = (editorRef: RefObject<EditorController | null>) => {
+ const t = useTranslate();
+ const { actions, dispatch, getState } = useEditorContext();
+ const jobsRef = useRef(new Map<string, UploadJob>());
+ const disposedRef = useRef(false);
+ const [uploadingLocalFileURLs, setUploadingLocalFileURLs] = useState<ReadonlySet<string>>(new Set());
+
+ /** Publishes everything derived from the live job map; call after any mutation of it. */
+ const syncJobState = useCallback(() => {
+ const jobs = Array.from(jobsRef.current.values());
+ const state = getState();
+ if (state.ui.pendingInlineImageInsertions !== jobs.length) {
+ dispatch(actions.setPendingInlineImageInsertions(jobs.length));
+ }
+ const isUploading = jobs.some((job) => job.active);
+ if (state.ui.isLoading.uploading !== isUploading) {
+ dispatch(actions.setLoading("uploading", isUploading));
+ }
+
+ const uploadingURLs = new Set(
+ jobs.flatMap((job) =>
+ job.active ? job.entries.filter((entry) => !entry.attachment).map((entry) => entry.localFile.previewUrl) : [],
+ ),
+ );
+ setUploadingLocalFileURLs((previous) =>
+ previous.size === uploadingURLs.size && [...uploadingURLs].every((url) => previous.has(url)) ? previous : uploadingURLs,
+ );
+ }, [actions, dispatch, getState]);
+
+ const appendAttachment = useCallback(
+ (attachment: Attachment, localPreviewURL: string) => {
+ const state = getState();
+ dispatch(actions.setMetadata({ attachments: uniqBy([...state.metadata.attachments, attachment], (item) => item.name) }));
+ if (state.localFiles.some((localFile) => localFile.previewUrl === localPreviewURL)) {
+ dispatch(actions.removeLocalFile(localPreviewURL));
+ }
+ },
+ [actions, dispatch, getState],
+ );
+
+ const finishJob = useCallback(
+ (job: UploadJob) => {
+ jobsRef.current.delete(job.id);
+ syncJobState();
+ },
+ [syncJobState],
+ );
+
+ const dismissJob = useCallback(
+ (id: string) => {
+ const job = jobsRef.current.get(id);
+ if (!job || job.active) return;
+ editorRef.current?.cancelUploadAnchor(id);
+ finishJob(job);
+ },
+ [editorRef, finishJob],
+ );
+
+ const runJobRef = useRef<(id: string) => Promise<void>>(async () => undefined);
+ const retryJob = useCallback((id: string) => void runJobRef.current(id), []);
+
+ const descriptorFor = useCallback(
+ (job: UploadJob, status: "uploading" | "failed") => {
+ const completed = job.entries.filter((entry) => entry.attachment).length;
+ return {
+ id: job.id,
+ status,
+ completed,
+ total: job.entries.length,
+ message: t(status === "uploading" ? "editor.insert-menu.uploading-images" : "editor.insert-menu.image-upload-stopped", {
+ completed,
+ total: job.entries.length,
+ }),
+ retryLabel: t("editor.insert-menu.retry-image-upload"),
+ // Partially-uploaded jobs keep what landed; a job with nothing uploaded is just cancelled.
+ keepLabel: t(completed > 0 ? "editor.insert-menu.keep-as-attachments" : "common.cancel"),
+ onRetry: status === "failed" ? () => retryJob(job.id) : undefined,
+ onKeepAttachments: status === "failed" ? () => dismissJob(job.id) : undefined,
+ };
+ },
+ [dismissJob, retryJob, t],
+ );
+
+ const runJob = useCallback(
+ async (id: string) => {
+ const job = jobsRef.current.get(id);
+ if (!job || job.active || disposedRef.current) return;
+ job.active = true;
+ syncJobState();
+ editorRef.current?.updateUploadAnchor(descriptorFor(job, "uploading"));
+
+ let lastError: unknown;
+ for (const entry of job.entries) {
+ if (entry.attachment) continue;
+ try {
+ entry.attachment = await uploadService.uploadFile(entry.localFile);
+ if (disposedRef.current) return;
+ appendAttachment(entry.attachment, entry.localFile.previewUrl);
+ editorRef.current?.updateUploadAnchor(descriptorFor(job, "uploading"));
+ } catch (error) {
+ lastError = error;
+ }
+ }
+
+ job.active = false;
+ if (disposedRef.current) return;
+ syncJobState();
+
+ if (job.entries.some((entry) => !entry.attachment)) {
+ editorRef.current?.updateUploadAnchor(descriptorFor(job, "failed"));
+ toast.error(errorService.getErrorMessage(lastError) || t("editor.insert-menu.image-upload-failed"));
+ return;
+ }
+
+ const markdown = job.representativeIndexes
+ .map((index) => buildManagedAttachmentMarkdown(job.entries[index]!.attachment!))
+ .join("\n\n");
+ editorRef.current?.resolveUploadAnchor(job.id, markdown);
+ finishJob(job);
+ },
+ [appendAttachment, descriptorFor, editorRef, finishJob, syncJobState, t],
+ );
+ runJobRef.current = runJob;
+
+ const insertLocalImages = useCallback(
+ (localFiles: LocalFile[], position?: number) => {
+ if (getState().ui.isLoading.saving) return;
+ const editor = editorRef.current;
+ const job = createJob(localFiles);
+ if (!editor || !job) return;
+ jobsRef.current.set(job.id, job);
+ syncJobState();
+ editor.createUploadAnchor(descriptorFor(job, "uploading"), position);
+ void runJob(job.id);
+ },
+ [descriptorFor, editorRef, getState, runJob, syncJobState],
+ );
+
+ const insertRemoteImages = useCallback(
+ (attachments: Attachment[]) => {
+ if (getState().ui.isLoading.saving) return;
+ const markdown = attachments.filter(canInlineAttachment).map(buildManagedAttachmentMarkdown).join("\n\n");
+ editorRef.current?.insertMarkdown(markdown);
+ },
+ [editorRef, getState],
+ );
+
+ useEffect(() => {
+ disposedRef.current = false;
+ return () => {
+ disposedRef.current = true;
+ jobsRef.current.clear();
+ };
+ }, []);
+
+ return { insertLocalImages, insertRemoteImages, uploadingLocalFileURLs };
+};
diff --git a/web/src/components/MemoEditor/hooks/useMemoInit.ts b/web/src/components/MemoEditor/hooks/useMemoInit.ts
index c1b6361d1..c06bbe9dd 100644
--- a/web/src/components/MemoEditor/hooks/useMemoInit.ts
+++ b/web/src/components/MemoEditor/hooks/useMemoInit.ts
@@ -37,9 +37,12 @@ export const useMemoInit = ({
cacheService.clear(key);
dispatch(actions.initMemo(initialState));
} else {
- const cachedContent = cacheService.load(key);
- if (cachedContent) {
- dispatch(actions.updateContent(cachedContent));
+ const cachedDraft = cacheService.loadDraft(key);
+ if (cachedDraft.content) {
+ dispatch(actions.updateContent(cachedDraft.content));
+ }
+ if (cachedDraft.attachments.length > 0) {
+ dispatch(actions.setMetadata({ attachments: cachedDraft.attachments }));
}
if (defaultVisibility !== undefined) {
dispatch(actions.setMetadata({ visibility: defaultVisibility }));
diff --git a/web/src/components/MemoEditor/hooks/useMemoSave.ts b/web/src/components/MemoEditor/hooks/useMemoSave.ts
index 34fadc4af..98ca6be75 100644
--- a/web/src/components/MemoEditor/hooks/useMemoSave.ts
+++ b/web/src/components/MemoEditor/hooks/useMemoSave.ts
@@ -41,9 +41,9 @@ export function useMemoSave({
return useCallback(async () => {
const state = getState();
- const { valid, reason } = validationService.canSave(state);
+ const { valid, reason, detail } = validationService.canSave(state);
if (!valid) {
- toast.error(reason || "Cannot save");
+ toast.error(reason ? t(reason, detail ? { url: detail } : undefined) : t("editor.validation.cannot-save"));
return;
}
diff --git a/web/src/components/MemoEditor/index.tsx b/web/src/components/MemoEditor/index.tsx
index 69a460e95..15678007f 100644
--- a/web/src/components/MemoEditor/index.tsx
+++ b/web/src/components/MemoEditor/index.tsx
@@ -10,7 +10,17 @@ 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 { useAudioRecorder, useAutoSave, useFocusMode, useMemoInit, useMemoSave } from "./hooks";
+import {
+ pairAppleLivePhotoFiles,
+ splitInlineLocalFiles,
+ useAudioRecorder,
+ useAutoSave,
+ useBlobUrls,
+ useFocusMode,
+ useInlineImageUpload,
+ useMemoInit,
+ useMemoSave,
+} from "./hooks";
import { cacheService, errorService, transcriptionService } from "./services";
import { EditorProvider, useEditorContext, useEditorSelector } from "./state";
import { EditorToolbar, FormattingToolbar } from "./Toolbar";
@@ -39,7 +49,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
const t = useTranslate();
const currentUser = useCurrentUser();
const editorRef = useRef<EditorController>(null);
- const { actions, dispatch } = useEditorContext();
+ const { actions, dispatch, getState } = useEditorContext();
// Subscribe only to the low-frequency slices this component renders from, so
// typing (which changes content) does not re-render the editor shell and its
// toolbar/metadata children.
@@ -49,6 +59,8 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
const { aiSetting, fetchSetting } = useInstance();
const [isAudioRecorderOpen, setIsAudioRecorderOpen] = useState(false);
const [isTranscribingAudio, setIsTranscribingAudio] = useState(false);
+ const { createBlobUrl } = useBlobUrls();
+ const inlineImageUpload = useInlineImageUpload(editorRef);
// Persisted preference: also show the formatting toolbar in normal mode. Focus
// mode always shows it regardless; this only governs the non-focus layout.
const [isFormattingToolbarVisible, setFormattingToolbarVisible] = useLocalStorage(FORMATTING_TOOLBAR_STORAGE_KEY, false);
@@ -220,6 +232,29 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
void handleStartAudioRecording();
};
+ const toLocalFiles = useCallback(
+ (files: File[]): LocalFile[] =>
+ pairAppleLivePhotoFiles(
+ files.map((file) => ({
+ file,
+ previewUrl: createBlobUrl(file),
+ origin: "upload",
+ })),
+ ),
+ [createBlobUrl],
+ );
+
+ /** Shared by the + menu (no position) and by editor paste/drop (drop position). */
+ const handleInsertImages = useCallback(
+ (files: File[], position?: number) => {
+ if (getState().ui.isLoading.saving) return;
+ const { inline, attachments } = splitInlineLocalFiles(toLocalFiles(files));
+ attachments.forEach((file) => dispatch(actions.addLocalFile(file)));
+ inlineImageUpload.insertLocalImages(inline, position);
+ },
+ [actions, dispatch, getState, inlineImageUpload.insertLocalImages, toLocalFiles],
+ );
+
const handleCancelAudioRecording = () => {
setIsTranscribingAudio(false);
audioRecorder.resetRecording();
@@ -285,7 +320,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
)}
{/* Editor content grows to fill available space in focus mode */}
- <EditorContent ref={editorRef} placeholder={placeholder} onSubmit={handleSave} />
+ <EditorContent ref={editorRef} placeholder={placeholder} onSubmit={handleSave} onFiles={handleInsertImages} />
{isAudioRecorderOpen && (audioRecorder.isBusy || isTranscribingAudio) && (
<AudioRecorderPanel
@@ -301,7 +336,12 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
{/* Metadata and toolbar grouped together at bottom */}
<div className="w-full flex flex-col gap-2">
- <EditorMetadata memoName={memoName} />
+ <EditorMetadata
+ memoName={memoName}
+ uploadingLocalFileURLs={inlineImageUpload.uploadingLocalFileURLs}
+ onInsertAttachments={inlineImageUpload.insertRemoteImages}
+ onInsertLocalFiles={inlineImageUpload.insertLocalImages}
+ />
<EditorToolbar
onSave={handleSave}
onCancel={onCancel ? handleCancel : undefined}
@@ -309,6 +349,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
onAudioRecorderClick={handleAudioRecorderClick}
isFormattingToolbarVisible={isFormattingToolbarVisible}
onToggleFormattingToolbar={handleToggleFormattingToolbar}
+ onInsertImages={handleInsertImages}
/>
</div>
</div>
diff --git a/web/src/components/MemoEditor/services/cacheService.ts b/web/src/components/MemoEditor/services/cacheService.ts
index f4429aa20..8a4733b97 100644
--- a/web/src/components/MemoEditor/services/cacheService.ts
+++ b/web/src/components/MemoEditor/services/cacheService.ts
@@ -1,30 +1,64 @@
+import { fromJson, type JsonValue, toJson } from "@bufbuild/protobuf";
+import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
+import { AttachmentSchema } from "@/types/proto/api/v1/attachment_service_pb";
+
export const CACHE_DEBOUNCE_DELAY = 500;
const pendingSaves = new Map<string, ReturnType<typeof window.setTimeout>>();
const cursors = new Map<string, number>();
const STRUCTURED_CACHE_ENTRY_KIND = "memos.editor-cache";
-const STRUCTURED_CACHE_ENTRY_VERSION = 1;
+const STRUCTURED_CACHE_ENTRY_VERSION = 2;
+
+export interface EditorDraft {
+ content: string;
+ attachments: Attachment[];
+}
-function deserializeContent(raw: string): string {
+function deserializeDraft(raw: string): EditorDraft {
try {
- const parsed = JSON.parse(raw) as { kind?: unknown; version?: unknown; content?: unknown };
+ const parsed = JSON.parse(raw) as { kind?: unknown; version?: unknown; content?: unknown; attachments?: unknown };
+ if (parsed.kind === STRUCTURED_CACHE_ENTRY_KIND && parsed.version === 1 && typeof parsed.content === "string") {
+ return { content: parsed.content, attachments: [] };
+ }
if (
parsed.kind === STRUCTURED_CACHE_ENTRY_KIND &&
parsed.version === STRUCTURED_CACHE_ENTRY_VERSION &&
typeof parsed.content === "string"
) {
- return parsed.content;
+ const attachments = Array.isArray(parsed.attachments)
+ ? parsed.attachments.flatMap((value) => {
+ try {
+ return [fromJson(AttachmentSchema, value as JsonValue, { ignoreUnknownFields: true })];
+ } catch {
+ return [];
+ }
+ })
+ : [];
+ return { content: parsed.content, attachments };
}
} catch {
// Drafts have historically been stored as raw markdown strings.
}
- return raw;
+ return { content: raw, attachments: [] };
}
-function writeEntry(key: string, content: string): void {
- if (content.trim()) {
- localStorage.setItem(key, content);
+function serializeDraft(content: string, attachments: Attachment[]): string {
+ if (attachments.length === 0) {
+ return content;
+ }
+
+ return JSON.stringify({
+ kind: STRUCTURED_CACHE_ENTRY_KIND,
+ version: STRUCTURED_CACHE_ENTRY_VERSION,
+ content,
+ attachments: attachments.map((attachment) => toJson(AttachmentSchema, attachment)),
+ });
+}
+
+function writeEntry(key: string, content: string, attachments: Attachment[]): void {
+ if (content.trim() || attachments.length > 0) {
+ localStorage.setItem(key, serializeDraft(content, attachments));
} else {
localStorage.removeItem(key);
}
@@ -35,7 +69,7 @@ export const cacheService = {
return `${username}-${cacheKey || ""}`;
},
- save: (key: string, content: string) => {
+ save: (key: string, content: string, attachments: Attachment[] = []) => {
const pendingSave = pendingSaves.get(key);
if (pendingSave) {
window.clearTimeout(pendingSave);
@@ -44,25 +78,30 @@ export const cacheService = {
const timeoutId = window.setTimeout(() => {
pendingSaves.delete(key);
- writeEntry(key, content);
+ writeEntry(key, content, attachments);
}, CACHE_DEBOUNCE_DELAY);
pendingSaves.set(key, timeoutId);
},
- saveNow: (key: string, content: string) => {
+ saveNow: (key: string, content: string, attachments: Attachment[] = []) => {
const pendingSave = pendingSaves.get(key);
if (pendingSave) {
window.clearTimeout(pendingSave);
pendingSaves.delete(key);
}
- writeEntry(key, content);
+ writeEntry(key, content, attachments);
},
load(key: string): string {
const raw = localStorage.getItem(key);
- return raw ? deserializeContent(raw) : "";
+ return raw ? deserializeDraft(raw).content : "";
+ },
+
+ loadDraft(key: string): EditorDraft {
+ const raw = localStorage.getItem(key);
+ return raw ? deserializeDraft(raw) : { content: "", attachments: [] };
},
saveCursor(key: string, cursor: number): void {
diff --git a/web/src/components/MemoEditor/services/uploadService.ts b/web/src/components/MemoEditor/services/uploadService.ts
index 404eae584..1d4880c3f 100644
--- a/web/src/components/MemoEditor/services/uploadService.ts
+++ b/web/src/components/MemoEditor/services/uploadService.ts
@@ -5,24 +5,27 @@ import { AttachmentSchema, MotionMediaSchema } from "@/types/proto/api/v1/attach
import type { LocalFile } from "../types/attachment";
export const uploadService = {
+ async uploadFile(localFile: LocalFile): Promise<Attachment> {
+ const { file, motionMedia } = localFile;
+ const buffer = new Uint8Array(await file.arrayBuffer());
+ return attachmentServiceClient.createAttachment({
+ attachment: create(AttachmentSchema, {
+ filename: file.name,
+ size: BigInt(file.size),
+ type: file.type,
+ content: buffer,
+ motionMedia: motionMedia ? create(MotionMediaSchema, motionMedia) : undefined,
+ }),
+ });
+ },
+
async uploadFiles(localFiles: LocalFile[]): Promise<Attachment[]> {
if (localFiles.length === 0) return [];
const attachments: Attachment[] = [];
for (const localFile of localFiles) {
- const { file, motionMedia } = localFile;
- const buffer = new Uint8Array(await file.arrayBuffer());
- const attachment = await attachmentServiceClient.createAttachment({
- attachment: create(AttachmentSchema, {
- filename: file.name,
- size: BigInt(file.size),
- type: file.type,
- content: buffer,
- motionMedia: motionMedia ? create(MotionMediaSchema, motionMedia) : undefined,
- }),
- });
- attachments.push(attachment);
+ attachments.push(await uploadService.uploadFile(localFile));
}
return attachments;
diff --git a/web/src/components/MemoEditor/services/validationService.ts b/web/src/components/MemoEditor/services/validationService.ts
index 4693e0cbb..852da0d91 100644
--- a/web/src/components/MemoEditor/services/validationService.ts
+++ b/web/src/components/MemoEditor/services/validationService.ts
@@ -1,35 +1,49 @@
+import type { Translations } from "@/utils/i18n";
+import { findInvalidManagedAttachmentReferences } from "@/utils/managed-attachment";
import type { EditorState } from "../state";
export interface ValidationResult {
valid: boolean;
- reason?: string;
+ reason?: Translations;
+ detail?: string;
}
export const validationService = {
canSave(state: EditorState): ValidationResult {
// Cannot save while loading initial content
if (state.ui.isLoading.loading) {
- return { valid: false, reason: "Loading memo content" };
+ return { valid: false, reason: "editor.validation.loading-content" };
}
// Must have content, attachment, or local file
if (!state.content.trim() && state.metadata.attachments.length === 0 && state.localFiles.length === 0) {
- return { valid: false, reason: "Content, attachment, or file required" };
+ return { valid: false, reason: "editor.validation.content-required" };
}
// Cannot save while uploading
if (state.ui.isLoading.uploading) {
- return { valid: false, reason: "Wait for upload to complete" };
+ return { valid: false, reason: "editor.validation.wait-for-upload" };
+ }
+
+ if (state.ui.pendingInlineImageInsertions > 0) {
+ return { valid: false, reason: "editor.validation.resolve-image-uploads" };
+ }
+
+ // The API rejects these outright, so catch them here rather than letting the
+ // save fail with an opaque error that doesn't say which URL is at fault.
+ const [invalidReference] = findInvalidManagedAttachmentReferences(state.content);
+ if (invalidReference) {
+ return { valid: false, reason: "editor.validation.unsupported-attachment-image-url", detail: invalidReference };
}
// Cannot save while audio recorder is active
if (state.recorderBusy) {
- return { valid: false, reason: "Finish audio recording before saving" };
+ return { valid: false, reason: "editor.validation.finish-audio-recording" };
}
// Cannot save while already saving
if (state.ui.isLoading.saving) {
- return { valid: false, reason: "Save in progress" };
+ return { valid: false, reason: "editor.validation.save-in-progress" };
}
return { valid: true };
diff --git a/web/src/components/MemoEditor/state/actions.ts b/web/src/components/MemoEditor/state/actions.ts
index 8c80fcacc..5b9ee093a 100644
--- a/web/src/components/MemoEditor/state/actions.ts
+++ b/web/src/components/MemoEditor/state/actions.ts
@@ -41,6 +41,11 @@ export const editorActions = {
payload: { key, value },
}),
+ setPendingInlineImageInsertions: (value: number): EditorAction => ({
+ type: "SET_PENDING_INLINE_IMAGE_INSERTIONS",
+ payload: value,
+ }),
+
setTimestamps: (timestamps: Partial<EditorState["timestamps"]>): EditorAction => ({
type: "SET_TIMESTAMPS",
payload: timestamps,
diff --git a/web/src/components/MemoEditor/state/reducer.ts b/web/src/components/MemoEditor/state/reducer.ts
index 31ea0ce88..962a13568 100644
--- a/web/src/components/MemoEditor/state/reducer.ts
+++ b/web/src/components/MemoEditor/state/reducer.ts
@@ -65,6 +65,15 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS
},
};
+ case "SET_PENDING_INLINE_IMAGE_INSERTIONS":
+ return {
+ ...state,
+ ui: {
+ ...state.ui,
+ pendingInlineImageInsertions: action.payload,
+ },
+ };
+
case "SET_TIMESTAMPS":
return {
...state,
diff --git a/web/src/components/MemoEditor/state/types.ts b/web/src/components/MemoEditor/state/types.ts
index 861e25396..e89041b91 100644
--- a/web/src/components/MemoEditor/state/types.ts
+++ b/web/src/components/MemoEditor/state/types.ts
@@ -15,6 +15,7 @@ export interface EditorState {
};
ui: {
isFocusMode: boolean;
+ pendingInlineImageInsertions: number;
isLoading: {
saving: boolean;
uploading: boolean;
@@ -40,6 +41,7 @@ export type EditorAction =
| { type: "SET_LOCAL_FILES"; payload: LocalFile[] }
| { type: "TOGGLE_FOCUS_MODE" }
| { type: "SET_LOADING"; payload: { key: LoadingKey; value: boolean } }
+ | { type: "SET_PENDING_INLINE_IMAGE_INSERTIONS"; payload: number }
| { type: "SET_TIMESTAMPS"; payload: Partial<EditorState["timestamps"]> }
| { type: "SET_RECORDER_BUSY"; payload: boolean }
| { type: "RESET" };
@@ -55,6 +57,7 @@ const defaultState: EditorState = {
},
ui: {
isFocusMode: false,
+ pendingInlineImageInsertions: 0,
isLoading: {
saving: false,
uploading: false,
diff --git a/web/src/components/MemoEditor/types/components.ts b/web/src/components/MemoEditor/types/components.ts
index 37af5a86c..c0dc935b9 100644
--- a/web/src/components/MemoEditor/types/components.ts
+++ b/web/src/components/MemoEditor/types/components.ts
@@ -1,5 +1,7 @@
+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 { AudioRecorderStatus } from "../hooks/useAudioRecorder";
+import type { LocalFile } from "./attachment";
export interface MemoEditorProps {
className?: string;
@@ -29,6 +31,7 @@ export interface EditorContentProps {
placeholder?: string;
/** Invoked by the in-editor save shortcut (Cmd/Ctrl+Enter). */
onSubmit: () => void;
+ onFiles: (files: File[], position: number) => void;
}
export interface EditorToolbarProps {
@@ -39,10 +42,14 @@ export interface EditorToolbarProps {
/** Whether the formatting toolbar is shown in normal mode (persisted preference). */
isFormattingToolbarVisible: boolean;
onToggleFormattingToolbar: () => void;
+ onInsertImages: (files: File[]) => void;
}
export interface EditorMetadataProps {
memoName?: string;
+ uploadingLocalFileURLs: ReadonlySet<string>;
+ onInsertAttachments: (attachments: Attachment[]) => void;
+ onInsertLocalFiles: (localFiles: LocalFile[]) => void;
}
export interface AudioRecorderPanelProps {
@@ -69,6 +76,7 @@ export interface FocusModeExitButtonProps {
export interface InsertMenuProps {
isUploading?: boolean;
+ isSaving?: boolean;
location?: Location;
onLocationChange: (location?: Location) => void;
onToggleFocusMode?: () => void;
@@ -77,6 +85,7 @@ export interface InsertMenuProps {
/** Persisted toggle for the normal-mode formatting toolbar. */
isFormattingToolbarVisible?: boolean;
onToggleFormattingToolbar?: () => void;
+ onInsertImages: (files: File[]) => void;
}
export interface VisibilitySelectorProps {
diff --git a/web/src/components/MemoEditor/types/editorController.ts b/web/src/components/MemoEditor/types/editorController.ts
index 3829027f5..00f9f4131 100644
--- a/web/src/components/MemoEditor/types/editorController.ts
+++ b/web/src/components/MemoEditor/types/editorController.ts
@@ -1,3 +1,4 @@
+import type { UploadAnchorDescriptor } from "../Editor/uploadAnchors";
import type { ActiveFormatState, EditorCommandContext, EditorCommandId } from "../formatting/commands";
/**
@@ -16,6 +17,10 @@ export interface EditorController {
setMarkdown(markdown: string): void;
/** Insert markdown at the cursor as its own block. */
insertMarkdown(markdown: string): void;
+ createUploadAnchor(descriptor: UploadAnchorDescriptor, position?: number): void;
+ updateUploadAnchor(descriptor: UploadAnchorDescriptor): void;
+ resolveUploadAnchor(id: string, markdown: string): void;
+ cancelUploadAnchor(id: string): void;
getCursor(): number;
setCursor(position: number): void;
scrollToCursor(): void;
diff --git a/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx b/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx
index 9ca6dff59..6c3961105 100644
--- a/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx
+++ b/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx
@@ -1,4 +1,14 @@
-import { ChevronDownIcon, ChevronUpIcon, FileAudioIcon, FileIcon, PaperclipIcon, PauseIcon, PlayIcon, XIcon } from "lucide-react";
+import {
+ ChevronDownIcon,
+ ChevronUpIcon,
+ FileAudioIcon,
+ FileIcon,
+ ImagePlusIcon,
+ PaperclipIcon,
+ PauseIcon,
+ PlayIcon,
+ XIcon,
+} from "lucide-react";
import { type FC, type MouseEvent, useMemo, useRef, useState } from "react";
import type { AttachmentItem, LocalFile } from "@/components/MemoEditor/types/attachment";
import { getAudioRecordingTimeLabel, toAttachmentItems } from "@/components/MemoEditor/types/attachment";
@@ -9,30 +19,55 @@ import { cn } from "@/lib/utils";
import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
import { formatFileSize, getFileTypeLabel } from "@/utils/format";
import { useTranslate } from "@/utils/i18n";
+import { canInlineAttachment, extractAttachmentUIDFromName } from "@/utils/managed-attachment";
import type { PreviewMediaItem } from "@/utils/media-item";
import { formatAudioTime, toggleAudioPlayback } from "./attachmentHelpers";
+const collectMembers = <T,>(byId: ReadonlyMap<string, T>, memberIds: string[]): T[] =>
+ memberIds.map((memberId) => byId.get(memberId)).filter((member): member is T => member !== undefined);
+
interface AttachmentListEditorProps {
attachments: Attachment[];
localFiles?: LocalFile[];
onAttachmentsChange?: (attachments: Attachment[]) => void;
onLocalFilesChange?: (localFiles: LocalFile[]) => void;
onRemoveLocalFile?: (previewUrl: string) => void;
+ inlineAttachmentUIDs?: ReadonlySet<string>;
+ onInsertAttachments?: (attachments: Attachment[]) => void;
+ onInsertLocalFiles?: (localFiles: LocalFile[]) => void;
+ placementActionsDisabled?: boolean;
+ uploadingLocalFileURLs?: ReadonlySet<string>;
}
const AttachmentItemActions: FC<{
+ placementAction?: { label: string; onClick: () => void; disabled?: boolean };
onRemove?: () => void;
onMoveUp?: () => void;
onMoveDown?: () => void;
canMoveUp?: boolean;
canMoveDown?: boolean;
-}> = ({ onRemove, onMoveUp, onMoveDown, canMoveUp = true, canMoveDown = true }) => {
+}> = ({ placementAction, onRemove, onMoveUp, onMoveDown, canMoveUp = true, canMoveDown = true }) => {
const stopPropagation = (event: MouseEvent) => {
event.stopPropagation();
};
return (
<div className="shrink-0 flex items-center gap-0.5">
+ {placementAction && (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={(event) => {
+ stopPropagation(event);
+ placementAction.onClick();
+ }}
+ className="h-6 gap-1 px-1.5 text-[10px] text-muted-foreground"
+ disabled={placementAction.disabled}
+ >
+ <ImagePlusIcon className="size-3" />
+ {placementAction.label}
+ </Button>
+ )}
{onMoveUp && (
<Button
variant="ghost"
@@ -91,7 +126,9 @@ const AttachmentItemCard: FC<{
onMoveDown?: () => void;
canMoveUp?: boolean;
canMoveDown?: boolean;
-}> = ({ item, onPreview, onRemove, onMoveUp, onMoveDown, canMoveUp = true, canMoveDown = true }) => {
+ isUploadingInline?: boolean;
+ placementAction?: { label: string; onClick: () => void; disabled?: boolean };
+}> = ({ item, onPreview, onRemove, onMoveUp, onMoveDown, canMoveUp = true, canMoveDown = true, isUploadingInline, placementAction }) => {
const t = useTranslate();
const { category, filename, thumbnailUrl, mimeType, size, sourceUrl, isVoiceNote, audioMeta } = item;
const audioRef = useRef<HTMLAudioElement>(null);
@@ -106,6 +143,7 @@ const AttachmentItemCard: FC<{
? t("editor.audio-recorder.attachment-label")
: filename;
const detailParts = [
+ isUploadingInline ? t("editor.insert-menu.uploading-inline-image") : undefined,
audioMeta?.durationSeconds ? formatAudioTime(audioMeta.durationSeconds) : undefined,
fileTypeLabel,
size ? formatFileSize(size) : undefined,
@@ -123,7 +161,10 @@ const AttachmentItemCard: FC<{
};
return (
- <div className="relative rounded border border-transparent px-1.5 py-1 transition-all hover:border-border hover:bg-accent/20">
+ <div
+ className="relative rounded border border-transparent px-1.5 py-1 transition-all hover:border-border hover:bg-accent/20"
+ aria-busy={isUploadingInline || undefined}
+ >
<div className="flex items-center gap-1.5">
<div className="relative flex h-6 w-6 shrink-0 items-center justify-center overflow-hidden rounded bg-muted/40">
{(category === "image" || category === "motion") && thumbnailUrl ? (
@@ -196,6 +237,7 @@ const AttachmentItemCard: FC<{
</div>
<AttachmentItemActions
+ placementAction={placementAction}
onRemove={onRemove}
onMoveUp={onMoveUp}
onMoveDown={onMoveDown}
@@ -213,9 +255,28 @@ const AttachmentListEditor: FC<AttachmentListEditorProps> = ({
onAttachmentsChange,
onLocalFilesChange,
onRemoveLocalFile,
+ inlineAttachmentUIDs = new Set(),
+ onInsertAttachments,
+ onInsertLocalFiles,
+ placementActionsDisabled = false,
+ uploadingLocalFileURLs = new Set(),
}) => {
+ const t = useTranslate();
const [previewState, setPreviewState] = useState<{ open: boolean; initialIndex: number }>({ open: false, initialIndex: 0 });
- const items = toAttachmentItems(attachments, localFiles);
+ const attachmentsByName = useMemo(() => new Map(attachments.map((attachment) => [attachment.name, attachment])), [attachments]);
+ const allItems = toAttachmentItems(attachments, localFiles);
+ const isInlineItem = (item: AttachmentItem) =>
+ !item.isLocal &&
+ collectMembers(attachmentsByName, item.memberIds).some((attachment) => {
+ const uid = extractAttachmentUIDFromName(attachment.name);
+ return uid ? inlineAttachmentUIDs.has(uid) : false;
+ });
+ // A managed image already has its placement represented in Markdown. Keep
+ // the attachment bound to the memo, but do not repeat its logical media group
+ // in the attachment section. Removing the Markdown reference makes it
+ // visible here again on the next render.
+ const items = allItems.filter((item) => !isInlineItem(item));
+ const allAttachmentItems = allItems.filter((item) => !item.isLocal);
const attachmentItems = items.filter((item) => !item.isLocal);
const localItems = items.filter((item) => item.isLocal);
const previewItems = useMemo<PreviewMediaItem[]>(
@@ -241,6 +302,10 @@ const AttachmentListEditor: FC<AttachmentListEditorProps> = ({
[items],
);
+ // Items address their members by id, so index once instead of re-scanning both
+ // source arrays for every item on every render.
+ const localFilesByPreviewUrl = useMemo(() => new Map(localFiles.map((localFile) => [localFile.previewUrl, localFile])), [localFiles]);
+
const handleMoveAttachments = (itemId: string, direction: -1 | 1) => {
if (!onAttachmentsChange) return;
@@ -253,10 +318,9 @@ const AttachmentListEditor: FC<AttachmentListEditorProps> = ({
const reorderedItems = [...attachmentItems];
[reorderedItems[itemIndex], reorderedItems[targetIndex]] = [reorderedItems[targetIndex], reorderedItems[itemIndex]];
- const attachmentMap = new Map(attachments.map((attachment) => [attachment.name, attachment]));
- onAttachmentsChange(
- reorderedItems.flatMap((item) => item.memberIds.map((memberId) => attachmentMap.get(memberId)).filter(Boolean) as Attachment[]),
- );
+ let visibleIndex = 0;
+ const mergedItems = allAttachmentItems.map((item) => (isInlineItem(item) ? item : reorderedItems[visibleIndex++]!));
+ onAttachmentsChange(mergedItems.flatMap((item) => collectMembers(attachmentsByName, item.memberIds)));
};
const handleMoveLocalFiles = (itemId: string, direction: -1 | 1) => {
@@ -271,10 +335,7 @@ const AttachmentListEditor: FC<AttachmentListEditorProps> = ({
const reorderedItems = [...localItems];
[reorderedItems[itemIndex], reorderedItems[targetIndex]] = [reorderedItems[targetIndex], reorderedItems[itemIndex]];
- const localFileMap = new Map(localFiles.map((localFile) => [localFile.previewUrl, localFile]));
- onLocalFilesChange(
- reorderedItems.flatMap((item) => item.memberIds.map((memberId) => localFileMap.get(memberId)).filter(Boolean) as LocalFile[]),
- );
+ onLocalFilesChange(reorderedItems.flatMap((item) => collectMembers(localFilesByPreviewUrl, item.memberIds)));
};
const handleRemoveItem = (item: AttachmentItem) => {
@@ -311,17 +372,32 @@ const AttachmentListEditor: FC<AttachmentListEditorProps> = ({
{items.map((item) => {
const itemList = item.isLocal ? localItems : attachmentItems;
const itemIndex = itemList.findIndex((entry) => entry.id === item.id);
+ const itemAttachments = collectMembers(attachmentsByName, item.memberIds);
+ const itemLocalFiles = collectMembers(localFilesByPreviewUrl, item.memberIds);
+ const isUploadingInline = item.isLocal && item.memberIds.some((memberID) => uploadingLocalFileURLs.has(memberID));
+ const canInsert =
+ (item.category === "image" || item.category === "motion") && (item.isLocal || itemAttachments.some(canInlineAttachment));
+ const placementAction = canInsert
+ ? {
+ label: t("editor.insert-menu.insert-image"),
+ onClick: () =>
+ item.isLocal ? onInsertLocalFiles?.(itemLocalFiles) : onInsertAttachments?.(itemAttachments.filter(canInlineAttachment)),
+ disabled: placementActionsDisabled,
+ }
+ : undefined;
return (
<AttachmentItemCard
key={item.id}
item={item}
+ isUploadingInline={isUploadingInline}
+ placementAction={placementAction}
onPreview={
item.category === "image" || item.category === "video" || item.category === "motion"
? () => handlePreviewItem(item)
: undefined
}
- onRemove={() => handleRemoveItem(item)}
+ onRemove={isUploadingInline ? undefined : () => handleRemoveItem(item)}
onMoveUp={item.isLocal ? () => handleMoveLocalFiles(item.id, -1) : () => handleMoveAttachments(item.id, -1)}
onMoveDown={item.isLocal ? () => handleMoveLocalFiles(item.id, 1) : () => handleMoveAttachments(item.id, 1)}
canMoveUp={itemIndex > 0}
diff --git a/web/src/components/MemoPreview/MemoPreview.tsx b/web/src/components/MemoPreview/MemoPreview.tsx
index db26ce944..2663071ea 100644
--- a/web/src/components/MemoPreview/MemoPreview.tsx
+++ b/web/src/components/MemoPreview/MemoPreview.tsx
@@ -1,11 +1,13 @@
import { create } from "@bufbuild/protobuf";
import { FileIcon } from "lucide-react";
+import { useMemo } from "react";
import { extractMemoIdFromName } from "@/lib/resource-names";
import { cn } from "@/lib/utils";
import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
import { MemoSchema } from "@/types/proto/api/v1/memo_service_pb";
import type { User } from "@/types/proto/api/v1/user_service_pb";
import { getAttachmentType, isMotionAttachment } from "@/utils/attachment";
+import { filterInlineManagedAttachments } from "@/utils/managed-attachment";
import { buildAttachmentVisualItems, countLogicalAttachmentItems } from "@/utils/media-item";
import MemoContent from "../MemoContent";
import { MemoViewContext, type MemoViewContextValue } from "../MemoView/MemoViewContext";
@@ -114,7 +116,8 @@ const MemoPreview = ({
truncate = false,
}: MemoPreviewProps) => {
const hasContent = content.trim().length > 0;
- const hasAttachments = attachments.length > 0;
+ const attachmentOnlyItems = useMemo(() => filterInlineManagedAttachments(content, attachments), [content, attachments]);
+ const hasAttachments = attachmentOnlyItems.length > 0;
const showMeta = showCreator || showMemoId;
if (!hasContent && !hasAttachments) {
@@ -133,7 +136,7 @@ const MemoPreview = ({
// interactive clamp a full memo card gets.
hasContent && (
<div className="max-h-36 w-full overflow-hidden">
- <MemoContent content={content} compact={compact} />
+ <MemoContent content={content} attachments={attachments} compact={compact} />
</div>
)
);
@@ -154,10 +157,10 @@ const MemoPreview = ({
(truncate ? (
<div className="shrink-0 text-muted-foreground/70 inline-flex justify-center items-center gap-0.5">
<FileIcon className="w-3 h-3 inline-block" />
- <span className="text-xs">{countLogicalAttachmentItems(attachments)}</span>
+ <span className="text-xs">{countLogicalAttachmentItems(attachmentOnlyItems)}</span>
</div>
) : (
- <AttachmentThumbnails attachments={attachments} />
+ <AttachmentThumbnails attachments={attachmentOnlyItems} />
))}
</div>
</MemoViewContext.Provider>
diff --git a/web/src/components/MemoView/components/MemoBody.tsx b/web/src/components/MemoView/components/MemoBody.tsx
index c004d2c08..98ba794fb 100644
--- a/web/src/components/MemoView/components/MemoBody.tsx
+++ b/web/src/components/MemoView/components/MemoBody.tsx
@@ -1,10 +1,12 @@
import { EyeIcon } from "lucide-react";
+import { useMemo } from "react";
import ClampedSection from "@/components/ClampedSection";
import { AttachmentListView, LocationDisplayView, RelationListView } from "@/components/MemoMetadata";
import { isReferenceRelation } from "@/components/MemoMetadata/Relation/relationHelpers";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
+import { filterInlineManagedAttachments } from "@/utils/managed-attachment";
import MemoContent from "../../MemoContent";
import { MemoReactionListView } from "../../MemoReactionListView";
import { useMemoHandlers } from "../hooks";
@@ -35,6 +37,11 @@ const MemoBody: React.FC<MemoBodyProps> = ({ compact }) => {
const { handleMemoContentClick, handleMemoContentDoubleClick } = useMemoHandlers({ readonly, openEditor, openPreview });
const referencedMemos = memo.relations.filter(isReferenceRelation);
+ // Memoized so AttachmentListView's own useMemo chain keeps its cache across body renders.
+ const attachmentOnlyItems = useMemo(
+ () => filterInlineManagedAttachments(memo.content, memo.attachments),
+ [memo.content, memo.attachments],
+ );
return (
<>
@@ -50,11 +57,12 @@ const MemoBody: React.FC<MemoBodyProps> = ({ compact }) => {
<MemoContent
memoName={memo.name}
content={memo.content}
+ attachments={memo.attachments}
onClick={handleMemoContentClick}
onDoubleClick={handleMemoContentDoubleClick}
compact={Boolean(compact)}
/>
- <AttachmentListView attachments={memo.attachments} onImagePreview={openPreview} />
+ <AttachmentListView attachments={attachmentOnlyItems} onImagePreview={openPreview} />
<RelationListView relations={referencedMemos} currentMemoName={memo.name} parentPage={parentPage} />
{memo.location && <LocationDisplayView location={memo.location} />}
</ClampedSection>
diff --git a/web/src/components/PagedMemoList/memoCardHeight.ts b/web/src/components/PagedMemoList/memoCardHeight.ts
index 3e95e9629..0afc5dcdf 100644
--- a/web/src/components/PagedMemoList/memoCardHeight.ts
+++ b/web/src/components/PagedMemoList/memoCardHeight.ts
@@ -3,6 +3,7 @@ import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
import type { Memo } from "@/types/proto/api/v1/memo_service_pb";
import { MemoRelation_Type } from "@/types/proto/api/v1/memo_service_pb";
import { getAttachmentType, isMotionAttachment } from "@/utils/attachment";
+import { filterInlineManagedAttachments } from "@/utils/managed-attachment";
import { buildAttachmentVisualItems } from "@/utils/media-item";
interface EstimateMemoCardHeightOptions {
@@ -99,7 +100,7 @@ const estimateCommentPreviewHeight = (memo: Memo): number => {
export const estimateMemoCardHeight = (memo: Memo, { columnWidth }: EstimateMemoCardHeightOptions): number => {
const content = memo.content ?? "";
const contentHeight = estimateWrappedTextHeight(content, columnWidth) + countMarkdownImages(content) * MARKDOWN_IMAGE_HEIGHT;
- const attachmentHeight = estimateAttachmentSectionHeight(memo.attachments ?? [], columnWidth);
+ const attachmentHeight = estimateAttachmentSectionHeight(filterInlineManagedAttachments(content, memo.attachments ?? []), columnWidth);
const bodyHeight = contentHeight + attachmentHeight + (contentHeight > 0 && attachmentHeight > 0 ? CARD_SECTION_GAP : 0);
const compactBodyHeight = bodyHeight > CLAMP_TRIGGER_HEIGHT_PX ? CLAMP_PREVIEW_HEIGHT_PX + SHOW_MORE_BUTTON_HEIGHT : bodyHeight;
const reactionHeight = (memo.reactions ?? []).length > 0 ? CARD_SECTION_GAP + REACTION_ROW_HEIGHT : 0;
diff --git a/web/src/contexts/InstanceContext.tsx b/web/src/contexts/InstanceContext.tsx
index 5c784e585..dc209a122 100644
--- a/web/src/contexts/InstanceContext.tsx
+++ b/web/src/contexts/InstanceContext.tsx
@@ -17,6 +17,7 @@ import {
InstanceSetting_StorageSetting,
InstanceSetting_StorageSettingSchema,
} from "@/types/proto/api/v1/instance_service_pb";
+import { setManagedAttachmentInstanceUrl } from "@/utils/managed-attachment";
const instanceSettingNamePrefix = "instance/settings/";
@@ -111,6 +112,10 @@ export function InstanceProvider({ children }: { children: ReactNode }) {
const profileRequest = instanceServiceClient
.getInstanceProfile({})
.then((profile) => {
+ // Managed attachment URLs are resolved against the instance URL, and the
+ // parser runs outside React (card layout estimation), so it reads the
+ // value from module scope rather than from this context.
+ setManagedAttachmentInstanceUrl(profile.instanceUrl);
setState((prev) => ({
...prev,
profile,
diff --git a/web/src/locales/en.json b/web/src/locales/en.json
index 84e4c85f8..14b4b7407 100644
--- a/web/src/locales/en.json
+++ b/web/src/locales/en.json
@@ -224,13 +224,31 @@
"more": "More formatting"
},
"insert-menu": {
+ "add-attachment": "Add attachment",
"add-location": "Add location",
+ "image-upload-failed": "Some images could not be uploaded. Retry or keep the uploaded files as attachments.",
+ "image-upload-stopped": "Image upload stopped {{completed}}/{{total}}",
+ "insert-image": "Insert image",
+ "keep-as-attachments": "Keep as attachments",
"link-memo": "Link memo",
+ "retry-image-upload": "Retry",
+ "uploading-inline-image": "Uploading to content",
+ "uploading-images": "Uploading images {{completed}}/{{total}}",
"upload-file": "Upload file"
},
"no-changes-detected": "No changes detected",
"save": "Save",
"saving": "Saving...",
+ "validation": {
+ "cannot-save": "Cannot save",
+ "content-required": "Content, attachment, or file required",
+ "finish-audio-recording": "Finish audio recording before saving",
+ "loading-content": "Loading memo content",
+ "resolve-image-uploads": "Resolve image uploads before saving",
+ "save-in-progress": "Save in progress",
+ "unsupported-attachment-image-url": "Unsupported attachment image URL: {{url}}",
+ "wait-for-upload": "Wait for upload to complete"
+ },
"unsupported-syntax-raw-mode": "This memo contains syntax the rich-text editor can't safely edit, so it opened in raw Markdown mode.",
"wysiwyg-editor": "WYSIWYG Editor",
"audio-recorder": {
diff --git a/web/src/locales/zh-Hans.json b/web/src/locales/zh-Hans.json
index 331c0e6ab..03f9718d1 100644
--- a/web/src/locales/zh-Hans.json
+++ b/web/src/locales/zh-Hans.json
@@ -190,9 +190,27 @@
"no-changes-detected": "未检测到更改",
"save": "保存",
"saving": "保存中...",
+ "validation": {
+ "cannot-save": "无法保存",
+ "content-required": "需要填写正文或添加附件",
+ "finish-audio-recording": "请先完成录音再保存",
+ "loading-content": "正在加载备忘录内容",
+ "resolve-image-uploads": "请先处理未完成的图片上传",
+ "save-in-progress": "正在保存",
+ "unsupported-attachment-image-url": "不支持的附件图片地址:{{url}}",
+ "wait-for-upload": "请等待上传完成"
+ },
"insert-menu": {
+ "add-attachment": "添加附件",
"add-location": "添加位置",
+ "image-upload-failed": "部分图片上传失败,请重试或将已上传文件保留为附件。",
+ "image-upload-stopped": "图片上传已暂停 {{completed}}/{{total}}",
+ "insert-image": "插入图片",
+ "keep-as-attachments": "保留为附件",
"link-memo": "链接备忘录",
+ "retry-image-upload": "重试",
+ "uploading-inline-image": "正在上传到正文",
+ "uploading-images": "正在上传图片 {{completed}}/{{total}}",
"upload-file": "上传文件"
},
"audio-recorder": {
diff --git a/web/src/locales/zh-Hant.json b/web/src/locales/zh-Hant.json
index e674a8d4c..0d682e6df 100644
--- a/web/src/locales/zh-Hant.json
+++ b/web/src/locales/zh-Hant.json
@@ -186,13 +186,31 @@
"exit-focus-mode": "退出專注模式",
"focus-mode": "專注模式",
"insert-menu": {
+ "add-attachment": "新增附件",
"add-location": "新增位置",
+ "image-upload-failed": "部分圖片上傳失敗,請重試或將已上傳檔案保留為附件。",
+ "image-upload-stopped": "圖片上傳已暫停 {{completed}}/{{total}}",
+ "insert-image": "插入圖片",
+ "keep-as-attachments": "保留為附件",
"link-memo": "連結備忘錄",
+ "retry-image-upload": "重試",
+ "uploading-inline-image": "正在上傳到正文",
+ "uploading-images": "正在上傳圖片 {{completed}}/{{total}}",
"upload-file": "上傳文件"
},
"no-changes-detected": "未發現變更",
"save": "儲存",
"saving": "儲存中...",
+ "validation": {
+ "cannot-save": "無法儲存",
+ "content-required": "需要填寫正文或新增附件",
+ "finish-audio-recording": "請先完成錄音再儲存",
+ "loading-content": "正在載入備忘錄內容",
+ "resolve-image-uploads": "請先處理未完成的圖片上傳",
+ "save-in-progress": "正在儲存",
+ "unsupported-attachment-image-url": "不支援的附件圖片網址:{{url}}",
+ "wait-for-upload": "請等待上傳完成"
+ },
"audio-recorder": {
"attachment-label": "錄音",
"attachment-label-with-time": "錄音 {{time}}",
diff --git a/web/src/utils/managed-attachment.ts b/web/src/utils/managed-attachment.ts
new file mode 100644
index 000000000..336264f68
--- /dev/null
+++ b/web/src/utils/managed-attachment.ts
@@ -0,0 +1,255 @@
+import type { Definition, Html, Image, ImageReference, Root } from "mdast";
+import { fromMarkdown } from "mdast-util-from-markdown";
+import { gfmFromMarkdown } from "mdast-util-gfm";
+import { gfm } from "micromark-extension-gfm";
+import { normalizeIdentifier } from "micromark-util-normalize-identifier";
+import { visit } from "unist-util-visit";
+import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
+import { getAttachmentMotionGroupId, getAttachmentUrl, isImage } from "@/utils/attachment";
+
+const ATTACHMENT_NAME_PREFIX = "attachments/";
+const MANAGED_ATTACHMENT_PATH_PREFIX = "/file/attachments/";
+const UID_PATTERN = /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,34}[a-zA-Z0-9])?$/;
+
+interface ManagedImageNode {
+ uid: string;
+ start?: number;
+ end?: number;
+}
+
+interface ManagedImageIndex {
+ nodes: ManagedImageNode[];
+ uids: ReadonlySet<string>;
+ /** Destinations the server will reject on save (see `findInvalidManagedAttachmentReferences`). */
+ invalidReferences: readonly string[];
+}
+
+/**
+ * Mirrors the server's three-way classification in `internal/markdown`: a URL is
+ * either none of our business, a managed reference, or a managed reference the
+ * API refuses. Collapsing the last two would leave the editor unable to warn
+ * about content that cannot be saved.
+ */
+type ManagedImageURL = { kind: "unmanaged" } | { kind: "invalid" } | { kind: "managed"; uid: string };
+
+const UNMANAGED: ManagedImageURL = { kind: "unmanaged" };
+const INVALID: ManagedImageURL = { kind: "invalid" };
+
+const parseMarkdown = (source: string): Root =>
+ fromMarkdown(source, {
+ extensions: [gfm()],
+ mdastExtensions: [gfmFromMarkdown()],
+ });
+
+export const extractAttachmentUIDFromName = (name: string): string | undefined => {
+ if (!name.startsWith(ATTACHMENT_NAME_PREFIX)) return undefined;
+ const uid = name.slice(ATTACHMENT_NAME_PREFIX.length);
+ return UID_PATTERN.test(uid) ? uid : undefined;
+};
+
+// The API resolves absolute managed URLs against the configured instance URL, not
+// against whatever host the browser happens to be on, so the client has to know
+// the same value or the two disagree about which attachments are inline.
+let instanceOrigin: string | undefined;
+let instanceHost: string | undefined;
+
+/** Publishes the instance profile's URL to this module; clears the parse cache since results depend on it. */
+export const setManagedAttachmentInstanceUrl = (instanceUrl: string | undefined): void => {
+ let nextOrigin: string | undefined;
+ let nextHost: string | undefined;
+ if (instanceUrl?.trim()) {
+ try {
+ const parsed = new URL(instanceUrl.trim());
+ nextOrigin = parsed.origin;
+ nextHost = parsed.host;
+ } catch {
+ // A malformed instance URL is a server-side misconfiguration; treat it as unset.
+ }
+ }
+ if (nextOrigin === instanceOrigin && nextHost === instanceHost) return;
+ instanceOrigin = nextOrigin;
+ instanceHost = nextHost;
+ indexCache.clear();
+};
+
+const hasScheme = (raw: string): boolean => /^[a-z][a-z0-9+.-]*:/i.test(raw);
+
+/**
+ * Classifies an image destination the way the memo API does. Stored Markdown is
+ * expected to be origin-independent; an absolute URL is only a managed reference
+ * when it matches the configured instance URL, and is rejected outright when no
+ * instance URL is configured.
+ */
+export const classifyManagedAttachmentImageURL = (raw: string): ManagedImageURL => {
+ // The API accepts only root-relative managed paths. Do not let URL
+ // normalization turn `file/attachments/...` into a different contract.
+ if (!raw.startsWith("/") && !hasScheme(raw)) return UNMANAGED;
+
+ let parsed: URL;
+ try {
+ parsed = new URL(raw, window.location.origin);
+ } catch {
+ return UNMANAGED;
+ }
+ if (!parsed.pathname.startsWith(MANAGED_ATTACHMENT_PATH_PREFIX)) return UNMANAGED;
+
+ const isProtocolRelative = raw.startsWith("//");
+ if (isProtocolRelative) {
+ // Rejected whenever it could address this instance; otherwise it is someone else's URL.
+ return !instanceHost || parsed.host === instanceHost ? INVALID : UNMANAGED;
+ }
+ if (hasScheme(raw)) {
+ if (!instanceOrigin) return INVALID;
+ if (parsed.origin !== instanceOrigin) return UNMANAGED;
+ }
+
+ if (parsed.search || parsed.hash || parsed.pathname.includes("%")) return INVALID;
+
+ const parts = parsed.pathname.slice(MANAGED_ATTACHMENT_PATH_PREFIX.length).split("/");
+ if ((parts.length !== 1 && parts.length !== 2) || !UID_PATTERN.test(parts[0] ?? "") || (parts.length === 2 && !parts[1])) {
+ return INVALID;
+ }
+ return { kind: "managed", uid: parts[0]! };
+};
+
+export const parseManagedAttachmentImageURL = (raw: string): string | undefined => {
+ const classified = classifyManagedAttachmentImageURL(raw);
+ return classified.kind === "managed" ? classified.uid : undefined;
+};
+
+const EMPTY_INDEX: ManagedImageIndex = { nodes: [], uids: new Set(), invalidReferences: [] };
+/**
+ * Memo bodies are re-scanned on hot paths (every editor keystroke, every card
+ * relayout, every render of a memo view), so the mdast parse is cached by source
+ * text. The cache is bounded and also keeps the derived `uids` set referentially
+ * stable, which is what lets callers memoize on it.
+ */
+const INDEX_CACHE_LIMIT = 128;
+const indexCache = new Map<string, ManagedImageIndex>();
+
+const buildManagedImageIndex = (source: string): ManagedImageIndex => {
+ const tree = parseMarkdown(source);
+ const definitions = new Map<string, string>();
+ visit(tree, "definition", (node: Definition) => {
+ const identifier = normalizeIdentifier(node.identifier);
+ // CommonMark and the API's Goldmark parser resolve duplicate definitions
+ // to the first occurrence, so the client must not overwrite it here.
+ if (!definitions.has(identifier)) definitions.set(identifier, node.url);
+ });
+
+ const nodes: ManagedImageNode[] = [];
+ const invalidReferences: string[] = [];
+ visit(tree, (node) => {
+ // The API accepts managed URLs only through Markdown image nodes and rejects
+ // any raw HTML mentioning the route, rather than running a second HTML parser.
+ if (node.type === "html") {
+ const raw = (node as Html).value;
+ if (raw.includes(MANAGED_ATTACHMENT_PATH_PREFIX)) invalidReferences.push(raw);
+ return;
+ }
+
+ let destination: string | undefined;
+ if (node.type === "image") {
+ destination = (node as Image).url;
+ } else if (node.type === "imageReference") {
+ destination = definitions.get(normalizeIdentifier((node as ImageReference).identifier));
+ }
+ if (!destination) return;
+
+ const classified = classifyManagedAttachmentImageURL(destination);
+ if (classified.kind === "invalid") {
+ invalidReferences.push(destination);
+ return;
+ }
+ if (classified.kind !== "managed") return;
+ nodes.push({ uid: classified.uid, start: node.position?.start.offset, end: node.position?.end.offset });
+ });
+ return { nodes, uids: new Set(nodes.map((node) => node.uid)), invalidReferences };
+};
+
+const managedImageIndex = (source: string): ManagedImageIndex => {
+ if (!source.includes(MANAGED_ATTACHMENT_PATH_PREFIX)) return EMPTY_INDEX;
+
+ const cached = indexCache.get(source);
+ if (cached) return cached;
+
+ const index = buildManagedImageIndex(source);
+ if (indexCache.size >= INDEX_CACHE_LIMIT) indexCache.delete(indexCache.keys().next().value!);
+ indexCache.set(source, index);
+ return index;
+};
+
+export const extractManagedAttachmentUIDs = (source: string): ReadonlySet<string> => managedImageIndex(source).uids;
+
+/**
+ * Managed image URLs the API will reject (`InvalidArgument`) if this content is
+ * saved — a query or fragment on the route, percent-encoding, a malformed UID, a
+ * protocol-relative or unrecognized absolute URL, or a raw HTML `<img>`.
+ */
+export const findInvalidManagedAttachmentReferences = (source: string): readonly string[] => managedImageIndex(source).invalidReferences;
+
+const escapeMarkdownAlt = (value: string): string => value.replace(/\\/g, "\\\\").replace(/\[/g, "\\[").replace(/]/g, "\\]");
+
+const filenameStem = (filename: string): string => {
+ const normalized = filename.replace(/[\r\n]+/g, " ").trim();
+ const lastDot = normalized.lastIndexOf(".");
+ return lastDot > 0 ? normalized.slice(0, lastDot) : normalized || "image";
+};
+
+export const buildManagedAttachmentMarkdown = (attachment: Attachment): string => {
+ const uid = extractAttachmentUIDFromName(attachment.name);
+ if (!uid) throw new Error(`Invalid attachment resource name: ${attachment.name}`);
+ return `![${escapeMarkdownAlt(filenameStem(attachment.filename))}](${MANAGED_ATTACHMENT_PATH_PREFIX}${uid})`;
+};
+
+/** Whether an attachment can be referenced inline; mirrors the server-side rule for managed images. */
+export const canInlineAttachment = (attachment: Attachment): boolean => isImage(attachment.type) && !attachment.externalLink;
+
+export const removeManagedAttachmentReferences = (source: string, uids: ReadonlySet<string>): string => {
+ const ranges = managedImageIndex(source)
+ .nodes.filter((node) => uids.has(node.uid) && node.start !== undefined && node.end !== undefined)
+ .map((node) => ({ start: node.start!, end: node.end! }))
+ .sort((left, right) => right.start - left.start);
+
+ let result = source;
+ for (const range of ranges) {
+ const lineStart = result.lastIndexOf("\n", range.start - 1) + 1;
+ const nextNewline = result.indexOf("\n", range.end);
+ const lineEnd = nextNewline === -1 ? result.length : nextNewline;
+ const before = result.slice(lineStart, range.start);
+ const after = result.slice(range.end, lineEnd);
+ const removeWholeLine = before.trim() === "" && after.trim() === "";
+ const start = removeWholeLine ? lineStart : range.start;
+ let end = removeWholeLine && nextNewline !== -1 ? nextNewline + 1 : removeWholeLine ? lineEnd : range.end;
+ if (removeWholeLine && result.slice(0, start).endsWith("\n\n") && result.startsWith("\n", end)) end += 1;
+ result = result.slice(0, start) + result.slice(end);
+ }
+ return result;
+};
+
+export const filterInlineManagedAttachments = (content: string, attachments: Attachment[]): Attachment[] => {
+ const referencedUIDs = extractManagedAttachmentUIDs(content);
+ if (referencedUIDs.size === 0) return attachments;
+
+ const inlineGroups = new Set<string>();
+ const inlineNames = new Set<string>();
+ for (const attachment of attachments) {
+ const uid = extractAttachmentUIDFromName(attachment.name);
+ if (!uid || !referencedUIDs.has(uid)) continue;
+ inlineNames.add(attachment.name);
+ const groupID = getAttachmentMotionGroupId(attachment);
+ if (groupID) inlineGroups.add(groupID);
+ }
+
+ return attachments.filter(
+ (attachment) => !inlineNames.has(attachment.name) && !inlineGroups.has(getAttachmentMotionGroupId(attachment) ?? ""),
+ );
+};
+
+export const resolveManagedAttachmentImageSource = (source: string | undefined, attachments: Attachment[]): string | undefined => {
+ if (!source) return source;
+ const uid = parseManagedAttachmentImageURL(source);
+ if (!uid) return source;
+ const attachment = attachments.find((candidate) => extractAttachmentUIDFromName(candidate.name) === uid);
+ return attachment ? getAttachmentUrl(attachment) : source;
+};
diff --git a/web/tests/attachment-inline-placement.test.tsx b/web/tests/attachment-inline-placement.test.tsx
new file mode 100644
index 000000000..5d780a743
--- /dev/null
+++ b/web/tests/attachment-inline-placement.test.tsx
@@ -0,0 +1,108 @@
+import { create } from "@bufbuild/protobuf";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import AttachmentListEditor from "@/components/MemoMetadata/Attachment/AttachmentListEditor";
+import { AttachmentSchema } from "@/types/proto/api/v1/attachment_service_pb";
+
+const image = create(AttachmentSchema, {
+ name: "attachments/photo",
+ filename: "photo.png",
+ type: "image/png",
+ size: 128n,
+});
+
+beforeAll(() => {
+ Object.defineProperty(window, "matchMedia", {
+ writable: true,
+ value: () => ({
+ matches: false,
+ addEventListener: () => undefined,
+ removeEventListener: () => undefined,
+ }),
+ });
+});
+
+describe("attachment inline placement actions", () => {
+ it("offers insertion for an attachment-only image", () => {
+ const onInsertAttachments = vi.fn();
+ render(
+ <AttachmentListEditor
+ attachments={[image]}
+ inlineAttachmentUIDs={new Set()}
+ onAttachmentsChange={vi.fn()}
+ onInsertAttachments={onInsertAttachments}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Insert image" }));
+ expect(onInsertAttachments).toHaveBeenCalledWith([image]);
+ expect(screen.getByRole("button", { name: "Remove attachment" })).toBeInTheDocument();
+ });
+
+ it("hides an inline image and restores it after its Markdown reference is removed", () => {
+ const props = {
+ attachments: [image],
+ onAttachmentsChange: vi.fn(),
+ };
+ const { rerender } = render(<AttachmentListEditor {...props} inlineAttachmentUIDs={new Set(["photo"])} />);
+
+ expect(screen.queryByText("Attachments")).not.toBeInTheDocument();
+ expect(screen.queryByText("photo.png")).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Remove attachment" })).not.toBeInTheDocument();
+
+ rerender(<AttachmentListEditor {...props} inlineAttachmentUIDs={new Set()} />);
+
+ expect(screen.getByText(/Attachments/)).toBeInTheDocument();
+ expect(screen.getByText("photo.png")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Remove attachment" })).toBeInTheDocument();
+ });
+
+ it("preserves hidden inline attachments when visible attachments are reordered", () => {
+ const second = create(AttachmentSchema, { ...image, name: "attachments/second", filename: "second.png" });
+ const third = create(AttachmentSchema, { ...image, name: "attachments/third", filename: "third.png" });
+ const onAttachmentsChange = vi.fn();
+ render(
+ <AttachmentListEditor
+ attachments={[image, second, third]}
+ inlineAttachmentUIDs={new Set(["photo"])}
+ onAttachmentsChange={onAttachmentsChange}
+ />,
+ );
+
+ fireEvent.click(screen.getAllByRole("button", { name: "Move attachment down" })[0]!);
+ expect(onAttachmentsChange).toHaveBeenCalledWith([image, third, second]);
+ });
+
+ it("does not offer inline placement for external images", () => {
+ render(
+ <AttachmentListEditor
+ attachments={[create(AttachmentSchema, { ...image, externalLink: "https://example.com/photo.png" })]}
+ onAttachmentsChange={vi.fn()}
+ />,
+ );
+
+ expect(screen.queryByRole("button", { name: "Insert image" })).not.toBeInTheDocument();
+ });
+
+ it("shows local inline-upload status and prevents removal while uploading", () => {
+ const localImage = {
+ file: new File(["image"], "local.png", { type: "image/png" }),
+ previewUrl: "blob:local",
+ origin: "upload" as const,
+ };
+ render(
+ <AttachmentListEditor
+ attachments={[]}
+ localFiles={[localImage]}
+ uploadingLocalFileURLs={new Set([localImage.previewUrl])}
+ onLocalFilesChange={vi.fn()}
+ onInsertLocalFiles={vi.fn()}
+ placementActionsDisabled
+ />,
+ );
+
+ expect(screen.getByText("Uploading to content")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Insert image" })).toBeDisabled();
+ expect(screen.queryByRole("button", { name: "Remove attachment" })).not.toBeInTheDocument();
+ });
+});
diff --git a/web/tests/editor-inline-image-validation.test.ts b/web/tests/editor-inline-image-validation.test.ts
new file mode 100644
index 000000000..1c6d5d2c9
--- /dev/null
+++ b/web/tests/editor-inline-image-validation.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, test } from "vitest";
+import { validationService } from "@/components/MemoEditor/services/validationService";
+import { createInitialState } from "@/components/MemoEditor/state";
+
+describe("inline image editor validation", () => {
+ test("blocks saving while an inline image insertion is unresolved", () => {
+ const state = createInitialState();
+ state.content = "memo";
+ state.ui.pendingInlineImageInsertions = 1;
+
+ expect(validationService.canSave(state)).toEqual({
+ valid: false,
+ reason: "editor.validation.resolve-image-uploads",
+ });
+ });
+
+ test("allows saving after the insertion is resolved", () => {
+ const state = createInitialState();
+ state.content = "memo";
+
+ expect(validationService.canSave(state)).toEqual({ valid: true });
+ });
+});
diff --git a/web/tests/editor-upload-anchor.test.ts b/web/tests/editor-upload-anchor.test.ts
new file mode 100644
index 000000000..bce8eab8c
--- /dev/null
+++ b/web/tests/editor-upload-anchor.test.ts
@@ -0,0 +1,73 @@
+import { EditorState } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import { describe, expect, it, vi } from "vitest";
+import { createController } from "@/components/MemoEditor/Editor/controller";
+import { type UploadAnchorDescriptor, uploadAnchorField } from "@/components/MemoEditor/Editor/uploadAnchors";
+
+const descriptor = (id: string): UploadAnchorDescriptor => ({
+ id,
+ status: "uploading",
+ completed: 0,
+ total: 1,
+ message: "Uploading images 0/1",
+ retryLabel: "Retry",
+ keepLabel: "Keep as attachments",
+ onRetry: vi.fn(),
+ onKeepAttachments: vi.fn(),
+});
+
+const view = (doc = "") => new EditorView({ state: EditorState.create({ doc, extensions: [uploadAnchorField] }) });
+
+describe("editor upload anchors", () => {
+ it("maps the anchor through edits before resolving Markdown", () => {
+ const editorView = view("alpha");
+ const controller = createController(editorView, {} as never);
+ controller.setCursor(5);
+ controller.createUploadAnchor(descriptor("upload-one"));
+
+ editorView.dispatch({ changes: { from: 0, insert: "X" } });
+ controller.resolveUploadAnchor("upload-one", "![photo](/file/attachments/photo)");
+
+ expect(controller.getMarkdown()).toBe("Xalpha\n\n![photo](/file/attachments/photo)");
+ expect(editorView.dom.querySelector(".cm-upload-anchor")).toBeNull();
+ });
+
+ it("cancels an anchor without changing serialized Markdown", () => {
+ const editorView = view("alpha");
+ const controller = createController(editorView, {} as never);
+ controller.createUploadAnchor(descriptor("upload-two"), 2);
+ expect(editorView.dom.querySelector(".cm-upload-anchor")).not.toBeNull();
+
+ controller.cancelUploadAnchor("upload-two");
+
+ expect(controller.getMarkdown()).toBe("alpha");
+ expect(editorView.dom.querySelector(".cm-upload-anchor")).toBeNull();
+ });
+
+ // The buttons that reach insertMarkdown live outside the editor, and CodeMirror
+ // keeps its selection across blur, so an insert must not consume the range.
+ it("inserts at the caret without replacing the selection", () => {
+ const editorView = view("keep this paragraph of text");
+ const controller = createController(editorView, {} as never);
+ editorView.dispatch({ selection: { anchor: 5, head: 19 } });
+
+ controller.insertMarkdown("![photo](/file/attachments/photo)");
+
+ expect(controller.getMarkdown()).toBe("keep this paragraph\n\n![photo](/file/attachments/photo)\n\n of text");
+ });
+
+ it("re-renders the anchor when only its labels or callbacks change", () => {
+ const editorView = view("alpha");
+ const controller = createController(editorView, {} as never);
+ const stale = vi.fn();
+ controller.createUploadAnchor({ ...descriptor("upload-three"), status: "failed", onRetry: stale });
+
+ const fresh = vi.fn();
+ controller.updateUploadAnchor({ ...descriptor("upload-three"), status: "failed", message: "Retrying soon", onRetry: fresh });
+
+ expect(editorView.dom.querySelector(".cm-upload-anchor-badge")?.textContent).toBe("Retrying soon");
+ editorView.dom.querySelector<HTMLButtonElement>(".cm-upload-anchor-action")?.click();
+ expect(fresh).toHaveBeenCalledTimes(1);
+ expect(stale).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/tests/inline-image-upload-files.test.ts b/web/tests/inline-image-upload-files.test.ts
new file mode 100644
index 000000000..17017f91f
--- /dev/null
+++ b/web/tests/inline-image-upload-files.test.ts
@@ -0,0 +1,42 @@
+import { create } from "@bufbuild/protobuf";
+import { describe, expect, it } from "vitest";
+import { pairAppleLivePhotoFiles } from "@/components/MemoEditor/hooks";
+import { splitInlineLocalFiles } from "@/components/MemoEditor/hooks/useInlineImageUpload";
+import type { LocalFile } from "@/components/MemoEditor/types/attachment";
+import { MotionMediaRole } from "@/types/proto/api/v1/attachment_service_pb";
+
+const localFile = (name: string, type: string): LocalFile => ({
+ file: new File([name], name, { type }),
+ previewUrl: `blob:${name}`,
+ origin: "upload",
+});
+
+describe("inline image file routing", () => {
+ it("routes images inline and keeps non-images as attachments", () => {
+ const image = localFile("photo.png", "image/png");
+ const document = localFile("notes.pdf", "application/pdf");
+ expect(splitInlineLocalFiles([image, document])).toMatchObject({
+ inline: [image],
+ representativeIndexes: [0],
+ attachments: [document],
+ });
+ });
+
+ it("keeps both halves of an Apple Live Photo in the inline upload", () => {
+ const still = localFile("IMG_0001.HEIC", "image/heic");
+ const video = localFile("IMG_0001.MOV", "video/quicktime");
+ const paired = pairAppleLivePhotoFiles([still, video]);
+ const result = splitInlineLocalFiles(paired);
+
+ expect(result.inline).toHaveLength(2);
+ expect(result.attachments).toHaveLength(0);
+ expect(result.inline.map((file) => file.motionMedia?.role)).toEqual([MotionMediaRole.STILL, MotionMediaRole.VIDEO]);
+ // The still is what the inline Markdown reference is written for.
+ expect(result.representativeIndexes).toEqual([0]);
+ });
+
+ it("does not treat PSD files as renderable inline images", () => {
+ const psd = localFile("design.psd", "image/vnd.adobe.photoshop");
+ expect(splitInlineLocalFiles([psd])).toMatchObject({ inline: [], representativeIndexes: [], attachments: [psd] });
+ });
+});
diff --git a/web/tests/insert-menu.test.tsx b/web/tests/insert-menu.test.tsx
new file mode 100644
index 000000000..bcdf6a26c
--- /dev/null
+++ b/web/tests/insert-menu.test.tsx
@@ -0,0 +1,99 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { beforeAll, describe, expect, test, vi } from "vitest";
+import { createInitialState, EditorProvider } from "@/components/MemoEditor/state";
+import { EditorToolbar } from "@/components/MemoEditor/Toolbar/EditorToolbar";
+import InsertMenu from "@/components/MemoEditor/Toolbar/InsertMenu";
+
+vi.mock("@/utils/i18n", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/utils/i18n")>()),
+ useTranslate: () => (key: string) => key,
+}));
+vi.mock("@/hooks/useCurrentUser", () => ({ default: () => undefined }));
+vi.mock("@/components/map/useReverseGeocoding", () => ({ useReverseGeocoding: () => ({ data: undefined }) }));
+
+beforeAll(() => {
+ Element.prototype.scrollIntoView = vi.fn();
+ Element.prototype.hasPointerCapture = vi.fn(() => false);
+ Element.prototype.setPointerCapture = vi.fn();
+ Element.prototype.releasePointerCapture = vi.fn();
+});
+
+const renderMenu = (onInsertImages = vi.fn(), isSaving = false) =>
+ render(
+ <EditorProvider>
+ <InsertMenu
+ isSaving={isSaving}
+ onLocationChange={vi.fn()}
+ onInsertImages={onInsertImages}
+ onAudioRecorderClick={vi.fn()}
+ isFormattingToolbarVisible={false}
+ />
+ </EditorProvider>,
+ );
+
+describe("InsertMenu", () => {
+ test("shows attachment and inline-image actions in the intended order", () => {
+ renderMenu();
+ const trigger = screen.getByRole("button", { name: "common.add" });
+ expect(trigger).toHaveAttribute("tabindex", "0");
+
+ fireEvent.click(trigger);
+
+ expect(screen.getAllByRole("menuitem").map((item) => item.textContent)).toEqual([
+ "editor.insert-menu.add-attachment",
+ "editor.insert-menu.insert-image",
+ "editor.audio-recorder.trigger",
+ "editor.insert-menu.link-memo",
+ "editor.insert-menu.add-location",
+ "editor.focus-mode",
+ "editor.formatting-toolbar",
+ ]);
+ });
+
+ test("uses separate unrestricted and multi-image file inputs", () => {
+ const onInsertImages = vi.fn();
+ const { container } = renderMenu(onInsertImages);
+ const inputs = Array.from(container.querySelectorAll<HTMLInputElement>('input[type="file"]'));
+ const attachmentInput = inputs.find((input) => input.accept === "");
+ const inlineImageInput = inputs.find((input) => input.accept === "image/*");
+
+ expect(attachmentInput).toBeDefined();
+ expect(attachmentInput).toHaveAttribute("multiple");
+ expect(inlineImageInput).toBeDefined();
+ expect(inlineImageInput).toHaveAttribute("multiple");
+
+ const image = new File(["image"], "photo.png", { type: "image/png" });
+ fireEvent.change(inlineImageInput!, { target: { files: [image] } });
+ expect(onInsertImages).toHaveBeenCalledWith([image]);
+ });
+
+ test("disables insertion controls while saving", () => {
+ const { container } = renderMenu(vi.fn(), true);
+
+ expect(screen.getByRole("button", { name: "common.add" })).toBeDisabled();
+ for (const input of container.querySelectorAll('input[type="file"]')) {
+ expect(input).toBeDisabled();
+ }
+ });
+
+ test("exposes a localized save-blocking reason from a focusable wrapper", () => {
+ const state = createInitialState();
+ state.content = "memo";
+ state.ui.pendingInlineImageInsertions = 1;
+
+ render(
+ <EditorProvider initialEditorState={state}>
+ <EditorToolbar
+ onSave={vi.fn()}
+ onAudioRecorderClick={vi.fn()}
+ isFormattingToolbarVisible={false}
+ onToggleFormattingToolbar={vi.fn()}
+ onInsertImages={vi.fn()}
+ />
+ </EditorProvider>,
+ );
+
+ expect(screen.getByRole("button", { name: "editor.save" })).toBeDisabled();
+ expect(screen.getByLabelText("editor.validation.resolve-image-uploads")).toHaveAttribute("tabindex", "0");
+ });
+});
diff --git a/web/tests/managed-attachment.test.ts b/web/tests/managed-attachment.test.ts
new file mode 100644
index 000000000..28c0933c3
--- /dev/null
+++ b/web/tests/managed-attachment.test.ts
@@ -0,0 +1,158 @@
+import { create } from "@bufbuild/protobuf";
+import { afterEach, describe, expect, it } from "vitest";
+import { AttachmentSchema, MotionMediaFamily, MotionMediaRole, MotionMediaSchema } from "@/types/proto/api/v1/attachment_service_pb";
+import {
+ buildManagedAttachmentMarkdown,
+ extractManagedAttachmentUIDs,
+ filterInlineManagedAttachments,
+ findInvalidManagedAttachmentReferences,
+ parseManagedAttachmentImageURL,
+ removeManagedAttachmentReferences,
+ resolveManagedAttachmentImageSource,
+ setManagedAttachmentInstanceUrl,
+} from "@/utils/managed-attachment";
+
+const attachment = (name: string, filename = "photo.png", externalLink = "") =>
+ create(AttachmentSchema, { name, filename, type: "image/png", externalLink });
+
+afterEach(() => setManagedAttachmentInstanceUrl(undefined));
+
+describe("managed attachment Markdown", () => {
+ it("builds canonical URLs and escapes filename alt text", () => {
+ expect(buildManagedAttachmentMarkdown(attachment("attachments/image-one", "garden[west]\\view.png"))).toBe(
+ "![garden\\[west\\]\\\\view](/file/attachments/image-one)",
+ );
+ });
+
+ it("extracts canonical, legacy, and reference-style images", () => {
+ const content = [
+ "![one](/file/attachments/image-one)",
+ "![two](/file/attachments/image-two/photo.png)",
+ "![three][photo]",
+ "[photo]: /file/attachments/image-three",
+ "`![code](/file/attachments/code-image)`",
+ "```md\n![fenced](/file/attachments/fenced-image)\n```",
+ ].join("\n\n");
+
+ expect(Array.from(extractManagedAttachmentUIDs(content))).toEqual(["image-one", "image-two", "image-three"]);
+ expect(findInvalidManagedAttachmentReferences(content)).toEqual([]);
+ });
+
+ it("uses the first duplicate reference definition like Goldmark", () => {
+ const content = [
+ "![photo][asset]",
+ "[asset]: /file/attachments/first-image",
+ "[asset]: /file/attachments/second-image",
+ ].join("\n\n");
+
+ expect(Array.from(extractManagedAttachmentUIDs(content))).toEqual(["first-image"]);
+ });
+
+ it("does not normalize path-relative images into managed attachment URLs", () => {
+ const source = "file/attachments/image-one";
+
+ expect(parseManagedAttachmentImageURL(source)).toBeUndefined();
+ expect(extractManagedAttachmentUIDs(`![image](${source})`)).toEqual(new Set());
+ expect(resolveManagedAttachmentImageSource(source, [attachment("attachments/image-one")])).toBe(source);
+ });
+
+ // The API matches absolute URLs against the configured instance URL, not the
+ // browsing origin, and rejects them outright when no instance URL is set.
+ it("resolves absolute images against the configured instance URL", () => {
+ setManagedAttachmentInstanceUrl("https://memos.example.com");
+ const content = [
+ "![configured](https://memos.example.com/file/attachments/image-one)",
+ `![browsing-host](${window.location.origin}/file/attachments/image-two)`,
+ "![elsewhere](https://example.com/file/attachments/image-three)",
+ ].join("\n\n");
+
+ expect(Array.from(extractManagedAttachmentUIDs(content))).toEqual(["image-one"]);
+ expect(findInvalidManagedAttachmentReferences(content)).toEqual([]);
+ });
+
+ // Matches the API, which errors on any absolute URL under the managed route
+ // when it has no instance URL to compare against — whoever hosts it.
+ it("rejects absolute images when no instance URL is configured", () => {
+ const own = `${window.location.origin}/file/attachments/image-one`;
+ const content = [`![own](${own})`, "![elsewhere](https://example.com/file/attachments/image-two)"].join("\n\n");
+
+ expect(extractManagedAttachmentUIDs(content)).toEqual(new Set());
+ expect(findInvalidManagedAttachmentReferences(content)).toEqual([own, "https://example.com/file/attachments/image-two"]);
+ });
+
+ it("reports raw HTML managed images as unsupported instead of ignoring them", () => {
+ const raw = '<img src="/file/attachments/html-image">';
+
+ expect(extractManagedAttachmentUIDs(raw)).toEqual(new Set());
+ expect(findInvalidManagedAttachmentReferences(raw)).toEqual([raw]);
+ // Code spans and fences are not raw HTML, so they stay out of the way.
+ expect(findInvalidManagedAttachmentReferences('`<img src="/file/attachments/html-image">`')).toEqual([]);
+ });
+
+ it("rejects encoded, protocol-relative, queried, and malformed managed paths", () => {
+ for (const url of [
+ "/file/attachments/%69mage",
+ "//localhost/file/attachments/image",
+ "/file/attachments/image?token=x",
+ "/file/attachments/image#fragment",
+ "/file/attachments/image/",
+ "/file/attachments/image/file/extra",
+ ]) {
+ expect(parseManagedAttachmentImageURL(url)).toBeUndefined();
+ expect(findInvalidManagedAttachmentReferences(`![x](${url})`)).toEqual([url]);
+ }
+ });
+
+ it("removes only matching image nodes and leaves code and other content intact", () => {
+ const content = [
+ "before",
+ "",
+ "![remove](/file/attachments/remove-me)",
+ "",
+ "keep ![other](/file/attachments/keep-me) here",
+ "",
+ "`![code](/file/attachments/remove-me)`",
+ ].join("\n");
+
+ expect(removeManagedAttachmentReferences(content, new Set(["remove-me"]))).toBe(
+ ["before", "", "keep ![other](/file/attachments/keep-me) here", "", "`![code](/file/attachments/remove-me)`"].join("\n"),
+ );
+ });
+
+ it("filters the entire motion group when its still image is inline", () => {
+ const motion = create(MotionMediaSchema, {
+ family: MotionMediaFamily.APPLE_LIVE_PHOTO,
+ role: MotionMediaRole.STILL,
+ groupId: "live-one",
+ });
+ const still = create(AttachmentSchema, { ...attachment("attachments/still"), motionMedia: motion });
+ const video = create(AttachmentSchema, {
+ name: "attachments/video",
+ filename: "photo.mov",
+ type: "video/quicktime",
+ motionMedia: create(MotionMediaSchema, { ...motion, role: MotionMediaRole.VIDEO }),
+ });
+ const regular = attachment("attachments/regular");
+
+ expect(filterInlineManagedAttachments("![still](/file/attachments/still)", [still, video, regular])).toEqual([regular]);
+ });
+
+ it("filters repeated references once and never hides an unrelated attachment", () => {
+ const own = attachment("attachments/own");
+ const content = [
+ "![foreign](/file/attachments/someone-elses-image)",
+ "![own](/file/attachments/own)",
+ "![own again](/file/attachments/own)",
+ ].join("\n\n");
+
+ expect(filterInlineManagedAttachments(content, [own, attachment("attachments/unrelated")])).toEqual([
+ attachment("attachments/unrelated"),
+ ]);
+ });
+
+ it("resolves managed image sources through attachment metadata", () => {
+ const shared = attachment("attachments/shared", "shared.png", `${window.location.origin}/file/attachments/shared?share_token=abc`);
+ expect(resolveManagedAttachmentImageSource("/file/attachments/shared", [shared])).toBe(shared.externalLink);
+ expect(resolveManagedAttachmentImageSource("https://example.com/image.png", [shared])).toBe("https://example.com/image.png");
+ });
+});
diff --git a/web/tests/memo-card-height.test.ts b/web/tests/memo-card-height.test.ts
index 8fea2fe93..936c6a260 100644
--- a/web/tests/memo-card-height.test.ts
+++ b/web/tests/memo-card-height.test.ts
@@ -1,8 +1,14 @@
import { create } from "@bufbuild/protobuf";
import { describe, expect, it } from "vitest";
import { estimateMemoCardHeight } from "@/components/PagedMemoList/memoCardHeight";
-import { AttachmentSchema, type Attachment } from "@/types/proto/api/v1/attachment_service_pb";
-import { MemoRelation_MemoSchema, MemoRelation_Type, MemoRelationSchema, MemoSchema, type Memo } from "@/types/proto/api/v1/memo_service_pb";
+import { type Attachment, AttachmentSchema } from "@/types/proto/api/v1/attachment_service_pb";
+import {
+ type Memo,
+ MemoRelation_MemoSchema,
+ MemoRelation_Type,
+ MemoRelationSchema,
+ MemoSchema,
+} from "@/types/proto/api/v1/memo_service_pb";
const buildAttachment = (overrides: Partial<Attachment>) =>
create(AttachmentSchema, {
@@ -46,6 +52,14 @@ describe("estimateMemoCardHeight", () => {
);
});
+ it("does not count an inline managed image again as an attachment gallery", () => {
+ const image = buildAttachment({ name: "attachments/image", filename: "image.png", type: "image/png" });
+ const inline = buildMemo({ content: "![image](/file/attachments/image)", attachments: [image] });
+ const external = buildMemo({ content: "![image](https://example.com/image.png)", attachments: [image] });
+
+ expect(estimateMemoCardHeight(inline, { columnWidth: 320 })).toBeLessThan(estimateMemoCardHeight(external, { columnWidth: 320 }));
+ });
+
it("estimates the visible comment preview height and caps it at three comments", () => {
const oneComment = buildMemo({ relations: [buildCommentRelation("memos/main", 1)] });
const threeComments = buildMemo({
diff --git a/web/tests/memo-editor-cache.test.ts b/web/tests/memo-editor-cache.test.ts
index d9a94af68..78f0ab998 100644
--- a/web/tests/memo-editor-cache.test.ts
+++ b/web/tests/memo-editor-cache.test.ts
@@ -1,5 +1,7 @@
+import { create } from "@bufbuild/protobuf";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cacheService } from "@/components/MemoEditor/services/cacheService";
+import { AttachmentSchema, MotionMediaFamily, MotionMediaRole, MotionMediaSchema } from "@/types/proto/api/v1/attachment_service_pb";
describe("memo editor cache", () => {
beforeEach(() => {
@@ -39,6 +41,40 @@ describe("memo editor cache", () => {
expect(cacheService.load(key)).toBe("- [ ] migrated task");
});
+ it("round-trips uploaded attachment metadata with a structured draft", () => {
+ const key = cacheService.key("users/steven", "home-memo-editor");
+ const attachment = create(AttachmentSchema, {
+ name: "attachments/image-one",
+ filename: "garden.png",
+ externalLink: "https://cdn.example.com/garden.png",
+ type: "image/png",
+ size: 42n,
+ motionMedia: create(MotionMediaSchema, {
+ family: MotionMediaFamily.APPLE_LIVE_PHOTO,
+ role: MotionMediaRole.STILL,
+ groupId: "live-one",
+ }),
+ });
+
+ cacheService.saveNow(key, "![garden](/file/attachments/image-one)", [attachment]);
+
+ const restored = cacheService.loadDraft(key);
+ expect(restored.content).toBe("![garden](/file/attachments/image-one)");
+ expect(restored.attachments).toHaveLength(1);
+ expect(restored.attachments[0]).toMatchObject({
+ name: "attachments/image-one",
+ filename: "garden.png",
+ externalLink: "https://cdn.example.com/garden.png",
+ type: "image/png",
+ size: 42n,
+ motionMedia: {
+ family: MotionMediaFamily.APPLE_LIVE_PHOTO,
+ role: MotionMediaRole.STILL,
+ groupId: "live-one",
+ },
+ });
+ });
+
it("keeps raw JSON markdown drafts intact", () => {
const key = cacheService.key("users/steven", "home-memo-editor");
const jsonDraft = '{"content":"not a cache envelope"}';
diff --git a/web/tests/memo-editor-extensions.test.ts b/web/tests/memo-editor-extensions.test.ts
index dbbea7926..1cde9004f 100644
--- a/web/tests/memo-editor-extensions.test.ts
+++ b/web/tests/memo-editor-extensions.test.ts
@@ -57,17 +57,16 @@ describe("MemoEditor CodeMirror extensions", () => {
parent,
});
views.push(view);
+ view.dispatch({ selection: { anchor: 2 } });
const file = new File(["must not become memo content"], "attachment.txt", { type: "text/plain" });
const transfer =
- eventType === "paste"
- ? { items: [{ kind: "file", getAsFile: () => file }], files: [file] }
- : { files: [file], types: ["Files"] };
+ eventType === "paste" ? { items: [{ kind: "file", getAsFile: () => file }], files: [file] } : { files: [file], types: ["Files"] };
const event = new Event(eventType, { bubbles: true, cancelable: true });
Object.defineProperty(event, transferProperty, { value: transfer });
view.contentDOM.dispatchEvent(event);
- expect(onFiles).toHaveBeenCalledWith([file]);
+ expect(onFiles).toHaveBeenCalledWith([file], eventType === "paste" ? 2 : 0);
expect(event.defaultPrevented).toBe(true);
expect(view.state.doc.toString()).toBe("memo");
});
diff --git a/web/tests/memo-share-image.test.ts b/web/tests/memo-share-image.test.ts
index 8665f1cb9..bcb66d98d 100644
--- a/web/tests/memo-share-image.test.ts
+++ b/web/tests/memo-share-image.test.ts
@@ -10,8 +10,8 @@ import {
getMemoShareRenderWidth,
} from "@/components/MemoActionMenu/memoShareImage";
import { buildMemoShareImagePreviewModel } from "@/components/MemoActionMenu/memoShareImagePreviewModel";
-import { AttachmentSchema, type Attachment } from "@/types/proto/api/v1/attachment_service_pb";
-import { MemoSchema, type Memo } from "@/types/proto/api/v1/memo_service_pb";
+import { type Attachment, AttachmentSchema } from "@/types/proto/api/v1/attachment_service_pb";
+import { type Memo, MemoSchema } from "@/types/proto/api/v1/memo_service_pb";
vi.mock("html-to-image", () => ({
toBlob: vi.fn(),
@@ -88,6 +88,18 @@ describe("memo share image preview model", () => {
expect(model.footerBadges).toEqual([]);
});
+ it("does not repeat a managed inline image in the media grid", () => {
+ const memo = buildMemo({
+ content: "![image](/file/attachments/image)",
+ attachments: [buildAttachment({ name: "attachments/image", filename: "image.png", type: "image/png" })],
+ });
+
+ const model = buildPreviewModel(memo);
+
+ expect(model.visualItems).toEqual([]);
+ expect(model.footerBadges).toEqual([]);
+ });
+
it("counts mixed visual and non-visual attachments in the summary", () => {
const memo = buildMemo({
attachments: [
diff --git a/web/tests/use-auto-save.test.tsx b/web/tests/use-auto-save.test.tsx
index f96ded3f2..1bb41ac6f 100644
--- a/web/tests/use-auto-save.test.tsx
+++ b/web/tests/use-auto-save.test.tsx
@@ -1,8 +1,10 @@
+import { create } from "@bufbuild/protobuf";
import { act, render } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useAutoSave } from "@/components/MemoEditor/hooks/useAutoSave";
import { cacheService } from "@/components/MemoEditor/services/cacheService";
import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
+import { AttachmentSchema } from "@/types/proto/api/v1/attachment_service_pb";
// Probe surfaces the store's dispatch/actions plus the autosave API so tests can
// drive content changes the way the editor does and assert on cache writes.
@@ -45,7 +47,58 @@ describe("useAutoSave (store-subscribed)", () => {
act(() => {
api.dispatch(api.actions.updateContent("hello world"));
});
- expect(saveSpy).toHaveBeenCalledWith(key, "hello world");
+ expect(saveSpy).toHaveBeenCalledWith(key, "hello world", []);
+ });
+
+ it("persists uploaded attachments when editor metadata changes", () => {
+ render(
+ <EditorProvider>
+ <Probe username="users/steven" cacheKey="attachment-draft" enabled />
+ </EditorProvider>,
+ );
+ const key = cacheService.key("users/steven", "attachment-draft");
+ const image = create(AttachmentSchema, {
+ name: "attachments/image-one",
+ filename: "image.png",
+ type: "image/png",
+ });
+ saveSpy.mockClear();
+
+ act(() => {
+ api.dispatch(api.actions.setMetadata({ attachments: [image] }));
+ });
+
+ expect(saveSpy).toHaveBeenCalledWith(key, "", [image]);
+ });
+
+ it("persists metadata changes for an attachment with the same name", () => {
+ render(
+ <EditorProvider>
+ <Probe username="users/steven" cacheKey="attachment-update" enabled />
+ </EditorProvider>,
+ );
+ const key = cacheService.key("users/steven", "attachment-update");
+ const initial = create(AttachmentSchema, {
+ name: "attachments/image-one",
+ filename: "image.png",
+ type: "image/png",
+ });
+ const updated = create(AttachmentSchema, {
+ name: "attachments/image-one",
+ filename: "image.png",
+ type: "image/png",
+ externalLink: "https://cdn.example.com/image.png",
+ });
+
+ act(() => {
+ api.dispatch(api.actions.setMetadata({ attachments: [initial] }));
+ });
+ saveSpy.mockClear();
+ act(() => {
+ api.dispatch(api.actions.setMetadata({ attachments: [updated] }));
+ });
+
+ expect(saveSpy).toHaveBeenCalledWith(key, "", [updated]);
});
it("does not persist when disabled", () => {
diff --git a/web/tests/use-inline-image-upload.test.tsx b/web/tests/use-inline-image-upload.test.tsx
new file mode 100644
index 000000000..f3910cd4e
--- /dev/null
+++ b/web/tests/use-inline-image-upload.test.tsx
@@ -0,0 +1,120 @@
+import { create } from "@bufbuild/protobuf";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import type { PropsWithChildren, RefObject } from "react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { UploadAnchorDescriptor } from "@/components/MemoEditor/Editor/uploadAnchors";
+import { useInlineImageUpload } from "@/components/MemoEditor/hooks/useInlineImageUpload";
+import { uploadService } from "@/components/MemoEditor/services";
+import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
+import type { LocalFile } from "@/components/MemoEditor/types/attachment";
+import type { EditorController } from "@/components/MemoEditor/types/editorController";
+import { AttachmentSchema } from "@/types/proto/api/v1/attachment_service_pb";
+
+vi.mock("@/utils/i18n", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/utils/i18n")>()),
+ useTranslate: () => (key: string) => key,
+}));
+vi.mock("react-hot-toast", () => ({ toast: { error: vi.fn() } }));
+
+const wrapper = ({ children }: PropsWithChildren) => <EditorProvider>{children}</EditorProvider>;
+
+const localImage = (filename: string): LocalFile => ({
+ file: new File([filename], filename, { type: "image/png" }),
+ previewUrl: `blob:${filename}`,
+ origin: "upload",
+});
+
+const remoteImage = (uid: string, filename: string) =>
+ create(AttachmentSchema, {
+ name: `attachments/${uid}`,
+ filename,
+ type: "image/png",
+ });
+
+const makeController = () => {
+ const descriptors: UploadAnchorDescriptor[] = [];
+ const controller = {
+ createUploadAnchor: vi.fn((descriptor: UploadAnchorDescriptor) => descriptors.push(descriptor)),
+ updateUploadAnchor: vi.fn((descriptor: UploadAnchorDescriptor) => descriptors.push(descriptor)),
+ resolveUploadAnchor: vi.fn(),
+ cancelUploadAnchor: vi.fn(),
+ insertMarkdown: vi.fn(),
+ } as unknown as EditorController;
+ return { controller, descriptors };
+};
+
+describe("useInlineImageUpload", () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ test("inserts multiple uploaded images once and in selection order", async () => {
+ const first = remoteImage("first", "first.png");
+ const second = remoteImage("second", "second.png");
+ vi.spyOn(uploadService, "uploadFile").mockResolvedValueOnce(first).mockResolvedValueOnce(second);
+ const { controller } = makeController();
+ const editorRef = { current: controller } as RefObject<EditorController>;
+ const { result } = renderHook(() => useInlineImageUpload(editorRef), { wrapper });
+
+ act(() => result.current.insertLocalImages([localImage("first.png"), localImage("second.png")], 7));
+
+ await waitFor(() => expect(controller.resolveUploadAnchor).toHaveBeenCalledTimes(1));
+ expect(controller.createUploadAnchor).toHaveBeenCalledWith(expect.any(Object), 7);
+ expect(controller.resolveUploadAnchor).toHaveBeenCalledWith(
+ expect.any(String),
+ "![first](/file/attachments/first)\n\n![second](/file/attachments/second)",
+ );
+ });
+
+ test("retries only failed files and preserves their original placement", async () => {
+ const first = remoteImage("first", "first.png");
+ const second = remoteImage("second", "second.png");
+ const upload = vi
+ .spyOn(uploadService, "uploadFile")
+ .mockResolvedValueOnce(first)
+ .mockRejectedValueOnce(new Error("network"))
+ .mockResolvedValueOnce(second);
+ const { controller, descriptors } = makeController();
+ const editorRef = { current: controller } as RefObject<EditorController>;
+ const { result } = renderHook(() => useInlineImageUpload(editorRef), { wrapper });
+ const files = [localImage("first.png"), localImage("second.png")];
+
+ act(() => result.current.insertLocalImages(files));
+ await waitFor(() => expect(descriptors.at(-1)?.status).toBe("failed"));
+ expect(controller.resolveUploadAnchor).not.toHaveBeenCalled();
+
+ act(() => descriptors.at(-1)?.onRetry?.());
+ await waitFor(() => expect(controller.resolveUploadAnchor).toHaveBeenCalledTimes(1));
+
+ expect(upload).toHaveBeenCalledTimes(3);
+ expect(upload.mock.calls.map(([file]) => file.file.name)).toEqual(["first.png", "second.png", "second.png"]);
+ expect(controller.resolveUploadAnchor).toHaveBeenCalledWith(
+ expect.any(String),
+ "![first](/file/attachments/first)\n\n![second](/file/attachments/second)",
+ );
+ });
+
+ test("does not start local or remote insertion while a save is in progress", () => {
+ const upload = vi.spyOn(uploadService, "uploadFile");
+ const { controller } = makeController();
+ const editorRef = { current: controller } as RefObject<EditorController>;
+ const { result } = renderHook(
+ () => {
+ const inlineUpload = useInlineImageUpload(editorRef);
+ const editor = useEditorContext();
+ return { inlineUpload, editor };
+ },
+ { wrapper },
+ );
+
+ act(() => result.current.editor.dispatch(result.current.editor.actions.setLoading("saving", true)));
+ act(() => {
+ result.current.inlineUpload.insertLocalImages([localImage("late.png")]);
+ result.current.inlineUpload.insertRemoteImages([remoteImage("late", "late.png")]);
+ });
+
+ expect(upload).not.toHaveBeenCalled();
+ expect(controller.createUploadAnchor).not.toHaveBeenCalled();
+ expect(controller.insertMarkdown).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/tests/use-memo-init.test.tsx b/web/tests/use-memo-init.test.tsx
new file mode 100644
index 000000000..159dd82f0
--- /dev/null
+++ b/web/tests/use-memo-init.test.tsx
@@ -0,0 +1,62 @@
+import { create } from "@bufbuild/protobuf";
+import { render, waitFor } from "@testing-library/react";
+import type { RefObject } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useMemoInit } from "@/components/MemoEditor/hooks/useMemoInit";
+import { cacheService } from "@/components/MemoEditor/services/cacheService";
+import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
+import type { EditorController } from "@/components/MemoEditor/types/editorController";
+import { AttachmentSchema } from "@/types/proto/api/v1/attachment_service_pb";
+
+const editorRef = { current: null } as RefObject<EditorController | null>;
+let getEditorState: ReturnType<typeof useEditorContext>["getState"];
+
+function Probe() {
+ getEditorState = useEditorContext().getState;
+ useMemoInit({
+ editorRef,
+ username: "users/steven",
+ cacheKey: "restored-draft",
+ });
+ return null;
+}
+
+describe("useMemoInit", () => {
+ beforeEach(() => {
+ const storage = new Map<string, string>();
+ vi.stubGlobal("localStorage", {
+ getItem: vi.fn((key: string) => storage.get(key) ?? null),
+ setItem: vi.fn((key: string, value: string) => storage.set(key, value)),
+ removeItem: vi.fn((key: string) => storage.delete(key)),
+ });
+ cacheService.clearAll();
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("restores uploaded attachment bindings with a new memo draft", async () => {
+ const attachment = create(AttachmentSchema, {
+ name: "attachments/image-one",
+ filename: "image.png",
+ type: "image/png",
+ });
+ cacheService.saveNow(
+ cacheService.key("users/steven", "restored-draft"),
+ "![image](/file/attachments/image-one)",
+ [attachment],
+ );
+
+ render(
+ <EditorProvider>
+ <Probe />
+ </EditorProvider>,
+ );
+
+ await waitFor(() => {
+ expect(getEditorState().content).toBe("![image](/file/attachments/image-one)");
+ expect(getEditorState().metadata.attachments).toEqual([attachment]);
+ });
+ });
+});