mirror of https://github.com/usememos/memos.git
refactor(web): improve consistency and design of editor components
This commit standardizes the design patterns across all editor enhancement features for better maintainability and consistency. Key improvements: **useListAutoCompletion hook:** - Now self-manages event listeners (consistent with useSuggestions) - Uses refs to avoid stale closures - Proper cleanup on unmount - No longer requires manual event handler in parent **useSuggestions hook:** - Enhanced TypeScript documentation with JSDoc - Added usage examples - Improved error handling with warnings - Consistent interface design **SuggestionsPopup component:** - Auto-scrolls selected item into view during keyboard navigation - Added max height (max-h-60) with proper overflow handling - Improved styling with border and shadow - Prevents text selection with select-none - Smooth scroll behavior for better UX **Editor component:** - Simplified - removed manual keyboard handler - Cleaner code with hooks managing their own concerns - Better separation of responsibilities **CommandSuggestions & TagSuggestions:** - Added comprehensive JSDoc comments - Explained filtering strategies (prefix vs substring) - Documented user interaction patterns - Clarified autocomplete behavior Benefits: - Consistent patterns across all features - Self-contained, reusable hooks - Better developer experience with docs - Improved UX with auto-scroll - Easier to maintain and test
This commit is contained in:
parent
7f8f0c753d
commit
858c1d2448
|
|
@ -11,6 +11,15 @@ interface CommandSuggestionsProps {
|
||||||
commands: Command[];
|
commands: Command[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Command suggestions popup that appears when typing "/" in the editor.
|
||||||
|
* Shows available editor commands like formatting options, insertions, etc.
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* - Type "/" to trigger
|
||||||
|
* - Continue typing to filter commands
|
||||||
|
* - Use Arrow keys to navigate, Enter/Tab to select
|
||||||
|
*/
|
||||||
const CommandSuggestions = observer(({ editorRef, editorActions, commands }: CommandSuggestionsProps) => {
|
const CommandSuggestions = observer(({ editorRef, editorActions, commands }: CommandSuggestionsProps) => {
|
||||||
const { position, suggestions, selectedIndex, isVisible, handleItemSelect } = useSuggestions({
|
const { position, suggestions, selectedIndex, isVisible, handleItemSelect } = useSuggestions({
|
||||||
editorRef,
|
editorRef,
|
||||||
|
|
@ -18,14 +27,15 @@ const CommandSuggestions = observer(({ editorRef, editorActions, commands }: Com
|
||||||
triggerChar: "/",
|
triggerChar: "/",
|
||||||
items: commands,
|
items: commands,
|
||||||
filterItems: (items, searchQuery) => {
|
filterItems: (items, searchQuery) => {
|
||||||
// Show all commands when no search query
|
|
||||||
if (!searchQuery) return items;
|
if (!searchQuery) return items;
|
||||||
// Filter commands that start with the search query
|
// Filter commands by prefix match for intuitive searching
|
||||||
return items.filter((cmd) => cmd.name.toLowerCase().startsWith(searchQuery));
|
return items.filter((cmd) => cmd.name.toLowerCase().startsWith(searchQuery));
|
||||||
},
|
},
|
||||||
onAutocomplete: (cmd, word, index, actions) => {
|
onAutocomplete: (cmd, word, index, actions) => {
|
||||||
|
// Replace the trigger word with the command output
|
||||||
actions.removeText(index, word.length);
|
actions.removeText(index, word.length);
|
||||||
actions.insertText(cmd.run());
|
actions.insertText(cmd.run());
|
||||||
|
// Position cursor if command specifies an offset
|
||||||
if (cmd.cursorOffset) {
|
if (cmd.cursorOffset) {
|
||||||
actions.setCursorPosition(actions.getCursorPosition() + cmd.cursorOffset);
|
actions.setCursorPosition(actions.getCursorPosition() + cmd.cursorOffset);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { ReactNode } from "react";
|
import { ReactNode, useEffect, useRef } from "react";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { Position } from "./useSuggestions";
|
import { Position } from "./useSuggestions";
|
||||||
|
|
||||||
|
|
@ -14,6 +14,12 @@ interface SuggestionsPopupProps<T> {
|
||||||
/**
|
/**
|
||||||
* Shared popup component for displaying suggestion items.
|
* Shared popup component for displaying suggestion items.
|
||||||
* Provides consistent styling and behavior across different suggestion types.
|
* Provides consistent styling and behavior across different suggestion types.
|
||||||
|
*
|
||||||
|
* Features:
|
||||||
|
* - Automatically scrolls selected item into view
|
||||||
|
* - Handles keyboard navigation highlighting
|
||||||
|
* - Prevents text selection during mouse interaction
|
||||||
|
* - Consistent styling with max height constraints
|
||||||
*/
|
*/
|
||||||
export function SuggestionsPopup<T>({
|
export function SuggestionsPopup<T>({
|
||||||
position,
|
position,
|
||||||
|
|
@ -23,17 +29,33 @@ export function SuggestionsPopup<T>({
|
||||||
renderItem,
|
renderItem,
|
||||||
getItemKey,
|
getItemKey,
|
||||||
}: SuggestionsPopupProps<T>) {
|
}: SuggestionsPopupProps<T>) {
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const selectedItemRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
// Scroll selected item into view when selection changes
|
||||||
|
useEffect(() => {
|
||||||
|
if (selectedItemRef.current && containerRef.current) {
|
||||||
|
selectedItemRef.current.scrollIntoView({
|
||||||
|
block: "nearest",
|
||||||
|
behavior: "smooth",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [selectedIndex]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="z-20 p-1 mt-1 -ml-2 absolute max-w-48 gap-px rounded font-mono flex flex-col justify-start items-start overflow-auto shadow bg-popover"
|
ref={containerRef}
|
||||||
|
className="z-20 p-1 mt-1 -ml-2 absolute max-w-48 max-h-60 gap-px rounded font-mono flex flex-col overflow-y-auto overflow-x-hidden shadow-lg border bg-popover text-popover-foreground"
|
||||||
style={{ left: position.left, top: position.top + position.height }}
|
style={{ left: position.left, top: position.top + position.height }}
|
||||||
>
|
>
|
||||||
{suggestions.map((item, i) => (
|
{suggestions.map((item, i) => (
|
||||||
<div
|
<div
|
||||||
key={getItemKey(item, i)}
|
key={getItemKey(item, i)}
|
||||||
|
ref={i === selectedIndex ? selectedItemRef : null}
|
||||||
onMouseDown={() => onItemSelect(item)}
|
onMouseDown={() => onItemSelect(item)}
|
||||||
className={cn(
|
className={cn(
|
||||||
"rounded p-1 px-2 w-full truncate text-sm cursor-pointer hover:bg-accent hover:text-accent-foreground",
|
"rounded p-1 px-2 w-full text-sm cursor-pointer transition-colors select-none",
|
||||||
|
"hover:bg-accent hover:text-accent-foreground",
|
||||||
i === selectedIndex ? "bg-accent text-accent-foreground" : "",
|
i === selectedIndex ? "bg-accent text-accent-foreground" : "",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
|
|
|
||||||
|
|
@ -11,8 +11,18 @@ interface TagSuggestionsProps {
|
||||||
editorActions: React.ForwardedRef<EditorRefActions>;
|
editorActions: React.ForwardedRef<EditorRefActions>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tag suggestions popup that appears when typing "#" in the editor.
|
||||||
|
* Shows previously used tags sorted by frequency.
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* - Type "#" to trigger
|
||||||
|
* - Continue typing to filter tags
|
||||||
|
* - Use Arrow keys to navigate, Enter/Tab to select
|
||||||
|
* - Tags are sorted by usage count (most used first)
|
||||||
|
*/
|
||||||
const TagSuggestions = observer(({ editorRef, editorActions }: TagSuggestionsProps) => {
|
const TagSuggestions = observer(({ editorRef, editorActions }: TagSuggestionsProps) => {
|
||||||
// Sort tags by usage count (descending), then alphabetically
|
// Sort tags by usage count (descending), then alphabetically for ties
|
||||||
const sortedTags = useMemo(
|
const sortedTags = useMemo(
|
||||||
() =>
|
() =>
|
||||||
Object.entries(userStore.state.tagCount)
|
Object.entries(userStore.state.tagCount)
|
||||||
|
|
@ -28,12 +38,12 @@ const TagSuggestions = observer(({ editorRef, editorActions }: TagSuggestionsPro
|
||||||
triggerChar: "#",
|
triggerChar: "#",
|
||||||
items: sortedTags,
|
items: sortedTags,
|
||||||
filterItems: (items, searchQuery) => {
|
filterItems: (items, searchQuery) => {
|
||||||
// Show all tags when no search query
|
|
||||||
if (!searchQuery) return items;
|
if (!searchQuery) return items;
|
||||||
// Filter tags that contain the search query
|
// Filter tags by substring match for flexible searching
|
||||||
return items.filter((tag) => tag.toLowerCase().includes(searchQuery));
|
return items.filter((tag) => tag.toLowerCase().includes(searchQuery));
|
||||||
},
|
},
|
||||||
onAutocomplete: (tag, word, index, actions) => {
|
onAutocomplete: (tag, word, index, actions) => {
|
||||||
|
// Replace the trigger word with the complete tag
|
||||||
actions.removeText(index, word.length);
|
actions.removeText(index, word.length);
|
||||||
actions.insertText(`#${tag}`);
|
actions.insertText(`#${tag}`);
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -152,17 +152,13 @@ const Editor = forwardRef(function Editor(props: Props, ref: React.ForwardedRef<
|
||||||
updateEditorHeight();
|
updateEditorHeight();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const { handleEnterKey } = useListAutoCompletion({
|
// Auto-complete markdown lists when pressing Enter
|
||||||
|
useListAutoCompletion({
|
||||||
|
editorRef,
|
||||||
editorActions,
|
editorActions,
|
||||||
isInIME,
|
isInIME,
|
||||||
});
|
});
|
||||||
|
|
||||||
const handleEditorKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
|
||||||
if (event.key === "Enter") {
|
|
||||||
handleEnterKey(event);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={cn("flex flex-col justify-start items-start relative w-full h-auto max-h-[50vh] bg-inherit", className)}>
|
<div className={cn("flex flex-col justify-start items-start relative w-full h-auto max-h-[50vh] bg-inherit", className)}>
|
||||||
<textarea
|
<textarea
|
||||||
|
|
@ -172,7 +168,6 @@ const Editor = forwardRef(function Editor(props: Props, ref: React.ForwardedRef<
|
||||||
ref={editorRef}
|
ref={editorRef}
|
||||||
onPaste={onPaste}
|
onPaste={onPaste}
|
||||||
onInput={handleEditorInput}
|
onInput={handleEditorInput}
|
||||||
onKeyDown={handleEditorKeyDown}
|
|
||||||
onCompositionStart={() => setIsInIME(true)}
|
onCompositionStart={() => setIsInIME(true)}
|
||||||
onCompositionEnd={() => setTimeout(() => setIsInIME(false))}
|
onCompositionEnd={() => setTimeout(() => setIsInIME(false))}
|
||||||
></textarea>
|
></textarea>
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,9 @@
|
||||||
import { useCallback } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import { detectLastListItem, generateListContinuation } from "@/utils/markdown-list-detection";
|
import { detectLastListItem, generateListContinuation } from "@/utils/markdown-list-detection";
|
||||||
import { EditorRefActions } from ".";
|
import { EditorRefActions } from ".";
|
||||||
|
|
||||||
interface UseListAutoCompletionOptions {
|
interface UseListAutoCompletionOptions {
|
||||||
|
editorRef: React.RefObject<HTMLTextAreaElement>;
|
||||||
editorActions: EditorRefActions;
|
editorActions: EditorRefActions;
|
||||||
isInIME: boolean;
|
isInIME: boolean;
|
||||||
}
|
}
|
||||||
|
|
@ -17,26 +18,34 @@ interface UseListAutoCompletionOptions {
|
||||||
* - Unordered lists (- item, * item, + item)
|
* - Unordered lists (- item, * item, + item)
|
||||||
* - Task lists (- [ ] task, - [x] task)
|
* - Task lists (- [ ] task, - [x] task)
|
||||||
* - Nested lists with proper indentation
|
* - Nested lists with proper indentation
|
||||||
|
*
|
||||||
|
* This hook manages its own event listeners and cleanup.
|
||||||
*/
|
*/
|
||||||
export function useListAutoCompletion({ editorActions, isInIME }: UseListAutoCompletionOptions) {
|
export function useListAutoCompletion({ editorRef, editorActions, isInIME }: UseListAutoCompletionOptions) {
|
||||||
/**
|
// Use refs to avoid stale closures in event handlers
|
||||||
* Handles the Enter key press to auto-complete list items.
|
const isInIMERef = useRef(isInIME);
|
||||||
* Returns true if the event was handled, false otherwise.
|
isInIMERef.current = isInIME;
|
||||||
*/
|
|
||||||
const handleEnterKey = useCallback(
|
const editorActionsRef = useRef(editorActions);
|
||||||
(event: React.KeyboardEvent<HTMLTextAreaElement>): boolean => {
|
editorActionsRef.current = editorActions;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const editor = editorRef.current;
|
||||||
|
if (!editor) return;
|
||||||
|
|
||||||
|
const handleKeyDown = (event: KeyboardEvent) => {
|
||||||
|
// Only handle Enter key
|
||||||
|
if (event.key !== "Enter") return;
|
||||||
|
|
||||||
// Don't handle if in IME composition (for Asian languages)
|
// Don't handle if in IME composition (for Asian languages)
|
||||||
if (isInIME) {
|
if (isInIMERef.current) return;
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Don't handle if modifier keys are pressed (user wants manual control)
|
// Don't handle if modifier keys are pressed (user wants manual control)
|
||||||
if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) {
|
if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return;
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const cursorPosition = editorActions.getCursorPosition();
|
const actions = editorActionsRef.current;
|
||||||
const contentBeforeCursor = editorActions.getContent().substring(0, cursorPosition);
|
const cursorPosition = actions.getCursorPosition();
|
||||||
|
const contentBeforeCursor = actions.getContent().substring(0, cursorPosition);
|
||||||
|
|
||||||
// Detect if we're on a list item
|
// Detect if we're on a list item
|
||||||
const listInfo = detectLastListItem(contentBeforeCursor);
|
const listInfo = detectLastListItem(contentBeforeCursor);
|
||||||
|
|
@ -44,14 +53,14 @@ export function useListAutoCompletion({ editorActions, isInIME }: UseListAutoCom
|
||||||
if (listInfo.type) {
|
if (listInfo.type) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const continuation = generateListContinuation(listInfo);
|
const continuation = generateListContinuation(listInfo);
|
||||||
editorActions.insertText("\n" + continuation);
|
actions.insertText("\n" + continuation);
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return false;
|
editor.addEventListener("keydown", handleKeyDown);
|
||||||
},
|
|
||||||
[editorActions, isInIME],
|
|
||||||
);
|
|
||||||
|
|
||||||
return { handleEnterKey };
|
return () => {
|
||||||
|
editor.removeEventListener("keydown", handleKeyDown);
|
||||||
|
};
|
||||||
|
}, [editorRef.current]);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,28 +2,64 @@ import { useEffect, useRef, useState } from "react";
|
||||||
import getCaretCoordinates from "textarea-caret";
|
import getCaretCoordinates from "textarea-caret";
|
||||||
import { EditorRefActions } from ".";
|
import { EditorRefActions } from ".";
|
||||||
|
|
||||||
export type Position = { left: number; top: number; height: number };
|
export interface Position {
|
||||||
|
left: number;
|
||||||
|
top: number;
|
||||||
|
height: number;
|
||||||
|
}
|
||||||
|
|
||||||
export interface UseSuggestionsOptions<T> {
|
export interface UseSuggestionsOptions<T> {
|
||||||
|
/** Reference to the textarea element */
|
||||||
editorRef: React.RefObject<HTMLTextAreaElement>;
|
editorRef: React.RefObject<HTMLTextAreaElement>;
|
||||||
|
/** Reference to editor actions for text manipulation */
|
||||||
editorActions: React.ForwardedRef<EditorRefActions>;
|
editorActions: React.ForwardedRef<EditorRefActions>;
|
||||||
|
/** Character that triggers the suggestions (e.g., '/', '#', '@') */
|
||||||
triggerChar: string;
|
triggerChar: string;
|
||||||
|
/** Array of items to show in suggestions */
|
||||||
items: T[];
|
items: T[];
|
||||||
|
/** Function to filter items based on search query */
|
||||||
filterItems: (items: T[], searchQuery: string) => T[];
|
filterItems: (items: T[], searchQuery: string) => T[];
|
||||||
|
/** Callback when an item is selected for autocomplete */
|
||||||
onAutocomplete: (item: T, word: string, startIndex: number, actions: EditorRefActions) => void;
|
onAutocomplete: (item: T, word: string, startIndex: number, actions: EditorRefActions) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UseSuggestionsReturn<T> {
|
export interface UseSuggestionsReturn<T> {
|
||||||
|
/** Current position of the popup, or null if hidden */
|
||||||
position: Position | null;
|
position: Position | null;
|
||||||
|
/** Filtered suggestions based on current search */
|
||||||
suggestions: T[];
|
suggestions: T[];
|
||||||
|
/** Index of the currently selected suggestion */
|
||||||
selectedIndex: number;
|
selectedIndex: number;
|
||||||
|
/** Whether the suggestions popup is visible */
|
||||||
isVisible: boolean;
|
isVisible: boolean;
|
||||||
|
/** Handler to select a suggestion item */
|
||||||
handleItemSelect: (item: T) => void;
|
handleItemSelect: (item: T) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Shared hook for managing suggestion popups in the editor.
|
* Shared hook for managing suggestion popups in the editor.
|
||||||
* Handles positioning, keyboard navigation, filtering, and autocomplete logic.
|
* Handles positioning, keyboard navigation, filtering, and autocomplete logic.
|
||||||
|
*
|
||||||
|
* Features:
|
||||||
|
* - Auto-positioning based on caret location
|
||||||
|
* - Keyboard navigation (Arrow Up/Down, Enter, Tab, Escape)
|
||||||
|
* - Smart filtering based on trigger character
|
||||||
|
* - Proper event cleanup
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* const { position, suggestions, selectedIndex, isVisible, handleItemSelect } = useSuggestions({
|
||||||
|
* editorRef,
|
||||||
|
* editorActions,
|
||||||
|
* triggerChar: '#',
|
||||||
|
* items: tags,
|
||||||
|
* filterItems: (items, query) => items.filter(tag => tag.includes(query)),
|
||||||
|
* onAutocomplete: (tag, word, index, actions) => {
|
||||||
|
* actions.removeText(index, word.length);
|
||||||
|
* actions.insertText(`#${tag}`);
|
||||||
|
* },
|
||||||
|
* });
|
||||||
|
* ```
|
||||||
*/
|
*/
|
||||||
export function useSuggestions<T>({
|
export function useSuggestions<T>({
|
||||||
editorRef,
|
editorRef,
|
||||||
|
|
@ -64,7 +100,10 @@ export function useSuggestions<T>({
|
||||||
isVisibleRef.current = !!(position && suggestionsRef.current.length > 0);
|
isVisibleRef.current = !!(position && suggestionsRef.current.length > 0);
|
||||||
|
|
||||||
const handleAutocomplete = (item: T) => {
|
const handleAutocomplete = (item: T) => {
|
||||||
if (!editorActions || !("current" in editorActions) || !editorActions.current) return;
|
if (!editorActions || !("current" in editorActions) || !editorActions.current) {
|
||||||
|
console.warn("useSuggestions: editorActions not available for autocomplete");
|
||||||
|
return;
|
||||||
|
}
|
||||||
const [word, index] = getCurrentWord();
|
const [word, index] = getCurrentWord();
|
||||||
onAutocomplete(item, word, index, editorActions.current);
|
onAutocomplete(item, word, index, editorActions.current);
|
||||||
hide();
|
hide();
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue