Skip to content
AI Interfaces block

Ghost Text Completion

Copilot-style completion in a plain textarea: a transparent-caret field over a metric-matched mirror, Tab to accept, Escape that actually sticks, and the suggestion announced rather than left as invisible grey text.

206 lineslucide-reactAdded 13 Aug 2026
  • autocomplete
  • ghost text
  • completion
  • inline ai
  • textarea

What's included

  • components/ai-inline-suggestion.tsx
  • Needs lucide-react

Works with

  • React
  • Next.js
  • Tailwind CSS
  • TypeScript

npx hoverlab add ai-inline-suggestion

Or over MCP, from your editor's agent — no account needed.

License

Free to read, copy and install, for personal and non-commercial projects. Shipping it in client work or a paid product needs Pro ($79 once). The source lands in your repo and stops being ours — no attribution, nothing to upgrade.

Was this useful?

Start a page with this section — add more, order them, and leave with the page source.

Preview

Keep typing — completions appear after a short pause.

Rendered live in your current theme — this is the same component whose source is below, not a screenshot of it.

Source

components/ai-inline-suggestion.tsx
/**
 * <AiInlineSuggestion> — ghost-text completion inside a real field: the
 * model proposes the rest of the sentence, Tab accepts, Escape refuses.
 *
 * Copilot-style completion done as a plain textarea rather than an editor
 * framework. The technique is a two-layer overlay: a transparent-caret
 * textarea on top of a mirror div that renders the typed text plus the
 * suggestion in muted grey. Both layers must share every text metric —
 * font, size, leading, padding, wrapping — or the ghost drifts out of
 * alignment with the caret by a few pixels per line, which is worse than
 * not having it. That is why the metrics live in one constant used by both.
 *
 * Interaction rules that make it tolerable rather than infuriating:
 *
 *  - Tab accepts, Escape dismisses, and any other keystroke invalidates the
 *    suggestion. A completion that survives the next character is one the
 *    user has to fight.
 *  - A dismissed suggestion does not come back for the same prefix. Without
 *    that, Escape means "show it again in 400ms".
 *  - Nothing is proposed mid-word or while the field is empty.
 *  - The hint is announced through `role="status"` — a sighted user sees
 *    grey text, and everyone else is told a completion is available and how
 *    to take it. Ghost text with no announcement is invisible to a screen
 *    reader, which is the accessibility failure this pattern is known for.
 */

'use client'

import * as React from 'react'
import { CornerDownLeft, Sparkles } from 'lucide-react'

export interface SuggestionRule {
  /** Lowercased prefix the draft must end with. */
  when: string
  /** The completion offered, appended verbatim. */
  then: string
}

export interface AiInlineSuggestionProps {
  label?: string
  placeholder?: string
  /** Starting draft, so the block demonstrates itself. */
  defaultValue?: string
  rules?: SuggestionRule[]
  /** Milliseconds of quiet before a completion is offered. */
  delay?: number
  className?: string
}

/**
 * Shared text metrics.
 *
 * The mirror and the textarea must agree on every one of these or the ghost
 * text stops lining up with the caret.
 */
const METRICS =
  'w-full whitespace-pre-wrap break-words px-3.5 py-3 text-sm leading-relaxed font-sans'

const DEFAULT_RULES: SuggestionRule[] = [
  { when: 'thanks for flagging', then: ' this — I have raised it with the team and will follow up by Friday.' },
  { when: 'the renewal', then: ' conversation should start ninety days out, not thirty.' },
  { when: 'i wanted to', then: ' follow up on the pricing question from our call last week.' },
  { when: 'hi', then: ' there — quick update on where the migration stands.' },
]

