Mention input
A native message textarea with filtered @person and #channel suggestions inserted as readable text.
pnpm dlx shadcn@latest add @haze/mention-input---
import { cn } from "../../../lib/haze/utils";
interface Suggestion { id: string; label: string; kind: "person" | "channel" }
interface Props {
id: string;
name?: string;
label?: string;
placeholder?: string;
value?: string;
suggestions?: Suggestion[];
rows?: number;
disabled?: boolean;
class?: string;
[key: string]: unknown;
}
const { id, name = id, label = "Message", placeholder = "Write a note. Try @Mira or #design.", value = "", suggestions = [{ id: "mira", label: "Mira Bell", kind: "person" }, { id: "noah", label: "Noah Vale", kind: "person" }, { id: "design", label: "design", kind: "channel" }, { id: "releases", label: "releases", kind: "channel" }], rows = 3, disabled, class: className, ...rest } = Astro.props;
---
<div data-haze-mention-input data-label={label} class={cn("relative grid min-w-0 gap-2", className)}>
<label id={`${id}-label`} for={id} class="text-[0.8125rem]/5 font-medium">{label}</label>
<div data-mention-composite class="relative">
<textarea {...rest} id={id} name={name} rows={rows} disabled={disabled} placeholder={placeholder} data-mention-field aria-describedby={`${id}-hint`} class="block min-h-24 w-full min-w-0 resize-none rounded-lg border border-frame-input bg-field px-3 py-2.5 text-sm/6 tracking-[-0.01em] text-foreground transition-[border-color,background-color,box-shadow] duration-150 ease-snappy placeholder:text-muted-foreground hover:border-frame-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-50">{value}</textarea>
<div id={`${id}-suggestions`} data-mention-list role="listbox" aria-label="Mention suggestions" class="pointer-events-none absolute top-full z-20 mt-1 hidden max-h-48 w-full min-w-0 -translate-y-1 gap-0.5 overflow-y-auto rounded-lg border border-border bg-popover p-1 text-popover-foreground opacity-0 shadow-float transition-[opacity,translate,display] transition-discrete duration-150 ease-snappy motion-reduce:transition-none data-[open]:pointer-events-auto data-[open]:grid data-[open]:translate-y-0 data-[open]:opacity-100 starting:data-[open]:-translate-y-1 starting:data-[open]:opacity-0">
{suggestions.map((item, index) => <button type="button" id={`${id}-option-${index}`} role="option" aria-selected="false" tabindex="-1" data-mention-option data-key={item.id} data-label={item.label} data-kind={item.kind} class="flex min-h-10 min-w-0 cursor-pointer items-center gap-2 rounded-sm px-3 text-start text-[0.8125rem]/5 transition-colors duration-75 hover:bg-accent aria-selected:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring [&[hidden]]:hidden"><span aria-hidden="true" class="grid size-6 shrink-0 place-items-center rounded-md bg-muted text-[0.6875rem]/4 font-medium text-muted-foreground">{item.kind === "person" ? "@" : "#"}</span><span class="truncate">{item.label}</span></button>)}
</div>
</div>
<p id={`${id}-hint`} class="text-[0.8125rem]/5 text-muted-foreground">Mention a person with @ or a channel with #.</p>
<span data-mention-status role="status" class="sr-only"></span>
</div>
<script>
function initMentionInputs() {
document.querySelectorAll<HTMLElement>("[data-haze-mention-input]").forEach(root => {
if (root.hasAttribute("data-enhanced")) return;
const field = root.querySelector<HTMLTextAreaElement>("[data-mention-field]");
const composite = root.querySelector<HTMLElement>("[data-mention-composite]");
const list = root.querySelector<HTMLElement>("[data-mention-list]");
const status = root.querySelector<HTMLElement>("[data-mention-status]");
const options = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-mention-option]"));
if (!field || !composite || !list || !status) return;
let visible: HTMLButtonElement[] = [];
let active = 0;
let start = 0;
let end = 0;
let announced = "";
let timer = 0;
const announce = (text: string) => { clearTimeout(timer); timer = window.setTimeout(() => { if (text !== announced) { announced = text; status.textContent = text; } }, 400); };
const isOpen = () => list.hasAttribute("data-open");
const close = () => { list.removeAttribute("data-open"); field.setAttribute("aria-expanded", "false"); announced = ""; clearTimeout(timer); field.removeAttribute("aria-activedescendant"); };
const highlight = () => { options.forEach(option => option.setAttribute("aria-selected", String(option === visible[active]))); if (visible[active]) field.setAttribute("aria-activedescendant", visible[active]!.id); else field.removeAttribute("aria-activedescendant"); };
const update = () => {
const prefix = field.value.slice(0, field.selectionStart);
const match = prefix.match(/(?:^|\s)([@#])([\p{L}\p{N}_-]*)$/u);
if (!match || field.disabled || field.readOnly) { close(); return; }
start = prefix.length - match[2]!.length - 1;
end = field.selectionStart;
const kind = match[1] === "@" ? "person" : "channel";
const query = match[2]!.toLocaleLowerCase();
visible = options.filter(option => option.dataset.kind === kind && `${option.dataset.label} ${option.dataset.key}`.toLocaleLowerCase().includes(query));
options.forEach(option => { option.hidden = !visible.includes(option); });
active = 0;
list.toggleAttribute("data-open", visible.length > 0);
field.setAttribute("aria-expanded", String(isOpen()));
announce(visible.length ? `${visible.length} ${kind === "person" ? (visible.length === 1 ? "person" : "people") : (visible.length === 1 ? "channel" : "channels")} available. Use arrow keys and Enter to choose.` : "No matching mentions.");
highlight();
};
const choose = (option: HTMLButtonElement) => {
const token = `${option.dataset.kind === "person" ? "@" : "#"}${option.dataset.key} `;
field.setRangeText(token, start, end, "end");
field.dispatchEvent(new Event("input", { bubbles: true }));
close();
clearTimeout(timer); announced = ""; status.textContent = `${option.dataset.label} inserted.`;
field.focus();
};
field.addEventListener("input", update);
field.addEventListener("click", update);
field.addEventListener("keyup", event => { if (["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) update(); });
field.addEventListener("keydown", event => {
if (!isOpen() || event.isComposing) return;
if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); active = (active + (event.key === "ArrowDown" ? 1 : visible.length - 1)) % visible.length; highlight(); visible[active]?.scrollIntoView({ block: "nearest" }); }
else if (event.key === "Enter" && visible[active]) { event.preventDefault(); choose(visible[active]!); }
else if (event.key === "Escape") { event.preventDefault(); close(); }
else if (event.key === "Tab") close();
});
options.forEach(option => { option.addEventListener("mousedown", event => event.preventDefault()); option.addEventListener("click", () => choose(option)); });
root.addEventListener("focusout", () => queueMicrotask(() => { if (!root.contains(document.activeElement)) close(); }));
field.setAttribute("role", "combobox");
field.setAttribute("aria-expanded", "false");
field.setAttribute("aria-autocomplete", "list");
field.setAttribute("aria-controls", list.id);
root.setAttribute("data-enhanced", "");
});
}
initMentionInputs();
if (!document.documentElement.hasAttribute("data-haze-mention-input-listener")) {
document.documentElement.setAttribute("data-haze-mention-input-listener", "");
document.addEventListener("astro:page-load", initMentionInputs);
}
</script>When to use
- A team note should help people find the correct person or channel
- Mention values can remain ordinary text in the submitted message
When not to use
- Use textarea when a message has no mention directory
- Use tags-input when the whole value is a collection of removable tags
Installation
Add the Haze registry to components.json once, then install Mention input with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/mention-inputnpx shadcn@latest add @haze/mention-inputyarn dlx shadcn@latest add @haze/mention-inputbunx --bun shadcn@latest add @haze/mention-inputFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique caller-supplied prefix for this component and its related elements. |
| name | string | id | Form submission name. |
| label | string | "Message" | Visible label for the message. |
| placeholder | string | "Write a note. Try @Mira or #design." | Example hint inside the textarea. |
| value | string | "" | Initial plain message text. |
| suggestions | { id: string; label: string; kind: "person" | "channel" }[] | Two people and two channels | Values inserted after @ or # and their display labels. |
| rows | number | 3 | Initial native textarea rows. |
| disabled | boolean | – | Disables the native control and its enhancement. |
| class | string | – | Additional classes for the component root. |
| ...attributes | native control attributes | – | Other attributes are forwarded to the real form control. |
Keyboard interactions
- @ or #
- Start filtering people or channel suggestions at the current caret.
- ArrowUp, ArrowDown, Enter
- Move through matching suggestions and insert the highlighted value.
- Escape, Tab
- Close suggestions without changing the current message.
Accessibility
- The textarea remains the only editing surface and submits readable mention text without a hidden rich-text model.
- The enhanced suggestion list announces counts, tracks the active option and leaves focus in the textarea while choosing.
- The textarea works as an ordinary message field when the enhancement is unavailable.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Mention input" with `npx shadcn@latest add @haze/mention-input`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import MentionInput from "@/components/haze/ui/mention-input.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/mention-input.md
Customize with real content
Adapt the Haze mention-input ui for our product. Replace the demo values of these props with our real content: id, name, label, placeholder, value, suggestions, rows, disabled, class, ...attributes. Keep the layout, the heading level rules and these accessibility details: The textarea remains the only editing surface and submits readable mention text without a hidden rich-text model. The enhanced suggestion list announces counts, tracks the active option and leaves focus in the textarea while choosing. The textarea works as an ordinary message field when the enhancement is unavailable. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using mention-input, check it fits: use it when a team note should help people find the correct person or channel; mention values can remain ordinary text in the submitted message. Avoid it when use textarea when a message has no mention directory; use tags-input when the whole value is a collection of removable tags. Alternatives: @haze/textarea, @haze/tags-input, @haze/combobox.
Dependencies
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.