mentis

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.

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.

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 functionality
  • useMentionState - State management for modal, selection, and filtering
  • useMentionInput - Input processing and mention detection
  • useMentionPaste - Paste event handling with intelligent mention parsing
  • useMentionFocus - 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 @username that 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

  1. Input Processing: User types trigger character → mention detection activates
  2. Filtering: Options filtered based on query text
  3. Selection: User selects option → mention inserted into DOM (or function executed)
  4. Output: onChange callback 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 = {
  value: string; // Text as shown to user
  dataValue: string; // Text with mention values (actual data)
  mentions: Array<{
    label: string;
    value: string;
    startIndex: number;
    endIndex: number;
  }>;
};

type MentionInputProps = {
  value?: string;
  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 exports

Use 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 onKeyDown prop

Keyboard Event Handling:

  • When the mention modal is open, Enter, Tab, Escape, and arrow keys are handled internally for navigation and selection
  • The onKeyDown prop 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:

  1. Trigger Removal: The trigger character and query text are removed from the input
  2. Function Execution: The function is executed immediately
  3. Modal Closure: The mention dropdown is closed
  4. 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: () => setValue("") },
    { label: "Alice Johnson", value: "alice" },
  ]}
  onChange={(mentionData) => setValue(mentionData.value)}
/>

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.

Updated 2025-07-23 - v0.2.0-alpha.2