UIPackage React Native
Search
Menu

Mention Input

Text field with trigger detection (default @), caret-aware mention queries, range-tracked mention tokens that survive edits around them, and caller-composed suggestions.

Install

First install? Set up the registry in your app.

npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add mention-input

Source files

Expand a file to read the source the installer copies into your app.

components/ui/mention-input/MentionInput.tsx
import * as React from 'react'
import { View, type TextInput } from 'react-native'
import { Input, type InputProps } from '@/components/ui/input'
import { cn } from '@/lib/utils'
import {
  applyTextChange,
  findQuery,
  insertMention,
  validateMentions,
  type MentionItem,
  type MentionQuery,
  type MentionValue,
  type TextSelection,
} from './mention-utils'

export interface MentionSuggestionsProps {
  query: MentionQuery
  /** Replaces the query token with `trigger + label`, records the mention, and moves the caret after it. */
  select: (item: MentionItem) => void
}

export interface MentionInputProps extends Omit<
  InputProps,
  'value' | 'defaultValue' | 'onChangeText' | 'selection' | 'children'
> {
  value?: MentionValue
  defaultValue?: MentionValue
  onValueChange?: (value: MentionValue) => void
  /** Single-character trigger(s). Default `'@'`. */
  trigger?: string | readonly string[]
  /** Fires once per distinct query, and with `null` when the query ends. */
  onQueryChange?: (query: MentionQuery | null) => void
  /** Rendered below the field while a query is active. Compose your own list, popover, or sheet. */
  renderSuggestions?: (props: MentionSuggestionsProps) => React.ReactNode
  disabled?: boolean
  wrapperClassName?: string
}

const EMPTY: MentionValue = { text: '', mentions: [] }

const MentionInput = React.forwardRef<React.ComponentRef<typeof TextInput>, MentionInputProps>(
  (
    {
      value,
      defaultValue,
      onValueChange,
      trigger = '@',
      onQueryChange,
      renderSuggestions,
      disabled,
      editable = true,
      onSelectionChange,
      wrapperClassName,
      ...props
    },
    ref,
  ) => {
    const controlled = value !== undefined
    const [inner, setInner] = React.useState<MentionValue>(() => {
      const initial = defaultValue ?? EMPTY
      return { text: initial.text, mentions: validateMentions(initial.text, initial.mentions) }
    })
    const current = React.useMemo(
      () => (controlled ? { text: value.text, mentions: validateMentions(value.text, value.mentions) } : inner),
      [controlled, value, inner],
    )
    const end = current.text.length
    const [selection, setSelection] = React.useState<TextSelection>({ start: end, end })
    // Caret to force after inserting a mention; cleared on the next native selection event.
    const [pendingCaret, setPendingCaret] = React.useState<number | null>(null)
    const enabled = editable && !disabled
    const triggers = React.useMemo(() => (typeof trigger === 'string' ? [trigger] : trigger), [trigger])

    const query = React.useMemo(
      () => (enabled ? findQuery(current.text, selection, triggers, current.mentions) : null),
      [enabled, current, selection, triggers],
    )

    const queryKey = query ? `${query.trigger}|${query.text}|${query.start}|${query.end}` : ''
    const lastQueryKey = React.useRef('')
    const onQueryChangeRef = React.useRef(onQueryChange)
    onQueryChangeRef.current = onQueryChange
    React.useEffect(() => {
      if (queryKey === lastQueryKey.current) return
      lastQueryKey.current = queryKey
      onQueryChangeRef.current?.(query)
    }, [queryKey, query])

    const commit = (next: MentionValue, caret: number) => {
      if (!controlled) setInner(next)
      setSelection({ start: caret, end: caret })
      onValueChange?.(next)
    }

    const select = (item: MentionItem) => {
      if (!query || !enabled) return
      const result = insertMention(current, query, item)
      commit(result.value, result.caret)
      setPendingCaret(result.caret)
    }

    // ponytail: the controlled `selection` prop is only sent while a caret is pending and within the
    // shown text, so a refused controlled update can never push an out-of-range selection to Android.
    const forcedSelection =
      pendingCaret !== null && pendingCaret <= end ? { start: pendingCaret, end: pendingCaret } : undefined

    return (
      <View className={cn('gap-2', wrapperClassName)}>
        <Input
          ref={ref}
          {...props}
          editable={enabled}
          value={current.text}
          selection={forcedSelection}
          onChangeText={(text) => {
            if (!enabled) return
            setPendingCaret(null)
            // onChangeText vs onSelectionChange order differs by platform; the diff's own caret is
            // correct for typing/paste, and a later selection event corrects anything else.
            const result = applyTextChange(current, text, Math.min(selection.start, selection.end))
            commit(result.value, result.caret)
          }}
          onSelectionChange={(event) => {
            setPendingCaret(null)
            setSelection(event.nativeEvent.selection)
            onSelectionChange?.(event)
          }}
        />
        {query && renderSuggestions ? renderSuggestions({ query, select }) : null}
      </View>
    )
  },
)
MentionInput.displayName = 'MentionInput'

export { MentionInput }
export type { Mention, MentionItem, MentionQuery, MentionValue } from './mention-utils'
components/ui/mention-input/mention-utils.ts
/** A committed mention: `text.slice(start, end) === trigger + label`. `end` is exclusive. */
export interface Mention {
  start: number
  end: number
  id: string
  label: string
  trigger: string
}

