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.

refactor(web): one memo component, MemoEditor, with view and edit modes (#6481)

boojack3bea6df0300a
diff --git a/AGENTS.md b/AGENTS.md
index 558dfe477..da12b67a7 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -122,6 +122,7 @@ Black-box service tests live in `server/api/test/`, unit tests next to the code.
- Use `@/` for absolute imports.
- Follow Biome formatting: 2-space indent, double quotes, semicolons, 140-character line width.
- Put server data in React Query hooks under `web/src/hooks/`; keep UI-only state in contexts or component state.
+- Show, edit and compose memos through `web/src/components/MemoEditor` (a name or draft seed plus a mode); see its `README.md`.
- Use Tailwind CSS v4 utilities, `cn()` for class merging, and CVA for variants.
- Reuse Base UI primitives and existing components before adding new UI primitives.
- Keep generated proto TypeScript under `web/src/types/proto/` out of manual edits and Biome rewrites.
diff --git a/web/package.json b/web/package.json
index e71284501..adfb40d02 100644
--- a/web/package.json
+++ b/web/package.json
@@ -25,7 +25,7 @@
"@tailwindcss/vite": "^4.2.4",
"@tanstack/react-query": "^5.100.9",
"@tanstack/react-query-devtools": "^5.100.9",
- "@usememos/editor": "26.10.16",
+ "@usememos/editor": "26.10.19",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"copy-to-clipboard": "^4.0.2",
diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml
index acbde7baa..e26b11909 100644
--- a/web/pnpm-lock.yaml
+++ b/web/pnpm-lock.yaml
@@ -36,8 +36,8 @@ importers:
specifier: ^5.100.9
'@usememos/editor':
- specifier: 26.10.16
+ specifier: 26.10.19
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
@@ -1135,8 +1135,8 @@ packages:
'@upsetjs/[email protected]':
resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==}
- '@usememos/[email protected]':
- resolution: {integrity: sha512-o8C4gObGaKT1rV0z6zzigreQSpSjB/NQuGyicm+pUsICKyjyXPPH8OmDecW44X3l6pv157MsFxWm4IXafSblvw==}
+ '@usememos/[email protected]':
+ resolution: {integrity: sha512-TgQkyVyC9Dpez/pZgm4hM8AFr9fKs429Xi/joMNNPSWkYlGLutJ1na57EkBdIiQpAhW2iYSgXcFc7W/g1PRC8w==}
peerDependencies:
react: '>=18'
react-dom: '>=18'
@@ -3262,7 +3262,7 @@ snapshots:
d3-selection: 3.0.0
d3-transition: 3.0.1([email protected])
optionalDependencies:
react: 19.2.6
react-dom: 19.2.6([email protected])
diff --git a/web/src/components/CalendarView/CalendarDayCell.tsx b/web/src/components/CalendarView/CalendarDayCell.tsx
index 6bf849331..8a232b5a9 100644
--- a/web/src/components/CalendarView/CalendarDayCell.tsx
+++ b/web/src/components/CalendarView/CalendarDayCell.tsx
@@ -5,9 +5,9 @@ import {
getActivityLevel,
getTooltipText,
} from "@/components/ActivityCalendar";
-import { useResolvedUser, useResolvedUsersByNames } from "@/components/MemoContent/MentionResolutionContext";
import UserAvatar from "@/components/UserAvatar";
import { FOCUS_VISIBLE_OUTLINE_CLASSES } from "@/components/ui/focus";
+import { useResolvedUser, useResolvedUsersByNames } from "@/contexts/MentionResolutionContext";
import type { MemoTimeBasis } from "@/contexts/ViewContext";
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
diff --git a/web/src/components/CalendarView/CalendarView.tsx b/web/src/components/CalendarView/CalendarView.tsx
index 1c805af9b..9f7c6989e 100644
--- a/web/src/components/CalendarView/CalendarView.tsx
+++ b/web/src/components/CalendarView/CalendarView.tsx
@@ -1,12 +1,12 @@
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useLocation, useNavigate } from "react-router-dom";
-import { MentionResolutionProvider } from "@/components/MemoContent/MentionResolutionContext";
-import { deriveDefaultCreateTimeFromDate } from "@/components/MemoEditor/utils/deriveDefaultCreateTime";
+import { deriveDefaultCreateTimeFromDate } from "@/components/MemoEditor/edit/utils/deriveDefaultCreateTime";
import { MEMO_PANEL_INSET, MEMO_PANEL_TITLE_CLASS, MEMO_PANEL_WIDTH_CSS, MemoPanel, MemoPanelList } from "@/components/MemoPanel";
import MemoListError from "@/components/PagedMemoList/MemoListError";
import { useAuth } from "@/contexts/AuthContext";
import { useInstance } from "@/contexts/InstanceContext";
+import { MentionResolutionProvider } from "@/contexts/MentionResolutionContext";
import { useSpaceContext } from "@/contexts/SpaceContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useFilteredMemoStats } from "@/hooks/useFilteredMemoStats";
@@ -125,9 +125,9 @@ export const CalendarView = ({ month, date }: CalendarViewProps) => {
compose={
canCompose
? {
- cacheKey: `calendar-day-editor:${activeDate}`,
+ scope: `calendar:${activeDate}`,
label: t("calendar.new-memo-on-day"),
- defaults: { defaultCreateTime },
+ defaults: { createTime: defaultCreateTime },
onSavingChange: setSaving,
}
: undefined
diff --git a/web/src/components/MapView/MapView.tsx b/web/src/components/MapView/MapView.tsx
index c8646ec2c..8764c1d7f 100644
--- a/web/src/components/MapView/MapView.tsx
+++ b/web/src/components/MapView/MapView.tsx
@@ -305,9 +305,9 @@ export function MapView() {
compose={
composeLocation && user && (!creatorUsername || creatorUsername === user.username)
? {
- cacheKey: `map-editor:${user?.name}:${selectedSpaceName ?? "all"}:${locationKey(composeLocation)}`,
+ scope: `map:${user?.name}:${selectedSpaceName ?? "all"}:${locationKey(composeLocation)}`,
label: t("map.new-here"),
- defaults: { defaultLocation: composeLocation },
+ defaults: { location: composeLocation },
onComposingChange: setComposing,
onSavingChange: setSaving,
onConfirm: (name) => void afterSave(name),
diff --git a/web/src/components/MemoActionMenu/MemoShareImagePreview.tsx b/web/src/components/MemoActionMenu/MemoShareImagePreview.tsx
index 5ff105497..e80b596ae 100644
--- a/web/src/components/MemoActionMenu/MemoShareImagePreview.tsx
+++ b/web/src/components/MemoActionMenu/MemoShareImagePreview.tsx
@@ -1,5 +1,5 @@
import { forwardRef, useMemo } from "react";
-import MemoContent from "@/components/MemoContent";
+import { MemoContentView } from "@/components/MemoEditor/view/MemoContentView";
import UserAvatar from "@/components/UserAvatar";
import i18n from "@/i18n";
import { cn } from "@/lib/utils";
@@ -39,7 +39,7 @@ const MemoShareImagePreview = forwardRef<HTMLDivElement, { width: number }>(({ w
<div className="mt-4">
<div className={cn("pointer-events-none", blurred && !showBlurredContent && "blur-lg")}>
- <MemoContent
+ <MemoContentView
content={memo.content}
attachments={memo.attachments}
compact={false}
diff --git a/web/src/components/MemoCommentSection.tsx b/web/src/components/MemoCommentSection.tsx
index 13e73d7f0..aebe60dad 100644
--- a/web/src/components/MemoCommentSection.tsx
+++ b/web/src/components/MemoCommentSection.tsx
@@ -1,7 +1,6 @@
import { LoaderCircleIcon, MessageCircleIcon } from "lucide-react";
-import { type ComponentType, forwardRef, useCallback, useImperativeHandle, useRef, useState } from "react";
-import { loadMemoEditor } from "@/components/MemoEditor/loader";
-import type { MemoEditorProps } from "@/components/MemoEditor/types";
+import { forwardRef, useCallback, useImperativeHandle, useRef, useState } from "react";
+import { MemoEditor, preloadMemoEditing } from "@/components/MemoEditor";
import MemoView from "@/components/MemoView";
import { Button } from "@/components/ui/button";
import useCurrentUser from "@/hooks/useCurrentUser";
@@ -31,8 +30,6 @@ const MemoCommentSection = forwardRef<MemoCommentSectionHandle, Props>(
const t = useTranslate();
const currentUser = useCurrentUser();
const [showEditor, setShowEditor] = useState(false);
- const [isEditorLoading, setIsEditorLoading] = useState(false);
- const [EditorComponent, setEditorComponent] = useState<ComponentType<MemoEditorProps>>();
const sectionRef = useRef<HTMLDivElement>(null);
const canCreateComment = !!currentUser && memo.state === State.NORMAL;
@@ -42,9 +39,8 @@ const MemoCommentSection = forwardRef<MemoCommentSectionHandle, Props>(
setShowEditor(false);
};
- const preloadEditor = useCallback(() => {
- void loadMemoEditor().catch(() => undefined);
- }, []);
+ // The editing session's code loads while the pointer is still on the button.
+ const preloadEditor = useCallback(() => preloadMemoEditing(), []);
const focusMountedEditor = useCallback(() => {
const editorRoot = sectionRef.current?.querySelector<HTMLElement>('.memo-editor-root[contenteditable="true"]');
@@ -53,25 +49,15 @@ const MemoCommentSection = forwardRef<MemoCommentSectionHandle, Props>(
}, []);
const openEditor = useCallback(async () => {
- if (!canCreateComment || isEditorLoading) {
+ if (!canCreateComment) {
return;
}
- if (showEditor && EditorComponent) {
+ if (showEditor) {
focusMountedEditor();
return;
}
-
- setIsEditorLoading(true);
- try {
- const { default: MemoEditor } = await loadMemoEditor();
- setEditorComponent(() => MemoEditor);
- setShowEditor(true);
- } catch {
- // Chunk failures are handled by loadWithReload; keep the current UI mounted.
- } finally {
- setIsEditorLoading(false);
- }
- }, [EditorComponent, canCreateComment, focusMountedEditor, isEditorLoading, showEditor]);
+ setShowEditor(true);
+ }, [canCreateComment, focusMountedEditor, showEditor]);
const scrollIntoView = useCallback(() => {
sectionRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });
@@ -88,19 +74,9 @@ const MemoCommentSection = forwardRef<MemoCommentSectionHandle, Props>(
{comments.length === 0 ? (
showCreateButton && (
<div className="w-full flex flex-row justify-center items-center py-6">
- <Button
- variant="ghost"
- onPointerEnter={preloadEditor}
- onFocus={preloadEditor}
- onClick={openEditor}
- disabled={isEditorLoading}
- >
+ <Button variant="ghost" onPointerEnter={preloadEditor} onFocus={preloadEditor} onClick={openEditor}>
<span className="text-muted-foreground">{t("memo.comment.write-a-comment")}</span>
- {isEditorLoading ? (
- <LoaderCircleIcon className="ml-2 h-5 w-5 animate-spin text-muted-foreground" />
- ) : (
- <MessageCircleIcon className="ml-2 w-5 h-auto text-muted-foreground" />
- )}
+ <MessageCircleIcon className="ml-2 w-5 h-auto text-muted-foreground" />
</Button>
</div>
)
@@ -118,20 +94,17 @@ const MemoCommentSection = forwardRef<MemoCommentSectionHandle, Props>(
onPointerEnter={preloadEditor}
onFocus={preloadEditor}
onClick={openEditor}
- disabled={isEditorLoading}
>
- {isEditorLoading && <LoaderCircleIcon className="h-4 w-4 animate-spin" />}
{t("memo.comment.write-a-comment")}
</Button>
)}
</div>
)}
- {showEditor && EditorComponent && (
+ {showEditor && (
<div className="w-full mb-2">
- <EditorComponent
- cacheKey={`${memo.name}-comment`}
+ <MemoEditor
+ draft={{ parent: memo.name }}
placeholder={t("editor.add-your-comment-here")}
- parentMemoName={memo.name}
autoFocus
onConfirm={handleCommentCreated}
onCancel={() => setShowEditor(false)}
diff --git a/web/src/components/MemoContent/enhance.ts b/web/src/components/MemoContent/enhance.ts
deleted file mode 100644
index ee8aefafa..000000000
--- a/web/src/components/MemoContent/enhance.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { type Block, type Editor, inlineText } from "@usememos/editor";
-
-/** App UI mounted into the read-only editor's DOM with a portal. */
-export type Island = { key: string; target: HTMLElement; href: string };
-
-let islandCounter = 0;
-/** Stable portal keys per target element, so a second pass does not remount mounted islands. */
-const islandKeys = new WeakMap<HTMLElement, string>();
-const islandKey = (target: HTMLElement): string => {
- let key = islandKeys.get(target);
- if (!key) {
- key = `island-${++islandCounter}`;
- islandKeys.set(target, key);
- }
- return key;
-};
-
-/** The URL a paragraph consists of, when it is nothing but one bare web link: `https://…` written as its own text. */
-function bareLinkOf(block: Block): string | undefined {
- if (block.type !== "paragraph" || block.content.length === 0) return undefined;
- const href = block.content[0].link;
- // Only web links have metadata to preview; `tel:`/`sms:`/`mailto:` hand off to another app.
- if (!href || !/^https?:\/\//i.test(href)) return undefined;
- // A titled link is a written `[text](url "title")`, never a bare URL; a card would drop its title.
- if (!block.content.every((span) => span.link === href && !span.linkTitle && !span.image)) return undefined;
- return inlineText(block.content) === href ? href : undefined;
-}
-
-const blockElement = (root: HTMLElement, blockId: string) => root.querySelector<HTMLElement>(`[data-block-id="${CSS.escape(blockId)}"]`);
-
-/**
- * The places in the read-only editor's DOM where memos' own UI takes over: a link card
- * in place of a paragraph that is one bare link, which needs the page's details from the
- * memos server. Everything else the view shows comes from the editor. Safe to run
- * repeatedly: targets keep their keys, and only new targets are prepared.
- */
-export function findIslands(editor: Editor, root: HTMLElement, linkPreviewEnabled: boolean): Island[] {
- const islands: Island[] = [];
- for (const block of editor.state.doc.blocks) {
- const href = linkPreviewEnabled ? bareLinkOf(block) : undefined;
- const target = href ? blockElement(root, block.id) : null;
- if (!href || !target) continue;
- if (!target.hasAttribute("data-link-preview")) {
- target.setAttribute("data-link-preview", "");
- target.replaceChildren();
- }
- islands.push({ key: islandKey(target), target, href });
- }
- return islands;
-}
-
-/** Whether two passes produced the same islands, so React can skip a render. */
-export const sameIslands = (a: readonly Island[], b: readonly Island[]): boolean =>
- a.length === b.length &&
- a.every((island, index) => island.key === b[index].key && island.target === b[index].target && island.href === b[index].href);
diff --git a/web/src/components/MemoContent/index.tsx b/web/src/components/MemoContent/index.tsx
deleted file mode 100644
index 8390197b7..000000000
--- a/web/src/components/MemoContent/index.tsx
+++ /dev/null
@@ -1,198 +0,0 @@
-import type { Editor } from "@usememos/editor";
-import { MarkdownEditor } from "@usememos/editor/react";
-import "@usememos/editor/style.css";
-import { memo, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
-import { createPortal } from "react-dom";
-import { useNavigate } from "react-router-dom";
-import { useAuth } from "@/contexts/AuthContext";
-import { useContentSearchTerms } from "@/contexts/MemoFilterContext";
-import { useLinkPreviewEnabled } from "@/contexts/ViewContext";
-import { useNearViewport } from "@/hooks/useNearViewport";
-import { markdownStyles } from "@/lib/markdownStyles";
-import {
- MEMO_EDITOR_THEME,
- MEMO_MARKDOWN,
- memoEditorLabels,
- memoExtensions,
- memoMentionOptions,
- memoResolveUrl,
- memoTagOptions,
-} from "@/lib/memo-markdown";
-import { cn } from "@/lib/utils";
-import { getCreatorHomePath } from "@/router/routes";
-import { useTranslate } from "@/utils/i18n";
-import { findAnchorTarget } from "@/utils/markdown-manipulation";
-import { createMemoNavigationState } from "../MemoView/navigation";
-import { findIslands, type Island, sameIslands } from "./enhance";
-import { headingSlugs } from "./headings";
-import LinkMetadataCard from "./LinkMetadataCard";
-import { useResolvedMentionUsernames } from "./MentionResolutionContext";
-import type { MemoContentProps } from "./types";
-import { useSearchMatchHighlight } from "./useSearchMatchHighlight";
-import { useTagNavigation } from "./useTagNavigation";
-
-// A memo with a Mermaid diagram draws it in the page's color scheme; the editor keeps drawn
-// diagrams, so a new scheme needs a new editor to draw them again.
-const MERMAID_FENCE = /^ {0,3}(?:`{3,}|~{3,})[ \t]*mermaid\b/im;
-const subscribeColorScheme = (onChange: () => void) => {
- const observer = new MutationObserver(onChange);
- observer.observe(document.documentElement, { attributes: true, attributeFilter: ["style"] });
- return () => observer.disconnect();
-};
-const getColorScheme = () => document.documentElement.style.colorScheme;
-
-const LinkPreview = ({ href }: { href: string }) => {
- const { ref, isNearViewport } = useNearViewport<HTMLAnchorElement>();
- const fallback = (
- <a ref={ref} href={href} target="_blank" rel="noopener noreferrer" className={markdownStyles.link}>
- {href}
- </a>
- );
- return <LinkMetadataCard url={href} fallback={fallback} enabled={isNearViewport} />;
-};
-
-/**
- * A memo's content, shown by the same Markdown editor the composer uses, read-only. Owners
- * can tick task items: each tick reports the new Markdown, in which only that item's
- * `[ ]` or `[x]` changed. Truncation is not this component's concern — compact cards are
- * bounded by ClampedSection around the whole memo body; `compact` only tells in-memo
- * anchor links to open the detail page, since a collapsed card may hide their target.
- */
-const MemoContent = (props: MemoContentProps) => {
- const { className, contentClassName, content, attachments, memoName, parentPage, compact, onTaskToggle, onClick, onDoubleClick } = props;
- const t = useTranslate();
- const navigate = useNavigate();
- const { userTagsSetting } = useAuth();
- const labels = useMemo(() => memoEditorLabels(t), [t]);
- const linkPreviewEnabled = useLinkPreviewEnabled();
- const resolvedMentionUsernames = useResolvedMentionUsernames(content);
- const navigateToTag = useTagNavigation(parentPage);
- // Whatever the page's search matched is painted here, without altering the rendered tree.
- const contentRef = useRef<HTMLDivElement>(null);
- useSearchMatchHighlight(contentRef, useContentSearchTerms());
- const [editor, setEditor] = useState<Editor | null>(null);
- const colorScheme = useSyncExternalStore(subscribeColorScheme, getColorScheme, () => "");
- const editorKey = MERMAID_FENCE.test(content) ? colorScheme : undefined;
- const [islands, setIslands] = useState<Island[]>([]);
-
- // Tag colors and resolved mentions come from outside the document: the decorations
- // read them here, and the editor decorates again when they change.
- const decorationState = useRef({ resolvedMentionUsernames, userTagsSetting });
- decorationState.current = { resolvedMentionUsernames, userTagsSetting };
- const extensions = useMemo(
- () =>
- memoExtensions({
- tags: memoTagOptions(() => decorationState.current.userTagsSetting),
- mentions: memoMentionOptions((username) => decorationState.current.resolvedMentionUsernames.has(username)),
- }),
- [],
- );
- // Redecorate only when what the decorations read actually changed: a new editor already
- // decorates with the current values, and a resolution that comes back equal is a no-op.
- const mentionKey = [...resolvedMentionUsernames].sort().join(" ");
- const decorated = useRef({ mentionKey, userTagsSetting });
- useEffect(() => {
- const changed = decorated.current.mentionKey !== mentionKey || decorated.current.userTagsSetting !== userTagsSetting;
- decorated.current = { mentionKey, userTagsSetting };
- if (changed) editor?.redecorate();
- }, [editor, mentionKey, userTagsSetting]);
-
- const resolveUrl = useMemo(() => memoResolveUrl(attachments), [attachments]);
-
- // Mount memos' own UI after every render of the editor's blocks: on load, on a new
- // value, and when a ticked task item or new image URLs re-render blocks.
- useEffect(() => {
- if (!editor || editor.isDestroyed) return;
- const root = editor.root;
- let frame: number | null = null;
- const update = () => {
- frame = null;
- if (editor.isDestroyed) return;
- const next = findIslands(editor, root, linkPreviewEnabled);
- setIslands((previous) => (sameIslands(previous, next) ? previous : next));
- };
- update();
- const observer = new MutationObserver(() => {
- frame ??= requestAnimationFrame(update);
- });
- observer.observe(root, { childList: true });
- return () => {
- observer.disconnect();
- if (frame !== null) cancelAnimationFrame(frame);
- };
- }, [editor, content, linkPreviewEnabled, resolveUrl]);
-
- // In-memo anchors scroll within this memo; a collapsed card may hide the target, so it opens the detail page.
- const handleLinkClick = ({ href }: { href: string }) => {
- if (!href.startsWith("#")) return false;
- const id = decodeURIComponent(href.slice(1));
- const target = !compact && id && contentRef.current ? findAnchorTarget(contentRef.current, id) : null;
- if (target) {
- target.scrollIntoView({ behavior: "smooth", block: "center" });
- } else if (memoName) {
- navigate(`/${memoName}${href}`, { state: parentPage ? createMemoNavigationState(parentPage) : undefined });
- }
- return true;
- };
-
- const handleClick = (event: React.MouseEvent) => {
- const target = event.target as HTMLElement;
- const tag = target.closest<HTMLElement>(".mbe-tag")?.dataset.tag;
- if (tag) {
- event.stopPropagation();
- navigateToTag(tag);
- return;
- }
- const mention = target.closest<HTMLElement>(".mbe-mention[data-resolved]")?.dataset.mention;
- if (mention) {
- event.stopPropagation();
- navigate(getCreatorHomePath(mention));
- }
- };
-
- return (
- <div className={`w-full flex flex-col justify-start items-start text-foreground ${className || ""}`}>
- <div
- ref={contentRef}
- data-memo-content
- data-memo-name={memoName}
- className={cn(
- "relative w-full max-w-full wrap-break-word text-base leading-6",
- // Tags filter the list when clicked here; the composer shows them the same, without the click.
- "[&_.mbe-tag]:cursor-pointer [&_.mbe-tag]:transition-opacity [&_.mbe-tag:hover]:opacity-75",
- "[&_.mbe-mention[data-resolved]]:cursor-pointer [&_.mbe-mention[data-resolved]:hover]:underline",
- "[&_.katex-display]:max-w-full",
- "[&_.katex-display]:overflow-x-auto",
- "[&_.katex-display]:overflow-y-hidden",
- contentClassName,
- )}
- onClick={handleClick}
- onMouseUp={onClick}
- onDoubleClick={onDoubleClick}
- >
- <MarkdownEditor
- key={editorKey}
- ref={setEditor}
- value={content}
- onChange={onTaskToggle}
- editable={false}
- taskToggle={Boolean(onTaskToggle)}
- toolbar={false}
- slashMenu={false}
- markdown={MEMO_MARKDOWN}
- extensions={extensions}
- theme={MEMO_EDITOR_THEME}
- labels={labels}
- resolveUrl={resolveUrl}
- referrerPolicy="no-referrer"
- headingIds={headingSlugs}
- onLinkClick={handleLinkClick}
- className="memo-content-root"
- />
- {islands.map((island) => createPortal(<LinkPreview href={island.href} />, island.target, island.key))}
- </div>
- </div>
- );
-};
-
-export default memo(MemoContent);
diff --git a/web/src/components/MemoContent/types.ts b/web/src/components/MemoContent/types.ts
deleted file mode 100644
index db530e49f..000000000
--- a/web/src/components/MemoContent/types.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import type React from "react";
-import type { Attachment } from "@/types/proto/api/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`). Lets in-memo anchor links open the memo detail page. */
- memoName?: string;
- /** Collection page that rendered the memo, preserved when an inline link opens its detail page. */
- parentPage?: string;
- /** The card renders collapsed (ClampedSection), so in-memo anchor links navigate instead of scrolling. */
- compact?: boolean;
- /**
- * Lets the viewer tick task items, for a memo they can manage. Called with the new
- * Markdown, in which only the ticked item's `[ ]` or `[x]` changed.
- */
- onTaskToggle?: (content: string) => void;
- className?: string;
- contentClassName?: string;
- onClick?: (e: React.MouseEvent) => void;
- onDoubleClick?: (e: React.MouseEvent) => void;
-}
diff --git a/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx b/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx
index c1cf37a74..980609c1a 100644
--- a/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx
+++ b/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx
@@ -14,7 +14,7 @@ import toast from "react-hot-toast";
import { Link, useLocation } from "react-router-dom";
import SidebarRow, { SIDEBAR_ROW_CLASSES, SIDEBAR_ROW_COUNT_RAIL_CLASSES, SidebarRowIconSlot } from "@/components/AppSidebar/SidebarRow";
import SidebarSection, { SIDEBAR_SECTION_STACK_CLASSES } from "@/components/AppSidebar/SidebarSection";
-import { extractHeadings } from "@/components/MemoContent/headings";
+import { extractHeadings } from "@/components/MemoEditor/view/headings";
import { getRelationBuckets, getRelationMemo } from "@/components/MemoMetadata/Relation/relationHelpers";
import { useResolvedRelationMemos } from "@/components/MemoMetadata/Relation/useResolvedRelationMemos";
import MemoParentPlaceholder, { type MemoParentStatus } from "@/components/MemoParentPlaceholder";
diff --git a/web/src/components/MemoDetailSidebar/MemoOutline.tsx b/web/src/components/MemoDetailSidebar/MemoOutline.tsx
index c70c87fc9..ee120a721 100644
--- a/web/src/components/MemoDetailSidebar/MemoOutline.tsx
+++ b/web/src/components/MemoDetailSidebar/MemoOutline.tsx
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState } from "react";
-import type { HeadingItem } from "@/components/MemoContent/headings";
+import type { HeadingItem } from "@/components/MemoEditor/view/headings";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { findAnchorTarget, findMemoContentRoot } from "@/utils/markdown-manipulation";
diff --git a/web/src/components/MemoEditor/MemoEditor.tsx b/web/src/components/MemoEditor/MemoEditor.tsx
new file mode 100644
index 000000000..032deef07
--- /dev/null
+++ b/web/src/components/MemoEditor/MemoEditor.tsx
@@ -0,0 +1,232 @@
+import { Suspense, useState } from "react";
+import { useAuth } from "@/contexts/AuthContext";
+import useCurrentUser from "@/hooks/useCurrentUser";
+import { useMemoByName, useUpdateMemo } from "@/hooks/useMemoQueries";
+import type { MemoSuggestion } from "@/lib/memo-suggestions";
+import { cn } from "@/lib/utils";
+import type { Location } from "@/types/proto/api/memo_service_pb";
+import { lazyWithReload } from "@/utils/lazy";
+import { convertVisibilityFromString } from "@/utils/memo";
+import { canManageMemo } from "@/utils/user";
+import { draftKeyFor, type MemoEditIdentity, migrateLegacyDraft } from "./edit/draftKey";
+import { canChooseSpaceFor, initialEditorState } from "./edit/initialState";
+import { cacheService } from "./edit/services/cacheService";
+import { EditorProvider } from "./edit/state";
+import { MemoContentView } from "./view/MemoContentView";
+
+// The editing session is the composer's chrome, uploads, audio and menus: loaded when a
+// memo is first edited or composed, so a page of memos does not carry it. Once loaded it
+// renders at once, with no suspense, so a host that preloaded it opens without a gap.
+type EditSessionComponent = typeof import("./edit/EditSession").EditSession;
+let loadedEditSession: EditSessionComponent | undefined;
+const loadEditSession = () =>
+ import("./edit/EditSession").then((module) => {
+ loadedEditSession = module.EditSession;
+ return { default: module.EditSession };
+ });
+const LazyEditSession = lazyWithReload(loadEditSession);
+
+/** Loads the editing session's code ahead of time, for a host that is about to open an editor. */
+export const preloadMemoEditing = (): Promise<void> =>
+ loadEditSession().then(
+ () => undefined,
+ () => undefined,
+ );
+
+export interface MemoEditorViewProps {
+ mode?: "view";
+ /** The memo's resource name, such as `memos/abc`. */
+ name: string;
+ /** The card renders collapsed, so in-memo anchor links open the detail page instead of scrolling. */
+ compact?: boolean;
+ /** Collection page that rendered the memo, preserved when an inline link opens its detail page. */
+ parentPage?: string;
+ className?: string;
+ contentClassName?: string;
+ onClick?: (event: React.MouseEvent) => void;
+ onDoubleClick?: (event: React.MouseEvent) => void;
+}
+
+/** What a new memo or comment starts from. */
+export interface MemoDraftSeed {
+ /** The memo this draft comments on. A comment has no scope, Space or timestamps of its own. */
+ parent?: string;
+ /**
+ * Where a new memo is composed, such as `home`, `global`, `calendar:<date>` or
+ * `map:<key>`. Each scope keeps its own draft, per Space.
+ */
+ scope?: string;
+ /** Fixes the new memo's Space; the Space chooser is then off. */
+ space?: string;
+ /** Seeds the location once; a restored draft wins. */
+ location?: Location;
+ /**
+ * Seeds `createTime` and `updateTime` and shows the timestamp popover. Followed live
+ * while the draft is open, for a calendar whose selected day changes.
+ */
+ createTime?: Date;
+}
+
+export interface MemoEditingProps {
+ /** A callback can decide whether focus is still appropriate after the draft is restored. */
+ autoFocus?: boolean | (() => boolean);
+ placeholder?: string;
+ /** Context-derived suggestions for a new top-level memo. */
+ suggestions?: readonly MemoSuggestion[];
+ className?: string;
+ /** Inside a card that is the frame already: no background, border or padding of its own outside focus mode. */
+ frameless?: boolean;
+ /**
+ * Marks the instance as hosted: a host (the global composer dialog) presents the
+ * editor in the focus-mode layout and owns that frame. The editor mounts straight
+ * into focus mode and exits by calling this to dismiss the host.
+ */
+ onFocusModeExit?: () => void;
+ /** Reports inline focus-mode changes, for a host whose layout must let the editor take the viewport. */
+ onFocusModeChange?: (isFocusMode: boolean) => void;
+ onConfirm?: (memoName: string) => void;
+ /** Offers Cancel; without it the session has no way out but saving, as the Home composer. */
+ onCancel?: () => void;
+ /** Reports save activity so a host can keep itself open mid-transaction. */
+ onSavingChange?: (isSaving: boolean) => void;
+}
+
+/** Editing an existing memo by name. */
+export interface MemoEditorEditProps extends MemoEditingProps {
+ mode: "edit";
+ name: string;
+}
+
+/** Composing a new memo or comment. */
+export interface MemoEditorDraftProps extends MemoEditingProps {
+ mode?: "edit";
+ draft: MemoDraftSeed;
+}
+
+export type MemoEditorProps = MemoEditorViewProps | MemoEditorEditProps | MemoEditorDraftProps;
+
+/**
+ * A memo, shown or edited. In view mode it reads the memo by name from whatever query
+ * already holds it (a list, a comment page, a detail) and shows it read-only; a viewer
+ * who can manage the memo ticks its task items, and each tick is saved through the memo
+ * mutation, so every copy of the memo on the page follows at once. In edit mode, for an
+ * existing memo by name or a new memo from a draft seed, it owns the draft store,
+ * initialized once from the memo or the persisted draft, and renders the editing
+ * session over it. The parent owns the mode and hears back through `onConfirm` and
+ * `onCancel`.
+ */
+export const MemoEditor = (props: MemoEditorProps) => {
+ if ("draft" in props) return <MemoEditorDraft {...props} />;
+ if (props.mode === "edit") return <MemoEditorEdit {...props} />;
+ return <MemoEditorView {...props} />;
+};
+
+const MemoEditorView = ({ name, compact, parentPage, className, contentClassName, onClick, onDoubleClick }: MemoEditorViewProps) => {
+ const { data: memo } = useMemoByName(name);
+ const currentUser = useCurrentUser();
+ const { mutate: updateMemo } = useUpdateMemo();
+ if (!memo) return null;
+
+ const handleTaskToggle = (content: string) => updateMemo({ update: { name, content }, updateMask: ["content", "update_time"] });
+
+ return (
+ <MemoContentView
+ memoName={name}
+ content={memo.content}
+ attachments={memo.attachments}
+ parentPage={parentPage}
+ compact={compact}
+ onTaskToggle={canManageMemo(memo, currentUser) ? handleTaskToggle : undefined}
+ className={className}
+ contentClassName={contentClassName}
+ onClick={onClick}
+ onDoubleClick={onDoubleClick}
+ />
+ );
+};
+
+const MemoEditorEdit = ({ name, ...editing }: MemoEditorEditProps) => {
+ const { data: memo } = useMemoByName(name);
+ // The memo stays readable while the session's code loads, and until the memo itself has.
+ const fallback = <MemoEditorView name={name} className={editing.className} />;
+ if (!memo) return fallback;
+ const identity: MemoEditIdentity = { kind: "edit", name };
+ return (
+ <Suspense fallback={fallback}>
+ <EditingSession key={draftKeyFor(identity)} identity={identity} memo={memo} {...editing} />
+ </Suspense>
+ );
+};
+
+const MemoEditorDraft = ({ draft, ...editing }: MemoEditorDraftProps) => {
+ const identity: MemoEditIdentity = draft.parent
+ ? { kind: "comment", parent: draft.parent }
+ : { kind: "new", scope: draft.scope ?? "default", space: draft.space };
+ const fallback = editing.frameless ? null : (
+ <div aria-hidden className={cn("w-full min-h-28 rounded-lg border border-border/70 bg-card", editing.className)} />
+ );
+ return (
+ <Suspense fallback={fallback}>
+ <EditingSession
+ key={draftKeyFor(identity)}
+ identity={identity}
+ parentMemoName={draft.parent}
+ defaultSpace={draft.space}
+ defaultLocation={draft.location}
+ defaultCreateTime={draft.createTime}
+ {...editing}
+ />
+ </Suspense>
+ );
+};
+
+interface EditingSessionProps extends MemoEditingProps {
+ identity: MemoEditIdentity;
+ memo?: Parameters<typeof initialEditorState>[0]["memo"];
+ parentMemoName?: string;
+ defaultSpace?: string;
+ defaultLocation?: Location;
+ defaultCreateTime?: Date;
+}
+
+/** One session over one identity: the draft store is created once, so a new identity is a new key. */
+const EditingSession = ({
+ identity,
+ memo,
+ parentMemoName,
+ defaultSpace,
+ defaultLocation,
+ defaultCreateTime,
+ ...editing
+}: EditingSessionProps) => {
+ const currentUser = useCurrentUser();
+ const { userGeneralSetting } = useAuth();
+ const username = currentUser?.name ?? "";
+ const draftKey = cacheService.key(username, draftKeyFor(identity));
+ const [initialState] = useState(() => {
+ migrateLegacyDraft(username, identity);
+ return initialEditorState({
+ memo,
+ draftKey,
+ // A hosted editor starts in focus mode and stays there.
+ initialFocusMode: Boolean(editing.onFocusModeExit),
+ defaultVisibility: userGeneralSetting?.memoVisibility ? convertVisibilityFromString(userGeneralSetting.memoVisibility) : undefined,
+ defaultCreateTime,
+ defaultLocation,
+ canChooseSpace: canChooseSpaceFor({ memo, currentUser, parentMemoName, defaultSpace }),
+ });
+ });
+ const EditSession = loadedEditSession ?? LazyEditSession;
+ return (
+ <EditorProvider initialEditorState={initialState}>
+ <EditSession
+ memo={memo}
+ parentMemoName={parentMemoName}
+ defaultSpace={defaultSpace}
+ defaultCreateTime={defaultCreateTime}
+ draftKey={draftKey}
+ {...editing}
+ />
+ </EditorProvider>
+ );
+};
diff --git a/web/src/components/MemoEditor/MemoMarkdown.tsx b/web/src/components/MemoEditor/MemoMarkdown.tsx
new file mode 100644
index 000000000..df6ae6b92
--- /dev/null
+++ b/web/src/components/MemoEditor/MemoMarkdown.tsx
@@ -0,0 +1,138 @@
+import type { Editor, EditorMode, Extension } from "@usememos/editor";
+import { MarkdownEditor, type MarkdownEditorProps } from "@usememos/editor/react";
+import "@usememos/editor/style.css";
+import { type Ref, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
+import { MEMO_EDITOR_THEME, MEMO_MARKDOWN, memoEditorLabels, memoExtensions, memoResolveUrl } from "@/lib/memo-markdown";
+import type { Attachment } from "@/types/proto/api/attachment_service_pb";
+import { useTranslate } from "@/utils/i18n";
+import { useMemoDecorations } from "./useMemoDecorations";
+
+export interface MemoMarkdownProps {
+ /** The Markdown. Applied only when it is not a value the editor emitted itself. */
+ value: string;
+ /** Editing, or the read-only memo view. Default read-only. Updates live. */
+ editable?: boolean;
+ /** While read-only, lets the viewer tick task items; each tick reports the new Markdown through `onChange`. */
+ taskToggle?: boolean;
+ onChange?: (markdown: string) => void;
+ /** Mod+Enter or Ctrl+Enter while editing. */
+ onSubmit?: () => void;
+ /** Rich text, or the whole memo as Markdown text. Switching changes no text. */
+ mode?: EditorMode;
+ placeholder?: string;
+ /** The memo's attachments, so images of managed attachments resolve to their served URL. */
+ attachments?: readonly Attachment[];
+ /** Extensions beyond the memo syntax, for editing. Keep the array's identity stable: a new set of names recreates the editor. */
+ extensions?: readonly Extension[];
+ /** The core editor instance. */
+ editorRef?: Ref<Editor | null>;
+ headingIds?: MarkdownEditorProps["headingIds"];
+ onLinkClick?: MarkdownEditorProps["onLinkClick"];
+ /** A tag was clicked to be followed (a plain click while read-only, Mod+click while editing), without its `#`. */
+ onTagClick?: (tag: string) => void;
+ /** A mention of someone who exists was clicked to be followed, without its `@`. */
+ onMentionClick?: (username: string) => void;
+ /** Attributes for the editable root, such as `spellcheck`. */
+ attributes?: Record<string, string>;
+ /** The formatting toolbar and the image toolbar. Read once; the editor hides them while read-only. */
+ toolbar?: boolean;
+ /** The slash menu's items, or `false` for none. Read once. */
+ slashMenu?: MarkdownEditorProps["slashMenu"];
+ className?: string;
+}
+
+// A memo with a Mermaid diagram draws it in the page's color scheme; a new scheme draws
+// the diagrams again.
+const MERMAID_FENCE = /^ {0,3}(?:`{3,}|~{3,})[ \t]*mermaid\b/im;
+const subscribeColorScheme = (onChange: () => void) => {
+ const observer = new MutationObserver(onChange);
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["style"] });
+ return () => observer.disconnect();
+};
+const getColorScheme = () => document.documentElement.style.colorScheme;
+
+const assignRef = <T,>(ref: Ref<T> | undefined, value: T) => {
+ if (typeof ref === "function") ref(value);
+ else if (ref) ref.current = value;
+};
+
+/**
+ * A memo's Markdown in memos' dialect, look and policy, shown by the same editor whether
+ * read-only or editing: the memo syntax extensions (math, footnotes, tags, mentions,
+ * highlighted code, Mermaid, sanitized HTML), the theme in the app's CSS variables, the
+ * translated labels, the image and link URL policy, and tags and mentions decorated from
+ * the viewer's data. Everything a memo surface adds sits around this component.
+ */
+export const MemoMarkdown = (props: MemoMarkdownProps) => {
+ const {
+ value,
+ editable = false,
+ taskToggle,
+ onChange,
+ onSubmit,
+ mode,
+ placeholder,
+ attachments,
+ extensions,
+ editorRef,
+ headingIds,
+ onLinkClick,
+ onTagClick,
+ onMentionClick,
+ attributes,
+ toolbar,
+ slashMenu,
+ className,
+ } = props;
+ const t = useTranslate();
+ const [editor, setEditor] = useState<Editor | null>(null);
+ const attach = useCallback(
+ (instance: Editor | null) => {
+ setEditor(instance);
+ assignRef(editorRef, instance);
+ },
+ [editorRef],
+ );
+
+ const decorations = useMemoDecorations(editor, value, editable, { onTagClick, onMentionClick });
+ const baseExtensions = useMemo(() => memoExtensions({ tags: decorations.tags, mentions: decorations.mentions }), [decorations]);
+ const allExtensions = useMemo(
+ () => (extensions?.length ? [...baseExtensions, ...extensions] : baseExtensions),
+ [baseExtensions, extensions],
+ );
+ const labels = useMemo(() => memoEditorLabels(t), [t]);
+ const resolveUrl = useMemo(() => memoResolveUrl(attachments), [attachments]);
+ const colorScheme = useSyncExternalStore(subscribeColorScheme, getColorScheme, () => "");
+ const drawnScheme = useRef(colorScheme);
+ useEffect(() => {
+ if (drawnScheme.current === colorScheme) return;
+ drawnScheme.current = colorScheme;
+ if (MERMAID_FENCE.test(value)) editor?.refreshViews("code:mermaid");
+ }, [colorScheme, editor, value]);
+
+ return (
+ <MarkdownEditor
+ ref={attach}
+ value={value}
+ // The React wrapper calls the latest callbacks, so inline functions are fine.
+ onChange={onChange}
+ onSubmit={onSubmit ? () => onSubmit() : undefined}
+ editable={editable}
+ taskToggle={taskToggle}
+ mode={mode}
+ placeholder={placeholder}
+ markdown={MEMO_MARKDOWN}
+ extensions={allExtensions}
+ theme={MEMO_EDITOR_THEME}
+ labels={labels}
+ attributes={attributes}
+ resolveUrl={resolveUrl}
+ referrerPolicy="no-referrer"
+ headingIds={headingIds}
+ onLinkClick={onLinkClick}
+ toolbar={toolbar}
+ slashMenu={slashMenu}
+ className={className}
+ />
+ );
+};
diff --git a/web/src/components/MemoEditor/README.md b/web/src/components/MemoEditor/README.md
index b3e45f389..f4cc3d2c8 100644
--- a/web/src/components/MemoEditor/README.md
+++ b/web/src/components/MemoEditor/README.md
@@ -1,170 +1,95 @@
-# MemoEditor Architecture
+# MemoEditor
## Overview
-MemoEditor is a three-layer component. At its core is a single editor — `Editor/`, built on [`@usememos/editor`](https://github.com/usememos/editor), a block editor whose storage format is standard Markdown. Markdown goes in and comes out: blocks the user did not edit are saved byte for byte, and edited blocks are written in a normalized style. The memo view (`components/MemoContent`) is the same editor, read-only, so a memo looks the same while editing and after saving. Everything above the editor boundary talks markdown through the `EditorController` contract.
+`MemoEditor` is the one way a memo is shown, edited or composed. It is memo-aware: it takes a memo's resource name, or a seed for a new memo or comment, and a mode. In view mode it reads the memo from whatever query already holds it and shows it read-only. In edit mode it owns a draft store and renders the editing session over it. The parent owns the mode and hears back through `onConfirm` and `onCancel`.
-## Architecture
+Both modes show the memo through the same binding of [`@usememos/editor`](https://github.com/usememos/editor), a block editor whose storage format is standard Markdown, so a memo looks the same while editing and after saving. Blocks the user did not edit are saved byte for byte; edited blocks are written in a normalized style.
-```
-┌─────────────────────────────────────────┐
-│ Presentation Layer (Components) │
-│ - EditorToolbar, EditorContent, etc. │
-└─────────────────┬───────────────────────┘
- │ EditorController
-┌─────────────────▼───────────────────────┐
-│ State Layer (reducer over an external │
-│ store; per-slice subscriptions) │
-│ - state/, useEditorContext(), │
-│ useEditorSelector() │
-│ - state.content ← markdown (the │
-│ single source of truth) │
-└─────────────────┬───────────────────────┘
- │
-┌─────────────────▼───────────────────────┐
-│ Service Layer (Business Logic) │
-│ - services/ (pure functions) │
-└─────────────────────────────────────────┘
+```tsx
+<MemoEditor name="memos/abc" /> // view; the owner can tick tasks
+<MemoEditor mode="edit" name="memos/abc" onConfirm onCancel /> // edit in place
+<MemoEditor draft={{ parent: "memos/abc" }} onConfirm onCancel /> // new comment
+<MemoEditor draft={{ scope: "home", space, createTime }} /> // new memo
```
-## Directory Structure
+## Layers
```
-MemoEditor/
-├── index.tsx # The shell: EditorProvider + MemoEditorImpl
-├── loader.ts # loadMemoEditor(): the shared lazy-load entry point
-├── state/ # State management (reducer, actions, context)
-├── services/ # Business logic (pure functions)
-├── components/ # UI components
-│ ├── EditorContent.tsx # Hosts Editor; forwards its EditorController ref
-│ ├── EditorMetadata.tsx # Attachment strip below the document
-│ └── ...
-├── hooks/ # React hooks (utilities)
-│ ├── useMemoSave.ts # Save transaction, cache invalidation, and reset
-│ ├── useSourceMode.ts # Rich or source mode, remembered per device
-│ └── useFocusMode.ts # Scroll lock and layout-stable focus presentation
-├── Editor/ # The composer, on @usememos/editor
-│ ├── index.tsx # React wrapper around <MarkdownEditor>; hands out the controller
-│ ├── extensions.ts # buildEditorExtensions(): memo syntax, #tag and :emoji autocomplete, file paste/drop
-│ ├── uploadAnchors.ts # Widget rendering for in-flight upload placeholders
-│ ├── controller.ts # EditorController over the editor
-│ └── editor.css # Composer sizing and upload-anchor styles
-├── Toolbar/ # EditorToolbar, InsertMenu, AudienceMenu
-├── constants.ts
-└── types/ # EditorController, component props,
- # attachment and insert-menu types
+MemoEditor memo level: name | draft seed, mode, data, draft store, mutations
+├── MemoContentView the read-only surface: navigation, anchors, link cards, search highlight
+│ └── MemoMarkdown the editor binding: dialect, theme, labels, URL policy, memo syntax, decorations
+└── EditSession the editing surface: chrome, uploads, audio, suggestions, save
+ └── Editor MemoMarkdown editable, with the composer's extensions, behind EditorController
```
-## Key Concepts
-
-### State Management
-
-A reducer (`state/reducer.ts`) drives an **external store**, not a `useReducer` in the provider, and consumers subscribe to just the slice they read via `useEditorSelector` (`useSyncExternalStore` under the hood). Content changes on every keystroke, so routing it through a single context value would re-render every consumer — toolbar, insert menu, metadata — per keystroke; with per-slice subscriptions only the components whose slice actually changed re-render. All state changes still go through action creators.
-
-`state.content` holds the document as a **markdown string** and is the single source of truth. Because the editor stores markdown verbatim, `state.content` is exactly the editor's document — there is no encoding or normalization step.
-
-### The editor contract
+- **`MemoMarkdown.tsx`** binds the editor to memos once: the memo Markdown dialect, the theme in the app's CSS variables, translated labels, the image and link URL policy, the memo syntax extensions (math, footnotes, tags, mentions, highlighted code, Mermaid, sanitized HTML) and the stylesheet. `useMemoDecorations` is the one flow for tag colors and resolved mentions, with one redecorate effect. Everything a surface adds sits around this component; nothing in memos styles the editor's own classes.
+- **`view/`** is the read-only surface over `MemoMarkdown`: tags and mentions navigate, in-memo anchors scroll, a paragraph that is one bare link becomes a preview card through the editor's block view (`linkCards.ts`), the page's search matches are painted, and heading ids match the outline. Tag and mention clicks arrive through the editor's `onClick` callbacks, so nothing in memos matches the editor's class names or mutates its DOM. Previews that have Markdown but no memo query (the link-memo search, the share image) use `MemoContentView` directly.
+- **`edit/`** is the editing surface: `EditSession` renders the chrome (timestamp, attachments, suggestions, toolbar, focus mode, audio recording) over the draft store `MemoEditor` provides, persists the draft while open, and saves through the memo mutations. `Editor.tsx` is the composer's editor: `MemoMarkdown` editable with the composer's own extensions (`#tag` and `:emoji` autocomplete, file paste and drop), behind the `EditorController` contract in `controller.ts`.
-`types/editorController.ts` defines `EditorController` — document access (`getMarkdown`, `setMarkdown`, `insertMarkdown`), selection and focus (`focus`, `hasFocus`, `isEmpty`, `getSelection`, `setSelection`, `selectAll`), the upload-anchor group below, and `toggleTaskList`. Callers outside the editor implementation use this interface exclusively and never reach into the editor's own API.
+## Data
-`Editor/controller.ts` implements `EditorController` over the editor instance. Every method reads the live editor when called, so calls before mount or after destroy do nothing. `insertMarkdown` inserts after the caret's block (or in place of an empty paragraph) without consuming selected text. Selections are the editor's `SelectionJSON` (block index and offset), which survives remounting the same Markdown, so `cacheService` can restore the caret.
+- **Reads are by name.** `useMemoByName` (`hooks/useMemoQueries.ts`) returns the freshest copy of the memo any query holds (a list, a comment page, the calendar month, a detail, a shared memo) and fetches the detail only when nothing holds it. A card in a list therefore costs no request beyond the list's, follows the list's refetches, and never refetches on its own.
+- **Writes are mutations.** A ticked task, a save and a new memo go through `useUpdateMemo` and `useCreateMemo`, which patch and refresh every query holding the memo, so the saved text shows wherever the memo is on the page as soon as the server answers.
+- **The draft is UI state keyed by identity.** `edit/draftKey.ts` derives the key from what is edited: `edit:<name>`, `comment:<parent>`, `new:<scope>[:<space>]`. `initialEditorState` computes the store's first state once, from the memo or the persisted draft over the host's defaults; `useAutoSave` persists it while the session is open; an edit of an existing memo persists no draft. A new identity is a new session (`key`).
-`createUploadAnchor`/`updateUploadAnchor`/`resolveUploadAnchor`/`cancelUploadAnchor` drive editor widgets (`editor.addWidget`) that hold a place after a block while an attachment uploads and carry its progress, failure message, and retry/keep affordances. Widgets are never saved and are not part of undo history. `resolveUploadAnchor` inserts the finished markdown after the widget's block; resolving with empty markdown cancels instead, as does `cancelUploadAnchor`.
+## The editing session
-### Formatting
+### State
-Formatting is the editor's own: its toolbar appears over selected text (bold, italic, strikethrough, code, link), the slash menu and Markdown shortcuts change block types, and its keys cover the rest. Memos adds no formatting toolbar. The one formatting call memos makes itself is `toggleTaskList()`, for the checklist suggestion chip.
+A reducer (`edit/state/reducer.ts`) drives an external store; consumers subscribe to one slice via `useEditorSelector`, so typing re-renders only what reads `content`. `state.content` is the document as Markdown and the single source of truth. UI flags (focus mode, loading, pending inline images), metadata (visibility, Space, attachments, relations, location), timestamps, local files awaiting upload and accepted suggestions live beside it.
-### Source mode
-
-The editor's `mode` option shows the whole memo as Markdown text and edits it as plain text (see the editor README's "Source mode"). Every composer offers it, hosted ones included, because it changes how the text is edited, not the frame: the + menu has a "Source Mode" checkbox item, and while it is on, `EditorContent` puts a small "Source" tag in the editor's top-right corner, styled like a code block's language label, that says why autocomplete and formatting are gone and switches back. The editor's first line leaves room for the tag (a float sized by `--memo-source-tag-width` in `Editor/editor.css`), so the rest of the text keeps its full width. `useSourceMode` keeps the choice in localStorage (`memos-editor-mode`), so it is per device and every composer mounted afterwards opens in it. Switching changes no text, so saving, drafts and `state.content` are unaffected. In source mode:
-
-- The editor's toolbar, slash menu, autocomplete and formatting keys are off, and the checklist suggestion chip is hidden because `toggleTaskList()` cannot apply.
-- The editor's document is one block of Markdown text, so the controller reads `getTags()` and `hasChecklist()` from the text parsed as a memo, not from its blocks. Insertions (`insertMarkdown`, `insertTag`, upload anchors) work as in rich mode.
-- A selection's shape depends on the mode, so `cacheService` stores the mode with a saved caret and does not restore a caret taken in the other mode.
-
-### Editor extensions
-
-`lib/memo-markdown.ts` holds what the composer and the memo view share: the memo Markdown dialect (`breaks: true`, `setext: false`, and the editor's defaults for GitHub alerts as callouts and `<details>` as collapsible sections); `memoExtensions()` (math rendered with KaTeX loaded on demand, footnotes, `#tags` and `@mentions`, code highlighted with highlight.js, ```` ```mermaid ```` diagrams, and raw HTML through the sanitizer in `lib/sanitized-html.ts`); the URL policy for links and images (`memoResolveUrl`); the theme in the app's CSS variables; the translated UI labels; and the tag and mention collectors. Whatever the editor renders shows its source at the caret while editing.
-
-`Editor/extensions.ts` adds what only the composer needs: the `#tag` autocomplete (`suggestion()` with `matchToken(scanTags)`, so the popup opens exactly where tags are highlighted; not inside code or links, and not for a bare `#` at the start of a line, which may be a heading) with items from `useTagCounts`, `:emoji` autocomplete from `@usememos/editor/emoji` (its list loads the first time the popup opens), and a `fileHandler()`: pasted files join the attachment list, dropped images are inserted inline where they land and other dropped files are attached.
+### The editor contract
-Keys are the editor's own (see its README): Mod+B/I/E, Mod+Shift+S, Mod+Alt+0–4, Mod+Alt+C, Mod+Shift+6 (collapsible section), Mod+Shift+7–9, Tab/Shift+Tab, and Mod+Enter / Ctrl+Enter to save. The first Escape selects the caret's block; a second Escape leaves the editor.
+`edit/types/editorController.ts` defines `EditorController`: document access (`getMarkdown`, `setMarkdown`, `insertMarkdown`), selection and focus, the upload-anchor group, `getTags`, `hasChecklist`, `insertTag` and `toggleTaskList`. The chrome uses this interface and never reaches into the editor's own API. `edit/controller.ts` implements it over the live editor; calls before mount or after destroy do nothing.
-### Tags and mentions
+### Formatting and source mode
-Highlighting, autocomplete, `EditorController.getTags()` and the memo view all use the editor's scanners (`scanTags`, `scanMentions`), which skip code, links, images and extension tokens, so what is highlighted is what counts. `extractMentionUsernames` in `lib/memo-markdown.ts` reads mentions the same way to decide which users to resolve.
+Formatting is the editor's own: its toolbar appears over selected text, the slash menu and Markdown shortcuts change block types, and its keys cover the rest. The editor's `mode` option shows the whole memo as Markdown text and edits it as plain text; `useSourceMode` remembers the choice per device. In source mode the toolbar, slash menu, autocomplete and formatting keys are off, the checklist chip is hidden, and the controller reads tags and checklists from the text parsed as a memo.
-### Services
+### Saving
-Pure TypeScript functions containing business logic. No React hooks, easy to test.
+`useMemoSave` validates the draft, uploads local files, and hands the save to `memoService.save` with the operations it runs: the server's current copy (fetched into the detail cache to diff against), `useUpdateMemo` and `useCreateMemo`. Hosts that close after saving (edit, comment) hold a brief "Saved" confirmation before the session resets; the in-place composer resets at once. Uploads that landed before a failed save stay on the draft as attachments so a retry does not upload them again.
### Suggestions
-Hosts of a new top-level memo (Home, the global composer) pass `useMemoSuggestions()`
-into the `suggestions` prop; edits and comments omit the bar. `lib/memo-suggestions.ts`
-merges typed candidates from providers and keeps the strongest source per id
-(selection, then search, then the selected View). `lib/suggestion-expression.ts` is a
-small Boolean CEL reader shared by the providers; unsupported syntax never falls back
-to scanning free text.
+Hosts of a new top-level memo pass `useMemoSuggestions()` into `suggestions`; edits and comments show none. `EditorSuggestions` hides until the draft has text, drops suggestions already satisfied or accepted, and shows at most three. Acceptance history lives in the store so Undo does not immediately resuggest, and clears with the draft.
-- Tags: explicit tag conditions and selected tags. `insertTag()` is one isolated undo
- step at the caret that keeps selected text and honors the current Markdown context.
-- Checklist: task-list conditions in saved Views or filters; a negative
- task-list or incomplete-task condition suppresses it.
-- Visibility: exactly one explicit audience across filters and View, otherwise nothing.
- Space visibility also requires actual Space placement.
+### Presentation: in a card, inline, hosted
-`EditorSuggestions` hides until the draft has text, drops suggestions already satisfied
-(via the Markdown-aware `getTags()` / `hasChecklist()`, so code examples do not count)
-or already accepted, and shows at most three across kinds. Acceptance history lives in
-the editor store so Undo or reverting a choice does not immediately resuggest it, and it
-clears with the draft on reset; nothing is persisted with the memo. `SuggestionsBar` is
-payload-agnostic; a new kind extends the `MemoSuggestion` union and its
-eligibility/application in `EditorSuggestions`.
+- **In a card** (`frameless`): the card is the frame, so the session has no background, border or padding of its own outside focus mode. `MemoView` flips its body into the session by name and keeps its header, frame and reactions mounted.
+- **Inline** (Home, panels): the session brings its own frame. The + menu offers focus mode, which expands it over the page; the exit button minimizes it back.
+- **Hosted** (`onFocusModeExit`): a host presents the session full-screen and owns that frame (`contexts/GlobalMemoEditorContext.tsx`). It mounts straight into focus mode and exits by calling back to dismiss the host.
-### Presentation: inline vs hosted
-
-Every instance is one of two things, and `onFocusModeExit` is the switch:
-
-- **Inline** (prop omitted) — the editor sits in page flow (Home composer, memo edit, comments) and owns its presentation. The + menu offers focus mode, which expands the editor over the page; the exit button in its top row minimizes it back in place.
-- **Hosted** (prop supplied) — a host presents the editor full-screen and owns that frame; `contexts/GlobalMemoEditorContext.tsx` is the one today. The editor mounts straight into focus mode and exits by calling back to dismiss the host, so the exit button reads as Close rather than minimize. The + menu's view toggle is absent: focus mode is not the editor's to leave.
-
-The toggle travels as an optional `viewToggles` object (`types/components.ts`) down `EditorToolbar` → `InsertMenu`. The source-mode switch is not a view toggle and travels separately as `sourceMode` to `InsertMenu` and `EditorContent`, which every instance has.
+The session's code is a chunk of its own, loaded when a memo is first edited or composed, and renders without suspending once loaded; a host that knows an editor is coming calls `preloadMemoEditing()`.
### Destination and visibility
-`AudienceMenu` is one dropdown for a memo's visibility and, where allowed, its Space. Visibility options come first; the Space is an optional row below them that never names the empty state: it reads "Add to space" until one is chosen, then shows the Space, and the selected Space in its submenu toggles back off (a check at rest, an ✕ under the pointer or keyboard, always an ✕ on touch). New top-level memos and edits of top-level memos the user can manage offer the row; a host-provided `defaultSpace` fixes a new memo's placement, and comments never offer it because their Space is the parent's. The destination lives in editor metadata: it is sent on creation, and an edit that changes it sends `space` and `visibility` together so the server can validate the move as one transition. Clearing a Space-only audience resets it to Private; adding a Space never changes the audience. Drafts retain destination and visibility alongside content, attachments, and location. Long names are truncated, with their full text retained for accessible labels and hover titles. Moving a memo between Spaces happens here; there is no separate move dialog.
-
-### Lifecycle hooks
-
-Cross-cutting React workflows stay outside the editor shell. `useMemoSave`
-coordinates validation, persistence, query invalidation, and post-save reducer
-state. `useFocusMode` owns focus mode's DOM lifecycle, including restoring the
-previous body scroll style and preserving the editor's place in grid layouts.
-
-### Components
+`AudienceMenu` is one dropdown for a memo's visibility and, where allowed, its Space. New top-level memos and edits of top-level memos the user can manage offer the Space row; a draft seed's `space` fixes a new memo's placement; comments never offer it because their Space is their parent's. An edit that changes the Space sends `space` and `visibility` together so the server validates the move as one transition.
-Thin presentation components that dispatch actions and render UI.
+## Directory structure
-## Usage
-
-```typescript
-import MemoEditor from "@/components/MemoEditor";
-
-// Create mode: omit `memo`. Pass an existing Memo to edit it instead.
-<MemoEditor
- cacheKey="home-composer"
- onConfirm={(name) => console.log('Saved:', name)}
- onCancel={() => console.log('Cancelled')}
-/>
+```
+MemoEditor/
+├── index.ts # MemoEditor, preloadMemoEditing, prop types
+├── MemoEditor.tsx # The memo-level component: modes, data, draft store, lazy session
+├── MemoMarkdown.tsx # The editor binding
+├── useMemoDecorations.ts # Tag colors and resolved mentions, one redecorate
+├── view/ # Read-only surface: MemoContentView, linkCards, headings, navigation, search highlight
+└── edit/ # Editing surface
+ ├── EditSession.tsx # The chrome over the draft store
+ ├── Editor.tsx # MemoMarkdown editable + composer extensions + controller
+ ├── controller.ts, extensions.ts, uploadAnchors.ts, editor.css
+ ├── draftKey.ts # Identity → draft key, legacy migration
+ ├── initialState.ts # The store's first state, from the memo or the draft
+ ├── state/, services/, hooks/, components/, Toolbar/, types/, utils/
+ └── constants.ts
```
## Testing
-Services are pure functions — easy to unit test without React.
-
-```typescript
-const state = createInitialState(); // from state/types.ts
-const result = await memoService.save(state, { memoName: 'memos/123' });
-```
+- `tests/memo-record.test.tsx`: reads by name, freshness, optimistic patches, the comment mutations.
+- `tests/memo-editor-view.test.tsx`: view mode by name, task ticking through the mutation.
+- `tests/memo-content-view.test.tsx`, `tests/editor.test.tsx`: the surfaces over the binding.
+- `tests/use-memo-init.test.tsx`, `tests/draft-key.test.ts`, `tests/use-auto-save.test.tsx`: drafts and keys.
+- `tests/use-memo-save.test.tsx`, `tests/memo-editor-*.test.ts*`: the session and its save path. Tests that mount the session call `await preloadMemoEditing()` first so it renders without suspending.
diff --git a/web/src/components/MemoEditor/components/EditorContent.tsx b/web/src/components/MemoEditor/components/EditorContent.tsx
deleted file mode 100644
index 7ddde9301..000000000
--- a/web/src/components/MemoEditor/components/EditorContent.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-import { forwardRef, useLayoutEffect, useRef } from "react";
-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import { useTranslate } from "@/utils/i18n";
-import Editor from "../Editor";
-import { useEditorContext, useEditorSelector } from "../state";
-import type { EditorContentProps } from "../types";
-import type { EditorController } from "../types/editorController";
-
-// Imported eagerly (not React.lazy): the editor is the always-present compose
-// box on the home route, which is already code-split — so deferring the
-// editor bundle separately bought nothing and made the editor paint empty
-// for a beat before its placeholder appeared (a visible flicker on load).
-
-/**
- * Hosts the Markdown Editor behind the EditorController contract. The
- * editor writes into state.content on every change.
- */
-export const EditorContent = forwardRef<EditorController, EditorContentProps>(
- ({ placeholder, sourceMode, onSubmit, onFiles, tagsSetting }, ref) => {
- const t = useTranslate();
- const wrapperRef = useRef<HTMLDivElement>(null);
- const sourceTagRef = useRef<HTMLButtonElement>(null);
- const isSourceMode = sourceMode.isSourceMode;
- const sourceLabel = t("editor.source");
- // The first line of the text leaves room for the tag; its width varies by language.
- useLayoutEffect(() => {
- const width = isSourceMode ? sourceTagRef.current?.offsetWidth : undefined;
- wrapperRef.current?.style.setProperty("--memo-source-tag-width", width ? `${width}px` : "0px");
- }, [isSourceMode, sourceLabel]);
- const { actions, dispatch } = useEditorContext();
- const content = useEditorSelector((s) => s.content);
- const isFocusMode = useEditorSelector((s) => s.ui.isFocusMode);
- const attachments = useEditorSelector((s) => s.metadata.attachments);
-
- const handleContentChange = (content: string) => {
- dispatch(actions.updateContent(content));
- };
-
- return (
- <div ref={wrapperRef} className="relative w-full flex flex-col flex-1">
- <Editor
- ref={ref}
- className="memo-editor-content"
- value={content}
- placeholder={placeholder || ""}
- isFocusMode={isFocusMode}
- mode={isSourceMode ? "source" : "rich"}
- attachments={attachments}
- tagsSetting={tagsSetting}
- onContentChange={handleContentChange}
- onFiles={onFiles}
- onSubmit={onSubmit}
- />
- {/* Source mode names itself in the corner, as a code block names its language, and switches back from there.
- It fills on hover like the toolbar's quiet buttons, so it reads as a button once pointed at. */}
- {isSourceMode && (
- <Tooltip>
- <TooltipTrigger
- render={
- <button
- ref={sourceTagRef}
- type="button"
- onClick={sourceMode.onToggle}
- className="absolute end-0 top-0.5 flex h-5 cursor-pointer items-center rounded px-1 text-2xs text-muted-foreground outline-none transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:bg-muted/60 focus-visible:text-foreground"
- />
- }
- >
- {sourceLabel}
- </TooltipTrigger>
- <TooltipContent side="top">{t("editor.switch-to-rich-text")}</TooltipContent>
- </Tooltip>
- )}
- </div>
- );
- },
-);
-
-EditorContent.displayName = "EditorContent";
diff --git a/web/src/components/MemoEditor/index.tsx b/web/src/components/MemoEditor/edit/EditSession.tsx
similarity index 90%
rename from web/src/components/MemoEditor/index.tsx
rename to web/src/components/MemoEditor/edit/EditSession.tsx
index d031149b7..223fb0deb 100644
--- a/web/src/components/MemoEditor/index.tsx
+++ b/web/src/components/MemoEditor/edit/EditSession.tsx
@@ -7,11 +7,11 @@ import { cn } from "@/lib/utils";
import { InstanceSetting_Key } from "@/types/proto/api/instance_service_pb";
import { useTranslate } from "@/utils/i18n";
import { convertVisibilityFromString } from "@/utils/memo";
-import { canManageMemo } from "@/utils/user";
+
import { AudioRecorderPanel, EditorContent, EditorMetadata, FocusModeExitButton, FocusModeOverlay, TimestampPopover } from "./components";
import { EditorSuggestions } from "./components/EditorSuggestions";
import { FOCUS_MODE_STYLES } from "./constants";
-import type { EditorFileOrigin } from "./Editor/extensions";
+import type { EditorFileOrigin } from "./extensions";
import {
splitInlineLocalFiles,
toLocalFiles,
@@ -25,29 +25,30 @@ import {
useMemoSave,
useSourceMode,
} from "./hooks";
+import { canChooseSpaceFor } from "./initialState";
import { cacheService, errorService, transcriptionService } from "./services";
-import { EditorProvider, useEditorContext, useEditorSelector } from "./state";
+import { useEditorContext, useEditorSelector } from "./state";
import { EditorToolbar } from "./Toolbar";
-import type { EditorViewToggles, MemoEditorProps } from "./types";
+import type { EditorViewToggles, EditSessionProps } from "./types";
import type { LocalFile } from "./types/attachment";
import type { EditorController, EditorPosition } from "./types/editorController";
-// A host that presents the editor full-screen supplies `onFocusModeExit`; its
-// presence is what makes an instance hosted, so focus mode starts on and stays on.
-const MemoEditor = (props: MemoEditorProps) => (
- <EditorProvider initialFocusMode={Boolean(props.onFocusModeExit)}>
- <MemoEditorImpl {...props} />
- </EditorProvider>
-);
-
-const MemoEditorImpl: React.FC<MemoEditorProps> = ({
+/**
+ * An editing session over the draft store MemoEditor provides: the editor with the
+ * composer's chrome around it (timestamp, attachments, suggestions, toolbar, focus
+ * mode, audio recording), the draft persisted while it is open, and the save that
+ * writes the memo through the memo mutations. A host that presents the editor
+ * full-screen supplies `onFocusModeExit`; its presence is what makes an instance
+ * hosted, so focus mode starts on and stays on.
+ */
+export const EditSession: React.FC<EditSessionProps> = ({
className,
- cacheKey,
+ draftKey,
+ frameless,
memo,
parentMemoName,
suggestions = [],
defaultSpace,
- defaultLocation,
autoFocus,
onFocusModeExit,
onFocusModeChange,
@@ -71,7 +72,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
}, [isFocusMode, onFocusModeChange]);
const isSaving = useEditorSelector((s) => s.ui.isLoading.saving);
const hasTimestamp = useEditorSelector((s) => Boolean(s.timestamps.createTime));
- const { userGeneralSetting, userTagsSetting } = useAuth();
+ const { userGeneralSetting } = useAuth();
const { aiSetting, fetchSetting } = useInstance();
const [isAudioRecorderOpen, setIsAudioRecorderOpen] = useState(false);
const [isTranscribingAudio, setIsTranscribingAudio] = useState(false);
@@ -85,7 +86,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
// An edited top-level memo can change its Space; a new one can unless its
// host fixes the target (e.g. composing inside a Space).
const draftSpace = useEditorSelector((s) => s.metadata.space);
- const canChooseSpace = memo ? !memo.parent && canManageMemo(memo, currentUser) : !parentMemoName && !defaultSpace;
+ const canChooseSpace = canChooseSpaceFor({ memo, currentUser, parentMemoName, defaultSpace });
const editorSpace = memo ? draftSpace : parentMemoName ? undefined : (defaultSpace ?? draftSpace);
const canTranscribe = useMemo(() => {
const providerId = aiSetting.transcription?.providerId ?? "";
@@ -96,25 +97,14 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
// Get default visibility from user settings
const defaultVisibility = userGeneralSetting?.memoVisibility ? convertVisibilityFromString(userGeneralSetting.memoVisibility) : undefined;
- const editorCacheKey = cacheService.key(currentUser?.name ?? "", cacheKey);
// Source mode only changes how the text is edited, so every composer offers it.
const [editorMode, setEditorMode] = useSourceMode();
const isSourceMode = editorMode === "source";
const sourceMode = { isSourceMode, onToggle: () => setEditorMode(isSourceMode ? "rich" : "source") };
- const { isInitialized } = useMemoInit({
- editorRef,
- memo,
- cacheKey,
- username: currentUser?.name ?? "",
- autoFocus,
- defaultVisibility,
- defaultCreateTime,
- defaultLocation,
- canChooseSpace,
- mode: editorMode,
- });
+ const { isInitialized } = useMemoInit({ editorRef, draftKey, autoFocus, mode: editorMode });
+ // An edit starts from the memo and never persists a draft; only new memos and comments do.
const isDraftCacheEnabled = !memo;
useEffect(() => {
@@ -122,7 +112,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
}, [isSaving, onSavingChange]);
// Auto-save content to localStorage (subscribes to the store internally).
- const { discardDraft } = useAutoSave(currentUser?.name ?? "", cacheKey, isInitialized && isDraftCacheEnabled);
+ const { discardDraft } = useAutoSave(draftKey, isInitialized && isDraftCacheEnabled);
const { containerRef: editorContainerRef, placeholderHeight } = useFocusMode(isFocusMode);
@@ -231,9 +221,9 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
const rememberCursor = useCallback(() => {
const cursor = editorRef.current?.getSelection();
if (cursor !== undefined) {
- cacheService.saveCursor(editorCacheKey, cursor, editorMode);
+ cacheService.saveCursor(draftKey, cursor, editorMode);
}
- }, [editorCacheKey, editorMode]);
+ }, [draftKey, editorMode]);
// Hosted: focus mode is the host's frame, so leaving it dismisses the host.
// Inline: focus mode is a view this editor owns and toggles in place.
@@ -351,7 +341,10 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
<div
ref={editorContainerRef}
className={cn(
- "group relative w-full flex flex-col justify-between items-start bg-card px-4 py-3 rounded-lg border border-border/70 gap-2",
+ "group relative w-full flex flex-col justify-between items-start gap-2",
+ // A card that is the frame already supplies the background, border and padding; a
+ // session floating over the page in focus mode always brings its own.
+ (!frameless || isFocusMode) && "bg-card px-4 py-3 rounded-lg border border-border/70",
FOCUS_MODE_STYLES.transition,
isFocusMode && cn(FOCUS_MODE_STYLES.container.base, FOCUS_MODE_STYLES.container.spacing),
!isFocusMode && className,
@@ -379,7 +372,6 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
sourceMode={sourceMode}
onSubmit={handleSave}
onFiles={handleEditorFiles}
- tagsSetting={userTagsSetting}
/>
{isAudioRecorderOpen && (audioRecorder.isBusy || isTranscribingAudio) && (
@@ -425,5 +417,3 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
</>
);
};
-
-export default MemoEditor;
diff --git a/web/src/components/MemoEditor/Editor/index.tsx b/web/src/components/MemoEditor/edit/Editor.tsx
similarity index 55%
rename from web/src/components/MemoEditor/Editor/index.tsx
rename to web/src/components/MemoEditor/edit/Editor.tsx
index c2d31f442..2ae10b854 100644
--- a/web/src/components/MemoEditor/Editor/index.tsx
+++ b/web/src/components/MemoEditor/edit/Editor.tsx
@@ -1,16 +1,12 @@
import type { EditorMode, Editor as MarkdownEditorInstance } from "@usememos/editor";
-import { MarkdownEditor } from "@usememos/editor/react";
-import "@usememos/editor/style.css";
-import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
-import { useDebouncedEffect } from "@/hooks";
-import { useTagCounts, useUsersByUsernames } from "@/hooks/useUserQueries";
-import { extractMentionUsernames, MEMO_EDITOR_THEME, MEMO_MARKDOWN, memoEditorLabels, memoResolveUrl } from "@/lib/memo-markdown";
+import { forwardRef, useImperativeHandle, useMemo, useRef } from "react";
+import { useTagCounts } from "@/hooks/useUserQueries";
import { cn } from "@/lib/utils";
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
-import type { UserSetting_TagsSetting } from "@/types/proto/api/user_service_pb";
import { useTranslate } from "@/utils/i18n";
-import type { EditorController } from "../types/editorController";
+import { MemoMarkdown } from "../MemoMarkdown";
import { createController } from "./controller";
+import type { EditorController } from "./types/editorController";
import "./editor.css";
import { buildEditorExtensions, type EditorFileOrigin } from "./extensions";
@@ -28,8 +24,6 @@ interface EditorProps {
mode?: EditorMode;
/** The draft's attachments, so images of managed attachments show. */
attachments?: readonly Attachment[];
- /** The user's tag settings, for tags in their custom colors. */
- tagsSetting?: UserSetting_TagsSetting;
}
const EDITOR_ATTRIBUTES = {
@@ -41,55 +35,21 @@ const EDITOR_ATTRIBUTES = {
spellcheck: "true",
};
+/** The composer's editor: MemoMarkdown, editable, with the composer's extensions, behind the EditorController contract. */
const Editor = forwardRef(function Editor(props: EditorProps, ref: React.ForwardedRef<EditorController>) {
- const { className, value, placeholder, onContentChange, onFiles, onSubmit, isFocusMode, mode, attachments, tagsSetting } = props;
+ const { className, value, placeholder, onContentChange, onFiles, onSubmit, isFocusMode, mode, attachments } = props;
const t = useTranslate();
const editorRef = useRef<MarkdownEditorInstance | null>(null);
const onContentChangeRef = useRef(onContentChange);
onContentChangeRef.current = onContentChange;
const onFilesRef = useRef(onFiles);
onFilesRef.current = onFiles;
- const onSubmitRef = useRef(onSubmit);
- onSubmitRef.current = onSubmit;
// A user can only author their own memos. Reuse the current-user stats query
// instead of fetching and aggregating every user's tags for autocomplete.
const { data: tagData } = useTagCounts(true);
const tagsRef = useRef<string[]>([]);
tagsRef.current = useMemo(() => Object.keys(tagData ?? {}), [tagData]);
- const tagsSettingRef = useRef(tagsSetting);
- tagsSettingRef.current = tagsSetting;
- // Tag colors are drawn from the settings; draw them again when the settings change.
- const decoratedTagsSetting = useRef(tagsSetting);
- useEffect(() => {
- if (decoratedTagsSetting.current === tagsSetting) return;
- decoratedTagsSetting.current = tagsSetting;
- editorRef.current?.redecorate();
- }, [tagsSetting]);
-
- // Mentions of people who exist are drawn as in the memo view. The names are looked up
- // once typing pauses, so a half-typed name is not; until a lookup answers, the people
- // already found stay found.
- const [mentionNames, setMentionNames] = useState<string[]>([]);
- useDebouncedEffect(
- () => {
- const next = extractMentionUsernames(value);
- setMentionNames((previous) => (previous.join("\n") === next.join("\n") ? previous : next));
- },
- 400,
- [value],
- );
- const { data: mentionUsers } = useUsersByUsernames(mentionNames);
- const resolvedMentionsRef = useRef<ReadonlySet<string>>(new Set());
- useEffect(() => {
- if (!mentionUsers) return;
- const next = new Set([...mentionUsers].flatMap(([username, user]) => (user ? [username] : [])));
- const current = resolvedMentionsRef.current;
- if (next.size === current.size && [...next].every((username) => current.has(username))) return;
- resolvedMentionsRef.current = next;
- editorRef.current?.redecorate();
- }, [mentionUsers]);
-
const controller = useMemo(
() =>
createController(
@@ -107,15 +67,11 @@ const Editor = forwardRef(function Editor(props: EditorProps, ref: React.Forward
buildEditorExtensions({
getTags: () => tagsRef.current,
onFiles: (files, origin) => onFilesRef.current(files, origin),
- getTagsSetting: () => tagsSettingRef.current,
- isMentionResolved: (username) => resolvedMentionsRef.current.has(username),
// Read once, like the rest: the popup keeps the language the composer opened in.
emojiLabel: t("editor.blocks.emoji"),
}),
[],
);
- const labels = useMemo(() => memoEditorLabels(t), [t]);
- const resolveUrl = useMemo(() => memoResolveUrl(attachments), [attachments]);
return (
<div
@@ -124,20 +80,17 @@ const Editor = forwardRef(function Editor(props: EditorProps, ref: React.Forward
data-source-mode={mode === "source" || undefined}
>
<div className={cn("memo-editor-scroller w-full text-base", isFocusMode && "min-h-0 flex-1")}>
- <MarkdownEditor
- ref={editorRef}
+ <MemoMarkdown
+ editorRef={editorRef}
value={value}
+ editable
onChange={onContentChange}
- onSubmit={() => onSubmitRef.current()}
+ onSubmit={onSubmit}
placeholder={placeholder}
mode={mode}
- markdown={MEMO_MARKDOWN}
+ attachments={attachments}
extensions={extensions}
- theme={MEMO_EDITOR_THEME}
- labels={labels}
attributes={EDITOR_ATTRIBUTES}
- resolveUrl={resolveUrl}
- referrerPolicy="no-referrer"
className="memo-editor-root"
/>
</div>
diff --git a/web/src/components/MemoEditor/Toolbar/AudienceMenu.tsx b/web/src/components/MemoEditor/edit/Toolbar/AudienceMenu.tsx
similarity index 100%
rename from web/src/components/MemoEditor/Toolbar/AudienceMenu.tsx
rename to web/src/components/MemoEditor/edit/Toolbar/AudienceMenu.tsx
diff --git a/web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx b/web/src/components/MemoEditor/edit/Toolbar/EditorToolbar.tsx
similarity index 100%
rename from web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx
rename to web/src/components/MemoEditor/edit/Toolbar/EditorToolbar.tsx
diff --git a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx b/web/src/components/MemoEditor/edit/Toolbar/InsertMenu.tsx
similarity index 100%
rename from web/src/components/MemoEditor/Toolbar/InsertMenu.tsx
rename to web/src/components/MemoEditor/edit/Toolbar/InsertMenu.tsx
diff --git a/web/src/components/MemoEditor/Toolbar/index.ts b/web/src/components/MemoEditor/edit/Toolbar/index.ts
similarity index 100%
rename from web/src/components/MemoEditor/Toolbar/index.ts
rename to web/src/components/MemoEditor/edit/Toolbar/index.ts
diff --git a/web/src/components/MemoEditor/components/AudioRecorderPanel.tsx b/web/src/components/MemoEditor/edit/components/AudioRecorderPanel.tsx
similarity index 100%
rename from web/src/components/MemoEditor/components/AudioRecorderPanel.tsx
rename to web/src/components/MemoEditor/edit/components/AudioRecorderPanel.tsx
diff --git a/web/src/components/MemoEditor/edit/components/EditorContent.tsx b/web/src/components/MemoEditor/edit/components/EditorContent.tsx
new file mode 100644
index 000000000..68d1e62a0
--- /dev/null
+++ b/web/src/components/MemoEditor/edit/components/EditorContent.tsx
@@ -0,0 +1,74 @@
+import { forwardRef, useLayoutEffect, useRef } from "react";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { useTranslate } from "@/utils/i18n";
+import Editor from "../Editor";
+import { useEditorContext, useEditorSelector } from "../state";
+import type { EditorContentProps } from "../types";
+import type { EditorController } from "../types/editorController";
+
+// The editor itself is imported eagerly: the memo view needs it on every page, so
+// splitting it would only make the composer paint empty for a beat. The session
+// around it is what loads lazily (see MemoEditor.tsx).
+
+/**
+ * Hosts the Markdown Editor behind the EditorController contract. The
+ * editor writes into state.content on every change.
+ */
+export const EditorContent = forwardRef<EditorController, EditorContentProps>(({ placeholder, sourceMode, onSubmit, onFiles }, ref) => {
+ const t = useTranslate();
+ const wrapperRef = useRef<HTMLDivElement>(null);
+ const sourceTagRef = useRef<HTMLButtonElement>(null);
+ const isSourceMode = sourceMode.isSourceMode;
+ const sourceLabel = t("editor.source");
+ // The first line of the text leaves room for the tag; its width varies by language.
+ useLayoutEffect(() => {
+ const width = isSourceMode ? sourceTagRef.current?.offsetWidth : undefined;
+ wrapperRef.current?.style.setProperty("--memo-source-tag-width", width ? `${width}px` : "0px");
+ }, [isSourceMode, sourceLabel]);
+ const { actions, dispatch } = useEditorContext();
+ const content = useEditorSelector((s) => s.content);
+ const isFocusMode = useEditorSelector((s) => s.ui.isFocusMode);
+ const attachments = useEditorSelector((s) => s.metadata.attachments);
+
+ const handleContentChange = (content: string) => {
+ dispatch(actions.updateContent(content));
+ };
+
+ return (
+ <div ref={wrapperRef} className="relative w-full flex flex-col flex-1">
+ <Editor
+ ref={ref}
+ className="memo-editor-content"
+ value={content}
+ placeholder={placeholder || ""}
+ isFocusMode={isFocusMode}
+ mode={isSourceMode ? "source" : "rich"}
+ attachments={attachments}
+ onContentChange={handleContentChange}
+ onFiles={onFiles}
+ onSubmit={onSubmit}
+ />
+ {/* Source mode names itself in the corner, as a code block names its language, and switches back from there.
+ It fills on hover like the toolbar's quiet buttons, so it reads as a button once pointed at. */}
+ {isSourceMode && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <button
+ ref={sourceTagRef}
+ type="button"
+ onClick={sourceMode.onToggle}
+ className="absolute end-0 top-0.5 flex h-5 cursor-pointer items-center rounded px-1 text-2xs text-muted-foreground outline-none transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:bg-muted/60 focus-visible:text-foreground"
+ />
+ }
+ >
+ {sourceLabel}
+ </TooltipTrigger>
+ <TooltipContent side="top">{t("editor.switch-to-rich-text")}</TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ );
+});
+
+EditorContent.displayName = "EditorContent";
diff --git a/web/src/components/MemoEditor/components/EditorMetadata.tsx b/web/src/components/MemoEditor/edit/components/EditorMetadata.tsx
similarity index 100%
rename from web/src/components/MemoEditor/components/EditorMetadata.tsx
rename to web/src/components/MemoEditor/edit/components/EditorMetadata.tsx
diff --git a/web/src/components/MemoEditor/components/EditorSuggestions.tsx b/web/src/components/MemoEditor/edit/components/EditorSuggestions.tsx
similarity index 100%
rename from web/src/components/MemoEditor/components/EditorSuggestions.tsx
rename to web/src/components/MemoEditor/edit/components/EditorSuggestions.tsx
diff --git a/web/src/components/MemoEditor/components/FocusModeOverlay.tsx b/web/src/components/MemoEditor/edit/components/FocusModeOverlay.tsx
similarity index 100%
rename from web/src/components/MemoEditor/components/FocusModeOverlay.tsx
rename to web/src/components/MemoEditor/edit/components/FocusModeOverlay.tsx
diff --git a/web/src/components/MemoEditor/components/TimestampPopover.tsx b/web/src/components/MemoEditor/edit/components/TimestampPopover.tsx
similarity index 100%
rename from web/src/components/MemoEditor/components/TimestampPopover.tsx
rename to web/src/components/MemoEditor/edit/components/TimestampPopover.tsx
diff --git a/web/src/components/MemoEditor/components/VoiceWaveform.tsx b/web/src/components/MemoEditor/edit/components/VoiceWaveform.tsx
similarity index 100%
rename from web/src/components/MemoEditor/components/VoiceWaveform.tsx
rename to web/src/components/MemoEditor/edit/components/VoiceWaveform.tsx
diff --git a/web/src/components/MemoEditor/components/index.ts b/web/src/components/MemoEditor/edit/components/index.ts
similarity index 100%
rename from web/src/components/MemoEditor/components/index.ts
rename to web/src/components/MemoEditor/edit/components/index.ts
diff --git a/web/src/components/MemoEditor/constants.ts b/web/src/components/MemoEditor/edit/constants.ts
similarity index 100%
rename from web/src/components/MemoEditor/constants.ts
rename to web/src/components/MemoEditor/edit/constants.ts
diff --git a/web/src/components/MemoEditor/Editor/controller.ts b/web/src/components/MemoEditor/edit/controller.ts
similarity index 62%
rename from web/src/components/MemoEditor/Editor/controller.ts
rename to web/src/components/MemoEditor/edit/controller.ts
index 469b4111e..b870e07ab 100644
--- a/web/src/components/MemoEditor/Editor/controller.ts
+++ b/web/src/components/MemoEditor/edit/controller.ts
@@ -1,7 +1,7 @@
-import { type Block, containerContent, type Editor, getBlock, inlineText, type Position, type Widget } from "@usememos/editor";
+import { type Block, type Editor, inlineText, type Widget } from "@usememos/editor";
import { collectTags, parseMemoMarkdown } from "@/lib/memo-markdown";
import { isCompleteTagValue } from "@/utils/tag-grammar";
-import type { EditorController } from "../types/editorController";
+import type { EditorController } from "./types/editorController";
import { renderUploadAnchor } from "./uploadAnchors";
/** The live editor, or null before it mounts and after it is destroyed. */
@@ -12,12 +12,6 @@ const live = (getEditor: EditorGetter): Editor | null => {
return editor && !editor.isDestroyed ? editor : null;
};
-/** The text of the block (or table cell) holding `position`. */
-const textAt = (editor: Editor, position: Position): string => {
- const content = containerContent(getBlock(editor.state.doc, position.blockId), position.cell);
- return content ? inlineText(content) : "";
-};
-
/**
* The memo's blocks. Source mode holds the whole memo as one block of Markdown
* text, so the blocks are read from that text instead.
@@ -25,23 +19,9 @@ const textAt = (editor: Editor, position: Position): string => {
const memoBlocks = (editor: Editor): readonly Block[] =>
editor.mode === "source" ? parseMemoMarkdown(editor.getMarkdown()).blocks : editor.state.doc.blocks;
-/** An empty paragraph, which an inserted block should replace rather than follow. */
+/** An empty paragraph, which inserted blocks take the place of rather than follow. */
const isEmptyParagraph = (block: Block): boolean => block.type === "paragraph" && inlineText(block.content) === "";
-/**
- * Inserts Markdown as its own blocks at `position`. In an empty paragraph it
- * takes the paragraph's place, as a paste would, so no empty line is left
- * above the inserted content.
- */
-const insertBlocks = (editor: Editor, markdown: string, position: Position): void => {
- if (isEmptyParagraph(getBlock(editor.state.doc, position.blockId))) {
- editor.setSelection({ anchor: position, focus: position });
- editor.commands.insertMarkdown(markdown, { block: true });
- } else {
- editor.commands.insertMarkdown(markdown, { at: position, block: true });
- }
-};
-
/**
* EditorController over a @usememos/editor instance. Every method reads the
* live editor when called, so the controller can be handed out before the
@@ -74,8 +54,9 @@ export function createController(getEditor: EditorGetter, onReplace: (markdown:
if (!editor || !markdown) return;
// Insert at the caret without consuming the selection: callers live outside
// the editor (attachment list, audio recorder), and replacing the range
- // would delete text the user merely had highlighted.
- insertBlocks(editor, markdown, editor.getSelection().focus);
+ // would delete text the user merely had highlighted. An empty paragraph at
+ // the caret is replaced, as a paste would.
+ editor.commands.insertMarkdown(markdown, { at: editor.getSelection().focus, block: true });
editor.commands.focus();
editor.commands.scrollIntoView();
},
@@ -89,21 +70,10 @@ export function createController(getEditor: EditorGetter, onReplace: (markdown:
},
insertTag: (tag) => {
const editor = live(getEditor);
- if (!editor || !isCompleteTagValue(tag) || editor.isComposing || currentTags(editor).includes(tag)) return false;
- // Like insertMarkdown, keep highlighted text and insert at the active end.
- // Honor the chosen Markdown context, including code, instead of relocating it.
- const head = editor.getSelection().focus;
- const text = textAt(editor, head);
- const prefix = head.offset > 0 && !/\s/.test(text[head.offset - 1] ?? "") ? " " : "";
- const hasFollowingSpace = /^[ \t]$/.test(text[head.offset] ?? "");
- editor.setSelection({ anchor: head, focus: head });
- editor.commands.insertText(`${prefix}#${tag}${hasFollowingSpace ? "" : " "}`);
- if (hasFollowingSpace) {
- // Exactly one space follows the tag, inserted or reused; the caret lands after it.
- const after = editor.getSelection().focus;
- const next = { ...after, offset: after.offset + 1 };
- editor.setSelection({ anchor: next, focus: next });
- }
+ if (!editor || !isCompleteTagValue(tag) || currentTags(editor).includes(tag)) return false;
+ // As a word of its own at the caret, keeping highlighted text and the Markdown
+ // context, including code; refused while an input method is composing.
+ if (!editor.commands.insertToken(`#${tag}`)) return false;
editor.commands.focus();
editor.commands.scrollIntoView();
return true;
@@ -124,12 +94,10 @@ export function createController(getEditor: EditorGetter, onReplace: (markdown:
const widget = takeAnchor(id);
if (!editor || !widget) return;
if (markdown) {
+ // The anchor sits after its block; an empty block gives its place to the content.
const block = editor.state.doc.blocks.find((candidate) => candidate.id === widget.blockId);
- if (block && isEmptyParagraph(block)) {
- insertBlocks(editor, markdown, { blockId: block.id, offset: 0 });
- } else {
- editor.commands.insertMarkdown(markdown, { at: widget, block: true });
- }
+ const at = block && isEmptyParagraph(block) ? { blockId: block.id, offset: 0 } : widget;
+ editor.commands.insertMarkdown(markdown, { at, block: true });
editor.commands.focus();
editor.commands.scrollIntoView();
}
diff --git a/web/src/components/MemoEditor/edit/draftKey.ts b/web/src/components/MemoEditor/edit/draftKey.ts
new file mode 100644
index 000000000..6a4298de2
--- /dev/null
+++ b/web/src/components/MemoEditor/edit/draftKey.ts
@@ -0,0 +1,56 @@
+import { cacheService } from "./services/cacheService";
+
+/** What an editing session is for, which decides where its draft and caret are kept. */
+export type MemoEditIdentity =
+ | { kind: "edit"; name: string }
+ | { kind: "comment"; parent: string }
+ | { kind: "new"; scope: string; space?: string };
+
+/** The suffix of the draft's storage key; `cacheService.key` prefixes the user. */
+export function draftKeyFor(identity: MemoEditIdentity): string {
+ switch (identity.kind) {
+ case "edit":
+ return `edit:${identity.name}`;
+ case "comment":
+ return `comment:${identity.parent}`;
+ case "new":
+ return identity.space ? `new:${identity.scope}:${identity.space}` : `new:${identity.scope}`;
+ }
+}
+
+// The keys hosts chose for themselves before the key followed the identity.
+const LEGACY_SCOPE_PREFIXES: Record<string, string> = {
+ home: "home-memo-editor",
+ global: "global-memo-editor",
+ calendar: "calendar-day-editor",
+ map: "map-editor",
+};
+
+/** The key a draft for `identity` was stored under before this scheme, if it had one. */
+export function legacyDraftKeyFor(identity: MemoEditIdentity): string | undefined {
+ if (identity.kind === "comment") return `${identity.parent}-comment`;
+ if (identity.kind !== "new") return undefined;
+ const [head, ...rest] = identity.scope.split(":");
+ const prefix = LEGACY_SCOPE_PREFIXES[head];
+ if (!prefix) return undefined;
+ const scoped = rest.length > 0 ? `${prefix}:${rest.join(":")}` : prefix;
+ return identity.space ? `${scoped}:${identity.space}` : scoped;
+}
+
+/**
+ * Moves a draft stored under the previous key scheme to its key under this one, once.
+ * A draft already under the new key wins.
+ */
+export function migrateLegacyDraft(username: string, identity: MemoEditIdentity): void {
+ const legacySuffix = legacyDraftKeyFor(identity);
+ if (!legacySuffix) return;
+ const from = cacheService.key(username, legacySuffix);
+ const to = cacheService.key(username, draftKeyFor(identity));
+ try {
+ if (localStorage.getItem(to) !== null || localStorage.getItem(from) === null) return;
+ cacheService.saveNow(to, cacheService.loadDraft(from));
+ cacheService.clear(from);
+ } catch {
+ // Storage is unavailable; there is nothing to move.
+ }
+}
diff --git a/web/src/components/MemoEditor/Editor/editor.css b/web/src/components/MemoEditor/edit/editor.css
similarity index 100%
rename from web/src/components/MemoEditor/Editor/editor.css
rename to web/src/components/MemoEditor/edit/editor.css
diff --git a/web/src/components/MemoEditor/Editor/extensions.ts b/web/src/components/MemoEditor/edit/extensions.ts
similarity index 78%
rename from web/src/components/MemoEditor/Editor/extensions.ts
rename to web/src/components/MemoEditor/edit/extensions.ts
index f64730a23..f5f7485af 100644
--- a/web/src/components/MemoEditor/Editor/extensions.ts
+++ b/web/src/components/MemoEditor/edit/extensions.ts
@@ -1,8 +1,6 @@
import { type Extension, fileHandler, matchToken, type SuggestionAllowContext, scanTags, suggestion } from "@usememos/editor";
import { emoji } from "@usememos/editor/emoji";
-import { memoExtensions, memoMentionOptions, memoTagOptions } from "@/lib/memo-markdown";
-import type { UserSetting_TagsSetting } from "@/types/proto/api/user_service_pb";
-import type { EditorPosition } from "../types/editorController";
+import type { EditorPosition } from "./types/editorController";
/** The gesture that handed files to the editor: a drop lands at a document position, a paste has none. */
export type EditorFileOrigin = { source: "paste" } | { source: "drop"; position: EditorPosition | null };
@@ -11,10 +9,6 @@ export interface EditorExtensionsOptions {
/** Known tags, read when the popup asks for items. */
getTags: () => string[];
onFiles: (files: File[], origin: EditorFileOrigin) => void;
- /** The user's tag settings, read when tags are drawn, for their custom colors. */
- getTagsSetting: () => UserSetting_TagsSetting | undefined;
- /** Whether a mentioned username belongs to a user, read when mentions are drawn. */
- isMentionResolved: (username: string) => boolean;
/** Accessible name of the emoji popup. */
emojiLabel: string;
}
@@ -57,16 +51,9 @@ export const allowTagSuggestion = ({ excluded, explicit, query, textBefore }: Su
return !(query === "" && /(^|\n)[ \t]*$/.test(textBefore));
};
-export function buildEditorExtensions({
- getTags,
- onFiles,
- getTagsSetting,
- isMentionResolved,
- emojiLabel,
-}: EditorExtensionsOptions): Extension[] {
+/** What only the composer adds to the memo syntax MemoMarkdown already reads: autocomplete and file handling. */
+export function buildEditorExtensions({ getTags, onFiles, emojiLabel }: EditorExtensionsOptions): Extension[] {
return [
- // Tags and mentions look the same as in the memo view.
- ...memoExtensions({ tags: memoTagOptions(getTagsSetting), mentions: memoMentionOptions(isMentionResolved) }),
// The popup opens exactly where tags are highlighted: the matcher is built
// from the same scanner as tags(). A pick writes "#work/planning ".
suggestion({
diff --git a/web/src/components/MemoEditor/hooks/index.ts b/web/src/components/MemoEditor/edit/hooks/index.ts
similarity index 100%
rename from web/src/components/MemoEditor/hooks/index.ts
rename to web/src/components/MemoEditor/edit/hooks/index.ts
diff --git a/web/src/components/MemoEditor/hooks/useAttachmentTranscription.ts b/web/src/components/MemoEditor/edit/hooks/useAttachmentTranscription.ts
similarity index 100%
rename from web/src/components/MemoEditor/hooks/useAttachmentTranscription.ts
rename to web/src/components/MemoEditor/edit/hooks/useAttachmentTranscription.ts
diff --git a/web/src/components/MemoEditor/hooks/useAudioRecorder.ts b/web/src/components/MemoEditor/edit/hooks/useAudioRecorder.ts
similarity index 100%
rename from web/src/components/MemoEditor/hooks/useAudioRecorder.ts
rename to web/src/components/MemoEditor/edit/hooks/useAudioRecorder.ts
diff --git a/web/src/components/MemoEditor/hooks/useAudioWaveform.ts b/web/src/components/MemoEditor/edit/hooks/useAudioWaveform.ts
similarity index 100%
rename from web/src/components/MemoEditor/hooks/useAudioWaveform.ts
rename to web/src/components/MemoEditor/edit/hooks/useAudioWaveform.ts
diff --git a/web/src/components/MemoEditor/hooks/useAutoSave.ts b/web/src/components/MemoEditor/edit/hooks/useAutoSave.ts
similarity index 89%
rename from web/src/components/MemoEditor/hooks/useAutoSave.ts
rename to web/src/components/MemoEditor/edit/hooks/useAutoSave.ts
index 1f68e6464..458910967 100644
--- a/web/src/components/MemoEditor/hooks/useAutoSave.ts
+++ b/web/src/components/MemoEditor/edit/hooks/useAutoSave.ts
@@ -30,7 +30,7 @@ const sameDraft = (left: EditorDraft, right: EditorDraft): boolean =>
* 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) => {
+export const useAutoSave = (key: string, enabled = true) => {
const store = useEditorStore();
const latestDraftRef = useRef<EditorDraft>(draftFromState(store.getState()));
const discardedDraftRef = useRef<EditorDraft | undefined>(undefined);
@@ -38,7 +38,6 @@ export const useAutoSave = (username: string, cacheKey: string | undefined, enab
useEffect(() => {
if (!enabled) return;
- const key = cacheService.key(username, cacheKey);
const persist = (draft: EditorDraft) => {
latestDraftRef.current = draft;
if (discardedDraftRef.current !== undefined && !sameDraft(discardedDraftRef.current, draft)) {
@@ -55,12 +54,11 @@ export const useAutoSave = (username: string, cacheKey: string | undefined, enab
persist(draft);
}
});
- }, [store, username, cacheKey, enabled]);
+ }, [store, key, enabled]);
useEffect(() => {
if (!enabled) return;
- const key = cacheService.key(username, cacheKey);
const flushDraft = () => {
if (discardedDraftRef.current && sameDraft(discardedDraftRef.current, latestDraftRef.current)) {
return;
@@ -84,13 +82,12 @@ export const useAutoSave = (username: string, cacheKey: string | undefined, enab
window.removeEventListener("pagehide", flushDraft);
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
- }, [store, username, cacheKey, enabled]);
+ }, [store, key, enabled]);
const discardDraft = useCallback(() => {
- const key = cacheService.key(username, cacheKey);
discardedDraftRef.current = latestDraftRef.current;
cacheService.clear(key);
- }, [username, cacheKey]);
+ }, [key]);
return { discardDraft };
};
diff --git a/web/src/components/MemoEditor/hooks/useBlobUrls.ts b/web/src/components/MemoEditor/edit/hooks/useBlobUrls.ts
similarity index 100%
rename from web/src/components/MemoEditor/hooks/useBlobUrls.ts
rename to web/src/components/MemoEditor/edit/hooks/useBlobUrls.ts
diff --git a/web/src/components/MemoEditor/hooks/useFileUpload.ts b/web/src/components/MemoEditor/edit/hooks/useFileUpload.ts
similarity index 100%
rename from web/src/components/MemoEditor/hooks/useFileUpload.ts
rename to web/src/components/MemoEditor/edit/hooks/useFileUpload.ts
diff --git a/web/src/components/MemoEditor/hooks/useFocusMode.ts b/web/src/components/MemoEditor/edit/hooks/useFocusMode.ts
similarity index 100%
rename from web/src/components/MemoEditor/hooks/useFocusMode.ts
rename to web/src/components/MemoEditor/edit/hooks/useFocusMode.ts
diff --git a/web/src/components/MemoEditor/hooks/useInlineImageUpload.ts b/web/src/components/MemoEditor/edit/hooks/useInlineImageUpload.ts
similarity index 100%
rename from web/src/components/MemoEditor/hooks/useInlineImageUpload.ts
rename to web/src/components/MemoEditor/edit/hooks/useInlineImageUpload.ts
diff --git a/web/src/components/MemoEditor/hooks/useLinkMemo.ts b/web/src/components/MemoEditor/edit/hooks/useLinkMemo.ts
similarity index 100%
rename from web/src/components/MemoEditor/hooks/useLinkMemo.ts
rename to web/src/components/MemoEditor/edit/hooks/useLinkMemo.ts
diff --git a/web/src/components/MemoEditor/hooks/useLocation.ts b/web/src/components/MemoEditor/edit/hooks/useLocation.ts
similarity index 100%
rename from web/src/components/MemoEditor/hooks/useLocation.ts
rename to web/src/components/MemoEditor/edit/hooks/useLocation.ts
diff --git a/web/src/components/MemoEditor/edit/hooks/useMemoInit.ts b/web/src/components/MemoEditor/edit/hooks/useMemoInit.ts
new file mode 100644
index 000000000..5583d988c
--- /dev/null
+++ b/web/src/components/MemoEditor/edit/hooks/useMemoInit.ts
@@ -0,0 +1,50 @@
+import type { EditorMode } from "@usememos/editor";
+import { useEffect, useRef, useState } from "react";
+import { cacheService } from "../services";
+import type { EditorController } from "../types/editorController";
+
+interface UseMemoInitOptions {
+ editorRef: React.RefObject<EditorController | null>;
+ /** The persisted draft's key, under which the caret was remembered. */
+ draftKey: string;
+ autoFocus?: boolean | (() => boolean);
+ /** The mode the editor opens in; a caret saved in the other mode is not restored. */
+ mode: EditorMode;
+}
+
+/**
+ * Once the editor has mounted over its initial draft (see `initialEditorState`), puts
+ * the caret back where it was remembered and focuses when asked. `autoFocus` is read
+ * after the caret is restored, so a host can decide then whether focus is still wanted.
+ */
+export const useMemoInit = ({ editorRef, draftKey, autoFocus, mode }: UseMemoInitOptions) => {
+ const initializedRef = useRef(false);
+ const [isInitialized, setIsInitialized] = useState(false);
+
+ useEffect(() => {
+ if (initializedRef.current) return;
+ initializedRef.current = true;
+
+ const cachedCursor = cacheService.loadCursor(draftKey, mode);
+ let restoreCursorTimer: ReturnType<typeof setTimeout> | undefined;
+ if (autoFocus || cachedCursor !== undefined) {
+ restoreCursorTimer = setTimeout(() => {
+ if (cachedCursor !== undefined) {
+ editorRef.current?.setSelection(cachedCursor);
+ }
+ if (typeof autoFocus === "function" ? autoFocus() : autoFocus) {
+ editorRef.current?.focus();
+ }
+ }, 100);
+ }
+
+ setIsInitialized(true);
+ return () => {
+ if (restoreCursorTimer) {
+ clearTimeout(restoreCursorTimer);
+ }
+ };
+ }, [draftKey, autoFocus, mode, editorRef]);
+
+ return { isInitialized };
+};
diff --git a/web/src/components/MemoEditor/hooks/useMemoSave.ts b/web/src/components/MemoEditor/edit/hooks/useMemoSave.ts
similarity index 81%
rename from web/src/components/MemoEditor/hooks/useMemoSave.ts
rename to web/src/components/MemoEditor/edit/hooks/useMemoSave.ts
index 27106817b..c9493a179 100644
--- a/web/src/components/MemoEditor/hooks/useMemoSave.ts
+++ b/web/src/components/MemoEditor/edit/hooks/useMemoSave.ts
@@ -1,15 +1,17 @@
+import { Code, ConnectError } from "@connectrpc/connect";
import { useQueryClient } from "@tanstack/react-query";
import { useCallback } from "react";
import { toast } from "react-hot-toast";
import { useNewMemo } from "@/contexts/NewMemoContext";
import { attachmentKeys } from "@/hooks/useAttachmentQueries";
-import { memoKeys } from "@/hooks/useMemoQueries";
+import { memoDetailQueryOptions, useCreateMemo, useUpdateMemo } from "@/hooks/useMemoQueries";
import { userKeys } from "@/hooks/useUserQueries";
import { handleError } from "@/lib/error";
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
import type { Visibility } from "@/types/proto/api/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
import { errorService, memoService, validationService } from "../services";
+import type { MemoSaveOperations } from "../services/memoService";
import { useEditorContext } from "../state";
import { restampDefaultCreateTime } from "../utils/deriveDefaultCreateTime";
@@ -28,9 +30,10 @@ interface UseMemoSaveOptions {
}
/**
- * Owns the editor's save transaction and its post-save cache/state updates.
- * Keeping this workflow outside the shell makes saving identical whether it is
- * triggered by the toolbar or the editor keyboard shortcut.
+ * Owns the editor's save transaction and its post-save state. The memo itself is
+ * written through the memo mutation hooks, which patch and refresh every query that
+ * holds it, so the saved text shows wherever the memo is on the page as soon as the
+ * server answers. Saving is identical whether the toolbar or the keyboard triggers it.
*/
export function useMemoSave({
memoName,
@@ -44,6 +47,8 @@ export function useMemoSave({
}: UseMemoSaveOptions): () => Promise<void> {
const t = useTranslate();
const queryClient = useQueryClient();
+ const { mutateAsync: createMemo } = useCreateMemo();
+ const { mutateAsync: updateMemo } = useUpdateMemo();
const { markNewMemo } = useNewMemo();
const { actions, dispatch, getState } = useEditorContext();
@@ -78,6 +83,17 @@ export function useMemoSave({
dispatch(actions.setLocalFiles(current.localFiles.filter((file) => !uploaded.has(file.previewUrl))));
};
+ const operations: MemoSaveOperations = {
+ // The server's current copy, fetched afresh into the detail cache.
+ getMemo: async (name) => {
+ const memo = await queryClient.fetchQuery({ ...memoDetailQueryOptions(name), staleTime: 0 });
+ if (!memo) throw new ConnectError("memo not found", Code.NotFound);
+ return memo;
+ },
+ updateMemo: (update, updateMask) => updateMemo({ update, updateMask }),
+ createMemo: (memo, parent) => createMemo({ memo, parent }),
+ };
+
try {
// A new memo composed on a selected day keeps the day but is stamped with
// the time of saving, so consecutive memos do not share one createTime.
@@ -96,6 +112,7 @@ export function useMemoSave({
space: defaultSpace,
onFileUploaded: (file, attachment) => uploaded.set(file.previewUrl, attachment),
},
+ operations,
);
if (!result.hasChanges) {
@@ -111,27 +128,14 @@ export function useMemoSave({
toast.success(t("memo.moved"));
}
- const invalidationPromises: Promise<unknown>[] = [
- queryClient.invalidateQueries({ queryKey: memoKeys.lists() }),
- queryClient.invalidateQueries({ queryKey: userKeys.stats() }),
- queryClient.invalidateQueries({ queryKey: attachmentKeys.lists() }),
- ];
- if (memoName) {
- invalidationPromises.push(queryClient.invalidateQueries({ queryKey: memoKeys.detail(memoName) }));
- }
- if (parentMemoName) {
- invalidationPromises.push(queryClient.invalidateQueries({ queryKey: memoKeys.comments(parentMemoName) }));
- invalidationPromises.push(queryClient.invalidateQueries({ queryKey: memoKeys.detail(parentMemoName) }));
- }
// Hosts that close after saving (edit, comment) hold a brief "Saved"
// confirmation on the toolbar while the caches refresh underneath. The
// in-place composer clears immediately, so it shows nothing.
if (memoName || parentMemoName) {
dispatch(actions.setLoading("saving", false));
dispatch(actions.setJustSaved(true));
- invalidationPromises.push(new Promise((resolve) => setTimeout(resolve, SAVED_CONFIRMATION_MS)));
+ await new Promise((resolve) => setTimeout(resolve, SAVED_CONFIRMATION_MS));
}
- await Promise.all(invalidationPromises);
dispatch(actions.reset());
if (!memoName && defaultVisibility) {
@@ -166,6 +170,7 @@ export function useMemoSave({
}
}, [
actions,
+ createMemo,
defaultCreateTime,
defaultSpace,
defaultVisibility,
@@ -179,5 +184,6 @@ export function useMemoSave({
parentMemoName,
queryClient,
t,
+ updateMemo,
]);
}
diff --git a/web/src/components/MemoEditor/hooks/useSourceMode.ts b/web/src/components/MemoEditor/edit/hooks/useSourceMode.ts
similarity index 100%
rename from web/src/components/MemoEditor/hooks/useSourceMode.ts
rename to web/src/components/MemoEditor/edit/hooks/useSourceMode.ts
diff --git a/web/src/components/MemoEditor/edit/initialState.ts b/web/src/components/MemoEditor/edit/initialState.ts
new file mode 100644
index 000000000..b6b9a0fec
--- /dev/null
+++ b/web/src/components/MemoEditor/edit/initialState.ts
@@ -0,0 +1,73 @@
+import type { Location, Memo, Visibility } from "@/types/proto/api/memo_service_pb";
+import type { User } from "@/types/proto/api/user_service_pb";
+import { canManageMemo } from "@/utils/user";
+import { cacheService } from "./services/cacheService";
+import { memoService } from "./services/memoService";
+import { createInitialState, type EditorState } from "./state/types";
+
+/**
+ * Whether a session may place the memo in a Space of its own. Replies are never placed
+ * independently: a comment's Space is its parent's. An edited top-level memo can change
+ * its Space; a new one can unless its host fixes the target, such as composing inside a
+ * Space.
+ */
+export const canChooseSpaceFor = ({
+ memo,
+ currentUser,
+ parentMemoName,
+ defaultSpace,
+}: {
+ memo?: Memo;
+ currentUser: User | undefined;
+ parentMemoName?: string;
+ defaultSpace?: string;
+}): boolean => (memo ? !memo.parent && canManageMemo(memo, currentUser) : !parentMemoName && !defaultSpace);
+
+export interface InitialEditorStateOptions {
+ /** The memo being edited; its draft is never restored from the cache. */
+ memo?: Memo;
+ /** The persisted draft's key, for a new memo or comment. */
+ draftKey: string;
+ initialFocusMode?: boolean;
+ defaultVisibility?: Visibility;
+ defaultCreateTime?: Date;
+ defaultLocation?: Location;
+ /** Whether the draft may carry a Space of its own; a comment's Space is its parent's. */
+ canChooseSpace?: boolean;
+}
+
+/**
+ * The draft store's first state, computed once when editing starts: the memo's own
+ * fields for an edit, otherwise the persisted draft under `draftKey` over the host's
+ * defaults. A cached `null` location is one the user removed, so the default does not
+ * come back.
+ */
+export function initialEditorState({
+ memo,
+ draftKey,
+ initialFocusMode = false,
+ defaultVisibility,
+ defaultCreateTime,
+ defaultLocation,
+ canChooseSpace = false,
+}: InitialEditorStateOptions): EditorState {
+ const base = createInitialState(initialFocusMode);
+ if (memo) {
+ cacheService.clear(draftKey);
+ return { ...base, ...memoService.fromMemo(memo) };
+ }
+ const draft = cacheService.loadDraft(draftKey);
+ const visibility = draft.visibility ?? defaultVisibility ?? base.metadata.visibility;
+ return {
+ ...base,
+ content: draft.content,
+ metadata: {
+ ...base.metadata,
+ attachments: draft.attachments.length > 0 ? draft.attachments : base.metadata.attachments,
+ location: draft.location === null ? undefined : (draft.location ?? defaultLocation),
+ visibility,
+ space: canChooseSpace ? draft.space : undefined,
+ },
+ timestamps: defaultCreateTime ? { createTime: defaultCreateTime, updateTime: defaultCreateTime } : base.timestamps,
+ };
+}
diff --git a/web/src/components/MemoEditor/services/cacheService.ts b/web/src/components/MemoEditor/edit/services/cacheService.ts
similarity index 96%
rename from web/src/components/MemoEditor/services/cacheService.ts
rename to web/src/components/MemoEditor/edit/services/cacheService.ts
index fc21d5f0b..35ace5718 100644
--- a/web/src/components/MemoEditor/services/cacheService.ts
+++ b/web/src/components/MemoEditor/edit/services/cacheService.ts
@@ -98,8 +98,9 @@ function writeEntry(key: string, draft: EditorDraft): void {
}
export const cacheService = {
- key: (username: string, cacheKey?: string): string => {
- return `${username}-${cacheKey || ""}`;
+ /** The storage key for a draft: the user, then the identity-derived suffix (see `draftKeyFor`). */
+ key: (username: string, draftKey?: string): string => {
+ return `${username}-${draftKey || ""}`;
},
save: (key: string, draft: EditorDraft) => {
diff --git a/web/src/components/MemoEditor/services/errorService.ts b/web/src/components/MemoEditor/edit/services/errorService.ts
similarity index 100%
rename from web/src/components/MemoEditor/services/errorService.ts
rename to web/src/components/MemoEditor/edit/services/errorService.ts
diff --git a/web/src/components/MemoEditor/services/index.ts b/web/src/components/MemoEditor/edit/services/index.ts
similarity index 100%
rename from web/src/components/MemoEditor/services/index.ts
rename to web/src/components/MemoEditor/edit/services/index.ts
diff --git a/web/src/components/MemoEditor/services/mediaMetadataService.ts b/web/src/components/MemoEditor/edit/services/mediaMetadataService.ts
similarity index 100%
rename from web/src/components/MemoEditor/services/mediaMetadataService.ts
rename to web/src/components/MemoEditor/edit/services/mediaMetadataService.ts
diff --git a/web/src/components/MemoEditor/services/memoService.ts b/web/src/components/MemoEditor/edit/services/memoService.ts
similarity index 88%
rename from web/src/components/MemoEditor/services/memoService.ts
rename to web/src/components/MemoEditor/edit/services/memoService.ts
index 56dd3eea1..f72965a43 100644
--- a/web/src/components/MemoEditor/services/memoService.ts
+++ b/web/src/components/MemoEditor/edit/services/memoService.ts
@@ -1,8 +1,7 @@
import { create } from "@bufbuild/protobuf";
-import { FieldMaskSchema, timestampDate, timestampFromDate } from "@bufbuild/protobuf/wkt";
+import { timestampDate, timestampFromDate } from "@bufbuild/protobuf/wkt";
import { isEqual } from "lodash-es";
import { getEditorReferenceRelations } from "@/components/MemoMetadata/Relation/relationHelpers";
-import { memoServiceClient } from "@/connect";
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
import { AttachmentSchema } from "@/types/proto/api/attachment_service_pb";
import type { Memo } from "@/types/proto/api/memo_service_pb";
@@ -85,6 +84,15 @@ function buildUpdateMask(
return { mask, patch };
}
+/** The memo operations a save runs: the memo mutation hooks, so caches follow every save. */
+export interface MemoSaveOperations {
+ /** The memo as the server has it now, to diff the draft against. */
+ getMemo: (name: string) => Promise<Memo>;
+ updateMemo: (update: Partial<Memo>, updateMask: string[]) => Promise<Memo>;
+ /** Creates a memo, or a comment on `parent`. */
+ createMemo: (memo: Memo, parent?: string) => Promise<Memo>;
+}
+
export const memoService = {
async save(
state: EditorState,
@@ -95,6 +103,7 @@ export const memoService = {
/** Runs as each local file finishes uploading, before the memo is saved. */
onFileUploaded?: (localFile: LocalFile, attachment: Attachment) => void;
},
+ operations: MemoSaveOperations,
): Promise<{ memoName: string; hasChanges: boolean; moved?: boolean }> {
// 1. Upload local files first
const newAttachments = await uploadService.uploadFiles(state.localFiles, options.onFileUploaded);
@@ -102,17 +111,14 @@ export const memoService = {
// 2. Update existing memo
if (options.memoName) {
- const prevMemo = await memoServiceClient.getMemo({ name: options.memoName });
+ const prevMemo = await operations.getMemo(options.memoName);
const { mask, patch } = buildUpdateMask(prevMemo, state, allAttachments);
if (mask.size === 0) {
return { memoName: prevMemo.name, hasChanges: false };
}
- const memo = await memoServiceClient.updateMemo({
- memo: create(MemoSchema, patch as Record<string, unknown>),
- updateMask: create(FieldMaskSchema, { paths: Array.from(mask) }),
- });
+ const memo = await operations.updateMemo(patch, Array.from(mask));
return { memoName: memo.name, hasChanges: true, moved: mask.has("space") };
}
@@ -128,13 +134,7 @@ export const memoService = {
space: options.parentMemoName ? undefined : (options.space ?? state.metadata.space),
});
- const memo = options.parentMemoName
- ? await memoServiceClient.createMemoComment({
- parent: options.parentMemoName,
- comment: memoData,
- })
- : await memoServiceClient.createMemo({ memo: memoData });
-
+ const memo = await operations.createMemo(memoData, options.parentMemoName);
return { memoName: memo.name, hasChanges: true };
},
diff --git a/web/src/components/MemoEditor/services/transcriptionService.ts b/web/src/components/MemoEditor/edit/services/transcriptionService.ts
similarity index 100%
rename from web/src/components/MemoEditor/services/transcriptionService.ts
rename to web/src/components/MemoEditor/edit/services/transcriptionService.ts
diff --git a/web/src/components/MemoEditor/services/uploadService.ts b/web/src/components/MemoEditor/edit/services/uploadService.ts
similarity index 100%
rename from web/src/components/MemoEditor/services/uploadService.ts
rename to web/src/components/MemoEditor/edit/services/uploadService.ts
diff --git a/web/src/components/MemoEditor/services/validationService.ts b/web/src/components/MemoEditor/edit/services/validationService.ts
similarity index 100%
rename from web/src/components/MemoEditor/services/validationService.ts
rename to web/src/components/MemoEditor/edit/services/validationService.ts
diff --git a/web/src/components/MemoEditor/state/actions.ts b/web/src/components/MemoEditor/edit/state/actions.ts
similarity index 100%
rename from web/src/components/MemoEditor/state/actions.ts
rename to web/src/components/MemoEditor/edit/state/actions.ts
diff --git a/web/src/components/MemoEditor/state/context.tsx b/web/src/components/MemoEditor/edit/state/context.tsx
similarity index 100%
rename from web/src/components/MemoEditor/state/context.tsx
rename to web/src/components/MemoEditor/edit/state/context.tsx
diff --git a/web/src/components/MemoEditor/state/index.ts b/web/src/components/MemoEditor/edit/state/index.ts
similarity index 100%
rename from web/src/components/MemoEditor/state/index.ts
rename to web/src/components/MemoEditor/edit/state/index.ts
diff --git a/web/src/components/MemoEditor/state/reducer.ts b/web/src/components/MemoEditor/edit/state/reducer.ts
similarity index 100%
rename from web/src/components/MemoEditor/state/reducer.ts
rename to web/src/components/MemoEditor/edit/state/reducer.ts
diff --git a/web/src/components/MemoEditor/state/types.ts b/web/src/components/MemoEditor/edit/state/types.ts
similarity index 100%
rename from web/src/components/MemoEditor/state/types.ts
rename to web/src/components/MemoEditor/edit/state/types.ts
diff --git a/web/src/components/MemoEditor/types/attachment.ts b/web/src/components/MemoEditor/edit/types/attachment.ts
similarity index 100%
rename from web/src/components/MemoEditor/types/attachment.ts
rename to web/src/components/MemoEditor/edit/types/attachment.ts
diff --git a/web/src/components/MemoEditor/types/components.ts b/web/src/components/MemoEditor/edit/types/components.ts
similarity index 90%
rename from web/src/components/MemoEditor/types/components.ts
rename to web/src/components/MemoEditor/edit/types/components.ts
index 656b5d1dd..c6d87ecc5 100644
--- a/web/src/components/MemoEditor/types/components.ts
+++ b/web/src/components/MemoEditor/edit/types/components.ts
@@ -1,24 +1,25 @@
import type { MemoSuggestion } from "@/lib/memo-suggestions";
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
import type { Location, Memo, Visibility } from "@/types/proto/api/memo_service_pb";
-import type { UserSetting_TagsSetting } from "@/types/proto/api/user_service_pb";
-import type { EditorFileOrigin } from "../Editor/extensions";
+import type { EditorFileOrigin } from "../extensions";
import type { AudioRecorderStatus } from "../hooks/useAudioRecorder";
import type { LocalFile } from "./attachment";
-export interface MemoEditorProps {
+/** What MemoEditor hands an editing session: its subject, the host's defaults, and where the draft lives. */
+export interface EditSessionProps {
className?: string;
- cacheKey?: string;
+ /** The draft and caret storage key, derived from what is edited; see `draftKeyFor`. */
+ draftKey: string;
+ /** Inside a card that is the frame already: no background, border or padding of its own outside focus mode. */
+ frameless?: boolean;
placeholder?: string;
- /** Existing memo to edit. When provided, the editor initializes from it without fetching. */
+ /** Existing memo to edit; the session starts from it and persists no draft. */
memo?: Memo;
parentMemoName?: string;
/** Context-derived suggestions for a new top-level memo. */
suggestions?: readonly MemoSuggestion[];
/** Assigns a newly created top-level memo to this Space. Ignored for edits and comments. */
defaultSpace?: string;
- /** Seeds a new memo once; restored draft metadata takes precedence. */
- defaultLocation?: Location;
/** A callback can decide whether focus is still appropriate after draft restoration. */
autoFocus?: boolean | (() => boolean);
/**
@@ -54,8 +55,6 @@ export interface EditorContentProps {
/** Invoked by the in-editor save shortcut (Cmd/Ctrl+Enter). */
onSubmit: () => void;
onFiles: (files: File[], origin: EditorFileOrigin) => void;
- /** The user's tag settings, for tags in their custom colors. */
- tagsSetting?: UserSetting_TagsSetting;
}
/**
diff --git a/web/src/components/MemoEditor/types/editorController.ts b/web/src/components/MemoEditor/edit/types/editorController.ts
similarity index 96%
rename from web/src/components/MemoEditor/types/editorController.ts
rename to web/src/components/MemoEditor/edit/types/editorController.ts
index cf4ea4b14..fcb8e5c83 100644
--- a/web/src/components/MemoEditor/types/editorController.ts
+++ b/web/src/components/MemoEditor/edit/types/editorController.ts
@@ -1,5 +1,5 @@
import type { Position, SelectionJSON } from "@usememos/editor";
-import type { UploadAnchorDescriptor } from "../Editor/uploadAnchors";
+import type { UploadAnchorDescriptor } from "../uploadAnchors";
/** A place in the document, such as where files were dropped. Valid until the document changes. */
export type EditorPosition = Position;
diff --git a/web/src/components/MemoEditor/types/index.ts b/web/src/components/MemoEditor/edit/types/index.ts
similarity index 95%
rename from web/src/components/MemoEditor/types/index.ts
rename to web/src/components/MemoEditor/edit/types/index.ts
index 5c99c7d2a..d4d48cecd 100644
--- a/web/src/components/MemoEditor/types/index.ts
+++ b/web/src/components/MemoEditor/edit/types/index.ts
@@ -8,10 +8,10 @@ export type {
EditorSourceModeToggle,
EditorToolbarProps,
EditorViewToggles,
+ EditSessionProps,
FocusModeExitButtonProps,
FocusModeOverlayProps,
InsertMenuProps,
- MemoEditorProps,
} from "./components";
export type { EditorController } from "./editorController";
export type { LocationState } from "./insertMenu";
diff --git a/web/src/components/MemoEditor/types/insertMenu.ts b/web/src/components/MemoEditor/edit/types/insertMenu.ts
similarity index 100%
rename from web/src/components/MemoEditor/types/insertMenu.ts
rename to web/src/components/MemoEditor/edit/types/insertMenu.ts
diff --git a/web/src/components/MemoEditor/Editor/uploadAnchors.ts b/web/src/components/MemoEditor/edit/uploadAnchors.ts
similarity index 100%
rename from web/src/components/MemoEditor/Editor/uploadAnchors.ts
rename to web/src/components/MemoEditor/edit/uploadAnchors.ts
diff --git a/web/src/components/MemoEditor/utils/deriveDefaultCreateTime.ts b/web/src/components/MemoEditor/edit/utils/deriveDefaultCreateTime.ts
similarity index 100%
rename from web/src/components/MemoEditor/utils/deriveDefaultCreateTime.ts
rename to web/src/components/MemoEditor/edit/utils/deriveDefaultCreateTime.ts
diff --git a/web/src/components/MemoEditor/hooks/useMemoInit.ts b/web/src/components/MemoEditor/hooks/useMemoInit.ts
deleted file mode 100644
index add599a35..000000000
--- a/web/src/components/MemoEditor/hooks/useMemoInit.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import type { EditorMode } from "@usememos/editor";
-import { useEffect, useRef, useState } from "react";
-import type { Location, Memo, Visibility } from "@/types/proto/api/memo_service_pb";
-import { cacheService, memoService } from "../services";
-import { useEditorContext } from "../state";
-import type { EditorController } from "../types/editorController";
-
-interface UseMemoInitOptions {
- editorRef: React.RefObject<EditorController | null>;
- memo?: Memo;
- cacheKey?: string;
- username: string;
- autoFocus?: boolean | (() => boolean);
- defaultVisibility?: Visibility;
- defaultCreateTime?: Date;
- defaultLocation?: Location;
- canChooseSpace?: boolean;
- /** The mode the editor opens in; a caret saved in the other mode is not restored. */
- mode: EditorMode;
-}
-
-export const useMemoInit = ({
- editorRef,
- memo,
- cacheKey,
- username,
- autoFocus,
- defaultVisibility,
- defaultCreateTime,
- defaultLocation,
- canChooseSpace = false,
- mode,
-}: UseMemoInitOptions) => {
- const { actions, dispatch } = useEditorContext();
- const initializedRef = useRef(false);
- const [isInitialized, setIsInitialized] = useState(false);
-
- useEffect(() => {
- if (initializedRef.current) return;
- initializedRef.current = true;
- const key = cacheService.key(username, cacheKey);
-
- if (memo) {
- const initialState = memoService.fromMemo(memo);
- cacheService.clear(key);
- dispatch(actions.initMemo(initialState));
- } else {
- const cachedDraft = cacheService.loadDraft(key);
- if (cachedDraft.content) {
- dispatch(actions.updateContent(cachedDraft.content));
- }
- if (cachedDraft.attachments.length > 0) {
- dispatch(actions.setMetadata({ attachments: cachedDraft.attachments }));
- }
- dispatch(actions.setMetadata({ location: cachedDraft.location === null ? undefined : (cachedDraft.location ?? defaultLocation) }));
- const visibility = cachedDraft.visibility ?? defaultVisibility;
- if (visibility !== undefined) {
- dispatch(actions.setMetadata({ visibility }));
- }
- if (canChooseSpace) {
- dispatch(actions.setMetadata({ space: cachedDraft.space }));
- }
- if (defaultCreateTime) {
- dispatch(actions.setTimestamps({ createTime: defaultCreateTime, updateTime: defaultCreateTime }));
- }
- }
-
- const cachedCursor = cacheService.loadCursor(key, mode);
- let restoreCursorTimer: ReturnType<typeof setTimeout> | undefined;
- if (autoFocus || cachedCursor !== undefined) {
- restoreCursorTimer = setTimeout(() => {
- if (cachedCursor !== undefined) {
- editorRef.current?.setSelection(cachedCursor);
- }
- if (typeof autoFocus === "function" ? autoFocus() : autoFocus) {
- editorRef.current?.focus();
- }
- }, 100);
- }
-
- setIsInitialized(true);
- return () => {
- if (restoreCursorTimer) {
- clearTimeout(restoreCursorTimer);
- }
- };
- }, [
- memo,
- cacheKey,
- username,
- autoFocus,
- defaultVisibility,
- defaultCreateTime,
- defaultLocation,
- canChooseSpace,
- mode,
- actions,
- dispatch,
- editorRef,
- ]);
-
- return { isInitialized };
-};
diff --git a/web/src/components/MemoEditor/index.ts b/web/src/components/MemoEditor/index.ts
new file mode 100644
index 000000000..80f7633e5
--- /dev/null
+++ b/web/src/components/MemoEditor/index.ts
@@ -0,0 +1,10 @@
+export {
+ type MemoDraftSeed,
+ type MemoEditingProps,
+ MemoEditor,
+ type MemoEditorDraftProps,
+ type MemoEditorEditProps,
+ type MemoEditorProps,
+ type MemoEditorViewProps,
+ preloadMemoEditing,
+} from "./MemoEditor";
diff --git a/web/src/components/MemoEditor/loader.ts b/web/src/components/MemoEditor/loader.ts
deleted file mode 100644
index e10dfb497..000000000
--- a/web/src/components/MemoEditor/loader.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { loadWithReload } from "@/utils/lazy";
-
-type MemoEditorModule = typeof import(".");
-
-let memoEditorModulePromise: Promise<MemoEditorModule> | undefined;
-
-// Share one in-flight request across edit and comment entry points. Callers
-// keep their current UI mounted until this promise resolves.
-export const loadMemoEditor = (): Promise<MemoEditorModule> => {
- memoEditorModulePromise ??= loadWithReload(() => import(".")).catch((error) => {
- memoEditorModulePromise = undefined;
- throw error;
- });
- return memoEditorModulePromise;
-};
diff --git a/web/src/components/MemoEditor/useMemoDecorations.ts b/web/src/components/MemoEditor/useMemoDecorations.ts
new file mode 100644
index 000000000..f235133eb
--- /dev/null
+++ b/web/src/components/MemoEditor/useMemoDecorations.ts
@@ -0,0 +1,87 @@
+import type { Editor, TagsOptions } from "@usememos/editor";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useAuth } from "@/contexts/AuthContext";
+import { useResolvedMentionUsernames } from "@/contexts/MentionResolutionContext";
+import { useDebouncedEffect } from "@/hooks";
+import { memoMentionOptions, memoTagOptions } from "@/lib/memo-markdown";
+
+/** How long typing pauses before the mentions in a draft are looked up. */
+const MENTION_LOOKUP_DELAY_MS = 400;
+
+export interface MemoDecorations {
+ /** `tags()` class, attributes and click: pills in the viewer's custom tag colors. */
+ readonly tags: Pick<TagsOptions, "class" | "attributes" | "onClick">;
+ /** `mentions()` class, attributes and click: the primary color for people who exist. */
+ readonly mentions: Pick<TagsOptions, "class" | "attributes" | "onClick">;
+}
+
+export interface MemoDecorationHandlers {
+ /** A tag was clicked to be followed, without its `#`. */
+ onTagClick?: (tag: string) => void;
+ /** A mention of someone who exists was clicked to be followed, without its `@`. Unknown names are plain text. */
+ onMentionClick?: (username: string) => void;
+}
+
+/**
+ * What a memo's tags and mentions look like wherever a memo is shown, and what a click on
+ * them does. The options are stable for the editor's lifetime and read the latest data
+ * and handlers through refs; `editor` decorates again when that data changes.
+ *
+ * Tag colors come from the viewer's tag settings. Mentions resolve through the shared
+ * provider of the surrounding list when it knows this content, otherwise with a lookup
+ * of their own. While editing, a half-typed name is not looked up: mentions are read
+ * once typing pauses, and until a lookup answers, the people already found stay found.
+ */
+export function useMemoDecorations(
+ editor: Editor | null,
+ value: string,
+ editable: boolean,
+ handlers: MemoDecorationHandlers = {},
+): MemoDecorations {
+ const { userTagsSetting } = useAuth();
+ const [settled, setSettled] = useState(value);
+ useDebouncedEffect(() => setSettled(value), MENTION_LOOKUP_DELAY_MS, [value]);
+ const resolved = useResolvedMentionUsernames(editable ? settled : value);
+
+ const tagsSettingRef = useRef(userTagsSetting);
+ tagsSettingRef.current = userTagsSetting;
+ const resolvedRef = useRef(resolved);
+ resolvedRef.current = resolved;
+ const handlersRef = useRef(handlers);
+ handlersRef.current = handlers;
+
+ // Decorate again only when what the decorations read changed: a new editor already
+ // decorates with the current values, and a lookup that answers the same is a no-op.
+ const mentionKey = useMemo(() => [...resolved].sort().join(" "), [resolved]);
+ const decorated = useRef({ mentionKey, userTagsSetting });
+ useEffect(() => {
+ const changed = decorated.current.mentionKey !== mentionKey || decorated.current.userTagsSetting !== userTagsSetting;
+ decorated.current = { mentionKey, userTagsSetting };
+ if (changed) editor?.redecorate();
+ }, [editor, mentionKey, userTagsSetting]);
+
+ return useMemo(
+ () => ({
+ tags: {
+ ...memoTagOptions(() => tagsSettingRef.current),
+ onClick: ({ match }) => {
+ const onTagClick = handlersRef.current.onTagClick;
+ if (!onTagClick) return false;
+ onTagClick(match.slice(1));
+ return true;
+ },
+ },
+ mentions: {
+ ...memoMentionOptions((username) => resolvedRef.current.has(username)),
+ onClick: ({ match }) => {
+ const username = match.slice(1);
+ const onMentionClick = handlersRef.current.onMentionClick;
+ if (!onMentionClick || !resolvedRef.current.has(username)) return false;
+ onMentionClick(username);
+ return true;
+ },
+ },
+ }),
+ [],
+ );
+}
diff --git a/web/src/components/MemoContent/LinkMetadataCard.tsx b/web/src/components/MemoEditor/view/LinkMetadataCard.tsx
similarity index 100%
rename from web/src/components/MemoContent/LinkMetadataCard.tsx
rename to web/src/components/MemoEditor/view/LinkMetadataCard.tsx
diff --git a/web/src/components/MemoEditor/view/MemoContentView.tsx b/web/src/components/MemoEditor/view/MemoContentView.tsx
new file mode 100644
index 000000000..40e3bd689
--- /dev/null
+++ b/web/src/components/MemoEditor/view/MemoContentView.tsx
@@ -0,0 +1,153 @@
+import type { Editor } from "@usememos/editor";
+import { memo, useEffect, useMemo, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+import { useNavigate } from "react-router-dom";
+import { MemoMarkdown } from "@/components/MemoEditor/MemoMarkdown";
+import { createMemoNavigationState } from "@/components/MemoView/navigation";
+import { useContentSearchTerms } from "@/contexts/MemoFilterContext";
+import { useLinkPreviewEnabled } from "@/contexts/ViewContext";
+import { useNearViewport } from "@/hooks/useNearViewport";
+import { markdownStyles } from "@/lib/markdownStyles";
+import { cn } from "@/lib/utils";
+import { getCreatorHomePath } from "@/router/routes";
+import type { Attachment } from "@/types/proto/api/attachment_service_pb";
+import { findAnchorTarget } from "@/utils/markdown-manipulation";
+import { headingSlugs } from "./headings";
+import LinkMetadataCard from "./LinkMetadataCard";
+import { type LinkCardMount, linkCardsExtension } from "./linkCards";
+import { useSearchMatchHighlight } from "./useSearchMatchHighlight";
+import { useTagNavigation } from "./useTagNavigation";
+
+export interface MemoContentViewProps {
+ content: string;
+ /** Attachments bound to this memo, used to resolve managed image URLs in share/S3 modes. */
+ attachments?: readonly Attachment[];
+ /** Resource name of the memo (e.g. `memos/abc123`). Lets in-memo anchor links open the memo detail page. */
+ memoName?: string;
+ /** Collection page that rendered the memo, preserved when an inline link opens its detail page. */
+ parentPage?: string;
+ /** The card renders collapsed (ClampedSection), so in-memo anchor links navigate instead of scrolling. */
+ compact?: boolean;
+ /**
+ * Lets the viewer tick task items, for a memo they can manage. Called with the new
+ * Markdown, in which only the ticked item's `[ ]` or `[x]` changed.
+ */
+ onTaskToggle?: (content: string) => void;
+ className?: string;
+ contentClassName?: string;
+ onClick?: (e: React.MouseEvent) => void;
+ onDoubleClick?: (e: React.MouseEvent) => void;
+}
+
+const LinkPreview = ({ href }: { href: string }) => {
+ const { ref, isNearViewport } = useNearViewport<HTMLAnchorElement>();
+ const fallback = (
+ <a ref={ref} href={href} target="_blank" rel="noopener noreferrer" className={markdownStyles.link}>
+ {href}
+ </a>
+ );
+ return <LinkMetadataCard url={href} fallback={fallback} enabled={isNearViewport} />;
+};
+
+/** A mounted card, keyed for React: the element is the editor's, so the key cannot be derived from the block. */
+interface LinkCard extends LinkCardMount {
+ readonly key: number;
+}
+let nextLinkCardKey = 0;
+
+/**
+ * A memo's content, read-only, with the memo view's own surface over MemoMarkdown: tags and
+ * mentions navigate, in-memo anchors scroll, bare links become preview cards, and the page's
+ * search matches are painted. Owners can tick task items: each tick reports the new Markdown,
+ * in which only that item's `[ ]` or `[x]` changed. Truncation is not this component's
+ * concern — compact cards are bounded by ClampedSection around the whole memo body;
+ * `compact` only tells in-memo anchor links to open the detail page, since a collapsed card
+ * may hide their target. MemoEditor shows a memo by name through it; previews pass content.
+ */
+const MemoContentViewImpl = (props: MemoContentViewProps) => {
+ const { className, contentClassName, content, attachments, memoName, parentPage, compact, onTaskToggle, onClick, onDoubleClick } = props;
+ const navigate = useNavigate();
+ const linkPreviewEnabled = useLinkPreviewEnabled();
+ const navigateToTag = useTagNavigation(parentPage);
+ // Whatever the page's search matched is painted here, without altering the rendered tree.
+ const contentRef = useRef<HTMLDivElement>(null);
+ useSearchMatchHighlight(contentRef, useContentSearchTerms());
+ const [editor, setEditor] = useState<Editor | null>(null);
+
+ // Bare links become preview cards through the editor's block view: it hands over an
+ // element per such paragraph and keeps it while the block is unchanged, so the card
+ // portaled into it survives renders. Built once; the setting is read through a ref and
+ // applied with a refresh of this view.
+ const [cards, setCards] = useState<readonly LinkCard[]>([]);
+ const linkPreviewEnabledRef = useRef(linkPreviewEnabled);
+ linkPreviewEnabledRef.current = linkPreviewEnabled;
+ const linkCards = useMemo(
+ () => [
+ linkCardsExtension({
+ isEnabled: () => linkPreviewEnabledRef.current,
+ onMount: (mount) =>
+ setCards((previous) => [...previous.filter((card) => card.element !== mount.element), { ...mount, key: nextLinkCardKey++ }]),
+ onUnmount: (element) => setCards((previous) => previous.filter((card) => card.element !== element)),
+ }),
+ ],
+ [],
+ );
+ const appliedLinkPreview = useRef(linkPreviewEnabled);
+ useEffect(() => {
+ if (appliedLinkPreview.current === linkPreviewEnabled) return;
+ appliedLinkPreview.current = linkPreviewEnabled;
+ editor?.refreshViews("linkCards");
+ }, [editor, linkPreviewEnabled]);
+
+ // In-memo anchors scroll within this memo; a collapsed card may hide the target, so it opens the detail page.
+ const handleLinkClick = ({ href }: { href: string }) => {
+ if (!href.startsWith("#")) return false;
+ const id = decodeURIComponent(href.slice(1));
+ const target = !compact && id && contentRef.current ? findAnchorTarget(contentRef.current, id) : null;
+ if (target) {
+ target.scrollIntoView({ behavior: "smooth", block: "center" });
+ } else if (memoName) {
+ navigate(`/${memoName}${href}`, { state: parentPage ? createMemoNavigationState(parentPage) : undefined });
+ }
+ return true;
+ };
+
+ return (
+ <div className={`w-full flex flex-col justify-start items-start text-foreground ${className || ""}`}>
+ <div
+ ref={contentRef}
+ data-memo-content
+ data-memo-name={memoName}
+ className={cn(
+ "relative w-full max-w-full wrap-break-word text-base leading-6",
+ "[&_.katex-display]:max-w-full",
+ "[&_.katex-display]:overflow-x-auto",
+ "[&_.katex-display]:overflow-y-hidden",
+ contentClassName,
+ )}
+ onMouseUp={onClick}
+ onDoubleClick={onDoubleClick}
+ >
+ <MemoMarkdown
+ editorRef={setEditor}
+ value={content}
+ onChange={onTaskToggle}
+ taskToggle={Boolean(onTaskToggle)}
+ toolbar={false}
+ slashMenu={false}
+ attachments={attachments}
+ extensions={linkCards}
+ headingIds={headingSlugs}
+ onLinkClick={handleLinkClick}
+ // Tags filter the list when clicked here; mentions of people who exist open their page.
+ onTagClick={navigateToTag}
+ onMentionClick={(username) => navigate(getCreatorHomePath(username))}
+ className="memo-content-root"
+ />
+ {cards.map((card) => createPortal(<LinkPreview href={card.href} />, card.element, String(card.key)))}
+ </div>
+ </div>
+ );
+};
+
+export const MemoContentView = memo(MemoContentViewImpl);
diff --git a/web/src/components/MemoContent/headings.ts b/web/src/components/MemoEditor/view/headings.ts
similarity index 100%
rename from web/src/components/MemoContent/headings.ts
rename to web/src/components/MemoEditor/view/headings.ts
diff --git a/web/src/components/MemoEditor/view/linkCards.ts b/web/src/components/MemoEditor/view/linkCards.ts
new file mode 100644
index 000000000..7acbb0ef3
--- /dev/null
+++ b/web/src/components/MemoEditor/view/linkCards.ts
@@ -0,0 +1,46 @@
+import { type Block, type Extension, inlineText } from "@usememos/editor";
+
+/** The URL a paragraph consists of, when it is nothing but one bare web link: `https://…` written as its own text. */
+export function bareLinkOf(block: Block): string | undefined {
+ if (block.type !== "paragraph" || block.content.length === 0) return undefined;
+ const href = block.content[0].link;
+ // Only web links have metadata to preview; `tel:`/`sms:`/`mailto:` hand off to another app.
+ if (!href || !/^https?:\/\//i.test(href)) return undefined;
+ // A titled link is a written `[text](url "title")`, never a bare URL; a card would drop its title.
+ if (!block.content.every((span) => span.link === href && !span.linkTitle && !span.image)) return undefined;
+ return inlineText(block.content) === href ? href : undefined;
+}
+
+/** A card's place in the editor: the element the editor owns for the block, and the link it shows. */
+export interface LinkCardMount {
+ readonly element: HTMLElement;
+ readonly href: string;
+}
+
+export interface LinkCardsHooks {
+ /** Read when the editor draws a block; `editor.refreshViews("linkCards")` applies a change. */
+ isEnabled: () => boolean;
+ /** The editor has an element for a bare-link paragraph; the host mounts its card into it. */
+ onMount: (mount: LinkCardMount) => void;
+ /** The editor let the element go: the block was removed or changed, or the view was refreshed. */
+ onUnmount: (element: HTMLElement) => void;
+}
+
+/**
+ * The link preview cards, as the editor's own block view: a paragraph that is one bare
+ * web link is drawn by the host, which needs the page's details from the memos server.
+ * The editor keeps the element while the block is unchanged, so the card the host mounts
+ * into it (a React portal) survives renders, and calls `onUnmount` when it lets it go.
+ */
+export const linkCardsExtension = (hooks: LinkCardsHooks): Extension => ({
+ name: "linkCards",
+ blockView: {
+ match: (block) => hooks.isEnabled() && bareLinkOf(block) !== undefined,
+ render: (block, element) => {
+ const href = bareLinkOf(block);
+ if (!href) return false;
+ hooks.onMount({ element, href });
+ return () => hooks.onUnmount(element);
+ },
+ },
+});
diff --git a/web/src/components/MemoContent/useSearchMatchHighlight.ts b/web/src/components/MemoEditor/view/useSearchMatchHighlight.ts
similarity index 100%
rename from web/src/components/MemoContent/useSearchMatchHighlight.ts
rename to web/src/components/MemoEditor/view/useSearchMatchHighlight.ts
diff --git a/web/src/components/MemoContent/useTagNavigation.ts b/web/src/components/MemoEditor/view/useTagNavigation.ts
similarity index 93%
rename from web/src/components/MemoContent/useTagNavigation.ts
rename to web/src/components/MemoEditor/view/useTagNavigation.ts
index acb8b47ef..31dfca5a3 100644
--- a/web/src/components/MemoContent/useTagNavigation.ts
+++ b/web/src/components/MemoEditor/view/useTagNavigation.ts
@@ -1,8 +1,8 @@
import { useLocation } from "react-router-dom";
+import { isMemoResourcePath, withMemoFilter } from "@/components/MemoView/navigation";
import { type MemoFilter, stringifyFilters, useMemoFilterContext } from "@/contexts/MemoFilterContext";
import useNavigateTo from "@/hooks/useNavigateTo";
import { Routes } from "@/router";
-import { isMemoResourcePath, withMemoFilter } from "../MemoView/navigation";
/**
* What clicking a tag in a memo does. On a memo detail page it opens the collection the
diff --git a/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx b/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx
index 87e7eb0a9..346bec14e 100644
--- a/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx
+++ b/web/src/components/MemoMetadata/Attachment/AttachmentListEditor.tsx
@@ -11,8 +11,8 @@ import {
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";
+import type { AttachmentItem, LocalFile } from "@/components/MemoEditor/edit/types/attachment";
+import { getAudioRecordingTimeLabel, toAttachmentItems } from "@/components/MemoEditor/edit/types/attachment";
import MetadataSection, {
METADATA_ROW_BOX_CLASSES,
METADATA_ROW_CONTROLS_CLASSES,
diff --git a/web/src/components/MemoMetadata/Location/LocationDialog.tsx b/web/src/components/MemoMetadata/Location/LocationDialog.tsx
index d3b918a09..fecc5882a 100644
--- a/web/src/components/MemoMetadata/Location/LocationDialog.tsx
+++ b/web/src/components/MemoMetadata/Location/LocationDialog.tsx
@@ -1,4 +1,4 @@
-import type { LocationState } from "@/components/MemoEditor/types/insertMenu";
+import type { LocationState } from "@/components/MemoEditor/edit/types/insertMenu";
import { LazyLocationPicker } from "@/components/map/LazyLocationPicker";
import type { MapPoint } from "@/components/map/types";
import { Button } from "@/components/ui/button";
diff --git a/web/src/components/MemoPanel/MemoPanelList.tsx b/web/src/components/MemoPanel/MemoPanelList.tsx
index 6cedf3e89..01842f1e7 100644
--- a/web/src/components/MemoPanel/MemoPanelList.tsx
+++ b/web/src/components/MemoPanel/MemoPanelList.tsx
@@ -1,12 +1,11 @@
import { PlusIcon } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
-import { MentionResolutionProvider } from "@/components/MemoContent/MentionResolutionContext";
-import MemoEditor from "@/components/MemoEditor";
-import type { MemoEditorProps } from "@/components/MemoEditor/types/components";
+import { type MemoDraftSeed, MemoEditor } from "@/components/MemoEditor";
import MemoView from "@/components/MemoView";
import type { MemoTimeDisplay } from "@/components/MemoView/types";
import { buttonVariants } from "@/components/ui/button";
import { useAuth } from "@/contexts/AuthContext";
+import { MentionResolutionProvider } from "@/contexts/MentionResolutionContext";
import { NewMemoProvider } from "@/contexts/NewMemoContext";
import { useSpaceContext } from "@/contexts/SpaceContext";
import { useView } from "@/contexts/ViewContext";
@@ -18,11 +17,12 @@ import { useTranslate } from "@/utils/i18n";
const COMPOSE_ROW_CLASS = cn(buttonVariants({ variant: "quiet", size: "sm" }), "self-start");
export interface MemoPanelCompose {
- cacheKey: string;
+ /** Where the new memo is composed, such as `calendar:<date>`; each scope keeps its own draft. */
+ scope: string;
/** The quiet row's label, e.g. "New memo on this day". */
label: string;
/** What the new memo inherits from the selection: its day, its place. */
- defaults?: Pick<MemoEditorProps, "defaultCreateTime" | "defaultLocation">;
+ defaults?: Pick<MemoDraftSeed, "createTime" | "location">;
/** Whether the editor is open in place of the row, for hosts whose own gestures could dismiss it. */
onComposingChange?: (composing: boolean) => void;
onSavingChange?: (saving: boolean) => void;
@@ -94,11 +94,9 @@ export function MemoPanelList({ memos, selectionKey, timeDisplay, emptyText, com
isUserSettingsInitialized &&
(composing ? (
<MemoEditor
- cacheKey={compose.cacheKey}
+ draft={{ scope: compose.scope, space: selectedSpaceName, ...compose.defaults }}
autoFocus
placeholder={t("editor.any-thoughts")}
- defaultSpace={selectedSpaceName}
- {...compose.defaults}
onSavingChange={compose.onSavingChange}
onConfirm={(name) => {
setComposingFor(undefined);
diff --git a/web/src/components/MemoPreview/MemoPreview.tsx b/web/src/components/MemoPreview/MemoPreview.tsx
index 268770c3f..71a19083f 100644
--- a/web/src/components/MemoPreview/MemoPreview.tsx
+++ b/web/src/components/MemoPreview/MemoPreview.tsx
@@ -1,6 +1,7 @@
import { create } from "@bufbuild/protobuf";
import { FileIcon } from "lucide-react";
import { useMemo } from "react";
+import { MemoContentView } from "@/components/MemoEditor/view/MemoContentView";
import { extractMemoIdFromName } from "@/lib/resource-names";
import { cn } from "@/lib/utils";
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
@@ -9,7 +10,6 @@ import type { User } from "@/types/proto/api/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";
interface MemoPreviewProps {
@@ -34,7 +34,10 @@ const STUB_CONTEXT: MemoViewContextValue = {
readonly: true,
showBlurredContent: false,
blurred: false,
+ isEditing: false,
openEditor: () => {},
+ closeEditor: () => {},
+ onEditorFocusModeChange: () => {},
toggleBlurVisibility: () => {},
openPreview: () => {},
};
@@ -134,7 +137,7 @@ const MemoPreview = ({
// interactive clamp a full memo card gets.
hasContent && (
<div className="max-h-36 w-full overflow-hidden">
- <MemoContent content={content} attachments={attachments} compact={compact} />
+ <MemoContentView content={content} attachments={attachments} compact={compact} />
</div>
)
);
diff --git a/web/src/components/MemoReactionListView/hooks.ts b/web/src/components/MemoReactionListView/hooks.ts
index cf9f3a1b8..f544632f8 100644
--- a/web/src/components/MemoReactionListView/hooks.ts
+++ b/web/src/components/MemoReactionListView/hooks.ts
@@ -1,7 +1,7 @@
import { useQueryClient } from "@tanstack/react-query";
import { useMemo } from "react";
-import { useResolvedUsersByNames } from "@/components/MemoContent/MentionResolutionContext";
import { memoServiceClient } from "@/connect";
+import { useResolvedUsersByNames } from "@/contexts/MentionResolutionContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { memoKeys } from "@/hooks/useMemoQueries";
import type { Memo, Reaction } from "@/types/proto/api/memo_service_pb";
diff --git a/web/src/components/MemoView/MemoView.tsx b/web/src/components/MemoView/MemoView.tsx
index f8a0898cd..5ee970ed4 100644
--- a/web/src/components/MemoView/MemoView.tsx
+++ b/web/src/components/MemoView/MemoView.tsx
@@ -1,22 +1,8 @@
-import {
- type ComponentType,
- forwardRef,
- memo,
- Suspense,
- useCallback,
- useEffect,
- useImperativeHandle,
- useLayoutEffect,
- useMemo,
- useRef,
- useState,
-} from "react";
+import { forwardRef, memo, Suspense, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useLocation } from "react-router-dom";
import { useColumnGridUntrapped } from "@/components/ColumnGrid/ColumnGridContext";
-import { useResolvedUser } from "@/components/MemoContent/MentionResolutionContext";
-import { loadMemoEditor } from "@/components/MemoEditor/loader";
-import type { MemoEditorProps } from "@/components/MemoEditor/types";
import { useAuth } from "@/contexts/AuthContext";
+import { useResolvedUser } from "@/contexts/MentionResolutionContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { isMemoBlurred } from "@/lib/tag";
import { cn } from "@/lib/utils";
@@ -47,8 +33,7 @@ const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((props, ref) => {
showSpace,
} = props;
const cardRef = useRef<HTMLDivElement>(null);
- const [showEditor, setShowEditor] = useState(false);
- const [EditorComponent, setEditorComponent] = useState<ComponentType<MemoEditorProps>>();
+ const [isEditing, setIsEditing] = useState(false);
const [cardWidth, setCardWidth] = useState(0);
const currentUser = useCurrentUser();
@@ -70,27 +55,23 @@ const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((props, ref) => {
const toggleBlurVisibility = useCallback(() => setShowBlurredContent((prev) => !prev), []);
const { previewState, openPreview, setPreviewOpen } = useImagePreview();
- const editorHostRef = useRef<HTMLDivElement>(null);
const focusMountedEditor = useCallback(() => {
- const editorRoot = editorHostRef.current?.querySelector<HTMLElement>('.memo-editor-root[contenteditable="true"]');
- const fallbackInput = editorHostRef.current?.querySelector<HTMLElement>("textarea, input");
+ const editorRoot = cardRef.current?.querySelector<HTMLElement>('.memo-editor-root[contenteditable="true"]');
+ const fallbackInput = cardRef.current?.querySelector<HTMLElement>("textarea, input");
(editorRoot ?? fallbackInput)?.focus();
}, []);
+ // The body edits in place: the card, its header and its frame stay, and the memo's
+ // own editing session takes the body's place until it saves or cancels.
const openEditor = useCallback(() => {
- if (showEditor && EditorComponent) {
+ if (isEditing) {
focusMountedEditor();
return;
}
- void loadMemoEditor()
- .then(({ default: MemoEditor }) => {
- setEditorComponent(() => MemoEditor);
- setShowEditor(true);
- })
- .catch(() => undefined);
- }, [EditorComponent, focusMountedEditor, showEditor]);
- const closeEditor = useCallback(() => setShowEditor(false), []);
+ setIsEditing(true);
+ }, [focusMountedEditor, isEditing]);
+ const closeEditor = useCallback(() => setIsEditing(false), []);
// The grid keys tiles by memo name (see getMemoKey), so the focused editor
// identifies its own tile by name and untraps it for the duration.
@@ -108,10 +89,10 @@ const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((props, ref) => {
// Release the slot when the editor closes or this card unmounts. Both calls
// are ownership-scoped, so mounting cards never clobber another card's slot.
useEffect(() => {
- if (!showEditor) {
+ if (!isEditing) {
clearUntrappedKey(memoData.name);
}
- }, [showEditor, memoData.name, clearUntrappedKey]);
+ }, [isEditing, memoData.name, clearUntrappedKey]);
useEffect(() => () => clearUntrappedKey(memoData.name), [memoData.name, clearUntrappedKey]);
useImperativeHandle(ref, () => ({ openEditor }), [openEditor]);
@@ -163,7 +144,10 @@ const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((props, ref) => {
readonly,
showBlurredContent,
blurred,
+ isEditing,
openEditor,
+ closeEditor,
+ onEditorFocusModeChange: handleFocusModeChange,
toggleBlurVisibility,
openPreview,
}),
@@ -177,7 +161,10 @@ const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((props, ref) => {
readonly,
showBlurredContent,
blurred,
+ isEditing,
openEditor,
+ closeEditor,
+ handleFocusModeChange,
toggleBlurVisibility,
openPreview,
],
@@ -222,26 +209,7 @@ const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((props, ref) => {
article
);
- return (
- <MemoViewContext.Provider value={contextValue}>
- {showEditor && EditorComponent ? (
- <div ref={editorHostRef} className="w-full">
- <EditorComponent
- autoFocus
- className="mb-2"
- cacheKey={`inline-memo-editor-${memoData.name}`}
- memo={memoData}
- parentMemoName={memoData.parent || undefined}
- onConfirm={closeEditor}
- onCancel={closeEditor}
- onFocusModeChange={handleFocusModeChange}
- />
- </div>
- ) : (
- memoDisplay
- )}
- </MemoViewContext.Provider>
- );
+ return <MemoViewContext.Provider value={contextValue}>{memoDisplay}</MemoViewContext.Provider>;
});
MemoView.displayName = "MemoView";
diff --git a/web/src/components/MemoView/MemoViewContext.tsx b/web/src/components/MemoView/MemoViewContext.tsx
index a973c7869..250c89d90 100644
--- a/web/src/components/MemoView/MemoViewContext.tsx
+++ b/web/src/components/MemoView/MemoViewContext.tsx
@@ -19,7 +19,12 @@ export interface MemoViewContextValue {
readonly: boolean;
showBlurredContent: boolean;
blurred: boolean;
+ /** Whether the card shows the memo's editing session in place of its body. */
+ isEditing: boolean;
openEditor: () => void;
+ closeEditor: () => void;
+ /** The session reports focus mode so the card's layout can let it take the viewport. */
+ onEditorFocusModeChange: (isFocusMode: boolean) => void;
toggleBlurVisibility: () => void;
openPreview: (items: string | string[] | PreviewMediaItem[], index?: number) => void;
}
diff --git a/web/src/components/MemoView/components/MemoBody.tsx b/web/src/components/MemoView/components/MemoBody.tsx
index c51c3d1c8..11030ea39 100644
--- a/web/src/components/MemoView/components/MemoBody.tsx
+++ b/web/src/components/MemoView/components/MemoBody.tsx
@@ -1,15 +1,14 @@
import { EyeIcon } from "lucide-react";
import { useMemo } from "react";
import ClampedSection from "@/components/ClampedSection";
+import { MemoEditor } from "@/components/MemoEditor/MemoEditor";
import { AttachmentGallery, MemoMetadataRows } from "@/components/MemoMetadata";
import { separateAttachments } from "@/components/MemoMetadata/Attachment/attachmentHelpers";
import { isReferenceRelation } from "@/components/MemoMetadata/Relation/relationHelpers";
import { Button } from "@/components/ui/button";
-import { useUpdateMemo } from "@/hooks/useMemoQueries";
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";
import { useMemoViewContext } from "../MemoViewContext";
@@ -28,12 +27,21 @@ const BlurOverlay: React.FC<{ onClick?: () => void }> = ({ onClick }) => {
};
const MemoBody: React.FC<MemoBodyProps> = ({ compact }) => {
- const { memo, parentPage, showBlurredContent, blurred, readonly, openEditor, openPreview, toggleBlurVisibility } = useMemoViewContext();
+ const {
+ memo,
+ parentPage,
+ showBlurredContent,
+ blurred,
+ readonly,
+ isEditing,
+ openEditor,
+ closeEditor,
+ onEditorFocusModeChange,
+ openPreview,
+ toggleBlurVisibility,
+ } = useMemoViewContext();
const { handleMemoContentClick, handleMemoContentDoubleClick } = useMemoHandlers({ readonly, openEditor, openPreview });
- const { mutate: updateMemo } = useUpdateMemo();
- const handleTaskToggle = (content: string) =>
- updateMemo({ update: { name: memo.name, content }, updateMask: ["content", "update_time"] });
const referencedMemos = memo.relations.filter(isReferenceRelation);
// Memoized so AttachmentListView's own useMemo chain keeps its cache across body renders.
@@ -43,6 +51,24 @@ const MemoBody: React.FC<MemoBodyProps> = ({ compact }) => {
);
const { visual, audio, docs } = useMemo(() => separateAttachments(attachmentOnlyItems), [attachmentOnlyItems]);
+ // Editing takes the body's place inside the card's own frame: the session brings its
+ // attachments, metadata and toolbar, so the read-only rows and reactions step aside.
+ if (isEditing) {
+ return (
+ <div data-slot="memo-body" className="w-full">
+ <MemoEditor
+ mode="edit"
+ name={memo.name}
+ frameless
+ autoFocus
+ onConfirm={closeEditor}
+ onCancel={closeEditor}
+ onFocusModeChange={onEditorFocusModeChange}
+ />
+ </div>
+ );
+ }
+
return (
<div className="w-full flex flex-col justify-start items-start gap-2">
<div data-slot="memo-body" className="relative w-full">
@@ -55,15 +81,12 @@ const MemoBody: React.FC<MemoBodyProps> = ({ compact }) => {
{/* Compact bounds the whole body — attachments included — behind one Show more.
Reactions stay outside so they never hide under the fade. */}
<ClampedSection enabled={Boolean(compact)}>
- <MemoContent
- memoName={memo.name}
+ <MemoEditor
+ name={memo.name}
parentPage={parentPage}
- content={memo.content}
- attachments={memo.attachments}
+ compact={Boolean(compact)}
onClick={handleMemoContentClick}
onDoubleClick={handleMemoContentDoubleClick}
- onTaskToggle={readonly ? undefined : handleTaskToggle}
- compact={Boolean(compact)}
/>
<AttachmentGallery visual={visual} onImagePreview={openPreview} />
<MemoMetadataRows
diff --git a/web/src/components/MemoView/components/MemoHeader.tsx b/web/src/components/MemoView/components/MemoHeader.tsx
index a5c4f19ff..a4b73fb48 100644
--- a/web/src/components/MemoView/components/MemoHeader.tsx
+++ b/web/src/components/MemoView/components/MemoHeader.tsx
@@ -27,7 +27,7 @@ const MEMO_HEADER_ACTION_CLASSES = cn(buttonVariants({ variant: "quiet", size: "
const MemoHeader: React.FC<MemoHeaderProps> = ({ timeDisplay = "relative", showCreator, showVisibility, showSpace }) => {
const t = useTranslate();
- const { memo, creator, currentUser, parentPage, isArchived, readonly, openEditor } = useMemoViewContext();
+ const { memo, creator, currentUser, parentPage, isArchived, readonly, isEditing, openEditor } = useMemoViewContext();
const location = useLocation();
const { createTime, updateTime, displayTime: memoDisplayTime, isDisplayingUpdatedTime, relativeTimeFormat } = useMemoViewDerived();
const { newMemoName } = useNewMemo();
@@ -55,6 +55,24 @@ const MemoHeader: React.FC<MemoHeaderProps> = ({ timeDisplay = "relative", showC
: undefined,
};
const spaceMetadata = showSpace && memo.space ? <MemoSpaceBadge spaceName={memo.space} /> : null;
+ const showsCreator = Boolean(showCreator && creator);
+ const isNew = memo.name === newMemoName;
+
+ // While the card edits in place, the header keeps only identity. The time, visibility
+ // and Space show once, in their editable form, in the session below (its timestamp row
+ // and audience menu); reacting or opening the action menu makes no sense mid-edit, and
+ // the "new" mark is for finding the memo in the list, not for the person editing it.
+ // With no identity to show, the row goes and the session's timestamp row takes its place.
+ if (isEditing) {
+ if (!showsCreator || !creator) return null;
+ return (
+ <div className="flex h-6 w-full items-center gap-2">
+ <div data-slot="memo-header-meta" className="flex min-w-0 items-center gap-1.5 overflow-hidden">
+ <CreatorDisplay creator={creator} withSeparator={false} />
+ </div>
+ </div>
+ );
+ }
return (
// A fixed 24px row, the height of its action squares, so the card's top edge never
@@ -63,7 +81,7 @@ const MemoHeader: React.FC<MemoHeaderProps> = ({ timeDisplay = "relative", showC
<div className="flex min-w-0 flex-1 items-center gap-2">
{/* The time stays visible while the creator and Space badge can shrink and truncate. */}
<div data-slot="memo-header-meta" className="flex min-w-0 items-center gap-1.5 overflow-hidden">
- {showCreator && creator && <CreatorDisplay creator={creator} />}
+ {showsCreator && creator && <CreatorDisplay creator={creator} />}
<TimeDisplay
displayTime={displayTime}
timeTooltip={timeTooltip}
@@ -73,11 +91,7 @@ const MemoHeader: React.FC<MemoHeaderProps> = ({ timeDisplay = "relative", showC
/>
{spaceMetadata}
</div>
- {memo.name === newMemoName && (
- <span className="shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-2xs font-medium leading-none text-primary">
- {t("memo.new-badge")}
- </span>
- )}
+ {isNew && <NewBadge />}
</div>
<div data-slot="memo-header-actions" className="flex shrink-0 select-none flex-row items-center justify-end gap-1">
@@ -103,12 +117,21 @@ const MemoHeader: React.FC<MemoHeaderProps> = ({ timeDisplay = "relative", showC
);
};
+const NewBadge = () => {
+ const t = useTranslate();
+ return (
+ <span className="shrink-0 rounded-full bg-primary/10 px-1.5 py-0.5 text-2xs font-medium leading-none text-primary">
+ {t("memo.new-badge")}
+ </span>
+ );
+};
+
/**
* The author on one line with the time: a 20px avatar in a 20px slot, then the name in
* medium 13px foreground ink. It is the identity, so it carries the weight; the time after
- * it is muted.
+ * it is muted, and the separator before it goes when nothing follows.
*/
-const CreatorDisplay: React.FC<{ creator: User }> = ({ creator }) => (
+const CreatorDisplay: React.FC<{ creator: User; withSeparator?: boolean }> = ({ creator, withSeparator = true }) => (
<>
<Link
className={cn(
@@ -123,9 +146,11 @@ const CreatorDisplay: React.FC<{ creator: User }> = ({ creator }) => (
</span>
<span className="min-w-0 truncate">{creator.displayName || creator.username}</span>
</Link>
- <span aria-hidden="true" className="shrink-0 text-muted-foreground/40">
- ·
- </span>
+ {withSeparator && (
+ <span aria-hidden="true" className="shrink-0 text-muted-foreground/40">
+ ·
+ </span>
+ )}
</>
);
diff --git a/web/src/components/PagedMemoList/PagedMemoList.tsx b/web/src/components/PagedMemoList/PagedMemoList.tsx
index 8e05d2787..f8a7be4bd 100644
--- a/web/src/components/PagedMemoList/PagedMemoList.tsx
+++ b/web/src/components/PagedMemoList/PagedMemoList.tsx
@@ -1,10 +1,10 @@
import { ArrowUpIcon, LoaderCircleIcon } from "lucide-react";
import { type ReactElement, type ReactNode, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
-import { MentionResolutionProvider } from "@/components/MemoContent/MentionResolutionContext";
import { Button } from "@/components/ui/button";
import { useAppSidebar } from "@/contexts/AppSidebarContext";
import { useAuth } from "@/contexts/AuthContext";
import { isSearchFilter, useMemoFilterContext } from "@/contexts/MemoFilterContext";
+import { MentionResolutionProvider } from "@/contexts/MentionResolutionContext";
import { useNewMemo } from "@/contexts/NewMemoContext";
import { useView } from "@/contexts/ViewContext";
import { useDelayedFlag } from "@/hooks/useDelayedFlag";
diff --git a/web/src/contexts/GlobalMemoEditorContext.tsx b/web/src/contexts/GlobalMemoEditorContext.tsx
index 27f9fcb50..071def8c2 100644
--- a/web/src/contexts/GlobalMemoEditorContext.tsx
+++ b/web/src/contexts/GlobalMemoEditorContext.tsx
@@ -1,9 +1,8 @@
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
-import { type ComponentType, createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
+import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { useLocation } from "react-router-dom";
import { getSidebarRouteKind } from "@/components/AppSidebar/routes";
-import { loadMemoEditor } from "@/components/MemoEditor/loader";
-import type { MemoEditorProps } from "@/components/MemoEditor/types";
+import { MemoEditor, preloadMemoEditing } from "@/components/MemoEditor";
import { VisuallyHidden } from "@/components/ui/visually-hidden";
import { useAppSidebar } from "@/contexts/AppSidebarContext";
import { useAuth } from "@/contexts/AuthContext";
@@ -11,7 +10,6 @@ import { useSpaceContext } from "@/contexts/SpaceContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import useMediaQuery from "@/hooks/useMediaQuery";
import { useMemoSuggestions } from "@/hooks/useMemoSuggestions";
-import { spaceScopedCacheKey } from "@/lib/resource-names";
import { useTranslate } from "@/utils/i18n";
interface GlobalMemoEditorContextValue {
@@ -55,12 +53,10 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
// signing out closes the composer in the same render and a different user signing
// in cannot resurrect it, and pinned to the Space that was selected at that moment.
const [opened, setOpened] = useState<{ user: string; space?: string }>();
- const [EditorComponent, setEditorComponent] = useState<ComponentType<MemoEditorProps>>();
// Only ever read from event handlers, so a ref keeps each save from
// re-rendering the provider and the whole editor tree it hosts.
const isSavingRef = useRef(false);
const returnFocusRef = useRef<HTMLElement | null>(null);
- const openRequestVersionRef = useRef(0);
useEffect(() => {
if (
@@ -83,7 +79,6 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
}, []);
const closeEditor = useCallback(() => {
- openRequestVersionRef.current += 1;
isSavingRef.current = false;
setOpened(undefined);
}, []);
@@ -106,18 +101,13 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
setMobileOpen(false);
setQuickFindOpen(false);
- const requestVersion = ++openRequestVersionRef.current;
isSavingRef.current = false;
const activeElement = document.activeElement;
returnFocusRef.current = activeElement instanceof HTMLElement && activeElement !== document.body ? activeElement : null;
- void loadMemoEditor()
- .then(({ default: MemoEditor }) => {
- if (openRequestVersionRef.current !== requestVersion) return;
- setEditorComponent(() => MemoEditor);
- setOpened({ user: currentUserName, space: selectedSpaceName });
- })
- .catch(() => undefined);
+ // The dialog opens at once; the editor fills it as soon as its code is here.
+ preloadMemoEditing();
+ setOpened({ user: currentUserName, space: selectedSpaceName });
}, [canOpen, selectedSpaceName, currentUserName, setMobileOpen, setQuickFindOpen]);
useEffect(() => {
@@ -158,7 +148,7 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
}
}}
>
- {EditorComponent && (
+ {editorIsOpen && (
<DialogPrimitive.Portal>
<DialogPrimitive.Backdrop className="fixed inset-0 z-overlay bg-transparent" />
<DialogPrimitive.Popup
@@ -170,10 +160,9 @@ export function GlobalMemoEditorProvider({ children }: { children: ReactNode })
<VisuallyHidden>
<DialogPrimitive.Title>{t("editor.new-memo")}</DialogPrimitive.Title>
</VisuallyHidden>
- <EditorComponent
+ <MemoEditor
autoFocus
- cacheKey={spaceScopedCacheKey("global-memo-editor", opened?.space)}
- defaultSpace={opened?.space}
+ draft={{ scope: "global", space: opened?.space }}
suggestions={suggestions}
placeholder={t("editor.any-thoughts")}
onConfirm={closeEditor}
diff --git a/web/src/components/MemoContent/MentionResolutionContext.tsx b/web/src/contexts/MentionResolutionContext.tsx
similarity index 79%
rename from web/src/components/MemoContent/MentionResolutionContext.tsx
rename to web/src/contexts/MentionResolutionContext.tsx
index 0974aa72f..356ea5f41 100644
--- a/web/src/components/MemoContent/MentionResolutionContext.tsx
+++ b/web/src/contexts/MentionResolutionContext.tsx
@@ -1,5 +1,5 @@
import { useQueries } from "@tanstack/react-query";
-import { createContext, type ReactNode, useContext, useMemo } from "react";
+import { createContext, type ReactNode, useContext, useMemo, useRef } from "react";
import { userDetailQueryOptions, useUsersByUsernames } from "@/hooks/useUserQueries";
import { extractMentionUsernames } from "@/lib/memo-markdown";
import { extractUsernameFromName } from "@/lib/resource-names";
@@ -57,23 +57,24 @@ export const MentionResolutionProvider = ({ contents, userNames = EMPTY_USER_NAM
export function useResolvedMentionUsernames(content: string) {
const sharedResolution = useContext(UserResolutionContext);
- const shouldUseSharedResolution = sharedResolution !== null;
- const usernames = useMemo(
- () => sharedResolution?.mentionUsernamesByContent.get(content) ?? extractMentionUsernames(content),
- [content, sharedResolution],
- );
- const { data: mentionUsers } = useUsersByUsernames(usernames, { enabled: !shouldUseSharedResolution });
+ // The provider resolves only the contents it was given; a draft in the composer, or a
+ // memo outside its list, looks its own mentions up.
+ const shared = sharedResolution?.mentionUsernamesByContent.has(content) ? sharedResolution : null;
+ const usernames = useMemo(() => shared?.mentionUsernamesByContent.get(content) ?? extractMentionUsernames(content), [content, shared]);
+ const { data: mentionUsers } = useUsersByUsernames(usernames, { enabled: shared === null });
+ // Until a lookup answers, the people already found stay found: a name typed next to a
+ // resolved mention must not unresolve it for the length of a request.
+ const lastAnswer = useRef(new Set<string>());
return useMemo(() => {
- if (sharedResolution) {
- return new Set(usernames.filter((username) => sharedResolution.resolvedMentionUsernames.has(username)));
+ if (shared) {
+ return new Set(usernames.filter((username) => shared.resolvedMentionUsernames.has(username)));
}
- if (!mentionUsers) {
- return new Set<string>();
+ if (mentionUsers) {
+ lastAnswer.current = new Set(Array.from(mentionUsers.entries()).flatMap(([username, user]) => (user ? [username] : [])));
}
-
- return new Set(Array.from(mentionUsers.entries()).flatMap(([username, user]) => (user ? [username] : [])));
- }, [mentionUsers, sharedResolution, usernames]);
+ return lastAnswer.current;
+ }, [mentionUsers, shared, usernames]);
}
export function useResolvedUser(name: string, options?: { enabled?: boolean }) {
diff --git a/web/src/hooks/useMemoQueries.ts b/web/src/hooks/useMemoQueries.ts
index 81d920898..1a1be2606 100644
--- a/web/src/hooks/useMemoQueries.ts
+++ b/web/src/hooks/useMemoQueries.ts
@@ -10,8 +10,10 @@ import {
useQuery,
useQueryClient,
} from "@tanstack/react-query";
+import { useCallback, useSyncExternalStore } from "react";
import { memoServiceClient } from "@/connect";
import { attachmentKeys } from "@/hooks/useAttachmentQueries";
+import { memoShareKeys } from "@/hooks/useMemoShareQueries";
import { userKeys } from "@/hooks/useUserQueries";
import { DEFAULT_LIST_MEMOS_PAGE_SIZE } from "@/lib/constants";
import { shouldRetry } from "@/lib/query-client";
@@ -58,112 +60,181 @@ function discardUnavailableMemo(client: QueryClient, name: string) {
const relations = memo.relations.filter((relation) => relation.memo?.name !== name && relation.relatedMemo?.name !== name);
return relations.length === memo.relations.length ? memo : { ...memo, relations };
};
- const stripList = (data: ListMemosResponse): ListMemosResponse => {
- const memos = data.memos.filter((memo) => memo.name !== name).map(stripRelations);
- return memos.length === data.memos.length && memos.every((memo, index) => memo === data.memos[index]) ? data : { ...data, memos };
- };
- for (const [key, data] of client.getQueriesData<MemoCollectionQueryData | Memo | null>({ queryKey: memoKeys.all })) {
- let next = data;
- if (isMemoListResponse(data)) next = stripList(data);
- else if (isInfiniteMemoListData(data)) {
- const pages = data.pages.map(stripList);
- if (pages.some((page, index) => page !== data.pages[index])) next = { ...data, pages };
- } else if (key[1] === "detail" && data && "name" in data && data.name !== name) next = stripRelations(data);
+ for (const [key, data] of client.getQueriesData<unknown>({ queryKey: memoKeys.all })) {
+ let next: unknown;
+ if (isMemo(data)) next = data.name === name ? data : stripRelations(data);
+ else next = mapMemoCollection(data, (memos) => filterMemos(memos, (memo) => memo.name !== name, stripRelations));
if (next !== data) client.setQueryData(key, next);
}
}
type MemoPatch = Partial<Memo> & Pick<Memo, "name">;
-type MemoCollectionQueryData = ListMemosResponse | InfiniteData<ListMemosResponse>;
+
+// The shapes a memo query holds: a memo list response (`memos`), a comment list
+// response (`comments`), a bare array (the calendar month), the infinite-query
+// pages of either response, or one memo (a detail or a shared memo).
+
+function isMemo(data: unknown): data is Memo {
+ return typeof data === "object" && data !== null && typeof (data as { name?: unknown }).name === "string" && "content" in data;
+}
function isMemoListResponse(data: unknown): data is ListMemosResponse {
return typeof data === "object" && data !== null && Array.isArray((data as { memos?: unknown }).memos);
}
-function isInfiniteMemoListData(data: unknown): data is InfiniteData<ListMemosResponse> {
- return typeof data === "object" && data !== null && Array.isArray((data as { pages?: unknown }).pages);
+function isMemoCommentsResponse(data: unknown): data is { comments: Memo[] } {
+ return typeof data === "object" && data !== null && Array.isArray((data as { comments?: unknown }).comments);
}
-function patchMemoListResponse(response: ListMemosResponse, update: MemoPatch): ListMemosResponse {
- let changed = false;
- const memos = response.memos.map((memo) => {
- if (memo.name !== update.name) {
- return memo;
- }
-
- changed = true;
- return { ...memo, ...update };
- });
-
- return changed ? { ...response, memos } : response;
+function isInfiniteData(data: unknown): data is InfiniteData<unknown> {
+ return typeof data === "object" && data !== null && Array.isArray((data as { pages?: unknown }).pages);
}
-function patchMemoListQueryData<T>(data: T | undefined, update: MemoPatch): T | undefined {
- if (!data) {
- return data;
- }
-
- if (isMemoListResponse(data)) {
- return patchMemoListResponse(data, update) as T;
- }
+function memosOfPage(page: unknown): Memo[] | undefined {
+ if (Array.isArray(page)) return page as Memo[];
+ if (isMemoListResponse(page)) return page.memos;
+ if (isMemoCommentsResponse(page)) return page.comments;
+ return undefined;
+}
- if (isInfiniteMemoListData(data)) {
- let changed = false;
- const pages = data.pages.map((page) => {
- const patchedPage = patchMemoListResponse(page, update);
- if (patchedPage !== page) {
- changed = true;
- }
- return patchedPage;
- });
+/** Replaces a page's memos, keeping the page's reference when the memos did not change. */
+function withMemos<T>(page: T, memos: Memo[]): T {
+ if (memosOfPage(page) === memos) return page;
+ if (Array.isArray(page)) return memos as T;
+ if (isMemoListResponse(page)) return { ...page, memos } as T;
+ return { ...(page as object), comments: memos } as T;
+}
- return (changed ? { ...data, pages } : data) as T;
+/** Maps every page of memos in a collection query, keeping references where nothing changed. */
+function mapMemoCollection<T>(data: T, map: (memos: Memo[]) => Memo[]): T {
+ if (isInfiniteData(data)) {
+ const pages = data.pages.map((page) => mapMemoCollection(page, map));
+ return pages.some((page, index) => page !== data.pages[index]) ? ({ ...data, pages } as T) : data;
}
+ const memos = memosOfPage(data);
+ return memos ? withMemos(data, map(memos)) : data;
+}
- return data;
+function filterMemos(memos: Memo[], keep: (memo: Memo) => boolean, map: (memo: Memo) => Memo = (memo) => memo): Memo[] {
+ const next = memos.filter(keep).map(map);
+ return next.length === memos.length && next.every((memo, index) => memo === memos[index]) ? memos : next;
}
-function findMemoInListResponse(response: ListMemosResponse, name: string): Memo | undefined {
- return response.memos.find((memo) => memo.name === name);
+function patchMemos(memos: Memo[], update: MemoPatch): Memo[] {
+ let changed = false;
+ const next = memos.map((memo) => {
+ if (memo.name !== update.name) return memo;
+ changed = true;
+ return { ...memo, ...update };
+ });
+ return changed ? next : memos;
}
-function findMemoInQueryData(data: unknown, name: string): Memo | undefined {
- if (!data) {
- return undefined;
+function* memosInQueryData(data: unknown): Generator<Memo> {
+ if (isMemo(data)) {
+ yield data;
+ return;
}
-
- if (isMemoListResponse(data)) {
- return findMemoInListResponse(data, name);
+ const pages = isInfiniteData(data) ? data.pages : [data];
+ for (const page of pages) {
+ const memos = memosOfPage(page);
+ if (memos) yield* memos;
}
+}
- if (isInfiniteMemoListData(data)) {
- for (const page of data.pages) {
- const memo = findMemoInListResponse(page, name);
- if (memo) {
- return memo;
- }
- }
+function findMemoInQueryData(data: unknown, name: string): Memo | undefined {
+ for (const memo of memosInQueryData(data)) {
+ if (memo.name === name) return memo;
}
-
return undefined;
}
+/** The query roots that hold memos: the memo queries, and shared memos under their tokens. */
+const MEMO_QUERY_ROOTS = [memoKeys.all, memoShareKeys.all] as const;
+
+/**
+ * Looks a memo up by name in the collections already fetched (lists, comments,
+ * the calendar month): a seed for a detail query that would otherwise refetch
+ * a memo the page already shows. A detail cached as unavailable (`null`) wins.
+ */
export function findMemoInCollectionQueries(queryClient: QueryClient, name: string, freshOnly = false): Memo | undefined {
if (queryClient.getQueryData(memoKeys.detail(name)) === null) return undefined;
for (const [key, data] of queryClient.getQueriesData<unknown>({ queryKey: memoKeys.all })) {
+ if (isMemo(data)) continue;
const state = queryClient.getQueryState(key);
if (freshOnly && (!state || state.isInvalidated || state.dataUpdatedAt < Date.now() - 10_000)) continue;
const memo = findMemoInQueryData(data, name);
- if (memo) {
- return memo;
- }
+ if (memo) return memo;
}
-
return undefined;
}
+/**
+ * The freshest copy of a memo any query holds, by name: a detail, a shared memo, or
+ * an entry in a list, comment page or month. `null` when a detail query recorded it as
+ * unavailable, `undefined` when no query holds it.
+ */
+export function findMemoRecord(queryClient: QueryClient, name: string): Memo | null | undefined {
+ if (queryClient.getQueryData(memoKeys.detail(name)) === null) return null;
+ let found: Memo | undefined;
+ let foundAt = -1;
+ for (const root of MEMO_QUERY_ROOTS) {
+ for (const query of queryClient.getQueryCache().findAll({ queryKey: root })) {
+ if (query.state.dataUpdatedAt <= foundAt) continue;
+ const memo = findMemoInQueryData(query.state.data, name);
+ if (memo) {
+ found = memo;
+ foundAt = query.state.dataUpdatedAt;
+ }
+ }
+ }
+ return found;
+}
+
function patchMemoInCollectionQueries(queryClient: QueryClient, update: MemoPatch) {
- queryClient.setQueriesData<MemoCollectionQueryData>({ queryKey: memoKeys.all }, (data) => patchMemoListQueryData(data, update));
+ queryClient.setQueriesData<unknown>({ queryKey: memoKeys.all }, (data: unknown) =>
+ isMemo(data) ? data : mapMemoCollection(data, (memos) => patchMemos(memos, update)),
+ );
+}
+
+/**
+ * A memo by name, read from whatever query already holds it, with no request of its
+ * own: a card in a list reads the list's copy and follows the list's refetches and the
+ * mutations' optimistic patches. Returns `null` for a memo recorded as unavailable and
+ * `undefined` for one no query holds.
+ */
+export function useMemoRecord(name: string): Memo | null | undefined {
+ const queryClient = useQueryClient();
+ const subscribe = useCallback(
+ (onChange: () => void) =>
+ queryClient.getQueryCache().subscribe((event) => {
+ const root = event.query.queryKey[0];
+ if (MEMO_QUERY_ROOTS.some((key) => key[0] === root)) onChange();
+ }),
+ [queryClient],
+ );
+ const getSnapshot = useCallback(() => findMemoRecord(queryClient, name), [queryClient, name]);
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+}
+
+/**
+ * A memo by name for a surface that shows it: the copy a query already holds, or else
+ * one fetch of the detail. Unlike `useMemo`, it never refetches on its own, so a list
+ * of cards costs no requests beyond the list's.
+ */
+export function useMemoByName(name: string, options?: { enabled?: boolean }) {
+ const record = useMemoRecord(name);
+ const query = useQuery({
+ ...memoDetailQueryOptions(name),
+ enabled: (options?.enabled ?? true) && record === undefined,
+ });
+ const data = record ?? undefined;
+ return {
+ data,
+ isUnavailable: record === null,
+ isLoading: record === undefined && query.isLoading,
+ error: record === undefined ? query.error : null,
+ };
}
export function useMemos(request: Partial<ListMemosRequest> = {}) {
@@ -229,20 +300,22 @@ export function useLinkMetadata(url: string, options?: { enabled?: boolean }) {
});
}
+/** Creates a memo, or a comment on `parent`; the server fills the comment's parent and relation. */
export function useCreateMemo() {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async (memoToCreate: Memo) => {
- const memo = await memoServiceClient.createMemo({ memo: memoToCreate });
- return memo;
+ mutationFn: async ({ memo, parent }: { memo: Memo; parent?: string }) => {
+ return parent ? await memoServiceClient.createMemoComment({ parent, comment: memo }) : await memoServiceClient.createMemo({ memo });
},
- onSuccess: (newMemo) => {
- // Invalidate memo lists to refetch
- queryClient.invalidateQueries({ queryKey: memoKeys.lists() });
- // Add new memo to cache
+ onSuccess: (newMemo, { parent }) => {
queryClient.setQueryData(memoKeys.detail(newMemo.name), newMemo);
- // Invalidate user stats
+ queryClient.invalidateQueries({ queryKey: memoKeys.lists() });
+ if (parent) {
+ // The parent's comment list and its comment count.
+ queryClient.invalidateQueries({ queryKey: memoKeys.comments(parent) });
+ queryClient.invalidateQueries({ queryKey: memoKeys.detail(parent) });
+ }
queryClient.invalidateQueries({ queryKey: userKeys.stats() });
// Creating a memo can bind previously unlinked attachments.
queryClient.invalidateQueries({ queryKey: attachmentKeys.lists() });
@@ -302,7 +375,9 @@ export function useUpdateMemo() {
// Invalidate lists to refresh
queryClient.invalidateQueries({ queryKey: memoKeys.lists() });
if (updatedMemo.parent) {
+ // The parent's comment list, and the parent itself, which carries the comment relation.
queryClient.invalidateQueries({ queryKey: memoKeys.comments(updatedMemo.parent) });
+ queryClient.invalidateQueries({ queryKey: memoKeys.detail(updatedMemo.parent) });
}
// Invalidate user stats
queryClient.invalidateQueries({ queryKey: userKeys.stats() });
diff --git a/web/src/lib/markdownStyles.ts b/web/src/lib/markdownStyles.ts
index abb835559..b78b2072c 100644
--- a/web/src/lib/markdownStyles.ts
+++ b/web/src/lib/markdownStyles.ts
@@ -33,8 +33,8 @@ export const headingTypeClass = (level: HeadingLevel): string => headingTypeClas
/**
* Tag pill styling for the memo view. Split into two tokens so the view can swap
- * `defaultColor` for a custom tag color (MemoContent/enhance.ts). The composer
- * colors tags as text instead (MemoEditor/Editor/editor.css).
+ * `defaultColor` for a custom tag color (MemoEditor/view/MemoContentView.tsx). The composer
+ * colors tags as text instead (MemoEditor/MemoMarkdown.tsx).
*/
export const tagStyles = {
/** Shape, padding, and typography — always applied. */
diff --git a/web/src/lib/memo-markdown.ts b/web/src/lib/memo-markdown.ts
index 74616e205..826c5473d 100644
--- a/web/src/lib/memo-markdown.ts
+++ b/web/src/lib/memo-markdown.ts
@@ -204,9 +204,9 @@ export const memoMentionOptions = (isResolved: (username: string) => boolean): P
interface MemoExtensionOptions {
/** `tags()` class and attributes, for the memo view's pills and colors. */
- readonly tags?: Pick<TagsOptions, "class" | "attributes">;
+ readonly tags?: Pick<TagsOptions, "class" | "attributes" | "onClick">;
/** `mentions()` class and attributes, for links to the people who exist. */
- readonly mentions?: Pick<TagsOptions, "class" | "attributes">;
+ readonly mentions?: Pick<TagsOptions, "class" | "attributes" | "onClick">;
}
/**
@@ -352,6 +352,9 @@ export const memoEditorLabels = (t: ReturnType<typeof useTranslate>): Partial<La
alignRight: t("editor.blocks.align-right"),
tableSection: t("editor.blocks.table"),
imageSection: t("editor.blocks.image"),
+ imageAlignLeft: t("editor.blocks.image-align-left"),
+ imageAlignCenter: t("editor.blocks.image-align-center"),
+ imageAlignRight: t("editor.blocks.image-align-right"),
resetImageSize: t("editor.blocks.reset-image-size"),
altText: t("editor.blocks.alt-text"),
altTextPlaceholder: t("editor.blocks.alt-text-placeholder"),
diff --git a/web/src/locales/ar.json b/web/src/locales/ar.json
index 7179f3529..496a69c5b 100644
--- a/web/src/locales/ar.json
+++ b/web/src/locales/ar.json
@@ -247,6 +247,9 @@
"align-left": "يسار",
"align-center": "وسط",
"align-right": "يمين",
+ "image-align-left": "محاذاة لليسار",
+ "image-align-center": "محاذاة للوسط",
+ "image-align-right": "محاذاة لليمين",
"text-style": "نمط النص",
"image": "صورة",
"reset-image-size": "إعادة تعيين الحجم",
diff --git a/web/src/locales/az.json b/web/src/locales/az.json
index efdedd565..5333c41d2 100644
--- a/web/src/locales/az.json
+++ b/web/src/locales/az.json
@@ -344,6 +344,9 @@
"align-left": "Sol",
"align-center": "Mərkəz",
"align-right": "Sağ",
+ "image-align-left": "Sola düzləndir",
+ "image-align-center": "Mərkəzə düzləndir",
+ "image-align-right": "Sağa düzləndir",
"text-style": "Mətn üslubu",
"image": "Şəkil",
"reset-image-size": "Ölçünü sıfırla",
diff --git a/web/src/locales/bg.json b/web/src/locales/bg.json
index 9b1a1f046..8cb4f8906 100644
--- a/web/src/locales/bg.json
+++ b/web/src/locales/bg.json
@@ -285,6 +285,9 @@
"align-left": "Вляво",
"align-center": "Центрирано",
"align-right": "Вдясно",
+ "image-align-left": "Подравняване вляво",
+ "image-align-center": "Центриране",
+ "image-align-right": "Подравняване вдясно",
"text-style": "Стил на текста",
"image": "Изображение",
"reset-image-size": "Нулиране на размера",
diff --git a/web/src/locales/ca.json b/web/src/locales/ca.json
index 84c3d7e54..abf898c60 100644
--- a/web/src/locales/ca.json
+++ b/web/src/locales/ca.json
@@ -247,6 +247,9 @@
"align-left": "Esquerra",
"align-center": "Centre",
"align-right": "Dreta",
+ "image-align-left": "Alinea a l'esquerra",
+ "image-align-center": "Centra",
+ "image-align-right": "Alinea a la dreta",
"text-style": "Estil de text",
"image": "Imatge",
"reset-image-size": "Restableix la mida",
diff --git a/web/src/locales/cs.json b/web/src/locales/cs.json
index 135618bc4..76aaaca6c 100644
--- a/web/src/locales/cs.json
+++ b/web/src/locales/cs.json
@@ -247,6 +247,9 @@
"align-left": "Vlevo",
"align-center": "Na střed",
"align-right": "Vpravo",
+ "image-align-left": "Zarovnat vlevo",
+ "image-align-center": "Zarovnat na střed",
+ "image-align-right": "Zarovnat vpravo",
"text-style": "Styl textu",
"image": "Obrázek",
"reset-image-size": "Obnovit velikost",
diff --git a/web/src/locales/da.json b/web/src/locales/da.json
index 0802b7ecb..63fe1e147 100644
--- a/web/src/locales/da.json
+++ b/web/src/locales/da.json
@@ -285,6 +285,9 @@
"align-left": "Venstre",
"align-center": "Centreret",
"align-right": "Højre",
+ "image-align-left": "Venstrejuster",
+ "image-align-center": "Centrer",
+ "image-align-right": "Højrejuster",
"text-style": "Tekststil",
"image": "Billede",
"reset-image-size": "Nulstil størrelse",
diff --git a/web/src/locales/de.json b/web/src/locales/de.json
index 3d8e18ffc..abed613fa 100644
--- a/web/src/locales/de.json
+++ b/web/src/locales/de.json
@@ -247,6 +247,9 @@
"align-left": "Links",
"align-center": "Zentriert",
"align-right": "Rechts",
+ "image-align-left": "Linksbündig",
+ "image-align-center": "Zentrieren",
+ "image-align-right": "Rechtsbündig",
"text-style": "Textstil",
"image": "Bild",
"reset-image-size": "Größe zurücksetzen",
diff --git a/web/src/locales/el.json b/web/src/locales/el.json
index 5d1635b70..7b41286cd 100644
--- a/web/src/locales/el.json
+++ b/web/src/locales/el.json
@@ -285,6 +285,9 @@
"align-left": "Αριστερά",
"align-center": "Κέντρο",
"align-right": "Δεξιά",
+ "image-align-left": "Στοίχιση αριστερά",
+ "image-align-center": "Στοίχιση στο κέντρο",
+ "image-align-right": "Στοίχιση δεξιά",
"text-style": "Στυλ κειμένου",
"image": "Εικόνα",
"reset-image-size": "Επαναφορά μεγέθους",
diff --git a/web/src/locales/en-GB.json b/web/src/locales/en-GB.json
index 61d458362..12f886d5a 100644
--- a/web/src/locales/en-GB.json
+++ b/web/src/locales/en-GB.json
@@ -247,6 +247,9 @@
"align-left": "Left",
"align-center": "Centre",
"align-right": "Right",
+ "image-align-left": "Align left",
+ "image-align-center": "Align centre",
+ "image-align-right": "Align right",
"text-style": "Text style",
"image": "Image",
"reset-image-size": "Reset size",
diff --git a/web/src/locales/en.json b/web/src/locales/en.json
index 1f89b1476..ecf232522 100644
--- a/web/src/locales/en.json
+++ b/web/src/locales/en.json
@@ -344,6 +344,9 @@
"align-left": "Left",
"align-center": "Center",
"align-right": "Right",
+ "image-align-left": "Align left",
+ "image-align-center": "Align center",
+ "image-align-right": "Align right",
"text-style": "Text style",
"image": "Image",
"reset-image-size": "Reset size",
diff --git a/web/src/locales/es.json b/web/src/locales/es.json
index 428e33b05..ccc71b2e1 100644
--- a/web/src/locales/es.json
+++ b/web/src/locales/es.json
@@ -247,6 +247,9 @@
"align-left": "Izquierda",
"align-center": "Centro",
"align-right": "Derecha",
+ "image-align-left": "Alinear a la izquierda",
+ "image-align-center": "Centrar",
+ "image-align-right": "Alinear a la derecha",
"text-style": "Estilo de texto",
"image": "Imagen",
"reset-image-size": "Restablecer tamaño",
diff --git a/web/src/locales/et.json b/web/src/locales/et.json
index a7166f82f..66cb56098 100644
--- a/web/src/locales/et.json
+++ b/web/src/locales/et.json
@@ -285,6 +285,9 @@
"align-left": "Vasak",
"align-center": "Keskel",
"align-right": "Parem",
+ "image-align-left": "Joonda vasakule",
+ "image-align-center": "Joonda keskele",
+ "image-align-right": "Joonda paremale",
"text-style": "Teksti stiil",
"image": "Pilt",
"reset-image-size": "Lähtesta suurus",
diff --git a/web/src/locales/fa.json b/web/src/locales/fa.json
index 8ebcd4769..d13107f88 100644
--- a/web/src/locales/fa.json
+++ b/web/src/locales/fa.json
@@ -247,6 +247,9 @@
"align-left": "چپ",
"align-center": "وسط",
"align-right": "راست",
+ "image-align-left": "تراز چپ",
+ "image-align-center": "تراز وسط",
+ "image-align-right": "تراز راست",
"text-style": "سبک متن",
"image": "تصویر",
"reset-image-size": "بازنشانی اندازه",
diff --git a/web/src/locales/fi.json b/web/src/locales/fi.json
index bae9d132b..b9959c88c 100644
--- a/web/src/locales/fi.json
+++ b/web/src/locales/fi.json
@@ -285,6 +285,9 @@
"align-left": "Vasen",
"align-center": "Keskitetty",
"align-right": "Oikea",
+ "image-align-left": "Tasaa vasemmalle",
+ "image-align-center": "Keskitä",
+ "image-align-right": "Tasaa oikealle",
"text-style": "Tekstityyli",
"image": "Kuva",
"reset-image-size": "Palauta koko",
diff --git a/web/src/locales/fr.json b/web/src/locales/fr.json
index 57f049f15..264c93cd8 100644
--- a/web/src/locales/fr.json
+++ b/web/src/locales/fr.json
@@ -247,6 +247,9 @@
"align-left": "Gauche",
"align-center": "Centre",
"align-right": "Droite",
+ "image-align-left": "Aligner à gauche",
+ "image-align-center": "Centrer",
+ "image-align-right": "Aligner à droite",
"text-style": "Style de texte",
"image": "Image",
"reset-image-size": "Réinitialiser la taille",
diff --git a/web/src/locales/gl.json b/web/src/locales/gl.json
index c2b38ae97..397e7b5b4 100644
--- a/web/src/locales/gl.json
+++ b/web/src/locales/gl.json
@@ -247,6 +247,9 @@
"align-left": "Esquerda",
"align-center": "Centro",
"align-right": "Dereita",
+ "image-align-left": "Aliñar á esquerda",
+ "image-align-center": "Centrar",
+ "image-align-right": "Aliñar á dereita",
"text-style": "Estilo de texto",
"image": "Imaxe",
"reset-image-size": "Restablecer o tamaño",
diff --git a/web/src/locales/he.json b/web/src/locales/he.json
index 2e401d16d..c003bb1dd 100644
--- a/web/src/locales/he.json
+++ b/web/src/locales/he.json
@@ -318,6 +318,9 @@
"align-left": "שמאל",
"align-center": "מרכז",
"align-right": "ימין",
+ "image-align-left": "יישור לשמאל",
+ "image-align-center": "יישור למרכז",
+ "image-align-right": "יישור לימין",
"text-style": "סגנון טקסט",
"image": "תמונה",
"reset-image-size": "איפוס גודל",
diff --git a/web/src/locales/hi.json b/web/src/locales/hi.json
index ea287a095..389bfafd3 100644
--- a/web/src/locales/hi.json
+++ b/web/src/locales/hi.json
@@ -247,6 +247,9 @@
"align-left": "बाएँ",
"align-center": "बीच में",
"align-right": "दाएँ",
+ "image-align-left": "बाएँ संरेखित करें",
+ "image-align-center": "बीच में संरेखित करें",
+ "image-align-right": "दाएँ संरेखित करें",
"text-style": "टेक्स्ट शैली",
"image": "इमेज",
"reset-image-size": "आकार रीसेट करें",
diff --git a/web/src/locales/hr.json b/web/src/locales/hr.json
index 521dbdbd0..75af54ed9 100644
--- a/web/src/locales/hr.json
+++ b/web/src/locales/hr.json
@@ -247,6 +247,9 @@
"align-left": "Lijevo",
"align-center": "Sredina",
"align-right": "Desno",
+ "image-align-left": "Poravnaj lijevo",
+ "image-align-center": "Poravnaj po sredini",
+ "image-align-right": "Poravnaj desno",
"text-style": "Stil teksta",
"image": "Slika",
"reset-image-size": "Vrati veličinu",
diff --git a/web/src/locales/hu.json b/web/src/locales/hu.json
index d8626e2bd..02ac2cb72 100644
--- a/web/src/locales/hu.json
+++ b/web/src/locales/hu.json
@@ -247,6 +247,9 @@
"align-left": "Balra",
"align-center": "Középre",
"align-right": "Jobbra",
+ "image-align-left": "Balra igazítás",
+ "image-align-center": "Középre igazítás",
+ "image-align-right": "Jobbra igazítás",
"text-style": "Szövegstílus",
"image": "Kép",
"reset-image-size": "Méret visszaállítása",
diff --git a/web/src/locales/id.json b/web/src/locales/id.json
index 9c3de00be..fdf07b490 100644
--- a/web/src/locales/id.json
+++ b/web/src/locales/id.json
@@ -247,6 +247,9 @@
"align-left": "Kiri",
"align-center": "Tengah",
"align-right": "Kanan",
+ "image-align-left": "Rata kiri",
+ "image-align-center": "Rata tengah",
+ "image-align-right": "Rata kanan",
"text-style": "Gaya teks",
"image": "Gambar",
"reset-image-size": "Atur ulang ukuran",
diff --git a/web/src/locales/it.json b/web/src/locales/it.json
index a540eab57..e616edc7c 100644
--- a/web/src/locales/it.json
+++ b/web/src/locales/it.json
@@ -247,6 +247,9 @@
"align-left": "Sinistra",
"align-center": "Centro",
"align-right": "Destra",
+ "image-align-left": "Allinea a sinistra",
+ "image-align-center": "Allinea al centro",
+ "image-align-right": "Allinea a destra",
"text-style": "Stile testo",
"image": "Immagine",
"reset-image-size": "Ripristina dimensioni",
diff --git a/web/src/locales/ja.json b/web/src/locales/ja.json
index a88a3d508..df791894a 100644
--- a/web/src/locales/ja.json
+++ b/web/src/locales/ja.json
@@ -247,6 +247,9 @@
"align-left": "左",
"align-center": "中央",
"align-right": "右",
+ "image-align-left": "左揃え",
+ "image-align-center": "中央揃え",
+ "image-align-right": "右揃え",
"text-style": "テキストスタイル",
"image": "画像",
"reset-image-size": "サイズをリセット",
diff --git a/web/src/locales/ka-GE.json b/web/src/locales/ka-GE.json
index c2af1aa4c..de59f6c54 100644
--- a/web/src/locales/ka-GE.json
+++ b/web/src/locales/ka-GE.json
@@ -247,6 +247,9 @@
"align-left": "მარცხნივ",
"align-center": "ცენტრში",
"align-right": "მარჯვნივ",
+ "image-align-left": "მარცხნივ სწორება",
+ "image-align-center": "ცენტრში სწორება",
+ "image-align-right": "მარჯვნივ სწორება",
"text-style": "ტექსტის სტილი",
"image": "სურათი",
"reset-image-size": "ზომის აღდგენა",
diff --git a/web/src/locales/ko.json b/web/src/locales/ko.json
index 0f8d91231..1c9ad3e38 100644
--- a/web/src/locales/ko.json
+++ b/web/src/locales/ko.json
@@ -247,6 +247,9 @@
"align-left": "왼쪽",
"align-center": "가운데",
"align-right": "오른쪽",
+ "image-align-left": "왼쪽 정렬",
+ "image-align-center": "가운데 정렬",
+ "image-align-right": "오른쪽 정렬",
"text-style": "텍스트 스타일",
"image": "이미지",
"reset-image-size": "크기 초기화",
diff --git a/web/src/locales/lt.json b/web/src/locales/lt.json
index 5a3dd1445..02494f630 100644
--- a/web/src/locales/lt.json
+++ b/web/src/locales/lt.json
@@ -285,6 +285,9 @@
"align-left": "Kairėje",
"align-center": "Centre",
"align-right": "Dešinėje",
+ "image-align-left": "Lygiuoti kairėje",
+ "image-align-center": "Lygiuoti centre",
+ "image-align-right": "Lygiuoti dešinėje",
"text-style": "Teksto stilius",
"image": "Paveikslėlis",
"reset-image-size": "Atkurti dydį",
diff --git a/web/src/locales/lv.json b/web/src/locales/lv.json
index f5af2fcaa..8f8067c1c 100644
--- a/web/src/locales/lv.json
+++ b/web/src/locales/lv.json
@@ -285,6 +285,9 @@
"align-left": "Pa kreisi",
"align-center": "Centrā",
"align-right": "Pa labi",
+ "image-align-left": "Līdzināt pa kreisi",
+ "image-align-center": "Līdzināt centrā",
+ "image-align-right": "Līdzināt pa labi",
"text-style": "Teksta stils",
"image": "Attēls",
"reset-image-size": "Atiestatīt izmēru",
diff --git a/web/src/locales/mr.json b/web/src/locales/mr.json
index 61a17bb9f..b4fd2ed2c 100644
--- a/web/src/locales/mr.json
+++ b/web/src/locales/mr.json
@@ -247,6 +247,9 @@
"align-left": "डावीकडे",
"align-center": "मध्यभागी",
"align-right": "उजवीकडे",
+ "image-align-left": "डावीकडे संरेखित करा",
+ "image-align-center": "मध्यभागी संरेखित करा",
+ "image-align-right": "उजवीकडे संरेखित करा",
"text-style": "मजकूर शैली",
"image": "प्रतिमा",
"reset-image-size": "आकार रीसेट करा",
diff --git a/web/src/locales/nb.json b/web/src/locales/nb.json
index b98ebae6e..12eed2467 100644
--- a/web/src/locales/nb.json
+++ b/web/src/locales/nb.json
@@ -247,6 +247,9 @@
"align-left": "Venstre",
"align-center": "Midtstilt",
"align-right": "Høyre",
+ "image-align-left": "Venstrejuster",
+ "image-align-center": "Midtstill",
+ "image-align-right": "Høyrejuster",
"text-style": "Tekststil",
"image": "Bilde",
"reset-image-size": "Tilbakestill størrelse",
diff --git a/web/src/locales/nl.json b/web/src/locales/nl.json
index a13851ec9..b35ea5619 100644
--- a/web/src/locales/nl.json
+++ b/web/src/locales/nl.json
@@ -247,6 +247,9 @@
"align-left": "Links",
"align-center": "Midden",
"align-right": "Rechts",
+ "image-align-left": "Links uitlijnen",
+ "image-align-center": "Centreren",
+ "image-align-right": "Rechts uitlijnen",
"text-style": "Tekststijl",
"image": "Afbeelding",
"reset-image-size": "Grootte herstellen",
diff --git a/web/src/locales/nn.json b/web/src/locales/nn.json
index d1684c166..60556edd8 100644
--- a/web/src/locales/nn.json
+++ b/web/src/locales/nn.json
@@ -323,6 +323,9 @@
"align-left": "Venstre",
"align-center": "Midtstilt",
"align-right": "Høgre",
+ "image-align-left": "Venstrejuster",
+ "image-align-center": "Midtstill",
+ "image-align-right": "Høgrejuster",
"text-style": "Tekststil",
"image": "Bilete",
"reset-image-size": "Tilbakestill storleik",
diff --git a/web/src/locales/pl.json b/web/src/locales/pl.json
index 9ef3af87d..cf90c5c86 100644
--- a/web/src/locales/pl.json
+++ b/web/src/locales/pl.json
@@ -247,6 +247,9 @@
"align-left": "Do lewej",
"align-center": "Do środka",
"align-right": "Do prawej",
+ "image-align-left": "Wyrównaj do lewej",
+ "image-align-center": "Wyrównaj do środka",
+ "image-align-right": "Wyrównaj do prawej",
"text-style": "Styl tekstu",
"image": "Obraz",
"reset-image-size": "Przywróć rozmiar",
diff --git a/web/src/locales/pt-BR.json b/web/src/locales/pt-BR.json
index 051dac775..1c07b2be8 100644
--- a/web/src/locales/pt-BR.json
+++ b/web/src/locales/pt-BR.json
@@ -247,6 +247,9 @@
"align-left": "Esquerda",
"align-center": "Centro",
"align-right": "Direita",
+ "image-align-left": "Alinhar à esquerda",
+ "image-align-center": "Centralizar",
+ "image-align-right": "Alinhar à direita",
"text-style": "Estilo de texto",
"image": "Imagem",
"reset-image-size": "Redefinir tamanho",
diff --git a/web/src/locales/pt-PT.json b/web/src/locales/pt-PT.json
index 98f5364df..a7af01d1d 100644
--- a/web/src/locales/pt-PT.json
+++ b/web/src/locales/pt-PT.json
@@ -247,6 +247,9 @@
"align-left": "Esquerda",
"align-center": "Centro",
"align-right": "Direita",
+ "image-align-left": "Alinhar à esquerda",
+ "image-align-center": "Centrar",
+ "image-align-right": "Alinhar à direita",
"text-style": "Estilo de texto",
"image": "Imagem",
"reset-image-size": "Repor tamanho",
diff --git a/web/src/locales/ro.json b/web/src/locales/ro.json
index e4939ef68..83e2fae68 100644
--- a/web/src/locales/ro.json
+++ b/web/src/locales/ro.json
@@ -285,6 +285,9 @@
"align-left": "Stânga",
"align-center": "Centru",
"align-right": "Dreapta",
+ "image-align-left": "Aliniere la stânga",
+ "image-align-center": "Aliniere la centru",
+ "image-align-right": "Aliniere la dreapta",
"text-style": "Stil text",
"image": "Imagine",
"reset-image-size": "Resetează dimensiunea",
diff --git a/web/src/locales/ru.json b/web/src/locales/ru.json
index 48b43b5b0..83756c694 100644
--- a/web/src/locales/ru.json
+++ b/web/src/locales/ru.json
@@ -247,6 +247,9 @@
"align-left": "По левому краю",
"align-center": "По центру",
"align-right": "По правому краю",
+ "image-align-left": "Выровнять по левому краю",
+ "image-align-center": "Выровнять по центру",
+ "image-align-right": "Выровнять по правому краю",
"text-style": "Стиль текста",
"image": "Изображение",
"reset-image-size": "Сбросить размер",
diff --git a/web/src/locales/sk.json b/web/src/locales/sk.json
index a4f758c65..02f86e37b 100644
--- a/web/src/locales/sk.json
+++ b/web/src/locales/sk.json
@@ -285,6 +285,9 @@
"align-left": "Vľavo",
"align-center": "Na stred",
"align-right": "Vpravo",
+ "image-align-left": "Zarovnať vľavo",
+ "image-align-center": "Zarovnať na stred",
+ "image-align-right": "Zarovnať vpravo",
"text-style": "Štýl textu",
"image": "Obrázok",
"reset-image-size": "Obnoviť veľkosť",
diff --git a/web/src/locales/sl.json b/web/src/locales/sl.json
index f0022b39b..5cfa0babd 100644
--- a/web/src/locales/sl.json
+++ b/web/src/locales/sl.json
@@ -247,6 +247,9 @@
"align-left": "Levo",
"align-center": "Sredina",
"align-right": "Desno",
+ "image-align-left": "Poravnaj levo",
+ "image-align-center": "Poravnaj na sredino",
+ "image-align-right": "Poravnaj desno",
"text-style": "Slog besedila",
"image": "Slika",
"reset-image-size": "Ponastavi velikost",
diff --git a/web/src/locales/sr.json b/web/src/locales/sr.json
index 24ca24b9a..47dd0538e 100644
--- a/web/src/locales/sr.json
+++ b/web/src/locales/sr.json
@@ -285,6 +285,9 @@
"align-left": "Лево",
"align-center": "Средина",
"align-right": "Десно",
+ "image-align-left": "Поравнај лево",
+ "image-align-center": "Поравнај по средини",
+ "image-align-right": "Поравнај десно",
"text-style": "Стил текста",
"image": "Слика",
"reset-image-size": "Врати величину",
diff --git a/web/src/locales/sv.json b/web/src/locales/sv.json
index ed0b813cf..cd572ddb4 100644
--- a/web/src/locales/sv.json
+++ b/web/src/locales/sv.json
@@ -247,6 +247,9 @@
"align-left": "Vänster",
"align-center": "Centrerat",
"align-right": "Höger",
+ "image-align-left": "Vänsterjustera",
+ "image-align-center": "Centrera",
+ "image-align-right": "Högerjustera",
"text-style": "Textstil",
"image": "Bild",
"reset-image-size": "Återställ storlek",
diff --git a/web/src/locales/th.json b/web/src/locales/th.json
index 8ff2746e1..e23198845 100644
--- a/web/src/locales/th.json
+++ b/web/src/locales/th.json
@@ -247,6 +247,9 @@
"align-left": "ซ้าย",
"align-center": "กึ่งกลาง",
"align-right": "ขวา",
+ "image-align-left": "จัดชิดซ้าย",
+ "image-align-center": "จัดกึ่งกลาง",
+ "image-align-right": "จัดชิดขวา",
"text-style": "รูปแบบข้อความ",
"image": "รูปภาพ",
"reset-image-size": "รีเซ็ตขนาด",
diff --git a/web/src/locales/tr.json b/web/src/locales/tr.json
index f7e34ad4e..9d3b6f5b9 100644
--- a/web/src/locales/tr.json
+++ b/web/src/locales/tr.json
@@ -273,6 +273,9 @@
"align-left": "Sol",
"align-center": "Orta",
"align-right": "Sağ",
+ "image-align-left": "Sola hizala",
+ "image-align-center": "Ortala",
+ "image-align-right": "Sağa hizala",
"text-style": "Metin stili",
"image": "Görsel",
"reset-image-size": "Boyutu sıfırla",
diff --git a/web/src/locales/uk.json b/web/src/locales/uk.json
index dd969b968..6f6441636 100644
--- a/web/src/locales/uk.json
+++ b/web/src/locales/uk.json
@@ -247,6 +247,9 @@
"align-left": "Ліворуч",
"align-center": "По центру",
"align-right": "Праворуч",
+ "image-align-left": "Вирівняти ліворуч",
+ "image-align-center": "Вирівняти по центру",
+ "image-align-right": "Вирівняти праворуч",
"text-style": "Стиль тексту",
"image": "Зображення",
"reset-image-size": "Скинути розмір",
diff --git a/web/src/locales/vi.json b/web/src/locales/vi.json
index 7025e39ee..b57cbf587 100644
--- a/web/src/locales/vi.json
+++ b/web/src/locales/vi.json
@@ -247,6 +247,9 @@
"align-left": "Trái",
"align-center": "Giữa",
"align-right": "Phải",
+ "image-align-left": "Căn trái",
+ "image-align-center": "Căn giữa",
+ "image-align-right": "Căn phải",
"text-style": "Kiểu văn bản",
"image": "Hình ảnh",
"reset-image-size": "Đặt lại kích thước",
diff --git a/web/src/locales/zh-Hans.json b/web/src/locales/zh-Hans.json
index 20563f071..d92fbe461 100644
--- a/web/src/locales/zh-Hans.json
+++ b/web/src/locales/zh-Hans.json
@@ -278,6 +278,9 @@
"align-left": "靠左",
"align-center": "居中",
"align-right": "靠右",
+ "image-align-left": "左对齐",
+ "image-align-center": "居中对齐",
+ "image-align-right": "右对齐",
"text-style": "文本样式",
"image": "图片",
"reset-image-size": "重置尺寸",
diff --git a/web/src/locales/zh-Hant.json b/web/src/locales/zh-Hant.json
index c84a6243b..8e9d63834 100644
--- a/web/src/locales/zh-Hant.json
+++ b/web/src/locales/zh-Hant.json
@@ -326,6 +326,9 @@
"align-left": "靠左",
"align-center": "置中",
"align-right": "靠右",
+ "image-align-left": "靠左對齊",
+ "image-align-center": "置中對齊",
+ "image-align-right": "靠右對齊",
"text-style": "文字樣式",
"image": "圖片",
"reset-image-size": "重設尺寸",
diff --git a/web/src/pages/Home.tsx b/web/src/pages/Home.tsx
index ecb15b497..5294c9d11 100644
--- a/web/src/pages/Home.tsx
+++ b/web/src/pages/Home.tsx
@@ -1,6 +1,6 @@
import { useMemo } from "react";
-import MemoEditor from "@/components/MemoEditor";
-import { deriveDefaultCreateTimeFromFilters } from "@/components/MemoEditor/utils/deriveDefaultCreateTime";
+import { MemoEditor } from "@/components/MemoEditor";
+import { deriveDefaultCreateTimeFromFilters } from "@/components/MemoEditor/edit/utils/deriveDefaultCreateTime";
import MemoView from "@/components/MemoView";
import PagedMemoList, { getMemoKey } from "@/components/PagedMemoList";
import { useAuth } from "@/contexts/AuthContext";
@@ -11,7 +11,6 @@ import { useSpaceContext } from "@/contexts/SpaceContext";
import { useMemoFilters, useMemoSorting } from "@/hooks";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useMemoSuggestions } from "@/hooks/useMemoSuggestions";
-import { spaceScopedCacheKey } from "@/lib/resource-names";
import { State } from "@/types/proto/api/common_pb";
import { Memo } from "@/types/proto/api/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
@@ -25,9 +24,6 @@ const Home = () => {
const { filters } = useMemoFilterContext();
const { memoFilter: contextFilter, selectedSpaceName, creatorUsername } = useSpaceContext();
const defaultCreateTime = useMemo(() => deriveDefaultCreateTimeFromFilters(filters), [filters]);
- // Doubles as the remount key: the draft cache only reloads on mount, so the editor
- // has to be rebuilt for the new Space rather than just re-pointed at another cache.
- const editorCacheKey = spaceScopedCacheKey("home-memo-editor", selectedSpaceName);
const memoFilter = useMemoFilters({
includeMemoViews: true,
@@ -67,13 +63,11 @@ const Home = () => {
return (
<MemoEditor
- key={editorCacheKey}
+ // Each Space keeps its own Home draft; the editor restarts when the Space changes.
+ draft={{ scope: "home", space: selectedSpaceName, createTime: defaultCreateTime }}
autoFocus={claimHomeAutoFocus}
className={useGrid ? undefined : "mb-2"}
- cacheKey={editorCacheKey}
placeholder={t("editor.any-thoughts")}
- defaultCreateTime={defaultCreateTime}
- defaultSpace={selectedSpaceName}
suggestions={suggestions}
/>
);
diff --git a/web/src/pages/MemoDetail.tsx b/web/src/pages/MemoDetail.tsx
index 8b9b1f66c..81ba600af 100644
--- a/web/src/pages/MemoDetail.tsx
+++ b/web/src/pages/MemoDetail.tsx
@@ -3,7 +3,6 @@ import { ArrowUpLeftFromCircleIcon } from "lucide-react";
import { useCallback, useEffect, useMemo as useReactMemo, useRef, useState } from "react";
import { Link, Navigate, useLocation, useParams } from "react-router-dom";
import MemoCommentSection, { type MemoCommentSectionHandle } from "@/components/MemoCommentSection";
-import { MentionResolutionProvider } from "@/components/MemoContent/MentionResolutionContext";
import MemoParentPlaceholder, { type MemoParentStatus } from "@/components/MemoParentPlaceholder";
import MemoView, { type MemoViewHandle } from "@/components/MemoView";
import { computeCommentAmount } from "@/components/MemoView/MemoViewContext";
@@ -11,6 +10,7 @@ import { createMemoNavigationState, resolveMemoDetailOrigin } from "@/components
import { useAppSidebar } from "@/contexts/AppSidebarContext";
import { useAuth } from "@/contexts/AuthContext";
import { useInstance } from "@/contexts/InstanceContext";
+import { MentionResolutionProvider } from "@/contexts/MentionResolutionContext";
import useMemoDetailError from "@/hooks/useMemoDetailError";
import { useInfiniteMemoComments, useMemo } from "@/hooks/useMemoQueries";
import { useSharedMemo, withShareAttachmentLinks } from "@/hooks/useMemoShareQueries";
diff --git a/web/tests/audience-menu.test.tsx b/web/tests/audience-menu.test.tsx
index b4a1ae177..388a0ebdc 100644
--- a/web/tests/audience-menu.test.tsx
+++ b/web/tests/audience-menu.test.tsx
@@ -1,8 +1,8 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
-import { createInitialState, EditorProvider, useEditorContext, useEditorSelector } from "@/components/MemoEditor/state";
-import AudienceMenu from "@/components/MemoEditor/Toolbar/AudienceMenu";
-import { EditorToolbar } from "@/components/MemoEditor/Toolbar/EditorToolbar";
+import { createInitialState, EditorProvider, useEditorContext, useEditorSelector } from "@/components/MemoEditor/edit/state";
+import AudienceMenu from "@/components/MemoEditor/edit/Toolbar/AudienceMenu";
+import { EditorToolbar } from "@/components/MemoEditor/edit/Toolbar/EditorToolbar";
import { Visibility } from "@/types/proto/api/memo_service_pb";
const spacesQuery = vi.hoisted(() => ({
@@ -14,7 +14,7 @@ const spacesQuery = vi.hoisted(() => ({
isError: false,
refetch: vi.fn(),
}));
-vi.mock("@/components/MemoEditor/Toolbar/InsertMenu", () => ({ default: () => null }));
+vi.mock("@/components/MemoEditor/edit/Toolbar/InsertMenu", () => ({ default: () => null }));
vi.mock("@/hooks/useCurrentUser", () => ({ default: () => ({ name: "users/test" }) }));
vi.mock("@/hooks/useSpaceQueries", () => ({ useSpaces: () => spacesQuery }));
diff --git a/web/tests/calendar-day-snapshot.test.tsx b/web/tests/calendar-day-snapshot.test.tsx
index 9c630c810..b55f83731 100644
--- a/web/tests/calendar-day-snapshot.test.tsx
+++ b/web/tests/calendar-day-snapshot.test.tsx
@@ -11,7 +11,7 @@ const users: Record<string, { name: string; username: string; displayName: strin
"users/carol": { name: "users/carol", username: "carol", displayName: "Carol Diaz", avatarUrl: "/carol.png" },
"users/dan": { name: "users/dan", username: "dan", displayName: "Dan Okafor", avatarUrl: "/dan.png" },
};
-vi.mock("@/components/MemoContent/MentionResolutionContext", () => ({
+vi.mock("@/contexts/MentionResolutionContext", () => ({
useResolvedUser: (name: string, options?: { enabled?: boolean }) => (options?.enabled ? users[name] : undefined),
useResolvedUsersByNames: (names: string[]) => new Map(names.map((name) => [name, users[name]])),
}));
diff --git a/web/tests/derive-default-create-time.test.ts b/web/tests/derive-default-create-time.test.ts
index 19437d62e..afc88b8bf 100644
--- a/web/tests/derive-default-create-time.test.ts
+++ b/web/tests/derive-default-create-time.test.ts
@@ -4,7 +4,7 @@ import {
deriveDefaultCreateTimeFromFilters,
restampDefaultCreateTime,
withTimeOfDay,
-} from "@/components/MemoEditor/utils/deriveDefaultCreateTime";
+} from "@/components/MemoEditor/edit/utils/deriveDefaultCreateTime";
import type { MemoFilter } from "@/contexts/MemoFilterContext";
describe("deriveDefaultCreateTimeFromFilters", () => {
diff --git a/web/tests/draft-key.test.ts b/web/tests/draft-key.test.ts
new file mode 100644
index 000000000..feef85a59
--- /dev/null
+++ b/web/tests/draft-key.test.ts
@@ -0,0 +1,57 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { draftKeyFor, legacyDraftKeyFor, migrateLegacyDraft } from "@/components/MemoEditor/edit/draftKey";
+import { cacheService } from "@/components/MemoEditor/edit/services/cacheService";
+
+describe("draft keys", () => {
+ it("follow what is edited", () => {
+ expect(draftKeyFor({ kind: "edit", name: "memos/a" })).toBe("edit:memos/a");
+ expect(draftKeyFor({ kind: "comment", parent: "memos/a" })).toBe("comment:memos/a");
+ expect(draftKeyFor({ kind: "new", scope: "home" })).toBe("new:home");
+ expect(draftKeyFor({ kind: "new", scope: "home", space: "spaces/work" })).toBe("new:home:spaces/work");
+ expect(draftKeyFor({ kind: "new", scope: "calendar:2026-10-18" })).toBe("new:calendar:2026-10-18");
+ });
+
+ it("name the key each host chose before, where one existed", () => {
+ expect(legacyDraftKeyFor({ kind: "comment", parent: "memos/a" })).toBe("memos/a-comment");
+ expect(legacyDraftKeyFor({ kind: "new", scope: "home" })).toBe("home-memo-editor");
+ expect(legacyDraftKeyFor({ kind: "new", scope: "global", space: "spaces/x" })).toBe("global-memo-editor:spaces/x");
+ expect(legacyDraftKeyFor({ kind: "new", scope: "calendar:2026-10-18" })).toBe("calendar-day-editor:2026-10-18");
+ expect(legacyDraftKeyFor({ kind: "new", scope: "map:users/1:all:35,135" })).toBe("map-editor:users/1:all:35,135");
+ expect(legacyDraftKeyFor({ kind: "new", scope: "elsewhere" })).toBeUndefined();
+ expect(legacyDraftKeyFor({ kind: "edit", name: "memos/a" })).toBeUndefined();
+ });
+});
+
+describe("migrateLegacyDraft", () => {
+ 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)),
+ });
+ });
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("moves a draft from the old key to the new one, once", () => {
+ const identity = { kind: "new", scope: "home", space: "spaces/work" } as const;
+ const oldKey = cacheService.key("users/1", "home-memo-editor:spaces/work");
+ const newKey = cacheService.key("users/1", draftKeyFor(identity));
+ cacheService.saveNow(oldKey, { content: "Unfinished", attachments: [] });
+
+ migrateLegacyDraft("users/1", identity);
+
+ expect(cacheService.loadDraft(newKey).content).toBe("Unfinished");
+ expect(localStorage.getItem(oldKey)).toBeNull();
+ });
+
+ it("keeps a draft already under the new key", () => {
+ const identity = { kind: "comment", parent: "memos/a" } as const;
+ cacheService.saveNow(cacheService.key("users/1", "memos/a-comment"), { content: "old", attachments: [] });
+ cacheService.saveNow(cacheService.key("users/1", draftKeyFor(identity)), { content: "new", attachments: [] });
+
+ migrateLegacyDraft("users/1", identity);
+
+ expect(cacheService.loadDraft(cacheService.key("users/1", draftKeyFor(identity))).content).toBe("new");
+ });
+});
diff --git a/web/tests/editor-commit-button.test.tsx b/web/tests/editor-commit-button.test.tsx
index 6745d6611..23d6f9923 100644
--- a/web/tests/editor-commit-button.test.tsx
+++ b/web/tests/editor-commit-button.test.tsx
@@ -1,10 +1,10 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
-import { createInitialState, EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
-import { EditorToolbar } from "@/components/MemoEditor/Toolbar/EditorToolbar";
+import { createInitialState, EditorProvider, useEditorContext } from "@/components/MemoEditor/edit/state";
+import { EditorToolbar } from "@/components/MemoEditor/edit/Toolbar/EditorToolbar";
-vi.mock("@/components/MemoEditor/Toolbar/InsertMenu", () => ({ default: () => null }));
-vi.mock("@/components/MemoEditor/Toolbar/AudienceMenu", () => ({ default: () => null }));
+vi.mock("@/components/MemoEditor/edit/Toolbar/InsertMenu", () => ({ default: () => null }));
+vi.mock("@/components/MemoEditor/edit/Toolbar/AudienceMenu", () => ({ default: () => null }));
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
let dispatchSaving: ((saving: boolean) => void) | undefined;
diff --git a/web/tests/editor-controller.test.tsx b/web/tests/editor-controller.test.tsx
index 98c7715fd..b4557fa02 100644
--- a/web/tests/editor-controller.test.tsx
+++ b/web/tests/editor-controller.test.tsx
@@ -2,14 +2,16 @@ import { render } from "@testing-library/react";
import type { EditorMode } from "@usememos/editor";
import { createRef } from "react";
import { describe, expect, it, vi } from "vitest";
-import Editor from "@/components/MemoEditor/Editor";
-import type { UploadAnchorDescriptor } from "@/components/MemoEditor/Editor/uploadAnchors";
-import type { EditorController } from "@/components/MemoEditor/types/editorController";
+import Editor from "@/components/MemoEditor/edit/Editor";
+import type { EditorController } from "@/components/MemoEditor/edit/types/editorController";
+import type { UploadAnchorDescriptor } from "@/components/MemoEditor/edit/uploadAnchors";
vi.mock("@/hooks/useUserQueries", () => ({
useTagCounts: () => ({ data: {} }),
useUsersByUsernames: () => ({ data: undefined }),
+ userDetailQueryOptions: () => ({}),
}));
+vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ userTagsSetting: undefined }) }));
function setup(value = "", mode: EditorMode = "rich") {
const ref = createRef<EditorController>();
diff --git a/web/tests/editor-inline-image-validation.test.ts b/web/tests/editor-inline-image-validation.test.ts
index 1c6d5d2c9..29b7e4b1d 100644
--- a/web/tests/editor-inline-image-validation.test.ts
+++ b/web/tests/editor-inline-image-validation.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "vitest";
-import { validationService } from "@/components/MemoEditor/services/validationService";
-import { createInitialState } from "@/components/MemoEditor/state";
+import { validationService } from "@/components/MemoEditor/edit/services/validationService";
+import { createInitialState } from "@/components/MemoEditor/edit/state";
describe("inline image editor validation", () => {
test("blocks saving while an inline image insertion is unresolved", () => {
diff --git a/web/tests/editor-suggestions.test.tsx b/web/tests/editor-suggestions.test.tsx
index e38dc3d1b..43751476c 100644
--- a/web/tests/editor-suggestions.test.tsx
+++ b/web/tests/editor-suggestions.test.tsx
@@ -1,15 +1,16 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { useRef } from "react";
import { describe, expect, it, vi } from "vitest";
-import { EditorContent } from "@/components/MemoEditor/components/EditorContent";
-import { EditorSuggestions, SuggestionsBar } from "@/components/MemoEditor/components/EditorSuggestions";
-import { createInitialState, EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
-import type { EditorController } from "@/components/MemoEditor/types/editorController";
+import { EditorContent } from "@/components/MemoEditor/edit/components/EditorContent";
+import { EditorSuggestions, SuggestionsBar } from "@/components/MemoEditor/edit/components/EditorSuggestions";
+import { createInitialState, EditorProvider, useEditorContext } from "@/components/MemoEditor/edit/state";
+import type { EditorController } from "@/components/MemoEditor/edit/types/editorController";
import { getMemoSuggestions, type MemoSuggestion } from "@/lib/memo-suggestions";
import { Visibility } from "@/types/proto/api/memo_service_pb";
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
vi.mock("@/hooks/useUserQueries", () => ({ useTagCounts: () => ({ data: {} }), useUsersByUsernames: () => ({ data: undefined }) }));
+vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ userTagsSetting: undefined }) }));
/** A caret at `offset` in block `block`. */
const caret = (block: number, offset: number) => ({ anchor: { block, offset }, focus: { block, offset } });
diff --git a/web/tests/editor-tag-autocomplete.test.ts b/web/tests/editor-tag-autocomplete.test.ts
index f6405a517..8c251200f 100644
--- a/web/tests/editor-tag-autocomplete.test.ts
+++ b/web/tests/editor-tag-autocomplete.test.ts
@@ -1,6 +1,6 @@
import { matchToken, type SuggestionAllowContext, scanTags } from "@usememos/editor";
import { describe, expect, it } from "vitest";
-import { allowTagSuggestion, rankTags } from "@/components/MemoEditor/Editor/extensions";
+import { allowTagSuggestion, rankTags } from "@/components/MemoEditor/edit/extensions";
const match = matchToken(scanTags);
diff --git a/web/tests/editor.test.tsx b/web/tests/editor.test.tsx
index 7e9fad15d..c1a2ffc11 100644
--- a/web/tests/editor.test.tsx
+++ b/web/tests/editor.test.tsx
@@ -2,14 +2,15 @@ import { create } from "@bufbuild/protobuf";
import { render, waitFor } from "@testing-library/react";
import { createRef } from "react";
import { describe, expect, it, vi } from "vitest";
-import Editor from "@/components/MemoEditor/Editor";
-import type { EditorController } from "@/components/MemoEditor/types/editorController";
+import Editor from "@/components/MemoEditor/edit/Editor";
+import type { EditorController } from "@/components/MemoEditor/edit/types/editorController";
import { UserSetting_TagsSettingSchema } from "@/types/proto/api/user_service_pb";
import { ColorSchema } from "@/types/proto/google/type/color_pb";
const queries = vi.hoisted(() => ({
useTagCounts: vi.fn(() => ({ data: {} })),
users: new Map<string, unknown>(),
+ tagsSetting: undefined as unknown,
}));
vi.mock("@/hooks/useUserQueries", () => ({
@@ -17,7 +18,9 @@ vi.mock("@/hooks/useUserQueries", () => ({
useUsersByUsernames: (usernames: string[]) => ({
data: usernames.length ? new Map(usernames.map((username) => [username, queries.users.get(username)])) : undefined,
}),
+ userDetailQueryOptions: () => ({}),
}));
+vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ userTagsSetting: queries.tagsSetting }) }));
const baseProps = {
className: "x",
@@ -89,18 +92,20 @@ describe("Editor", () => {
expect(root?.style.getPropertyValue("--mbe-placeholder")).toBe('"有什么想法?"');
});
- it("draws tags as the memo view does, in their custom colors", async () => {
- const tagsSetting = create(UserSetting_TagsSettingSchema, {
- tags: { work: { backgroundColor: create(ColorSchema, { red: 1, green: 0, blue: 0 }) } },
- });
+ it("draws tags as the memo view does, in the viewer's custom colors", async () => {
+ queries.tagsSetting = undefined;
const { container, rerender } = render(<Editor {...baseProps} value="#work and #life" />);
const tag = (name: string) => container.querySelector<HTMLElement>(`.mbe-tag[data-tag="${name}"]`);
expect(tag("life")).toHaveClass("rounded-full", "border-primary");
expect(tag("work")).not.toHaveAttribute("style");
- rerender(<Editor {...baseProps} value="#work and #life" tagsSetting={tagsSetting} />);
+ queries.tagsSetting = create(UserSetting_TagsSettingSchema, {
+ tags: { work: { backgroundColor: create(ColorSchema, { red: 1, green: 0, blue: 0 }) } },
+ });
+ rerender(<Editor {...baseProps} value="#work and #life" />);
await waitFor(() => expect(tag("work")?.getAttribute("style")).toContain("color-mix"));
expect(tag("work")).not.toHaveClass("border-primary");
+ queries.tagsSetting = undefined;
});
it("draws mentions of people who exist as the memo view does", async () => {
diff --git a/web/tests/focus-mode-exit-button.test.tsx b/web/tests/focus-mode-exit-button.test.tsx
index 2df835612..d467020e3 100644
--- a/web/tests/focus-mode-exit-button.test.tsx
+++ b/web/tests/focus-mode-exit-button.test.tsx
@@ -1,6 +1,6 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
-import { FocusModeExitButton } from "@/components/MemoEditor/components/FocusModeOverlay";
+import { FocusModeExitButton } from "@/components/MemoEditor/edit/components/FocusModeOverlay";
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
diff --git a/web/tests/global-memo-editor.test.tsx b/web/tests/global-memo-editor.test.tsx
index e764903f2..e5d1b261d 100644
--- a/web/tests/global-memo-editor.test.tsx
+++ b/web/tests/global-memo-editor.test.tsx
@@ -1,7 +1,7 @@
-import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { useState } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import type { MemoEditorProps } from "@/components/MemoEditor/types";
+import type { MemoEditorDraftProps } from "@/components/MemoEditor";
import { GlobalMemoEditorProvider, useGlobalMemoEditor } from "@/contexts/GlobalMemoEditorContext";
const DIALOG = { name: "editor.new-memo" };
@@ -13,8 +13,9 @@ vi.mock("@/hooks/useMemoSuggestions", () => ({
const mocks = vi.hoisted(() => ({
currentUser: { name: "users/test" } as { name: string } | undefined,
isUserSettingsInitialized: true,
- editorProps: undefined as MemoEditorProps | undefined,
- loadMemoEditor: vi.fn(),
+ editorProps: undefined as MemoEditorDraftProps | undefined,
+ preload: vi.fn(),
+ renderEditor: ((_props: MemoEditorDraftProps) => null) as (props: MemoEditorDraftProps) => React.ReactNode,
setMobileOpen: vi.fn(),
setQuickFindOpen: vi.fn(),
selectedSpaceName: undefined as string | undefined,
@@ -28,8 +29,10 @@ vi.mock("react-router-dom", async (importOriginal) => ({
useLocation: () => ({ pathname: mocks.pathname }),
}));
-vi.mock("@/components/MemoEditor/loader", () => ({
- loadMemoEditor: mocks.loadMemoEditor,
+vi.mock("@/components/MemoEditor", () => ({
+ preloadMemoEditing: mocks.preload,
+ // Looked up at render time, after the mock component below exists.
+ MemoEditor: (props: MemoEditorDraftProps) => mocks.renderEditor(props),
}));
vi.mock("@/contexts/AppSidebarContext", () => ({
@@ -56,7 +59,7 @@ vi.mock("@/utils/i18n", () => ({
useTranslate: () => (key: string) => key,
}));
-const MockMemoEditor = (props: MemoEditorProps) => {
+const MockMemoEditor = (props: MemoEditorDraftProps) => {
mocks.editorProps = props;
return (
<div data-testid="global-editor">
@@ -122,6 +125,8 @@ const openViaTrigger = async () => {
return trigger;
};
+mocks.renderEditor = (props) => <MockMemoEditor {...props} />;
+
const expectClosed = () => waitFor(() => expect(screen.queryByRole("dialog", DIALOG)).not.toBeInTheDocument());
describe("GlobalMemoEditorProvider", () => {
@@ -129,7 +134,6 @@ describe("GlobalMemoEditorProvider", () => {
mocks.currentUser = { name: "users/test" };
mocks.isUserSettingsInitialized = true;
mocks.editorProps = undefined;
- mocks.loadMemoEditor.mockResolvedValue({ default: MockMemoEditor });
mocks.setMobileOpen.mockClear();
mocks.setQuickFindOpen.mockClear();
mocks.selectedSpaceName = undefined;
@@ -200,7 +204,7 @@ describe("GlobalMemoEditorProvider", () => {
// exits by dismissing this dialog rather than collapsing inline.
expect(mocks.editorProps).toMatchObject({
autoFocus: true,
- cacheKey: "global-memo-editor",
+ draft: { scope: "global", space: undefined },
suggestions: [{ id: "tag:work" }],
onFocusModeExit: expect.any(Function),
});
@@ -265,42 +269,10 @@ describe("GlobalMemoEditorProvider", () => {
fireEvent.click(screen.getByRole("button", { name: "Open editor" }));
- expect(mocks.loadMemoEditor).not.toHaveBeenCalled();
+ expect(mocks.preload).not.toHaveBeenCalled();
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
- it("invalidates a pending open request across sign-out and same-user sign-in", async () => {
- let resolveEditorLoad!: (module: { default: typeof MockMemoEditor }) => void;
- mocks.loadMemoEditor.mockReturnValue(
- new Promise((resolve) => {
- resolveEditorLoad = resolve;
- }),
- );
- const view = renderProvider();
-
- fireEvent.click(screen.getByRole("button", { name: "Open editor" }));
- expect(mocks.loadMemoEditor).toHaveBeenCalledOnce();
-
- mocks.currentUser = undefined;
- view.rerender(
- <GlobalMemoEditorProvider>
- <Trigger />
- </GlobalMemoEditorProvider>,
- );
- mocks.currentUser = { name: "users/test" };
- view.rerender(
- <GlobalMemoEditorProvider>
- <Trigger />
- </GlobalMemoEditorProvider>,
- );
-
- await act(async () => {
- resolveEditorLoad({ default: MockMemoEditor });
- });
-
- expect(screen.queryByRole("dialog", DIALOG)).not.toBeInTheDocument();
- });
-
it("does not resurrect an open composer after the same user signs out and back in", async () => {
const view = renderProvider();
fireEvent.click(screen.getByRole("button", { name: "Open editor" }));
@@ -329,7 +301,7 @@ describe("GlobalMemoEditorProvider", () => {
fireEvent.keyDown(window, { key: "m", shiftKey: true, metaKey: true });
- expect(mocks.loadMemoEditor).not.toHaveBeenCalled();
+ expect(mocks.preload).not.toHaveBeenCalled();
});
it("disables new memo while the route Space is unresolved or inaccessible", () => {
@@ -338,7 +310,7 @@ describe("GlobalMemoEditorProvider", () => {
mocks.isSpaceReady = false;
renderProvider(<Trigger />);
fireEvent.click(screen.getByRole("button", { name: "Open editor" }));
- expect(mocks.loadMemoEditor).not.toHaveBeenCalled();
+ expect(mocks.preload).not.toHaveBeenCalled();
});
it("snapshots the selected Space when opening the composer", async () => {
@@ -346,14 +318,12 @@ describe("GlobalMemoEditorProvider", () => {
await openViaTrigger();
expect(mocks.editorProps).toMatchObject({
- cacheKey: "global-memo-editor:spaces/product",
- defaultSpace: "spaces/product",
+ draft: { scope: "global", space: "spaces/product" },
});
mocks.selectedSpaceName = "spaces/other";
expect(mocks.editorProps).toMatchObject({
- cacheKey: "global-memo-editor:spaces/product",
- defaultSpace: "spaces/product",
+ draft: { scope: "global", space: "spaces/product" },
});
});
@@ -367,8 +337,7 @@ describe("GlobalMemoEditorProvider", () => {
await openViaTrigger();
expect(mocks.editorProps).toMatchObject({
- cacheKey: "global-memo-editor:spaces/product",
- defaultSpace: "spaces/product",
+ draft: { scope: "global", space: "spaces/product" },
});
});
@@ -390,8 +359,7 @@ describe("GlobalMemoEditorProvider", () => {
await openViaTrigger();
expect(mocks.editorProps).toMatchObject({
- cacheKey: "global-memo-editor",
- defaultSpace: undefined,
+ draft: { scope: "global", space: undefined },
});
});
});
diff --git a/web/tests/helpers/memo-save-operations.ts b/web/tests/helpers/memo-save-operations.ts
new file mode 100644
index 000000000..4bef8621c
--- /dev/null
+++ b/web/tests/helpers/memo-save-operations.ts
@@ -0,0 +1,20 @@
+import { create } from "@bufbuild/protobuf";
+import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
+import type { MemoSaveOperations } from "@/components/MemoEditor/edit/services/memoService";
+import { memoServiceClient } from "@/connect";
+import { MemoSchema } from "@/types/proto/api/memo_service_pb";
+
+/**
+ * Save operations over the bare (mocked) client, shaping requests as the memo
+ * mutation hooks do, for tests of the service's own logic.
+ */
+export const clientSaveOperations: MemoSaveOperations = {
+ getMemo: (name) => memoServiceClient.getMemo({ name }),
+ updateMemo: (update, paths) =>
+ memoServiceClient.updateMemo({
+ memo: create(MemoSchema, update as Record<string, unknown>),
+ updateMask: create(FieldMaskSchema, { paths }),
+ }),
+ createMemo: (memo, parent) =>
+ parent ? memoServiceClient.createMemoComment({ parent, comment: memo }) : memoServiceClient.createMemo({ memo }),
+};
diff --git a/web/tests/home-loading-boundary.test.tsx b/web/tests/home-loading-boundary.test.tsx
index 9130595ce..b3350aae3 100644
--- a/web/tests/home-loading-boundary.test.tsx
+++ b/web/tests/home-loading-boundary.test.tsx
@@ -16,7 +16,7 @@ const state = vi.hoisted(() => ({
}));
vi.mock("@/components/MemoEditor", () => ({
- default: (props: Record<string, unknown>) => {
+ MemoEditor: (props: Record<string, unknown>) => {
state.editorProps = props;
return <div data-testid="memo-editor" />;
},
@@ -110,7 +110,7 @@ describe("<Home>", () => {
expect(screen.getByTestId("memo-editor")).toBeInTheDocument();
expect(screen.getByTestId("memo-view")).toBeInTheDocument();
expect(state.listProps).toMatchObject({ contextFilter: undefined });
- expect(state.editorProps).toMatchObject({ cacheKey: "home-memo-editor", defaultSpace: undefined });
+ expect(state.editorProps).toMatchObject({ draft: { scope: "home", space: undefined } });
expect(state.editorProps?.autoFocus).toEqual(expect.any(Function));
expect(state.editorProps?.suggestions).toEqual([{ id: "tag:work" }]);
expect(state.filterOptions).not.toHaveProperty("creatorName");
@@ -131,8 +131,7 @@ describe("<Home>", () => {
expect(state.listProps).toMatchObject({ contextFilter: 'space == "spaces/product"' });
expect(state.editorProps).toMatchObject({
- cacheKey: "home-memo-editor:spaces/product",
- defaultSpace: "spaces/product",
+ draft: { scope: "home", space: "spaces/product" },
});
});
});
diff --git a/web/tests/inline-image-upload-files.test.ts b/web/tests/inline-image-upload-files.test.ts
index 904dc39a5..e5dff8a45 100644
--- a/web/tests/inline-image-upload-files.test.ts
+++ b/web/tests/inline-image-upload-files.test.ts
@@ -1,7 +1,7 @@
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 { pairAppleLivePhotoFiles } from "@/components/MemoEditor/edit/hooks";
+import { splitInlineLocalFiles } from "@/components/MemoEditor/edit/hooks/useInlineImageUpload";
+import type { LocalFile } from "@/components/MemoEditor/edit/types/attachment";
import { MotionMediaRole } from "@/types/proto/api/attachment_service_pb";
const localFile = (name: string, type: string): LocalFile => ({
diff --git a/web/tests/insert-menu.test.tsx b/web/tests/insert-menu.test.tsx
index a7bea8aa7..4dcbabba7 100644
--- a/web/tests/insert-menu.test.tsx
+++ b/web/tests/insert-menu.test.tsx
@@ -1,8 +1,8 @@
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";
+import { createInitialState, EditorProvider } from "@/components/MemoEditor/edit/state";
+import { EditorToolbar } from "@/components/MemoEditor/edit/Toolbar/EditorToolbar";
+import InsertMenu from "@/components/MemoEditor/edit/Toolbar/InsertMenu";
vi.mock("@/utils/i18n", async (importOriginal) => ({
...(await importOriginal<typeof import("@/utils/i18n")>()),
diff --git a/web/tests/map-view.test.tsx b/web/tests/map-view.test.tsx
index 118590fa7..32949e2f9 100644
--- a/web/tests/map-view.test.tsx
+++ b/web/tests/map-view.test.tsx
@@ -4,11 +4,11 @@ import type { ReactNode } from "react";
import { MemoryRouter } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { MapView } from "@/components/MapView/MapView";
-import type { MemoEditorProps } from "@/components/MemoEditor/types";
+import type { MemoEditorDraftProps } from "@/components/MemoEditor";
import { type Memo, MemoSchema } from "@/types/proto/api/memo_service_pb";
const mocks = vi.hoisted(() => ({
- editor: {} as MemoEditorProps,
+ editor: {} as MemoEditorDraftProps,
refetch: vi.fn(),
toast: vi.fn(),
memos: [] as Memo[],
@@ -35,13 +35,13 @@ vi.mock("@/components/MapView/useMapMemos", () => ({
}));
vi.mock("@/components/MapView/useMapPins", () => ({ useMapPins: () => new Map() }));
vi.mock("@/components/MemoEditor", () => ({
- default: (props: MemoEditorProps) => {
+ MemoEditor: (props: MemoEditorDraftProps) => {
mocks.editor = props;
return <div data-testid="editor" />;
},
}));
vi.mock("@/components/MemoView", () => ({ default: () => <p>Memo</p> }));
-vi.mock("@/components/MemoContent/MentionResolutionContext", () => ({
+vi.mock("@/contexts/MentionResolutionContext", () => ({
MentionResolutionProvider: ({ children }: { children: ReactNode }) => children,
}));
vi.mock("@/contexts/NewMemoContext", () => ({ NewMemoProvider: ({ children }: { children: ReactNode }) => children }));
@@ -94,8 +94,8 @@ describe("map composer", () => {
it("seeds the selected point and Space and releases controls after save", async () => {
mocks.refetch.mockResolvedValue({ data: { pages: [{ memos: [item] }] } });
start();
- expect(mocks.editor.defaultSpace).toBe("spaces/travel");
- expect(mocks.editor.defaultLocation).toEqual(item.location);
+ expect(mocks.editor.draft.space).toBe("spaces/travel");
+ expect(mocks.editor.draft.location).toEqual(item.location);
act(() => mocks.editor.onSavingChange?.(true));
expect(screen.getByTestId("panel")).toHaveAttribute("data-busy", "true");
act(() => mocks.editor.onConfirm?.("memos/one"));
@@ -133,7 +133,7 @@ describe("map place labels", () => {
it("never copies another author's label into a new memo", () => {
mocks.memos = [other];
start("memo=memos%2Ftwo");
- expect(mocks.editor.defaultLocation).toMatchObject({ latitude: 35, longitude: 135, placeholder: "35.0000°, 135.0000°" });
+ expect(mocks.editor.draft.location).toMatchObject({ latitude: 35, longitude: 135, placeholder: "35.0000°, 135.0000°" });
// A single author's label still titles their own memos.
expect(screen.getByTestId("panel")).toHaveAttribute("data-title", "Mom's house");
});
@@ -143,7 +143,7 @@ describe("map place labels", () => {
start("memo=memos%2Ftwo&memo=memos%2Fone");
expect(screen.getByTestId("panel")).toHaveAttribute("data-title", "35.0000°, 135.0000°");
// The writer's own label at the point is theirs to reuse.
- expect(mocks.editor.defaultLocation).toMatchObject({ placeholder: "Kyoto" });
+ expect(mocks.editor.draft.location).toMatchObject({ placeholder: "Kyoto" });
});
});
diff --git a/web/tests/media-metadata-exif-fixture.test.ts b/web/tests/media-metadata-exif-fixture.test.ts
index 4d8ce499a..34fefc792 100644
--- a/web/tests/media-metadata-exif-fixture.test.ts
+++ b/web/tests/media-metadata-exif-fixture.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { mediaMetadataService } from "@/components/MemoEditor/services/mediaMetadataService";
+import { mediaMetadataService } from "@/components/MemoEditor/edit/services/mediaMetadataService";
describe("mediaMetadataService EXIF fixture", () => {
beforeEach(() => {
diff --git a/web/tests/media-metadata-service.test.ts b/web/tests/media-metadata-service.test.ts
index dc43f40c1..68b73b3f7 100644
--- a/web/tests/media-metadata-service.test.ts
+++ b/web/tests/media-metadata-service.test.ts
@@ -8,7 +8,7 @@ vi.mock("exifr", () => ({
parse: mocks.parseExif,
}));
-import { mediaMetadataService } from "@/components/MemoEditor/services/mediaMetadataService";
+import { mediaMetadataService } from "@/components/MemoEditor/edit/services/mediaMetadataService";
describe("mediaMetadataService", () => {
beforeEach(() => {
diff --git a/web/tests/memo-body-compact.test.tsx b/web/tests/memo-body-compact.test.tsx
index 996c793f5..2bff6de79 100644
--- a/web/tests/memo-body-compact.test.tsx
+++ b/web/tests/memo-body-compact.test.tsx
@@ -21,12 +21,12 @@ vi.mock("@/utils/i18n", () => ({
useTranslate: () => (key: string) => key,
}));
-vi.mock("@/components/MemoContent/MentionResolutionContext", () => ({
+vi.mock("@/contexts/MentionResolutionContext", () => ({
useResolvedMentionUsernames: () => new Set<string>(),
}));
-vi.mock("@/components/MemoContent", () => ({
- default: ({ content }: { content: string }) => <div>{content}</div>,
+vi.mock("@/components/MemoEditor/MemoEditor", () => ({
+ MemoEditor: ({ name }: { name: string }) => <div>{mockState.memo.content ?? name}</div>,
}));
vi.mock("@/hooks/useMemoQueries", () => ({
diff --git a/web/tests/memo-comment-section.test.tsx b/web/tests/memo-comment-section.test.tsx
index be5fcda93..4b736066d 100644
--- a/web/tests/memo-comment-section.test.tsx
+++ b/web/tests/memo-comment-section.test.tsx
@@ -3,31 +3,28 @@ import { render, screen } from "@testing-library/react";
import { act, createRef } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import MemoCommentSection, { type MemoCommentSectionHandle } from "@/components/MemoCommentSection";
-import type { MemoEditorProps } from "@/components/MemoEditor/types";
import { State } from "@/types/proto/api/common_pb";
import { MemoSchema } from "@/types/proto/api/memo_service_pb";
const mocks = vi.hoisted(() => ({
currentUser: { name: "users/alice" } as { name: string } | undefined,
- loadMemoEditor: vi.fn(),
}));
-vi.mock("@/components/MemoEditor/loader", () => ({ loadMemoEditor: mocks.loadMemoEditor }));
+vi.mock("@/components/MemoEditor", () => ({
+ preloadMemoEditing: () => Promise.resolve(),
+ MemoEditor: ({ autoFocus, draft }: { autoFocus?: boolean; draft: { parent?: string } }) => (
+ <div data-testid="comment-editor" data-auto-focus={autoFocus} data-parent-memo-name={draft.parent}>
+ <textarea aria-label="Comment editor" />
+ </div>
+ ),
+}));
vi.mock("@/components/MemoView", () => ({ default: () => <div data-testid="comment-memo" /> }));
vi.mock("@/hooks/useCurrentUser", () => ({ default: () => mocks.currentUser }));
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
-const MockMemoEditor = ({ autoFocus, parentMemoName }: MemoEditorProps) => (
- <div data-testid="comment-editor" data-auto-focus={autoFocus} data-parent-memo-name={parentMemoName}>
- <textarea aria-label="Comment editor" />
- </div>
-);
-
describe("MemoCommentSection", () => {
beforeEach(() => {
mocks.currentUser = { name: "users/alice" };
- mocks.loadMemoEditor.mockReset();
- mocks.loadMemoEditor.mockResolvedValue({ default: MockMemoEditor });
});
it("does not offer or imperatively open a comment editor for archived memos", async () => {
@@ -47,7 +44,7 @@ describe("MemoCommentSection", () => {
expect(screen.getByRole("heading", { name: "memo.comment.self" })).toBeInTheDocument();
expect(screen.getByRole("heading", { name: "memo.comment.self" })).toHaveAttribute("id", "memo-comments");
expect(screen.queryByRole("button", { name: /memo.comment.write-a-comment/ })).not.toBeInTheDocument();
- expect(mocks.loadMemoEditor).not.toHaveBeenCalled();
+ expect(screen.queryByTestId("comment-editor")).not.toBeInTheDocument();
});
it("opens and focuses the existing comment editor through its sidebar handle", async () => {
@@ -68,7 +65,6 @@ describe("MemoCommentSection", () => {
await ref.current?.openEditor();
});
- expect(mocks.loadMemoEditor).toHaveBeenCalledOnce();
expect(screen.getByTestId("comment-editor")).toHaveAttribute("data-auto-focus", "true");
expect(screen.getByTestId("comment-editor")).toHaveAttribute("data-parent-memo-name", "memos/detail");
diff --git a/web/tests/memo-content.test.tsx b/web/tests/memo-content-view.test.tsx
similarity index 97%
rename from web/tests/memo-content.test.tsx
rename to web/tests/memo-content-view.test.tsx
index ff7179ae0..63bcc36ba 100644
--- a/web/tests/memo-content.test.tsx
+++ b/web/tests/memo-content-view.test.tsx
@@ -1,7 +1,7 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import MemoContent from "@/components/MemoContent";
+import { MemoContentView } from "@/components/MemoEditor/view/MemoContentView";
import { highlightLoadedCode, loadHighlighter } from "@/lib/code-highlight";
const state = vi.hoisted(() => ({
@@ -28,7 +28,7 @@ vi.mock("@/contexts/MemoFilterContext", async (importOriginal) => ({
}));
vi.mock("@/contexts/ViewContext", () => ({ useLinkPreviewEnabled: () => state.linkPreview }));
-vi.mock("@/components/MemoContent/MentionResolutionContext", () => ({ useResolvedMentionUsernames: () => state.resolved }));
+vi.mock("@/contexts/MentionResolutionContext", () => ({ useResolvedMentionUsernames: () => state.resolved }));
vi.mock("@/hooks/useNavigateTo", () => ({ default: () => state.navigateTo }));
vi.mock("@/hooks/useNearViewport", () => ({ useNearViewport: () => ({ ref: () => {}, isNearViewport: true }) }));
vi.mock("@/hooks/useMemoQueries", () => ({
@@ -38,10 +38,10 @@ vi.mock("@/hooks/useMemoQueries", () => ({
}),
}));
-const renderMemo = (content: string, props: Partial<React.ComponentProps<typeof MemoContent>> = {}, path = "/") =>
+const renderMemo = (content: string, props: Partial<React.ComponentProps<typeof MemoContentView>> = {}, path = "/") =>
render(
<MemoryRouter initialEntries={[path]}>
- <MemoContent content={content} memoName="memos/1" {...props} />
+ <MemoContentView content={content} memoName="memos/1" {...props} />
</MemoryRouter>,
);
diff --git a/web/tests/memo-detail-access.test.tsx b/web/tests/memo-detail-access.test.tsx
index 9ffb80c4d..2a86b6122 100644
--- a/web/tests/memo-detail-access.test.tsx
+++ b/web/tests/memo-detail-access.test.tsx
@@ -23,7 +23,7 @@ vi.mock("@/contexts/AppSidebarContext", () => ({ useAppSidebar: () => ({ setMemo
vi.mock("@/components/MemoView", () => ({ default: ({ memo }: { memo: Memo }) => <article>{memo.content}</article> }));
vi.mock("@/components/MemoView/MemoViewContext", () => ({ computeCommentAmount: () => 0 }));
vi.mock("@/components/MemoCommentSection", () => ({ default: () => null }));
-vi.mock("@/components/MemoContent/MentionResolutionContext", () => ({
+vi.mock("@/contexts/MentionResolutionContext", () => ({
MentionResolutionProvider: ({ children }: { children: ReactNode }) => children,
}));
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
diff --git a/web/tests/memo-editor-cache.test.ts b/web/tests/memo-editor-cache.test.ts
index 1c6f6cf7a..173668bfa 100644
--- a/web/tests/memo-editor-cache.test.ts
+++ b/web/tests/memo-editor-cache.test.ts
@@ -1,6 +1,6 @@
import { create } from "@bufbuild/protobuf";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { cacheService } from "@/components/MemoEditor/services/cacheService";
+import { cacheService } from "@/components/MemoEditor/edit/services/cacheService";
import { AttachmentSchema, MotionMediaFamily, MotionMediaRole, MotionMediaSchema } from "@/types/proto/api/attachment_service_pb";
import { LocationSchema, Visibility } from "@/types/proto/api/memo_service_pb";
diff --git a/web/tests/memo-editor-paste-files.test.tsx b/web/tests/memo-editor-paste-files.test.tsx
index 39ffd57bb..4ee86f973 100644
--- a/web/tests/memo-editor-paste-files.test.tsx
+++ b/web/tests/memo-editor-paste-files.test.tsx
@@ -1,8 +1,8 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render, waitFor } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
-import MemoEditor from "@/components/MemoEditor";
-import { uploadService } from "@/components/MemoEditor/services";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import { MemoEditor, preloadMemoEditing } from "@/components/MemoEditor";
+import { uploadService } from "@/components/MemoEditor/edit/services";
vi.mock("@/utils/i18n", async (importOriginal) => ({
...(await importOriginal<typeof import("@/utils/i18n")>()),
@@ -38,11 +38,14 @@ const paste = (target: Element, files: File[]) => {
return event;
};
+// The editing session loads lazily; loaded once, it renders without suspending.
+beforeAll(() => preloadMemoEditing());
+
const mount = () => {
const client = new QueryClient();
const result = render(
<QueryClientProvider client={client}>
- <MemoEditor cacheKey="paste-test" />
+ <MemoEditor draft={{ scope: "paste-test" }} />
</QueryClientProvider>,
);
const content = result.container.querySelector<HTMLElement>(".memo-editor-root");
diff --git a/web/tests/memo-editor-relations.test.ts b/web/tests/memo-editor-relations.test.ts
index 51ee3ceb9..bdc004c00 100644
--- a/web/tests/memo-editor-relations.test.ts
+++ b/web/tests/memo-editor-relations.test.ts
@@ -1,7 +1,7 @@
import { create } from "@bufbuild/protobuf";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { memoService } from "@/components/MemoEditor/services/memoService";
-import { createInitialState, type EditorState } from "@/components/MemoEditor/state";
+import { memoService } from "@/components/MemoEditor/edit/services/memoService";
+import { createInitialState, type EditorState } from "@/components/MemoEditor/edit/state";
import {
type Memo,
MemoRelation_MemoRefSchema,
@@ -9,6 +9,7 @@ import {
MemoRelationSchema,
MemoSchema,
} from "@/types/proto/api/memo_service_pb";
+import { clientSaveOperations as ops } from "./helpers/memo-save-operations";
const clients = vi.hoisted(() => ({
createMemo: vi.fn(),
@@ -62,7 +63,7 @@ describe("memo editor relation updates", () => {
const state = createInitialState();
state.content = "Roadmap";
- await memoService.save(state, { space: "spaces/product" });
+ await memoService.save(state, { space: "spaces/product" }, ops);
expect(clients.createMemo).toHaveBeenCalledWith({
memo: expect.objectContaining({ content: "Roadmap", space: "spaces/product" }),
@@ -73,9 +74,9 @@ describe("memo editor relation updates", () => {
const state = createInitialState();
state.content = "Draft";
state.metadata = { ...state.metadata, space: "spaces/work" };
- await memoService.save(state, {});
+ await memoService.save(state, {}, ops);
expect(clients.createMemo).toHaveBeenLastCalledWith({ memo: expect.objectContaining({ space: "spaces/work" }) });
- await memoService.save(state, { space: "spaces/current" });
+ await memoService.save(state, { space: "spaces/current" }, ops);
expect(clients.createMemo).toHaveBeenLastCalledWith({ memo: expect.objectContaining({ space: "spaces/current" }) });
});
@@ -84,7 +85,7 @@ describe("memo editor relation updates", () => {
state.content = "Reply";
state.metadata = { ...state.metadata, space: "spaces/draft" };
- await memoService.save(state, { parentMemoName: "memos/parent", space: "spaces/product" });
+ await memoService.save(state, { parentMemoName: "memos/parent", space: "spaces/product" }, ops);
expect(clients.createMemoComment).toHaveBeenCalledOnce();
const request = clients.createMemoComment.mock.calls[0][0];
@@ -108,7 +109,7 @@ describe("memo editor relation updates", () => {
state.metadata.relations = [...state.metadata.relations, addedReference];
clients.getMemo.mockResolvedValue(comment);
- await memoService.save(state, { memoName: commentName });
+ await memoService.save(state, { memoName: commentName }, ops);
expect(clients.updateMemo).toHaveBeenCalledOnce();
const request = clients.updateMemo.mock.calls[0][0];
@@ -135,7 +136,7 @@ describe("memo editor relation updates", () => {
const state = createEditorState(editorMemo);
clients.getMemo.mockResolvedValue(freshMemo);
- const result = await memoService.save(state, { memoName: parentName });
+ const result = await memoService.save(state, { memoName: parentName }, ops);
expect(result).toEqual({ memoName: parentName, hasChanges: false });
expect(clients.updateMemo).not.toHaveBeenCalled();
diff --git a/web/tests/memo-editor-source-mode.test.tsx b/web/tests/memo-editor-source-mode.test.tsx
index 1899d808f..269ac5076 100644
--- a/web/tests/memo-editor-source-mode.test.tsx
+++ b/web/tests/memo-editor-source-mode.test.tsx
@@ -1,8 +1,9 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
-import MemoEditor from "@/components/MemoEditor";
-import { cacheService } from "@/components/MemoEditor/services";
+import { MemoEditor, preloadMemoEditing } from "@/components/MemoEditor";
+import { draftKeyFor } from "@/components/MemoEditor/edit/draftKey";
+import { cacheService } from "@/components/MemoEditor/edit/services";
import type { MemoSuggestion } from "@/lib/memo-suggestions";
vi.mock("@/utils/i18n", async (importOriginal) => ({
@@ -29,7 +30,9 @@ vi.stubGlobal(
},
);
-beforeAll(() => {
+beforeAll(async () => {
+ // The editing session loads lazily; loaded once, it renders without suspending.
+ await preloadMemoEditing();
Element.prototype.scrollIntoView = vi.fn();
Element.prototype.hasPointerCapture = vi.fn(() => false);
Element.prototype.setPointerCapture = vi.fn();
@@ -42,7 +45,7 @@ const CACHE_KEY = "source-mode-test";
const mount = (suggestions?: readonly MemoSuggestion[]) =>
render(
<QueryClientProvider client={new QueryClient()}>
- <MemoEditor cacheKey={CACHE_KEY} suggestions={suggestions} />
+ <MemoEditor draft={{ scope: CACHE_KEY }} suggestions={suggestions} />
</QueryClientProvider>,
);
@@ -89,7 +92,10 @@ describe("MemoEditor source mode", () => {
["source", false],
])("offers the checklist suggestion in %s mode: %s", async (mode, offered) => {
localStorage.setItem(MODE_KEY, JSON.stringify(mode));
- cacheService.saveNow(cacheService.key("users/1", CACHE_KEY), { content: "Groceries", attachments: [] });
+ cacheService.saveNow(cacheService.key("users/1", draftKeyFor({ kind: "new", scope: CACHE_KEY })), {
+ content: "Groceries",
+ attachments: [],
+ });
mount([
{ id: "tag:food", source: "view", kind: "tag", tag: "food" },
{ id: "checklist", source: "view", kind: "checklist" },
diff --git a/web/tests/memo-editor-space-move.test.ts b/web/tests/memo-editor-space-move.test.ts
index 260cfcc36..b603b69db 100644
--- a/web/tests/memo-editor-space-move.test.ts
+++ b/web/tests/memo-editor-space-move.test.ts
@@ -1,8 +1,9 @@
import { create } from "@bufbuild/protobuf";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { memoService } from "@/components/MemoEditor/services/memoService";
-import { createInitialState, type EditorState } from "@/components/MemoEditor/state";
+import { memoService } from "@/components/MemoEditor/edit/services/memoService";
+import { createInitialState, type EditorState } from "@/components/MemoEditor/edit/state";
import { type Memo, MemoSchema, Visibility } from "@/types/proto/api/memo_service_pb";
+import { clientSaveOperations as ops } from "./helpers/memo-save-operations";
const clients = vi.hoisted(() => ({
getMemo: vi.fn(),
@@ -42,7 +43,7 @@ describe("editing a memo's Space", () => {
const memo = stored({ space: "spaces/work", visibility: Visibility.SPACE });
clients.getMemo.mockResolvedValue(memo);
- const result = await memoService.save(editedFrom(memo, { space: "spaces/reading" }), { memoName: memo.name });
+ const result = await memoService.save(editedFrom(memo, { space: "spaces/reading" }), { memoName: memo.name }, ops);
expect(new Set(savedMask())).toEqual(new Set(["space", "visibility"]));
expect(savedMemo().space).toBe("spaces/reading");
@@ -54,7 +55,7 @@ describe("editing a memo's Space", () => {
const memo = stored({ space: "spaces/work" });
clients.getMemo.mockResolvedValue(memo);
- await memoService.save(editedFrom(memo, { space: undefined }), { memoName: memo.name });
+ await memoService.save(editedFrom(memo, { space: undefined }), { memoName: memo.name }, ops);
expect(savedMask()).toContain("space");
expect(savedMemo().space).toBe("");
@@ -64,7 +65,7 @@ describe("editing a memo's Space", () => {
const memo = stored({ space: "spaces/work" });
clients.getMemo.mockResolvedValue(memo);
- const result = await memoService.save({ ...editedFrom(memo, {}), content: "Edited" }, { memoName: memo.name });
+ const result = await memoService.save({ ...editedFrom(memo, {}), content: "Edited" }, { memoName: memo.name }, ops);
expect(savedMask()).not.toContain("space");
expect(result.moved).toBe(false);
diff --git a/web/tests/memo-editor-timestamps.test.tsx b/web/tests/memo-editor-timestamps.test.tsx
index 1f3b6620b..5fb81ed9c 100644
--- a/web/tests/memo-editor-timestamps.test.tsx
+++ b/web/tests/memo-editor-timestamps.test.tsx
@@ -2,10 +2,11 @@ import { create } from "@bufbuild/protobuf";
import { timestampFromDate } from "@bufbuild/protobuf/wkt";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { TimestampPopover } from "@/components/MemoEditor/components/TimestampPopover";
-import { memoService } from "@/components/MemoEditor/services/memoService";
-import { createInitialState, EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
+import { TimestampPopover } from "@/components/MemoEditor/edit/components/TimestampPopover";
+import { memoService } from "@/components/MemoEditor/edit/services/memoService";
+import { createInitialState, EditorProvider, useEditorContext } from "@/components/MemoEditor/edit/state";
import { type Memo, MemoSchema } from "@/types/proto/api/memo_service_pb";
+import { clientSaveOperations as ops } from "./helpers/memo-save-operations";
const clients = vi.hoisted(() => ({ getMemo: vi.fn(), updateMemo: vi.fn() }));
vi.mock("@/connect", () => ({
@@ -57,7 +58,7 @@ describe("memo editor timestamps", () => {
fireEvent.keyDown(input, { key: "Escape" });
await waitFor(() => expect(screen.queryByRole("textbox")).not.toBeInTheDocument());
- await memoService.save(editor.getState(), { memoName: memo.name });
+ await memoService.save(editor.getState(), { memoName: memo.name }, ops);
expect(clients.updateMemo).toHaveBeenCalledOnce();
const request = clients.updateMemo.mock.calls[0][0];
@@ -77,14 +78,14 @@ describe("memo editor timestamps", () => {
fireEvent.blur(input);
expect(input).toHaveAttribute("data-invalid", "true");
expect(editor.getState().timestamps.createTime).toEqual(originalCreate);
- await memoService.save(editor.getState(), { memoName: memo.name });
+ await memoService.save(editor.getState(), { memoName: memo.name }, ops);
expect(clients.updateMemo).not.toHaveBeenCalled();
});
it("automatically updates the modification time for content edits", async () => {
const memo = renderEditor();
const state = { ...editor.getState(), content: "Changed content" };
- await memoService.save(state, { memoName: memo.name });
+ await memoService.save(state, { memoName: memo.name }, ops);
const request = clients.updateMemo.mock.calls[0][0];
expect(request.updateMask.paths).toEqual(["content", "update_time"]);
expect(request.memo.updateTime).toBeUndefined();
@@ -96,7 +97,7 @@ describe("memo editor timestamps", () => {
const input = screen.getAllByRole("textbox")[1];
fireEvent.change(input, { target: { value: "2024-02-29 12:34:56" } });
// Saving must see the edit even if the input has not blurred yet.
- await memoService.save({ ...editor.getState(), content: "Changed content" }, { memoName: memo.name });
+ await memoService.save({ ...editor.getState(), content: "Changed content" }, { memoName: memo.name }, ops);
const request = clients.updateMemo.mock.calls[0][0];
expect(request.updateMask.paths).toEqual(["content", "update_time"]);
expect(request.memo.updateTime).toEqual(timestampFromDate(customTime));
diff --git a/web/tests/memo-editor-transcription.test.tsx b/web/tests/memo-editor-transcription.test.tsx
index 01d2614df..7e6292f65 100644
--- a/web/tests/memo-editor-transcription.test.tsx
+++ b/web/tests/memo-editor-transcription.test.tsx
@@ -1,9 +1,10 @@
import { create } from "@bufbuild/protobuf";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
-import MemoEditor from "@/components/MemoEditor";
-import { transcriptionService } from "@/components/MemoEditor/services";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import { MemoEditor, preloadMemoEditing } from "@/components/MemoEditor";
+import { transcriptionService } from "@/components/MemoEditor/edit/services";
+import { memoKeys } from "@/hooks/useMemoQueries";
import { AttachmentSchema } from "@/types/proto/api/attachment_service_pb";
import { MemoSchema, Visibility } from "@/types/proto/api/memo_service_pb";
@@ -29,6 +30,9 @@ vi.stubGlobal(
},
);
+// The editing session loads lazily; loaded once, it renders without suspending.
+beforeAll(() => preloadMemoEditing());
+
describe("existing memo audio transcription", () => {
it("blocks save while transcribing, inserts into the editable draft and retains the original attachment on save", async () => {
const attachment = create(AttachmentSchema, { name: "attachments/voice", filename: "voice.wav", type: "audio/wav" });
@@ -43,9 +47,12 @@ describe("existing memo audio transcription", () => {
clients.updateMemo.mockImplementation(async ({ memo: update }) => create(MemoSchema, { ...memo, ...update }));
const pending = Promise.withResolvers<string>();
vi.spyOn(transcriptionService, "transcribeAttachment").mockReturnValue(pending.promise);
+ // The card edits a memo a query already holds; the save still fetches the server's copy to diff.
+ const client = new QueryClient();
+ client.setQueryData(memoKeys.detail(memo.name), memo);
const { container } = render(
- <QueryClientProvider client={new QueryClient()}>
- <MemoEditor memo={memo} />
+ <QueryClientProvider client={client}>
+ <MemoEditor mode="edit" name={memo.name} />
</QueryClientProvider>,
);
await waitFor(() => expect(container.querySelector(".memo-editor-root")?.textContent).toBe(memo.content));
diff --git a/web/tests/memo-editor-upload-retry.test.tsx b/web/tests/memo-editor-upload-retry.test.tsx
index 9e75c3612..716161fea 100644
--- a/web/tests/memo-editor-upload-retry.test.tsx
+++ b/web/tests/memo-editor-upload-retry.test.tsx
@@ -3,12 +3,13 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { act, renderHook } from "@testing-library/react";
import type { PropsWithChildren } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { useMemoSave } from "@/components/MemoEditor/hooks/useMemoSave";
-import { memoService } from "@/components/MemoEditor/services/memoService";
-import type { EditorState } from "@/components/MemoEditor/state";
-import { createInitialState } from "@/components/MemoEditor/state/types";
-import type { LocalFile } from "@/components/MemoEditor/types/attachment";
+import { useMemoSave } from "@/components/MemoEditor/edit/hooks/useMemoSave";
+import { memoService } from "@/components/MemoEditor/edit/services/memoService";
+import type { EditorState } from "@/components/MemoEditor/edit/state";
+import { createInitialState } from "@/components/MemoEditor/edit/state/types";
+import type { LocalFile } from "@/components/MemoEditor/edit/types/attachment";
import { type Attachment, AttachmentSchema } from "@/types/proto/api/attachment_service_pb";
+import { clientSaveOperations as ops } from "./helpers/memo-save-operations";
const mocks = vi.hoisted(() => ({
createMemo: vi.fn(),
@@ -28,7 +29,7 @@ vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
// The hook test drives a small stand-in for the editor reducer, so that what
// the hook dispatches after a failure is what the next save reads.
-vi.mock("@/components/MemoEditor/state", () => ({
+vi.mock("@/components/MemoEditor/edit/state", () => ({
useEditorContext: () => ({
actions: {
reset: () => ({ type: "reset" }),
@@ -71,7 +72,7 @@ describe("memoService.save", () => {
const file = localFile("a.txt");
const onFileUploaded = vi.fn();
- await expect(memoService.save(editorState([file]), { onFileUploaded })).rejects.toThrow("quota exceeded");
+ await expect(memoService.save(editorState([file]), { onFileUploaded }, ops)).rejects.toThrow("quota exceeded");
expect(onFileUploaded).toHaveBeenCalledOnce();
expect(onFileUploaded).toHaveBeenCalledWith(file, expect.objectContaining({ name: "attachments/a.txt" }));
diff --git a/web/tests/memo-editor-view.test.tsx b/web/tests/memo-editor-view.test.tsx
new file mode 100644
index 000000000..3aef4db88
--- /dev/null
+++ b/web/tests/memo-editor-view.test.tsx
@@ -0,0 +1,98 @@
+import { create } from "@bufbuild/protobuf";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, fireEvent, render, waitFor } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { MemoEditor } from "@/components/MemoEditor/MemoEditor";
+import { memoKeys } from "@/hooks/useMemoQueries";
+import { ListMemosResponseSchema, type Memo, MemoSchema } from "@/types/proto/api/memo_service_pb";
+
+const state = vi.hoisted(() => ({ currentUser: undefined as { name: string; role?: string } | undefined }));
+const api = vi.hoisted(() => ({ getMemo: vi.fn(), updateMemo: vi.fn() }));
+
+vi.mock("@/connect", () => ({ memoServiceClient: api }));
+vi.mock("@/hooks/useCurrentUser", () => ({ default: () => state.currentUser }));
+vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ userTagsSetting: undefined }) }));
+vi.mock("@/contexts/ViewContext", () => ({ useLinkPreviewEnabled: () => false }));
+vi.mock("@/contexts/MemoFilterContext", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/contexts/MemoFilterContext")>()),
+ useMemoFilterContext: () => ({ getFiltersByFactor: () => [], addFilter: vi.fn(), removeFilter: vi.fn() }),
+}));
+vi.mock("@/contexts/MentionResolutionContext", () => ({ useResolvedMentionUsernames: () => new Set<string>() }));
+vi.mock("@/hooks/useNavigateTo", () => ({ default: () => vi.fn() }));
+
+const setup = () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
+ const renderMemo = (name: string) =>
+ render(
+ <QueryClientProvider client={client}>
+ <MemoryRouter>
+ <MemoEditor name={name} />
+ </MemoryRouter>
+ </QueryClientProvider>,
+ );
+ return { client, renderMemo };
+};
+
+const memo = (content: string): Memo => create(MemoSchema, { name: "memos/one", creator: "users/owner", content });
+
+describe("MemoEditor in view mode", () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ state.currentUser = undefined;
+ });
+
+ it("shows the memo a list already holds, without fetching it", () => {
+ const { client, renderMemo } = setup();
+ client.setQueryData(memoKeys.list({}), create(ListMemosResponseSchema, { memos: [memo("# Title\n\nSome **bold** text")] }));
+
+ const { container } = renderMemo("memos/one");
+
+ expect(container.querySelector(".memo-content-root")).toHaveAttribute("aria-readonly", "true");
+ expect(container.querySelector("h1")).toHaveTextContent("Title");
+ expect(container.querySelector("[data-memo-name]")).toHaveAttribute("data-memo-name", "memos/one");
+ expect(api.getMemo).not.toHaveBeenCalled();
+ });
+
+ it("fetches a memo no query holds", async () => {
+ const { renderMemo } = setup();
+ api.getMemo.mockResolvedValue(memo("Fetched"));
+
+ const { container } = renderMemo("memos/one");
+
+ await waitFor(() => expect(container.querySelector(".memo-content-root")).toHaveTextContent("Fetched"));
+ expect(api.getMemo).toHaveBeenCalledOnce();
+ });
+
+ it("lets the owner tick a task and saves it through the mutation, so the list follows", async () => {
+ const { client, renderMemo } = setup();
+ state.currentUser = { name: "users/owner" };
+ client.setQueryData(memoKeys.list({}), create(ListMemosResponseSchema, { memos: [memo("- [ ] First\n- [x] Second")] }));
+ api.updateMemo.mockImplementation(async ({ memo: update }: { memo: Memo }) => ({ ...memo(update.content), content: update.content }));
+
+ const { container } = renderMemo("memos/one");
+ const checkbox = container.querySelector<HTMLInputElement>("input.mbe-checkbox");
+ expect(checkbox).not.toBeDisabled();
+ await act(async () => {
+ fireEvent.mouseDown(checkbox!);
+ });
+
+ await waitFor(() => expect(api.updateMemo).toHaveBeenCalledOnce());
+ const [{ memo: sent, updateMask }] = api.updateMemo.mock.calls[0];
+ expect(sent.content).toBe("- [x] First\n- [x] Second");
+ expect(updateMask.paths).toEqual(["content", "update_time"]);
+ await waitFor(() =>
+ expect(client.getQueryData<{ memos: Memo[] }>(memoKeys.list({}))?.memos[0].content).toBe("- [x] First\n- [x] Second"),
+ );
+ });
+
+ it("keeps tasks locked for a reader", () => {
+ const { client, renderMemo } = setup();
+ state.currentUser = { name: "users/reader" };
+ client.setQueryData(memoKeys.list({}), create(ListMemosResponseSchema, { memos: [memo("- [ ] First")] }));
+
+ const { container } = renderMemo("memos/one");
+
+ expect(container.querySelector("input.mbe-checkbox")).toBeDisabled();
+ });
+});
diff --git a/web/tests/memo-header-navigation.test.tsx b/web/tests/memo-header-navigation.test.tsx
index 27b3f9081..f79c57404 100644
--- a/web/tests/memo-header-navigation.test.tsx
+++ b/web/tests/memo-header-navigation.test.tsx
@@ -7,6 +7,7 @@ import MemoHeader from "@/components/MemoView/components/MemoHeader";
const state = vi.hoisted(() => ({
creator: undefined as { username: string; displayName: string; avatarUrl: string } | undefined,
currentUser: undefined as { name: string } | undefined,
+ isEditing: false,
}));
vi.mock("@/components/RelativeTime", () => ({
@@ -59,6 +60,7 @@ vi.mock("@/components/MemoView/MemoViewContext", () => ({
parentPage: "/explore?filter=tagSearch%3Awork",
isArchived: false,
readonly: false,
+ isEditing: state.isEditing,
openEditor: vi.fn(),
}),
useMemoViewDerived: () => ({
@@ -87,6 +89,31 @@ describe("MemoHeader navigation", () => {
beforeEach(() => {
state.creator = undefined;
state.currentUser = undefined;
+ state.isEditing = false;
+ });
+
+ it.each([false, true])("keeps only the creator while the card edits in place (showCreator=%s)", (showCreator) => {
+ state.currentUser = { name: "users/alice" };
+ state.creator = { username: "alice", displayName: "Alice", avatarUrl: "" };
+ state.isEditing = true;
+
+ const { container } = render(
+ <MemoryRouter>
+ <MemoHeader showCreator={showCreator} showVisibility showSpace />
+ </MemoryRouter>,
+ );
+
+ // The session below shows the editable time, visibility and Space; reacting and the menu wait.
+ expect(screen.queryByRole("link", { name: "time" })).not.toBeInTheDocument();
+ expect(screen.queryByTestId("memo-space")).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "add-reaction" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "memo-actions" })).not.toBeInTheDocument();
+ if (showCreator) {
+ expect(screen.getByRole("link", { name: /Alice/ })).toBeInTheDocument();
+ expect(container).not.toHaveTextContent("·");
+ } else {
+ expect(container).toBeEmptyDOMElement();
+ }
});
it("uses one compact interaction surface for memo header actions", () => {
diff --git a/web/tests/memo-outline-headings.test.ts b/web/tests/memo-outline-headings.test.ts
index 53695f5f5..2a27e2c59 100644
--- a/web/tests/memo-outline-headings.test.ts
+++ b/web/tests/memo-outline-headings.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { extractHeadings } from "@/components/MemoContent/headings";
+import { extractHeadings } from "@/components/MemoEditor/view/headings";
// The memo view sets the same anchors as element ids (see memo-content.test.tsx), so an
// outline link always has somewhere to land.
diff --git a/web/tests/memo-panel-list.test.tsx b/web/tests/memo-panel-list.test.tsx
index c64c2778b..0cb931a5c 100644
--- a/web/tests/memo-panel-list.test.tsx
+++ b/web/tests/memo-panel-list.test.tsx
@@ -17,13 +17,13 @@ vi.mock("@/components/MemoView", () => ({
return <p>{props.memo.name}</p>;
},
}));
-vi.mock("@/components/MemoContent/MentionResolutionContext", () => ({
+vi.mock("@/contexts/MentionResolutionContext", () => ({
MentionResolutionProvider: ({ userNames, children }: { userNames: string[]; children: ReactNode }) => {
mocks.userNames = userNames;
return children;
},
}));
-vi.mock("@/components/MemoEditor", () => ({ default: () => <div data-testid="editor" /> }));
+vi.mock("@/components/MemoEditor", () => ({ MemoEditor: () => <div data-testid="editor" /> }));
vi.mock("@/contexts/NewMemoContext", () => ({ NewMemoProvider: ({ children }: { children: ReactNode }) => children }));
vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ isUserSettingsInitialized: true }) }));
vi.mock("@/contexts/SpaceContext", () => ({ useSpaceContext: () => ({ creatorUsername: mocks.creatorUsername }) }));
diff --git a/web/tests/memo-record.test.tsx b/web/tests/memo-record.test.tsx
new file mode 100644
index 000000000..82b71b2bc
--- /dev/null
+++ b/web/tests/memo-record.test.tsx
@@ -0,0 +1,190 @@
+import { create } from "@bufbuild/protobuf";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { findMemoInCollectionQueries, memoKeys, useCreateMemo, useMemoByName, useMemoRecord, useUpdateMemo } from "@/hooks/useMemoQueries";
+import { memoShareKeys } from "@/hooks/useMemoShareQueries";
+import { ListMemoCommentsResponseSchema, ListMemosResponseSchema, type Memo, MemoSchema } from "@/types/proto/api/memo_service_pb";
+
+const api = vi.hoisted(() => ({ getMemo: vi.fn(), updateMemo: vi.fn(), createMemo: vi.fn(), createMemoComment: vi.fn() }));
+vi.mock("@/connect", () => ({ memoServiceClient: api }));
+
+const setup = () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, retryDelay: 0 }, mutations: { retry: false } } });
+ const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>;
+ return { client, wrapper };
+};
+
+const memo = (name: string, content = name): Memo => create(MemoSchema, { name, content });
+
+describe("useMemoRecord", () => {
+ beforeEach(() => vi.resetAllMocks());
+
+ it("reads a memo from an infinite list page without a request", () => {
+ const { client, wrapper } = setup();
+ const listed = memo("memos/listed");
+ client.setQueryData(memoKeys.list({}), { pages: [create(ListMemosResponseSchema, { memos: [listed] })], pageParams: [""] });
+
+ const { result } = renderHook(() => useMemoRecord(listed.name), { wrapper });
+
+ expect(result.current).toBe(listed);
+ expect(api.getMemo).not.toHaveBeenCalled();
+ });
+
+ it("reads a memo from comment pages, the calendar month and a shared memo", () => {
+ const { client, wrapper } = setup();
+ const comment = memo("memos/comment");
+ const monthly = memo("memos/monthly");
+ const shared = memo("memos/shared");
+ client.setQueryData([...memoKeys.comments("memos/parent"), "infinite", 50], {
+ pages: [create(ListMemoCommentsResponseSchema, { comments: [comment] })],
+ pageParams: [""],
+ });
+ client.setQueryData([...memoKeys.lists(), "calendar-month", { filter: "", orderBy: "" }], [monthly]);
+ client.setQueryData(memoShareKeys.byShare("token"), shared);
+
+ const { result } = renderHook(
+ () => [useMemoRecord(comment.name), useMemoRecord(monthly.name), useMemoRecord(shared.name), useMemoRecord("memos/none")],
+ { wrapper },
+ );
+
+ expect(result.current).toEqual([comment, monthly, shared, undefined]);
+ });
+
+ it("prefers the copy fetched most recently", () => {
+ const { client, wrapper } = setup();
+ const stale = memo("memos/x", "old");
+ const fresh = memo("memos/x", "new");
+ client.setQueryData(memoKeys.detail(stale.name), stale, { updatedAt: 1_000 });
+ client.setQueryData(memoKeys.list({}), create(ListMemosResponseSchema, { memos: [fresh] }), { updatedAt: 2_000 });
+
+ const { result } = renderHook(() => useMemoRecord(stale.name), { wrapper });
+
+ expect(result.current).toBe(fresh);
+ });
+
+ it("follows the list's refetch and a mutation's optimistic patch", async () => {
+ const { client, wrapper } = setup();
+ const before = memo("memos/x", "before");
+ client.setQueryData(memoKeys.list({}), create(ListMemosResponseSchema, { memos: [before] }));
+ let resolve!: (memo: Memo) => void;
+ api.updateMemo.mockImplementation(
+ () =>
+ new Promise<Memo>((done) => {
+ resolve = done;
+ }),
+ );
+
+ const { result } = renderHook(() => ({ record: useMemoRecord(before.name), update: useUpdateMemo() }), { wrapper });
+ expect(result.current.record?.content).toBe("before");
+
+ act(() => {
+ client.setQueryData(memoKeys.list({}), create(ListMemosResponseSchema, { memos: [memo("memos/x", "refetched")] }));
+ });
+ expect(result.current.record?.content).toBe("refetched");
+
+ act(() => result.current.update.mutate({ update: { name: before.name, content: "edited" }, updateMask: ["content"] }));
+ // The optimistic patch, before the server answers.
+ await waitFor(() => expect(result.current.record?.content).toBe("edited"));
+ expect(result.current.update.isSuccess).toBe(false);
+ await act(async () => resolve(memo("memos/x", "edited")));
+ await waitFor(() => expect(result.current.update.isSuccess).toBe(true));
+ expect(result.current.record?.content).toBe("edited");
+ });
+
+ it("patches an edited comment inside its comment page", async () => {
+ const { client, wrapper } = setup();
+ const comment = create(MemoSchema, { name: "memos/c", parent: "memos/p", content: "before" });
+ const key = [...memoKeys.comments("memos/p"), 0];
+ client.setQueryData(key, create(ListMemoCommentsResponseSchema, { comments: [comment] }));
+ api.updateMemo.mockImplementation(async ({ memo: update }: { memo: Memo }) => ({ ...comment, ...update }));
+
+ const { result } = renderHook(() => useUpdateMemo(), { wrapper });
+ act(() => result.current.mutate({ update: { name: comment.name, content: "after" }, updateMask: ["content"] }));
+ await waitFor(() => expect(client.getQueryData<{ comments: Memo[] }>(key)?.comments[0].content).toBe("after"));
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(findMemoInCollectionQueries(client, comment.name)?.content).toBe("after");
+ });
+
+ it("reports a memo recorded as unavailable", () => {
+ const { client, wrapper } = setup();
+ client.setQueryData(memoKeys.detail("memos/gone"), null);
+ client.setQueryData(memoKeys.list({}), create(ListMemosResponseSchema, { memos: [memo("memos/gone")] }));
+
+ const { result } = renderHook(() => useMemoRecord("memos/gone"), { wrapper });
+
+ expect(result.current).toBeNull();
+ });
+});
+
+describe("useMemoByName", () => {
+ beforeEach(() => vi.resetAllMocks());
+
+ it("fetches the detail once when no query holds the memo, then reads the cache", async () => {
+ const { client, wrapper } = setup();
+ const fetched = memo("memos/deep");
+ api.getMemo.mockResolvedValue(fetched);
+
+ const { result } = renderHook(() => useMemoByName(fetched.name), { wrapper });
+ expect(result.current.isLoading).toBe(true);
+ await waitFor(() => expect(result.current.data).toEqual(fetched));
+
+ expect(api.getMemo).toHaveBeenCalledOnce();
+ expect(client.getQueryData(memoKeys.detail(fetched.name))).toEqual(fetched);
+ await act(async () => {
+ await client.invalidateQueries({ queryKey: memoKeys.all, refetchType: "active" });
+ });
+ expect(api.getMemo).toHaveBeenCalledOnce();
+ });
+
+ it("costs no request when a list already holds the memo", () => {
+ const { client, wrapper } = setup();
+ const listed = memo("memos/listed");
+ client.setQueryData(memoKeys.list({}), create(ListMemosResponseSchema, { memos: [listed] }));
+
+ const { result } = renderHook(() => useMemoByName(listed.name), { wrapper });
+
+ expect(result.current.data).toBe(listed);
+ expect(result.current.isLoading).toBe(false);
+ expect(api.getMemo).not.toHaveBeenCalled();
+ });
+});
+
+describe("useCreateMemo", () => {
+ beforeEach(() => vi.resetAllMocks());
+
+ it("creates a comment through the parent and refreshes the parent's comments", async () => {
+ const { client, wrapper } = setup();
+ const created = create(MemoSchema, { name: "memos/new", parent: "memos/p", content: "hi" });
+ api.createMemoComment.mockResolvedValue(created);
+ const invalidate = vi.spyOn(client, "invalidateQueries");
+
+ const { result } = renderHook(() => useCreateMemo(), { wrapper });
+ await act(async () => {
+ await result.current.mutateAsync({ memo: memo("", "hi"), parent: "memos/p" });
+ });
+
+ expect(api.createMemoComment).toHaveBeenCalledWith({ parent: "memos/p", comment: expect.objectContaining({ content: "hi" }) });
+ expect(api.createMemo).not.toHaveBeenCalled();
+ expect(client.getQueryData(memoKeys.detail(created.name))).toEqual(created);
+ const keys = invalidate.mock.calls.map(([filters]) => filters?.queryKey);
+ expect(keys).toContainEqual(memoKeys.comments("memos/p"));
+ expect(keys).toContainEqual(memoKeys.detail("memos/p"));
+ });
+
+ it("creates a top-level memo without touching any comment query", async () => {
+ const { client, wrapper } = setup();
+ const created = memo("memos/new", "hi");
+ api.createMemo.mockResolvedValue(created);
+ const invalidate = vi.spyOn(client, "invalidateQueries");
+
+ const { result } = renderHook(() => useCreateMemo(), { wrapper });
+ await act(async () => {
+ await result.current.mutateAsync({ memo: memo("", "hi") });
+ });
+
+ expect(api.createMemo).toHaveBeenCalledWith({ memo: expect.objectContaining({ content: "hi" }) });
+ expect(invalidate.mock.calls.map(([filters]) => filters?.queryKey?.[1])).not.toContain("comments");
+ });
+});
diff --git a/web/tests/paged-memo-list.test.tsx b/web/tests/paged-memo-list.test.tsx
index 6eb5162cf..d98aa16d0 100644
--- a/web/tests/paged-memo-list.test.tsx
+++ b/web/tests/paged-memo-list.test.tsx
@@ -57,7 +57,7 @@ vi.mock("@/utils/i18n", () => ({
useTranslate: () => (key: string) => (key === "message.no-data" ? "No data found." : key),
}));
-vi.mock("@/components/MemoContent/MentionResolutionContext", () => ({
+vi.mock("@/contexts/MentionResolutionContext", () => ({
MentionResolutionProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
diff --git a/web/tests/query-deduplication.test.tsx b/web/tests/query-deduplication.test.tsx
index 4a633adb8..064a348d4 100644
--- a/web/tests/query-deduplication.test.tsx
+++ b/web/tests/query-deduplication.test.tsx
@@ -2,8 +2,8 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
import type { PropsWithChildren, ReactNode } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { MentionResolutionProvider, useResolvedMentionUsernames, useResolvedUser } from "@/components/MemoContent/MentionResolutionContext";
import { useResolvedRelationMemos } from "@/components/MemoMetadata/Relation/useResolvedRelationMemos";
+import { MentionResolutionProvider, useResolvedMentionUsernames, useResolvedUser } from "@/contexts/MentionResolutionContext";
import { memoKeys } from "@/hooks/useMemoQueries";
import { useMemoViews, userKeys, useUser, useUsersByNames, useUsersByUsernames } from "@/hooks/useUserQueries";
import type { Memo } from "@/types/proto/api/memo_service_pb";
diff --git a/web/tests/search-match-highlight.test.tsx b/web/tests/search-match-highlight.test.tsx
index aeea40887..8a78b2b7a 100644
--- a/web/tests/search-match-highlight.test.tsx
+++ b/web/tests/search-match-highlight.test.tsx
@@ -1,7 +1,7 @@
import { render, waitFor } from "@testing-library/react";
import { useRef } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { SEARCH_MATCH_HIGHLIGHT_NAME, useSearchMatchHighlight } from "@/components/MemoContent/useSearchMatchHighlight";
+import { SEARCH_MATCH_HIGHLIGHT_NAME, useSearchMatchHighlight } from "@/components/MemoEditor/view/useSearchMatchHighlight";
// jsdom has no CSS Custom Highlight API; a Set-backed Highlight and a Map registry are
// exactly the surface the hook uses (add/delete on the highlight, get/set on the registry).
diff --git a/web/tests/transcription-service.test.ts b/web/tests/transcription-service.test.ts
index 384d39cca..9197603d2 100644
--- a/web/tests/transcription-service.test.ts
+++ b/web/tests/transcription-service.test.ts
@@ -5,7 +5,7 @@ import { AttachmentSchema } from "@/types/proto/api/attachment_service_pb";
const { transcribe } = vi.hoisted(() => ({ transcribe: vi.fn() }));
vi.mock("@/connect", () => ({ aiServiceClient: { transcribe } }));
-import { transcriptionService } from "@/components/MemoEditor/services/transcriptionService";
+import { transcriptionService } from "@/components/MemoEditor/edit/services/transcriptionService";
const audio = create(AttachmentSchema, { name: "attachments/voice", filename: "voice.wav", type: "audio/wav", size: 3n });
diff --git a/web/tests/upload-media-metadata.test.ts b/web/tests/upload-media-metadata.test.ts
index e24a81074..b3b7b95e2 100644
--- a/web/tests/upload-media-metadata.test.ts
+++ b/web/tests/upload-media-metadata.test.ts
@@ -1,6 +1,6 @@
import { create } from "@bufbuild/protobuf";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import type { LocalFile } from "@/components/MemoEditor/types/attachment";
+import type { LocalFile } from "@/components/MemoEditor/edit/types/attachment";
import { MediaMetadataSchema } from "@/types/proto/api/attachment_service_pb";
const mocks = vi.hoisted(() => ({
@@ -17,12 +17,12 @@ vi.mock("@/connect", () => ({
refreshAccessToken: vi.fn(),
}));
-vi.mock("@/components/MemoEditor/services/mediaMetadataService", () => ({
+vi.mock("@/components/MemoEditor/edit/services/mediaMetadataService", () => ({
mediaMetadataService: { extract: mocks.extractMetadata },
}));
-import { toLocalFiles } from "@/components/MemoEditor/hooks/useFileUpload";
-import { uploadService } from "@/components/MemoEditor/services/uploadService";
+import { toLocalFiles } from "@/components/MemoEditor/edit/hooks/useFileUpload";
+import { uploadService } from "@/components/MemoEditor/edit/services/uploadService";
const createBlobUrl = (file: File) => `blob:${file.name}`;
diff --git a/web/tests/upload-service.test.ts b/web/tests/upload-service.test.ts
index 0ec9d5e3f..585a1d425 100644
--- a/web/tests/upload-service.test.ts
+++ b/web/tests/upload-service.test.ts
@@ -6,7 +6,7 @@ import { AttachmentSchema } from "@/types/proto/api/attachment_service_pb";
const { uploadAttachment } = vi.hoisted(() => ({ uploadAttachment: vi.fn() }));
vi.mock("@/connect", () => ({ attachmentServiceClient: { uploadAttachment } }));
-import { uploadService } from "@/components/MemoEditor/services/uploadService";
+import { uploadService } from "@/components/MemoEditor/edit/services/uploadService";
const attachment = create(AttachmentSchema, { name: "attachments/uploaded" });
const localFile = (content: string) => ({
diff --git a/web/tests/usage-limit-errors.test.ts b/web/tests/usage-limit-errors.test.ts
index 60f4d33cf..85a353602 100644
--- a/web/tests/usage-limit-errors.test.ts
+++ b/web/tests/usage-limit-errors.test.ts
@@ -1,7 +1,7 @@
import { BinaryWriter } from "@bufbuild/protobuf/wire";
import { Code, ConnectError } from "@connectrpc/connect";
import { describe, expect, it } from "vitest";
-import { errorService } from "@/components/MemoEditor/services/errorService";
+import { errorService } from "@/components/MemoEditor/edit/services/errorService";
import { ERROR_REASON_QUOTA_EXCEEDED, getErrorMessage, getRetryAfterSeconds } from "@/lib/error";
function quotaError(metadata: Record<string, string>): ConnectError {
diff --git a/web/tests/use-attachment-transcription.test.tsx b/web/tests/use-attachment-transcription.test.tsx
index c9ba0c3ab..775761273 100644
--- a/web/tests/use-attachment-transcription.test.tsx
+++ b/web/tests/use-attachment-transcription.test.tsx
@@ -3,8 +3,8 @@ import { Code, ConnectError } from "@connectrpc/connect";
import { act, renderHook } from "@testing-library/react";
import { toast } from "react-hot-toast";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { useAttachmentTranscription } from "@/components/MemoEditor/hooks/useAttachmentTranscription";
-import { transcriptionService } from "@/components/MemoEditor/services";
+import { useAttachmentTranscription } from "@/components/MemoEditor/edit/hooks/useAttachmentTranscription";
+import { transcriptionService } from "@/components/MemoEditor/edit/services";
import { AttachmentSchema } from "@/types/proto/api/attachment_service_pb";
vi.mock("react-hot-toast", () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
diff --git a/web/tests/use-auto-save.test.tsx b/web/tests/use-auto-save.test.tsx
index 7ae555669..d5e199acc 100644
--- a/web/tests/use-auto-save.test.tsx
+++ b/web/tests/use-auto-save.test.tsx
@@ -1,9 +1,9 @@
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 { useAutoSave } from "@/components/MemoEditor/edit/hooks/useAutoSave";
+import { cacheService } from "@/components/MemoEditor/edit/services/cacheService";
+import { EditorProvider, useEditorContext } from "@/components/MemoEditor/edit/state";
import { AttachmentSchema } from "@/types/proto/api/attachment_service_pb";
import { Visibility } from "@/types/proto/api/memo_service_pb";
@@ -17,7 +17,7 @@ let api: {
function Probe({ username, cacheKey, enabled }: { username: string; cacheKey?: string; enabled?: boolean }) {
const { dispatch, actions } = useEditorContext();
- const { discardDraft } = useAutoSave(username, cacheKey, enabled);
+ const { discardDraft } = useAutoSave(cacheService.key(username, cacheKey), enabled);
api = { dispatch, actions, discardDraft };
return null;
}
diff --git a/web/tests/use-inline-image-upload.test.tsx b/web/tests/use-inline-image-upload.test.tsx
index 77108e719..1da3b5599 100644
--- a/web/tests/use-inline-image-upload.test.tsx
+++ b/web/tests/use-inline-image-upload.test.tsx
@@ -2,12 +2,12 @@ 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 { useInlineImageUpload } from "@/components/MemoEditor/edit/hooks/useInlineImageUpload";
+import { uploadService } from "@/components/MemoEditor/edit/services";
+import { EditorProvider, useEditorContext } from "@/components/MemoEditor/edit/state";
+import type { LocalFile } from "@/components/MemoEditor/edit/types/attachment";
+import type { EditorController } from "@/components/MemoEditor/edit/types/editorController";
+import type { UploadAnchorDescriptor } from "@/components/MemoEditor/edit/uploadAnchors";
import { AttachmentSchema } from "@/types/proto/api/attachment_service_pb";
vi.mock("@/utils/i18n", async (importOriginal) => ({
diff --git a/web/tests/use-memo-init.test.tsx b/web/tests/use-memo-init.test.tsx
index 86261a835..9edb83b04 100644
--- a/web/tests/use-memo-init.test.tsx
+++ b/web/tests/use-memo-init.test.tsx
@@ -1,45 +1,47 @@
import { create } from "@bufbuild/protobuf";
-import { act, render, waitFor } from "@testing-library/react";
+import { act, render } from "@testing-library/react";
import type { EditorMode } from "@usememos/editor";
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 { useMemoInit } from "@/components/MemoEditor/edit/hooks/useMemoInit";
+import { initialEditorState } from "@/components/MemoEditor/edit/initialState";
+import { cacheService } from "@/components/MemoEditor/edit/services/cacheService";
+import { EditorProvider, useEditorContext } from "@/components/MemoEditor/edit/state";
+import type { EditorController } from "@/components/MemoEditor/edit/types/editorController";
import { AttachmentSchema } from "@/types/proto/api/attachment_service_pb";
-
-import { type Location, LocationSchema, Visibility } from "@/types/proto/api/memo_service_pb";
+import { type Location, LocationSchema, MemoSchema, Visibility } from "@/types/proto/api/memo_service_pb";
const editorRef = { current: null } as RefObject<EditorController | null>;
+const draftKey = cacheService.key("users/steven", "restored-draft");
let getEditorState: ReturnType<typeof useEditorContext>["getState"];
-function Probe({
- autoFocus,
- defaultLocation,
- canChooseSpace,
- mode = "rich",
-}: {
- autoFocus?: boolean | (() => boolean);
- defaultLocation?: Location;
- canChooseSpace?: boolean;
- mode?: EditorMode;
-}) {
+function Probe({ autoFocus, mode = "rich" }: { autoFocus?: boolean | (() => boolean); mode?: EditorMode }) {
getEditorState = useEditorContext().getState;
- useMemoInit({
- editorRef,
- username: "users/steven",
- cacheKey: "restored-draft",
- autoFocus,
- defaultLocation,
- canChooseSpace,
- defaultVisibility: Visibility.PUBLIC,
- mode,
- });
+ useMemoInit({ editorRef, draftKey, autoFocus, mode });
return null;
}
-describe("useMemoInit", () => {
+/** Mounts a session the way MemoEditor does: the draft read once, then the caret restored. */
+const mountSession = (props: {
+ autoFocus?: boolean | (() => boolean);
+ mode?: EditorMode;
+ defaultLocation?: Location;
+ canChooseSpace?: boolean;
+}) =>
+ render(
+ <EditorProvider
+ initialEditorState={initialEditorState({
+ draftKey,
+ defaultVisibility: Visibility.PUBLIC,
+ defaultLocation: props.defaultLocation,
+ canChooseSpace: props.canChooseSpace,
+ })}
+ >
+ <Probe autoFocus={props.autoFocus} mode={props.mode} />
+ </EditorProvider>,
+ );
+
+describe("the initial draft and useMemoInit", () => {
beforeEach(() => {
const storage = new Map<string, string>();
vi.stubGlobal("localStorage", {
@@ -58,10 +60,9 @@ describe("useMemoInit", () => {
it.each([true, false])("restores the draft and cursor before evaluating autofocus (%s)", (allowed) => {
vi.useFakeTimers();
- const key = cacheService.key("users/steven", "restored-draft");
- cacheService.saveNow(key, { content: "An unfinished memo", attachments: [] });
+ cacheService.saveNow(draftKey, { content: "An unfinished memo", attachments: [] });
const selection = { anchor: { block: 0, offset: 5 }, focus: { block: 0, offset: 5 } };
- cacheService.saveCursor(key, selection, "rich");
+ cacheService.saveCursor(draftKey, selection, "rich");
const focus = vi.fn();
const setSelection = vi.fn();
editorRef.current = { focus, setSelection } as unknown as EditorController;
@@ -71,11 +72,8 @@ describe("useMemoInit", () => {
return allowed;
});
- render(
- <EditorProvider>
- <Probe autoFocus={autoFocus} />
- </EditorProvider>,
- );
+ mountSession({ autoFocus });
+ expect(getEditorState().content).toBe("An unfinished memo");
expect(autoFocus).not.toHaveBeenCalled();
act(() => vi.advanceTimersByTime(100));
expect(autoFocus).toHaveBeenCalledOnce();
@@ -84,17 +82,12 @@ describe("useMemoInit", () => {
it("does not restore a cursor taken in the other editor mode", () => {
vi.useFakeTimers();
- const key = cacheService.key("users/steven", "restored-draft");
- cacheService.saveNow(key, { content: "An unfinished memo", attachments: [] });
- cacheService.saveCursor(key, { anchor: { block: 0, offset: 12 }, focus: { block: 0, offset: 12 } }, "source");
+ cacheService.saveNow(draftKey, { content: "An unfinished memo", attachments: [] });
+ cacheService.saveCursor(draftKey, { anchor: { block: 0, offset: 12 }, focus: { block: 0, offset: 12 } }, "source");
const setSelection = vi.fn();
editorRef.current = { focus: vi.fn(), setSelection } as unknown as EditorController;
- render(
- <EditorProvider>
- <Probe mode="rich" />
- </EditorProvider>,
- );
+ mountSession({ mode: "rich" });
act(() => vi.advanceTimersByTime(100));
expect(getEditorState().content).toBe("An unfinished memo");
expect(setSelection).not.toHaveBeenCalled();
@@ -102,69 +95,46 @@ describe("useMemoInit", () => {
it("seeds a new location once and honors a restored removal", () => {
const point = create(LocationSchema, { latitude: 35, longitude: 135, placeholder: "Cafe" });
- const { unmount, rerender } = render(
- <EditorProvider>
- <Probe defaultLocation={point} />
- </EditorProvider>,
- );
- expect(getEditorState().metadata.location).toEqual(point);
- rerender(
- <EditorProvider>
- <Probe defaultLocation={create(LocationSchema, { latitude: 1 })} />
- </EditorProvider>,
- );
+ const { unmount } = mountSession({ defaultLocation: point });
expect(getEditorState().metadata.location).toEqual(point);
unmount();
- cacheService.saveNow(cacheService.key("users/steven", "restored-draft"), {
- content: "Draft without a location",
- attachments: [],
- location: null,
- });
- render(
- <EditorProvider>
- <Probe defaultLocation={point} />
- </EditorProvider>,
- );
+ cacheService.saveNow(draftKey, { content: "Draft without a location", attachments: [], location: null });
+ mountSession({ defaultLocation: point });
expect(getEditorState().metadata.location).toBeUndefined();
});
it.each([true, false])("restores destination only when the composer can choose a Space (%s)", (canChooseSpace) => {
- cacheService.saveNow(cacheService.key("users/steven", "restored-draft"), {
+ cacheService.saveNow(draftKey, {
content: "Draft",
attachments: [],
location: null,
space: "spaces/work",
visibility: Visibility.PRIVATE,
});
- render(
- <EditorProvider>
- <Probe canChooseSpace={canChooseSpace} />
- </EditorProvider>,
- );
+ mountSession({ canChooseSpace });
expect(getEditorState().metadata.space).toBe(canChooseSpace ? "spaces/work" : undefined);
expect(getEditorState().metadata.visibility).toBe(Visibility.PRIVATE);
});
- 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"), {
- content: "![image](/file/attachments/image-one)",
- attachments: [attachment],
- });
+ it("restores uploaded attachment bindings with a new memo draft", () => {
+ const attachment = create(AttachmentSchema, { name: "attachments/image-one", filename: "image.png", type: "image/png" });
+ cacheService.saveNow(draftKey, { content: "![image](/file/attachments/image-one)", attachments: [attachment] });
- render(
- <EditorProvider>
- <Probe />
- </EditorProvider>,
- );
+ mountSession({});
- await waitFor(() => {
- expect(getEditorState().content).toBe("![image](/file/attachments/image-one)");
- expect(getEditorState().metadata.attachments).toEqual([attachment]);
- });
+ expect(getEditorState().content).toBe("![image](/file/attachments/image-one)");
+ expect(getEditorState().metadata.attachments).toEqual([attachment]);
+ });
+
+ it("starts an edit from the memo and drops any draft under its key", () => {
+ cacheService.saveNow(draftKey, { content: "stale draft", attachments: [] });
+ const memo = create(MemoSchema, { name: "memos/one", content: "The memo", visibility: Visibility.PUBLIC, space: "spaces/work" });
+
+ const state = initialEditorState({ memo, draftKey, initialFocusMode: true });
+
+ expect(state.content).toBe("The memo");
+ expect(state.metadata.space).toBe("spaces/work");
+ expect(state.ui.isFocusMode).toBe(true);
+ expect(cacheService.loadDraft(draftKey).content).toBe("");
});
});
diff --git a/web/tests/use-memo-save.test.tsx b/web/tests/use-memo-save.test.tsx
index d36ac142a..7a1e93668 100644
--- a/web/tests/use-memo-save.test.tsx
+++ b/web/tests/use-memo-save.test.tsx
@@ -2,23 +2,29 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { act, renderHook } from "@testing-library/react";
import type { PropsWithChildren } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { useMemoSave } from "@/components/MemoEditor/hooks/useMemoSave";
+import { useMemoSave } from "@/components/MemoEditor/edit/hooks/useMemoSave";
const mocks = vi.hoisted(() => ({
dispatch: vi.fn(),
markNewMemo: vi.fn(),
memoSave: vi.fn(),
+ createMemo: vi.fn(),
+ createMemoComment: vi.fn(),
newMemoName: null as string | null,
timestamps: {} as { createTime?: Date; updateTime?: Date },
}));
-vi.mock("@/components/MemoEditor/services", () => ({
+vi.mock("@/connect", () => ({
+ memoServiceClient: { createMemo: mocks.createMemo, createMemoComment: mocks.createMemoComment },
+}));
+
+vi.mock("@/components/MemoEditor/edit/services", () => ({
errorService: { getErrorMessage: () => "save failed" },
memoService: { save: mocks.memoSave },
validationService: { canSave: () => ({ valid: true }) },
}));
-vi.mock("@/components/MemoEditor/state", () => ({
+vi.mock("@/components/MemoEditor/edit/state", () => ({
useEditorContext: () => ({
actions: {
reset: () => ({ type: "reset" }),
@@ -53,7 +59,12 @@ describe("useMemoSave", () => {
});
it("invalidates scoped attachment libraries after a memo save", async () => {
- mocks.memoSave.mockResolvedValue({ hasChanges: true, memoName: "memos/new" });
+ // The service hands the create to the memo mutation, whose hook refreshes the caches.
+ mocks.createMemo.mockResolvedValue({ name: "memos/new" });
+ mocks.memoSave.mockImplementation(async (_state, _options, operations) => {
+ const memo = await operations.createMemo({ name: "" });
+ return { hasChanges: true, memoName: memo.name };
+ });
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const invalidateQueries = vi.spyOn(queryClient, "invalidateQueries");
const wrapper = ({ children }: PropsWithChildren) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
@@ -68,7 +79,11 @@ describe("useMemoSave", () => {
});
it("refreshes the parent memo total after creating a comment", async () => {
- mocks.memoSave.mockResolvedValue({ hasChanges: true, memoName: "memos/comment" });
+ mocks.createMemoComment.mockResolvedValue({ name: "memos/comment", parent: "memos/parent" });
+ mocks.memoSave.mockImplementation(async (_state, options, operations) => {
+ const memo = await operations.createMemo({ name: "" }, options.parentMemoName);
+ return { hasChanges: true, memoName: memo.name };
+ });
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const invalidateQueries = vi.spyOn(queryClient, "invalidateQueries");
const wrapper = ({ children }: PropsWithChildren) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;