mirror of https://github.com/usememos/memos
chore(web): improve CommandSuggestions and TagSuggestions components (#5239)
Co-authored-by: Claude <noreply@anthropic.com>pull/5240/head
parent
bd21338fdb
commit
e8b0273473
@ -0,0 +1,67 @@
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
suggestions,
|
||||
selectedIndex,
|
||||
onItemSelect,
|
||||
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
|
||||
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 text-sm cursor-pointer transition-colors select-none",
|
||||
"hover:bg-accent hover:text-accent-foreground",
|
||||
i === selectedIndex ? "bg-accent text-accent-foreground" : "",
|
||||
)}
|
||||
>
|
||||
{renderItem(item, i === selectedIndex)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,66 @@
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom hook for handling markdown list auto-completion.
|
||||
* When the user presses Enter on a list item, this hook automatically
|
||||
* continues the list with the appropriate formatting.
|
||||
*
|
||||
* Supports:
|
||||
* - Ordered lists (1. item, 2. item, etc.)
|
||||
* - 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({ 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 (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;
|
||||
|
||||
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);
|
||||
|
||||
if (listInfo.type) {
|
||||
event.preventDefault();
|
||||
const continuation = generateListContinuation(listInfo);
|
||||
actions.insertText("\n" + continuation);
|
||||
}
|
||||
};
|
||||
|
||||
editor.addEventListener("keydown", handleKeyDown);
|
||||
|
||||
return () => {
|
||||
editor.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, [editorRef.current]);
|
||||
}
|
||||
@ -0,0 +1,194 @@
|
||||
import { 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> {
|
||||
/** 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,
|
||||
editorActions,
|
||||
triggerChar,
|
||||
items,
|
||||
filterItems,
|
||||
onAutocomplete,
|
||||
}: UseSuggestionsOptions<T>): UseSuggestionsReturn<T> {
|
||||
const [position, setPosition] = useState<Position | null>(null);
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
|
||||
// Use refs to avoid stale closures in event handlers
|
||||
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);
|
||||
|
||||
// Filter items based on the current word after the trigger character
|
||||
const suggestionsRef = useRef<T[]>([]);
|
||||
suggestionsRef.current = (() => {
|
||||
const [word] = getCurrentWord();
|
||||
if (!word.startsWith(triggerChar)) return [];
|
||||
const searchQuery = word.slice(triggerChar.length).toLowerCase();
|
||||
return filterItems(items, searchQuery);
|
||||
})();
|
||||
|
||||
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 for autocomplete");
|
||||
return;
|
||||
}
|
||||
const [word, index] = getCurrentWord();
|
||||
onAutocomplete(item, word, index, editorActions.current);
|
||||
hide();
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (!isVisibleRef.current) return;
|
||||
|
||||
const suggestions = suggestionsRef.current;
|
||||
const selected = selectedRef.current;
|
||||
|
||||
// Hide on Escape or horizontal arrows
|
||||
if (["Escape", "ArrowLeft", "ArrowRight"].includes(e.code)) {
|
||||
hide();
|
||||
return;
|
||||
}
|
||||
|
||||
// Navigate down
|
||||
if (e.code === "ArrowDown") {
|
||||
setSelectedIndex((selected + 1) % suggestions.length);
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return;
|
||||
}
|
||||
|
||||
// Navigate up
|
||||
if (e.code === "ArrowUp") {
|
||||
setSelectedIndex((selected - 1 + suggestions.length) % suggestions.length);
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return;
|
||||
}
|
||||
|
||||
// Accept suggestion
|
||||
if (["Enter", "Tab"].includes(e.code)) {
|
||||
handleAutocomplete(suggestions[selected]);
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}
|
||||
};
|
||||
|
||||
const handleInput = () => {
|
||||
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 caretCoordinates = getCaretCoordinates(editor, index);
|
||||
caretCoordinates.top -= editor.scrollTop;
|
||||
setPosition(caretCoordinates);
|
||||
} else {
|
||||
hide();
|
||||
}
|
||||
};
|
||||
|
||||
// Register event listeners
|
||||
const listenersRegisteredRef = useRef(false);
|
||||
useEffect(() => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor || listenersRegisteredRef.current) return;
|
||||
|
||||
editor.addEventListener("click", hide);
|
||||
editor.addEventListener("blur", hide);
|
||||
editor.addEventListener("keydown", handleKeyDown);
|
||||
editor.addEventListener("input", handleInput);
|
||||
listenersRegisteredRef.current = true;
|
||||
|
||||
return () => {
|
||||
editor.removeEventListener("click", hide);
|
||||
editor.removeEventListener("blur", hide);
|
||||
editor.removeEventListener("keydown", handleKeyDown);
|
||||
editor.removeEventListener("input", handleInput);
|
||||
listenersRegisteredRef.current = false;
|
||||
};
|
||||
}, [editorRef.current]);
|
||||
|
||||
return {
|
||||
position,
|
||||
suggestions: suggestionsRef.current,
|
||||
selectedIndex,
|
||||
isVisible: isVisibleRef.current,
|
||||
handleItemSelect: handleAutocomplete,
|
||||
};
|
||||
}
|
||||
Loading…
Reference in New Issue