export interface MentionValue {
  text: string
  mentions: Mention[]
}

/**
 * The active mention query. `text` is what was typed between the trigger and the caret (use it to
 * filter); `start..end` is the whole token that `select` replaces, so picking a suggestion with the
 * caret mid-word replaces the full word, not just the part before the caret.
 */
export interface MentionQuery {
  trigger: string
  text: string
  start: number
  end: number
}

export interface MentionItem {
  id: string
  label: string
}

export interface TextSelection {
  start: number
  end: number
}

const isSpace = (char: string | undefined) => char !== undefined && /\s/.test(char)

/**
 * A query is active only with a collapsed caret inside a run that starts with a trigger at the start
 * of the text or after whitespace, with no whitespace between trigger and caret. `a@b` never
 * triggers, and neither does a caret inside or at the end of a committed mention.
 */
export function findQuery(
  text: string,
  selection: TextSelection,
  triggers: readonly string[],
  mentions: readonly Mention[] = [],
): MentionQuery | null {
  if (selection.start !== selection.end) return null
  const caret = Math.min(Math.max(selection.start, 0), text.length)
  let start = caret
  while (start > 0 && !isSpace(text[start - 1])) start--
  if (start === caret || !triggers.includes(text[start]!)) return null
  if (mentions.some((m) => (start >= m.start && start < m.end) || (caret > m.start && caret <= m.end))) return null
  let end = caret
  while (end < text.length && !isSpace(text[end])) end++
  return { trigger: text[start]!, text: text.slice(start + 1, caret), start, end }
}

export interface TextEdit {
  /** First changed index (same in both strings). */
  start: number
  /** End of the removed range in the previous text. */
  removedEnd: number
  /** End of the inserted range in the next text. */
  insertedEnd: number
}

/**
 * Common prefix/suffix diff. With repeated characters the edit position is ambiguous (typing `@`
 * before `@Ann` looks like an insertion after the first `@`), so `caretHint` โ€” the caret before the
 * edit โ€” caps the prefix to where the user was actually typing.
 */
export function diffText(prev: string, next: string, caretHint = Infinity): TextEdit {
  const max = Math.min(prev.length, next.length)
  let start = 0
  while (start < max && start < caretHint && prev[start] === next[start]) start++
  let suffix = 0
  while (suffix < max - start && prev[prev.length - 1 - suffix] === next[next.length - 1 - suffix]) suffix++
  return { start, removedEnd: prev.length - suffix, insertedEnd: next.length - suffix }
}

/**
 * Shifts mentions after an edit and drops any mention the edit touched. A partial edit breaks the
 * token: the label no longer names the entity, so keeping the id would lie. Pure insertions exactly at
 * a mention's start or end leave it intact.
 */
export function shiftMentions(mentions: readonly Mention[], edit: TextEdit): Mention[] {
  const delta = edit.insertedEnd - edit.removedEnd
  const pureInsert = edit.removedEnd === edit.start
  return mentions.flatMap((m) => {
    const touched = pureInsert
      ? edit.start > m.start && edit.start < m.end
      : edit.start < m.end && edit.removedEnd > m.start
    if (touched) return []
    return edit.removedEnd <= m.start ? [{ ...m, start: m.start + delta, end: m.end + delta }] : [m]
  })
}

/** Applies a native text change to the value; returns the caret the edit implies. */
export function applyTextChange(
  value: MentionValue,
  nextText: string,
  caretHint?: number,
): { value: MentionValue; caret: number } {
  const edit = diffText(value.text, nextText, caretHint)
  return { value: { text: nextText, mentions: shiftMentions(value.mentions, edit) }, caret: edit.insertedEnd }
}

/** Replaces the query's token with `trigger + label` plus a trailing space and records the range. */
export function insertMention(
  value: MentionValue,
  query: MentionQuery,
  item: MentionItem,
): { value: MentionValue; caret: number } {
  const token = query.trigger + item.label
  const spacer = isSpace(value.text[query.end]) ? '' : ' '
  const text = value.text.slice(0, query.start) + token + spacer + value.text.slice(query.end)
  const edit = { start: query.start, removedEnd: query.end, insertedEnd: query.start + token.length + spacer.length }
  const mention: Mention = { start: query.start, end: query.start + token.length, ...item, trigger: query.trigger }
  const mentions = [...shiftMentions(value.mentions, edit), mention].sort((a, b) => a.start - b.start)
  return { value: { text, mentions }, caret: mention.end + 1 }
}

/** Keeps only mentions whose range matches the text exactly and does not overlap an earlier one. */
export function validateMentions(text: string, mentions: readonly Mention[] = []): Mention[] {
  let lastEnd = 0
  return [...mentions]
    .sort((a, b) => a.start - b.start)
    .filter((m) => {
      const ok =
        Number.isInteger(m.start) &&
        m.start >= lastEnd &&
        m.end <= text.length &&
        text.slice(m.start, m.end) === m.trigger + m.label &&
        m.end > m.start
      if (ok) lastEnd = m.end
      return ok
    })
}
components/ui/mention-input/index.ts
export * from './MentionInput'
export * from './mention-utils'

Dependencies

Registry items

Browse controls and interactions