export function AiInlineSuggestion({
  label = 'Reply',
  placeholder = 'Start typing — a completion appears after a moment…',
  defaultValue = 'Thanks for flagging',
  rules = DEFAULT_RULES,
  delay = 400,
  className = '',
}: AiInlineSuggestionProps) {
  const [value, setValue] = React.useState(defaultValue)
  const [suggestion, setSuggestion] = React.useState('')
  /** Prefixes the user has already refused, so Escape sticks. */
  const [refused, setRefused] = React.useState<string[]>([])
  const fieldRef = React.useRef<HTMLTextAreaElement>(null)
  const fieldId = React.useId()

  React.useEffect(() => {
    setSuggestion('')

    const draft = value.trimEnd()
    // Nothing mid-word, nothing on an empty field, nothing already refused.
    if (draft.length === 0 || draft !== value) return
    if (refused.includes(draft.toLowerCase())) return

    const id = window.setTimeout(() => {
      const lower = draft.toLowerCase()
      const rule = rules.find((r) => lower.endsWith(r.when))
      if (rule) setSuggestion(rule.then)
    }, delay)

    return () => window.clearTimeout(id)
  }, [value, rules, delay, refused])

  function accept() {
    if (!suggestion) return
    const next = value + suggestion
    setValue(next)
    setSuggestion('')
    requestAnimationFrame(() => {
      const el = fieldRef.current
      if (!el) return
      el.focus()
      el.setSelectionRange(next.length, next.length)
    })
  }

  function onKeyDown(event: React.KeyboardEvent<HTMLTextAreaElement>) {
    if (!suggestion) return

    if (event.key === 'Tab') {
      event.preventDefault()
      accept()
      return
    }

    if (event.key === 'Escape') {
      event.preventDefault()
      setRefused((list) => [...list, value.trimEnd().toLowerCase()])
      setSuggestion('')
    }
  }

  return (
    <div className={`mx-auto w-full max-w-xl p-6 ${className}`}>
      <label htmlFor={fieldId} className="mb-2 block text-sm font-medium">
        {label}
      </label>

      <div className="relative rounded-2xl border border-border/60 bg-card focus-within:ring-2 focus-within:ring-ring">
        {/*
          The mirror. `aria-hidden` because its text duplicates the field's
          value, and a screen reader must not read the draft twice.
          `pointer-events-none` so clicks reach the textarea beneath.
        */}
        <div
          aria-hidden
          className={`pointer-events-none absolute inset-0 ${METRICS} text-transparent`}
        >
          {value}
          {suggestion ? <span className="text-muted-foreground/60">{suggestion}</span> : null}
        </div>

        <textarea
          ref={fieldRef}
          id={fieldId}
          rows={4}
          value={value}
          onChange={(e) => setValue(e.target.value)}
          onKeyDown={onKeyDown}
          placeholder={placeholder}
          // Autocomplete off: a browser dropdown over ghost text is two
          // competing suggestions in the same place.
          autoComplete="off"
          spellCheck
          aria-describedby={suggestion ? `${fieldId}-hint` : undefined}
          className={`relative resize-none border border-transparent bg-transparent outline-none placeholder:text-muted-foreground ${METRICS}`}
        />
      </div>

      {/* The announcement ghost text otherwise lacks entirely. */}
      <p
        id={`${fieldId}-hint`}
        role="status"
        className="mt-2 flex min-h-5 items-center gap-2 text-xs text-muted-foreground"
      >
        {suggestion ? (
          <>
            <Sparkles aria-hidden className="h-3.5 w-3.5 shrink-0 text-primary" />
            <span>
              Suggestion available — press{' '}
              <kbd className="rounded border border-border/60 bg-muted px-1 py-0.5 font-mono">
                Tab
              </kbd>{' '}
              to accept,{' '}
              <kbd className="rounded border border-border/60 bg-muted px-1 py-0.5 font-mono">
                Esc
              </kbd>{' '}
              to dismiss
            </span>
          </>
        ) : (
          <>
            <CornerDownLeft aria-hidden className="h-3.5 w-3.5 shrink-0" />
            Keep typing — completions appear after a short pause.
          </>
        )}
      </p>

      {suggestion ? (
        <button
          type="button"
          onClick={accept}
          className="mt-2 inline-flex items-center gap-1.5 rounded-lg border border-border/60 px-2.5 py-1.5 text-xs font-medium transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
        >
          <Sparkles aria-hidden className="h-3.5 w-3.5" />
          Accept suggestion
        </button>
      ) : null}
    </div>
  )
}

Before you paste

  • Styling is Tailwind utility classes on semantic tokens (bg-card, text-muted-foreground) — it inherits your theme instead of overriding it.
  • Install: npm i lucide-react
  • Every prop has a default, so it renders standalone before you wire it up.

Where it goes

Drop it at components/ai-inline-suggestion.tsx and import it where you need the section:

import { AiInlineSuggestion } from '@/components/ai-inline-suggestion'

Customize

4 of this block’s props are simple enough to drive from here. Change them and the block below re-renders — it is the same component whose source is above, not a mock of it. Everything else it accepts is in the table underneath.

Props

Read out of the component’s own type and signature, so this cannot drift from the source below. Every prop has a default — the component renders standalone before you pass it anything.

PropTypeDefault
labelstring'Reply'
placeholderstring'Start typing — a completion appears after a …
defaultValueStarting draft, so the block demonstrates itself.string'Thanks for flagging'
rulesSuggestionRule[]DEFAULT_RULES
delayMilliseconds of quiet before a completion is offered.number400
classNamestring''

