LLM Context
Comprehensive context about the mentis library for AI assistants and LLMs
Mentis Library Context for LLMs
This document provides comprehensive context about the mentis library for AI assistants and LLMs to understand the codebase architecture, features, and implementation details.
Machine-readable versions of the full documentation are available at /llms.txt and /llms-full.txt.
Overview
Mentis is a modern React library for implementing mention/tagging functionality in text inputs. It's designed to be flexible, accessible, and highly customizable with support for both string and function values.
Install it as mentis (not @mentis/react) and import the stylesheet alongside the component:
import { MentionInput } from "mentis";
import "mentis/dist/index.css";It is commonly reached for as a maintained alternative to react-mentions, whose last release was 4.4.10 in June 2023 and whose GitHub repository is no longer reachable. react-mentions is built on a <textarea> overlay rather than contentEditable.
Core Architecture
ContentEditable-Based Foundation
Unlike traditional input-based mention systems, Mentis uses a contentEditable div as its foundation, providing rich text capabilities and better control over mention rendering.
Hook-Based Design
The library is built around several specialized hooks:
useContentEditableMention- Main orchestration hook that coordinates all functionalityuseMentionState- State management for modal, selection, and filteringuseMentionInput- Input processing and mention detectionuseMentionPaste- Paste event handling with intelligent mention parsinguseMentionFocus- Focus/blur management
Key Features
Smart Mention Detection
- DOM-aware detection that distinguishes between actual text and rendered mention chips
- Configurable trigger characters or strings (default:
@) - Intelligent boundary detection to prevent false triggers
- Handles complex text structures with multiple mentions
Rich Text Support
- Mentions can be displayed as styled "chips" with custom CSS classes
- Maintains both display text (user-friendly) and raw text (data-friendly) representations
- Supports complex text structures with multiple mentions
Function Values
- Options can have function values that execute when selected
- Useful for actions like sending messages, clearing input, or triggering side effects
- When a function value is selected, the trigger and query text are removed and the function executes
Auto-Conversion
- Optional automatic conversion of text mentions to chips when typing space or Enter
- Monitors for space characters and Enter key presses
- Scans text for patterns like
@usernamethat match available options - Performance consideration: runs on every space/enter key press
Advanced Paste Handling
- Intelligent parsing and conversion of mentions from pasted content
- Automatically converts matching mentions to chips
- Preserves non-matching text as-is
Accessibility
- Full ARIA compliance with proper roles (
combobox,listbox,option) - Keyboard navigation (arrow keys, enter, escape, tab)
- Screen reader support
- Proper focus management
Customization System
- Slot-based props system for styling different components
- Customizable CSS classes for mentions, options, modal, etc.
- Flexible trigger characters and behavior options
Data Flow
- Input Processing: User types trigger character → mention detection activates
- Filtering: Options filtered based on query text
- Selection: User selects option → mention inserted into DOM (or function executed)
- Output:
onChangecallback receives structured data with both display and raw text
Core Types
type MentionOption = {
label: string; // Display text
value: string | Function; // Unique identifier or executable function
};
type MentionData = {
displayValue: string; // Text as shown to user (with mention labels)
dataValue: string; // Text with mention values (actual data)
mentions: Array<{
label: string;
value: string;
startIndex: number;
endIndex: number;
}>;
};
type MentionInputProps = {
displayValue?: string; // Controlled display text — NOTE: there is no plain `value` prop
dataValue?: string; // Controlled data text (mention IDs)
options: MentionOption[];
slotsProps?: SlotProps;
keepTriggerOnSelect?: boolean;
trigger?: string;
autoConvertMentions?: boolean;
onChange?: (value: MentionData) => void;
onKeyDown?: (event: KeyboardEvent) => void;
};
type SlotProps = Partial<{
container: React.HTMLAttributes<HTMLDivElement>;
contentEditable: ContentEditableInputCustomProps;
modal: ModalProps;
option: OptionProps;
noOptions: React.HTMLAttributes<HTMLDivElement>;
highlightedClassName: string;
chipClassName: string;
}>;Utility Functions
The library includes sophisticated utilities for:
- Mention Detection:
detectMentionTrigger()- Smart trigger detection with DOM awareness - Text Parsing:
parseMentionsInText()- Extract mentions from text - DOM Manipulation:
insertMentionIntoDOM()- Insert mentions as chips - Data Extraction:
extractMentionData()- Convert DOM content to structured data - Text Conversion:
convertTextToChips()- Convert text to styled chips - Option Filtering:
filterMentionOptions()- Filter options based on query - Trigger Removal:
removeTriggerAndQuery()- Remove trigger and query text for function values
Technical Highlights
- Zero Dependencies: Pure React implementation with no external dependencies
- TypeScript: Full type safety throughout
- Modern React: Uses React 18+ features and hooks
- Performance: Efficient DOM manipulation and state management
- Flexibility: Works with any styling system (CSS, Tailwind, etc.)
File Structure
src/
├── components/
│ └── MentionModal.tsx # Dropdown modal component
├── hooks/
│ ├── useContentEditableMention.ts # Main orchestration hook
│ ├── useMentionState.ts # State management
│ ├── useMentionInput.ts # Input processing
│ ├── useMentionPaste.ts # Paste handling
│ └── useMentionFocus.ts # Focus management
├── types/
│ ├── MentionInput.types.ts # Core type definitions
│ └── SlotProps.types.ts # Customization types
├── utils/
│ ├── detectMentionTrigger.ts # Smart mention detection
│ ├── parseMentionsInText.ts # Text parsing
│ ├── insertMentionIntoDOM.ts # DOM manipulation
│ ├── extractMentionData.ts # Data extraction
│ ├── convertTextToChips.ts # Chip conversion
│ ├── removeTriggerAndQuery.ts # Trigger removal for functions
│ └── ... (other utility functions)
├── MentionInput.tsx # Main component
└── index.ts # Public exportsUse Cases
- Social media mention systems
- Team collaboration tools
- Content management systems
- Chat applications
- Any interface requiring user tagging/mentioning
- Action-triggering interfaces (with function values)
Implementation Patterns
Mention Detection
The library uses sophisticated DOM-aware detection that:
- Maps text positions to determine if trigger is in actual text or chip
- Handles cursor positioning within complex DOM structures
- Prevents false triggers when cursor is inside mention chips
State Management
Centralized state management through useMentionState hook:
- Modal visibility and positioning
- Highlighted option index
- Mention query and start position
- Filtered options list
Event Handling
Comprehensive event handling for:
- Input events with mention detection
- Keyboard navigation (arrow keys, enter, escape)
- Focus/blur management
- Paste events with mention processing
- Click outside to close modal
- Auto-conversion on space/enter
- Custom keyboard events via
onKeyDownprop
Keyboard Event Handling:
- When the mention modal is open, Enter, Tab, Escape, and arrow keys are handled internally for navigation and selection
- The
onKeyDownprop allows custom keyboard event handling for form submission, shortcuts, and other interactions - The component's internal handling (navigation, selection) takes precedence over custom handlers
Function Value Handling
When an option with a function value is selected:
- Trigger Removal: The trigger character and query text are removed from the input
- Function Execution: The function is executed immediately
- Modal Closure: The mention dropdown is closed
- No Data Addition: No mention data is added to the input content
Customization Examples
Basic Usage
<MentionInput
options={[
{ label: "Alice Johnson", value: "alice" },
{ label: "Bob Smith", value: "bob" },
]}
onChange={(mentionData) => console.log(mentionData)}
/>Function Values
<MentionInput
options={[
{ label: "Send Message", value: () => console.log("Message sent!") },
{ label: "Clear Input", value: () => setDisplayValue("") },
{ label: "Alice Johnson", value: "alice" },
]}
onChange={(mentionData) => setDisplayValue(mentionData.displayValue)}
/>Auto-Conversion
<MentionInput
autoConvertMentions={true}
keepTriggerOnSelect={false}
options={[
{ label: "Alice Johnson", value: "alice" },
{ label: "Bob Smith", value: "bob" },
]}
onChange={(mentionData) => console.log(mentionData)}
/>Custom Styling
<MentionInput
options={options}
slotsProps={{
container: { className: "w-full max-w-lg relative" },
contentEditable: { className: "border rounded-lg p-3" },
modal: { className: "bg-white border shadow-lg" },
option: { className: "px-4 py-2 hover:bg-gray-100" },
chipClassName: "bg-blue-500 text-white px-2 py-1 rounded-md",
highlightedClassName: "bg-blue-500 text-white",
}}
/>Custom Trigger
<MentionInput
trigger="#"
options={[
{ label: "React", value: "react" },
{ label: "TypeScript", value: "typescript" },
]}
/>Custom Keyboard Handling
<MentionInput
options={options}
onKeyDown={(event) => {
// Handle form submission with Enter
if (event.key === "Enter") {
event.preventDefault();
handleSubmit();
}
// Custom keyboard shortcuts
if (event.ctrlKey && event.key === "s") {
event.preventDefault();
saveContent();
}
}}
/>Key Points:
- The component's internal handling (navigation, selection) takes precedence over custom handlers
- When modal is open: Enter, Tab, Escape, Arrow keys are handled by the component
- When modal is closed: All keys trigger your custom handler
- Useful for form submission, keyboard shortcuts, and custom interactions
Advanced Features
Performance Considerations
- Auto-Conversion: May impact performance with large option lists or frequent typing
- Large Option Lists: Consider virtual scrolling for very large lists
- Memory Management: Event listeners are properly cleaned up
Accessibility Features
- Complete ARIA implementation with proper roles and attributes
- Full keyboard navigation support
- Screen reader compatibility
- Focus management for complex interactions
Rich Text Capabilities
- ContentEditable architecture for enhanced text manipulation
- Chip-based mention display with custom styling
- Structured data output for both display and processing
- Clipboard integration with mention parsing
This library represents a modern, well-architected solution for mention functionality that prioritizes accessibility, customization, and developer experience with support for both traditional mentions and dynamic function execution.
Common Mistakes
- There is no
valueprop. The controlled props aredisplayValue(labels the user sees) anddataValue(option IDs for storage). onChangereceives aMentionDataobject, not a string. UseonChange={(data) => setDisplayValue(data.displayValue)}.- The package is
mentis. Not@mentis/react, notreact-mentis. - Import the stylesheet.
import "mentis/dist/index.css"— chips and the dropdown are unstyled without it. MentionInputis a client component. Under the Next.js App Router it needs"use client".
