refactor(web): rename editor dirs and simplify raw mode to a plain textarea
This commit is contained in:
parent
797f1ff15d
commit
2c0efeba7c
42 changed files with 525 additions and 1334 deletions
|
|
@ -1,45 +0,0 @@
|
|||
import type { SlashCommandsProps } from "../types";
|
||||
import type { EditorRefActions } from ".";
|
||||
import { SuggestionsPopup } from "./SuggestionsPopup";
|
||||
import { useSuggestions } from "./useSuggestions";
|
||||
|
||||
const SlashCommands = ({ editorRef, editorActions, commands }: SlashCommandsProps) => {
|
||||
const handleCommandAutocomplete = (cmd: (typeof commands)[0], word: string, index: number, actions: EditorRefActions) => {
|
||||
// Remove trigger char + word, then insert command output
|
||||
actions.removeText(index, word.length);
|
||||
actions.insertText(cmd.run());
|
||||
// Position cursor relative to insertion point, if specified
|
||||
if (cmd.cursorOffset) {
|
||||
actions.setCursorPosition(index + cmd.cursorOffset);
|
||||
}
|
||||
};
|
||||
|
||||
const { position, suggestions, selectedIndex, isVisible, handleItemSelect } = useSuggestions({
|
||||
editorRef,
|
||||
editorActions,
|
||||
triggerChar: "/",
|
||||
items: commands,
|
||||
filterItems: (items, query) => (!query ? items : items.filter((cmd) => cmd.name.toLowerCase().startsWith(query))),
|
||||
onAutocomplete: handleCommandAutocomplete,
|
||||
});
|
||||
|
||||
if (!isVisible || !position) return null;
|
||||
|
||||
return (
|
||||
<SuggestionsPopup
|
||||
position={position}
|
||||
suggestions={suggestions}
|
||||
selectedIndex={selectedIndex}
|
||||
onItemSelect={handleItemSelect}
|
||||
getItemKey={(cmd) => cmd.name}
|
||||
renderItem={(cmd) => (
|
||||
<span className="tracking-wide">
|
||||
<span className="text-muted-foreground">/</span>
|
||||
{cmd.name}
|
||||
</span>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default SlashCommands;
|
||||
|
|
@ -1,49 +0,0 @@
|
|||
import { ReactNode, useEffect, useRef } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Position } from "./useSuggestions";
|
||||
|
||||
interface SuggestionsPopupProps<T> {
|
||||
position: Position;
|
||||
suggestions: T[];
|
||||
selectedIndex: number;
|
||||
onItemSelect: (item: T) => void;
|
||||
renderItem: (item: T, isSelected: boolean) => ReactNode;
|
||||
getItemKey: (item: T, index: number) => string;
|
||||
}
|
||||
|
||||
const POPUP_STYLES = {
|
||||
container:
|
||||
"z-20 absolute p-1 mt-1 -ml-2 max-w-48 max-h-60 rounded border bg-popover text-popover-foreground shadow-lg font-mono flex flex-col overflow-y-auto overflow-x-hidden",
|
||||
item: "rounded p-1 px-2 w-full text-sm cursor-pointer transition-colors select-none hover:bg-accent hover:text-accent-foreground",
|
||||
};
|
||||
|
||||
export function SuggestionsPopup<T>({
|
||||
position,
|
||||
suggestions,
|
||||
selectedIndex,
|
||||
onItemSelect,
|
||||
renderItem,
|
||||
getItemKey,
|
||||
}: SuggestionsPopupProps<T>) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const selectedItemRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
selectedItemRef.current?.scrollIntoView({ block: "nearest", behavior: "smooth" });
|
||||
}, [selectedIndex]);
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className={POPUP_STYLES.container} style={{ left: position.left, top: position.top + position.height }}>
|
||||
{suggestions.map((item, i) => (
|
||||
<div
|
||||
key={getItemKey(item, i)}
|
||||
ref={i === selectedIndex ? selectedItemRef : null}
|
||||
onMouseDown={() => onItemSelect(item)}
|
||||
className={cn(POPUP_STYLES.item, i === selectedIndex && "bg-accent text-accent-foreground")}
|
||||
>
|
||||
{renderItem(item, i === selectedIndex)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,50 +0,0 @@
|
|||
import { useMemo } from "react";
|
||||
import { matchPath } from "react-router-dom";
|
||||
import OverflowTip from "@/components/kit/OverflowTip";
|
||||
import { useTagCounts } from "@/hooks/useUserQueries";
|
||||
import { Routes } from "@/router";
|
||||
import type { TagSuggestionsProps } from "../types";
|
||||
import { SuggestionsPopup } from "./SuggestionsPopup";
|
||||
import { useSuggestions } from "./useSuggestions";
|
||||
|
||||
export default function TagSuggestions({ editorRef, editorActions }: TagSuggestionsProps) {
|
||||
// On explore page, show all users' tags; otherwise show current user's tags
|
||||
const isExplorePage = Boolean(matchPath(Routes.EXPLORE, window.location.pathname));
|
||||
const { data: tagCount = {} } = useTagCounts(!isExplorePage);
|
||||
|
||||
const sortedTags = useMemo(() => {
|
||||
return Object.entries(tagCount)
|
||||
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
||||
.map(([tag]) => tag);
|
||||
}, [tagCount]);
|
||||
|
||||
const { position, suggestions, selectedIndex, isVisible, handleItemSelect } = useSuggestions({
|
||||
editorRef,
|
||||
editorActions,
|
||||
triggerChar: "#",
|
||||
items: sortedTags,
|
||||
filterItems: (items, query) => (!query ? items : items.filter((tag) => tag.toLowerCase().includes(query))),
|
||||
onAutocomplete: (tag, word, index, actions) => {
|
||||
actions.removeText(index, word.length);
|
||||
actions.insertText(`#${tag} `);
|
||||
},
|
||||
});
|
||||
|
||||
if (!isVisible || !position) return null;
|
||||
|
||||
return (
|
||||
<SuggestionsPopup
|
||||
position={position}
|
||||
suggestions={suggestions}
|
||||
selectedIndex={selectedIndex}
|
||||
onItemSelect={handleItemSelect}
|
||||
getItemKey={(tag) => tag}
|
||||
renderItem={(tag) => (
|
||||
<OverflowTip>
|
||||
<span className="text-muted-foreground mr-1">#</span>
|
||||
{tag}
|
||||
</OverflowTip>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
export interface Command {
|
||||
name: string;
|
||||
run: () => string;
|
||||
cursorOffset?: number;
|
||||
}
|
||||
|
||||
export const editorCommands: Command[] = [
|
||||
{
|
||||
name: "todo",
|
||||
run: () => "- [ ] ",
|
||||
cursorOffset: 6,
|
||||
},
|
||||
{
|
||||
name: "code",
|
||||
run: () => "```\n\n```",
|
||||
cursorOffset: 4,
|
||||
},
|
||||
{
|
||||
name: "link",
|
||||
run: () => "[text](url)",
|
||||
cursorOffset: 1,
|
||||
},
|
||||
{
|
||||
name: "table",
|
||||
run: () => "| Header | Header |\n| ------ | ------ |\n| Cell | Cell |",
|
||||
cursorOffset: 1,
|
||||
},
|
||||
];
|
||||
|
|
@ -1,63 +0,0 @@
|
|||
import type { EditorController } from "../types/editorController";
|
||||
import type { EditorRefActions } from "./index";
|
||||
import { toggleTextStyle } from "./shortcuts";
|
||||
|
||||
const TASK_PREFIX = "- [ ] ";
|
||||
|
||||
/**
|
||||
* Adapts the textarea editor's imperative string-surgery API to the shared
|
||||
* EditorController contract. Takes a getter because the underlying ref is
|
||||
* populated after mount and may swap when the editor remounts.
|
||||
*/
|
||||
export function createTextareaController(getActions: () => EditorRefActions | null): EditorController {
|
||||
return {
|
||||
focus: () => getActions()?.focus(),
|
||||
hasFocus: () => {
|
||||
const element = getActions()?.getEditor();
|
||||
return Boolean(element) && document.activeElement === element;
|
||||
},
|
||||
isEmpty: () => (getActions()?.getContent() ?? "").trim() === "",
|
||||
getMarkdown: () => getActions()?.getContent() ?? "",
|
||||
setMarkdown: (markdown) => getActions()?.setContent(markdown),
|
||||
insertMarkdown: (markdown) => {
|
||||
const actions = getActions();
|
||||
if (!actions) return;
|
||||
if (!markdown) return;
|
||||
const content = actions.getContent();
|
||||
const cursor = actions.getCursorPosition();
|
||||
const before = content.slice(0, cursor);
|
||||
const after = content.slice(cursor);
|
||||
const prefix = before.length === 0 || before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n";
|
||||
const suffix = after.length === 0 || after.startsWith("\n\n") ? "" : after.startsWith("\n") ? "\n" : "\n\n";
|
||||
actions.insertText(markdown, prefix, suffix);
|
||||
},
|
||||
scrollToCursor: () => getActions()?.scrollToCursor(),
|
||||
selectAll: () => {
|
||||
const actions = getActions();
|
||||
if (!actions) return;
|
||||
actions.setCursorPosition(0, actions.getContent().length);
|
||||
},
|
||||
toggleBold: () => {
|
||||
const actions = getActions();
|
||||
if (actions) toggleTextStyle(actions, "**");
|
||||
},
|
||||
toggleItalic: () => {
|
||||
const actions = getActions();
|
||||
if (actions) toggleTextStyle(actions, "*");
|
||||
},
|
||||
toggleTaskList: () => {
|
||||
const actions = getActions();
|
||||
if (!actions) return;
|
||||
const lineNumber = actions.getCursorLineNumber();
|
||||
const line = actions.getLine(lineNumber);
|
||||
const taskMatch = line.match(/^(\s*)- \[[ xX]\] /);
|
||||
if (taskMatch) {
|
||||
actions.setLine(lineNumber, taskMatch[1] + line.slice(taskMatch[0].length));
|
||||
} else {
|
||||
const indentMatch = line.match(/^(\s*)/);
|
||||
const indent = indentMatch?.[1] ?? "";
|
||||
actions.setLine(lineNumber, `${indent}${TASK_PREFIX}${line.slice(indent.length)}`);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -1,244 +1,196 @@
|
|||
import { type ClipboardEvent, forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react";
|
||||
import getCaretCoordinates from "textarea-caret";
|
||||
import { Extension } from "@tiptap/core";
|
||||
import { Placeholder } from "@tiptap/extensions";
|
||||
import type { EditorProps as ProseMirrorEditorProps } from "@tiptap/pm/view";
|
||||
import { EditorContent as RichTextContent, useEditor } from "@tiptap/react";
|
||||
import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react";
|
||||
import { matchPath } from "react-router-dom";
|
||||
import { useTagCounts } from "@/hooks/useUserQueries";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ROUTES as Routes } from "@/router/routes";
|
||||
import { EDITOR_HEIGHT } from "../constants";
|
||||
import type { EditorProps } from "../types";
|
||||
import { editorCommands } from "./commands";
|
||||
import SlashCommands from "./SlashCommands";
|
||||
import { getMarkdownLinkForPastedUrl, handleMarkdownShortcuts } from "./shortcuts";
|
||||
import TagSuggestions from "./TagSuggestions";
|
||||
import { useListCompletion } from "./useListCompletion";
|
||||
import type { EditorController } from "../types/editorController";
|
||||
import { buildExtensions } from "./extensions";
|
||||
import { SlashCommand } from "./SlashCommand";
|
||||
import { TagSuggestion } from "./TagSuggestion";
|
||||
|
||||
export interface EditorRefActions {
|
||||
getEditor: () => HTMLTextAreaElement | null;
|
||||
focus: () => void;
|
||||
scrollToCursor: () => void;
|
||||
insertText: (text: string, prefix?: string, suffix?: string) => void;
|
||||
removeText: (start: number, length: number) => void;
|
||||
setContent: (text: string) => void;
|
||||
getContent: () => string;
|
||||
getSelectedContent: () => string;
|
||||
getCursorPosition: () => number;
|
||||
setCursorPosition: (startPos: number, endPos?: number) => void;
|
||||
getCursorLineNumber: () => number;
|
||||
getLine: (lineNumber: number) => string;
|
||||
setLine: (lineNumber: number, text: string) => void;
|
||||
// Mod-Enter is the app-wide "save memo" shortcut (useKeyboard). StarterKit's
|
||||
// HardBreak extension also binds Mod-Enter to insert a hard break, which would
|
||||
// mutate the document right before save fires. This extension swallows the
|
||||
// shortcut (returning true stops further keymap handlers) while preserving
|
||||
// DOM event bubbling — preventDefault does NOT stopPropagation, so the window-
|
||||
// level save listener in useKeyboard still receives and handles the keystroke.
|
||||
// Priority 1000 > HardBreak's default 100, so this handler runs first.
|
||||
// Shift-Enter still inserts a hard break as expected.
|
||||
const SaveShortcutPassthrough = Extension.create({
|
||||
name: "saveShortcutPassthrough",
|
||||
priority: 1000,
|
||||
addKeyboardShortcuts() {
|
||||
return {
|
||||
"Mod-Enter": () => true,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export interface EditorProps {
|
||||
className?: string;
|
||||
initialContent: string;
|
||||
placeholder: string;
|
||||
isFocusMode?: boolean;
|
||||
onContentChange: (content: string) => void;
|
||||
onPaste: (event: React.ClipboardEvent) => void;
|
||||
}
|
||||
|
||||
const Editor = forwardRef(function Editor(props: EditorProps, ref: React.ForwardedRef<EditorRefActions>) {
|
||||
const {
|
||||
className,
|
||||
initialContent,
|
||||
placeholder,
|
||||
onPaste,
|
||||
onContentChange: handleContentChangeCallback,
|
||||
isFocusMode,
|
||||
isInIME = false,
|
||||
onCompositionStart,
|
||||
onCompositionEnd,
|
||||
} = props;
|
||||
const editorRef = useRef<HTMLTextAreaElement>(null);
|
||||
/**
|
||||
* The Document serializer joins/terminates blocks with `\n\n`, so e.g. a task
|
||||
* list serializes with a trailing blank line. Outer whitespace is meaningless
|
||||
* at the document level (the round-trip corpus compares modulo outer trim),
|
||||
* so every markdown string leaving this component is trimmed.
|
||||
*/
|
||||
function serializeMarkdown(editor: { getMarkdown: () => string } | null): string {
|
||||
return (editor?.getMarkdown() ?? "").trim();
|
||||
}
|
||||
|
||||
const updateEditorHeight = useCallback(() => {
|
||||
if (editorRef.current) {
|
||||
editorRef.current.style.height = "auto";
|
||||
editorRef.current.style.height = `${editorRef.current.scrollHeight ?? 0}px`;
|
||||
}
|
||||
}, []);
|
||||
/**
|
||||
* WYSIWYG memo editor built on ProseMirror. Markdown is the only format
|
||||
* crossing its boundary: in via setContent(contentType: "markdown"), out via
|
||||
* serializeMarkdown() on every update. IME, list continuation, input rules,
|
||||
* and auto-grow are native ProseMirror/contenteditable behavior.
|
||||
*/
|
||||
const Editor = forwardRef<EditorController, EditorProps>(function Editor(props, ref) {
|
||||
const { className, initialContent, placeholder, isFocusMode, onContentChange, onPaste } = props;
|
||||
|
||||
const updateContent = useCallback(() => {
|
||||
if (editorRef.current) {
|
||||
handleContentChangeCallback(editorRef.current.value);
|
||||
updateEditorHeight();
|
||||
}
|
||||
}, [handleContentChangeCallback, updateEditorHeight]);
|
||||
// Last markdown emitted through onContentChange, so the sync effect can
|
||||
// recognize the parent echoing our own value back without re-serializing.
|
||||
const lastEmittedRef = useRef<string | null>(null);
|
||||
// Read through refs so the memoized extension/editorProps closures below
|
||||
// always see the latest props (Placeholder decorations recompute per
|
||||
// transaction; handlePaste resolves per event).
|
||||
const placeholderRef = useRef(placeholder);
|
||||
placeholderRef.current = placeholder;
|
||||
const onPasteRef = useRef(onPaste);
|
||||
onPasteRef.current = onPaste;
|
||||
|
||||
const scrollToCaret = useCallback((options: { force?: boolean } = {}) => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return;
|
||||
// On the explore page suggestions include all users' tags; otherwise the
|
||||
// current user's. Same sourcing as the raw editor's TagSuggestions.
|
||||
const isExplorePage = useMemo(() => Boolean(matchPath(Routes.EXPLORE, window.location.pathname)), []);
|
||||
const { data: tagCount = {} } = useTagCounts(!isExplorePage);
|
||||
const sortedTags = useMemo(
|
||||
() =>
|
||||
Object.entries(tagCount)
|
||||
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
||||
.map(([tag]) => tag),
|
||||
[tagCount],
|
||||
);
|
||||
const tagsRef = useRef<string[]>([]);
|
||||
tagsRef.current = sortedTags;
|
||||
|
||||
const { force = false } = options;
|
||||
const caret = getCaretCoordinates(editor, editor.selectionEnd);
|
||||
|
||||
if (force) {
|
||||
editor.scrollTop = Math.max(0, caret.top - editor.clientHeight / 2);
|
||||
return;
|
||||
}
|
||||
|
||||
const lineHeight = parseFloat(getComputedStyle(editor).lineHeight) || 24;
|
||||
const viewportBottom = editor.scrollTop + editor.clientHeight;
|
||||
// Scroll if cursor is near or beyond bottom edge (within 2 lines)
|
||||
if (caret.top + lineHeight * 2 > viewportBottom) {
|
||||
editor.scrollTop = Math.max(0, caret.top - editor.clientHeight / 2);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (editorRef.current && initialContent) {
|
||||
editorRef.current.value = initialContent;
|
||||
handleContentChangeCallback(initialContent);
|
||||
updateEditorHeight();
|
||||
}
|
||||
// Only run once on mount to set initial content
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// Update editor when content is externally changed (e.g., reset after save)
|
||||
useEffect(() => {
|
||||
if (editorRef.current && editorRef.current.value !== initialContent) {
|
||||
editorRef.current.value = initialContent;
|
||||
updateEditorHeight();
|
||||
}
|
||||
}, [initialContent, updateEditorHeight]);
|
||||
|
||||
const editorActions: EditorRefActions = useMemo(
|
||||
// Stable option identities so useEditor's compareOptions stays equal across
|
||||
// renders and the editor skips a needless setOptions/view.setProps pass per
|
||||
// keystroke. All dynamic values reach the closures through refs above.
|
||||
// `content` is only consumed at editor creation — later external changes
|
||||
// flow through the sync effect — so the mount-time value is frozen too.
|
||||
const mountContentRef = useRef(initialContent);
|
||||
const extensions = useMemo(
|
||||
() => [
|
||||
...buildExtensions(),
|
||||
Placeholder.configure({ placeholder: () => placeholderRef.current }),
|
||||
TagSuggestion.configure({ getTags: () => tagsRef.current }),
|
||||
SlashCommand,
|
||||
SaveShortcutPassthrough,
|
||||
],
|
||||
[],
|
||||
);
|
||||
const editorProps = useMemo<ProseMirrorEditorProps>(
|
||||
() => ({
|
||||
getEditor: () => editorRef.current,
|
||||
focus: () => editorRef.current?.focus(),
|
||||
scrollToCursor: () => {
|
||||
scrollToCaret({ force: true });
|
||||
attributes: {
|
||||
class: "memo-wysiwyg outline-none w-full text-base break-words min-h-6",
|
||||
},
|
||||
insertText: (content = "", prefix = "", suffix = "") => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return;
|
||||
|
||||
const cursorPos = editor.selectionStart;
|
||||
const endPos = editor.selectionEnd;
|
||||
const prev = editor.value;
|
||||
const actual = content || prev.slice(cursorPos, endPos);
|
||||
editor.value = prev.slice(0, cursorPos) + prefix + actual + suffix + prev.slice(endPos);
|
||||
|
||||
editor.focus();
|
||||
editor.setSelectionRange(cursorPos + prefix.length + actual.length, cursorPos + prefix.length + actual.length);
|
||||
updateContent();
|
||||
},
|
||||
removeText: (start: number, length: number) => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return;
|
||||
|
||||
editor.value = editor.value.slice(0, start) + editor.value.slice(start + length);
|
||||
editor.focus();
|
||||
editor.setSelectionRange(start, start);
|
||||
updateContent();
|
||||
},
|
||||
setContent: (text: string) => {
|
||||
const editor = editorRef.current;
|
||||
if (editor) {
|
||||
editor.value = text;
|
||||
updateContent();
|
||||
handlePaste: (_view, event) => {
|
||||
const hasFiles = Array.from(event.clipboardData?.items ?? []).some((item) => item.kind === "file");
|
||||
if (hasFiles) {
|
||||
onPasteRef.current(event as unknown as React.ClipboardEvent);
|
||||
return true;
|
||||
}
|
||||
},
|
||||
getContent: () => editorRef.current?.value ?? "",
|
||||
getCursorPosition: () => editorRef.current?.selectionStart ?? 0,
|
||||
getSelectedContent: () => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return "";
|
||||
return editor.value.slice(editor.selectionStart, editor.selectionEnd);
|
||||
},
|
||||
setCursorPosition: (startPos: number, endPos?: number) => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return;
|
||||
// setSelectionRange requires valid arguments; default to startPos if endPos is undefined
|
||||
const endPosition = endPos !== undefined && !Number.isNaN(endPos) ? endPos : startPos;
|
||||
editor.setSelectionRange(startPos, endPosition);
|
||||
},
|
||||
getCursorLineNumber: () => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return 0;
|
||||
const lines = editor.value.slice(0, editor.selectionStart).split("\n");
|
||||
return lines.length - 1;
|
||||
},
|
||||
getLine: (lineNumber: number) => editorRef.current?.value.split("\n")[lineNumber] ?? "",
|
||||
setLine: (lineNumber: number, text: string) => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return;
|
||||
const lines = editor.value.split("\n");
|
||||
lines[lineNumber] = text;
|
||||
editor.value = lines.join("\n");
|
||||
editor.focus();
|
||||
updateContent();
|
||||
// Text paste (incl. URL-over-selection → link) is handled natively.
|
||||
return false;
|
||||
},
|
||||
}),
|
||||
[updateContent, scrollToCaret],
|
||||
[],
|
||||
);
|
||||
|
||||
useImperativeHandle(ref, () => editorActions, [editorActions]);
|
||||
|
||||
const handleEditorInput = useCallback(() => {
|
||||
if (editorRef.current) {
|
||||
handleContentChangeCallback(editorRef.current.value);
|
||||
updateEditorHeight();
|
||||
|
||||
// Auto-scroll to keep cursor visible when typing
|
||||
// See: https://github.com/usememos/memos/issues/5469
|
||||
scrollToCaret();
|
||||
}
|
||||
}, [handleContentChangeCallback, updateEditorHeight, scrollToCaret]);
|
||||
|
||||
// Auto-complete markdown lists when pressing Enter
|
||||
useListCompletion({
|
||||
editorRef,
|
||||
editorActions,
|
||||
isInIME,
|
||||
const editor = useEditor({
|
||||
extensions,
|
||||
content: mountContentRef.current,
|
||||
contentType: "markdown",
|
||||
editorProps,
|
||||
onUpdate: ({ editor: currentEditor }) => {
|
||||
const markdown = serializeMarkdown(currentEditor);
|
||||
lastEmittedRef.current = markdown;
|
||||
onContentChange(markdown);
|
||||
},
|
||||
});
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(event: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if ((event.ctrlKey || event.metaKey) && !isInIME) {
|
||||
handleMarkdownShortcuts(event, editorActions);
|
||||
}
|
||||
},
|
||||
[editorActions, isInIME],
|
||||
);
|
||||
|
||||
const handleEditorPaste = useCallback(
|
||||
(event: ClipboardEvent<HTMLTextAreaElement>) => {
|
||||
const editor = editorRef.current;
|
||||
const pastedText = event.clipboardData?.getData("text/plain") || event.clipboardData?.getData("text");
|
||||
const markdownLink = editor ? getMarkdownLinkForPastedUrl(editorActions.getSelectedContent(), pastedText) : undefined;
|
||||
|
||||
if (markdownLink) {
|
||||
event.preventDefault();
|
||||
editorActions.insertText(markdownLink);
|
||||
return;
|
||||
}
|
||||
|
||||
onPaste(event);
|
||||
},
|
||||
[editorActions, onPaste],
|
||||
);
|
||||
|
||||
// Recalculate editor height when focus mode changes
|
||||
// Sync external content changes (e.g. reset after save, draft restore)
|
||||
// without clobbering the document the user is typing into: only apply when
|
||||
// the markdown actually differs.
|
||||
useEffect(() => {
|
||||
updateEditorHeight();
|
||||
}, [isFocusMode, updateEditorHeight]);
|
||||
if (!editor) {
|
||||
return;
|
||||
}
|
||||
// Parent echo of our own emission — nothing to sync (O(1) fast path).
|
||||
// Comparing against the live document instead would race: a keystroke
|
||||
// landing between the emission and this passive effect would make the
|
||||
// echo look like an external change and clobber the keystroke/cursor.
|
||||
if (initialContent === lastEmittedRef.current) {
|
||||
return;
|
||||
}
|
||||
// Never clobber an in-progress IME composition.
|
||||
if (editor.view.composing) {
|
||||
return;
|
||||
}
|
||||
if (serializeMarkdown(editor) !== initialContent.trim()) {
|
||||
editor.commands.setContent(initialContent, { contentType: "markdown", emitUpdate: false });
|
||||
// A subsequent identical echo of this value is also a no-op.
|
||||
lastEmittedRef.current = initialContent;
|
||||
}
|
||||
}, [initialContent, editor]);
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
(): EditorController => ({
|
||||
focus: () => editor?.commands.focus(),
|
||||
hasFocus: () => editor?.isFocused ?? false,
|
||||
// Contract: whitespace-only counts as empty. The editor's structural
|
||||
// `editor.isEmpty` would call a paragraph of spaces non-empty.
|
||||
isEmpty: () => serializeMarkdown(editor) === "",
|
||||
getMarkdown: () => serializeMarkdown(editor),
|
||||
setMarkdown: (markdown) => editor?.commands.setContent(markdown, { contentType: "markdown" }),
|
||||
insertMarkdown: (markdown) => editor?.chain().focus().insertContent(markdown, { contentType: "markdown" }).run(),
|
||||
scrollToCursor: () => editor?.commands.scrollIntoView(),
|
||||
selectAll: () => editor?.commands.selectAll(),
|
||||
toggleBold: () => editor?.chain().focus().toggleBold().run(),
|
||||
toggleItalic: () => editor?.chain().focus().toggleItalic().run(),
|
||||
toggleTaskList: () => editor?.chain().focus().toggleTaskList().run(),
|
||||
}),
|
||||
[editor],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col justify-start items-start relative w-full bg-inherit",
|
||||
// Focus mode: flex-1 to grow and fill space; Normal: h-auto with max-height
|
||||
"flex flex-col justify-start items-start relative w-full bg-inherit overflow-y-auto overflow-x-hidden",
|
||||
isFocusMode ? "flex-1" : `h-auto ${EDITOR_HEIGHT.normal}`,
|
||||
className,
|
||||
)}
|
||||
onClick={(event) => {
|
||||
// In focus mode the wrapper extends below the content; a click on the
|
||||
// empty area should land the caret at the end instead of doing nothing.
|
||||
if (event.target === event.currentTarget) {
|
||||
editor?.commands.focus("end");
|
||||
}
|
||||
}}
|
||||
>
|
||||
<textarea
|
||||
className={cn(
|
||||
"w-full text-base resize-none overflow-x-hidden overflow-y-auto bg-transparent outline-none placeholder:opacity-70 whitespace-pre-wrap wrap-break-word",
|
||||
// Focus mode: flex-1 h-0 to grow within flex container; Normal: h-full to fill wrapper
|
||||
isFocusMode ? "flex-1 h-0" : "h-full",
|
||||
)}
|
||||
rows={1}
|
||||
placeholder={placeholder}
|
||||
ref={editorRef}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handleEditorPaste}
|
||||
onInput={handleEditorInput}
|
||||
onCompositionStart={onCompositionStart}
|
||||
onCompositionEnd={onCompositionEnd}
|
||||
></textarea>
|
||||
<TagSuggestions editorRef={editorRef} editorActions={ref} />
|
||||
<SlashCommands editorRef={editorRef} editorActions={ref} commands={editorCommands} />
|
||||
<RichTextContent editor={editor} className="w-full" />
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,102 +0,0 @@
|
|||
import type { EditorRefActions } from "./index";
|
||||
|
||||
const SHORTCUTS = {
|
||||
BOLD: { key: "b", delimiter: "**" },
|
||||
ITALIC: { key: "i", delimiter: "*" },
|
||||
} as const;
|
||||
|
||||
const URL_PLACEHOLDER = "url";
|
||||
const URL_REGEX = /^https?:\/\/[^\s]+$/;
|
||||
const LINK_OFFSET = 3; // Length of "]()"
|
||||
|
||||
export function handleMarkdownShortcuts(event: React.KeyboardEvent, editor: EditorRefActions): void {
|
||||
const key = event.key.toLowerCase();
|
||||
if (key === SHORTCUTS.BOLD.key) {
|
||||
event.preventDefault();
|
||||
toggleTextStyle(editor, SHORTCUTS.BOLD.delimiter);
|
||||
} else if (key === SHORTCUTS.ITALIC.key) {
|
||||
event.preventDefault();
|
||||
toggleTextStyle(editor, SHORTCUTS.ITALIC.delimiter);
|
||||
}
|
||||
}
|
||||
|
||||
export function insertHyperlink(editor: EditorRefActions, url?: string): void {
|
||||
const cursorPosition = editor.getCursorPosition();
|
||||
const selectedContent = editor.getSelectedContent();
|
||||
const isUrlSelected = !url && URL_REGEX.test(selectedContent.trim());
|
||||
|
||||
if (isUrlSelected) {
|
||||
editor.insertText(`[](${selectedContent})`);
|
||||
editor.setCursorPosition(cursorPosition + 1, cursorPosition + 1);
|
||||
return;
|
||||
}
|
||||
|
||||
const href = url ?? URL_PLACEHOLDER;
|
||||
editor.insertText(`[${selectedContent}](${href})`);
|
||||
|
||||
if (href === URL_PLACEHOLDER) {
|
||||
const urlStart = cursorPosition + selectedContent.length + LINK_OFFSET;
|
||||
editor.setCursorPosition(urlStart, urlStart + href.length);
|
||||
}
|
||||
}
|
||||
|
||||
export function toggleTextStyle(editor: EditorRefActions, delimiter: string): void {
|
||||
const cursorPosition = editor.getCursorPosition();
|
||||
const selectedContent = editor.getSelectedContent();
|
||||
const isStyled = isTextStyled(selectedContent, delimiter);
|
||||
|
||||
if (isStyled) {
|
||||
const unstyled = selectedContent.slice(delimiter.length, -delimiter.length);
|
||||
editor.insertText(unstyled);
|
||||
editor.setCursorPosition(cursorPosition, cursorPosition + unstyled.length);
|
||||
} else {
|
||||
editor.insertText(`${delimiter}${selectedContent}${delimiter}`);
|
||||
editor.setCursorPosition(cursorPosition + delimiter.length, cursorPosition + delimiter.length + selectedContent.length);
|
||||
}
|
||||
}
|
||||
|
||||
function isTextStyled(text: string, delimiter: string): boolean {
|
||||
if (!text.startsWith(delimiter) || !text.endsWith(delimiter)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (delimiter !== "*") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const leadingAsterisks = countConsecutive(text, "*", "start");
|
||||
const trailingAsterisks = countConsecutive(text, "*", "end");
|
||||
return leadingAsterisks % 2 === 1 && trailingAsterisks % 2 === 1;
|
||||
}
|
||||
|
||||
function countConsecutive(text: string, character: string, position: "start" | "end"): number {
|
||||
let count = 0;
|
||||
let index = position === "start" ? 0 : text.length - 1;
|
||||
|
||||
while (index >= 0 && index < text.length && text[index] === character) {
|
||||
count += 1;
|
||||
index += position === "start" ? 1 : -1;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
export function hyperlinkHighlightedText(editor: EditorRefActions, url: string): void {
|
||||
const selectedContent = editor.getSelectedContent();
|
||||
const cursorPosition = editor.getCursorPosition();
|
||||
|
||||
editor.insertText(`[${selectedContent}](${url})`);
|
||||
|
||||
const newPosition = cursorPosition + selectedContent.length + url.length + 4;
|
||||
editor.setCursorPosition(newPosition, newPosition);
|
||||
}
|
||||
|
||||
export function getMarkdownLinkForPastedUrl(selectedContent: string, pastedText: string): string | undefined {
|
||||
const url = pastedText.trim();
|
||||
|
||||
if (!selectedContent || !URL_REGEX.test(url) || URL_REGEX.test(selectedContent.trim())) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return `[${selectedContent}](${url})`;
|
||||
}
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
import { type RefObject, useEffect, useRef } from "react";
|
||||
import { detectLastListItem, generateListContinuation } from "@/utils/markdown-list-detection";
|
||||
import { EditorRefActions } from ".";
|
||||
|
||||
interface UseListCompletionOptions {
|
||||
editorRef: RefObject<HTMLTextAreaElement | null>;
|
||||
editorActions: EditorRefActions;
|
||||
isInIME: boolean;
|
||||
}
|
||||
|
||||
// Patterns to detect empty list items
|
||||
const EMPTY_LIST_PATTERNS = [
|
||||
/^(\s*)([-*+])\s*$/, // Empty unordered list
|
||||
/^(\s*)([-*+])\s+\[([ xX])\]\s*$/, // Empty task list
|
||||
/^(\s*)(\d+)[.)]\s*$/, // Empty ordered list
|
||||
];
|
||||
|
||||
const isEmptyListItem = (line: string) => EMPTY_LIST_PATTERNS.some((pattern) => pattern.test(line));
|
||||
|
||||
export function useListCompletion({ editorRef, editorActions, isInIME }: UseListCompletionOptions) {
|
||||
const isInIMERef = useRef(isInIME);
|
||||
isInIMERef.current = isInIME;
|
||||
|
||||
const editorActionsRef = useRef(editorActions);
|
||||
editorActionsRef.current = editorActions;
|
||||
|
||||
// Track when composition ends to handle Safari race condition
|
||||
// Safari fires keydown(Enter) immediately after compositionend, while Chrome doesn't
|
||||
// See: https://github.com/usememos/memos/issues/5469
|
||||
const lastCompositionEndRef = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return;
|
||||
|
||||
const handleCompositionEnd = () => {
|
||||
lastCompositionEndRef.current = Date.now();
|
||||
};
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Enter" || isInIMERef.current || event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Safari fix: Ignore Enter key within 100ms of composition end
|
||||
// This prevents double-enter behavior when confirming IME input in lists
|
||||
if (Date.now() - lastCompositionEndRef.current < 100) {
|
||||
return;
|
||||
}
|
||||
|
||||
const actions = editorActionsRef.current;
|
||||
const cursorPosition = actions.getCursorPosition();
|
||||
const contentBeforeCursor = actions.getContent().substring(0, cursorPosition);
|
||||
const listInfo = detectLastListItem(contentBeforeCursor);
|
||||
|
||||
if (!listInfo.type) return;
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
const lines = contentBeforeCursor.split("\n");
|
||||
const currentLine = lines[lines.length - 1];
|
||||
|
||||
if (isEmptyListItem(currentLine)) {
|
||||
const lineStartPos = cursorPosition - currentLine.length;
|
||||
actions.removeText(lineStartPos, currentLine.length);
|
||||
} else {
|
||||
const continuation = generateListContinuation(listInfo);
|
||||
actions.insertText("\n" + continuation);
|
||||
|
||||
// Auto-scroll to keep cursor visible after inserting list item
|
||||
setTimeout(() => actions.scrollToCursor(), 0);
|
||||
}
|
||||
};
|
||||
|
||||
editor.addEventListener("compositionend", handleCompositionEnd);
|
||||
editor.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
editor.removeEventListener("compositionend", handleCompositionEnd);
|
||||
editor.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
|
|
@ -1,165 +0,0 @@
|
|||
import { type ForwardedRef, type RefObject, useEffect, useRef, useState } from "react";
|
||||
import getCaretCoordinates from "textarea-caret";
|
||||
import { EditorRefActions } from ".";
|
||||
|
||||
export interface Position {
|
||||
left: number;
|
||||
top: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface UseSuggestionsOptions<T> {
|
||||
editorRef: RefObject<HTMLTextAreaElement | null>;
|
||||
editorActions: ForwardedRef<EditorRefActions>;
|
||||
triggerChar: string;
|
||||
items: T[];
|
||||
filterItems: (items: T[], searchQuery: string) => T[];
|
||||
onAutocomplete: (item: T, word: string, startIndex: number, actions: EditorRefActions) => void;
|
||||
}
|
||||
|
||||
export interface UseSuggestionsReturn<T> {
|
||||
position: Position | null;
|
||||
suggestions: T[];
|
||||
selectedIndex: number;
|
||||
isVisible: boolean;
|
||||
searchQuery: string;
|
||||
handleItemSelect: (item: T) => void;
|
||||
}
|
||||
|
||||
export function useSuggestions<T>({
|
||||
editorRef,
|
||||
editorActions,
|
||||
triggerChar,
|
||||
items,
|
||||
filterItems,
|
||||
onAutocomplete,
|
||||
}: UseSuggestionsOptions<T>): UseSuggestionsReturn<T> {
|
||||
const [position, setPosition] = useState<Position | null>(null);
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const isProcessingRef = useRef(false);
|
||||
|
||||
const selectedRef = useRef(selectedIndex);
|
||||
selectedRef.current = selectedIndex;
|
||||
|
||||
const getCurrentWord = (): [word: string, startIndex: number] => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return ["", 0];
|
||||
const cursorPos = editor.selectionEnd;
|
||||
const before = editor.value.slice(0, cursorPos).match(/\S*$/) || { 0: "", index: cursorPos };
|
||||
const after = editor.value.slice(cursorPos).match(/^\S*/) || { 0: "" };
|
||||
return [before[0] + after[0], before.index ?? cursorPos];
|
||||
};
|
||||
|
||||
const hide = () => setPosition(null);
|
||||
|
||||
const suggestionsRef = useRef<T[]>([]);
|
||||
const searchQueryRef = useRef("");
|
||||
suggestionsRef.current = (() => {
|
||||
const [word] = getCurrentWord();
|
||||
if (!word.startsWith(triggerChar)) return [];
|
||||
searchQueryRef.current = word.slice(triggerChar.length).toLowerCase();
|
||||
return filterItems(items, searchQueryRef.current);
|
||||
})();
|
||||
if (suggestionsRef.current.length === 0) {
|
||||
const [word] = getCurrentWord();
|
||||
searchQueryRef.current = word.startsWith(triggerChar) ? word.slice(triggerChar.length).toLowerCase() : "";
|
||||
}
|
||||
|
||||
const isVisibleRef = useRef(false);
|
||||
isVisibleRef.current = !!(position && suggestionsRef.current.length > 0);
|
||||
|
||||
const handleAutocomplete = (item: T) => {
|
||||
if (!editorActions || !("current" in editorActions) || !editorActions.current) {
|
||||
console.warn("useSuggestions: editorActions not available");
|
||||
return;
|
||||
}
|
||||
isProcessingRef.current = true;
|
||||
const [word, index] = getCurrentWord();
|
||||
onAutocomplete(item, word, index, editorActions.current);
|
||||
hide();
|
||||
// Re-enable input handling after all DOM operations complete
|
||||
queueMicrotask(() => {
|
||||
isProcessingRef.current = false;
|
||||
});
|
||||
};
|
||||
|
||||
const handleNavigation = (e: KeyboardEvent, selected: number, suggestionsCount: number) => {
|
||||
if (e.code === "ArrowDown") {
|
||||
setSelectedIndex((selected + 1) % suggestionsCount);
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
} else if (e.code === "ArrowUp") {
|
||||
setSelectedIndex((selected - 1 + suggestionsCount) % suggestionsCount);
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (!isVisibleRef.current) return;
|
||||
|
||||
const suggestions = suggestionsRef.current;
|
||||
const selected = selectedRef.current;
|
||||
|
||||
if (["Escape", "ArrowLeft", "ArrowRight"].includes(e.code)) {
|
||||
hide();
|
||||
return;
|
||||
}
|
||||
|
||||
if (["ArrowDown", "ArrowUp"].includes(e.code)) {
|
||||
handleNavigation(e, selected, suggestions.length);
|
||||
return;
|
||||
}
|
||||
|
||||
if (["Enter", "Tab"].includes(e.code)) {
|
||||
handleAutocomplete(suggestions[selected]);
|
||||
e.preventDefault();
|
||||
e.stopImmediatePropagation();
|
||||
}
|
||||
};
|
||||
|
||||
const handleInput = () => {
|
||||
if (isProcessingRef.current) return;
|
||||
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return;
|
||||
|
||||
setSelectedIndex(0);
|
||||
const [word, index] = getCurrentWord();
|
||||
const currentChar = editor.value[editor.selectionEnd];
|
||||
const isActive = word.startsWith(triggerChar) && currentChar !== triggerChar;
|
||||
|
||||
if (isActive) {
|
||||
const coords = getCaretCoordinates(editor, index);
|
||||
coords.top -= editor.scrollTop;
|
||||
setPosition(coords);
|
||||
} else {
|
||||
hide();
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return;
|
||||
|
||||
const handlers = { click: hide, blur: hide, keydown: handleKeyDown, input: handleInput };
|
||||
Object.entries(handlers).forEach(([event, handler]) => {
|
||||
editor.addEventListener(event, handler as EventListener);
|
||||
});
|
||||
|
||||
return () => {
|
||||
Object.entries(handlers).forEach(([event, handler]) => {
|
||||
editor.removeEventListener(event, handler as EventListener);
|
||||
});
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {
|
||||
position,
|
||||
suggestions: suggestionsRef.current,
|
||||
selectedIndex,
|
||||
isVisible: isVisibleRef.current,
|
||||
searchQuery: searchQueryRef.current,
|
||||
handleItemSelect: handleAutocomplete,
|
||||
};
|
||||
}
|
||||
273
web/src/components/MemoEditor/PlainEditor/index.tsx
Normal file
273
web/src/components/MemoEditor/PlainEditor/index.tsx
Normal file
|
|
@ -0,0 +1,273 @@
|
|||
import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react";
|
||||
import getCaretCoordinates from "textarea-caret";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { EDITOR_HEIGHT } from "../constants";
|
||||
import type { EditorController } from "../types/editorController";
|
||||
|
||||
interface PlainEditorProps {
|
||||
className: string;
|
||||
initialContent: string;
|
||||
placeholder: string;
|
||||
onContentChange: (content: string) => void;
|
||||
onPaste: (event: React.ClipboardEvent) => void;
|
||||
isFocusMode?: boolean;
|
||||
}
|
||||
|
||||
// Low-level string-surgery handle over the textarea. Internal to this file —
|
||||
// outside callers only ever see the EditorController exposed via the ref.
|
||||
interface TextareaActions {
|
||||
getEditor: () => HTMLTextAreaElement | null;
|
||||
focus: () => void;
|
||||
scrollToCursor: () => void;
|
||||
insertText: (text: string, prefix?: string, suffix?: string) => void;
|
||||
setContent: (text: string) => void;
|
||||
getContent: () => string;
|
||||
getSelectedContent: () => string;
|
||||
getCursorPosition: () => number;
|
||||
setCursorPosition: (startPos: number, endPos?: number) => void;
|
||||
getCursorLineNumber: () => number;
|
||||
getLine: (lineNumber: number) => string;
|
||||
setLine: (lineNumber: number, text: string) => void;
|
||||
}
|
||||
|
||||
const TASK_PREFIX = "- [ ] ";
|
||||
|
||||
const PlainEditor = forwardRef(function PlainEditor(props: PlainEditorProps, ref: React.ForwardedRef<EditorController>) {
|
||||
const { className, initialContent, placeholder, onPaste, onContentChange: handleContentChangeCallback, isFocusMode } = props;
|
||||
const editorRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
const updateEditorHeight = useCallback(() => {
|
||||
if (editorRef.current) {
|
||||
editorRef.current.style.height = "auto";
|
||||
editorRef.current.style.height = `${editorRef.current.scrollHeight ?? 0}px`;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const updateContent = useCallback(() => {
|
||||
if (editorRef.current) {
|
||||
handleContentChangeCallback(editorRef.current.value);
|
||||
updateEditorHeight();
|
||||
}
|
||||
}, [handleContentChangeCallback, updateEditorHeight]);
|
||||
|
||||
const scrollToCaret = useCallback((options: { force?: boolean } = {}) => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return;
|
||||
|
||||
const { force = false } = options;
|
||||
const caret = getCaretCoordinates(editor, editor.selectionEnd);
|
||||
|
||||
if (force) {
|
||||
editor.scrollTop = Math.max(0, caret.top - editor.clientHeight / 2);
|
||||
return;
|
||||
}
|
||||
|
||||
const lineHeight = parseFloat(getComputedStyle(editor).lineHeight) || 24;
|
||||
const viewportBottom = editor.scrollTop + editor.clientHeight;
|
||||
// Scroll if cursor is near or beyond bottom edge (within 2 lines)
|
||||
if (caret.top + lineHeight * 2 > viewportBottom) {
|
||||
editor.scrollTop = Math.max(0, caret.top - editor.clientHeight / 2);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (editorRef.current && initialContent) {
|
||||
editorRef.current.value = initialContent;
|
||||
handleContentChangeCallback(initialContent);
|
||||
updateEditorHeight();
|
||||
}
|
||||
// Only run once on mount to set initial content
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// Update editor when content is externally changed (e.g., reset after save)
|
||||
useEffect(() => {
|
||||
if (editorRef.current && editorRef.current.value !== initialContent) {
|
||||
editorRef.current.value = initialContent;
|
||||
updateEditorHeight();
|
||||
}
|
||||
}, [initialContent, updateEditorHeight]);
|
||||
|
||||
const actions: TextareaActions = useMemo(
|
||||
() => ({
|
||||
getEditor: () => editorRef.current,
|
||||
focus: () => editorRef.current?.focus(),
|
||||
scrollToCursor: () => {
|
||||
scrollToCaret({ force: true });
|
||||
},
|
||||
insertText: (content = "", prefix = "", suffix = "") => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return;
|
||||
|
||||
const cursorPos = editor.selectionStart;
|
||||
const endPos = editor.selectionEnd;
|
||||
const prev = editor.value;
|
||||
const actual = content || prev.slice(cursorPos, endPos);
|
||||
editor.value = prev.slice(0, cursorPos) + prefix + actual + suffix + prev.slice(endPos);
|
||||
|
||||
editor.focus();
|
||||
editor.setSelectionRange(cursorPos + prefix.length + actual.length, cursorPos + prefix.length + actual.length);
|
||||
updateContent();
|
||||
},
|
||||
setContent: (text: string) => {
|
||||
const editor = editorRef.current;
|
||||
if (editor) {
|
||||
editor.value = text;
|
||||
updateContent();
|
||||
}
|
||||
},
|
||||
getContent: () => editorRef.current?.value ?? "",
|
||||
getSelectedContent: () => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return "";
|
||||
return editor.value.slice(editor.selectionStart, editor.selectionEnd);
|
||||
},
|
||||
getCursorPosition: () => editorRef.current?.selectionStart ?? 0,
|
||||
setCursorPosition: (startPos: number, endPos?: number) => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return;
|
||||
// setSelectionRange requires valid arguments; default to startPos if endPos is undefined
|
||||
const endPosition = endPos !== undefined && !Number.isNaN(endPos) ? endPos : startPos;
|
||||
editor.setSelectionRange(startPos, endPosition);
|
||||
},
|
||||
getCursorLineNumber: () => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return 0;
|
||||
const lines = editor.value.slice(0, editor.selectionStart).split("\n");
|
||||
return lines.length - 1;
|
||||
},
|
||||
getLine: (lineNumber: number) => editorRef.current?.value.split("\n")[lineNumber] ?? "",
|
||||
setLine: (lineNumber: number, text: string) => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return;
|
||||
const lines = editor.value.split("\n");
|
||||
lines[lineNumber] = text;
|
||||
editor.value = lines.join("\n");
|
||||
editor.focus();
|
||||
updateContent();
|
||||
},
|
||||
}),
|
||||
[updateContent, scrollToCaret],
|
||||
);
|
||||
|
||||
// Realize the shared EditorController contract on top of textarea surgery, so
|
||||
// the toolbar's formatting toggles and the mode-routing host talk markdown.
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
(): EditorController => ({
|
||||
focus: () => actions.focus(),
|
||||
hasFocus: () => {
|
||||
const element = actions.getEditor();
|
||||
return Boolean(element) && document.activeElement === element;
|
||||
},
|
||||
isEmpty: () => actions.getContent().trim() === "",
|
||||
getMarkdown: () => actions.getContent(),
|
||||
setMarkdown: (markdown) => actions.setContent(markdown),
|
||||
insertMarkdown: (markdown) => {
|
||||
if (!markdown) return;
|
||||
const content = actions.getContent();
|
||||
const cursor = actions.getCursorPosition();
|
||||
const before = content.slice(0, cursor);
|
||||
const after = content.slice(cursor);
|
||||
const prefix = before.length === 0 || before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n";
|
||||
const suffix = after.length === 0 || after.startsWith("\n\n") ? "" : after.startsWith("\n") ? "\n" : "\n\n";
|
||||
actions.insertText(markdown, prefix, suffix);
|
||||
},
|
||||
scrollToCursor: () => actions.scrollToCursor(),
|
||||
selectAll: () => actions.setCursorPosition(0, actions.getContent().length),
|
||||
toggleBold: () => toggleTextStyle(actions, "**"),
|
||||
toggleItalic: () => toggleTextStyle(actions, "*"),
|
||||
toggleTaskList: () => {
|
||||
const lineNumber = actions.getCursorLineNumber();
|
||||
const line = actions.getLine(lineNumber);
|
||||
const taskMatch = line.match(/^(\s*)- \[[ xX]\] /);
|
||||
if (taskMatch) {
|
||||
actions.setLine(lineNumber, taskMatch[1] + line.slice(taskMatch[0].length));
|
||||
} else {
|
||||
const indent = line.match(/^(\s*)/)?.[1] ?? "";
|
||||
actions.setLine(lineNumber, `${indent}${TASK_PREFIX}${line.slice(indent.length)}`);
|
||||
}
|
||||
},
|
||||
}),
|
||||
[actions],
|
||||
);
|
||||
|
||||
const handleEditorInput = useCallback(() => {
|
||||
if (editorRef.current) {
|
||||
handleContentChangeCallback(editorRef.current.value);
|
||||
updateEditorHeight();
|
||||
|
||||
// Auto-scroll to keep cursor visible when typing
|
||||
// See: https://github.com/usememos/memos/issues/5469
|
||||
scrollToCaret();
|
||||
}
|
||||
}, [handleContentChangeCallback, updateEditorHeight, scrollToCaret]);
|
||||
|
||||
// Recalculate editor height when focus mode changes
|
||||
useEffect(() => {
|
||||
updateEditorHeight();
|
||||
}, [isFocusMode, updateEditorHeight]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col justify-start items-start relative w-full bg-inherit",
|
||||
// Focus mode: flex-1 to grow and fill space; Normal: h-auto with max-height
|
||||
isFocusMode ? "flex-1" : `h-auto ${EDITOR_HEIGHT.normal}`,
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<textarea
|
||||
className={cn(
|
||||
"w-full text-base resize-none overflow-x-hidden overflow-y-auto bg-transparent outline-none placeholder:opacity-70 whitespace-pre-wrap wrap-break-word",
|
||||
// Focus mode: flex-1 h-0 to grow within flex container; Normal: h-full to fill wrapper
|
||||
isFocusMode ? "flex-1 h-0" : "h-full",
|
||||
)}
|
||||
rows={1}
|
||||
placeholder={placeholder}
|
||||
ref={editorRef}
|
||||
onPaste={onPaste}
|
||||
onInput={handleEditorInput}
|
||||
></textarea>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
function toggleTextStyle(editor: TextareaActions, delimiter: string): void {
|
||||
const cursorPosition = editor.getCursorPosition();
|
||||
const selectedContent = editor.getSelectedContent();
|
||||
const isStyled = isTextStyled(selectedContent, delimiter);
|
||||
|
||||
if (isStyled) {
|
||||
const unstyled = selectedContent.slice(delimiter.length, -delimiter.length);
|
||||
editor.insertText(unstyled);
|
||||
editor.setCursorPosition(cursorPosition, cursorPosition + unstyled.length);
|
||||
} else {
|
||||
editor.insertText(`${delimiter}${selectedContent}${delimiter}`);
|
||||
editor.setCursorPosition(cursorPosition + delimiter.length, cursorPosition + delimiter.length + selectedContent.length);
|
||||
}
|
||||
}
|
||||
|
||||
function isTextStyled(text: string, delimiter: string): boolean {
|
||||
if (!text.startsWith(delimiter) || !text.endsWith(delimiter)) {
|
||||
return false;
|
||||
}
|
||||
if (delimiter !== "*") {
|
||||
return true;
|
||||
}
|
||||
const leadingAsterisks = countConsecutive(text, "*", "start");
|
||||
const trailingAsterisks = countConsecutive(text, "*", "end");
|
||||
return leadingAsterisks % 2 === 1 && trailingAsterisks % 2 === 1;
|
||||
}
|
||||
|
||||
function countConsecutive(text: string, character: string, position: "start" | "end"): number {
|
||||
let count = 0;
|
||||
let index = position === "start" ? 0 : text.length - 1;
|
||||
while (index >= 0 && index < text.length && text[index] === character) {
|
||||
count += 1;
|
||||
index += position === "start" ? 1 : -1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
export default PlainEditor;
|
||||
|
|
@ -38,12 +38,9 @@ MemoEditor/
|
|||
├── hooks/ # React hooks (utilities)
|
||||
│ ├── useMemoInit.ts # Initializes editor content; load guard for WYSIWYG
|
||||
│ └── ...
|
||||
├── Editor/ # Textarea (raw mode) implementation
|
||||
│ ├── controllerAdapter.ts # Adapts EditorRefActions → EditorController
|
||||
│ ├── TagSuggestions.tsx # # popup for raw mode
|
||||
│ ├── SlashCommands.tsx # / popup for raw mode
|
||||
│ └── ...
|
||||
├── TiptapEditor/ # Tiptap WYSIWYG implementation
|
||||
├── PlainEditor/ # Plain textarea (raw mode) implementation
|
||||
│ └── index.tsx # Bare textarea implementing EditorController directly
|
||||
├── Editor/ # Tiptap WYSIWYG implementation (default)
|
||||
│ ├── index.tsx # Editor component; implements EditorController
|
||||
│ ├── extensions.ts # Canonical schema-relevant extension set (shared with codec)
|
||||
│ ├── markdownCodec.ts # Headless parse/serialize helpers (singleton editor)
|
||||
|
|
@ -72,8 +69,8 @@ Uses `useReducer` + Context for predictable state transitions. All state changes
|
|||
|
||||
`types/editorController.ts` defines the `EditorController` interface — `focus`, `getMarkdown`, `setMarkdown`, `insertMarkdown`, formatting toggles, etc. — that callers outside an editor implementation must use exclusively.
|
||||
|
||||
- **WYSIWYG mode** (`TiptapEditor/`): Tiptap/ProseMirror rich-text editor. The default mode. Implements `EditorController` directly via `useImperativeHandle` in `TiptapEditor/index.tsx`.
|
||||
- **Raw mode** (`Editor/`): plain textarea. `Editor/controllerAdapter.ts` adapts the textarea's imperative string-surgery API (`EditorRefActions`) to the same `EditorController` contract.
|
||||
- **WYSIWYG mode** (`Editor/`): Tiptap/ProseMirror rich-text editor. The default mode. Implements `EditorController` directly via `useImperativeHandle` in `Editor/index.tsx`.
|
||||
- **Raw mode** (`PlainEditor/`): a bare textarea with no in-editor assistance (no suggestion popups, list continuation, or keyboard markdown shortcuts) — just auto-grow and cursor-visibility scrolling. It implements `EditorController` directly (markdown is just the textarea value), so the toolbar's formatting toggles still work.
|
||||
|
||||
`components/EditorContent.tsx` hosts whichever implementation `state.ui.editorMode` selects and exposes a single mode-routing `EditorController` facade to the rest of the component tree via `forwardRef`.
|
||||
|
||||
|
|
@ -83,9 +80,9 @@ The toolbar button in `EditorToolbar.tsx` dispatches `SET_EDITOR_MODE` and calls
|
|||
|
||||
Mode switching is a markdown handoff: because both editors write into `state.content` on every keystroke, the incoming editor simply initializes from it — no content is ever pushed between editors directly.
|
||||
|
||||
### Markdown fidelity layer (TiptapEditor)
|
||||
### Markdown fidelity layer (Editor)
|
||||
|
||||
`TiptapEditor/extensions.ts` exports `buildExtensions()`, the canonical schema-relevant extension set. It is shared by the live editor and the headless `markdownCodec.ts` (parse/serialize/round-trip helpers over a singleton Tiptap instance) so parse and serialize behavior is identical in both contexts.
|
||||
`Editor/extensions.ts` exports `buildExtensions()`, the canonical schema-relevant extension set. It is shared by the live editor and the headless `markdownCodec.ts` (parse/serialize/round-trip helpers over a singleton Tiptap instance) so parse and serialize behavior is identical in both contexts.
|
||||
|
||||
`PreservedBlock.ts` handles syntax the WYSIWYG editor does not model richly: tables, `$$math$$`, and raw HTML are captured at parse time with their raw markdown source, shown as editable monospace literal text, and re-emitted byte-for-byte on serialize.
|
||||
|
||||
|
|
@ -93,10 +90,7 @@ Mode switching is a markdown handoff: because both editors write into `state.con
|
|||
|
||||
### Suggestions
|
||||
|
||||
Both modes provide `#` tag and `/` slash-command suggestion popups, but they are implemented separately:
|
||||
|
||||
- WYSIWYG mode: `TiptapEditor/TagSuggestion.ts` and `TiptapEditor/SlashCommand.ts`, both using the shared `TiptapEditor/suggestionMenu.tsx` renderer.
|
||||
- Raw mode: `Editor/TagSuggestions.tsx` and `Editor/SlashCommands.tsx`.
|
||||
`#` tag and `/` slash-command suggestion popups are a **WYSIWYG-only** feature: `Editor/TagSuggestion.ts` and `Editor/SlashCommand.ts`, both using the shared `Editor/suggestionMenu.tsx` renderer. Raw mode is a plain textarea with no suggestions.
|
||||
|
||||
### Load guard
|
||||
|
||||
|
|
|
|||
|
|
@ -1,198 +0,0 @@
|
|||
import { Extension } from "@tiptap/core";
|
||||
import { Placeholder } from "@tiptap/extensions";
|
||||
import type { EditorProps as ProseMirrorEditorProps } from "@tiptap/pm/view";
|
||||
import { EditorContent as TiptapEditorContent, useEditor } from "@tiptap/react";
|
||||
import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react";
|
||||
import { matchPath } from "react-router-dom";
|
||||
import { useTagCounts } from "@/hooks/useUserQueries";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ROUTES as Routes } from "@/router/routes";
|
||||
import { EDITOR_HEIGHT } from "../constants";
|
||||
import type { EditorController } from "../types/editorController";
|
||||
import { buildExtensions } from "./extensions";
|
||||
import { SlashCommand } from "./SlashCommand";
|
||||
import { TagSuggestion } from "./TagSuggestion";
|
||||
|
||||
// Mod-Enter is the app-wide "save memo" shortcut (useKeyboard). StarterKit's
|
||||
// HardBreak extension also binds Mod-Enter to insert a hard break, which would
|
||||
// mutate the document right before save fires. This extension swallows the
|
||||
// shortcut (returning true stops further keymap handlers) while preserving
|
||||
// DOM event bubbling — preventDefault does NOT stopPropagation, so the window-
|
||||
// level save listener in useKeyboard still receives and handles the keystroke.
|
||||
// Priority 1000 > HardBreak's default 100, so this handler runs first.
|
||||
// Shift-Enter still inserts a hard break as expected.
|
||||
const SaveShortcutPassthrough = Extension.create({
|
||||
name: "saveShortcutPassthrough",
|
||||
priority: 1000,
|
||||
addKeyboardShortcuts() {
|
||||
return {
|
||||
"Mod-Enter": () => true,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export interface TiptapEditorProps {
|
||||
className?: string;
|
||||
initialContent: string;
|
||||
placeholder: string;
|
||||
isFocusMode?: boolean;
|
||||
onContentChange: (content: string) => void;
|
||||
onPaste: (event: React.ClipboardEvent) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Document serializer joins/terminates blocks with `\n\n`, so e.g. a task
|
||||
* list serializes with a trailing blank line. Outer whitespace is meaningless
|
||||
* at the document level (the round-trip corpus compares modulo outer trim),
|
||||
* so every markdown string leaving this component is trimmed.
|
||||
*/
|
||||
function serializeMarkdown(editor: { getMarkdown: () => string } | null): string {
|
||||
return (editor?.getMarkdown() ?? "").trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* WYSIWYG memo editor on Tiptap/ProseMirror. Markdown is the only format
|
||||
* crossing its boundary: in via setContent(contentType: "markdown"), out via
|
||||
* serializeMarkdown() on every update. IME, list continuation, input rules,
|
||||
* and auto-grow are native ProseMirror/contenteditable behavior.
|
||||
*/
|
||||
const TiptapEditor = forwardRef<EditorController, TiptapEditorProps>(function TiptapEditor(props, ref) {
|
||||
const { className, initialContent, placeholder, isFocusMode, onContentChange, onPaste } = props;
|
||||
|
||||
// Last markdown emitted through onContentChange, so the sync effect can
|
||||
// recognize the parent echoing our own value back without re-serializing.
|
||||
const lastEmittedRef = useRef<string | null>(null);
|
||||
// Read through refs so the memoized extension/editorProps closures below
|
||||
// always see the latest props (Placeholder decorations recompute per
|
||||
// transaction; handlePaste resolves per event).
|
||||
const placeholderRef = useRef(placeholder);
|
||||
placeholderRef.current = placeholder;
|
||||
const onPasteRef = useRef(onPaste);
|
||||
onPasteRef.current = onPaste;
|
||||
|
||||
// On the explore page suggestions include all users' tags; otherwise the
|
||||
// current user's. Same sourcing as the raw editor's TagSuggestions.
|
||||
const isExplorePage = useMemo(() => Boolean(matchPath(Routes.EXPLORE, window.location.pathname)), []);
|
||||
const { data: tagCount = {} } = useTagCounts(!isExplorePage);
|
||||
const sortedTags = useMemo(
|
||||
() =>
|
||||
Object.entries(tagCount)
|
||||
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
||||
.map(([tag]) => tag),
|
||||
[tagCount],
|
||||
);
|
||||
const tagsRef = useRef<string[]>([]);
|
||||
tagsRef.current = sortedTags;
|
||||
|
||||
// Stable option identities so useEditor's compareOptions stays equal across
|
||||
// renders and Tiptap skips a needless setOptions/view.setProps pass per
|
||||
// keystroke. All dynamic values reach the closures through refs above.
|
||||
// `content` is only consumed at editor creation — later external changes
|
||||
// flow through the sync effect — so the mount-time value is frozen too.
|
||||
const mountContentRef = useRef(initialContent);
|
||||
const extensions = useMemo(
|
||||
() => [
|
||||
...buildExtensions(),
|
||||
Placeholder.configure({ placeholder: () => placeholderRef.current }),
|
||||
TagSuggestion.configure({ getTags: () => tagsRef.current }),
|
||||
SlashCommand,
|
||||
SaveShortcutPassthrough,
|
||||
],
|
||||
[],
|
||||
);
|
||||
const editorProps = useMemo<ProseMirrorEditorProps>(
|
||||
() => ({
|
||||
attributes: {
|
||||
class: "memo-wysiwyg outline-none w-full text-base break-words min-h-6",
|
||||
},
|
||||
handlePaste: (_view, event) => {
|
||||
const hasFiles = Array.from(event.clipboardData?.items ?? []).some((item) => item.kind === "file");
|
||||
if (hasFiles) {
|
||||
onPasteRef.current(event as unknown as React.ClipboardEvent);
|
||||
return true;
|
||||
}
|
||||
// Text paste (incl. URL-over-selection → link) is handled natively.
|
||||
return false;
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
const editor = useEditor({
|
||||
extensions,
|
||||
content: mountContentRef.current,
|
||||
contentType: "markdown",
|
||||
editorProps,
|
||||
onUpdate: ({ editor: currentEditor }) => {
|
||||
const markdown = serializeMarkdown(currentEditor);
|
||||
lastEmittedRef.current = markdown;
|
||||
onContentChange(markdown);
|
||||
},
|
||||
});
|
||||
|
||||
// Sync external content changes (e.g. reset after save, draft restore)
|
||||
// without clobbering the document the user is typing into: only apply when
|
||||
// the markdown actually differs.
|
||||
useEffect(() => {
|
||||
if (!editor) {
|
||||
return;
|
||||
}
|
||||
// Parent echo of our own emission — nothing to sync (O(1) fast path).
|
||||
// Comparing against the live document instead would race: a keystroke
|
||||
// landing between the emission and this passive effect would make the
|
||||
// echo look like an external change and clobber the keystroke/cursor.
|
||||
if (initialContent === lastEmittedRef.current) {
|
||||
return;
|
||||
}
|
||||
// Never clobber an in-progress IME composition.
|
||||
if (editor.view.composing) {
|
||||
return;
|
||||
}
|
||||
if (serializeMarkdown(editor) !== initialContent.trim()) {
|
||||
editor.commands.setContent(initialContent, { contentType: "markdown", emitUpdate: false });
|
||||
// A subsequent identical echo of this value is also a no-op.
|
||||
lastEmittedRef.current = initialContent;
|
||||
}
|
||||
}, [initialContent, editor]);
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
(): EditorController => ({
|
||||
focus: () => editor?.commands.focus(),
|
||||
hasFocus: () => editor?.isFocused ?? false,
|
||||
// Contract: whitespace-only counts as empty. Tiptap's structural
|
||||
// `editor.isEmpty` would call a paragraph of spaces non-empty.
|
||||
isEmpty: () => serializeMarkdown(editor) === "",
|
||||
getMarkdown: () => serializeMarkdown(editor),
|
||||
setMarkdown: (markdown) => editor?.commands.setContent(markdown, { contentType: "markdown" }),
|
||||
insertMarkdown: (markdown) => editor?.chain().focus().insertContent(markdown, { contentType: "markdown" }).run(),
|
||||
scrollToCursor: () => editor?.commands.scrollIntoView(),
|
||||
selectAll: () => editor?.commands.selectAll(),
|
||||
toggleBold: () => editor?.chain().focus().toggleBold().run(),
|
||||
toggleItalic: () => editor?.chain().focus().toggleItalic().run(),
|
||||
toggleTaskList: () => editor?.chain().focus().toggleTaskList().run(),
|
||||
}),
|
||||
[editor],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col justify-start items-start relative w-full bg-inherit overflow-y-auto overflow-x-hidden",
|
||||
isFocusMode ? "flex-1" : `h-auto ${EDITOR_HEIGHT.normal}`,
|
||||
className,
|
||||
)}
|
||||
onClick={(event) => {
|
||||
// In focus mode the wrapper extends below the content; a click on the
|
||||
// empty area should land the caret at the end instead of doing nothing.
|
||||
if (event.target === event.currentTarget) {
|
||||
editor?.commands.focus("end");
|
||||
}
|
||||
}}
|
||||
>
|
||||
<TiptapEditorContent editor={editor} className="w-full" />
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export default TiptapEditor;
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
import { uniqBy } from "lodash-es";
|
||||
import {
|
||||
CodeXmlIcon,
|
||||
FileIcon,
|
||||
ImageIcon,
|
||||
LinkIcon,
|
||||
|
|
@ -11,7 +10,6 @@ import {
|
|||
MicIcon,
|
||||
MoreHorizontalIcon,
|
||||
PlusIcon,
|
||||
TypeIcon,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { LinkMemoDialog, LocationDialog } from "@/components/MemoMetadata";
|
||||
|
|
@ -20,6 +18,7 @@ import { useReverseGeocoding } from "@/components/map/useReverseGeocoding";
|
|||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
|
|
@ -135,11 +134,14 @@ const InsertMenu = (props: InsertMenuProps) => {
|
|||
setMoreSubmenuOpen(false);
|
||||
}, [onToggleFocusMode]);
|
||||
|
||||
const handleToggleEditorMode = useCallback(() => {
|
||||
const next = state.ui.editorMode === "wysiwyg" ? "raw" : "wysiwyg";
|
||||
dispatch(actions.setEditorMode(next));
|
||||
setPreferredEditorMode(next);
|
||||
}, [state.ui.editorMode, actions, dispatch]);
|
||||
const handleEditorModeChange = useCallback(
|
||||
(checked: boolean) => {
|
||||
const next = checked ? "wysiwyg" : "raw";
|
||||
dispatch(actions.setEditorMode(next));
|
||||
setPreferredEditorMode(next);
|
||||
},
|
||||
[actions, dispatch],
|
||||
);
|
||||
|
||||
const handleMediaUploadClick = useCallback(() => {
|
||||
handleUploadClick("image/*,video/*");
|
||||
|
|
@ -209,12 +211,7 @@ const InsertMenu = (props: InsertMenuProps) => {
|
|||
</DropdownMenuItem>
|
||||
))}
|
||||
<DropdownMenuSeparator />
|
||||
{/* Editor display mode: raw Markdown ↔ rich text (WYSIWYG) */}
|
||||
<DropdownMenuItem onClick={handleToggleEditorMode}>
|
||||
{state.ui.editorMode === "wysiwyg" ? <CodeXmlIcon className="w-4 h-4" /> : <TypeIcon className="w-4 h-4" />}
|
||||
{state.ui.editorMode === "wysiwyg" ? t("editor.switch-to-raw") : t("editor.switch-to-wysiwyg")}
|
||||
</DropdownMenuItem>
|
||||
{/* View submenu with Focus Mode */}
|
||||
{/* View submenu with Focus Mode + editor display mode */}
|
||||
<DropdownMenuSub open={moreSubmenuOpen} onOpenChange={setMoreSubmenuOpen}>
|
||||
<DropdownMenuSubTrigger onPointerEnter={handleTriggerEnter} onPointerLeave={handleTriggerLeave}>
|
||||
<MoreHorizontalIcon className="w-4 h-4" />
|
||||
|
|
@ -225,6 +222,10 @@ const InsertMenu = (props: InsertMenuProps) => {
|
|||
<Maximize2Icon className="w-4 h-4" />
|
||||
{t("editor.focus-mode")}
|
||||
</DropdownMenuItem>
|
||||
{/* Editor display mode: checked = rich text (WYSIWYG), unchecked = raw Markdown */}
|
||||
<DropdownMenuCheckboxItem checked={state.ui.editorMode === "wysiwyg"} onCheckedChange={handleEditorModeChange}>
|
||||
{t("editor.wysiwyg-editor")}
|
||||
</DropdownMenuCheckboxItem>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
<div className="px-2 py-1 text-xs text-muted-foreground opacity-80">{t("editor.slash-commands")}</div>
|
||||
|
|
|
|||
|
|
@ -1,9 +1,8 @@
|
|||
import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef } from "react";
|
||||
import Editor, { type EditorRefActions } from "../Editor";
|
||||
import { createTextareaController } from "../Editor/controllerAdapter";
|
||||
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from "react";
|
||||
import Editor from "../Editor";
|
||||
import { useBlobUrls, useDragAndDrop } from "../hooks";
|
||||
import PlainEditor from "../PlainEditor";
|
||||
import { useEditorContext } from "../state";
|
||||
import TiptapEditor from "../TiptapEditor";
|
||||
import type { EditorContentProps } from "../types";
|
||||
import type { LocalFile } from "../types/attachment";
|
||||
import type { EditorController } from "../types/editorController";
|
||||
|
|
@ -19,16 +18,14 @@ export const EditorContent = forwardRef<EditorController, EditorContentProps>(({
|
|||
const { createBlobUrl } = useBlobUrls();
|
||||
const mode = state.ui.editorMode;
|
||||
|
||||
const textareaActionsRef = useRef<EditorRefActions>(null);
|
||||
const tiptapControllerRef = useRef<EditorController>(null);
|
||||
const textareaController = useMemo(() => createTextareaController(() => textareaActionsRef.current), []);
|
||||
// Both editors implement EditorController; the host holds one ref each and
|
||||
// routes the parent's single ref to whichever mode is active.
|
||||
const wysiwygRef = useRef<EditorController>(null);
|
||||
const plainRef = useRef<EditorController>(null);
|
||||
|
||||
const modeRef = useRef(mode);
|
||||
modeRef.current = mode;
|
||||
const getActive = useCallback(
|
||||
(): EditorController | null => (modeRef.current === "wysiwyg" ? tiptapControllerRef.current : textareaController),
|
||||
[textareaController],
|
||||
);
|
||||
const getActive = useCallback((): EditorController | null => (modeRef.current === "wysiwyg" ? wysiwygRef.current : plainRef.current), []);
|
||||
|
||||
// Mid-edit mode switches should land the user back in the editor, not on
|
||||
// the toolbar button. Skipped on first mount (useMemoInit owns autofocus).
|
||||
|
|
@ -68,14 +65,6 @@ export const EditorContent = forwardRef<EditorController, EditorContentProps>(({
|
|||
localFiles.forEach((localFile) => dispatch(actions.addLocalFile(localFile)));
|
||||
});
|
||||
|
||||
const handleCompositionStart = () => {
|
||||
dispatch(actions.setComposing(true));
|
||||
};
|
||||
|
||||
const handleCompositionEnd = () => {
|
||||
dispatch(actions.setComposing(false));
|
||||
};
|
||||
|
||||
const handleContentChange = (content: string) => {
|
||||
dispatch(actions.updateContent(content));
|
||||
};
|
||||
|
|
@ -109,11 +98,8 @@ export const EditorContent = forwardRef<EditorController, EditorContentProps>(({
|
|||
return (
|
||||
<div className="w-full flex flex-col flex-1" {...dragHandlers}>
|
||||
{mode === "wysiwyg" ? (
|
||||
// No composition wiring: ProseMirror handles IME natively, and
|
||||
// state.ui.isComposing is only read by the raw editor below — feeding
|
||||
// it from here could only strand the flag across a mode switch.
|
||||
<TiptapEditor
|
||||
ref={tiptapControllerRef}
|
||||
<Editor
|
||||
ref={wysiwygRef}
|
||||
className="memo-editor-content"
|
||||
initialContent={state.content}
|
||||
placeholder={placeholder || ""}
|
||||
|
|
@ -122,17 +108,14 @@ export const EditorContent = forwardRef<EditorController, EditorContentProps>(({
|
|||
onPaste={handlePaste}
|
||||
/>
|
||||
) : (
|
||||
<Editor
|
||||
ref={textareaActionsRef}
|
||||
<PlainEditor
|
||||
ref={plainRef}
|
||||
className="memo-editor-content"
|
||||
initialContent={state.content}
|
||||
placeholder={placeholder || ""}
|
||||
isFocusMode={state.ui.isFocusMode}
|
||||
isInIME={state.ui.isComposing}
|
||||
onContentChange={handleContentChange}
|
||||
onPaste={handlePaste}
|
||||
onCompositionStart={handleCompositionStart}
|
||||
onCompositionEnd={handleCompositionEnd}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -2,10 +2,10 @@ import { useEffect, useRef, useState } from "react";
|
|||
import toast from "react-hot-toast";
|
||||
import type { Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb";
|
||||
import { useTranslate } from "@/utils/i18n";
|
||||
import { isLosslessRoundTrip } from "../Editor/markdownCodec";
|
||||
import { getPreferredEditorMode } from "../editorMode";
|
||||
import { cacheService, memoService } from "../services";
|
||||
import { useEditorContext } from "../state";
|
||||
import { isLosslessRoundTrip } from "../TiptapEditor/markdownCodec";
|
||||
import type { EditorController } from "../types/editorController";
|
||||
|
||||
interface UseMemoInitOptions {
|
||||
|
|
|
|||
|
|
@ -68,11 +68,6 @@ export const editorActions = {
|
|||
payload: { key, value },
|
||||
}),
|
||||
|
||||
setComposing: (value: boolean): EditorAction => ({
|
||||
type: "SET_COMPOSING",
|
||||
payload: value,
|
||||
}),
|
||||
|
||||
setTimestamps: (timestamps: Partial<EditorState["timestamps"]>): EditorAction => ({
|
||||
type: "SET_TIMESTAMPS",
|
||||
payload: timestamps,
|
||||
|
|
|
|||
|
|
@ -107,15 +107,6 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS
|
|||
},
|
||||
};
|
||||
|
||||
case "SET_COMPOSING":
|
||||
return {
|
||||
...state,
|
||||
ui: {
|
||||
...state.ui,
|
||||
isComposing: action.payload,
|
||||
},
|
||||
};
|
||||
|
||||
case "SET_TIMESTAMPS":
|
||||
return {
|
||||
...state,
|
||||
|
|
@ -177,9 +168,6 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS
|
|||
ui: {
|
||||
...state.ui,
|
||||
editorMode: action.payload,
|
||||
// A composition can't survive an editor swap; a stuck flag would
|
||||
// disable the textarea's IME-guarded features until the next IME cycle.
|
||||
isComposing: false,
|
||||
},
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -23,7 +23,6 @@ export interface EditorState {
|
|||
uploading: boolean;
|
||||
loading: boolean;
|
||||
};
|
||||
isComposing: boolean;
|
||||
editorMode: EditorMode;
|
||||
};
|
||||
timestamps: {
|
||||
|
|
@ -54,7 +53,6 @@ export type EditorAction =
|
|||
| { type: "CLEAR_LOCAL_FILES" }
|
||||
| { type: "TOGGLE_FOCUS_MODE" }
|
||||
| { type: "SET_LOADING"; payload: { key: LoadingKey; value: boolean } }
|
||||
| { type: "SET_COMPOSING"; payload: boolean }
|
||||
| { type: "SET_TIMESTAMPS"; payload: Partial<EditorState["timestamps"]> }
|
||||
| { type: "SET_AUDIO_RECORDER_SUPPORT"; payload: boolean }
|
||||
| { type: "SET_AUDIO_RECORDER_PERMISSION"; payload: AudioRecorderPermission }
|
||||
|
|
@ -82,7 +80,6 @@ const defaultState: EditorState = {
|
|||
uploading: false,
|
||||
loading: false,
|
||||
},
|
||||
isComposing: false,
|
||||
editorMode: "wysiwyg",
|
||||
},
|
||||
timestamps: {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,4 @@
|
|||
import type { ClipboardEvent, ForwardedRef, RefObject } from "react";
|
||||
import type { Location, Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb";
|
||||
import type { EditorRefActions } from "../Editor";
|
||||
import type { Command } from "../Editor/commands";
|
||||
import type { EditorState } from "../state";
|
||||
|
||||
export interface MemoEditorProps {
|
||||
|
|
@ -70,29 +67,6 @@ export interface InsertMenuProps {
|
|||
onAudioRecorderClick?: () => void;
|
||||
}
|
||||
|
||||
export interface TagSuggestionsProps {
|
||||
editorRef: RefObject<HTMLTextAreaElement | null>;
|
||||
editorActions: ForwardedRef<EditorRefActions>;
|
||||
}
|
||||
|
||||
export interface SlashCommandsProps {
|
||||
editorRef: RefObject<HTMLTextAreaElement | null>;
|
||||
editorActions: ForwardedRef<EditorRefActions>;
|
||||
commands: Command[];
|
||||
}
|
||||
|
||||
export interface EditorProps {
|
||||
className: string;
|
||||
initialContent: string;
|
||||
placeholder: string;
|
||||
onContentChange: (content: string) => void;
|
||||
onPaste: (event: ClipboardEvent) => void;
|
||||
isFocusMode?: boolean;
|
||||
isInIME?: boolean;
|
||||
onCompositionStart?: () => void;
|
||||
onCompositionEnd?: () => void;
|
||||
}
|
||||
|
||||
export interface VisibilitySelectorProps {
|
||||
value: Visibility;
|
||||
onChange: (visibility: Visibility) => void;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
* The contract both memo editors (raw textarea and Tiptap WYSIWYG) implement.
|
||||
* The contract both memo editors (raw textarea and WYSIWYG) implement.
|
||||
* Everything outside an editor implementation must talk markdown through this
|
||||
* interface and never reach for editor-specific APIs like EditorRefActions.
|
||||
* interface and never reach for an editor's internal DOM/ProseMirror APIs.
|
||||
*/
|
||||
export interface EditorController {
|
||||
focus(): void;
|
||||
|
|
|
|||
|
|
@ -3,14 +3,11 @@
|
|||
export type {
|
||||
EditorContentProps,
|
||||
EditorMetadataProps,
|
||||
EditorProps,
|
||||
EditorToolbarProps,
|
||||
FocusModeExitButtonProps,
|
||||
FocusModeOverlayProps,
|
||||
InsertMenuProps,
|
||||
MemoEditorProps,
|
||||
SlashCommandsProps,
|
||||
TagSuggestionsProps,
|
||||
VisibilitySelectorProps,
|
||||
} from "./components";
|
||||
export type { EditorController } from "./editorController";
|
||||
|
|
|
|||
|
|
@ -173,9 +173,8 @@
|
|||
"save": "Save",
|
||||
"saving": "Saving...",
|
||||
"slash-commands": "Type `/` for commands",
|
||||
"switch-to-raw": "Edit raw Markdown",
|
||||
"switch-to-wysiwyg": "Edit rich text",
|
||||
"unsupported-syntax-raw-mode": "This memo contains syntax the rich-text editor can't safely edit, so it opened in raw Markdown mode.",
|
||||
"wysiwyg-editor": "WYSIWYG Editor",
|
||||
"audio-recorder": {
|
||||
"attachment-label": "Audio recording",
|
||||
"attachment-label-with-time": "Audio recording {{time}}",
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import type { Editor } from "@tiptap/core";
|
||||
import { act, fireEvent, render } from "@testing-library/react";
|
||||
import type { Editor as EditorInstance } from "@tiptap/core";
|
||||
import { createRef } from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import TiptapEditor from "@/components/MemoEditor/TiptapEditor";
|
||||
import Editor from "@/components/MemoEditor/Editor";
|
||||
import type { EditorController } from "@/components/MemoEditor/types/editorController";
|
||||
|
||||
vi.mock("@/hooks/useUserQueries", async (importOriginal) => ({
|
||||
|
|
@ -14,11 +14,11 @@ function setup(initialContent = "") {
|
|||
const ref = createRef<EditorController>();
|
||||
const onContentChange = vi.fn();
|
||||
const { container } = render(
|
||||
<TiptapEditor ref={ref} initialContent={initialContent} placeholder="memo" onContentChange={onContentChange} onPaste={vi.fn()} />,
|
||||
<Editor ref={ref} initialContent={initialContent} placeholder="memo" onContentChange={onContentChange} onPaste={vi.fn()} />,
|
||||
);
|
||||
// Tiptap exposes the editor instance on the ProseMirror DOM node; tests use
|
||||
// it only where the EditorController surface cannot produce the state.
|
||||
const editor = (container.querySelector(".ProseMirror") as HTMLElement & { editor?: Editor }).editor as Editor;
|
||||
// The editor instance is exposed on the ProseMirror DOM node; tests use it
|
||||
// only where the EditorController surface cannot produce the state.
|
||||
const editor = (container.querySelector(".ProseMirror") as HTMLElement & { editor?: EditorInstance }).editor as EditorInstance;
|
||||
return { ref, onContentChange, editor };
|
||||
}
|
||||
|
||||
|
|
@ -28,14 +28,14 @@ function setupRerenderable(initialContent = "") {
|
|||
const ref = createRef<EditorController>();
|
||||
const onContentChange = vi.fn();
|
||||
const renderEditor = (content: string) => (
|
||||
<TiptapEditor ref={ref} initialContent={content} placeholder="memo" onContentChange={onContentChange} onPaste={vi.fn()} />
|
||||
<Editor ref={ref} initialContent={content} placeholder="memo" onContentChange={onContentChange} onPaste={vi.fn()} />
|
||||
);
|
||||
const { rerender: rtlRerender } = render(renderEditor(initialContent));
|
||||
const rerender = (content: string) => act(() => rtlRerender(renderEditor(content)));
|
||||
return { ref, onContentChange, rerender };
|
||||
}
|
||||
|
||||
describe("TiptapEditor EditorController", () => {
|
||||
describe("Editor EditorController", () => {
|
||||
it("loads markdown and serializes it back", () => {
|
||||
const { ref } = setup("# Title\n\nSome **bold** text.");
|
||||
expect(ref.current?.getMarkdown()).toBe("# Title\n\nSome **bold** text.");
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { create } from "@bufbuild/protobuf";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { create } from "@bufbuild/protobuf";
|
||||
import { useMemoInit } from "@/components/MemoEditor/hooks";
|
||||
import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
|
||||
import { MemoSchema } from "@/types/proto/api/v1/memo_service_pb";
|
||||
|
|
@ -12,7 +12,7 @@ vi.mock("react-hot-toast", () => ({
|
|||
}));
|
||||
|
||||
const isLosslessMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/components/MemoEditor/TiptapEditor/markdownCodec", () => ({
|
||||
vi.mock("@/components/MemoEditor/Editor/markdownCodec", () => ({
|
||||
isLosslessRoundTrip: isLosslessMock,
|
||||
}));
|
||||
|
||||
|
|
|
|||
|
|
@ -7,8 +7,6 @@ vi.mock("@/hooks/useUserQueries", () => ({
|
|||
useTagCounts: () => ({ data: {} }),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/MemoEditor/Editor/TagSuggestions", () => ({ default: () => null }));
|
||||
vi.mock("@/components/MemoEditor/Editor/SlashCommands", () => ({ default: () => null }));
|
||||
// useTranslate returns the key string in tests (no i18next backend initialised).
|
||||
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
|
||||
|
||||
|
|
@ -23,11 +21,7 @@ function ModeProbe() {
|
|||
>
|
||||
{state.ui.editorMode}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="probe-set-content"
|
||||
onClick={() => dispatch(actions.updateContent("from **wysiwyg**"))}
|
||||
>
|
||||
<button type="button" data-testid="probe-set-content" onClick={() => dispatch(actions.updateContent("from **wysiwyg**"))}>
|
||||
set content
|
||||
</button>
|
||||
</>
|
||||
|
|
@ -103,7 +97,7 @@ describe("editor mode switching", () => {
|
|||
|
||||
it("focuses the incoming editor after a toggle", () => {
|
||||
localStorage.setItem("memos-editor-mode", "raw");
|
||||
// Tiptap's focus command schedules the actual DOM focus via
|
||||
// The WYSIWYG editor's focus command schedules the actual DOM focus via
|
||||
// requestAnimationFrame. Mock rAF to fire synchronously so we can assert
|
||||
// that HTMLElement.prototype.focus() was called within the act() boundary.
|
||||
const pendingRafs: FrameRequestCallback[] = [];
|
||||
|
|
@ -119,7 +113,7 @@ describe("editor mode switching", () => {
|
|||
act(() => {
|
||||
fireEvent.click(screen.getByTestId("probe-toggle")); // raw → wysiwyg
|
||||
});
|
||||
// Flush pending animation frames (captures Tiptap's deferred view.focus()).
|
||||
// Flush pending animation frames (captures the editor's deferred view.focus()).
|
||||
act(() => {
|
||||
pendingRafs.splice(0).forEach((cb) => cb(0));
|
||||
});
|
||||
|
|
|
|||
|
|
@ -31,11 +31,4 @@ describe("editor mode in reducer", () => {
|
|||
const reset = editorReducer(state, { type: "RESET" });
|
||||
expect(reset.ui.editorMode).toBe("raw");
|
||||
});
|
||||
|
||||
it("SET_EDITOR_MODE clears isComposing", () => {
|
||||
const state = { ...createInitialState() };
|
||||
state.ui = { ...state.ui, isComposing: true };
|
||||
const next = editorReducer(state, { type: "SET_EDITOR_MODE", payload: "raw" });
|
||||
expect(next.ui.isComposing).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/TiptapEditor/markdownCodec";
|
||||
import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/Editor/markdownCodec";
|
||||
|
||||
function blockTypes(markdown: string): string[] {
|
||||
return (parseMarkdown(markdown).content ?? []).map((node) => node.type ?? "");
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { Editor } from "@tiptap/core";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { buildExtensions } from "@/components/MemoEditor/TiptapEditor/extensions";
|
||||
import { filterSlashCommands, slashCommandItems } from "@/components/MemoEditor/TiptapEditor/SlashCommand";
|
||||
import { buildExtensions } from "@/components/MemoEditor/Editor/extensions";
|
||||
import { filterSlashCommands, slashCommandItems } from "@/components/MemoEditor/Editor/SlashCommand";
|
||||
|
||||
let editor: Editor;
|
||||
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import type { JSONContent } from "@tiptap/core";
|
||||
import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/TiptapEditor/markdownCodec";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/Editor/markdownCodec";
|
||||
|
||||
function firstParagraphChildren(markdown: string) {
|
||||
return parseMarkdown(markdown).content?.[0]?.content ?? [];
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import InsertMenu from "@/components/MemoEditor/Toolbar/InsertMenu";
|
||||
import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
|
||||
import InsertMenu from "@/components/MemoEditor/Toolbar/InsertMenu";
|
||||
|
||||
// useTranslate returns the i18n key directly (no i18next backend in tests).
|
||||
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
|
||||
|
|
@ -36,29 +36,34 @@ function renderInsertMenu() {
|
|||
);
|
||||
}
|
||||
|
||||
// Opens the "+" dropdown, then its "More" submenu, and returns the
|
||||
// "WYSIWYG Editor" checkbox item.
|
||||
function openWysiwygCheckbox() {
|
||||
// Open the dropdown (keyboard open is the most reliable path in jsdom).
|
||||
fireEvent.keyDown(screen.getByRole("button"), { key: "Enter" });
|
||||
// Open the "More" submenu (controlled open state toggles on trigger click).
|
||||
fireEvent.click(screen.getByText("common.more"));
|
||||
return screen.getByText("editor.wysiwyg-editor");
|
||||
}
|
||||
|
||||
describe("InsertMenu editor-mode toggle", () => {
|
||||
it("switches mode and persists the preference when the item is selected", () => {
|
||||
it("unchecking the WYSIWYG item switches to raw and persists the preference", () => {
|
||||
localStorage.clear();
|
||||
renderInsertMenu();
|
||||
expect(screen.getByTestId("mode").textContent).toBe("wysiwyg");
|
||||
|
||||
// Open the dropdown (keyboard open is the most reliable path in jsdom).
|
||||
fireEvent.keyDown(screen.getByRole("button"), { key: "Enter" });
|
||||
|
||||
// Default mode is wysiwyg, so the item offers to switch to raw.
|
||||
fireEvent.click(screen.getByText("editor.switch-to-raw"));
|
||||
fireEvent.click(openWysiwygCheckbox());
|
||||
|
||||
expect(screen.getByTestId("mode").textContent).toBe("raw");
|
||||
expect(localStorage.getItem("memos-editor-mode")).toBe("raw");
|
||||
});
|
||||
|
||||
it("offers to switch back to rich text when already in raw mode", () => {
|
||||
it("checking the WYSIWYG item switches back to rich text from raw mode", () => {
|
||||
localStorage.setItem("memos-editor-mode", "raw");
|
||||
renderInsertMenu();
|
||||
expect(screen.getByTestId("mode").textContent).toBe("raw");
|
||||
|
||||
fireEvent.keyDown(screen.getByRole("button"), { key: "Enter" });
|
||||
fireEvent.click(screen.getByText("editor.switch-to-wysiwyg"));
|
||||
fireEvent.click(openWysiwygCheckbox());
|
||||
|
||||
expect(screen.getByTestId("mode").textContent).toBe("wysiwyg");
|
||||
expect(localStorage.getItem("memos-editor-mode")).toBe("wysiwyg");
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/TiptapEditor/markdownCodec";
|
||||
import { parseMarkdown, roundTripMarkdown } from "@/components/MemoEditor/Editor/markdownCodec";
|
||||
|
||||
const CORPUS_DIR = join(__dirname, "fixtures", "markdown-corpus");
|
||||
|
||||
|
|
|
|||
|
|
@ -1,14 +1,6 @@
|
|||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import Editor from "@/components/MemoEditor/Editor";
|
||||
|
||||
vi.mock("@/components/MemoEditor/Editor/TagSuggestions", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("@/components/MemoEditor/Editor/SlashCommands", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
import PlainEditor from "@/components/MemoEditor/PlainEditor";
|
||||
|
||||
function pastePlainText(textarea: HTMLTextAreaElement, text: string) {
|
||||
fireEvent.paste(textarea, {
|
||||
|
|
@ -20,15 +12,7 @@ function pastePlainText(textarea: HTMLTextAreaElement, text: string) {
|
|||
|
||||
function renderEditor(initialContent: string) {
|
||||
const onPaste = vi.fn();
|
||||
render(
|
||||
<Editor
|
||||
className=""
|
||||
initialContent={initialContent}
|
||||
placeholder="memo"
|
||||
onContentChange={vi.fn()}
|
||||
onPaste={onPaste}
|
||||
/>,
|
||||
);
|
||||
render(<PlainEditor className="" initialContent={initialContent} placeholder="memo" onContentChange={vi.fn()} onPaste={onPaste} />);
|
||||
|
||||
return {
|
||||
onPaste,
|
||||
|
|
@ -36,46 +20,16 @@ function renderEditor(initialContent: string) {
|
|||
};
|
||||
}
|
||||
|
||||
describe("memo editor paste handling", () => {
|
||||
it("wraps selected text with a pasted URL", () => {
|
||||
describe("plain editor paste handling", () => {
|
||||
// The plain textarea does no in-editor paste transformation (no URL → link
|
||||
// wrapping); it forwards every paste to onPaste so the host can handle files.
|
||||
it("forwards pasted text to onPaste without altering the value", () => {
|
||||
const { onPaste, textarea } = renderEditor("read the docs");
|
||||
textarea.setSelectionRange(9, 13);
|
||||
|
||||
pastePlainText(textarea, "https://example.com");
|
||||
|
||||
expect(textarea).toHaveValue("read the [docs](https://example.com)");
|
||||
expect(textarea.selectionStart).toBe("read the [docs](https://example.com)".length);
|
||||
expect(textarea.selectionEnd).toBe("read the [docs](https://example.com)".length);
|
||||
expect(onPaste).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("delegates non-URL text paste", () => {
|
||||
const { onPaste, textarea } = renderEditor("read the docs");
|
||||
textarea.setSelectionRange(9, 13);
|
||||
|
||||
pastePlainText(textarea, "not a url");
|
||||
|
||||
expect(textarea).toHaveValue("read the docs");
|
||||
expect(onPaste).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("delegates pasted URLs when no text is selected", () => {
|
||||
const { onPaste, textarea } = renderEditor("read the docs");
|
||||
textarea.setSelectionRange(13, 13);
|
||||
|
||||
pastePlainText(textarea, "https://example.com");
|
||||
|
||||
expect(textarea).toHaveValue("read the docs");
|
||||
expect(onPaste).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("delegates pasted URLs when the selected text is already a URL", () => {
|
||||
const { onPaste, textarea } = renderEditor("https://memos.example");
|
||||
textarea.setSelectionRange(0, "https://memos.example".length);
|
||||
|
||||
pastePlainText(textarea, "https://example.com");
|
||||
|
||||
expect(textarea).toHaveValue("https://memos.example");
|
||||
expect(onPaste).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,116 +0,0 @@
|
|||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import Editor from "@/components/MemoEditor/Editor";
|
||||
|
||||
vi.mock("@/components/MemoEditor/Editor/TagSuggestions", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("@/components/MemoEditor/Editor/SlashCommands", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
function renderEditor(initialContent: string, isInIME = false) {
|
||||
render(
|
||||
<Editor
|
||||
className=""
|
||||
initialContent={initialContent}
|
||||
placeholder="memo"
|
||||
onContentChange={vi.fn()}
|
||||
onPaste={vi.fn()}
|
||||
isInIME={isInIME}
|
||||
/>,
|
||||
);
|
||||
return screen.getByPlaceholderText("memo") as HTMLTextAreaElement;
|
||||
}
|
||||
|
||||
describe("memo editor markdown shortcuts", () => {
|
||||
describe("Ctrl+B (bold)", () => {
|
||||
it("wraps selected text with **", () => {
|
||||
const textarea = renderEditor("read the docs");
|
||||
textarea.setSelectionRange(9, 13);
|
||||
|
||||
fireEvent.keyDown(textarea, { key: "b", ctrlKey: true });
|
||||
|
||||
expect(textarea).toHaveValue("read the **docs**");
|
||||
});
|
||||
|
||||
it("removes ** from already-bolded text", () => {
|
||||
const textarea = renderEditor("read the **docs**");
|
||||
textarea.setSelectionRange(9, 17);
|
||||
|
||||
fireEvent.keyDown(textarea, { key: "b", ctrlKey: true });
|
||||
|
||||
expect(textarea).toHaveValue("read the docs");
|
||||
});
|
||||
|
||||
it("works with metaKey (Mac Cmd+B)", () => {
|
||||
const textarea = renderEditor("read the docs");
|
||||
textarea.setSelectionRange(9, 13);
|
||||
|
||||
fireEvent.keyDown(textarea, { key: "b", metaKey: true });
|
||||
|
||||
expect(textarea).toHaveValue("read the **docs**");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ctrl+I (italic)", () => {
|
||||
it("wraps selected text with *", () => {
|
||||
const textarea = renderEditor("read the docs");
|
||||
textarea.setSelectionRange(9, 13);
|
||||
|
||||
fireEvent.keyDown(textarea, { key: "i", ctrlKey: true });
|
||||
|
||||
expect(textarea).toHaveValue("read the *docs*");
|
||||
});
|
||||
|
||||
it("removes * from already-italicized text", () => {
|
||||
const textarea = renderEditor("read the *docs*");
|
||||
textarea.setSelectionRange(9, 15);
|
||||
|
||||
fireEvent.keyDown(textarea, { key: "i", ctrlKey: true });
|
||||
|
||||
expect(textarea).toHaveValue("read the docs");
|
||||
});
|
||||
|
||||
it("works with metaKey (Mac Cmd+I)", () => {
|
||||
const textarea = renderEditor("read the docs");
|
||||
textarea.setSelectionRange(9, 13);
|
||||
|
||||
fireEvent.keyDown(textarea, { key: "i", metaKey: true });
|
||||
|
||||
expect(textarea).toHaveValue("read the *docs*");
|
||||
});
|
||||
|
||||
it("preserves bold when italicizing already-bolded text", () => {
|
||||
const textarea = renderEditor("read the **docs**");
|
||||
textarea.setSelectionRange(9, 17);
|
||||
|
||||
fireEvent.keyDown(textarea, { key: "i", ctrlKey: true });
|
||||
|
||||
expect(textarea).toHaveValue("read the ***docs***");
|
||||
});
|
||||
});
|
||||
|
||||
describe("shortcuts suppressed during IME composition", () => {
|
||||
it("does not apply bold during IME input", () => {
|
||||
const textarea = renderEditor("テスト", true);
|
||||
textarea.setSelectionRange(0, 3);
|
||||
|
||||
fireEvent.keyDown(textarea, { key: "b", ctrlKey: true });
|
||||
|
||||
expect(textarea).toHaveValue("テスト");
|
||||
});
|
||||
});
|
||||
|
||||
describe("no modifier key — no action", () => {
|
||||
it("does not apply bold when Ctrl/Cmd is not held", () => {
|
||||
const textarea = renderEditor("read the docs");
|
||||
textarea.setSelectionRange(9, 13);
|
||||
|
||||
fireEvent.keyDown(textarea, { key: "b" });
|
||||
|
||||
expect(textarea).toHaveValue("read the docs");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,30 +1,20 @@
|
|||
import { render, screen } from "@testing-library/react";
|
||||
import { createRef } from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import Editor, { type EditorRefActions } from "@/components/MemoEditor/Editor";
|
||||
import { createTextareaController } from "@/components/MemoEditor/Editor/controllerAdapter";
|
||||
|
||||
vi.mock("@/components/MemoEditor/Editor/TagSuggestions", () => ({ default: () => null }));
|
||||
vi.mock("@/components/MemoEditor/Editor/SlashCommands", () => ({ default: () => null }));
|
||||
import PlainEditor from "@/components/MemoEditor/PlainEditor";
|
||||
import type { EditorController } from "@/components/MemoEditor/types/editorController";
|
||||
|
||||
function setup(initialContent = "") {
|
||||
const ref = createRef<EditorRefActions>();
|
||||
const ref = createRef<EditorController>();
|
||||
render(
|
||||
<Editor
|
||||
ref={ref}
|
||||
className=""
|
||||
initialContent={initialContent}
|
||||
placeholder="memo"
|
||||
onContentChange={vi.fn()}
|
||||
onPaste={vi.fn()}
|
||||
/>,
|
||||
<PlainEditor ref={ref} className="" initialContent={initialContent} placeholder="memo" onContentChange={vi.fn()} onPaste={vi.fn()} />,
|
||||
);
|
||||
const controller = createTextareaController(() => ref.current);
|
||||
const controller = ref.current as EditorController;
|
||||
const textarea = screen.getByPlaceholderText("memo") as HTMLTextAreaElement;
|
||||
return { controller, textarea };
|
||||
}
|
||||
|
||||
describe("textarea EditorController adapter", () => {
|
||||
describe("PlainEditor EditorController", () => {
|
||||
it("getMarkdown/setMarkdown mirror the textarea value", () => {
|
||||
const { controller, textarea } = setup("hello");
|
||||
expect(controller.getMarkdown()).toBe("hello");
|
||||
|
|
@ -1,7 +1,8 @@
|
|||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { createRef } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { SuggestionMenu, createSuggestionRenderer, type SuggestionMenuHandle } from "@/components/MemoEditor/TiptapEditor/suggestionMenu";
|
||||
import { createSuggestionRenderer, SuggestionMenu, type SuggestionMenuHandle } from "@/components/MemoEditor/Editor/suggestionMenu";
|
||||
|
||||
function setup(items = ["alpha", "beta", "gamma"]) {
|
||||
const command = vi.fn();
|
||||
|
|
@ -79,7 +80,6 @@ describe("createSuggestionRenderer blur handling", () => {
|
|||
setRenderer: vi.fn((_id: string, renderer: { reactElement: React.ReactNode; element: HTMLElement }) => {
|
||||
// Mimic the real portal: render the element directly into renderer.element
|
||||
// via React so it shows up in the DOM when appended to document.body.
|
||||
const { createRoot } = require("react-dom/client") as typeof import("react-dom/client");
|
||||
const root = createRoot(renderer.element);
|
||||
act(() => {
|
||||
root.render(renderer.reactElement as React.ReactElement);
|
||||
|
|
|
|||
Loading…
Reference in a new issue