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 { Extension } from "@tiptap/core";
|
||||||
import getCaretCoordinates from "textarea-caret";
|
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 { cn } from "@/lib/utils";
|
||||||
|
import { ROUTES as Routes } from "@/router/routes";
|
||||||
import { EDITOR_HEIGHT } from "../constants";
|
import { EDITOR_HEIGHT } from "../constants";
|
||||||
import type { EditorProps } from "../types";
|
import type { EditorController } from "../types/editorController";
|
||||||
import { editorCommands } from "./commands";
|
import { buildExtensions } from "./extensions";
|
||||||
import SlashCommands from "./SlashCommands";
|
import { SlashCommand } from "./SlashCommand";
|
||||||
import { getMarkdownLinkForPastedUrl, handleMarkdownShortcuts } from "./shortcuts";
|
import { TagSuggestion } from "./TagSuggestion";
|
||||||
import TagSuggestions from "./TagSuggestions";
|
|
||||||
import { useListCompletion } from "./useListCompletion";
|
|
||||||
|
|
||||||
export interface EditorRefActions {
|
// Mod-Enter is the app-wide "save memo" shortcut (useKeyboard). StarterKit's
|
||||||
getEditor: () => HTMLTextAreaElement | null;
|
// HardBreak extension also binds Mod-Enter to insert a hard break, which would
|
||||||
focus: () => void;
|
// mutate the document right before save fires. This extension swallows the
|
||||||
scrollToCursor: () => void;
|
// shortcut (returning true stops further keymap handlers) while preserving
|
||||||
insertText: (text: string, prefix?: string, suffix?: string) => void;
|
// DOM event bubbling — preventDefault does NOT stopPropagation, so the window-
|
||||||
removeText: (start: number, length: number) => void;
|
// level save listener in useKeyboard still receives and handles the keystroke.
|
||||||
setContent: (text: string) => void;
|
// Priority 1000 > HardBreak's default 100, so this handler runs first.
|
||||||
getContent: () => string;
|
// Shift-Enter still inserts a hard break as expected.
|
||||||
getSelectedContent: () => string;
|
const SaveShortcutPassthrough = Extension.create({
|
||||||
getCursorPosition: () => number;
|
name: "saveShortcutPassthrough",
|
||||||
setCursorPosition: (startPos: number, endPos?: number) => void;
|
priority: 1000,
|
||||||
getCursorLineNumber: () => number;
|
addKeyboardShortcuts() {
|
||||||
getLine: (lineNumber: number) => string;
|
return {
|
||||||
setLine: (lineNumber: number, text: string) => void;
|
"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 {
|
* The Document serializer joins/terminates blocks with `\n\n`, so e.g. a task
|
||||||
className,
|
* list serializes with a trailing blank line. Outer whitespace is meaningless
|
||||||
initialContent,
|
* at the document level (the round-trip corpus compares modulo outer trim),
|
||||||
placeholder,
|
* so every markdown string leaving this component is trimmed.
|
||||||
onPaste,
|
*/
|
||||||
onContentChange: handleContentChangeCallback,
|
function serializeMarkdown(editor: { getMarkdown: () => string } | null): string {
|
||||||
isFocusMode,
|
return (editor?.getMarkdown() ?? "").trim();
|
||||||
isInIME = false,
|
}
|
||||||
onCompositionStart,
|
|
||||||
onCompositionEnd,
|
|
||||||
} = props;
|
|
||||||
const editorRef = useRef<HTMLTextAreaElement>(null);
|
|
||||||
|
|
||||||
const updateEditorHeight = useCallback(() => {
|
/**
|
||||||
if (editorRef.current) {
|
* WYSIWYG memo editor built on ProseMirror. Markdown is the only format
|
||||||
editorRef.current.style.height = "auto";
|
* crossing its boundary: in via setContent(contentType: "markdown"), out via
|
||||||
editorRef.current.style.height = `${editorRef.current.scrollHeight ?? 0}px`;
|
* 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(() => {
|
// Last markdown emitted through onContentChange, so the sync effect can
|
||||||
if (editorRef.current) {
|
// recognize the parent echoing our own value back without re-serializing.
|
||||||
handleContentChangeCallback(editorRef.current.value);
|
const lastEmittedRef = useRef<string | null>(null);
|
||||||
updateEditorHeight();
|
// Read through refs so the memoized extension/editorProps closures below
|
||||||
}
|
// always see the latest props (Placeholder decorations recompute per
|
||||||
}, [handleContentChangeCallback, updateEditorHeight]);
|
// 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 } = {}) => {
|
// On the explore page suggestions include all users' tags; otherwise the
|
||||||
const editor = editorRef.current;
|
// current user's. Same sourcing as the raw editor's TagSuggestions.
|
||||||
if (!editor) return;
|
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;
|
// Stable option identities so useEditor's compareOptions stays equal across
|
||||||
const caret = getCaretCoordinates(editor, editor.selectionEnd);
|
// renders and the editor skips a needless setOptions/view.setProps pass per
|
||||||
|
// keystroke. All dynamic values reach the closures through refs above.
|
||||||
if (force) {
|
// `content` is only consumed at editor creation — later external changes
|
||||||
editor.scrollTop = Math.max(0, caret.top - editor.clientHeight / 2);
|
// flow through the sync effect — so the mount-time value is frozen too.
|
||||||
return;
|
const mountContentRef = useRef(initialContent);
|
||||||
}
|
const extensions = useMemo(
|
||||||
|
() => [
|
||||||
const lineHeight = parseFloat(getComputedStyle(editor).lineHeight) || 24;
|
...buildExtensions(),
|
||||||
const viewportBottom = editor.scrollTop + editor.clientHeight;
|
Placeholder.configure({ placeholder: () => placeholderRef.current }),
|
||||||
// Scroll if cursor is near or beyond bottom edge (within 2 lines)
|
TagSuggestion.configure({ getTags: () => tagsRef.current }),
|
||||||
if (caret.top + lineHeight * 2 > viewportBottom) {
|
SlashCommand,
|
||||||
editor.scrollTop = Math.max(0, caret.top - editor.clientHeight / 2);
|
SaveShortcutPassthrough,
|
||||||
}
|
],
|
||||||
}, []);
|
[],
|
||||||
|
);
|
||||||
useEffect(() => {
|
const editorProps = useMemo<ProseMirrorEditorProps>(
|
||||||
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(
|
|
||||||
() => ({
|
() => ({
|
||||||
getEditor: () => editorRef.current,
|
attributes: {
|
||||||
focus: () => editorRef.current?.focus(),
|
class: "memo-wysiwyg outline-none w-full text-base break-words min-h-6",
|
||||||
scrollToCursor: () => {
|
|
||||||
scrollToCaret({ force: true });
|
|
||||||
},
|
},
|
||||||
insertText: (content = "", prefix = "", suffix = "") => {
|
handlePaste: (_view, event) => {
|
||||||
const editor = editorRef.current;
|
const hasFiles = Array.from(event.clipboardData?.items ?? []).some((item) => item.kind === "file");
|
||||||
if (!editor) return;
|
if (hasFiles) {
|
||||||
|
onPasteRef.current(event as unknown as React.ClipboardEvent);
|
||||||
const cursorPos = editor.selectionStart;
|
return true;
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
},
|
// Text paste (incl. URL-over-selection → link) is handled natively.
|
||||||
getContent: () => editorRef.current?.value ?? "",
|
return false;
|
||||||
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();
|
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
[updateContent, scrollToCaret],
|
[],
|
||||||
);
|
);
|
||||||
|
|
||||||
useImperativeHandle(ref, () => editorActions, [editorActions]);
|
const editor = useEditor({
|
||||||
|
extensions,
|
||||||
const handleEditorInput = useCallback(() => {
|
content: mountContentRef.current,
|
||||||
if (editorRef.current) {
|
contentType: "markdown",
|
||||||
handleContentChangeCallback(editorRef.current.value);
|
editorProps,
|
||||||
updateEditorHeight();
|
onUpdate: ({ editor: currentEditor }) => {
|
||||||
|
const markdown = serializeMarkdown(currentEditor);
|
||||||
// Auto-scroll to keep cursor visible when typing
|
lastEmittedRef.current = markdown;
|
||||||
// See: https://github.com/usememos/memos/issues/5469
|
onContentChange(markdown);
|
||||||
scrollToCaret();
|
},
|
||||||
}
|
|
||||||
}, [handleContentChangeCallback, updateEditorHeight, scrollToCaret]);
|
|
||||||
|
|
||||||
// Auto-complete markdown lists when pressing Enter
|
|
||||||
useListCompletion({
|
|
||||||
editorRef,
|
|
||||||
editorActions,
|
|
||||||
isInIME,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const handleKeyDown = useCallback(
|
// Sync external content changes (e.g. reset after save, draft restore)
|
||||||
(event: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
// without clobbering the document the user is typing into: only apply when
|
||||||
if ((event.ctrlKey || event.metaKey) && !isInIME) {
|
// the markdown actually differs.
|
||||||
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
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
updateEditorHeight();
|
if (!editor) {
|
||||||
}, [isFocusMode, updateEditorHeight]);
|
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 (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex flex-col justify-start items-start relative w-full bg-inherit",
|
"flex flex-col justify-start items-start relative w-full bg-inherit overflow-y-auto overflow-x-hidden",
|
||||||
// Focus mode: flex-1 to grow and fill space; Normal: h-auto with max-height
|
|
||||||
isFocusMode ? "flex-1" : `h-auto ${EDITOR_HEIGHT.normal}`,
|
isFocusMode ? "flex-1" : `h-auto ${EDITOR_HEIGHT.normal}`,
|
||||||
className,
|
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
|
<RichTextContent editor={editor} className="w-full" />
|
||||||
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} />
|
|
||||||
</div>
|
</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)
|
├── hooks/ # React hooks (utilities)
|
||||||
│ ├── useMemoInit.ts # Initializes editor content; load guard for WYSIWYG
|
│ ├── useMemoInit.ts # Initializes editor content; load guard for WYSIWYG
|
||||||
│ └── ...
|
│ └── ...
|
||||||
├── Editor/ # Textarea (raw mode) implementation
|
├── PlainEditor/ # Plain textarea (raw mode) implementation
|
||||||
│ ├── controllerAdapter.ts # Adapts EditorRefActions → EditorController
|
│ └── index.tsx # Bare textarea implementing EditorController directly
|
||||||
│ ├── TagSuggestions.tsx # # popup for raw mode
|
├── Editor/ # Tiptap WYSIWYG implementation (default)
|
||||||
│ ├── SlashCommands.tsx # / popup for raw mode
|
|
||||||
│ └── ...
|
|
||||||
├── TiptapEditor/ # Tiptap WYSIWYG implementation
|
|
||||||
│ ├── index.tsx # Editor component; implements EditorController
|
│ ├── index.tsx # Editor component; implements EditorController
|
||||||
│ ├── extensions.ts # Canonical schema-relevant extension set (shared with codec)
|
│ ├── extensions.ts # Canonical schema-relevant extension set (shared with codec)
|
||||||
│ ├── markdownCodec.ts # Headless parse/serialize helpers (singleton editor)
|
│ ├── 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.
|
`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`.
|
- **WYSIWYG mode** (`Editor/`): Tiptap/ProseMirror rich-text editor. The default mode. Implements `EditorController` directly via `useImperativeHandle` in `Editor/index.tsx`.
|
||||||
- **Raw mode** (`Editor/`): plain textarea. `Editor/controllerAdapter.ts` adapts the textarea's imperative string-surgery API (`EditorRefActions`) to the same `EditorController` contract.
|
- **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`.
|
`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.
|
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.
|
`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
|
### Suggestions
|
||||||
|
|
||||||
Both modes provide `#` tag and `/` slash-command suggestion popups, but they are implemented separately:
|
`#` 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.
|
||||||
|
|
||||||
- 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`.
|
|
||||||
|
|
||||||
### Load guard
|
### 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 { uniqBy } from "lodash-es";
|
||||||
import {
|
import {
|
||||||
CodeXmlIcon,
|
|
||||||
FileIcon,
|
FileIcon,
|
||||||
ImageIcon,
|
ImageIcon,
|
||||||
LinkIcon,
|
LinkIcon,
|
||||||
|
|
@ -11,7 +10,6 @@ import {
|
||||||
MicIcon,
|
MicIcon,
|
||||||
MoreHorizontalIcon,
|
MoreHorizontalIcon,
|
||||||
PlusIcon,
|
PlusIcon,
|
||||||
TypeIcon,
|
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { LinkMemoDialog, LocationDialog } from "@/components/MemoMetadata";
|
import { LinkMemoDialog, LocationDialog } from "@/components/MemoMetadata";
|
||||||
|
|
@ -20,6 +18,7 @@ import { useReverseGeocoding } from "@/components/map/useReverseGeocoding";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
|
DropdownMenuCheckboxItem,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuSeparator,
|
DropdownMenuSeparator,
|
||||||
|
|
@ -135,11 +134,14 @@ const InsertMenu = (props: InsertMenuProps) => {
|
||||||
setMoreSubmenuOpen(false);
|
setMoreSubmenuOpen(false);
|
||||||
}, [onToggleFocusMode]);
|
}, [onToggleFocusMode]);
|
||||||
|
|
||||||
const handleToggleEditorMode = useCallback(() => {
|
const handleEditorModeChange = useCallback(
|
||||||
const next = state.ui.editorMode === "wysiwyg" ? "raw" : "wysiwyg";
|
(checked: boolean) => {
|
||||||
dispatch(actions.setEditorMode(next));
|
const next = checked ? "wysiwyg" : "raw";
|
||||||
setPreferredEditorMode(next);
|
dispatch(actions.setEditorMode(next));
|
||||||
}, [state.ui.editorMode, actions, dispatch]);
|
setPreferredEditorMode(next);
|
||||||
|
},
|
||||||
|
[actions, dispatch],
|
||||||
|
);
|
||||||
|
|
||||||
const handleMediaUploadClick = useCallback(() => {
|
const handleMediaUploadClick = useCallback(() => {
|
||||||
handleUploadClick("image/*,video/*");
|
handleUploadClick("image/*,video/*");
|
||||||
|
|
@ -209,12 +211,7 @@ const InsertMenu = (props: InsertMenuProps) => {
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
))}
|
))}
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
{/* Editor display mode: raw Markdown ↔ rich text (WYSIWYG) */}
|
{/* View submenu with Focus Mode + editor display mode */}
|
||||||
<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 */}
|
|
||||||
<DropdownMenuSub open={moreSubmenuOpen} onOpenChange={setMoreSubmenuOpen}>
|
<DropdownMenuSub open={moreSubmenuOpen} onOpenChange={setMoreSubmenuOpen}>
|
||||||
<DropdownMenuSubTrigger onPointerEnter={handleTriggerEnter} onPointerLeave={handleTriggerLeave}>
|
<DropdownMenuSubTrigger onPointerEnter={handleTriggerEnter} onPointerLeave={handleTriggerLeave}>
|
||||||
<MoreHorizontalIcon className="w-4 h-4" />
|
<MoreHorizontalIcon className="w-4 h-4" />
|
||||||
|
|
@ -225,6 +222,10 @@ const InsertMenu = (props: InsertMenuProps) => {
|
||||||
<Maximize2Icon className="w-4 h-4" />
|
<Maximize2Icon className="w-4 h-4" />
|
||||||
{t("editor.focus-mode")}
|
{t("editor.focus-mode")}
|
||||||
</DropdownMenuItem>
|
</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>
|
</DropdownMenuSubContent>
|
||||||
</DropdownMenuSub>
|
</DropdownMenuSub>
|
||||||
<div className="px-2 py-1 text-xs text-muted-foreground opacity-80">{t("editor.slash-commands")}</div>
|
<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 { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from "react";
|
||||||
import Editor, { type EditorRefActions } from "../Editor";
|
import Editor from "../Editor";
|
||||||
import { createTextareaController } from "../Editor/controllerAdapter";
|
|
||||||
import { useBlobUrls, useDragAndDrop } from "../hooks";
|
import { useBlobUrls, useDragAndDrop } from "../hooks";
|
||||||
|
import PlainEditor from "../PlainEditor";
|
||||||
import { useEditorContext } from "../state";
|
import { useEditorContext } from "../state";
|
||||||
import TiptapEditor from "../TiptapEditor";
|
|
||||||
import type { EditorContentProps } from "../types";
|
import type { EditorContentProps } from "../types";
|
||||||
import type { LocalFile } from "../types/attachment";
|
import type { LocalFile } from "../types/attachment";
|
||||||
import type { EditorController } from "../types/editorController";
|
import type { EditorController } from "../types/editorController";
|
||||||
|
|
@ -19,16 +18,14 @@ export const EditorContent = forwardRef<EditorController, EditorContentProps>(({
|
||||||
const { createBlobUrl } = useBlobUrls();
|
const { createBlobUrl } = useBlobUrls();
|
||||||
const mode = state.ui.editorMode;
|
const mode = state.ui.editorMode;
|
||||||
|
|
||||||
const textareaActionsRef = useRef<EditorRefActions>(null);
|
// Both editors implement EditorController; the host holds one ref each and
|
||||||
const tiptapControllerRef = useRef<EditorController>(null);
|
// routes the parent's single ref to whichever mode is active.
|
||||||
const textareaController = useMemo(() => createTextareaController(() => textareaActionsRef.current), []);
|
const wysiwygRef = useRef<EditorController>(null);
|
||||||
|
const plainRef = useRef<EditorController>(null);
|
||||||
|
|
||||||
const modeRef = useRef(mode);
|
const modeRef = useRef(mode);
|
||||||
modeRef.current = mode;
|
modeRef.current = mode;
|
||||||
const getActive = useCallback(
|
const getActive = useCallback((): EditorController | null => (modeRef.current === "wysiwyg" ? wysiwygRef.current : plainRef.current), []);
|
||||||
(): EditorController | null => (modeRef.current === "wysiwyg" ? tiptapControllerRef.current : textareaController),
|
|
||||||
[textareaController],
|
|
||||||
);
|
|
||||||
|
|
||||||
// Mid-edit mode switches should land the user back in the editor, not on
|
// Mid-edit mode switches should land the user back in the editor, not on
|
||||||
// the toolbar button. Skipped on first mount (useMemoInit owns autofocus).
|
// 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)));
|
localFiles.forEach((localFile) => dispatch(actions.addLocalFile(localFile)));
|
||||||
});
|
});
|
||||||
|
|
||||||
const handleCompositionStart = () => {
|
|
||||||
dispatch(actions.setComposing(true));
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCompositionEnd = () => {
|
|
||||||
dispatch(actions.setComposing(false));
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleContentChange = (content: string) => {
|
const handleContentChange = (content: string) => {
|
||||||
dispatch(actions.updateContent(content));
|
dispatch(actions.updateContent(content));
|
||||||
};
|
};
|
||||||
|
|
@ -109,11 +98,8 @@ export const EditorContent = forwardRef<EditorController, EditorContentProps>(({
|
||||||
return (
|
return (
|
||||||
<div className="w-full flex flex-col flex-1" {...dragHandlers}>
|
<div className="w-full flex flex-col flex-1" {...dragHandlers}>
|
||||||
{mode === "wysiwyg" ? (
|
{mode === "wysiwyg" ? (
|
||||||
// No composition wiring: ProseMirror handles IME natively, and
|
<Editor
|
||||||
// state.ui.isComposing is only read by the raw editor below — feeding
|
ref={wysiwygRef}
|
||||||
// it from here could only strand the flag across a mode switch.
|
|
||||||
<TiptapEditor
|
|
||||||
ref={tiptapControllerRef}
|
|
||||||
className="memo-editor-content"
|
className="memo-editor-content"
|
||||||
initialContent={state.content}
|
initialContent={state.content}
|
||||||
placeholder={placeholder || ""}
|
placeholder={placeholder || ""}
|
||||||
|
|
@ -122,17 +108,14 @@ export const EditorContent = forwardRef<EditorController, EditorContentProps>(({
|
||||||
onPaste={handlePaste}
|
onPaste={handlePaste}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<Editor
|
<PlainEditor
|
||||||
ref={textareaActionsRef}
|
ref={plainRef}
|
||||||
className="memo-editor-content"
|
className="memo-editor-content"
|
||||||
initialContent={state.content}
|
initialContent={state.content}
|
||||||
placeholder={placeholder || ""}
|
placeholder={placeholder || ""}
|
||||||
isFocusMode={state.ui.isFocusMode}
|
isFocusMode={state.ui.isFocusMode}
|
||||||
isInIME={state.ui.isComposing}
|
|
||||||
onContentChange={handleContentChange}
|
onContentChange={handleContentChange}
|
||||||
onPaste={handlePaste}
|
onPaste={handlePaste}
|
||||||
onCompositionStart={handleCompositionStart}
|
|
||||||
onCompositionEnd={handleCompositionEnd}
|
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -2,10 +2,10 @@ import { useEffect, useRef, useState } from "react";
|
||||||
import toast from "react-hot-toast";
|
import toast from "react-hot-toast";
|
||||||
import type { Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb";
|
import type { Memo, Visibility } from "@/types/proto/api/v1/memo_service_pb";
|
||||||
import { useTranslate } from "@/utils/i18n";
|
import { useTranslate } from "@/utils/i18n";
|
||||||
|
import { isLosslessRoundTrip } from "../Editor/markdownCodec";
|
||||||
import { getPreferredEditorMode } from "../editorMode";
|
import { getPreferredEditorMode } from "../editorMode";
|
||||||
import { cacheService, memoService } from "../services";
|
import { cacheService, memoService } from "../services";
|
||||||
import { useEditorContext } from "../state";
|
import { useEditorContext } from "../state";
|
||||||
import { isLosslessRoundTrip } from "../TiptapEditor/markdownCodec";
|
|
||||||
import type { EditorController } from "../types/editorController";
|
import type { EditorController } from "../types/editorController";
|
||||||
|
|
||||||
interface UseMemoInitOptions {
|
interface UseMemoInitOptions {
|
||||||
|
|
|
||||||
|
|
@ -68,11 +68,6 @@ export const editorActions = {
|
||||||
payload: { key, value },
|
payload: { key, value },
|
||||||
}),
|
}),
|
||||||
|
|
||||||
setComposing: (value: boolean): EditorAction => ({
|
|
||||||
type: "SET_COMPOSING",
|
|
||||||
payload: value,
|
|
||||||
}),
|
|
||||||
|
|
||||||
setTimestamps: (timestamps: Partial<EditorState["timestamps"]>): EditorAction => ({
|
setTimestamps: (timestamps: Partial<EditorState["timestamps"]>): EditorAction => ({
|
||||||
type: "SET_TIMESTAMPS",
|
type: "SET_TIMESTAMPS",
|
||||||
payload: 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":
|
case "SET_TIMESTAMPS":
|
||||||
return {
|
return {
|
||||||
...state,
|
...state,
|
||||||
|
|
@ -177,9 +168,6 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS
|
||||||
ui: {
|
ui: {
|
||||||
...state.ui,
|
...state.ui,
|
||||||
editorMode: action.payload,
|
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;
|
uploading: boolean;
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
};
|
};
|
||||||
isComposing: boolean;
|
|
||||||
editorMode: EditorMode;
|
editorMode: EditorMode;
|
||||||
};
|
};
|
||||||
timestamps: {
|
timestamps: {
|
||||||
|
|
@ -54,7 +53,6 @@ export type EditorAction =
|
||||||
| { type: "CLEAR_LOCAL_FILES" }
|
| { type: "CLEAR_LOCAL_FILES" }
|
||||||
| { type: "TOGGLE_FOCUS_MODE" }
|
| { type: "TOGGLE_FOCUS_MODE" }
|
||||||
| { type: "SET_LOADING"; payload: { key: LoadingKey; value: boolean } }
|
| { type: "SET_LOADING"; payload: { key: LoadingKey; value: boolean } }
|
||||||
| { type: "SET_COMPOSING"; payload: boolean }
|
|
||||||
| { type: "SET_TIMESTAMPS"; payload: Partial<EditorState["timestamps"]> }
|
| { type: "SET_TIMESTAMPS"; payload: Partial<EditorState["timestamps"]> }
|
||||||
| { type: "SET_AUDIO_RECORDER_SUPPORT"; payload: boolean }
|
| { type: "SET_AUDIO_RECORDER_SUPPORT"; payload: boolean }
|
||||||
| { type: "SET_AUDIO_RECORDER_PERMISSION"; payload: AudioRecorderPermission }
|
| { type: "SET_AUDIO_RECORDER_PERMISSION"; payload: AudioRecorderPermission }
|
||||||
|
|
@ -82,7 +80,6 @@ const defaultState: EditorState = {
|
||||||
uploading: false,
|
uploading: false,
|
||||||
loading: false,
|
loading: false,
|
||||||
},
|
},
|
||||||
isComposing: false,
|
|
||||||
editorMode: "wysiwyg",
|
editorMode: "wysiwyg",
|
||||||
},
|
},
|
||||||
timestamps: {
|
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 { 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";
|
import type { EditorState } from "../state";
|
||||||
|
|
||||||
export interface MemoEditorProps {
|
export interface MemoEditorProps {
|
||||||
|
|
@ -70,29 +67,6 @@ export interface InsertMenuProps {
|
||||||
onAudioRecorderClick?: () => void;
|
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 {
|
export interface VisibilitySelectorProps {
|
||||||
value: Visibility;
|
value: Visibility;
|
||||||
onChange: (visibility: Visibility) => void;
|
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
|
* 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 {
|
export interface EditorController {
|
||||||
focus(): void;
|
focus(): void;
|
||||||
|
|
|
||||||
|
|
@ -3,14 +3,11 @@
|
||||||
export type {
|
export type {
|
||||||
EditorContentProps,
|
EditorContentProps,
|
||||||
EditorMetadataProps,
|
EditorMetadataProps,
|
||||||
EditorProps,
|
|
||||||
EditorToolbarProps,
|
EditorToolbarProps,
|
||||||
FocusModeExitButtonProps,
|
FocusModeExitButtonProps,
|
||||||
FocusModeOverlayProps,
|
FocusModeOverlayProps,
|
||||||
InsertMenuProps,
|
InsertMenuProps,
|
||||||
MemoEditorProps,
|
MemoEditorProps,
|
||||||
SlashCommandsProps,
|
|
||||||
TagSuggestionsProps,
|
|
||||||
VisibilitySelectorProps,
|
VisibilitySelectorProps,
|
||||||
} from "./components";
|
} from "./components";
|
||||||
export type { EditorController } from "./editorController";
|
export type { EditorController } from "./editorController";
|
||||||
|
|
|
||||||
|
|
@ -173,9 +173,8 @@
|
||||||
"save": "Save",
|
"save": "Save",
|
||||||
"saving": "Saving...",
|
"saving": "Saving...",
|
||||||
"slash-commands": "Type `/` for commands",
|
"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.",
|
"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": {
|
"audio-recorder": {
|
||||||
"attachment-label": "Audio recording",
|
"attachment-label": "Audio recording",
|
||||||
"attachment-label-with-time": "Audio recording {{time}}",
|
"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 { act, fireEvent, render } from "@testing-library/react";
|
||||||
|
import type { Editor as EditorInstance } from "@tiptap/core";
|
||||||
import { createRef } from "react";
|
import { createRef } from "react";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
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";
|
import type { EditorController } from "@/components/MemoEditor/types/editorController";
|
||||||
|
|
||||||
vi.mock("@/hooks/useUserQueries", async (importOriginal) => ({
|
vi.mock("@/hooks/useUserQueries", async (importOriginal) => ({
|
||||||
|
|
@ -14,11 +14,11 @@ function setup(initialContent = "") {
|
||||||
const ref = createRef<EditorController>();
|
const ref = createRef<EditorController>();
|
||||||
const onContentChange = vi.fn();
|
const onContentChange = vi.fn();
|
||||||
const { container } = render(
|
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
|
// The editor instance is exposed on the ProseMirror DOM node; tests use it
|
||||||
// it only where the EditorController surface cannot produce the state.
|
// only where the EditorController surface cannot produce the state.
|
||||||
const editor = (container.querySelector(".ProseMirror") as HTMLElement & { editor?: Editor }).editor as Editor;
|
const editor = (container.querySelector(".ProseMirror") as HTMLElement & { editor?: EditorInstance }).editor as EditorInstance;
|
||||||
return { ref, onContentChange, editor };
|
return { ref, onContentChange, editor };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -28,14 +28,14 @@ function setupRerenderable(initialContent = "") {
|
||||||
const ref = createRef<EditorController>();
|
const ref = createRef<EditorController>();
|
||||||
const onContentChange = vi.fn();
|
const onContentChange = vi.fn();
|
||||||
const renderEditor = (content: string) => (
|
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: rtlRerender } = render(renderEditor(initialContent));
|
||||||
const rerender = (content: string) => act(() => rtlRerender(renderEditor(content)));
|
const rerender = (content: string) => act(() => rtlRerender(renderEditor(content)));
|
||||||
return { ref, onContentChange, rerender };
|
return { ref, onContentChange, rerender };
|
||||||
}
|
}
|
||||||
|
|
||||||
describe("TiptapEditor EditorController", () => {
|
describe("Editor EditorController", () => {
|
||||||
it("loads markdown and serializes it back", () => {
|
it("loads markdown and serializes it back", () => {
|
||||||
const { ref } = setup("# Title\n\nSome **bold** text.");
|
const { ref } = setup("# Title\n\nSome **bold** text.");
|
||||||
expect(ref.current?.getMarkdown()).toBe("# 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 { render, screen } from "@testing-library/react";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
import { create } from "@bufbuild/protobuf";
|
|
||||||
import { useMemoInit } from "@/components/MemoEditor/hooks";
|
import { useMemoInit } from "@/components/MemoEditor/hooks";
|
||||||
import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
|
import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
|
||||||
import { MemoSchema } from "@/types/proto/api/v1/memo_service_pb";
|
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());
|
const isLosslessMock = vi.hoisted(() => vi.fn());
|
||||||
vi.mock("@/components/MemoEditor/TiptapEditor/markdownCodec", () => ({
|
vi.mock("@/components/MemoEditor/Editor/markdownCodec", () => ({
|
||||||
isLosslessRoundTrip: isLosslessMock,
|
isLosslessRoundTrip: isLosslessMock,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -7,8 +7,6 @@ vi.mock("@/hooks/useUserQueries", () => ({
|
||||||
useTagCounts: () => ({ data: {} }),
|
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).
|
// useTranslate returns the key string in tests (no i18next backend initialised).
|
||||||
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
|
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
|
||||||
|
|
||||||
|
|
@ -23,11 +21,7 @@ function ModeProbe() {
|
||||||
>
|
>
|
||||||
{state.ui.editorMode}
|
{state.ui.editorMode}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button type="button" data-testid="probe-set-content" onClick={() => dispatch(actions.updateContent("from **wysiwyg**"))}>
|
||||||
type="button"
|
|
||||||
data-testid="probe-set-content"
|
|
||||||
onClick={() => dispatch(actions.updateContent("from **wysiwyg**"))}
|
|
||||||
>
|
|
||||||
set content
|
set content
|
||||||
</button>
|
</button>
|
||||||
</>
|
</>
|
||||||
|
|
@ -103,7 +97,7 @@ describe("editor mode switching", () => {
|
||||||
|
|
||||||
it("focuses the incoming editor after a toggle", () => {
|
it("focuses the incoming editor after a toggle", () => {
|
||||||
localStorage.setItem("memos-editor-mode", "raw");
|
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
|
// requestAnimationFrame. Mock rAF to fire synchronously so we can assert
|
||||||
// that HTMLElement.prototype.focus() was called within the act() boundary.
|
// that HTMLElement.prototype.focus() was called within the act() boundary.
|
||||||
const pendingRafs: FrameRequestCallback[] = [];
|
const pendingRafs: FrameRequestCallback[] = [];
|
||||||
|
|
@ -119,7 +113,7 @@ describe("editor mode switching", () => {
|
||||||
act(() => {
|
act(() => {
|
||||||
fireEvent.click(screen.getByTestId("probe-toggle")); // raw → wysiwyg
|
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(() => {
|
act(() => {
|
||||||
pendingRafs.splice(0).forEach((cb) => cb(0));
|
pendingRafs.splice(0).forEach((cb) => cb(0));
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -31,11 +31,4 @@ describe("editor mode in reducer", () => {
|
||||||
const reset = editorReducer(state, { type: "RESET" });
|
const reset = editorReducer(state, { type: "RESET" });
|
||||||
expect(reset.ui.editorMode).toBe("raw");
|
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 { 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[] {
|
function blockTypes(markdown: string): string[] {
|
||||||
return (parseMarkdown(markdown).content ?? []).map((node) => node.type ?? "");
|
return (parseMarkdown(markdown).content ?? []).map((node) => node.type ?? "");
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { Editor } from "@tiptap/core";
|
import { Editor } from "@tiptap/core";
|
||||||
import { afterEach, describe, expect, it } from "vitest";
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
import { buildExtensions } from "@/components/MemoEditor/TiptapEditor/extensions";
|
import { buildExtensions } from "@/components/MemoEditor/Editor/extensions";
|
||||||
import { filterSlashCommands, slashCommandItems } from "@/components/MemoEditor/TiptapEditor/SlashCommand";
|
import { filterSlashCommands, slashCommandItems } from "@/components/MemoEditor/Editor/SlashCommand";
|
||||||
|
|
||||||
let editor: Editor;
|
let editor: Editor;
|
||||||
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import { describe, expect, it } from "vitest";
|
|
||||||
import type { JSONContent } from "@tiptap/core";
|
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) {
|
function firstParagraphChildren(markdown: string) {
|
||||||
return parseMarkdown(markdown).content?.[0]?.content ?? [];
|
return parseMarkdown(markdown).content?.[0]?.content ?? [];
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
import { fireEvent, render, screen } from "@testing-library/react";
|
import { fireEvent, render, screen } from "@testing-library/react";
|
||||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||||
import InsertMenu from "@/components/MemoEditor/Toolbar/InsertMenu";
|
|
||||||
import { EditorProvider, useEditorContext } from "@/components/MemoEditor/state";
|
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).
|
// useTranslate returns the i18n key directly (no i18next backend in tests).
|
||||||
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
|
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", () => {
|
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();
|
localStorage.clear();
|
||||||
renderInsertMenu();
|
renderInsertMenu();
|
||||||
expect(screen.getByTestId("mode").textContent).toBe("wysiwyg");
|
expect(screen.getByTestId("mode").textContent).toBe("wysiwyg");
|
||||||
|
|
||||||
// Open the dropdown (keyboard open is the most reliable path in jsdom).
|
fireEvent.click(openWysiwygCheckbox());
|
||||||
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"));
|
|
||||||
|
|
||||||
expect(screen.getByTestId("mode").textContent).toBe("raw");
|
expect(screen.getByTestId("mode").textContent).toBe("raw");
|
||||||
expect(localStorage.getItem("memos-editor-mode")).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");
|
localStorage.setItem("memos-editor-mode", "raw");
|
||||||
renderInsertMenu();
|
renderInsertMenu();
|
||||||
expect(screen.getByTestId("mode").textContent).toBe("raw");
|
expect(screen.getByTestId("mode").textContent).toBe("raw");
|
||||||
|
|
||||||
fireEvent.keyDown(screen.getByRole("button"), { key: "Enter" });
|
fireEvent.click(openWysiwygCheckbox());
|
||||||
fireEvent.click(screen.getByText("editor.switch-to-wysiwyg"));
|
|
||||||
|
|
||||||
expect(screen.getByTestId("mode").textContent).toBe("wysiwyg");
|
expect(screen.getByTestId("mode").textContent).toBe("wysiwyg");
|
||||||
expect(localStorage.getItem("memos-editor-mode")).toBe("wysiwyg");
|
expect(localStorage.getItem("memos-editor-mode")).toBe("wysiwyg");
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { readdirSync, readFileSync } from "node:fs";
|
import { readdirSync, readFileSync } from "node:fs";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import { describe, expect, it } from "vitest";
|
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");
|
const CORPUS_DIR = join(__dirname, "fixtures", "markdown-corpus");
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,6 @@
|
||||||
import { fireEvent, render, screen } from "@testing-library/react";
|
import { fireEvent, render, screen } from "@testing-library/react";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
import Editor from "@/components/MemoEditor/Editor";
|
import PlainEditor from "@/components/MemoEditor/PlainEditor";
|
||||||
|
|
||||||
vi.mock("@/components/MemoEditor/Editor/TagSuggestions", () => ({
|
|
||||||
default: () => null,
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock("@/components/MemoEditor/Editor/SlashCommands", () => ({
|
|
||||||
default: () => null,
|
|
||||||
}));
|
|
||||||
|
|
||||||
function pastePlainText(textarea: HTMLTextAreaElement, text: string) {
|
function pastePlainText(textarea: HTMLTextAreaElement, text: string) {
|
||||||
fireEvent.paste(textarea, {
|
fireEvent.paste(textarea, {
|
||||||
|
|
@ -20,15 +12,7 @@ function pastePlainText(textarea: HTMLTextAreaElement, text: string) {
|
||||||
|
|
||||||
function renderEditor(initialContent: string) {
|
function renderEditor(initialContent: string) {
|
||||||
const onPaste = vi.fn();
|
const onPaste = vi.fn();
|
||||||
render(
|
render(<PlainEditor className="" initialContent={initialContent} placeholder="memo" onContentChange={vi.fn()} onPaste={onPaste} />);
|
||||||
<Editor
|
|
||||||
className=""
|
|
||||||
initialContent={initialContent}
|
|
||||||
placeholder="memo"
|
|
||||||
onContentChange={vi.fn()}
|
|
||||||
onPaste={onPaste}
|
|
||||||
/>,
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
onPaste,
|
onPaste,
|
||||||
|
|
@ -36,46 +20,16 @@ function renderEditor(initialContent: string) {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
describe("memo editor paste handling", () => {
|
describe("plain editor paste handling", () => {
|
||||||
it("wraps selected text with a pasted URL", () => {
|
// 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");
|
const { onPaste, textarea } = renderEditor("read the docs");
|
||||||
textarea.setSelectionRange(9, 13);
|
textarea.setSelectionRange(9, 13);
|
||||||
|
|
||||||
pastePlainText(textarea, "https://example.com");
|
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(textarea).toHaveValue("read the docs");
|
||||||
expect(onPaste).toHaveBeenCalledOnce();
|
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 { render, screen } from "@testing-library/react";
|
||||||
import { createRef } from "react";
|
import { createRef } from "react";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
import Editor, { type EditorRefActions } from "@/components/MemoEditor/Editor";
|
import PlainEditor from "@/components/MemoEditor/PlainEditor";
|
||||||
import { createTextareaController } from "@/components/MemoEditor/Editor/controllerAdapter";
|
import type { EditorController } from "@/components/MemoEditor/types/editorController";
|
||||||
|
|
||||||
vi.mock("@/components/MemoEditor/Editor/TagSuggestions", () => ({ default: () => null }));
|
|
||||||
vi.mock("@/components/MemoEditor/Editor/SlashCommands", () => ({ default: () => null }));
|
|
||||||
|
|
||||||
function setup(initialContent = "") {
|
function setup(initialContent = "") {
|
||||||
const ref = createRef<EditorRefActions>();
|
const ref = createRef<EditorController>();
|
||||||
render(
|
render(
|
||||||
<Editor
|
<PlainEditor ref={ref} className="" initialContent={initialContent} placeholder="memo" onContentChange={vi.fn()} onPaste={vi.fn()} />,
|
||||||
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;
|
const textarea = screen.getByPlaceholderText("memo") as HTMLTextAreaElement;
|
||||||
return { controller, textarea };
|
return { controller, textarea };
|
||||||
}
|
}
|
||||||
|
|
||||||
describe("textarea EditorController adapter", () => {
|
describe("PlainEditor EditorController", () => {
|
||||||
it("getMarkdown/setMarkdown mirror the textarea value", () => {
|
it("getMarkdown/setMarkdown mirror the textarea value", () => {
|
||||||
const { controller, textarea } = setup("hello");
|
const { controller, textarea } = setup("hello");
|
||||||
expect(controller.getMarkdown()).toBe("hello");
|
expect(controller.getMarkdown()).toBe("hello");
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||||
import { createRef } from "react";
|
import { createRef } from "react";
|
||||||
|
import { createRoot } from "react-dom/client";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
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"]) {
|
function setup(items = ["alpha", "beta", "gamma"]) {
|
||||||
const command = vi.fn();
|
const command = vi.fn();
|
||||||
|
|
@ -79,7 +80,6 @@ describe("createSuggestionRenderer blur handling", () => {
|
||||||
setRenderer: vi.fn((_id: string, renderer: { reactElement: React.ReactNode; element: HTMLElement }) => {
|
setRenderer: vi.fn((_id: string, renderer: { reactElement: React.ReactNode; element: HTMLElement }) => {
|
||||||
// Mimic the real portal: render the element directly into renderer.element
|
// 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.
|
// 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);
|
const root = createRoot(renderer.element);
|
||||||
act(() => {
|
act(() => {
|
||||||
root.render(renderer.reactElement as React.ReactElement);
|
root.render(renderer.reactElement as React.ReactElement);
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue