Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.
Go dockerfossgomarkdownmemomicroblognote-takingnotesopen-sourceown-your-datareactself-hostedsqlitetimeline
feat(web): add source mode to the memo composer
johnnyjoygh1a51572406e1
diff --git a/web/src/components/AppSidebar/TagsSection.tsx b/web/src/components/AppSidebar/TagsSection.tsxindex 044a3c23a..a4129cebc 100644--- a/web/src/components/AppSidebar/TagsSection.tsx+++ b/web/src/components/AppSidebar/TagsSection.tsx@@ -120,12 +120,7 @@ const TagsSection = ({ tagCount, onSelect, scope }: Props) => {<DropdownMenuContent align="end" sideOffset={4} size="sm" className="w-44"><DropdownMenuGroup><DropdownMenuLabel className="text-muted-foreground">{t("common.tags")}</DropdownMenuLabel>- <DropdownMenuCheckboxItem- checked={treeMode}- onCheckedChange={setTreeMode}- closeOnClick- className="ps-2 pe-7 [&>span]:start-auto [&>span]:end-2"- >+ <DropdownMenuCheckboxItem checked={treeMode} onCheckedChange={setTreeMode} closeOnClick indicator="end"><ListTreeIcon className="text-muted-foreground" strokeWidth={1.8} />{t("common.tree-mode")}</DropdownMenuCheckboxItem>diff --git a/web/src/components/MemoEditor/Editor/controller.ts b/web/src/components/MemoEditor/Editor/controller.tsindex 84134be33..469b4111e 100644--- a/web/src/components/MemoEditor/Editor/controller.ts+++ b/web/src/components/MemoEditor/Editor/controller.ts@@ -1,5 +1,5 @@import { type Block, containerContent, type Editor, getBlock, inlineText, type Position, type Widget } from "@usememos/editor";-import { collectTags } from "@/lib/memo-markdown";+import { collectTags, parseMemoMarkdown } from "@/lib/memo-markdown";import { isCompleteTagValue } from "@/utils/tag-grammar";import type { EditorController } from "../types/editorController";import { renderUploadAnchor } from "./uploadAnchors";@@ -18,6 +18,13 @@ const textAt = (editor: Editor, position: Position): string => {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.+ */+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. */const isEmptyParagraph = (block: Block): boolean => block.type === "paragraph" && inlineText(block.content) === "";@@ -43,7 +50,7 @@ const insertBlocks = (editor: Editor, markdown: string, position: Position): voi*/export function createController(getEditor: EditorGetter, onReplace: (markdown: string) => void): EditorController {const anchors = new Map<string, Widget>();- const currentTags = (editor: Editor) => collectTags(editor.state.doc.blocks);+ const currentTags = (editor: Editor) => collectTags(memoBlocks(editor));const takeAnchor = (id: string): Widget | undefined => {const widget = anchors.get(id);@@ -76,7 +83,10 @@ export function createController(getEditor: EditorGetter, onReplace: (markdown:const editor = live(getEditor);return editor ? currentTags(editor) : [];},- hasChecklist: () => live(getEditor)?.state.doc.blocks.some((block) => block.type === "listItem" && block.listType === "task") ?? false,+ hasChecklist: () => {+ const editor = live(getEditor);+ return editor ? memoBlocks(editor).some((block) => block.type === "listItem" && block.listType === "task") : false;+ },insertTag: (tag) => {const editor = live(getEditor);if (!editor || !isCompleteTagValue(tag) || editor.isComposing || currentTags(editor).includes(tag)) return false;diff --git a/web/src/components/MemoEditor/Editor/editor.css b/web/src/components/MemoEditor/Editor/editor.cssindex 20042cf73..169667cd3 100644--- a/web/src/components/MemoEditor/Editor/editor.css+++ b/web/src/components/MemoEditor/Editor/editor.css@@ -26,6 +26,14 @@& .memo-editor-root ::selection {background: var(--accent);}+ /* Source mode: the first line leaves room for the tag EditorContent puts in the corner. */+ &[data-source-mode] .memo-editor-root::before {+ content: "";+ float: inline-end;+ /* The tag's width plus a gap, so the first line never runs into it. */+ width: calc(var(--memo-source-tag-width, 0px) + 0.5rem);+ height: 1lh;+ }}.memo-upload-anchor {diff --git a/web/src/components/MemoEditor/Editor/index.tsx b/web/src/components/MemoEditor/Editor/index.tsxindex 85b542af9..c2d31f442 100644--- a/web/src/components/MemoEditor/Editor/index.tsx+++ b/web/src/components/MemoEditor/Editor/index.tsx@@ -1,4 +1,4 @@-import type { Editor as MarkdownEditorInstance } from "@usememos/editor";+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";@@ -24,6 +24,8 @@ interface EditorProps {/** Invoked by the in-editor save shortcut (Cmd/Ctrl+Enter). */onSubmit: () => void;isFocusMode?: boolean;+ /** Rich text, or the whole memo as Markdown text. Switching changes no text. */+ 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. */@@ -40,7 +42,7 @@ const EDITOR_ATTRIBUTES = {};const Editor = forwardRef(function Editor(props: EditorProps, ref: React.ForwardedRef<EditorController>) {- const { className, value, placeholder, onContentChange, onFiles, onSubmit, isFocusMode, attachments, tagsSetting } = props;+ const { className, value, placeholder, onContentChange, onFiles, onSubmit, isFocusMode, mode, attachments, tagsSetting } = props;const t = useTranslate();const editorRef = useRef<MarkdownEditorInstance | null>(null);const onContentChangeRef = useRef(onContentChange);@@ -119,6 +121,7 @@ const Editor = forwardRef(function Editor(props: EditorProps, ref: React.Forward<divclassName={cn("relative flex w-full flex-col items-start justify-start bg-inherit", isFocusMode && "min-h-0 flex-1", className)}data-focus-mode={isFocusMode || undefined}+ data-source-mode={mode === "source" || undefined}><div className={cn("memo-editor-scroller w-full text-base", isFocusMode && "min-h-0 flex-1")}><MarkdownEditor@@ -127,6 +130,7 @@ const Editor = forwardRef(function Editor(props: EditorProps, ref: React.ForwardonChange={onContentChange}onSubmit={() => onSubmitRef.current()}placeholder={placeholder}+ mode={mode}markdown={MEMO_MARKDOWN}extensions={extensions}theme={MEMO_EDITOR_THEME}diff --git a/web/src/components/MemoEditor/README.md b/web/src/components/MemoEditor/README.mdindex db9ccfe67..b3e45f389 100644--- a/web/src/components/MemoEditor/README.md+++ b/web/src/components/MemoEditor/README.md@@ -41,6 +41,7 @@ MemoEditor/│ └── ...├── 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@@ -74,6 +75,14 @@ A reducer (`state/reducer.ts`) drives an **external store**, not a `useReducer`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.+### 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.@@ -121,7 +130,7 @@ 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 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.### Destination and visibilitydiff --git a/web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx b/web/src/components/MemoEditor/Toolbar/EditorToolbar.tsxindex 9aa9751e8..60ce41c27 100644--- a/web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx+++ b/web/src/components/MemoEditor/Toolbar/EditorToolbar.tsx@@ -32,6 +32,7 @@ export const EditorToolbar: FC<EditorToolbarProps> = ({canChooseSpace,onAudioRecorderClick,viewToggles,+ sourceMode,onInsertImages,}) => {const t = useTranslate();@@ -121,6 +122,7 @@ export const EditorToolbar: FC<EditorToolbarProps> = ({memoName={memoName}onAudioRecorderClick={onAudioRecorderClick}viewToggles={viewToggles}+ sourceMode={sourceMode}onInsertImages={onInsertImages}/><AudienceMenudiff --git a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsxindex e1340f23e..b8788a9d4 100644--- a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx+++ b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx@@ -1,5 +1,5 @@import { uniqBy } from "lodash-es";-import { ImageIcon, LinkIcon, LoaderIcon, MapPinIcon, Maximize2Icon, MicIcon, PaperclipIcon, PlusIcon } from "lucide-react";+import { FileCodeIcon, ImageIcon, LinkIcon, LoaderIcon, MapPinIcon, Maximize2Icon, MicIcon, PaperclipIcon, PlusIcon } from "lucide-react";import { useCallback, useEffect, useRef, useState } from "react";import { LinkMemoDialog, LocationDialog } from "@/components/MemoMetadata";import type { MapPoint } from "@/components/map/types";@@ -7,6 +7,7 @@ import { useReverseGeocoding } from "@/components/map/useReverseGeocoding";import { Button } from "@/components/ui/button";import {DropdownMenu,+ DropdownMenuCheckboxItem,DropdownMenuContent,DropdownMenuItem,DropdownMenuSeparator,@@ -24,7 +25,7 @@ const InsertMenu = (props: InsertMenuProps) => {const t = useTranslate();const { actions, dispatch, getState } = useEditorContext();const relations = useEditorSelector((s) => s.metadata.relations);- const { location: initialLocation, onLocationChange, viewToggles, isUploading: isUploadingProp } = props;+ const { location: initialLocation, onLocationChange, viewToggles, sourceMode, isUploading: isUploadingProp } = props;const [linkDialogOpen, setLinkDialogOpen] = useState(false);const [locationDialogOpen, setLocationDialogOpen] = useState(false);@@ -157,16 +158,19 @@ const InsertMenu = (props: InsertMenuProps) => {{item.label}</DropdownMenuItem>))}- {/* View toggle: focus mode. Absent when a host owns the editor's presentation. */}+ {/* View toggles. Focus mode is absent when a host owns the editor's presentation;+ source mode only changes how the text is edited, so every composer has it. */}+ <DropdownMenuSeparator />{viewToggles && (- <>- <DropdownMenuSeparator />- <DropdownMenuItem onClick={viewToggles.onToggleFocusMode}>- <Maximize2Icon />- {t("editor.focus-mode")}- </DropdownMenuItem>- </>+ <DropdownMenuItem onClick={viewToggles.onToggleFocusMode}>+ <Maximize2Icon />+ {t("editor.focus-mode")}+ </DropdownMenuItem>)}+ <DropdownMenuCheckboxItem checked={sourceMode.isSourceMode} onCheckedChange={sourceMode.onToggle} closeOnClick indicator="end">+ <FileCodeIcon />+ {t("editor.source-mode")}+ </DropdownMenuCheckboxItem></DropdownMenuContent></DropdownMenu>diff --git a/web/src/components/MemoEditor/components/EditorContent.tsx b/web/src/components/MemoEditor/components/EditorContent.tsxindex 606a6195b..7ddde9301 100644--- a/web/src/components/MemoEditor/components/EditorContent.tsx+++ b/web/src/components/MemoEditor/components/EditorContent.tsx@@ -1,4 +1,6 @@-import { forwardRef } from "react";+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";@@ -13,32 +15,64 @@ import type { EditorController } from "../types/editorController";* Hosts the Markdown Editor behind the EditorController contract. The* editor writes into state.content on every change.*/-export const EditorContent = forwardRef<EditorController, EditorContentProps>(({ placeholder, onSubmit, onFiles, tagsSetting }, ref) => {- const { actions, dispatch } = useEditorContext();- const content = useEditorSelector((s) => s.content);- const isFocusMode = useEditorSelector((s) => s.ui.isFocusMode);- const attachments = useEditorSelector((s) => s.metadata.attachments);+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));- };+ const handleContentChange = (content: string) => {+ dispatch(actions.updateContent(content));+ };- return (- <div className="w-full flex flex-col flex-1">- <Editor- ref={ref}- className="memo-editor-content"- value={content}- placeholder={placeholder || ""}- isFocusMode={isFocusMode}- attachments={attachments}- tagsSetting={tagsSetting}- onContentChange={handleContentChange}- onFiles={onFiles}- onSubmit={onSubmit}- />- </div>- );-});+ 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/hooks/index.ts b/web/src/components/MemoEditor/hooks/index.tsindex 9cc80fa41..ae0d034ce 100644--- a/web/src/components/MemoEditor/hooks/index.ts+++ b/web/src/components/MemoEditor/hooks/index.ts@@ -12,3 +12,4 @@ export { useLinkMemo } from "./useLinkMemo";export { useLocation } from "./useLocation";export { useMemoInit } from "./useMemoInit";export { useMemoSave } from "./useMemoSave";+export { useSourceMode } from "./useSourceMode";diff --git a/web/src/components/MemoEditor/hooks/useMemoInit.ts b/web/src/components/MemoEditor/hooks/useMemoInit.tsindex f243a4793..add599a35 100644--- a/web/src/components/MemoEditor/hooks/useMemoInit.ts+++ b/web/src/components/MemoEditor/hooks/useMemoInit.ts@@ -1,3 +1,4 @@+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";@@ -14,6 +15,8 @@ interface UseMemoInitOptions {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 = ({@@ -26,6 +29,7 @@ export const useMemoInit = ({defaultCreateTime,defaultLocation,canChooseSpace = false,+ mode,}: UseMemoInitOptions) => {const { actions, dispatch } = useEditorContext();const initializedRef = useRef(false);@@ -61,7 +65,7 @@ export const useMemoInit = ({}}- const cachedCursor = cacheService.loadCursor(key);+ const cachedCursor = cacheService.loadCursor(key, mode);let restoreCursorTimer: ReturnType<typeof setTimeout> | undefined;if (autoFocus || cachedCursor !== undefined) {restoreCursorTimer = setTimeout(() => {@@ -89,6 +93,7 @@ export const useMemoInit = ({defaultCreateTime,defaultLocation,canChooseSpace,+ mode,actions,dispatch,editorRef,diff --git a/web/src/components/MemoEditor/hooks/useSourceMode.ts b/web/src/components/MemoEditor/hooks/useSourceMode.tsnew file mode 100644index 000000000..a6e4f1c78--- /dev/null+++ b/web/src/components/MemoEditor/hooks/useSourceMode.ts@@ -0,0 +1,7 @@+import type { EditorMode } from "@usememos/editor";+import { useLocalStorage } from "@/hooks/useLocalStorage";++const STORAGE_KEY = "memos-editor-mode";++/** The composer's editing mode, remembered per device and shared by every composer. */+export const useSourceMode = () => useLocalStorage<EditorMode>(STORAGE_KEY, "rich");diff --git a/web/src/components/MemoEditor/index.tsx b/web/src/components/MemoEditor/index.tsxindex 31dd33667..d031149b7 100644--- a/web/src/components/MemoEditor/index.tsx+++ b/web/src/components/MemoEditor/index.tsx@@ -23,6 +23,7 @@ import {useInlineImageUpload,useMemoInit,useMemoSave,+ useSourceMode,} from "./hooks";import { cacheService, errorService, transcriptionService } from "./services";import { EditorProvider, useEditorContext, useEditorSelector } from "./state";@@ -97,6 +98,11 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({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,@@ -107,6 +113,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({defaultCreateTime,defaultLocation,canChooseSpace,+ mode: editorMode,});const isDraftCacheEnabled = !memo;@@ -224,9 +231,9 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({const rememberCursor = useCallback(() => {const cursor = editorRef.current?.getSelection();if (cursor !== undefined) {- cacheService.saveCursor(editorCacheKey, cursor);+ cacheService.saveCursor(editorCacheKey, cursor, editorMode);}- }, [editorCacheKey]);+ }, [editorCacheKey, 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.@@ -313,6 +320,9 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({onToggleFocusMode: handleToggleFocusMode,};+ // The checklist chip formats a block, which source mode cannot do.+ const visibleSuggestions = isSourceMode ? suggestions.filter((suggestion) => suggestion.kind !== "checklist") : suggestions;+const handleSave = useMemoSave({memoName,parentMemoName,@@ -366,6 +376,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({<EditorContentref={editorRef}placeholder={placeholder}+ sourceMode={sourceMode}onSubmit={handleSave}onFiles={handleEditorFiles}tagsSetting={userTagsSetting}@@ -394,8 +405,8 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({transcribingAttachment={transcribingAttachment}transcriptionDisabled={isSaving || audioRecorder.isBusy || isTranscribingAudio}/>- {!memo && !parentMemoName && isInitialized && suggestions.length > 0 && (- <EditorSuggestions suggestions={suggestions} controllerRef={editorRef} space={editorSpace} />+ {!memo && !parentMemoName && isInitialized && visibleSuggestions.length > 0 && (+ <EditorSuggestions suggestions={visibleSuggestions} controllerRef={editorRef} space={editorSpace} />)}<EditorToolbaronSave={handleSave}@@ -406,6 +417,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({canChooseSpace={canChooseSpace}onAudioRecorderClick={handleAudioRecorderClick}viewToggles={viewToggles}+ sourceMode={sourceMode}onInsertImages={handleInsertImages}/></div>diff --git a/web/src/components/MemoEditor/services/cacheService.ts b/web/src/components/MemoEditor/services/cacheService.tsindex ae67801a7..fc21d5f0b 100644--- a/web/src/components/MemoEditor/services/cacheService.ts+++ b/web/src/components/MemoEditor/services/cacheService.ts@@ -1,4 +1,5 @@import { fromJson, type JsonValue, toJson } from "@bufbuild/protobuf";+import type { EditorMode } from "@usememos/editor";import type { Attachment } from "@/types/proto/api/attachment_service_pb";import { AttachmentSchema } from "@/types/proto/api/attachment_service_pb";@@ -8,7 +9,8 @@ import type { EditorSelection } from "../types/editorController";export const CACHE_DEBOUNCE_DELAY = 500;const pendingSaves = new Map<string, number>();-const cursors = new Map<string, EditorSelection>();+// A selection's shape depends on the editor mode it was taken in, so each one keeps its mode.+const cursors = new Map<string, { selection: EditorSelection; mode: EditorMode }>();const STRUCTURED_CACHE_ENTRY_KIND = "memos.editor-cache";const STRUCTURED_CACHE_ENTRY_VERSION = 3;@@ -135,12 +137,14 @@ export const cacheService = {return raw ? deserializeDraft(raw) : { content: "", attachments: [] };},- saveCursor(key: string, cursor: EditorSelection): void {- cursors.set(key, cursor);+ saveCursor(key: string, selection: EditorSelection, mode: EditorMode): void {+ cursors.set(key, { selection, mode });},- loadCursor(key: string): EditorSelection | undefined {- return cursors.get(key);+ /** The caret saved for `key`, unless it was taken in another editor mode. */+ loadCursor(key: string, mode: EditorMode): EditorSelection | undefined {+ const cursor = cursors.get(key);+ return cursor?.mode === mode ? cursor.selection : undefined;},clear(key: string): void {diff --git a/web/src/components/MemoEditor/types/components.ts b/web/src/components/MemoEditor/types/components.tsindex 556884b35..656b5d1dd 100644--- a/web/src/components/MemoEditor/types/components.ts+++ b/web/src/components/MemoEditor/types/components.ts@@ -50,6 +50,7 @@ export interface MemoEditorProps {export interface EditorContentProps {placeholder?: string;+ sourceMode: EditorSourceModeToggle;/** Invoked by the in-editor save shortcut (Cmd/Ctrl+Enter). */onSubmit: () => void;onFiles: (files: File[], origin: EditorFileOrigin) => void;@@ -65,6 +66,12 @@ export interface EditorViewToggles {onToggleFocusMode: () => void;}+/** The composer's source-mode switch: an item in the + menu, and a tag in the editor's corner while on. */+export interface EditorSourceModeToggle {+ isSourceMode: boolean;+ onToggle: () => void;+}+export interface EditorToolbarProps {onSave: () => void;onCancel?: () => void;@@ -77,6 +84,7 @@ export interface EditorToolbarProps {canChooseSpace?: boolean;onAudioRecorderClick: () => void;viewToggles?: EditorViewToggles;+ sourceMode: EditorSourceModeToggle;onInsertImages: (files: File[]) => void;}@@ -120,6 +128,7 @@ export interface InsertMenuProps {memoName?: string;onAudioRecorderClick?: () => void;viewToggles?: EditorViewToggles;+ sourceMode: EditorSourceModeToggle;onInsertImages: (files: File[]) => void;}diff --git a/web/src/components/MemoEditor/types/index.ts b/web/src/components/MemoEditor/types/index.tsindex 572893fe0..5c99c7d2a 100644--- a/web/src/components/MemoEditor/types/index.ts+++ b/web/src/components/MemoEditor/types/index.ts@@ -5,6 +5,7 @@ export type {AudioRecorderPanelProps,EditorContentProps,EditorMetadataProps,+ EditorSourceModeToggle,EditorToolbarProps,EditorViewToggles,FocusModeExitButtonProps,diff --git a/web/src/components/ui/dropdown-menu.tsx b/web/src/components/ui/dropdown-menu.tsxindex bf19ec60a..9321f51cc 100644--- a/web/src/components/ui/dropdown-menu.tsx+++ b/web/src/components/ui/dropdown-menu.tsx@@ -109,8 +109,18 @@ function DropdownMenuLinkItem({ className, inset, ...props }: DropdownMenuPrimit);}-function DropdownMenuCheckboxItem({ className, children, checked, ...props }: DropdownMenuPrimitive.CheckboxItem.Props) {+function DropdownMenuCheckboxItem({+ className,+ children,+ checked,+ indicator = "start",+ ...props+}: DropdownMenuPrimitive.CheckboxItem.Props & {+ /** Where the check mark sits: before the label, or trailing it for items that lead with their own icon. */+ indicator?: "start" | "end";+}) {const size = React.useContext(DropdownMenuSizeContext);+ const trailing = indicator === "end";return (<DropdownMenuPrimitive.CheckboxItem@@ -118,14 +128,14 @@ function DropdownMenuCheckboxItem({ className, children, checked, ...props }: DrclassName={cn("data-highlighted:bg-accent data-highlighted:text-accent-foreground relative flex cursor-default items-center rounded-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",size === "sm"- ? "min-h-7 gap-1.5 py-1 pe-2 ps-7 text-ui [&_svg:not([class*='size-'])]:size-3.5"- : "gap-2 py-1.5 pe-2 ps-8 text-sm [&_svg:not([class*='size-'])]:size-4",+ ? cn("min-h-7 gap-1.5 py-1 text-ui [&_svg:not([class*='size-'])]:size-3.5", trailing ? "ps-2 pe-7" : "pe-2 ps-7")+ : cn("gap-2 py-1.5 text-sm [&_svg:not([class*='size-'])]:size-4", trailing ? "ps-2 pe-8" : "pe-2 ps-8"),className,)}checked={checked}{...props}>- <span className="pointer-events-none absolute start-2 flex size-3.5 items-center justify-center">+ <span className={cn("pointer-events-none absolute flex size-3.5 items-center justify-center", trailing ? "end-2" : "start-2")}><DropdownMenuPrimitive.CheckboxItemIndicator><CheckIcon className={size === "sm" ? "size-3.5" : "size-4"} /></DropdownMenuPrimitive.CheckboxItemIndicator>diff --git a/web/src/locales/ar.json b/web/src/locales/ar.jsonindex f80b6d8b5..7179f3529 100644--- a/web/src/locales/ar.json+++ b/web/src/locales/ar.json@@ -150,6 +150,9 @@"any-thoughts": "أية أفكار...","exit-focus-mode": "الخروج من وضع التركيز","focus-mode": "وضع التركيز",+ "source": "المصدر",+ "source-mode": "وضع المصدر",+ "switch-to-rich-text": "التبديل إلى النص المنسق","no-changes-detected": "لم يتم الكشف عن تغييرات","save": "حفظ","insert-menu": {diff --git a/web/src/locales/az.json b/web/src/locales/az.jsonindex 174da95b6..efdedd565 100644--- a/web/src/locales/az.json+++ b/web/src/locales/az.json@@ -247,6 +247,9 @@"any-thoughts": "Ağlınıza nə gəlir...","exit-focus-mode": "Fokus rejimindən çıx","focus-mode": "Fokus rejimi",+ "source": "Mənbə",+ "source-mode": "Mənbə rejimi",+ "switch-to-rich-text": "Zəngin mətnə keç","comment": "Şərh","format": {"paragraph": "Abzas",diff --git a/web/src/locales/bg.json b/web/src/locales/bg.jsonindex ee450e87b..9b1a1f046 100644--- a/web/src/locales/bg.json+++ b/web/src/locales/bg.json@@ -188,6 +188,9 @@"any-thoughts": "Някакви мисли...","exit-focus-mode": "Излезте от режима на фокусиране","focus-mode": "Режим на фокусиране",+ "source": "Изходен код",+ "source-mode": "Режим на изходен код",+ "switch-to-rich-text": "Превключване към форматиран текст","insert-menu": {"add-location": "Добавете местоположение","link-memo": "Бележка за връзка",diff --git a/web/src/locales/ca.json b/web/src/locales/ca.jsonindex c470a9579..84c3d7e54 100644--- a/web/src/locales/ca.json+++ b/web/src/locales/ca.json@@ -150,6 +150,9 @@"any-thoughts": "Alguna idea...","exit-focus-mode": "Surt del mode focus","focus-mode": "Mode focus",+ "source": "Font",+ "source-mode": "Mode font",+ "switch-to-rich-text": "Canvia a text enriquit","insert-menu": {"add-location": "Afegeix la ubicació","link-memo": "Nota d'enllaç",diff --git a/web/src/locales/cs.json b/web/src/locales/cs.jsonindex 720f8a5b4..135618bc4 100644--- a/web/src/locales/cs.json+++ b/web/src/locales/cs.json@@ -150,6 +150,9 @@"any-thoughts": "Jakékoli myšlenky...","exit-focus-mode": "Ukončit režim soustředění","focus-mode": "Režim soustředění",+ "source": "Zdroj",+ "source-mode": "Režim zdroje",+ "switch-to-rich-text": "Přepnout na formátovaný text","insert-menu": {"add-location": "Přidat umístění","link-memo": "Odkaz na poznámku",diff --git a/web/src/locales/da.json b/web/src/locales/da.jsonindex 24fbda10f..0802b7ecb 100644--- a/web/src/locales/da.json+++ b/web/src/locales/da.json@@ -188,6 +188,9 @@"any-thoughts": "Nogen tanker...","exit-focus-mode": "Afslut fokustilstand","focus-mode": "Fokustilstand",+ "source": "Kilde",+ "source-mode": "Kildetilstand",+ "switch-to-rich-text": "Skift til formateret tekst","insert-menu": {"add-location": "Tilføj placering","link-memo": "Link memo",diff --git a/web/src/locales/de.json b/web/src/locales/de.jsonindex 145d17bea..3d8e18ffc 100644--- a/web/src/locales/de.json+++ b/web/src/locales/de.json@@ -150,6 +150,9 @@"any-thoughts": "Ein Gedanke...","exit-focus-mode": "Fokus Modus verlassen","focus-mode": "Fokus Modus",+ "source": "Quelltext",+ "source-mode": "Quelltext Modus",+ "switch-to-rich-text": "Zu formatiertem Text wechseln","insert-menu": {"add-location": "Standort hinzufügen","link-memo": "Link-Memo",diff --git a/web/src/locales/el.json b/web/src/locales/el.jsonindex 7c332e394..5d1635b70 100644--- a/web/src/locales/el.json+++ b/web/src/locales/el.json@@ -188,6 +188,9 @@"any-thoughts": "Οποιαδήποτε σκέψη...","exit-focus-mode": "Έξοδος από τη λειτουργία εστίασης","focus-mode": "Λειτουργία εστίασης",+ "source": "Πηγή",+ "source-mode": "Λειτουργία πηγής",+ "switch-to-rich-text": "Εναλλαγή σε μορφοποιημένο κείμενο","insert-menu": {"add-location": "Προσθήκη τοποθεσίας","link-memo": "Σημείωμα σύνδεσης",diff --git a/web/src/locales/en-GB.json b/web/src/locales/en-GB.jsonindex ac349e1c9..61d458362 100644--- a/web/src/locales/en-GB.json+++ b/web/src/locales/en-GB.json@@ -150,6 +150,9 @@"any-thoughts": "Any thoughts...","exit-focus-mode": "Exit Focus Mode","focus-mode": "Focus Mode",+ "source": "Source",+ "source-mode": "Source Mode",+ "switch-to-rich-text": "Switch to rich text","insert-menu": {"add-location": "Add location","link-memo": "Link memo",diff --git a/web/src/locales/en.json b/web/src/locales/en.jsonindex 99c7e38e4..1f89b1476 100644--- a/web/src/locales/en.json+++ b/web/src/locales/en.json@@ -247,6 +247,9 @@"any-thoughts": "Any thoughts...","exit-focus-mode": "Exit Focus Mode","focus-mode": "Focus Mode",+ "source": "Source",+ "source-mode": "Source Mode",+ "switch-to-rich-text": "Switch to rich text","comment": "Comment","format": {"paragraph": "Paragraph",diff --git a/web/src/locales/es.json b/web/src/locales/es.jsonindex 3a4316ed3..428e33b05 100644--- a/web/src/locales/es.json+++ b/web/src/locales/es.json@@ -150,6 +150,9 @@"any-thoughts": "Alguna idea...","exit-focus-mode": "Salir del modo enfoque","focus-mode": "Modo enfoque",+ "source": "Fuente",+ "source-mode": "Modo fuente",+ "switch-to-rich-text": "Cambiar a texto enriquecido","insert-menu": {"add-location": "Agregar ubicación","link-memo": "Nota de enlace",diff --git a/web/src/locales/et.json b/web/src/locales/et.jsonindex e9a970373..a7166f82f 100644--- a/web/src/locales/et.json+++ b/web/src/locales/et.json@@ -188,6 +188,9 @@"any-thoughts": "Mingid mõtted...","exit-focus-mode": "Välju teravustamisrežiimist","focus-mode": "Fookusrežiim",+ "source": "Lähtetekst",+ "source-mode": "Lähtetekstirežiim",+ "switch-to-rich-text": "Lülitu vormindatud tekstile","insert-menu": {"add-location": "Lisa asukoht","link-memo": "Lingi memo",diff --git a/web/src/locales/fa.json b/web/src/locales/fa.jsonindex 01ff66d75..8ebcd4769 100644--- a/web/src/locales/fa.json+++ b/web/src/locales/fa.json@@ -150,6 +150,9 @@"any-thoughts": "فکر شما...","exit-focus-mode": "خروج از حالت تمرکز","focus-mode": "حالت تمرکز",+ "source": "منبع",+ "source-mode": "حالت منبع",+ "switch-to-rich-text": "تغییر به متن قالبدار","no-changes-detected": "تغییری شناسایی نشد","save": "ذخیره","insert-menu": {diff --git a/web/src/locales/fi.json b/web/src/locales/fi.jsonindex 7cf82e828..bae9d132b 100644--- a/web/src/locales/fi.json+++ b/web/src/locales/fi.json@@ -188,6 +188,9 @@"any-thoughts": "Mitään ajatuksia...","exit-focus-mode": "Poistu tarkennustilasta","focus-mode": "Tarkennustila",+ "source": "Lähde",+ "source-mode": "Lähdetila",+ "switch-to-rich-text": "Vaihda muotoiltuun tekstiin","insert-menu": {"add-location": "Lisää sijainti","link-memo": "Linkkimuistio",diff --git a/web/src/locales/fr.json b/web/src/locales/fr.jsonindex 2a3eb3e6c..57f049f15 100644--- a/web/src/locales/fr.json+++ b/web/src/locales/fr.json@@ -150,6 +150,9 @@"any-thoughts": "Des idées...","exit-focus-mode": "Quitter le mode concentration","focus-mode": "Mode concentration",+ "source": "Source",+ "source-mode": "Mode source",+ "switch-to-rich-text": "Passer au texte enrichi","insert-menu": {"add-location": "Ajouter un emplacement","link-memo": "Lien vers un mémo",diff --git a/web/src/locales/gl.json b/web/src/locales/gl.jsonindex 3da8b3480..c2b38ae97 100644--- a/web/src/locales/gl.json+++ b/web/src/locales/gl.json@@ -150,6 +150,9 @@"any-thoughts": "O que pensas...","exit-focus-mode": "Saír do modo sen distraccións","focus-mode": "Modo Sen distraccións",+ "source": "Fonte",+ "source-mode": "Modo fonte",+ "switch-to-rich-text": "Cambiar a texto enriquecido","insert-menu": {"add-location": "Engadir localización","link-memo": "Nota de ligazón",diff --git a/web/src/locales/he.json b/web/src/locales/he.jsonindex 63d299972..2e401d16d 100644--- a/web/src/locales/he.json+++ b/web/src/locales/he.json@@ -221,6 +221,9 @@"any-thoughts": "יש מחשבות...","exit-focus-mode": "יציאה ממצב מיקוד","focus-mode": "מצב מיקוד",+ "source": "מקור",+ "source-mode": "מצב מקור",+ "switch-to-rich-text": "מעבר לטקסט מעוצב","format": {"paragraph": "פסקה","heading-1": "כותרת 1",diff --git a/web/src/locales/hi.json b/web/src/locales/hi.jsonindex e6ef22588..ea287a095 100644--- a/web/src/locales/hi.json+++ b/web/src/locales/hi.json@@ -150,6 +150,9 @@"any-thoughts": "कोई विचार...","exit-focus-mode": "फोकस मोड से बाहर निकलें","focus-mode": "फोकस मोड",+ "source": "स्रोत",+ "source-mode": "स्रोत मोड",+ "switch-to-rich-text": "रिच टेक्स्ट पर जाएँ","no-changes-detected": "कोई बदलाव नहीं पाया गया","save": "सहेजें","insert-menu": {diff --git a/web/src/locales/hr.json b/web/src/locales/hr.jsonindex e7afd40b5..521dbdbd0 100644--- a/web/src/locales/hr.json+++ b/web/src/locales/hr.json@@ -150,6 +150,9 @@"any-thoughts": "Imaš li misli...","exit-focus-mode": "Izlazi iz načina rada za fokus","focus-mode": "Način rada za fokus",+ "source": "Izvor",+ "source-mode": "Način rada izvora",+ "switch-to-rich-text": "Prebaci na oblikovani tekst","insert-menu": {"add-location": "Dodajte lokaciju","link-memo": "Link dopis",diff --git a/web/src/locales/hu.json b/web/src/locales/hu.jsonindex ea002ff69..d8626e2bd 100644--- a/web/src/locales/hu.json+++ b/web/src/locales/hu.json@@ -150,6 +150,9 @@"any-thoughts": "Bármi ami a fejedben jár...","exit-focus-mode": "Kilépés a fókusz módból","focus-mode": "Fókusz mód",+ "source": "Forrás",+ "source-mode": "Forrás mód",+ "switch-to-rich-text": "Váltás formázott szövegre","insert-menu": {"add-location": "Hely hozzáadása","link-memo": "Linkjegyzet",diff --git a/web/src/locales/id.json b/web/src/locales/id.jsonindex 1a64b19fa..9c3de00be 100644--- a/web/src/locales/id.json+++ b/web/src/locales/id.json@@ -150,6 +150,9 @@"any-thoughts": "Punya pemikiran...","exit-focus-mode": "Keluar dari Mode Fokus","focus-mode": "Mode Fokus",+ "source": "Sumber",+ "source-mode": "Mode Sumber",+ "switch-to-rich-text": "Beralih ke Teks Kaya","no-changes-detected": "Tidak ada perubahan yang terdeteksi","save": "Simpan","insert-menu": {diff --git a/web/src/locales/it.json b/web/src/locales/it.jsonindex c4007ad74..a540eab57 100644--- a/web/src/locales/it.json+++ b/web/src/locales/it.json@@ -150,6 +150,9 @@"any-thoughts": "Qualsiasi cosa pensi...","exit-focus-mode": "Esci Modalità Focus","focus-mode": "Modalità Focus",+ "source": "Sorgente",+ "source-mode": "Modalità Sorgente",+ "switch-to-rich-text": "Passa al testo formattato","insert-menu": {"add-location": "Aggiungi posizione","link-memo": "Collegamento promemoria",diff --git a/web/src/locales/ja.json b/web/src/locales/ja.jsonindex f83dfedc2..a88a3d508 100644--- a/web/src/locales/ja.json+++ b/web/src/locales/ja.json@@ -150,6 +150,9 @@"any-thoughts": "今思ったことは...","exit-focus-mode": "フォーカスを終了","focus-mode": "フォーカスモード",+ "source": "ソース",+ "source-mode": "ソースモード",+ "switch-to-rich-text": "リッチテキストに切り替え","no-changes-detected": "変更はありません","save": "保存","insert-menu": {diff --git a/web/src/locales/ka-GE.json b/web/src/locales/ka-GE.jsonindex f88141c77..c2af1aa4c 100644--- a/web/src/locales/ka-GE.json+++ b/web/src/locales/ka-GE.json@@ -150,6 +150,9 @@"any-thoughts": "რამე იდეები...","exit-focus-mode": "ფოკუსის რეჟიმიდან გასვლა","focus-mode": "ფოკუსის რეჟიმი",+ "source": "წყარო",+ "source-mode": "წყაროს რეჟიმი",+ "switch-to-rich-text": "ფორმატირებულ ტექსტზე გადართვა","insert-menu": {"add-location": "მდებარეობის დამატება","link-memo": "ლინკ შენიშვნა",diff --git a/web/src/locales/ko.json b/web/src/locales/ko.jsonindex 1a368f8de..0f8d91231 100644--- a/web/src/locales/ko.json+++ b/web/src/locales/ko.json@@ -150,6 +150,9 @@"any-thoughts": "떠오르는 게 있나요...","exit-focus-mode": "집중 모드 종료","focus-mode": "집중 모드",+ "source": "소스",+ "source-mode": "소스 모드",+ "switch-to-rich-text": "서식 있는 텍스트로 전환","no-changes-detected": "변경사항이 없습니다","save": "저장","insert-menu": {diff --git a/web/src/locales/lt.json b/web/src/locales/lt.jsonindex 340474ca4..5a3dd1445 100644--- a/web/src/locales/lt.json+++ b/web/src/locales/lt.json@@ -188,6 +188,9 @@"any-thoughts": "Bet kokios mintys...","exit-focus-mode": "Išeikite iš fokusavimo režimo","focus-mode": "Fokusavimo režimas",+ "source": "Šaltinis",+ "source-mode": "Šaltinio režimas",+ "switch-to-rich-text": "Perjungti į formatuotą tekstą","insert-menu": {"add-location": "Pridėti vietą","link-memo": "Nuorodos atmintinė",diff --git a/web/src/locales/lv.json b/web/src/locales/lv.jsonindex 4cd9eef4e..f5af2fcaa 100644--- a/web/src/locales/lv.json+++ b/web/src/locales/lv.json@@ -188,6 +188,9 @@"any-thoughts": "Jebkuras domas...","exit-focus-mode": "Iziet no fokusa režīma","focus-mode": "Fokusa režīms",+ "source": "Avots",+ "source-mode": "Avota režīms",+ "switch-to-rich-text": "Pārslēgties uz formatētu tekstu","insert-menu": {"add-location": "Pievienot atrašanās vietu","link-memo": "Saites piezīme",diff --git a/web/src/locales/mr.json b/web/src/locales/mr.jsonindex 5ae6467a6..61a17bb9f 100644--- a/web/src/locales/mr.json+++ b/web/src/locales/mr.json@@ -150,6 +150,9 @@"any-thoughts": "आपले विचार...","exit-focus-mode": "फोकस मोड सोडा","focus-mode": "फोकस मोड",+ "source": "स्रोत",+ "source-mode": "स्रोत मोड",+ "switch-to-rich-text": "रिच टेक्स्टवर जा","no-changes-detected": "कोणतेही बदल आढळले नाहीत","save": "जतन","insert-menu": {diff --git a/web/src/locales/nb.json b/web/src/locales/nb.jsonindex fff800b8e..b98ebae6e 100644--- a/web/src/locales/nb.json+++ b/web/src/locales/nb.json@@ -150,6 +150,9 @@"any-thoughts": "Noen tanker...","exit-focus-mode": "Avslutt fokusmodus","focus-mode": "Fokusmodus",+ "source": "Kilde",+ "source-mode": "Kildemodus",+ "switch-to-rich-text": "Bytt til formatert tekst","insert-menu": {"add-location": "Legg til plassering","link-memo": "Koblingsnotat",diff --git a/web/src/locales/nl.json b/web/src/locales/nl.jsonindex bc61223df..a13851ec9 100644--- a/web/src/locales/nl.json+++ b/web/src/locales/nl.json@@ -150,6 +150,9 @@"any-thoughts": "Enkele gedachten…","exit-focus-mode": "Focusmodus afsluiten","focus-mode": "Focusmodus",+ "source": "Bron",+ "source-mode": "Bronmodus",+ "switch-to-rich-text": "Overschakelen naar opgemaakte tekst","insert-menu": {"add-location": "Locatie toevoegen","link-memo": "Link-memo",diff --git a/web/src/locales/nn.json b/web/src/locales/nn.jsonindex 6a6781734..d1684c166 100644--- a/web/src/locales/nn.json+++ b/web/src/locales/nn.json@@ -242,6 +242,9 @@"comment": "Kommenter","exit-focus-mode": "Gå ut av fokusmodus","focus-mode": "Fokusmodus",+ "source": "Kjelde",+ "source-mode": "Kjeldemodus",+ "switch-to-rich-text": "Byt til formatert tekst","format": {"bold": "Feit skrift","bullet-list": "Punktliste",diff --git a/web/src/locales/pl.json b/web/src/locales/pl.jsonindex 37a7ee7fb..9ef3af87d 100644--- a/web/src/locales/pl.json+++ b/web/src/locales/pl.json@@ -150,6 +150,9 @@"any-thoughts": "Jakieś przemyślenia...","exit-focus-mode": "Wyjdź z Trybu Skupienia","focus-mode": "Tryb Skupienia",+ "source": "Źródło",+ "source-mode": "Tryb Źródła",+ "switch-to-rich-text": "Przełącz na tekst sformatowany","format": {"paragraph": "Akapit","heading-1": "Nagłówek 1",diff --git a/web/src/locales/pt-BR.json b/web/src/locales/pt-BR.jsonindex 0c56b8466..051dac775 100644--- a/web/src/locales/pt-BR.json+++ b/web/src/locales/pt-BR.json@@ -150,6 +150,9 @@"any-thoughts": "Alguma ideia…","exit-focus-mode": "Sair do Modo Foco","focus-mode": "Modo Foco",+ "source": "Código",+ "source-mode": "Modo Código",+ "switch-to-rich-text": "Mudar para texto formatado","no-changes-detected": "Nenhuma alteração detectada","save": "Salvar","insert-menu": {diff --git a/web/src/locales/pt-PT.json b/web/src/locales/pt-PT.jsonindex 61877f4ed..98f5364df 100644--- a/web/src/locales/pt-PT.json+++ b/web/src/locales/pt-PT.json@@ -150,6 +150,9 @@"any-thoughts": "Alguma ideia…","exit-focus-mode": "Sair do Modo Foco","focus-mode": "Modo Foco",+ "source": "Código",+ "source-mode": "Modo Código",+ "switch-to-rich-text": "Mudar para texto formatado","insert-menu": {"add-location": "Adicionar local","link-memo": "Vincular memorando",diff --git a/web/src/locales/ro.json b/web/src/locales/ro.jsonindex 5e6d94a43..e4939ef68 100644--- a/web/src/locales/ro.json+++ b/web/src/locales/ro.json@@ -188,6 +188,9 @@"any-thoughts": "Orice gânduri...","exit-focus-mode": "Ieșiți din modul de focalizare","focus-mode": "Modul de focalizare",+ "source": "Sursă",+ "source-mode": "Modul sursă",+ "switch-to-rich-text": "Comută la text formatat","insert-menu": {"add-location": "Adăugați locația","link-memo": "Notă de legături",diff --git a/web/src/locales/ru.json b/web/src/locales/ru.jsonindex caa6e24a8..48b43b5b0 100644--- a/web/src/locales/ru.json+++ b/web/src/locales/ru.json@@ -150,6 +150,9 @@"any-thoughts": "Напишите что-нибудь...","exit-focus-mode": "Выйти из режима фокуса","focus-mode": "Режим фокуса",+ "source": "Исходник",+ "source-mode": "Режим исходника",+ "switch-to-rich-text": "Переключиться на форматированный текст","insert-menu": {"add-location": "Добавить местоположение","link-memo": "Ссылка на заметку",diff --git a/web/src/locales/sk.json b/web/src/locales/sk.jsonindex aa5b7414c..a4f758c65 100644--- a/web/src/locales/sk.json+++ b/web/src/locales/sk.json@@ -188,6 +188,9 @@"any-thoughts": "Akékoľvek myšlienky...","exit-focus-mode": "Ukončite režim zaostrenia","focus-mode": "Režim zaostrenia",+ "source": "Zdroj",+ "source-mode": "Režim zdroja",+ "switch-to-rich-text": "Prepnúť na formátovaný text","insert-menu": {"add-location": "Pridať polohu","link-memo": "Odkaz na poznámku",diff --git a/web/src/locales/sl.json b/web/src/locales/sl.jsonindex 9200338a8..f0022b39b 100644--- a/web/src/locales/sl.json+++ b/web/src/locales/sl.json@@ -150,6 +150,9 @@"any-thoughts": "Kakšne misli...","exit-focus-mode": "Izhod iz načina osredotočanja","focus-mode": "Način osredotočanja",+ "source": "Izvor",+ "source-mode": "Način izvora",+ "switch-to-rich-text": "Preklopi na oblikovano besedilo","insert-menu": {"add-location": "Dodajte lokacijo","link-memo": "Beležka povezave",diff --git a/web/src/locales/sr.json b/web/src/locales/sr.jsonindex aff802b33..24ca24b9a 100644--- a/web/src/locales/sr.json+++ b/web/src/locales/sr.json@@ -188,6 +188,9 @@"any-thoughts": "Било каква размишљања...","exit-focus-mode": "Изађите из режима фокуса","focus-mode": "Фоцус Моде",+ "source": "Извор",+ "source-mode": "Режим извора",+ "switch-to-rich-text": "Пребаци на форматирани текст","insert-menu": {"add-location": "Додајте локацију","link-memo": "Меморандум о вези",diff --git a/web/src/locales/sv.json b/web/src/locales/sv.jsonindex a68b05fbc..ed0b813cf 100644--- a/web/src/locales/sv.json+++ b/web/src/locales/sv.json@@ -150,6 +150,9 @@"any-thoughts": "Några tankar...","exit-focus-mode": "Avsluta fokusläge","focus-mode": "Fokusläge",+ "source": "Källa",+ "source-mode": "Källäge",+ "switch-to-rich-text": "Växla till formaterad text","insert-menu": {"add-location": "Lägg till plats","link-memo": "Länkmemo",diff --git a/web/src/locales/th.json b/web/src/locales/th.jsonindex 770120912..8ff2746e1 100644--- a/web/src/locales/th.json+++ b/web/src/locales/th.json@@ -150,6 +150,9 @@"any-thoughts": "ความคิดใดๆ...","exit-focus-mode": "ออกจากโหมดโฟกัส","focus-mode": "โหมดโฟกัส",+ "source": "ซอร์ส",+ "source-mode": "โหมดซอร์ส",+ "switch-to-rich-text": "สลับเป็นข้อความแบบจัดรูปแบบ","no-changes-detected": "ไม่มีการเปลี่ยนแปลง","save": "บันทึก","insert-menu": {diff --git a/web/src/locales/tr.json b/web/src/locales/tr.jsonindex 3a928d51a..f7e34ad4e 100644--- a/web/src/locales/tr.json+++ b/web/src/locales/tr.json@@ -176,6 +176,9 @@"any-thoughts": "Düşünceleriniz...","exit-focus-mode": "Odak modundan çık","focus-mode": "Odak modu",+ "source": "Kaynak",+ "source-mode": "Kaynak modu",+ "switch-to-rich-text": "Zengin metne geç","comment": "Yorum yap","format": {"paragraph": "Paragraf",diff --git a/web/src/locales/uk.json b/web/src/locales/uk.jsonindex d7c9d6010..dd969b968 100644--- a/web/src/locales/uk.json+++ b/web/src/locales/uk.json@@ -150,6 +150,9 @@"any-thoughts": "Якісь думки...","exit-focus-mode": "Вийти з режиму фокусування","focus-mode": "Режим фокусування",+ "source": "Вихідний код",+ "source-mode": "Режим вихідного коду",+ "switch-to-rich-text": "Перейти до форматованого тексту","insert-menu": {"add-location": "Додайте місцезнаходження","link-memo": "Пам'ятка про посилання",diff --git a/web/src/locales/vi.json b/web/src/locales/vi.jsonindex 299e0db40..7025e39ee 100644--- a/web/src/locales/vi.json+++ b/web/src/locales/vi.json@@ -150,6 +150,9 @@"any-thoughts": "Có suy nghĩ gì...","exit-focus-mode": "Thoát chế độ tập trung","focus-mode": "Chế độ tập trung",+ "source": "Mã nguồn",+ "source-mode": "Chế độ mã nguồn",+ "switch-to-rich-text": "Chuyển sang văn bản định dạng","no-changes-detected": "Không phát hiện thay đổi","save": "Lưu","insert-menu": {diff --git a/web/src/locales/zh-Hans.json b/web/src/locales/zh-Hans.jsonindex f20b7191a..20563f071 100644--- a/web/src/locales/zh-Hans.json+++ b/web/src/locales/zh-Hans.json@@ -181,6 +181,9 @@"any-thoughts": "此刻的想法...","exit-focus-mode": "退出聚焦模式","focus-mode": "聚焦模式",+ "source": "源码",+ "source-mode": "源码模式",+ "switch-to-rich-text": "切换到富文本","format": {"paragraph": "正文","heading-1": "一级标题",diff --git a/web/src/locales/zh-Hant.json b/web/src/locales/zh-Hant.jsonindex 7c4a998ee..c84a6243b 100644--- a/web/src/locales/zh-Hant.json+++ b/web/src/locales/zh-Hant.json@@ -229,6 +229,9 @@"any-thoughts": "任何想法...","exit-focus-mode": "退出專注模式","focus-mode": "專注模式",+ "source": "原始碼",+ "source-mode": "原始碼模式",+ "switch-to-rich-text": "切換到富文字","format": {"paragraph": "段落","heading-1": "標題 1",diff --git a/web/tests/audience-menu.test.tsx b/web/tests/audience-menu.test.tsxindex d97ae975a..b4a1ae177 100644--- a/web/tests/audience-menu.test.tsx+++ b/web/tests/audience-menu.test.tsx@@ -198,7 +198,16 @@ it("removing a Members memo from its Space falls back to Private without discardfunction Toolbar() {getState = useEditorContext().getState;const space = useEditorSelector((state) => state.metadata.space);- return <EditorToolbar space={space} canChooseSpace onSave={vi.fn()} onAudioRecorderClick={vi.fn()} onInsertImages={vi.fn()} />;+ return (+ <EditorToolbar+ space={space}+ canChooseSpace+ onSave={vi.fn()}+ onAudioRecorderClick={vi.fn()}+ sourceMode={{ isSourceMode: false, onToggle: vi.fn() }}+ onInsertImages={vi.fn()}+ />+ );}const initial = createInitialState();initial.content = "Keep this draft";diff --git a/web/tests/editor-commit-button.test.tsx b/web/tests/editor-commit-button.test.tsxindex 38a15ec9d..6745d6611 100644--- a/web/tests/editor-commit-button.test.tsx+++ b/web/tests/editor-commit-button.test.tsx@@ -12,7 +12,14 @@ let dispatchSaving: ((saving: boolean) => void) | undefined;const Toolbar = () => {const { actions, dispatch } = useEditorContext();dispatchSaving = (saving) => dispatch(actions.setLoading("saving", saving));- return <EditorToolbar onSave={vi.fn()} onAudioRecorderClick={vi.fn()} onInsertImages={vi.fn()} />;+ return (+ <EditorToolbar+ onSave={vi.fn()}+ onAudioRecorderClick={vi.fn()}+ sourceMode={{ isSourceMode: false, onToggle: vi.fn() }}+ onInsertImages={vi.fn()}+ />+ );};const renderToolbar = (content: string) => {diff --git a/web/tests/editor-controller.test.tsx b/web/tests/editor-controller.test.tsxindex a8eccb4e6..98c7715fd 100644--- a/web/tests/editor-controller.test.tsx+++ b/web/tests/editor-controller.test.tsx@@ -1,4 +1,5 @@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";@@ -10,7 +11,7 @@ vi.mock("@/hooks/useUserQueries", () => ({useUsersByUsernames: () => ({ data: undefined }),}));-function setup(value = "") {+function setup(value = "", mode: EditorMode = "rich") {const ref = createRef<EditorController>();const onContentChange = vi.fn();const utils = render(@@ -19,6 +20,7 @@ function setup(value = "") {className="x"value={value}placeholder="memo"+ mode={mode}onContentChange={onContentChange}onFiles={vi.fn()}onSubmit={vi.fn()}@@ -158,3 +160,35 @@ describe("upload anchors", () => {expect(stale).not.toHaveBeenCalled();});});++describe("source mode", () => {+ const memo = "# Plan\n\n- [ ] Ship #work\n\n`#code`";++ it("reads tags and tasks from the Markdown text", () => {+ const { c } = setup(memo, "source");+ expect(c.getTags()).toEqual(["work"]);+ expect(c.hasChecklist()).toBe(true);+ });++ it("does not insert a tag the text already has", () => {+ const { c } = setup(memo, "source");+ caretAtEnd(c, 0, "# Plan".length);+ expect(c.insertTag("work")).toBe(false);+ expect(c.insertTag("home")).toBe(true);+ // Plain text keeps the space after the tag; rich mode drops it at a paragraph's end.+ expect(c.getMarkdown()).toBe("# Plan #home \n\n- [ ] Ship #work\n\n`#code`");+ });++ it("inserts Markdown on lines of its own after the caret's line", () => {+ const { c } = setup(memo, "source");+ caretAtEnd(c, 0, "# Plan".length);+ c.insertMarkdown("");+ expect(c.getMarkdown()).toBe("# Plan\n\n\n- [ ] Ship #work\n\n`#code`");+ });++ it("shows the memo as Markdown text, the same document rich mode saves", () => {+ const { c, container } = setup(memo, "source");+ expect(container.querySelector(".mbe-source")?.textContent).toBe(memo);+ expect(c.getMarkdown()).toBe(memo);+ });+});diff --git a/web/tests/editor-suggestions.test.tsx b/web/tests/editor-suggestions.test.tsxindex 8433346f4..e38dc3d1b 100644--- a/web/tests/editor-suggestions.test.tsx+++ b/web/tests/editor-suggestions.test.tsx@@ -23,7 +23,7 @@ function Harness({ suggestions, space }: { suggestions: MemoSuggestion[]; space?controller = useRef<EditorController>(null);return (<>- <EditorContent ref={controller} onSubmit={vi.fn()} onFiles={vi.fn()} />+ <EditorContent ref={controller} sourceMode={{ isSourceMode: false, onToggle: vi.fn() }} onSubmit={vi.fn()} onFiles={vi.fn()} /><EditorSuggestions suggestions={suggestions} controllerRef={controller} space={space} /></>);diff --git a/web/tests/insert-menu.test.tsx b/web/tests/insert-menu.test.tsxindex 8281ee80b..a7bea8aa7 100644--- a/web/tests/insert-menu.test.tsx+++ b/web/tests/insert-menu.test.tsx@@ -25,8 +25,10 @@ const viewToggles = {onToggleFocusMode: vi.fn(),};+const richMode = { isSourceMode: false, onToggle: vi.fn() };+/** `hosted` mirrors an editor whose presentation belongs to a host (the global composer). */-const renderMenu = (onInsertImages = vi.fn(), isSaving = false, hosted = false) =>+const renderMenu = (onInsertImages = vi.fn(), isSaving = false, hosted = false, sourceMode = richMode) =>render(<EditorProvider><InsertMenu@@ -35,6 +37,7 @@ const renderMenu = (onInsertImages = vi.fn(), isSaving = false, hosted = false)onInsertImages={onInsertImages}onAudioRecorderClick={vi.fn()}viewToggles={hosted ? undefined : viewToggles}+ sourceMode={sourceMode}/></EditorProvider>,);@@ -57,14 +60,26 @@ describe("InsertMenu", () => {]);});- test("drops the view toggles when a host owns the editor's presentation", () => {+ test("drops focus mode but keeps source mode when a host owns the editor's presentation", () => {renderMenu(vi.fn(), false, true);fireEvent.click(screen.getByRole("button", { name: "common.add" }));const labels = screen.getAllByRole("menuitem").map((item) => item.textContent);expect(labels).not.toContain("editor.focus-mode");- expect(screen.queryByRole("separator")).not.toBeInTheDocument();+ expect(screen.getByRole("menuitemcheckbox", { name: "editor.source-mode" })).toBeInTheDocument();+ });++ test.each([false, true])("shows source mode as a checkbox item that toggles it (on: %s)", (isSourceMode) => {+ const onToggle = vi.fn();+ renderMenu(vi.fn(), false, false, { isSourceMode, onToggle });++ fireEvent.click(screen.getByRole("button", { name: "common.add" }));+ const item = screen.getByRole("menuitemcheckbox", { name: "editor.source-mode" });+ expect(item).toHaveAttribute("aria-checked", String(isSourceMode));++ fireEvent.click(item);+ expect(onToggle).toHaveBeenCalledOnce();});test("uses separate unrestricted and multi-image file inputs", () => {@@ -100,7 +115,13 @@ describe("InsertMenu", () => {render(<EditorProvider initialEditorState={state}>- <EditorToolbar onSave={vi.fn()} onAudioRecorderClick={vi.fn()} viewToggles={viewToggles} onInsertImages={vi.fn()} />+ <EditorToolbar+ onSave={vi.fn()}+ onAudioRecorderClick={vi.fn()}+ viewToggles={viewToggles}+ sourceMode={richMode}+ onInsertImages={vi.fn()}+ /></EditorProvider>,);diff --git a/web/tests/memo-editor-cache.test.ts b/web/tests/memo-editor-cache.test.tsindex 469d8b8be..1c6f6cf7a 100644--- a/web/tests/memo-editor-cache.test.ts+++ b/web/tests/memo-editor-cache.test.ts@@ -129,10 +129,20 @@ describe("memo editor cache", () => {const key = cacheService.key("users/steven", "global-memo-editor");const selection = { anchor: { block: 1, offset: 9 }, focus: { block: 1, offset: 9 } };- cacheService.saveCursor(key, selection);+ cacheService.saveCursor(key, selection, "rich");- expect(cacheService.loadCursor(key)).toEqual(selection);+ expect(cacheService.loadCursor(key, "rich")).toEqual(selection);cacheService.clear(key);- expect(cacheService.loadCursor(key)).toBeUndefined();+ expect(cacheService.loadCursor(key, "rich")).toBeUndefined();+ });++ it("drops a cursor taken in the other editor mode", () => {+ const key = cacheService.key("users/steven", "global-memo-editor");++ // Source mode is one block of Markdown, so its offsets mean nothing to rich mode.+ cacheService.saveCursor(key, { anchor: { block: 0, offset: 42 }, focus: { block: 0, offset: 42 } }, "source");++ expect(cacheService.loadCursor(key, "rich")).toBeUndefined();+ expect(cacheService.loadCursor(key, "source")).toBeDefined();});});diff --git a/web/tests/memo-editor-source-mode.test.tsx b/web/tests/memo-editor-source-mode.test.tsxnew file mode 100644index 000000000..1899d808f--- /dev/null+++ b/web/tests/memo-editor-source-mode.test.tsx@@ -0,0 +1,102 @@+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 type { MemoSuggestion } from "@/lib/memo-suggestions";++vi.mock("@/utils/i18n", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/utils/i18n")>()),+ useTranslate: () => (key: string) => key,+}));+vi.mock("@/hooks/useUserQueries", () => ({ useTagCounts: () => ({ data: {} }), useUsersByUsernames: () => ({ data: undefined }) }));+vi.mock("@/hooks/useCurrentUser", () => ({ default: () => ({ name: "users/1" }) }));+vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ userGeneralSetting: {} }) }));+vi.mock("@/contexts/InstanceContext", () => ({+ useInstance: () => ({ aiSetting: { providers: [], transcription: undefined }, fetchSetting: vi.fn().mockResolvedValue(undefined) }),+}));+vi.mock("@/contexts/NewMemoContext", () => ({ useNewMemo: () => ({ markNewMemo: vi.fn() }) }));+vi.mock("@/hooks/useSpaceQueries", () => ({ useSpaces: () => ({ data: [] }) }));+vi.mock("@/contexts/SpaceContext", () => ({ useSpaceContext: () => ({ selectedSpaceName: undefined }) }));+vi.mock("@/connect", () => ({ attachmentServiceClient: {}, memoServiceClient: {}, userServiceClient: {} }));+vi.stubGlobal("matchMedia", () => ({ matches: false, addEventListener() {}, removeEventListener() {} }));+vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+);++beforeAll(() => {+ Element.prototype.scrollIntoView = vi.fn();+ Element.prototype.hasPointerCapture = vi.fn(() => false);+ Element.prototype.setPointerCapture = vi.fn();+ Element.prototype.releasePointerCapture = vi.fn();+});++const MODE_KEY = "memos-editor-mode";+const CACHE_KEY = "source-mode-test";++const mount = (suggestions?: readonly MemoSuggestion[]) =>+ render(+ <QueryClientProvider client={new QueryClient()}>+ <MemoEditor cacheKey={CACHE_KEY} suggestions={suggestions} />+ </QueryClientProvider>,+ );++const sourceText = (container: HTMLElement) => container.querySelector(".mbe-source");++afterEach(() => {+ localStorage.clear();+ cacheService.clearAll();+});++describe("MemoEditor source mode", () => {+ it("switches from the + menu, names itself in the editor's corner while on, and switches back from there", () => {+ const { container } = mount();+ expect(sourceText(container)).toBeNull();+ expect(screen.queryByRole("button", { name: "editor.source" })).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "common.add" }));+ fireEvent.click(screen.getByRole("menuitemcheckbox", { name: "editor.source-mode" }));++ expect(sourceText(container)).not.toBeNull();+ expect(localStorage.getItem(MODE_KEY)).toBe(JSON.stringify("source"));+ // The tag belongs to the writing area, not the toolbar, and the first line leaves room for it.+ const tag = screen.getByRole("button", { name: "editor.source" });+ expect(tag.parentElement?.querySelector(":scope > .memo-editor-content")).not.toBeNull();+ expect(container.querySelector(".memo-editor-content")).toHaveAttribute("data-source-mode");++ fireEvent.click(screen.getByRole("button", { name: "editor.source" }));++ expect(sourceText(container)).toBeNull();+ expect(screen.queryByRole("button", { name: "editor.source" })).not.toBeInTheDocument();+ expect(localStorage.getItem(MODE_KEY)).toBe(JSON.stringify("rich"));+ });++ it("opens in the mode remembered on this device", () => {+ localStorage.setItem(MODE_KEY, JSON.stringify("source"));+ const { container } = mount();++ expect(sourceText(container)).not.toBeNull();+ expect(screen.getByRole("button", { name: "editor.source" })).toBeInTheDocument();+ });++ it.each([+ ["rich", true],+ ["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: [] });+ mount([+ { id: "tag:food", source: "view", kind: "tag", tag: "food" },+ { id: "checklist", source: "view", kind: "checklist" },+ ]);++ // The tag chip works in both modes, so the bar renders either way and only the checklist chip differs.+ await waitFor(() => expect(screen.getByRole("button", { name: "common.add #food" })).toBeInTheDocument());+ expect(screen.queryByRole("button", { name: "editor.format.task-list" }) !== null).toBe(offered);+ });+});diff --git a/web/tests/use-memo-init.test.tsx b/web/tests/use-memo-init.test.tsxindex 53d425ce0..86261a835 100644--- a/web/tests/use-memo-init.test.tsx+++ b/web/tests/use-memo-init.test.tsx@@ -1,5 +1,6 @@import { create } from "@bufbuild/protobuf";import { act, render, waitFor } 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";@@ -17,10 +18,12 @@ function Probe({autoFocus,defaultLocation,canChooseSpace,+ mode = "rich",}: {autoFocus?: boolean | (() => boolean);defaultLocation?: Location;canChooseSpace?: boolean;+ mode?: EditorMode;}) {getEditorState = useEditorContext().getState;useMemoInit({@@ -31,6 +34,7 @@ function Probe({defaultLocation,canChooseSpace,defaultVisibility: Visibility.PUBLIC,+ mode,});return null;}@@ -57,7 +61,7 @@ describe("useMemoInit", () => {const key = cacheService.key("users/steven", "restored-draft");cacheService.saveNow(key, { content: "An unfinished memo", attachments: [] });const selection = { anchor: { block: 0, offset: 5 }, focus: { block: 0, offset: 5 } };- cacheService.saveCursor(key, selection);+ cacheService.saveCursor(key, selection, "rich");const focus = vi.fn();const setSelection = vi.fn();editorRef.current = { focus, setSelection } as unknown as EditorController;@@ -78,6 +82,24 @@ describe("useMemoInit", () => {expect(focus).toHaveBeenCalledTimes(allowed ? 1 : 0);});+ 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");+ const setSelection = vi.fn();+ editorRef.current = { focus: vi.fn(), setSelection } as unknown as EditorController;++ render(+ <EditorProvider>+ <Probe mode="rich" />+ </EditorProvider>,+ );+ act(() => vi.advanceTimersByTime(100));+ expect(getEditorState().content).toBe("An unfinished memo");+ expect(setSelection).not.toHaveBeenCalled();+ });+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(