Not using React?

The same block rendered once to markup, wrapped as a file your framework compiles. Tailwind classes are framework-agnostic, so the design transfers intact — the behaviour does not.

This block is interactive. The markup below is its initial state with the event handlers stripped — you will need to re-wire the behaviour in your framework.

ai-inline-suggestion.html
<!--
  Ghost Text Completion — markup from the Hoverlab catalog.

  This is the block rendered once to HTML and wrapped as a component
  file. It is not a port of the React source: the Tailwind classes carry
  the design, which is the part that took the work, and they are the same
  in every framework.

  This block is interactive in React and the handlers are NOT here.
  Buttons, toggles and menus render in their initial state and do
  nothing until you wire them up.
-->
<div class="mx-auto w-full max-w-xl p-6 ">
  <label for="_R_0_" class="mb-2 block text-sm font-medium">Reply</label>
  <div class="relative rounded-2xl border border-border/60 bg-card focus-within:ring-2 focus-within:ring-ring">
    <div aria-hidden="true" class="pointer-events-none absolute inset-0 w-full whitespace-pre-wrap break-words px-3.5 py-3 text-sm leading-relaxed font-sans text-transparent">Thanks for flagging</div>
    <textarea id="_R_0_" rows="4" placeholder="Start typing — a completion appears after a moment…" autoComplete="off" spellCheck="true" class="relative resize-none border border-transparent bg-transparent outline-none placeholder:text-muted-foreground w-full whitespace-pre-wrap break-words px-3.5 py-3 text-sm leading-relaxed font-sans">Thanks for flagging</textarea>
  </div>
  <p id="_R_0_-hint" role="status" class="mt-2 flex min-h-5 items-center gap-2 text-xs text-muted-foreground"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-corner-down-left h-3.5 w-3.5 shrink-0" aria-hidden="true"><path d="M20 4v7a4 4 0 0 1-4 4H4"></path><path d="m9 10-5 5 5 5"></path></svg>Keep typing — completions appear after a short pause.</p>
</div>
  • This is rendered HTML, not a translation of the React source. The Tailwind classes carry the design and work in any framework.
  • It is one frame: the component in its initial state, with no props applied beyond the defaults.
  • This block is interactive in React — toggles, menus or form state. None of that survives here; the markup is the closed/default state and the handlers are gone. Re-wire them in your own framework.
  • Requires Tailwind, and the design tokens the classes reference (bg-card, text-muted-foreground, and so on). The template ZIPs ship a globals.css that defines them.

What each framework gets across the whole catalog — effects convert properly; this rung is markup.

For AI

The component, its props, the design tokens it expects and the command that installs it — as one prompt. Paste it into Claude, Cursor, v0 or ChatGPT and what they build around it will match the rest of the catalog instead of inventing its own system.

See the prompt

Used in these pages

Want the whole screen instead of this one section? Open a page and copy it entire.

5 more blocks in Inline AI Actions

All of them free to read, copy and install — no account, no locked tiles, no watermarked preview. The whole catalog is open, and so are the API and the CLI.

Browse Inline AI Actions

Shipping one commercially

Copying the code is free. Putting it in client work or a paid product is what Pro is for — the licence, not the access.

  • A commercial licence for everything in the catalog
  • Unlimited bundle exports, in Vue, Svelte and Tailwind
  • One payment — no subscription, nothing to renew
Pro — $79 once

More Inline AI Actions blocks

View category
Open the full page for this block

Selection Action Toolbar

Highlight a passage and hand it to the model. Positioned from the range rect relative to its container, raised by selectionchange so Shift-Arrow works, and every button prevents the mousedown that would collapse the selection.

Inline AI Actions251 lines1 dep
Open the full page for this block

Agent-Adjusted Inspector

The model edits real properties and every change is attributed and reversible — per-property provenance in words, per-property revert, and sliders whose aria-valuetext carries the unit.

Inline AI Actions381 lines1 dep
Open the full page for this block

Unprompted Insight Cards

Findings the agent surfaced on its own, paged one at a time, each stating its magnitude rather than its direction, dismissible, and carrying a sparkline that is also a sentence for anyone who cannot see it.

Inline AI Actions284 lines1 dep
Open the full page for this block

Editor Slash Menu

The "/" menu inside a document: focus never leaves the editor, every row names what it acts on, and Escape cleans up the trigger text it inserted instead of leaving you to backspace it.

Inline AI Actions343 lines1 dep
Open the full page for this block

Inline AI Action Menu

The actions offered on a selection, each saying whether it rewrites in place or opens a draft beside it.

Inline AI Actions151 linesNo deps