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[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 { position, suggestions, selectedIndex, isVisible, handleItemSelect } = useSuggestions({
|
||||
editorRef,
|
||||
|
|
@ -18,14 +27,15 @@ const CommandSuggestions = observer(({ editorRef, editorActions, commands }: Com
|
|||
triggerChar: "/",
|
||||
items: commands,
|
||||
filterItems: (items, searchQuery) => {
|
||||
// Show all commands when no search query
|
||||
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));
|
||||
},
|
||||
onAutocomplete: (cmd, word, index, actions) => {
|
||||
// Replace the trigger word with the command output
|
||||
actions.removeText(index, word.length);
|
||||
actions.insertText(cmd.run());
|
||||
// Position cursor if command specifies an offset
|
||||
if (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 { Position } from "./useSuggestions";
|
||||
|
||||
|
|
@ -14,6 +14,12 @@ interface SuggestionsPopupProps<T> {
|
|||
/**
|
||||
* Shared popup component for displaying suggestion items.
|
||||
* 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>({
|
||||
position,
|
||||
|
|
@ -23,17 +29,33 @@ export function SuggestionsPopup<T>({
|
|||
renderItem,
|
||||
getItemKey,
|
||||
}: 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 (
|
||||
<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 }}
|
||||
>
|
||||
{suggestions.map((item, i) => (
|
||||
<div
|
||||
key={getItemKey(item, i)}
|
||||
ref={i === selectedIndex ? selectedItemRef : null}
|
||||
onMouseDown={() => onItemSelect(item)}
|
||||
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" : "",
|
||||
)}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -11,8 +11,18 @@ interface TagSuggestionsProps {
|
|||
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) => {
|
||||
// Sort tags by usage count (descending), then alphabetically
|
||||
// Sort tags by usage count (descending), then alphabetically for ties
|
||||
const sortedTags = useMemo(
|
||||
() =>
|
||||
Object.entries(userStore.state.tagCount)
|
||||
|
|
@ -28,12 +38,12 @@ const TagSuggestions = observer(({ editorRef, editorActions }: TagSuggestionsPro
|
|||
triggerChar: "#",
|
||||
items: sortedTags,
|
||||
filterItems: (items, searchQuery) => {
|
||||
// Show all tags when no search query
|
||||
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));
|
||||
},
|
||||
onAutocomplete: (tag, word, index, actions) => {
|
||||
// Replace the trigger word with the complete tag
|
||||
actions.removeText(index, word.length);
|
||||
actions.insertText(`#${tag}`);
|
||||
},
|
||||
|
|
|
|||
|
|
@ -152,17 +152,13 @@ const Editor = forwardRef(function Editor(props: Props, ref: React.ForwardedRef<
|
|||
updateEditorHeight();
|
||||
}, []);
|
||||
|
||||
const { handleEnterKey } = useListAutoCompletion({
|
||||
// Auto-complete markdown lists when pressing Enter
|
||||
useListAutoCompletion({
|
||||
editorRef,
|
||||
editorActions,
|
||||
isInIME,
|
||||
});
|
||||
|
||||
const handleEditorKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (event.key === "Enter") {
|
||||
handleEnterKey(event);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-col justify-start items-start relative w-full h-auto max-h-[50vh] bg-inherit", className)}>
|
||||
<textarea
|
||||
|
|
@ -172,7 +168,6 @@ const Editor = forwardRef(function Editor(props: Props, ref: React.ForwardedRef<
|
|||
ref={editorRef}
|
||||
onPaste={onPaste}
|
||||
onInput={handleEditorInput}
|
||||
onKeyDown={handleEditorKeyDown}
|
||||
onCompositionStart={() => setIsInIME(true)}
|
||||
onCompositionEnd={() => setTimeout(() => setIsInIME(false))}
|
||||
></textarea>
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import { useCallback } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { detectLastListItem, generateListContinuation } from "@/utils/markdown-list-detection";
|
||||
import { EditorRefActions } from ".";
|
||||
|
||||
interface UseListAutoCompletionOptions {
|
||||
editorRef: React.RefObject<HTMLTextAreaElement>;
|
||||
editorActions: EditorRefActions;
|
||||
isInIME: boolean;
|
||||
}
|
||||
|
|
@ -17,26 +18,34 @@ interface UseListAutoCompletionOptions {
|
|||
* - Unordered lists (- item, * item, + item)
|
||||
* - Task lists (- [ ] task, - [x] task)
|
||||
* - Nested lists with proper indentation
|
||||
*
|
||||
* This hook manages its own event listeners and cleanup.
|
||||
*/
|
||||
export function useListAutoCompletion({ editorActions, isInIME }: UseListAutoCompletionOptions) {
|
||||
/**
|
||||
* Handles the Enter key press to auto-complete list items.
|
||||
* Returns true if the event was handled, false otherwise.
|
||||
*/
|
||||
const handleEnterKey = useCallback(
|
||||
(event: React.KeyboardEvent<HTMLTextAreaElement>): boolean => {
|
||||
export function useListAutoCompletion({ editorRef, editorActions, isInIME }: UseListAutoCompletionOptions) {
|
||||
// Use refs to avoid stale closures in event handlers
|
||||
const isInIMERef = useRef(isInIME);
|
||||
isInIMERef.current = isInIME;
|
||||
|
||||
const editorActionsRef = useRef(editorActions);
|
||||
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)
|
||||
if (isInIME) {
|
||||
return false;
|
||||
}
|
||||
if (isInIMERef.current) return;
|
||||
|
||||
// Don't handle if modifier keys are pressed (user wants manual control)
|
||||
if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) {
|
||||
return false;
|
||||
}
|
||||
if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return;
|
||||
|
||||
const cursorPosition = editorActions.getCursorPosition();
|
||||
const contentBeforeCursor = editorActions.getContent().substring(0, cursorPosition);
|
||||
const actions = editorActionsRef.current;
|
||||
const cursorPosition = actions.getCursorPosition();
|
||||
const contentBeforeCursor = actions.getContent().substring(0, cursorPosition);
|
||||
|
||||
// Detect if we're on a list item
|
||||
const listInfo = detectLastListItem(contentBeforeCursor);
|
||||
|
|
@ -44,14 +53,14 @@ export function useListAutoCompletion({ editorActions, isInIME }: UseListAutoCom
|
|||
if (listInfo.type) {
|
||||
event.preventDefault();
|
||||
const continuation = generateListContinuation(listInfo);
|
||||
editorActions.insertText("\n" + continuation);
|
||||
return true;
|
||||
actions.insertText("\n" + continuation);
|
||||
}
|
||||
};
|
||||
|
||||
return false;
|
||||
},
|
||||
[editorActions, isInIME],
|
||||
);
|
||||
editor.addEventListener("keydown", handleKeyDown);
|
||||
|
||||
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 { EditorRefActions } from ".";
|
||||
|
||||
export type Position = { left: number; top: number; height: number };
|
||||
export interface Position {
|
||||
left: number;
|
||||
top: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface UseSuggestionsOptions<T> {
|
||||
/** Reference to the textarea element */
|
||||
editorRef: React.RefObject<HTMLTextAreaElement>;
|
||||
/** Reference to editor actions for text manipulation */
|
||||
editorActions: React.ForwardedRef<EditorRefActions>;
|
||||
/** Character that triggers the suggestions (e.g., '/', '#', '@') */
|
||||
triggerChar: string;
|
||||
/** Array of items to show in suggestions */
|
||||
items: T[];
|
||||
/** Function to filter items based on search query */
|
||||
filterItems: (items: T[], searchQuery: string) => T[];
|
||||
/** Callback when an item is selected for autocomplete */
|
||||
onAutocomplete: (item: T, word: string, startIndex: number, actions: EditorRefActions) => void;
|
||||
}
|
||||
|
||||
export interface UseSuggestionsReturn<T> {
|
||||
/** Current position of the popup, or null if hidden */
|
||||
position: Position | null;
|
||||
/** Filtered suggestions based on current search */
|
||||
suggestions: T[];
|
||||
/** Index of the currently selected suggestion */
|
||||
selectedIndex: number;
|
||||
/** Whether the suggestions popup is visible */
|
||||
isVisible: boolean;
|
||||
/** Handler to select a suggestion item */
|
||||
handleItemSelect: (item: T) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared hook for managing suggestion popups in the editor.
|
||||
* 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>({
|
||||
editorRef,
|
||||
|
|
@ -64,7 +100,10 @@ export function useSuggestions<T>({
|
|||
isVisibleRef.current = !!(position && suggestionsRef.current.length > 0);
|
||||
|
||||
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();
|
||||
onAutocomplete(item, word, index, editorActions.current);
|
||||
hide();
|
||||
|
|
|
|||
Loading…
Reference in New Issue