Inline Completion
SaveA text area that suggests how to finish what you are typing as ghost text after the caret, taken all at once with Tab, a word at a time, or up to a clicked word.
- Category
- AI elements
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Inline Completion preview
Suggestions appear as you type. Tab accepts a suggestion, Right Arrow accepts one word, Escape dismisses it.
Suggestions appear as you type. Tab accepts a suggestion, Right Arrow accepts one word, Escape dismisses it.
Tab accepts, Right Arrow takes one word, Escape dismisses.
Installation
npx @shakenui/cli add inline-completionReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add inline-completion --dry-runUsage
inline-completion-example.tsx
"use client";
import { useId } from "react";
import { InlineCompletion } from "@/components/shaken/agent/inline-completion";
// Stands in for a completion model: finishes known drafts, then falls back to short endings.
const drafts = [
"Hi Priya, thanks for flagging the duplicate invoices. We traced it to a retry in our billing webhook and refunded the extra charge to your card this morning. It should show up within 3 to 5 business days.",
"Fix duplicate charge when the billing webhook retries after a timeout",
"Add idempotency keys to invoice creation",
];
const endings: [RegExp, string][] = [
[/let me know$/i, " if anything else looks off."],
[/thanks for$/i, " your patience while we looked into this."],
[/\bwe will$/i, " follow up once the fix is deployed."],
[/sorry for$/i, " the trouble this caused."],
];
function suggest(text: string, { signal }: { signal: AbortSignal }): Promise<string | null> {
return new Promise((resolve) => {
const timer = setTimeout(() => {
const lower = text.toLowerCase();
const draft = drafts.find((item) => item.toLowerCase().startsWith(lower) && item.length > text.length);
if (draft) return resolve(draft.slice(text.length));
const ending = endings.find(([pattern]) => pattern.test(text.trimEnd()));
resolve(ending && !/\s$/.test(text) ? ending[1] : null);
}, 220);
signal.addEventListener("abort", () => clearTimeout(timer));
});
}
export default function InlineCompletionExample() {
const id = useId();
return (
<div className="grid w-full max-w-md gap-5">
<div className="grid gap-2">
<label htmlFor={`${id}-reply`} className="text-sm font-medium text-zinc-950 dark:text-white">
Reply to Priya Raman
</label>
<InlineCompletion id={`${id}-reply`} defaultValue="Hi Priya, thanks for flagging the duplicate invoices." getSuggestion={suggest} suggestOnMount />
</div>
<div className="grid gap-2">
<label htmlFor={`${id}-commit`} className="text-sm font-medium text-zinc-950 dark:text-white">
Commit message
</label>
<InlineCompletion id={`${id}-commit`} singleLine placeholder="Fix duplicate…" getSuggestion={suggest} />
<p className="text-xs text-zinc-500">Tab accepts, Right Arrow takes one word, Escape dismisses.</p>
</div>
</div>
);
}API
| Prop | Type | Default | Description |
|---|---|---|---|
| getSuggestion | (text, { signal }) => string | null | Promise<string | null> | — | Returns text that continues the input, sync or async. Called after typing pauses; signal aborts when the user types again. |
| defaultValue / value | string | — | The text. Pass value with onValueChange to control it. |
| onValueChange | (value: string) => void | — | Called on every change, including accepted suggestions. |
| delay | number | 350 | Pause after typing before asking for a suggestion, in milliseconds. |
| singleLine | boolean | false | One line with no wrapping; Enter does not add a new line. |
| suggestOnMount | boolean | false | Asks for a suggestion for the starting text when the field mounts. |
| showHint | boolean | true | Shows a small Tab key after the suggestion while focused. |
| onAccept | (text, how: "all" | "word" | "click") => void | — | Called when the user takes some or all of a suggestion. |
| containerClassName | string | — | Classes for the bordered field; className styles the text area. |
Accessibility
- It is a native textarea, so labels, IME input, spellcheck, and selection behave as usual; it is described by a hidden hint listing the keys.
- Tab accepts the suggestion only while one is showing at the end of the text; otherwise Tab moves focus as normal. Right Arrow at the end takes one word, Escape dismisses.
- Accepted text is inserted as a native edit, so Undo removes exactly what was accepted.
- A polite status region reads the suggestion and "Press Tab to accept" when one appears.
- Ghost text is never part of the value and never moves the caret; typing a matching character keeps the rest of the suggestion.
- With reduced motion the suggestion appears at once instead of writing itself in word by word.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/agent/inline-completion.tsxinline-completion- npm packages: noneReact and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/inline-completion/0.1.0.json.
agent/inline-completion.tsxShowHide
agent/inline-completion.tsx
"use client";
import {
type ChangeEvent,
type ComponentProps,
type KeyboardEvent,
type UIEvent,
useCallback,
useEffect,
useId,
useRef,
useState,
} from "react";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";
export type SuggestionResult = string | null | undefined;
export interface InlineCompletionProps
extends Omit<ComponentProps<"textarea">, "value" | "defaultValue" | "onChange" | "children"> {
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
/**
* Returns text that continues `text` (sync or async), or nothing. Called after the user pauses
* typing; `signal` aborts when they type again. Include a leading space when the suggestion starts a new word.
*/
getSuggestion: (text: string, options: { signal: AbortSignal }) => SuggestionResult | Promise<SuggestionResult>;
/** Pause after typing before asking for a suggestion, in milliseconds. @default 350 */
delay?: number;
/** One line: no wrapping, and Enter does not add a new line. */
singleLine?: boolean;
/** Asks for a suggestion for the starting text as soon as the field mounts. */
suggestOnMount?: boolean;
/** Shows a small Tab key after the suggestion while the field has focus. @default true */
showHint?: boolean;
/** Called when the user takes some or all of a suggestion. */
onAccept?: (text: string, how: "all" | "word" | "click") => void;
/** Classes for the bordered field around the text. `className` styles the text area itself. */
containerClassName?: string;
}
interface Suggestion {
/** Where the suggestion starts in the value. */
origin: number;
text: string;
/** Characters of the suggestion already typed or accepted. */
used: number;
}
interface Word {
/** Offset in the suggestion text. */
start: number;
end: number;
text: string;
}
/** Words of a suggestion, each with the whitespace in front of it. */
function words(text: string): Word[] {
const out: Word[] = [];
const pattern = /\s*\S+|\s+$/g;
let match: RegExpExecArray | null;
while ((match = pattern.exec(text))) out.push({ start: match.index, end: match.index + match[0].length, text: match[0] });
return out;
}
/**
* A text area that suggests how to finish what the user is typing, as grey ghost text after the
* caret. Tab takes all of it, Right Arrow takes the next word, a click on a ghost word takes the
* text up to it, and Escape dismisses it. Typing a matching character keeps the rest.
*/
export function InlineCompletion({
value: valueProp,
defaultValue = "",
onValueChange,
getSuggestion,
delay = 350,
singleLine = false,
suggestOnMount = false,
showHint = true,
onAccept,
containerClassName,
className,
onKeyDown,
onSelect,
onScroll,
onFocus,
onBlur,
disabled,
rows = 3,
"aria-describedby": describedBy,
...props
}: InlineCompletionProps) {
const id = useId();
const [inner, setInner] = useState(defaultValue);
const value = valueProp ?? inner;
const [suggestion, setSuggestion] = useState<Suggestion | null>(null);
const [atEnd, setAtEnd] = useState(true);
const [focused, setFocused] = useState(false);
const [touched, setTouched] = useState(false);
const [hovered, setHovered] = useState<number | null>(null);
const [announcement, setAnnouncement] = useState("");
const fieldRef = useRef<HTMLTextAreaElement>(null);
const mirrorRef = useRef<HTMLDivElement>(null);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const controller = useRef<AbortController | null>(null);
const valueRef = useRef(value);
valueRef.current = value;
// How the next accepted insertion should be reported to onAccept.
const accepting = useRef<"all" | "word" | "click" | null>(null);
const getRef = useRef(getSuggestion);
getRef.current = getSuggestion;
const request = useCallback(
(text: string, wait: number) => {
if (timer.current) clearTimeout(timer.current);
controller.current?.abort();
if (!text.trim()) return;
timer.current = setTimeout(async () => {
const abort = new AbortController();
controller.current = abort;
try {
const result = await getRef.current(text, { signal: abort.signal });
if (abort.signal.aborted || valueRef.current !== text || !result) return;
setSuggestion({ origin: text.length, text: result, used: 0 });
setAnnouncement(`Suggestion: ${result.trim()}. Press Tab to accept.`);
} catch {
// A failed or aborted request just means no suggestion.
}
}, wait);
},
[],
);
useEffect(() => {
if (suggestOnMount) request(valueRef.current, 0);
return () => {
if (timer.current) clearTimeout(timer.current);
controller.current?.abort();
};
}, [suggestOnMount, request]);
const remaining = suggestion ? suggestion.text.slice(suggestion.used) : "";
const live = Boolean(suggestion && remaining && suggestion.origin + suggestion.used === value.length);
const visible = live && atEnd && (focused || !touched) && !disabled;
function setValue(next: string) {
if (valueProp === undefined) setInner(next);
onValueChange?.(next);
}
function dismiss() {
setSuggestion(null);
setHovered(null);
setAnnouncement("");
}
function handleChange(event: ChangeEvent<HTMLTextAreaElement>) {
const next = event.target.value;
const previous = value;
setValue(next);
syncCaret(event.target);
// Typing (or accepting) text that matches the suggestion keeps the rest of it.
if (suggestion && next.startsWith(previous) && next.length > previous.length) {
const typed = next.slice(previous.length);
const offset = previous.length - suggestion.origin;
if (offset === suggestion.used && suggestion.text.startsWith(typed, suggestion.used)) {
const used = suggestion.used + typed.length;
if (accepting.current) onAccept?.(typed, accepting.current);
accepting.current = null;
if (used >= suggestion.text.length) {
dismiss();
request(next, delay);
} else {
setSuggestion({ ...suggestion, used });
}
return;
}
}
accepting.current = null;
dismiss();
request(next, delay);
}
function syncCaret(field: HTMLTextAreaElement) {
setAtEnd(field.selectionStart === field.value.length && field.selectionEnd === field.value.length);
}
/** Inserts accepted text at the end as a normal edit, so it can be undone. */
function insert(text: string, how: "all" | "word" | "click") {
const field = fieldRef.current;
if (!field || !text) return;
field.focus();
field.setSelectionRange(field.value.length, field.value.length);
accepting.current = how;
const inserted = typeof document.execCommand === "function" && document.execCommand("insertText", false, text);
if (!inserted) {
field.setRangeText(text, field.value.length, field.value.length, "end");
field.dispatchEvent(new Event("input", { bubbles: true }));
}
setHovered(null);
}
function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
onKeyDown?.(event);
if (event.defaultPrevented) return;
if (singleLine && event.key === "Enter") {
event.preventDefault();
return;
}
if (!visible || event.metaKey || event.ctrlKey || event.altKey) return;
if (event.key === "Tab" && !event.shiftKey) {
event.preventDefault();
insert(remaining, "all");
} else if (event.key === "ArrowRight" && !event.shiftKey) {
const next = /^\s*\S+/.exec(remaining);
if (!next) return;
event.preventDefault();
insert(next[0], "word");
} else if (event.key === "Escape") {
event.preventDefault();
dismiss();
setAnnouncement("Suggestion dismissed.");
}
}
function handleScroll(event: UIEvent<HTMLTextAreaElement>) {
onScroll?.(event);
const mirror = mirrorRef.current;
if (!mirror) return;
mirror.scrollTop = event.currentTarget.scrollTop;
mirror.scrollLeft = event.currentTarget.scrollLeft;
}
// Keep the mirror scrolled with the field when text is added at the end.
useEffect(() => {
const field = fieldRef.current;
const mirror = mirrorRef.current;
if (!field || !mirror) return;
mirror.scrollTop = field.scrollTop;
mirror.scrollLeft = field.scrollLeft;
});
const ghostWords = suggestion ? words(suggestion.text).filter((word) => word.end > suggestion.used) : [];
const metrics = cx(
"px-3 py-2 text-sm leading-6 [scrollbar-gutter:stable]",
singleLine ? "whitespace-pre" : "whitespace-pre-wrap break-words",
);
return (
<div
data-disabled={disabled || undefined}
className={cx(
"relative w-full rounded-lg border border-zinc-950/15 bg-white text-zinc-950 shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
"transition-[border-color,box-shadow] duration-150 ease-out motion-reduce:transition-none",
"hover:border-zinc-950/25 focus-within:border-zinc-950/30 focus-within:shadow-[0_0_0_3px_rgb(14_165_233/0.16)]",
"dark:border-white/15 dark:bg-black dark:text-white dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)] dark:hover:border-white/25 dark:focus-within:border-white/30 dark:focus-within:shadow-[0_0_0_3px_rgb(56_189_248/0.18)]",
"data-[disabled]:pointer-events-none data-[disabled]:opacity-60",
containerClassName,
)}
>
<textarea
ref={fieldRef}
value={value}
disabled={disabled}
rows={singleLine ? 1 : rows}
aria-describedby={cx(describedBy, `${id}-help`)}
onChange={handleChange}
onKeyDown={handleKeyDown}
onScroll={handleScroll}
onSelect={(event) => {
onSelect?.(event);
syncCaret(event.currentTarget);
}}
onFocus={(event) => {
onFocus?.(event);
setFocused(true);
setTouched(true);
syncCaret(event.currentTarget);
}}
onBlur={(event) => {
onBlur?.(event);
setFocused(false);
setHovered(null);
}}
{...props}
className={cx(
"absolute inset-0 block size-full resize-none bg-transparent text-zinc-950 placeholder:text-zinc-500 focus:outline-none dark:text-white",
singleLine ? "overflow-x-auto overflow-y-hidden [scrollbar-width:none]" : "overflow-y-auto",
metrics,
className,
)}
/>
{/*
A transparent copy of the text in the same box, so the ghost words land right after the caret.
It sits in the flow and sizes the field, so a long suggestion grows the field instead of hiding.
*/}
<div
ref={mirrorRef}
aria-hidden="true"
style={singleLine ? undefined : { minHeight: `calc(${rows} * 1.5rem + 1rem)` }}
className={cx(
"pointer-events-none relative overflow-hidden",
singleLine ? "h-10 [scrollbar-width:none]" : "max-h-60",
metrics,
)}
>
<span className="text-transparent">{value}</span>
{visible
? ghostWords.map((word, index) => {
const shown = word.start < suggestion!.used ? word.text.slice(suggestion!.used - word.start) : word.text;
const lit = hovered !== null && index <= hovered;
return (
<span
key={suggestion!.origin + word.start}
onMouseDown={(event) => event.preventDefault()}
onMouseEnter={() => setHovered(index)}
onMouseLeave={() => setHovered((current) => (current === index ? null : current))}
onClick={() => insert(suggestion!.text.slice(suggestion!.used, word.end), "click")}
style={{ transitionDelay: word.start < suggestion!.used ? undefined : `${Math.min(index * 40, 600)}ms` }}
className={cx(
"pointer-events-auto cursor-pointer",
"transition-[opacity,filter,color] duration-300 starting:opacity-0 starting:blur-[3px] motion-reduce:transition-none",
ease,
lit ? "text-zinc-700 dark:text-zinc-300" : "text-zinc-500 dark:text-zinc-500",
)}
>
{shown}
</span>
);
})
: null}
{visible && showHint && focused ? (
<kbd
className={cx(
"ml-1.5 inline-flex h-4 translate-y-[-1px] items-center rounded-[4px] border border-b-[1.5px] px-1 align-middle font-sans text-[10px] leading-none font-medium",
"border-zinc-950/12 text-zinc-500 dark:border-white/15 dark:text-zinc-500",
`transition-opacity duration-300 ${ease} starting:opacity-0 motion-reduce:transition-none`,
)}
>
Tab
</kbd>
) : null}
{/* Keeps a trailing new line from collapsing, so the caret line has height. */}
{"\u200b"}
</div>
<span id={`${id}-help`} className="sr-only">
Suggestions appear as you type. Tab accepts a suggestion, Right Arrow accepts one word, Escape dismisses it.
</span>
<span role="status" className="sr-only">
{visible || announcement.startsWith("Suggestion dismissed") ? announcement : ""}
</span>
</div>
);
}