The client loved the prototype. They want to move the launch up by a week.
Message Rails Components
Messages lay out a single entry in a conversation: the bubble, its alignment, and the avatar, sender, status and actions around it. Use them for chat, support inboxes, comment threads and AI assistants.
Installation
Most examples are plain HTML and Tailwind CSS and need no JavaScript. Add the Stimulus controller only for the interactive ones: reactions and actions, the feedback buttons on the AI assistant message and the conversation thread. Save it as app/javascript/controllers/message_controller.js.
import { Controller } from "@hotwired/stimulus";
// Message controller
//
// Most message layouts are plain HTML and need no JavaScript. Add this controller
// when you want any of these behaviors:
//
// 1. Reactions Toggle an existing pill or add a new one (message#react).
// 2. Actions A WhatsApp-style menu: hover toolbar on desktop, press and hold
// on touch screens, Shift+F10 / the context menu key on keyboards.
// Reactions, Reply, Copy and your own actions (message#act).
// 3. Toggles Pressed-state buttons such as thumbs up / down (message#toggle).
// 4. Thread A scrollable list that never moves the reader against their intent:
// follows new and streamed messages only while you are at the bottom,
// keeps your place otherwise, anchors new turns near the top, keeps the
// typing indicator last and animates messages appended by Turbo Streams.
// 5. Composer Grows as you type, Enter to send, reply preview, then either
// appends the message in the browser (optimistic) or lets the form
// submit to Rails.
//
// Markup conventions:
// data-message-target="item" One message row. Optional data-message-id and
// data-message-author are passed to events and replies.
// data-message-outgoing On an item sent by the current user.
// data-message-target="bubble" The bubble inside an item: press and hold opens the menu.
// data-message-slot="text" The message text inside a bubble (used by Copy and Reply).
//
// Every action dispatches an event (message:react, message:reply, message:sent…) so you
// can persist it with fetch or a form submit. Templates keep all markup in your views.
const BUBBLE = '[data-message-target~="bubble"]';
const ITEM = '[data-message-target~="item"]';
const EASE_OUT = "cubic-bezier(0.23, 1, 0.32, 1)";
export default class extends Controller {
static targets = [
"list", // Scrollable element that holds the messages
"jump", // Button shown while scrolled away from the bottom (hidden). Gets data-unread when messages arrive
"typing", // Typing indicator, kept as the last child of the list (hidden)
"item", // One message row
"bubble", // The bubble of a message row
"reactions", // Container that holds the reaction pills of a message
"reactionTemplate", // <template> for a new reaction pill. Slots: emoji, count
"menu", // popover="auto" element with the reactions and actions menu, shared by every message
"menuPanel", // Positioned wrapper inside the menu
"menuPreview", // Holds the lifted bubble (press and hold) or a spacer the size of the bubble (More)
"input", // Composer <textarea>
"submit", // Send button (disabled while the input is empty)
"outgoingTemplate", // <template> for a message sent by the current user. Slots: text, time, status, quote
"replyPreview", // "Replying to…" bar above the composer (hidden). Slots: reply-author, reply-text
"replyInput", // Hidden field that receives the id of the message being replied to
];
static values = {
maxInputHeight: { type: Number, default: 144 }, // px the composer can grow to
optimistic: { type: Boolean, default: true }, // true: append in the browser. false: submit the form
sendOnTouchEnter: { type: Boolean, default: false }, // Enter sends on touch keyboards too
longPressDelay: { type: Number, default: 450 }, // ms to press and hold a bubble
stickThreshold: { type: Number, default: 96 }, // px from the bottom that still counts as "at the bottom"
anchorPeek: { type: Number, default: 48 }, // px of the previous message kept in view above an anchored turn
copiedLabel: { type: String, default: "Message copied" }, // Announced to screen readers after Copy
};
initialize() {
this.reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
this.coarsePointer = window.matchMedia("(pointer: coarse)");
this.pinned = true;
this.replyTo = null;
this.onPointerDown = this.onPointerDown.bind(this);
this.onPointerMove = this.onPointerMove.bind(this);
this.cancelPress = this.cancelPress.bind(this);
this.onContextMenu = this.onContextMenu.bind(this);
this.onKeydown = this.onKeydown.bind(this);
this.onScroll = this.onScroll.bind(this);
this.onSelectionChange = this.onSelectionChange.bind(this);
this.onListFocusIn = this.onListFocusIn.bind(this);
this.onListFocusOut = this.onListFocusOut.bind(this);
this.onMenuClick = this.onMenuClick.bind(this);
this.onMenuKeydown = this.onMenuKeydown.bind(this);
this.onMenuBeforeToggle = this.onMenuBeforeToggle.bind(this);
this.onMenuToggle = this.onMenuToggle.bind(this);
this.onMenuScroll = this.onMenuScroll.bind(this);
this.suppressClick = this.suppressClick.bind(this);
this.closeMenu = this.closeMenu.bind(this);
}
connect() {
this.element.addEventListener("pointerdown", this.onPointerDown);
this.element.addEventListener("contextmenu", this.onContextMenu);
this.element.addEventListener("keydown", this.onKeydown);
if (this.hasInputTarget) {
// Touch keyboards insert a new line on Enter, like WhatsApp and iMessage.
if (this.enterInsertsNewLine && this.inputTarget.enterKeyHint === "send") this.inputTarget.enterKeyHint = "enter";
this.resize();
}
}
disconnect() {
this.element.removeEventListener("pointerdown", this.onPointerDown);
this.element.removeEventListener("contextmenu", this.onContextMenu);
this.element.removeEventListener("keydown", this.onKeydown);
this.cancelPress();
this.closeMenu();
if (this.hasTypingTarget) this.typingTarget.hidden = true;
}
// ---------------------------------------------------------------------------
// Thread: never move the reader against their intent
// ---------------------------------------------------------------------------
//
// - Follows new and growing messages (Turbo Stream appends, streamed AI replies) only
// while the reader is at the bottom and not selecting text or using the keyboard.
// - Otherwise keeps the reader's place when content changes above or inside the view
// (older messages prepended, images loading, a message re-rendered), in every browser.
// - A message with data-message-anchor (e.g. the user's prompt in an AI chat) scrolls
// near the top with a peek of the previous message, and the reply grows into the screen.
// - Opens at an element with data-message-start (e.g. the unread marker), else at the bottom.
listTargetConnected(list) {
// We keep the reader's place ourselves, the same way in every browser.
list.style.overflowAnchor = "none";
this.basePadding = parseFloat(getComputedStyle(list).paddingBottom) || 0;
// Anything added to the list (Turbo Streams, the composer, your own JS) goes through
// listChanged, so streamed messages behave exactly like local ones.
this.listObserver = new MutationObserver((records) => this.listChanged(records));
this.listObserver.observe(list, { childList: true });
// The list box (composer grows, keyboard opens) and every row (streamed text, images,
// code blocks rendering) can change size.
this.sizeObserver = new ResizeObserver(() => this.contentResized());
this.sizeObserver.observe(list);
Array.from(list.children).forEach((child) => this.sizeObserver.observe(child));
list.addEventListener("scroll", this.onScroll, { passive: true });
list.addEventListener("focusin", this.onListFocusIn);
list.addEventListener("focusout", this.onListFocusOut);
document.addEventListener("selectionchange", this.onSelectionChange);
this.openAtStart(list);
}
listTargetDisconnected(list) {
this.listObserver?.disconnect();
this.sizeObserver?.disconnect();
list.removeEventListener("scroll", this.onScroll);
list.removeEventListener("focusin", this.onListFocusIn);
list.removeEventListener("focusout", this.onListFocusOut);
document.removeEventListener("selectionchange", this.onSelectionChange);
clearTimeout(this.rememberTimer);
}
openAtStart(list) {
const start = list.querySelector("[data-message-start]");
if (!start) {
this.scrollToBottom({ smooth: false });
return;
}
list.scrollTop = this.offsetInList(start) - this.anchorPeekValue;
this.updatePinned();
this.rememberPosition();
this.toggleJump(!this.pinned);
}
listChanged(records) {
const typing = this.hasTypingTarget ? this.typingTarget : null;
const added = [];
records.forEach((record) => {
record.removedNodes.forEach((node) => node.nodeType === Node.ELEMENT_NODE && this.sizeObserver?.unobserve(node));
record.addedNodes.forEach((node) => {
if (node.nodeType !== Node.ELEMENT_NODE || node.parentElement !== this.listTarget) return;
this.sizeObserver?.observe(node);
// A node removed and added in the same record is a replace (an edit or a streamed
// update), not a new message.
if (record.removedNodes.length === 0 && node !== typing) added.push(node);
});
});
if (added.length === 0) {
this.contentResized();
return;
}
this.keepTypingLast();
let follow = this.following;
let anchor = null;
let unseen = false;
added.filter((node) => this.isLast(node)).forEach((node) => {
const outgoing = node.matches("[data-message-outgoing]");
this.enter(node, outgoing ? "end" : "start");
if (node.matches("[data-message-anchor]")) anchor = node;
if (outgoing) {
follow = true; // Always show the message you just sent.
} else {
this.hideTyping();
unseen = true;
this.dispatch("received", { detail: { element: node, id: node.dataset.messageId } });
}
});
if (anchor) {
this.anchorTo(anchor);
} else if (follow) {
this.scrollToBottom();
} else {
// Older messages prepended above: stay on what you were reading (unless our own scroll is still landing).
if (performance.now() >= this.autoScrollUntil) this.restorePosition();
if (unseen) this.toggleJump(true, { unread: true });
}
}
// Public: show or hide the typing indicator, e.g. from an Action Cable subscription.
showTyping() {
if (!this.hasTypingTarget || !this.typingTarget.hidden) return;
this.keepTypingLast();
this.typingTarget.hidden = false;
this.enter(this.typingTarget, "start");
if (this.following) this.scrollToBottom();
}
hideTyping() {
if (this.hasTypingTarget) this.typingTarget.hidden = true;
}
// data-action="message#jumpToBottom" on the jump button
jumpToBottom() {
this.anchoredTurn = null;
this.scrollToBottom();
this.toggleJump(false);
}
// Public: scrolls a message near the top of the thread, keeping a peek of the one before.
anchorTo(element) {
if (!this.hasListTarget) return;
this.anchoredTurn = element;
this.pinned = false;
// Where the reader will be once the scroll lands, so a reply arriving mid-scroll keeps it.
this.position = { row: element, offset: this.anchorPeekValue };
this.updateSpacer();
this.scrollList(this.offsetInList(element) - this.anchorPeekValue);
}
scrollToBottom({ smooth = true } = {}) {
if (!this.hasListTarget) return;
this.pinned = true;
this.scrollList(this.listTarget.scrollHeight, { smooth });
}
scrollList(top, { smooth = true } = {}) {
const list = this.listTarget;
const animate = smooth && !this.reducedMotion.matches;
// Smooth scrolling fires scroll events on the way; they are not the reader scrolling.
this.autoScrollUntil = performance.now() + (animate ? 600 : 50);
list.scrollTo({ top, behavior: animate ? "smooth" : "auto" });
clearTimeout(this.rememberTimer);
this.rememberTimer = setTimeout(() => this.rememberPosition(), animate ? 650 : 60);
}
onScroll() {
if (performance.now() < this.autoScrollUntil) return;
this.updatePinned();
if (this.pinned) this.anchoredTurn = null;
this.rememberPosition();
this.toggleJump(!this.pinned, { unread: this.jumpUnread });
}
// Something changed size: a streamed reply grew, an image loaded, the composer grew.
contentResized() {
if (!this.hasListTarget) return;
if (this.anchoredTurn) this.updateSpacer();
if (performance.now() < this.autoScrollUntil) return; // let our own scroll finish
if (this.following) {
this.scrollToBottom({ smooth: false });
} else {
this.restorePosition();
this.toggleJump(!this.atBottom(), { unread: this.jumpUnread });
}
}
// Not selecting text, not using the keyboard in the thread, at the bottom, no anchored turn.
get following() {
return this.pinned && !this.anchoredTurn && !this.selecting && !this.keyboardInside;
}
updatePinned() {
this.pinned = this.atBottom();
}
atBottom() {
const list = this.listTarget;
return list.scrollHeight - list.scrollTop - list.clientHeight <= this.stickThresholdValue;
}
// The first row in view and where it sits, so it can be put back after layout changes.
rememberPosition() {
if (!this.hasListTarget) return;
const list = this.listTarget;
const top = list.getBoundingClientRect().top;
const row = Array.from(list.children).find((child) => child.getBoundingClientRect().bottom > top && child.getClientRects().length > 0);
this.position = row ? { row, offset: row.getBoundingClientRect().top - top } : null;
}
restorePosition() {
const { row, offset } = this.position || {};
if (!row?.isConnected) return this.rememberPosition();
const delta = row.getBoundingClientRect().top - this.listTarget.getBoundingClientRect().top - offset;
if (Math.abs(delta) < 1) return;
this.autoScrollUntil = performance.now() + 50;
this.listTarget.scrollTop += delta;
}
// Extra room below an anchored turn, so it can sit near the top before the reply fills the screen.
updateSpacer() {
const list = this.listTarget;
const anchor = this.anchoredTurn;
let room = 0;
if (anchor?.isConnected) {
const below = list.scrollHeight - parseFloat(list.style.paddingBottom || this.basePadding) - this.offsetInList(anchor);
room = Math.max(0, list.clientHeight - this.anchorPeekValue - below);
}
list.style.paddingBottom = room > 0 ? `${this.basePadding + room}px` : "";
}
offsetInList(element) {
const list = this.listTarget;
return element.getBoundingClientRect().top - list.getBoundingClientRect().top + list.scrollTop;
}
// Selecting text or moving through the thread with the keyboard holds it still.
onSelectionChange() {
const selection = document.getSelection();
this.selecting = !!selection && !selection.isCollapsed && this.listTarget.contains(selection.anchorNode);
}
onListFocusIn(event) {
this.keyboardInside = event.target !== this.listTarget && event.target.matches(":focus-visible");
}
onListFocusOut(event) {
if (!this.listTarget.contains(event.relatedTarget)) this.keyboardInside = false;
}
// The jump button shows whenever you are away from the bottom; data-unread is set when
// messages arrived meanwhile, so the button can say "New messages".
toggleJump(show, { unread = false } = {}) {
if (!this.hasJumpTarget) return;
const jump = this.jumpTarget;
this.jumpUnread = show && (unread || this.jumpUnread);
jump.toggleAttribute("data-unread", this.jumpUnread);
if (jump.hidden === !show) return;
jump.hidden = !show;
if (show) this.enter(jump, "bottom");
}
keepTypingLast() {
const typing = this.hasTypingTarget ? this.typingTarget : null;
if (typing && typing.parentElement === this.listTarget && this.listTarget.lastElementChild !== typing) {
this.listTarget.append(typing);
}
}
isLast(node) {
let next = node.nextElementSibling;
while (next && this.hasTypingTarget && next === this.typingTarget) next = next.nextElementSibling;
return !next;
}
// ---------------------------------------------------------------------------
// Reactions
// ---------------------------------------------------------------------------
// data-action="message#react" data-message-emoji-param="👍"
// Works on quick reactions, menu reactions and the pills themselves.
react(event) {
const emoji = event.params.emoji;
if (!emoji) return;
const button = event.currentTarget;
const item = this.itemFor(button);
const reactions = this.reactionsFor(item);
if (this.inMenu(button)) {
this.closeMenu();
} else if (event.detail > 0 && !reactions?.contains(button)) {
// After a pointer pick from an inline quick-reaction bar, drop focus so the bar
// closes. Keyboard users (event.detail === 0) keep their place.
button.blur();
}
let pressed = true;
let count = null;
if (reactions) {
const pill = this.findReaction(reactions, emoji);
if (!pill) {
count = 1;
this.addReaction(reactions, emoji);
} else {
pressed = pill.getAttribute("aria-pressed") !== "true";
count = this.readCount(pill) + (pressed ? 1 : -1);
if (count <= 0) {
this.removeReaction(reactions, pill);
} else {
pill.setAttribute("aria-pressed", String(pressed));
this.writeCount(pill, count);
if (pressed) this.pop(pill);
}
}
}
this.dispatch("react", { detail: { emoji, pressed, count: Math.max(count ?? 0, 0), id: item?.dataset.messageId, element: item } });
}
findReaction(reactions, emoji) {
return Array.from(reactions.querySelectorAll("[data-message-emoji-param]")).find(
(element) => element.dataset.messageEmojiParam === emoji && !element.dataset.messageLeaving,
);
}
addReaction(reactions, emoji) {
if (!this.hasReactionTemplateTarget) return;
const pill = this.reactionTemplateTarget.content.firstElementChild.cloneNode(true);
pill.dataset.messageEmojiParam = emoji;
pill.setAttribute("aria-pressed", "true");
this.fill(pill, "emoji", emoji);
this.writeCount(pill, 1);
// Keep an "add reaction" button (or anything marked as trailing) at the end.
reactions.insertBefore(pill, reactions.querySelector("[data-message-trailing]"));
reactions.hidden = false;
this.enter(pill, "center");
}
removeReaction(reactions, pill) {
const remove = () => {
pill.remove();
if (!reactions.querySelector("[data-message-emoji-param]") && reactions.dataset.messageHideWhenEmpty !== undefined) {
reactions.hidden = true;
}
};
if (this.reducedMotion.matches) return remove();
// Exits are quicker and quieter than entrances.
pill.dataset.messageLeaving = "true";
pill.animate([{ opacity: 1, transform: "scale(1)" }, { opacity: 0, transform: "scale(0.9)" }], {
duration: 120,
easing: "ease-out",
fill: "forwards",
}).onfinish = remove;
}
// ---------------------------------------------------------------------------
// Actions menu: hover toolbar, press and hold, keyboard
// ---------------------------------------------------------------------------
// The menu is a popover="auto" element: it sits in the top layer, closes on Escape and
// on a click outside, and never locks or dims the page. It has three modes:
// "reactions" The emoji row above the bubble (toolbar smiley).
// "menu" The emoji row above the bubble and the actions below it (More, Shift+F10).
// "full" Press and hold on touch screens: the page dims and the bubble is lifted, like WhatsApp.
// data-action="message#openReactions" on a toolbar button.
openReactions(event) {
this.toggleMenu(this.itemFor(event.currentTarget), "reactions", event.currentTarget);
}
// data-action="message#openMenu" on a toolbar button. Can also be called with a message row and a mode.
openMenu(itemOrEvent, mode = "menu") {
if (itemOrEvent instanceof Event) {
this.toggleMenu(this.itemFor(itemOrEvent.currentTarget), "menu", itemOrEvent.currentTarget);
} else {
this.showMenu(itemOrEvent, mode);
}
}
// A second click on the button that opened the menu closes it, like a dropdown. The click
// outside already closed it (light dismiss), so a close that just happened counts too.
toggleMenu(item, mode, opener) {
const last = this.lastMenuClose;
const sameMenu = (state) => state && state.item === item && state.mode === mode;
if ((this.menuOpen && sameMenu({ item: this.menuItem, mode: this.menuMode })) || (sameMenu(last) && performance.now() - last.at < 300)) {
this.closeMenu();
return;
}
this.showMenu(item, mode, opener);
}
showMenu(item, mode, opener = document.activeElement) {
const bubble = item && this.bubbleFor(item);
if (!this.hasMenuTarget || !bubble) return;
const menu = this.menuTarget;
if (this.menuOpen) menu.hidePopover();
this.menuItem = item;
this.menuMode = mode;
this.menuOpener = opener;
menu.dataset.mode = mode;
this.mirror(bubble, mode);
menu.showPopover();
this.positionMenu(item, bubble, mode);
this.animateMenu(mode);
menu.querySelector("button:not([disabled])")?.focus({ preventScroll: true });
window.addEventListener("resize", this.closeMenu);
window.addEventListener("scroll", this.onMenuScroll, { capture: true, passive: true });
}
closeMenu() {
if (this.menuOpen) this.menuTarget.hidePopover();
}
get menuOpen() {
return this.hasMenuTarget && this.menuTarget.matches(":popover-open");
}
menuTargetConnected(menu) {
menu.addEventListener("click", this.onMenuClick);
menu.addEventListener("keydown", this.onMenuKeydown);
menu.addEventListener("beforetoggle", this.onMenuBeforeToggle);
menu.addEventListener("toggle", this.onMenuToggle);
}
menuTargetDisconnected(menu) {
menu.removeEventListener("click", this.onMenuClick);
menu.removeEventListener("keydown", this.onMenuKeydown);
menu.removeEventListener("beforetoggle", this.onMenuBeforeToggle);
menu.removeEventListener("toggle", this.onMenuToggle);
}
onMenuClick(event) {
// In "full" mode the dimmed page belongs to the menu: a tap on it, or on the lifted bubble, closes the menu.
const panel = this.hasMenuPanelTarget ? this.menuPanelTarget : this.menuTarget;
if (!panel.contains(event.target) || this.previewElement?.contains(event.target)) this.closeMenu();
}
// Runs before the menu hides, while focus is still inside it.
onMenuBeforeToggle(event) {
if (event.newState === "closed") this.restoreMenuFocus = this.menuTarget.contains(document.activeElement);
}
onMenuToggle(event) {
if (event.newState !== "closed" || this.menuOpen) return; // Reopened for another message in the meantime
window.removeEventListener("resize", this.closeMenu);
window.removeEventListener("scroll", this.onMenuScroll, { capture: true });
if (this.menuFrame) cancelAnimationFrame(this.menuFrame);
this.menuFrame = null;
if (this.hasMenuPreviewTarget) this.menuPreviewTarget.replaceChildren();
delete this.menuTarget.dataset.mode;
// Escape, Copy and custom actions hand focus back to the button that opened the menu.
// Reply moves it to the composer, and a click elsewhere keeps it where the click put it.
const focusLost = !document.activeElement || document.activeElement === document.body;
if (this.restoreMenuFocus && focusLost && this.menuOpener?.isConnected) this.menuOpener.focus({ preventScroll: true });
this.lastMenuClose = { item: this.menuItem, mode: this.menuMode, at: performance.now() };
this.menuItem = null;
this.menuMode = null;
this.menuOpener = null;
this.restoreMenuFocus = false;
}
// The menu follows its message while the page or the thread scrolls, and closes once the
// message is out of view. The lifted bubble of "full" mode can't follow, so it closes.
onMenuScroll(event) {
if (event.target instanceof Node && this.menuTarget.contains(event.target)) return;
if (this.menuMode === "full") {
this.closeMenu();
return;
}
if (this.menuFrame) return;
this.menuFrame = requestAnimationFrame(() => {
this.menuFrame = null;
const bubble = this.menuItem && this.bubbleFor(this.menuItem);
if (!this.menuOpen || !bubble?.isConnected || this.outOfView(bubble)) {
this.closeMenu();
return;
}
this.positionMenu(this.menuItem, bubble, this.menuMode);
});
}
outOfView(element) {
const rect = element.getBoundingClientRect();
const view = this.hasListTarget && this.listTarget.contains(element) ? this.listTarget.getBoundingClientRect() : { top: 0, bottom: window.innerHeight };
return rect.bottom < view.top || rect.top > view.bottom;
}
// Arrow keys move between the menu buttons; Home and End jump to the ends.
onMenuKeydown(event) {
const keys = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1, Home: "first", End: "last" };
if (!(event.key in keys)) return;
const buttons = Array.from(this.menuTarget.querySelectorAll("button:not([disabled])")).filter(
(button) => button.getClientRects().length > 0 && !this.previewElement?.contains(button),
);
if (buttons.length === 0) return;
event.preventDefault();
const index = buttons.indexOf(document.activeElement);
const step = keys[event.key];
const next = step === "first" ? 0 : step === "last" ? buttons.length - 1 : (index + step + buttons.length) % buttons.length;
buttons[next].focus();
}
// "full": the pressed bubble is copied into the menu, above the dimmed page, the way WhatsApp
// lifts a message. Events and ids are stripped from the copy.
// "menu": an empty spacer the size of the bubble, so the reactions sit above the real bubble
// and the actions below it. Clicks pass through it.
mirror(bubble, mode) {
if (!this.hasMenuPreviewTarget) return;
const preview = this.menuPreviewTarget;
const rect = bubble.getBoundingClientRect();
preview.replaceChildren();
preview.hidden = mode === "reactions";
preview.style.height = mode === "menu" ? `${rect.height}px` : "";
preview.style.width = mode === "menu" ? `${rect.width}px` : "";
preview.style.pointerEvents = mode === "menu" ? "none" : "";
if (mode !== "full") return;
const copy = bubble.cloneNode(true);
[copy, ...copy.querySelectorAll("*")].forEach((element) => {
["id", "data-action", "data-controller", "data-message-target", "tabindex"].forEach((name) => element.removeAttribute(name));
});
copy.inert = true;
copy.setAttribute("aria-hidden", "true");
copy.style.width = `${rect.width}px`;
copy.style.maxWidth = "100%";
copy.style.margin = "0";
preview.append(copy);
}
positionMenu(item, bubble, mode) {
if (!this.hasMenuPanelTarget) return;
const panel = this.menuPanelTarget;
const preview = this.hasMenuPreviewTarget ? this.menuPreviewTarget : null;
const rect = bubble.getBoundingClientRect();
const gap = 6;
const edge = 8;
const viewportWidth = document.documentElement.clientWidth;
const viewportHeight = window.innerHeight;
// Outgoing messages open their menu aligned to the end side (right, or left in RTL).
const outgoing = item.matches("[data-message-outgoing]");
const alignRight = outgoing !== (getComputedStyle(bubble).direction === "rtl");
panel.style.alignItems = alignRight ? "flex-end" : "flex-start";
panel.style.maxWidth = `${viewportWidth - edge * 2}px`;
if (preview && mode === "menu") {
preview.hidden = false;
preview.style.height = `${rect.height}px`;
}
let height = panel.offsetHeight;
let top = null;
let below = false;
if (preview && mode !== "reactions") {
// Wrap the bubble: reactions above, actions below, the bubble (real or lifted) in between.
top = rect.top - preview.offsetTop;
if (mode === "menu" && (top < edge || top + height > viewportHeight - edge)) {
// No room around the bubble: stack the reactions and actions above it, or below it.
preview.hidden = true;
height = panel.offsetHeight;
top = null;
}
}
if (top === null) {
top = rect.top - height - gap;
if (top < edge) {
top = rect.bottom + gap;
below = true;
}
}
const width = panel.offsetWidth;
const left = alignRight ? rect.right - width : rect.left;
panel.style.left = `${this.clamp(left, edge, viewportWidth - width - edge)}px`;
panel.style.top = `${this.clamp(top, edge, viewportHeight - height - edge)}px`;
panel.style.transformOrigin = `${alignRight ? "right" : "left"} ${below ? "top" : "bottom"}`;
}
animateMenu(mode) {
if (this.reducedMotion.matches) return;
if (mode === "full") this.menuTarget.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 150, easing: "ease-out" });
const panel = this.hasMenuPanelTarget ? this.menuPanelTarget : this.menuTarget;
Array.from(panel.children)
.filter((child) => child !== this.previewElement && child.getClientRects().length > 0)
.forEach((child) => {
child.animate(
[
{ opacity: 0, transform: "scale(0.96)" },
{ opacity: 1, transform: "scale(1)" },
],
{ duration: 180, easing: EASE_OUT },
);
});
}
// Press and hold on touch screens
onPointerDown(event) {
if (event.pointerType === "mouse" || !event.isPrimary || !this.hasMenuTarget) return;
const bubble = event.target.closest(BUBBLE);
if (!bubble || !this.owns(bubble)) return;
this.cancelPress();
this.press = {
bubble,
x: event.clientX,
y: event.clientY,
timer: setTimeout(() => this.longPress(), this.longPressDelayValue),
};
window.addEventListener("pointermove", this.onPointerMove, { passive: true });
window.addEventListener("pointerup", this.cancelPress);
window.addEventListener("pointercancel", this.cancelPress); // fired when the browser starts scrolling
window.addEventListener("scroll", this.cancelPress, { capture: true, passive: true });
}
onPointerMove(event) {
if (this.press && Math.hypot(event.clientX - this.press.x, event.clientY - this.press.y) > 10) this.cancelPress();
}
cancelPress() {
if (this.press) clearTimeout(this.press.timer);
this.press = null;
window.removeEventListener("pointermove", this.onPointerMove);
window.removeEventListener("pointerup", this.cancelPress);
window.removeEventListener("pointercancel", this.cancelPress);
window.removeEventListener("scroll", this.cancelPress, { capture: true });
}
longPress() {
const bubble = this.press?.bubble;
this.cancelPress();
if (!bubble) return;
try {
navigator.vibrate?.(10); // Android only; iOS ignores it
} catch {
// Vibration can be blocked by permissions policy
}
// Lifting the finger must not also follow a link inside the bubble.
this.suppressClickUntil = performance.now() + 700;
document.addEventListener("click", this.suppressClick, { capture: true, once: true });
this.openMenu(this.itemFor(bubble), "full");
}
suppressClick(event) {
if (performance.now() > this.suppressClickUntil || this.inMenu(event.target)) return;
event.preventDefault();
event.stopPropagation();
}
// Android fires contextmenu on a long press: use it and keep the native menu away.
onContextMenu(event) {
const bubble = event.target.closest(BUBBLE);
if (!bubble || !this.owns(bubble) || !this.hasMenuTarget) return;
if (!this.press && !this.coarsePointer.matches) return; // Right-click with a mouse keeps the browser menu
event.preventDefault();
if (this.press) this.longPress();
}
// Shift+F10 or the context menu key opens the menu of the focused message.
onKeydown(event) {
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
const item = document.activeElement?.closest(ITEM);
if (!item || !this.owns(item) || !this.hasMenuTarget) return;
event.preventDefault();
this.showMenu(item, "menu");
}
// ---------------------------------------------------------------------------
// Message actions
// ---------------------------------------------------------------------------
// data-action="message#reply". Cancel the message:reply event to handle it yourself.
reply(event) {
const item = this.itemFor(event.currentTarget);
this.closeMenu();
if (!item) return;
const detail = {
id: item.dataset.messageId,
author: item.dataset.messageAuthor || "",
text: this.textOf(this.bubbleFor(item)),
href: item.id ? `#${item.id}` : null,
element: item,
};
if (this.dispatch("reply", { detail, cancelable: true }).defaultPrevented) return;
this.startReply(detail);
}
startReply(detail) {
if (!this.hasInputTarget) return;
this.replyTo = detail;
if (this.hasReplyInputTarget) this.replyInputTarget.value = detail.id || "";
if (this.hasReplyPreviewTarget) {
const preview = this.replyPreviewTarget;
this.fill(preview, "reply-author", detail.author);
this.fill(preview, "reply-text", detail.text);
if (preview.hidden) {
preview.hidden = false;
this.enter(preview, "bottom");
}
}
this.inputTarget.focus();
}
// data-action="message#cancelReply" on the reply preview's close button. Escape in the input also works.
cancelReply(event) {
this.replyTo = null;
if (this.hasReplyInputTarget) this.replyInputTarget.value = "";
if (this.hasReplyPreviewTarget) this.replyPreviewTarget.hidden = true;
if (event?.type === "click" && this.hasInputTarget) this.inputTarget.focus();
}
// data-action="message#copy". Copies the text slot (or the bubble's text).
async copy(event) {
const item = this.itemFor(event.currentTarget);
this.closeMenu();
if (!item) return;
const text = this.textOf(this.bubbleFor(item));
try {
await navigator.clipboard.writeText(text);
this.announce(this.copiedLabelValue);
} catch {
// Clipboard needs a secure context (https or localhost)
}
this.dispatch("copy", { detail: { text, id: item.dataset.messageId, element: item } });
}
// data-action="message#act" data-message-name-param="delete": closes the menu and
// dispatches message:action with the name, so you can wire up edit, delete, pin…
act(event) {
const item = this.itemFor(event.currentTarget);
this.closeMenu();
this.dispatch("action", { detail: { name: event.params.name, id: item?.dataset.messageId, element: item } });
}
// ---------------------------------------------------------------------------
// Show more / show less
// ---------------------------------------------------------------------------
// data-action="message#expand" aria-controls="<id of the text>" aria-expanded="false"
// Toggles data-expanded on the text (style it with line-clamp-6 data-expanded:line-clamp-none).
expand(event) {
const button = event.currentTarget;
const text = document.getElementById(button.getAttribute("aria-controls"));
const expanded = button.getAttribute("aria-expanded") !== "true";
button.setAttribute("aria-expanded", String(expanded));
text?.toggleAttribute("data-expanded", expanded);
if (!expanded) this.revealIfOffscreen(text);
}
// After collapsing a long message, bring its start back into view if it scrolled away.
revealIfOffscreen(element) {
if (!element) return;
const rect = element.getBoundingClientRect();
const viewport = this.hasListTarget ? this.listTarget.getBoundingClientRect() : { top: 0 };
if (rect.top < viewport.top) element.scrollIntoView({ block: "nearest", behavior: this.reducedMotion.matches ? "auto" : "smooth" });
}
// ---------------------------------------------------------------------------
// Pressed-state buttons (feedback, bookmark, pin...)
// ---------------------------------------------------------------------------
// data-action="message#toggle"
// Add data-message-group="feedback" to make buttons mutually exclusive.
toggle(event) {
const button = event.currentTarget;
const pressed = button.getAttribute("aria-pressed") !== "true";
const group = button.dataset.messageGroup;
if (pressed && group) {
this.element.querySelectorAll(`[data-message-group="${group}"][aria-pressed="true"]`).forEach((other) => {
if (other !== button) other.setAttribute("aria-pressed", "false");
});
}
button.setAttribute("aria-pressed", String(pressed));
if (pressed) this.pop(button);
const item = this.itemFor(button);
this.dispatch("toggle", {
detail: { pressed, group, value: button.dataset.messageValue, id: item?.dataset.messageId, element: button },
});
}
// ---------------------------------------------------------------------------
// Composer
// ---------------------------------------------------------------------------
// data-action="submit->message#send" on the form
send(event) {
if (!this.hasInputTarget) return;
const text = this.inputTarget.value.trim();
if (!text) {
event?.preventDefault();
return;
}
if (!this.optimisticValue) {
// Let the form submit to Rails; the message comes back as a Turbo Stream.
// Clear the composer only once the server accepted it, so nothing is lost on errors.
const form = event?.target instanceof HTMLFormElement ? event.target : this.inputTarget.form;
if (!event && form) form.requestSubmit();
form?.addEventListener(
"turbo:submit-end",
(submitEnd) => {
if (submitEnd.detail.success) this.clearComposer();
},
{ once: true },
);
return;
}
event?.preventDefault();
const replyTo = this.replyTo;
let message = null;
if (this.hasListTarget && this.hasOutgoingTemplateTarget) {
// Only the latest outgoing message shows a delivery status.
this.listTarget.querySelectorAll('[data-message-slot="status"]').forEach((status) => status.remove());
message = this.append(this.outgoingTemplateTarget, text, { replyTo });
}
this.clearComposer();
this.inputTarget.focus();
this.dispatch("sent", { detail: { text, element: message, replyTo: replyTo?.id ?? null } });
}
clearComposer() {
this.inputTarget.value = "";
this.resize();
this.cancelReply();
}
// data-action="keydown->message#composerKeydown" on the textarea.
// Enter sends (new line on touch keyboards unless sendOnTouchEnter), Shift+Enter adds
// a new line, Escape cancels a reply. Ignores IME composition.
composerKeydown(event) {
if (event.key === "Escape" && this.replyTo) {
event.preventDefault();
this.cancelReply();
return;
}
if (event.key !== "Enter" || event.shiftKey || event.isComposing || this.enterInsertsNewLine) return;
event.preventDefault();
if (this.optimisticValue) this.send();
else this.inputTarget.form?.requestSubmit();
}
// Kept for existing markup: data-action="keydown.enter->message#submitOnEnter"
submitOnEnter(event) {
this.composerKeydown(event);
}
// data-action="input->message#resize"
resize() {
const input = this.inputTarget;
input.style.height = "auto";
input.style.height = `${Math.min(input.scrollHeight, this.maxInputHeightValue)}px`;
input.style.overflowY = input.scrollHeight > this.maxInputHeightValue ? "auto" : "hidden";
if (this.hasSubmitTarget) this.submitTarget.disabled = input.value.trim() === "";
}
get enterInsertsNewLine() {
return this.coarsePointer.matches && !this.sendOnTouchEnterValue;
}
// Public: clones a template, fills its slots and adds it to the thread. The list
// observer animates it and scrolls it into view.
append(template, text, { replyTo = null } = {}) {
if (!this.hasListTarget) return null;
const message = template.content.firstElementChild.cloneNode(true);
const now = new Date();
this.fill(message, "text", text);
this.fill(message, "time", now.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }));
message.querySelectorAll("time[data-message-slot]").forEach((time) => (time.dateTime = now.toISOString()));
const quote = message.querySelector('[data-message-slot="quote"]');
if (quote && replyTo) {
this.fill(quote, "quote-author", replyTo.author);
this.fill(quote, "quote-text", replyTo.text);
if (quote.tagName === "A" && replyTo.href) quote.setAttribute("href", replyTo.href);
quote.hidden = false;
} else {
quote?.remove();
}
// Messages go above the typing indicator when it lives inside the list.
const typing = this.hasTypingTarget && this.typingTarget.parentElement === this.listTarget ? this.typingTarget : null;
this.listTarget.insertBefore(message, typing);
return message;
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
owns(element) {
return element.closest('[data-controller~="message"]') === this.element;
}
get previewElement() {
return this.hasMenuPreviewTarget ? this.menuPreviewTarget : null;
}
inMenu(element) {
return this.hasMenuTarget && this.menuTarget.contains(element);
}
// The message row an element belongs to. Inside the menu, the message it was opened for.
itemFor(element) {
if (this.inMenu(element)) return this.menuItem;
const item = element.closest(ITEM);
return item && this.owns(item) ? item : this.element;
}
bubbleFor(item) {
return item.matches(BUBBLE) ? item : item.querySelector(BUBBLE);
}
reactionsFor(item) {
return (item || this.element).querySelector('[data-message-target~="reactions"]');
}
textOf(bubble) {
if (!bubble) return "";
const slot = bubble.querySelector('[data-message-slot="text"]');
return (slot || bubble).innerText.trim();
}
fill(root, slot, value) {
root.querySelectorAll(`[data-message-slot="${slot}"]`).forEach((element) => (element.textContent = value));
}
readCount(pill) {
const count = pill.querySelector('[data-message-slot="count"]');
return count ? parseInt(count.textContent, 10) || 0 : 0;
}
writeCount(pill, value) {
this.fill(pill, "count", value);
}
clamp(value, min, max) {
return Math.min(Math.max(value, min), Math.max(min, max));
}
announce(text) {
if (!this.liveRegion) {
this.liveRegion = document.createElement("span");
this.liveRegion.setAttribute("aria-live", "polite");
this.liveRegion.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";
this.element.append(this.liveRegion);
}
this.liveRegion.textContent = "";
requestAnimationFrame(() => (this.liveRegion.textContent = text));
}
// Entrance for new bubbles and pills: a short rise and scale from the sender's side.
// Never from scale(0), always under 300ms, with a strong ease-out.
enter(element, side) {
if (this.reducedMotion.matches) return;
const rtl = getComputedStyle(element).direction === "rtl";
const origins = {
start: rtl ? "bottom right" : "bottom left",
end: rtl ? "bottom left" : "bottom right",
center: "center",
bottom: "bottom center",
};
element.style.transformOrigin = origins[side] || side;
element.animate(
[
{ opacity: 0, transform: "translateY(6px) scale(0.95)" },
{ opacity: 1, transform: "translateY(0) scale(1)" },
],
{ duration: 220, easing: EASE_OUT },
);
}
// Press feedback for reactions and toggles: the emoji or icon inside gets a quick,
// slightly playful pop. The button itself never scales.
pop(element) {
if (this.reducedMotion.matches) return;
// Buttons can swap an outline icon for a filled one when pressed: animate the visible one.
const content = Array.from(element.querySelectorAll('[data-message-slot="emoji"], svg')).find(
(candidate) => candidate.getClientRects().length > 0,
);
if (!content) return;
content.animate([{ transform: "scale(0.92)" }, { transform: "scale(1.06)", offset: 0.55 }, { transform: "scale(1)" }], {
duration: 200,
easing: EASE_OUT,
});
}
}
Examples
Basic Message
Incoming and outgoing bubbles. Incoming messages align to the start, outgoing messages to the end, and the corner nearest the sender is tightened to hint at who is speaking.
Morning! Is the pricing page ready for review?
Almost. I'm polishing the comparison table and will send you a link in ten minutes.
Perfect, no rush.
<div class="flex w-full max-w-md flex-col gap-2">
<%# Incoming message: aligned to the start %>
<div class="flex justify-start">
<p class="max-w-[80%] rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">
Morning! Is the pricing page ready for review?
</p>
</div>
<%# Outgoing message: aligned to the end %>
<div class="flex justify-end">
<p class="max-w-[80%] rounded-2xl rounded-br-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-white dark:bg-white dark:text-neutral-900">
Almost. I'm polishing the comparison table and will send you a link in ten minutes.
</p>
</div>
<div class="flex justify-start">
<p class="max-w-[80%] rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">
Perfect, no rush.
</p>
</div>
</div>
Message with Avatar
A header with the sender and time, an avatar that stays aligned with the bottom of the bubble, and a footer for the delivery status. Includes an initials fallback.
That's great news. A week is tight but doable if we cut the export feature.
<div class="flex w-full max-w-md flex-col gap-4">
<%# Incoming: header, avatar + bubble, footer. The avatar stays aligned with the bubble, not the footer. %>
<article class="flex flex-col gap-1">
<header class="flex items-baseline gap-2 pl-10 text-xs">
<span class="font-medium text-neutral-900 dark:text-neutral-100">Olivia Martin</span>
<time datetime="2026-11-09T09:41" class="text-neutral-500 dark:text-neutral-400">9:41 AM</time>
</header>
<div class="flex items-end gap-2">
<img
class="size-8 shrink-0 rounded-full object-cover outline -outline-offset-1 outline-black/10 dark:outline-white/10"
src="https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=160&h=160&fit=crop&crop=face&auto=format&q=80"
alt="Olivia Martin">
<p class="max-w-[80%] rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">
The client loved the prototype. They want to move the launch up by a week.
</p>
</div>
</article>
<%# Outgoing: same structure, mirrored with flex-row-reverse %>
<article class="flex flex-col gap-1">
<header class="flex flex-row-reverse items-baseline gap-2 pr-10 text-xs">
<span class="font-medium text-neutral-900 dark:text-neutral-100">You</span>
<time datetime="2026-11-09T09:43" class="text-neutral-500 dark:text-neutral-400">9:43 AM</time>
</header>
<div class="flex flex-row-reverse items-end gap-2">
<%# Initials fallback when there is no profile image %>
<span class="flex size-8 shrink-0 items-center justify-center rounded-full bg-neutral-200 text-xs font-medium text-neutral-700 dark:bg-neutral-700 dark:text-neutral-200" aria-hidden="true">AG</span>
<p class="max-w-[80%] rounded-2xl rounded-br-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-white dark:bg-white dark:text-neutral-900">
That's great news. A week is tight but doable if we cut the export feature.
</p>
</div>
<footer class="pr-10 text-right text-xs text-neutral-500 dark:text-neutral-400">Delivered</footer>
</article>
</div>
Grouped Messages
Consecutive messages from the same sender stack tightly and share one name and one avatar. The corners on the sender's side are squared between bubbles, and the tail stays on the last bubble, pointing at the avatar.
Marcus Chen
I checked the import job.
It stalls on rows with an empty email column, then retries forever.
Want me to skip those rows or fail the whole file?
Skip them.
And list the skipped rows in the summary email so nobody is surprised.
Read 2:14 PM
<div class="flex w-full max-w-md flex-col gap-4">
<%# Incoming group: tight spacing, one name, one avatar on the last message. %>
<%# Corners: the side facing the sender is squared between bubbles; the last bubble keeps the tail (bottom corner) next to the avatar. %>
<div class="flex flex-col gap-0.5" role="group" aria-label="Messages from Marcus Chen">
<p class="pb-0.5 pl-10 text-xs font-medium text-neutral-900 dark:text-neutral-100">Marcus Chen</p>
<%# First: tail corner squared, top corner round %>
<div class="flex items-end gap-2">
<span class="w-8 shrink-0" aria-hidden="true"></span>
<p class="max-w-[80%] rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">I checked the import job.</p>
</div>
<%# Middle: both corners on the sender's side squared %>
<div class="flex items-end gap-2">
<span class="w-8 shrink-0" aria-hidden="true"></span>
<p class="max-w-[80%] rounded-2xl rounded-l-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">It stalls on rows with an empty email column, then retries forever.</p>
</div>
<%# Last: squared on top (joins the group) and at the bottom (the tail, pointing at the avatar) %>
<div class="flex items-end gap-2">
<img
class="size-8 shrink-0 rounded-full object-cover outline -outline-offset-1 outline-black/10 dark:outline-white/10"
src="https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=160&h=160&fit=crop&crop=face&auto=format&q=80"
alt="" width="32" height="32" loading="lazy">
<p class="max-w-[80%] rounded-2xl rounded-l-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">Want me to skip those rows or fail the whole file?</p>
</div>
</div>
<%# Outgoing group: mirrored, no avatar. The tail stays on the last bubble, bottom right. %>
<div class="flex flex-col items-end gap-0.5" role="group" aria-label="Your messages">
<p class="max-w-[80%] rounded-2xl rounded-br-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-white dark:bg-white dark:text-neutral-900">Skip them.</p>
<p class="max-w-[80%] rounded-2xl rounded-r-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-white dark:bg-white dark:text-neutral-900">And list the skipped rows in the summary email so nobody is surprised.</p>
<p class="pt-0.5 text-xs text-neutral-500 dark:text-neutral-400">Read 2:14 PM</p>
</div>
</div>
Delivery Status
The four states of an outgoing message: sending, delivered, read, and failed with a retry action. The failed state uses role="alert" so it is announced.
Uploading the signed contract now.
Sending…
The invoice is in your inbox.
Delivered
Can we move our call to Thursday?
Read
Here's the recording from yesterday.
Not delivered.
<div class="flex w-full max-w-md flex-col gap-4">
<%# Sending %>
<div class="flex flex-col items-end gap-1">
<p class="max-w-[80%] rounded-2xl rounded-br-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-white opacity-60 dark:bg-white dark:text-neutral-900">Uploading the signed contract now.</p>
<p class="flex items-center gap-1 text-xs text-neutral-500 dark:text-neutral-400" role="status">
<svg class="size-3 animate-spin motion-reduce:animate-none" viewBox="0 0 16 16" fill="none" aria-hidden="true"><circle cx="8" cy="8" r="6.25" stroke="currentColor" stroke-width="1.5" class="opacity-25"></circle><path d="M14.25 8A6.25 6.25 0 0 0 8 1.75" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"></path></svg>
Sending…
</p>
</div>
<%# Delivered %>
<div class="flex flex-col items-end gap-1">
<p class="max-w-[80%] rounded-2xl rounded-br-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-white dark:bg-white dark:text-neutral-900">The invoice is in your inbox.</p>
<p class="flex items-center gap-1 text-xs text-neutral-500 dark:text-neutral-400">
<svg class="size-3.5" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="2.75 9.5 6.5 13.25 15.25 4.5"></polyline></svg>
Delivered
</p>
</div>
<%# Read %>
<div class="flex flex-col items-end gap-1">
<p class="max-w-[80%] rounded-2xl rounded-br-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-white dark:bg-white dark:text-neutral-900">Can we move our call to Thursday?</p>
<p class="flex items-center gap-1 text-xs text-neutral-500 dark:text-neutral-400">
<svg class="size-3.5 text-sky-600 dark:text-sky-400" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points=".75 9.5 4.5 14.25 12.5 4"></polyline><polyline points="8.506 13.308 9.25 14.25 17.25 4"></polyline></svg>
Read <time datetime="2026-11-09T11:02">11:02 AM</time>
</p>
</div>
<%# Failed, with a retry action %>
<div class="flex flex-col items-end gap-1">
<div class="flex max-w-[80%] items-center gap-2">
<svg class="size-4 shrink-0 text-red-600 dark:text-red-400" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 16.25C13.0041 16.25 16.25 13.004 16.25 9C16.25 4.996 13.0041 1.75 9 1.75C4.9959 1.75 1.75 4.996 1.75 9C1.75 13.004 4.9959 16.25 9 16.25Z"></path><path d="M9 5.431V9.5"></path><path d="M9 13.417C8.448 13.417 8 12.968 8 12.417C8 11.866 8.448 11.417 9 11.417C9.552 11.417 10 11.866 10 12.417C10 12.968 9.552 13.417 9 13.417Z" fill="currentColor" stroke="none"></path></svg>
<p class="rounded-2xl rounded-br-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-white dark:bg-white dark:text-neutral-900">Here's the recording from yesterday.</p>
</div>
<p class="flex items-center gap-1 text-xs text-red-600 dark:text-red-400" role="alert">
Not delivered.
<button type="button" class="-my-1 rounded-md px-1 py-1 font-medium underline underline-offset-2 hover:no-underline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-red-600 dark:focus-visible:outline-red-400">Try again</button>
</p>
</div>
</div>
Reactions and Actions
Works like WhatsApp. On desktop, hover a message for a small toolbar beside the bubble: the smiley shows the emoji row above the message, More adds the actions below it, and the page keeps scrolling. On touch screens, press and hold a bubble: the page dims, the bubble lifts, and the reactions and actions appear around it. Keyboard users can Tab to the toolbar or press Shift + F10. One menu serves every message, and each pick dispatches an event (message:react, message:copy, message:action) so you can save it.
<%# One "message" controller for the whole list. Each message is an item with a bubble. %>
<%# Desktop: hover a message for the toolbar. Touch: press and hold a bubble. Keyboard: Tab to a toolbar button, or Shift+F10. %>
<% reactions = [["👍", "Thumbs up"], ["❤️", "Heart"], ["😂", "Laughing"], ["😮", "Surprised"], ["🙏", "Thank you"]] %>
<% toolbar_classes = "absolute top-1/2 flex -translate-y-1/2 items-center gap-0.5 opacity-0 transition-opacity duration-150 ease-out group-focus-within/message:opacity-100 group-hover/message:opacity-100 pointer-coarse:sr-only motion-reduce:transition-none" %>
<% tool_classes = "flex size-7 items-center justify-center rounded-full text-neutral-500 transition-colors duration-100 hover:bg-neutral-100 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-neutral-600 dark:text-neutral-400 dark:hover:bg-neutral-800 dark:hover:text-white dark:focus-visible:outline-neutral-200" %>
<%# The ring matches the surface behind the messages (white, black in dark mode here), so pills look cut into the bubble edge %>
<% pill_classes = "relative inline-flex items-center gap-1 rounded-full bg-neutral-100 px-2 py-0.5 text-xs font-medium text-neutral-700 tabular-nums ring-3 ring-white after:absolute after:inset-x-0 after:-inset-y-2 transition-[background-color,color] duration-150 ease-out hover:bg-neutral-200 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 aria-pressed:bg-sky-100 aria-pressed:text-sky-800 motion-reduce:transition-none dark:bg-neutral-800 dark:text-neutral-200 dark:ring-black dark:hover:bg-neutral-700 dark:focus-visible:outline-neutral-200 dark:aria-pressed:bg-sky-950 dark:aria-pressed:text-sky-200" %>
<%# select-none and no callout on touch screens, so pressing and holding opens the menu instead of selecting text %>
<% bubble_touch_classes = "pointer-coarse:select-none pointer-coarse:[-webkit-touch-callout:none]" %>
<% smiley_icon = capture do %><svg class="size-4" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.25"></circle><path d="M5.75 9.5a2.75 2.75 0 0 0 4.5 0"></path><path d="M6 6.25v.01"></path><path d="M10 6.25v.01"></path></svg><% end %>
<% more_icon = capture do %><svg class="size-4" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><circle cx="3.5" cy="8" r="1.25"></circle><circle cx="8" cy="8" r="1.25"></circle><circle cx="12.5" cy="8" r="1.25"></circle></svg><% end %>
<div class="flex w-full max-w-md flex-col gap-6" data-controller="message">
<%# Incoming message with reactions %>
<article class="group/message flex flex-col items-start" data-message-target="item" data-message-id="2081" data-message-author="Olivia Martin">
<div class="relative max-w-[80%]">
<div class="rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100 <%= bubble_touch_classes %>" data-message-target="bubble">
<p data-message-slot="text">We just crossed 10,000 signups! Thank you all for the late nights.</p>
</div>
<%# Toolbar beside the bubble, on the side facing the conversation %>
<div class="<%= toolbar_classes %> left-full ml-1">
<button type="button" class="<%= tool_classes %>" aria-label="Add reaction" data-action="message#openReactions"><%= smiley_icon %></button>
<button type="button" class="<%= tool_classes %>" aria-label="More actions" data-action="message#openMenu"><%= more_icon %></button>
</div>
</div>
<%# Reaction pills overlap the bottom edge of the bubble %>
<div class="relative -mt-1.5 flex flex-wrap gap-1 pl-2" data-message-target="reactions" data-message-hide-when-empty>
<button type="button" class="<%= pill_classes %>" aria-pressed="true" data-action="message#react" data-message-emoji-param="🙏">
<span data-message-slot="emoji" class="inline-block">🙏</span>
<span data-message-slot="count">8</span>
</button>
<button type="button" class="<%= pill_classes %>" aria-pressed="false" data-action="message#react" data-message-emoji-param="❤️">
<span data-message-slot="emoji" class="inline-block">❤️</span>
<span data-message-slot="count">3</span>
</button>
</div>
</article>
<%# Outgoing message without reactions yet: the pill row stays hidden until the first one %>
<article class="group/message flex flex-col items-end" data-message-target="item" data-message-id="2082" data-message-author="You" data-message-outgoing>
<div class="relative max-w-[80%]">
<div class="rounded-2xl rounded-br-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-white dark:bg-white dark:text-neutral-900 <%= bubble_touch_classes %>" data-message-target="bubble">
<p data-message-slot="text">Couldn't have done it without this team.</p>
</div>
<div class="<%= toolbar_classes %> right-full mr-1 flex-row-reverse">
<button type="button" class="<%= tool_classes %>" aria-label="Add reaction" data-action="message#openReactions"><%= smiley_icon %></button>
<button type="button" class="<%= tool_classes %>" aria-label="More actions" data-action="message#openMenu"><%= more_icon %></button>
</div>
</div>
<div class="relative -mt-1.5 flex flex-wrap justify-end gap-1 pr-2" data-message-target="reactions" data-message-hide-when-empty hidden></div>
</article>
<%# Markup for reactions added by the controller. Slots: emoji, count. %>
<template data-message-target="reactionTemplate">
<button type="button" class="<%= pill_classes %>" aria-pressed="true" data-action="message#react">
<span data-message-slot="emoji" class="inline-block"></span>
<span data-message-slot="count">1</span>
</button>
</template>
<%# One popover menu for every message. No page dim or scroll lock; it closes on Escape or a click outside. %>
<%# "reactions" (toolbar smiley): emoji row above the bubble. "menu" (More, Shift+F10): reactions above, actions below. %>
<%# "full" (press and hold on touch screens): the page dims and the bubble is lifted, like WhatsApp. %>
<div popover="auto" role="dialog" class="group/menu fixed inset-0 m-0 size-full max-h-none max-w-none touch-none overflow-hidden border-0 bg-transparent p-0 text-inherit not-data-[mode=full]:pointer-events-none data-[mode=full]:bg-black/30 dark:data-[mode=full]:bg-black/60" aria-label="Message actions" data-message-target="menu">
<div class="pointer-events-auto absolute flex flex-col gap-2" data-message-target="menuPanel">
<div class="flex items-center gap-0.5 rounded-full border border-black/10 bg-white p-1 shadow-lg dark:border-white/10 dark:bg-neutral-800" role="group" aria-label="Reactions">
<% reactions.each do |emoji, label| %>
<button type="button" class="flex size-10 items-center justify-center rounded-full text-xl select-none hover:bg-neutral-100 focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-neutral-600 dark:hover:bg-neutral-700 dark:focus-visible:outline-neutral-200" aria-label="React with <%= label %>" data-action="message#react" data-message-emoji-param="<%= emoji %>"><%= emoji %></button>
<% end %>
</div>
<%# The pressed bubble is lifted here in "full" mode; in "menu" mode this is a spacer the size of the bubble %>
<div class="max-h-[40vh] overflow-hidden group-data-[mode=reactions]/menu:hidden" data-message-target="menuPreview"></div>
<div class="w-52 rounded-xl border border-black/10 bg-white p-1 shadow-lg group-data-[mode=reactions]/menu:hidden dark:border-white/10 dark:bg-neutral-800" role="group" aria-label="Actions">
<button type="button" class="flex w-full items-center justify-between gap-3 rounded-lg px-3 py-2 text-left text-sm text-neutral-900 hover:bg-neutral-100 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-neutral-600 dark:text-neutral-100 dark:hover:bg-neutral-700 dark:focus-visible:outline-neutral-200" data-action="message#copy">
Copy
<svg class="size-4 text-neutral-500 dark:text-neutral-400" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12.25 5.75H13.75C14.8546 5.75 15.75 6.6454 15.75 7.75V13.75C15.75 14.8546 14.8546 15.75 13.75 15.75H7.75C6.6454 15.75 5.75 14.8546 5.75 13.75V12.25"></path><path d="M10.25 2.25H4.25C3.14543 2.25 2.25 3.14543 2.25 4.25V10.25C2.25 11.3546 3.14543 12.25 4.25 12.25H10.25C11.3546 12.25 12.25 11.3546 12.25 10.25V4.25C12.25 3.14543 11.3546 2.25 10.25 2.25Z"></path></svg>
</button>
<%# Your own actions: message#act dispatches message:action with the name and the message id %>
<button type="button" class="flex w-full items-center justify-between gap-3 rounded-lg px-3 py-2 text-left text-sm text-neutral-900 hover:bg-neutral-100 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-neutral-600 dark:text-neutral-100 dark:hover:bg-neutral-700 dark:focus-visible:outline-neutral-200" data-action="message#act" data-message-name-param="pin">
Pin
<svg class="size-4 text-neutral-500 dark:text-neutral-400" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 10.75v3.5"></path><path d="M5.25 2.25h5.5"></path><path d="M6.25 2.25v3.5L4.25 8.5v2.25h7.5V8.5l-2-2.75v-3.5"></path></svg>
</button>
</div>
</div>
</div>
</div>
Attachments
An image with a caption inside the bubble, and a file card with its type, size and a download affordance. The whole card is one link, so it is easy to hit on touch screens.
Done. Here's the updated PDF.
lakeside-brochure-v3.pdf PDF · 2.4 MB DownloadLooks great, thank you!
<div class="flex w-full max-w-md flex-col gap-2">
<%# Image attachment with a caption %>
<div class="flex justify-end">
<figure class="max-w-[80%] overflow-hidden rounded-2xl rounded-br-md bg-neutral-900 text-white dark:bg-white dark:text-neutral-900">
<a href="https://images.unsplash.com/photo-1501785888041-af3ef285b470?w=1600&auto=format&q=80" target="_blank" rel="noopener" class="block focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-white dark:focus-visible:outline-neutral-900">
<img
class="aspect-[4/3] w-full bg-neutral-200 object-cover dark:bg-neutral-700"
src="https://images.unsplash.com/photo-1501785888041-af3ef285b470?w=640&h=480&fit=crop&auto=format&q=80"
alt="A lake surrounded by mountains at sunset"
width="640" height="480" loading="lazy">
</a>
<figcaption class="px-3.5 py-2 text-sm leading-relaxed text-pretty break-words">Found our cover photo. Can you drop it into the brochure?</figcaption>
</figure>
</div>
<%# Text and file sent together: grouped like consecutive messages (squared corners on the sender's side), %>
<%# with a little more room than text bubbles because the card has its own border. %>
<div class="flex flex-col items-start gap-1">
<p class="max-w-[80%] rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">Done. Here's the updated PDF.</p>
<a href="#" download class="group flex w-72 max-w-[80%] items-center gap-3 rounded-2xl rounded-l-md border border-black/10 bg-white p-2.5 shadow-xs transition-colors duration-150 hover:bg-neutral-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 dark:border-white/10 dark:bg-neutral-900 dark:hover:bg-neutral-800 dark:focus-visible:outline-neutral-200">
<span class="flex size-10 shrink-0 items-center justify-center rounded-md bg-red-50 text-red-600 dark:bg-red-500/10 dark:text-red-400">
<svg class="size-5" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="5.75" y1="6.75" x2="7.75" y2="6.75"></line><line x1="5.75" y1="9.75" x2="12.25" y2="9.75"></line><line x1="5.75" y1="12.75" x2="12.25" y2="12.75"></line><path d="M2.75 14.25V3.75c0-1.105.895-2 2-2h5.586c.265 0 .52.105.707.293l3.914 3.914c.188.188.293.442.293.707v7.586c0 1.105-.895 2-2 2H4.75c-1.105 0-2-.895-2-2Z"></path><path d="M15.16 6.25h-3.41c-.552 0-1-.448-1-1V1.852"></path></svg>
</span>
<span class="min-w-0 flex-1">
<span class="block truncate text-sm font-medium text-neutral-900 dark:text-neutral-100">lakeside-brochure-v3.pdf</span>
<span class="block text-xs text-neutral-500 dark:text-neutral-400">PDF · 2.4 MB</span>
</span>
<span class="flex size-8 shrink-0 items-center justify-center rounded-full text-neutral-500 transition-colors duration-150 group-hover:bg-neutral-200/70 group-hover:text-neutral-900 dark:text-neutral-400 dark:group-hover:bg-neutral-700 dark:group-hover:text-white">
<svg class="size-4" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15.25 11.75v1.5c0 1.105-.895 2-2 2H4.75c-1.105 0-2-.895-2-2v-1.5"></path><polyline points="5.5 6.75 9 10.25 12.5 6.75"></polyline><line x1="9" y1="10.25" x2="9" y2="2.75"></line></svg>
<span class="sr-only">Download</span>
</span>
</a>
</div>
<div class="flex justify-end">
<p class="max-w-[80%] rounded-2xl rounded-br-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-white dark:bg-white dark:text-neutral-900">Looks great, thank you!</p>
</div>
</div>
Reply
A reply quotes the original message inside the bubble, on either side. The quote is a link back to the original, and its accent bar stays straight because the quote clips it to its rounded corners.
Should we keep the free plan after the redesign, or replace it with a 14-day trial?
Keep it. Most of our paid teams started on free.
Agreed. I'll update the pricing page copy.
<div class="flex w-full max-w-md flex-col gap-2">
<div class="flex justify-start">
<p id="message-1042" class="max-w-[80%] scroll-mt-24 rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">
Should we keep the free plan after the redesign, or replace it with a 14-day trial?
</p>
</div>
<%# Outgoing reply: the quote sits inside the bubble and links back to the original. %>
<%# overflow-hidden clips the accent bar to the quote's rounded corners, so the bar stays straight. %>
<div class="flex justify-end">
<div id="message-1043" class="max-w-[80%] scroll-mt-24 rounded-2xl rounded-br-md bg-neutral-900 p-1 text-sm text-white dark:bg-white dark:text-neutral-900">
<a href="#message-1042" class="relative block overflow-hidden rounded-xl bg-white/10 py-1.5 pr-2.5 pl-3.5 transition-colors duration-150 hover:bg-white/15 focus-visible:outline-2 focus-visible:outline-white dark:bg-neutral-900/5 dark:hover:bg-neutral-900/10 dark:focus-visible:outline-neutral-900">
<span class="absolute inset-y-0 left-0 w-1 bg-sky-400 dark:bg-sky-600" aria-hidden="true"></span>
<span class="sr-only">Replying to</span>
<span class="block text-xs font-medium text-sky-300 dark:text-sky-700">Olivia Martin</span>
<span class="line-clamp-1 text-xs opacity-70">Should we keep the free plan after the redesign, or replace it with a 14-day trial?</span>
</a>
<p class="px-2.5 py-1 leading-relaxed text-pretty break-words">Keep it. Most of our paid teams started on free.</p>
</div>
</div>
<%# Incoming reply: same structure on the other side, colors adapted to the light bubble. %>
<div class="flex justify-start">
<div class="max-w-[80%] rounded-2xl rounded-bl-md bg-neutral-100 p-1 text-sm text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">
<a href="#message-1043" class="relative block overflow-hidden rounded-xl bg-black/5 py-1.5 pr-2.5 pl-3.5 transition-colors duration-150 hover:bg-black/10 focus-visible:outline-2 focus-visible:outline-neutral-600 dark:bg-white/5 dark:hover:bg-white/10 dark:focus-visible:outline-neutral-200">
<span class="absolute inset-y-0 left-0 w-1 bg-sky-600 dark:bg-sky-400" aria-hidden="true"></span>
<span class="sr-only">Replying to</span>
<span class="block text-xs font-medium text-sky-700 dark:text-sky-300">You</span>
<span class="line-clamp-1 text-xs opacity-70">Keep it. Most of our paid teams started on free.</span>
</a>
<p class="px-2.5 py-1 leading-relaxed text-pretty break-words">Agreed. I'll update the pricing page copy.</p>
</div>
</div>
</div>
Typing Indicator
A CSS-only typing bubble and a compact text version for group channels. Both use role="status" and stop animating when reduced motion is requested.
Marcus and Priya are typing…
<div class="flex w-full max-w-md flex-col gap-6">
<%# Bubble with bouncing dots. The label is read by screen readers. %>
<div class="flex items-end gap-2" role="status">
<img
class="size-8 shrink-0 rounded-full object-cover outline -outline-offset-1 outline-black/10 dark:outline-white/10"
src="https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=160&h=160&fit=crop&crop=face&auto=format&q=80"
alt="">
<div class="flex h-9 items-center gap-1 rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 dark:bg-neutral-800">
<span class="sr-only">Olivia is typing</span>
<%# Each dot sits in a taller box so animate-bounce travels a few pixels %>
<span class="flex h-3 animate-bounce items-end [animation-duration:1.1s] motion-reduce:animate-none" aria-hidden="true"><span class="size-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500"></span></span>
<span class="flex h-3 animate-bounce items-end [animation-delay:150ms] [animation-duration:1.1s] motion-reduce:animate-none" aria-hidden="true"><span class="size-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500"></span></span>
<span class="flex h-3 animate-bounce items-end [animation-delay:300ms] [animation-duration:1.1s] motion-reduce:animate-none" aria-hidden="true"><span class="size-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500"></span></span>
</div>
</div>
<%# Compact text version for busy channels %>
<p class="flex items-center gap-2 text-xs text-neutral-500 dark:text-neutral-400" role="status">
<span class="flex items-center gap-0.5" aria-hidden="true">
<span class="size-1 animate-pulse rounded-full bg-current motion-reduce:animate-none"></span>
<span class="size-1 animate-pulse rounded-full bg-current [animation-delay:200ms] motion-reduce:animate-none"></span>
<span class="size-1 animate-pulse rounded-full bg-current [animation-delay:400ms] motion-reduce:animate-none"></span>
</span>
<span><span class="font-medium text-neutral-700 dark:text-neutral-200">Marcus</span> and <span class="font-medium text-neutral-700 dark:text-neutral-200">Priya</span> are typing…</span>
</p>
</div>
AI Assistant Message
An assistant reply without a bubble: reasoning and tool steps, rich text with code, and a row of actions. Copy uses the clipboard controller; the thumbs swap to a filled icon when pressed and dispatch message:toggle. Steps and the streaming status use the Marker styles; the shimmer is the CSS animate-marker-shimmer utility from the Rails Blocks theme. With the ViewComponent, pass variant: :ghost for a reply without a bubble.
Why is the orders page so slow for big customers?
- Thought for 6 seconds
-
Ran
EXPLAIN ANALYZEon the orders query
The query filters on customer_id without an index, so Postgres scans the whole table. For customers with thousands of orders that takes about 840 ms.
Adding an index fixes it:
add_index :orders, :customer_id, algorithm: :concurrently
After the migration the same query should take under 5 ms.
And the invoices page?
Same pattern: the invoices query filters on account_id, which has no index either
<div class="flex w-full max-w-lg flex-col gap-5">
<%# User prompt %>
<div class="flex justify-end">
<p class="max-w-[85%] rounded-2xl rounded-br-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">
Why is the orders page so slow for big customers?
</p>
</div>
<%# Assistant answer: no bubble, full width, actions underneath %>
<article class="flex flex-col gap-3" data-controller="message" data-message-id="5120" aria-label="Assistant reply">
<%# Steps the assistant took (reasoning, tool calls), styled like the Marker component %>
<ul class="flex flex-col gap-1.5 text-sm text-neutral-500 dark:text-neutral-400">
<li class="flex items-center gap-2">
<svg class="size-3.5 shrink-0" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="9" cy="9" r="7.25"></circle><polyline points="9 4.75 9 9 12.25 11.25"></polyline></svg>
Thought for 6 seconds
</li>
<li class="flex items-center gap-2">
<svg class="size-3.5 shrink-0" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15.75 15.75L11.6386 11.6386"></path><path d="M7.75 13.25C10.7875 13.25 13.25 10.7875 13.25 7.75C13.25 4.7125 10.7875 2.25 7.75 2.25C4.7125 2.25 2.25 4.7125 2.25 7.75C2.25 10.7875 4.7125 13.25 7.75 13.25Z"></path></svg>
<span>Ran <code class="rounded bg-neutral-100 px-1 py-0.5 font-mono text-xs text-neutral-700 dark:bg-neutral-800 dark:text-neutral-300">EXPLAIN ANALYZE</code> on the orders query</span>
</li>
</ul>
<%# Copy reads this element, so the text is never duplicated and stays right while a reply streams in %>
<div id="assistant-reply-5120" class="space-y-3 text-sm leading-relaxed text-neutral-800 dark:text-neutral-200">
<p>The query filters on <code class="rounded bg-neutral-100 px-1 py-0.5 font-mono text-xs dark:bg-neutral-800">customer_id</code> without an index, so Postgres scans the whole table. For customers with thousands of orders that takes about 840 ms.</p>
<p>Adding an index fixes it:</p>
<pre class="overflow-x-auto rounded-xl border border-black/10 bg-neutral-50 p-3 font-mono text-xs leading-relaxed text-neutral-800 dark:border-white/10 dark:bg-neutral-900 dark:text-neutral-200"><code>add_index :orders, :customer_id, algorithm: :concurrently</code></pre>
<p>After the migration the same query should take under 5 ms.</p>
</div>
<%# Message actions %>
<div class="-ml-1.5 flex items-center gap-0.5 text-neutral-500 dark:text-neutral-400">
<button type="button" class="flex size-8 pointer-coarse:size-10 items-center justify-center rounded-lg bg-transparent text-neutral-500 transition-all duration-100 ease-in-out select-none hover:bg-neutral-100 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:text-neutral-400 dark:hover:bg-neutral-600/50 dark:hover:text-white dark:focus-visible:outline-neutral-200"
aria-label="Copy reply"
data-controller="clipboard"
data-clipboard-source-value="#assistant-reply-5120"
data-clipboard-success-message-value="Copied"
data-clipboard-tooltip-duration-value="1500">
<span data-clipboard-target="copyContent">
<svg class="size-4" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12.25 5.75H13.75C14.8546 5.75 15.75 6.6454 15.75 7.75V13.75C15.75 14.8546 14.8546 15.75 13.75 15.75H7.75C6.6454 15.75 5.75 14.8546 5.75 13.75V12.25"></path><path d="M10.25 2.25H4.25C3.14543 2.25 2.25 3.14543 2.25 4.25V10.25C2.25 11.3546 3.14543 12.25 4.25 12.25H10.25C11.3546 12.25 12.25 11.3546 12.25 10.25V4.25C12.25 3.14543 11.3546 2.25 10.25 2.25Z"></path></svg>
</span>
<span data-clipboard-target="copiedContent" class="hidden">
<svg class="size-4 text-green-600 dark:text-green-400" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="2.75 9.5 6.5 13.25 15.25 4.5"></polyline></svg>
</span>
</button>
<button type="button" class="flex size-8 pointer-coarse:size-10 items-center justify-center rounded-lg bg-transparent text-neutral-500 transition-all duration-100 ease-in-out select-none hover:bg-neutral-100 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:text-neutral-400 dark:hover:bg-neutral-600/50 dark:hover:text-white dark:focus-visible:outline-neutral-200" aria-label="Regenerate reply">
<svg class="size-4" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M16.2472 9.20422C16.1391 13.1138 12.9357 16.25 8.99998 16.25C5.98368 16.25 3.39809 14.408 2.30579 11.7883"></path><path d="M1.88 14.6949L2.28799 11.75L5.23199 12.157"></path><path d="M1.75281 8.79724C1.86021 4.88694 5.0638 1.75 9 1.75C12.0051 1.75 14.5826 3.5784 15.6819 6.1825"></path><path d="M16.12 3.30505L15.712 6.25L12.768 5.84302"></path></svg>
</button>
<span class="mx-1 h-4 w-px bg-black/10 dark:bg-white/10" aria-hidden="true"></span>
<%# Feedback: aria-pressed toggles, mutually exclusive through data-message-group. %>
<%# Each click dispatches message:toggle with { pressed, group, value, id }: send it to your server from there. %>
<button type="button" class="group flex size-8 pointer-coarse:size-10 items-center justify-center rounded-lg bg-transparent text-neutral-500 transition-all duration-100 ease-in-out select-none hover:bg-neutral-100 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 aria-pressed:text-neutral-900 dark:text-neutral-400 dark:hover:bg-neutral-600/50 dark:hover:text-white dark:focus-visible:outline-neutral-200 dark:aria-pressed:text-white" aria-label="Good reply" aria-pressed="false" data-action="message#toggle" data-message-group="feedback" data-message-value="up">
<svg class="size-4 group-aria-pressed:hidden" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5.25,7.494c0-.48,.173-.944,.486-1.307L10,1.25h0c.854,.427,1.25,1.428,.92,2.324l-1.17,3.176h4.402c1.313,0,2.269,1.243,1.933,2.512l-1.191,4.5c-.232,.877-1.026,1.488-1.933,1.488H7.25c-1.105,0-2-.895-2-2"></path><rect x="1.75" y="6.75" width="3.5" height="8.5" rx="1" ry="1"></rect></svg>
<svg class="hidden size-4 group-aria-pressed:block" viewBox="0 0 18 18" fill="currentColor" aria-hidden="true"><path d="m16.811,9.4546c.2517-.952-.0137-1.9498-.7274-2.6639-.5342-.5345-1.2891-.7901-2.0448-.7901h-3.5683l.8866-2.7534c.3485-1.0525-.067-1.8365-.4846-2.3138-.2918-.3334-.8194-.3118-1.109.0235l-4.0952,4.7416c-.4311.4991-.6683,1.1367-.6683,1.7962v5.756c0,1.5188,1.2312,2.75,2.75,2.75h5.211c1.2476,0,2.3388-.84,2.658-2.046l1.191-4.5h.001Z"></path><path d="m3.5,7.2506v7.5c0,.6904-.5596,1.25-1.25,1.25h0c-.6904,0-1.25-.5596-1.25-1.25v-7.5c0-.6904.5596-1.25,1.25-1.25h0c.6904,0,1.25.5596,1.25,1.25Z"></path></svg>
</button>
<button type="button" class="group flex size-8 pointer-coarse:size-10 items-center justify-center rounded-lg bg-transparent text-neutral-500 transition-all duration-100 ease-in-out select-none hover:bg-neutral-100 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 aria-pressed:text-neutral-900 dark:text-neutral-400 dark:hover:bg-neutral-600/50 dark:hover:text-white dark:focus-visible:outline-neutral-200 dark:aria-pressed:text-white" aria-label="Bad reply" aria-pressed="false" data-action="message#toggle" data-message-group="feedback" data-message-value="down">
<svg class="size-4 group-aria-pressed:hidden" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5.25,10.506c0,.48,.173,.944,.486,1.307l4.264,4.937h0c.854-.427,1.25-1.428,.92-2.324l-1.17-3.176h4.402c1.313,0,2.269-1.243,1.933-2.512l-1.191-4.5c-.232-.877-1.026-1.488-1.933-1.488H7.25c-1.105,0-2,.895-2,2"></path><rect x="1.75" y="2.75" width="3.5" height="8.5" rx="1" ry="1"></rect></svg>
<svg class="hidden size-4 group-aria-pressed:block" viewBox="0 0 18 18" fill="currentColor" aria-hidden="true"><path d="m16.81,8.5467l-1.191-4.5c-.3192-1.206-1.4104-2.046-2.658-2.046h-5.211c-1.5188,0-2.75,1.2312-2.75,2.75v5.756c0,.6595.2372,1.297.6683,1.7962l4.0952,4.7416c.2896.3353.8173.3569,1.109.0235.4177-.4773.8331-1.2614.4846-2.3138l-.8866-2.7534h3.5683c.7557,0,1.5105-.2556,2.0448-.7901.7137-.7141.9791-1.7119.7274-2.6639h-.001Z"></path><path d="m2.25,12.0007h0c-.6904,0-1.25-.5596-1.25-1.25V3.2507c0-.6904.5596-1.25,1.25-1.25h0c.6904,0,1.25.5596,1.25,1.25v7.5c0,.6904-.5596,1.25-1.25,1.25Z"></path></svg>
</button>
</div>
</article>
<%# Streaming state: aria-busy tells screen readers the reply is still being written. %>
<%# Remove aria-busy and the caret when the last chunk arrives (Turbo Stream replace or update). %>
<div class="flex justify-end">
<p class="max-w-[85%] rounded-2xl rounded-br-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">
And the invoices page?
</p>
</div>
<article class="flex flex-col gap-3" aria-label="Assistant reply" aria-busy="true">
<%# A status Marker (role="status" is announced). The shimmer is pure CSS (animate-marker-shimmer) and stays still for reduced motion. %>
<div role="status" class="flex items-center gap-2 text-sm">
<svg class="size-3.5 shrink-0 text-neutral-500 dark:text-neutral-400" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="5.75" y1="6.75" x2="7.75" y2="6.75"></line><line x1="5.75" y1="9.75" x2="12.25" y2="9.75"></line><line x1="5.75" y1="12.75" x2="12.25" y2="12.75"></line><path d="M2.75 14.25V3.75c0-1.105.895-2 2-2h5.586c.265 0 .52.105.707.293l3.914 3.914c.188.188.293.442.293.707v7.586c0 1.105-.895 2-2 2H4.75c-1.105 0-2-.895-2-2Z"></path><path d="M15.16 6.25h-3.41c-.552 0-1-.448-1-1V1.852"></path></svg>
<span class="bg-linear-to-r from-neutral-400 from-35% via-neutral-950 via-50% to-neutral-400 to-65% bg-[length:250%_100%] bg-[position:100%_0] bg-clip-text text-transparent motion-safe:animate-marker-shimmer dark:from-neutral-400 dark:from-40% dark:via-white dark:to-neutral-400 dark:to-60%">Reading invoices_controller.rb…</span>
</div>
<p class="text-sm leading-relaxed text-neutral-800 dark:text-neutral-200">
Same pattern: the invoices query filters on <code class="rounded bg-neutral-100 px-1 py-0.5 font-mono text-xs dark:bg-neutral-800">account_id</code>, which has no index either<span class="ml-0.5 inline-block h-4 w-1.5 translate-y-0.5 animate-pulse rounded-[1px] bg-neutral-900 motion-reduce:animate-none dark:bg-white" aria-hidden="true"></span>
</p>
</article>
</div>
System Messages
Everything in a thread that is not a bubble: line and pill date separators, a system event, and an unread marker.
Looping in Priya for the billing questions.
Olivia added Priya Shah to the conversation
Thanks! Priya, did the refund go through?
It did. The customer should see it within 3 business days.
<div class="flex w-full max-w-md flex-col gap-3">
<%# Date separator %>
<div class="flex items-center gap-3" role="separator" aria-label="Yesterday">
<span class="h-px flex-1 bg-black/10 dark:bg-white/10"></span>
<time datetime="2026-11-08" class="text-xs font-medium text-neutral-500 dark:text-neutral-400">Yesterday</time>
<span class="h-px flex-1 bg-black/10 dark:bg-white/10"></span>
</div>
<div class="flex justify-start">
<p class="max-w-[80%] rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">Looping in Priya for the billing questions.</p>
</div>
<%# System event: centered, quiet, not a bubble %>
<p class="flex items-center justify-center gap-1.5 py-1 text-center text-xs text-neutral-500 dark:text-neutral-400">
<svg class="size-3.5 shrink-0" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 7.2505C10.5188 7.2505 11.75 6.0195 11.75 4.5005C11.75 2.9815 10.5188 1.7505 9 1.7505C7.4812 1.7505 6.25 2.9815 6.25 4.5005C6.25 6.0195 7.4812 7.2505 9 7.2505Z"></path><path d="M17.25 14.7505H12.25"></path><path d="M14.75 12.2505V17.2505"></path><path d="M12.2164 10.677C11.2752 10.102 10.1839 9.7505 8.99999 9.7505C6.44899 9.7505 4.26099 11.2805 3.29099 13.4705C2.92599 14.2955 3.37799 15.2444 4.23799 15.5154C5.46299 15.9014 7.08389 16.2495 8.99999 16.2495C9.22329 16.2495 9.43029 16.2319 9.64399 16.2214"></path></svg>
<span><span class="font-medium text-neutral-700 dark:text-neutral-200">Olivia</span> added <span class="font-medium text-neutral-700 dark:text-neutral-200">Priya Shah</span> to the conversation</span>
</p>
<%# Pill-style date separator %>
<div class="flex justify-center py-1">
<time datetime="2026-11-09" class="rounded-full border border-black/10 bg-white px-2.5 py-0.5 text-xs font-medium text-neutral-600 shadow-xs dark:border-white/10 dark:bg-neutral-800 dark:text-neutral-300">Today</time>
</div>
<div class="flex justify-end">
<p class="max-w-[80%] rounded-2xl rounded-br-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-white dark:bg-white dark:text-neutral-900">Thanks! Priya, did the refund go through?</p>
</div>
<%# Unread marker %>
<div class="flex items-center gap-3" role="separator" aria-label="New messages">
<span class="h-px flex-1 bg-red-500/40"></span>
<span class="text-xs font-medium text-red-600 dark:text-red-400">New messages</span>
<span class="h-px flex-1 bg-red-500/40"></span>
</div>
<div class="flex justify-start">
<p class="max-w-[80%] rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">It did. The customer should see it within 3 business days.</p>
</div>
</div>
Conversation Thread
A complete chat panel. Type a message and press Enter to send (Shift + Enter for a new line; on touch keyboards Enter adds a new line). Hover or press and hold a message to react or reply. The thread follows new messages only while you are at the bottom; otherwise a jump button appears, saying New messages when something arrived. On this page a simulated reply follows after a typing indicator; in your app, messages appended with Turbo Streams get the same treatment.
Olivia Martin
Active now
<%# A complete chat panel with one "message" controller. %>
<%# Real apps: render messages from a partial and deliver new ones with Turbo Streams (turbo_stream.append "messages"). %>
<%# The controller animates appended messages, keeps the typing indicator last and only follows them while you are at the bottom. %>
<%# Mark your own messages with data-message-outgoing. To post to Rails instead of appending in the browser, set data-message-optimistic-value="false" and give the form an action. %>
<% reactions = [["👍", "Thumbs up"], ["❤️", "Heart"], ["😂", "Laughing"], ["😮", "Surprised"], ["🙏", "Thank you"]] %>
<% incoming_bubble = "rounded-2xl rounded-bl-md bg-neutral-100 p-1 text-sm text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100 pointer-coarse:select-none pointer-coarse:[-webkit-touch-callout:none]" %>
<% outgoing_bubble = "rounded-2xl rounded-br-md bg-neutral-900 p-1 text-sm text-white dark:bg-white dark:text-neutral-900 pointer-coarse:select-none pointer-coarse:[-webkit-touch-callout:none]" %>
<% text_classes = "px-2.5 py-1 leading-relaxed text-pretty break-words whitespace-pre-line" %>
<% toolbar_classes = "absolute top-1/2 flex -translate-y-1/2 items-center gap-0.5 opacity-0 transition-opacity duration-150 ease-out group-focus-within/message:opacity-100 group-hover/message:opacity-100 pointer-coarse:sr-only motion-reduce:transition-none" %>
<% tool_classes = "flex size-7 items-center justify-center rounded-full text-neutral-500 transition-colors duration-100 hover:bg-neutral-100 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-neutral-600 dark:text-neutral-400 dark:hover:bg-neutral-800 dark:hover:text-white dark:focus-visible:outline-neutral-200" %>
<%# The ring matches the surface behind the thread, so pills look cut into the bubble edge %>
<% pill_classes = "relative inline-flex items-center gap-1 rounded-full bg-neutral-100 px-2 py-0.5 text-xs font-medium text-neutral-700 tabular-nums ring-3 ring-white after:absolute after:inset-x-0 after:-inset-y-2 transition-[background-color,color] duration-150 ease-out hover:bg-neutral-200 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 aria-pressed:bg-sky-100 aria-pressed:text-sky-800 motion-reduce:transition-none dark:bg-neutral-800 dark:text-neutral-200 dark:ring-neutral-900 dark:hover:bg-neutral-700 dark:focus-visible:outline-neutral-200 dark:aria-pressed:bg-sky-950 dark:aria-pressed:text-sky-200" %>
<% menu_item_classes = "flex w-full items-center justify-between gap-3 rounded-lg px-3 py-2 text-left text-sm text-neutral-900 hover:bg-neutral-100 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-neutral-600 dark:text-neutral-100 dark:hover:bg-neutral-700 dark:focus-visible:outline-neutral-200" %>
<% smiley_icon = capture do %><svg class="size-4" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.25"></circle><path d="M5.75 9.5a2.75 2.75 0 0 0 4.5 0"></path><path d="M6 6.25v.01"></path><path d="M10 6.25v.01"></path></svg><% end %>
<% reply_icon = capture do %><svg class="size-4" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6.25 4.25 2.75 7.75l3.5 3.5"></path><path d="M2.75 7.75h6.5a4 4 0 0 1 4 4v.5"></path></svg><% end %>
<% messages = [
{ id: 3001, author: "Olivia Martin", text: "Hey! Are we still on for the design review at 3?" },
{ id: 3002, author: "You", text: "Yes! I'll bring the new dashboard mockups.", outgoing: true },
{ id: 3003, author: "Olivia Martin", text: "Great. Anything you want me to prepare?" }
] %>
<section
class="flex h-[30rem] w-full max-w-sm flex-col overflow-hidden rounded-2xl border border-black/10 bg-white shadow-sm dark:border-white/10 dark:bg-neutral-900"
aria-label="Conversation with Olivia Martin"
data-controller="message">
<%# Header %>
<header class="flex items-center gap-3 border-b border-black/10 px-4 py-3 dark:border-white/10">
<span class="relative shrink-0">
<img
class="size-9 rounded-full object-cover outline -outline-offset-1 outline-black/10 dark:outline-white/10"
src="https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=160&h=160&fit=crop&crop=face&auto=format&q=80"
alt="" width="36" height="36">
<span class="absolute right-0 bottom-0 size-2.5 rounded-full bg-green-500 ring-2 ring-white dark:ring-neutral-900"></span>
</span>
<div class="min-w-0">
<h3 class="truncate text-sm font-semibold text-neutral-900 dark:text-white">Olivia Martin</h3>
<p class="text-xs text-neutral-500 dark:text-neutral-400">Active now</p>
</div>
</header>
<div class="relative flex min-h-0 flex-1 flex-col">
<%# Messages. role="log" announces new messages to screen readers. Give it an id to target it with Turbo Streams. %>
<div id="messages" class="flex flex-1 flex-col gap-2 overflow-y-auto px-4 py-4" role="log" aria-label="Messages" tabindex="0" data-message-target="list">
<div class="flex justify-center pb-1">
<time datetime="2026-11-09" class="text-xs font-medium text-neutral-500 dark:text-neutral-400">Today</time>
</div>
<% messages.each do |message| %>
<article id="message-<%= message[:id] %>"
class="group/message flex scroll-mt-4 flex-col <%= message[:outgoing] ? "items-end" : "items-start" %>"
data-message-target="item"
data-message-id="<%= message[:id] %>"
data-message-author="<%= message[:author] %>"
<%= "data-message-outgoing" if message[:outgoing] %>>
<div class="relative max-w-[80%]">
<div class="<%= message[:outgoing] ? outgoing_bubble : incoming_bubble %>" data-message-target="bubble">
<span class="sr-only"><%= message[:outgoing] ? "You:" : "#{message[:author]}:" %></span>
<p class="<%= text_classes %>" data-message-slot="text"><%= message[:text] %></p>
</div>
<div class="<%= toolbar_classes %> <%= message[:outgoing] ? "right-full mr-1 flex-row-reverse" : "left-full ml-1" %>">
<button type="button" class="<%= tool_classes %>" aria-label="Add reaction" data-action="message#openReactions"><%= smiley_icon %></button>
<button type="button" class="<%= tool_classes %>" aria-label="Reply" data-action="message#reply"><%= reply_icon %></button>
</div>
</div>
<div class="relative -mt-1.5 flex flex-wrap gap-1 <%= message[:outgoing] ? "justify-end pr-2" : "pl-2" %>" data-message-target="reactions" data-message-hide-when-empty hidden></div>
<% if message[:outgoing] %>
<p class="pt-1 text-xs text-neutral-500 dark:text-neutral-400" data-message-slot="status">Delivered</p>
<% end %>
</article>
<% end %>
<%# Typing indicator: stays last, new messages are inserted above it %>
<div class="flex justify-start" role="status" data-message-target="typing" hidden>
<div class="flex h-9 items-center gap-1 rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 dark:bg-neutral-800">
<span class="sr-only">Olivia is typing</span>
<span class="flex h-3 animate-bounce items-end [animation-duration:1.1s] motion-reduce:animate-none" aria-hidden="true"><span class="size-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500"></span></span>
<span class="flex h-3 animate-bounce items-end [animation-delay:150ms] [animation-duration:1.1s] motion-reduce:animate-none" aria-hidden="true"><span class="size-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500"></span></span>
<span class="flex h-3 animate-bounce items-end [animation-delay:300ms] [animation-duration:1.1s] motion-reduce:animate-none" aria-hidden="true"><span class="size-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500"></span></span>
</div>
</div>
</div>
<%# Shown while you are scrolled away from the bottom. The controller adds data-unread when messages arrive meanwhile. %>
<button type="button"
class="group/jump absolute bottom-3 left-1/2 flex -translate-x-1/2 items-center gap-1.5 rounded-full border border-black/10 bg-white p-2 text-xs font-medium text-neutral-900 shadow-md hover:bg-neutral-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 data-unread:py-1.5 data-unread:pr-3 data-unread:pl-2.5 dark:border-white/10 dark:bg-neutral-800 dark:text-white dark:hover:bg-neutral-700 dark:focus-visible:outline-neutral-200"
aria-label="Jump to latest message"
data-message-target="jump"
data-action="message#jumpToBottom"
hidden>
<svg class="size-3.5 rotate-180" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="9" y1="2.75" x2="9" y2="15.25"></line><polyline points="4.75 7 9 2.75 13.25 7"></polyline></svg>
<span class="hidden group-data-unread/jump:inline" aria-hidden="true">New messages</span>
</button>
</div>
<%# Composer: Enter sends (a new line on touch keyboards), Shift+Enter adds a new line, Escape cancels a reply %>
<form class="border-t border-black/10 p-3 dark:border-white/10" data-action="submit->message#send">
<%# Reply preview, filled by message#reply %>
<div class="relative mb-2 flex items-center gap-2 overflow-hidden rounded-xl bg-neutral-100 py-1.5 pr-1.5 pl-3.5 dark:bg-neutral-800" data-message-target="replyPreview" hidden>
<span class="absolute inset-y-0 left-0 w-1 bg-sky-600 dark:bg-sky-400" aria-hidden="true"></span>
<div class="min-w-0 flex-1 text-xs">
<p class="font-medium text-sky-700 dark:text-sky-300"><span class="sr-only">Replying to </span><span data-message-slot="reply-author"></span></p>
<p class="truncate text-neutral-600 dark:text-neutral-400" data-message-slot="reply-text"></p>
</div>
<button type="button" class="relative flex size-7 shrink-0 items-center justify-center rounded-full text-neutral-500 after:absolute after:-inset-1 hover:bg-black/5 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-neutral-600 dark:text-neutral-400 dark:hover:bg-white/10 dark:hover:text-white dark:focus-visible:outline-neutral-200" aria-label="Cancel reply" data-action="message#cancelReply">
<svg class="size-3.5" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" aria-hidden="true"><path d="m4 4 8 8"></path><path d="m12 4-8 8"></path></svg>
</button>
</div>
<input type="hidden" name="message[reply_to_id]" data-message-target="replyInput">
<div class="flex items-end gap-2 rounded-2xl border border-black/10 bg-neutral-50 py-1.5 pr-1.5 pl-3.5 transition-colors duration-150 focus-within:border-neutral-400 focus-within:bg-white dark:border-white/10 dark:bg-neutral-800 dark:focus-within:border-neutral-500 dark:focus-within:bg-neutral-800">
<label for="thread-message-input" class="sr-only">Message Olivia</label>
<textarea
id="thread-message-input"
name="message[body]"
rows="1"
placeholder="Message Olivia…"
enterkeyhint="send"
autocomplete="off"
class="max-h-36 min-h-8 flex-1 resize-none border-0 bg-transparent px-0 py-1.5 text-base leading-5 text-neutral-900 placeholder:text-neutral-500 focus:ring-0 focus:outline-none sm:text-sm dark:text-white dark:placeholder:text-neutral-400"
data-message-target="input"
data-action="input->message#resize keydown->message#composerKeydown"></textarea>
<button
type="submit"
disabled
class="relative flex size-8 shrink-0 items-center justify-center gap-1.5 rounded-lg border border-neutral-400/30 bg-neutral-800 p-0 text-sm font-medium whitespace-nowrap text-white shadow-sm transition-all duration-100 ease-in-out select-none after:absolute after:-inset-1 hover:bg-neutral-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white dark:text-neutral-800 dark:hover:bg-neutral-100 dark:focus-visible:outline-neutral-200"
aria-label="Send message"
data-message-target="submit">
<svg class="size-4" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="9" y1="2.75" x2="9" y2="15.25"></line><polyline points="4.75 7 9 2.75 13.25 7"></polyline></svg>
</button>
</div>
</form>
<%# Markup for messages sent from the composer. Slots: text, time, status, quote (+ quote-author, quote-text). %>
<template data-message-target="outgoingTemplate">
<article class="group/message flex scroll-mt-4 flex-col items-end" data-message-target="item" data-message-author="You" data-message-outgoing>
<div class="relative max-w-[80%]">
<div class="<%= outgoing_bubble %>" data-message-target="bubble">
<a href="#" class="relative mb-0.5 block overflow-hidden rounded-xl bg-white/10 py-1.5 pr-2.5 pl-3.5 hover:bg-white/15 focus-visible:outline-2 focus-visible:outline-white dark:bg-neutral-900/5 dark:hover:bg-neutral-900/10 dark:focus-visible:outline-neutral-900" data-message-slot="quote" hidden>
<span class="absolute inset-y-0 left-0 w-1 bg-sky-400 dark:bg-sky-600" aria-hidden="true"></span>
<span class="sr-only">Replying to</span>
<span class="block text-xs font-medium text-sky-300 dark:text-sky-700" data-message-slot="quote-author"></span>
<span class="line-clamp-1 text-xs opacity-70" data-message-slot="quote-text"></span>
</a>
<span class="sr-only">You:</span>
<p class="<%= text_classes %>" data-message-slot="text"></p>
</div>
<div class="<%= toolbar_classes %> right-full mr-1 flex-row-reverse">
<button type="button" class="<%= tool_classes %>" aria-label="Add reaction" data-action="message#openReactions"><%= smiley_icon %></button>
<button type="button" class="<%= tool_classes %>" aria-label="Reply" data-action="message#reply"><%= reply_icon %></button>
</div>
</div>
<div class="relative -mt-1.5 flex flex-wrap justify-end gap-1 pr-2" data-message-target="reactions" data-message-hide-when-empty hidden></div>
<p class="pt-1 text-xs text-neutral-500 dark:text-neutral-400" data-message-slot="status">Delivered</p>
</article>
</template>
<template data-message-target="reactionTemplate">
<button type="button" class="<%= pill_classes %>" aria-pressed="true" data-action="message#react">
<span data-message-slot="emoji" class="inline-block"></span>
<span data-message-slot="count">1</span>
</button>
</template>
<%# One menu for every message: emoji row only from the toolbar, everything on press and hold or Shift+F10 %>
<div popover="auto" role="dialog" class="group/menu fixed inset-0 m-0 size-full max-h-none max-w-none touch-none overflow-hidden border-0 bg-transparent p-0 text-inherit not-data-[mode=full]:pointer-events-none data-[mode=full]:bg-black/30 dark:data-[mode=full]:bg-black/60" aria-label="Message actions" data-message-target="menu">
<div class="pointer-events-auto absolute flex flex-col gap-2" data-message-target="menuPanel">
<div class="flex items-center gap-0.5 rounded-full border border-black/10 bg-white p-1 shadow-lg dark:border-white/10 dark:bg-neutral-800" role="group" aria-label="Reactions">
<% reactions.each do |emoji, label| %>
<button type="button" class="flex size-10 items-center justify-center rounded-full text-xl select-none hover:bg-neutral-100 focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-neutral-600 dark:hover:bg-neutral-700 dark:focus-visible:outline-neutral-200" aria-label="React with <%= label %>" data-action="message#react" data-message-emoji-param="<%= emoji %>"><%= emoji %></button>
<% end %>
</div>
<div class="max-h-[40vh] overflow-hidden group-data-[mode=reactions]/menu:hidden" data-message-target="menuPreview"></div>
<div class="w-52 rounded-xl border border-black/10 bg-white p-1 shadow-lg group-data-[mode=reactions]/menu:hidden dark:border-white/10 dark:bg-neutral-800" role="group" aria-label="Actions">
<button type="button" class="<%= menu_item_classes %>" data-action="message#reply">
Reply
<span class="text-neutral-500 dark:text-neutral-400"><%= reply_icon %></span>
</button>
<button type="button" class="<%= menu_item_classes %>" data-action="message#copy">
Copy
<svg class="size-4 text-neutral-500 dark:text-neutral-400" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12.25 5.75H13.75C14.8546 5.75 15.75 6.6454 15.75 7.75V13.75C15.75 14.8546 14.8546 15.75 13.75 15.75H7.75C6.6454 15.75 5.75 14.8546 5.75 13.75V12.25"></path><path d="M10.25 2.25H4.25C3.14543 2.25 2.25 3.14543 2.25 4.25V10.25C2.25 11.3546 3.14543 12.25 4.25 12.25H10.25C11.3546 12.25 12.25 11.3546 12.25 10.25V4.25C12.25 3.14543 11.3546 2.25 10.25 2.25Z"></path></svg>
</button>
</div>
</div>
</div>
</section>
Bubble Variants
Six surfaces for different roles: solid for your messages, muted for everyone else, tinted to highlight, outline for bots and receipts, ghost for long AI replies and destructive for errors. Color is never the only signal, so the error keeps its reason in the text. Bubbles can also be links and buttons, such as a notification you can open or suggested replies; they use real <a> and <button> elements, so they get the right role and keyboard support. With the ViewComponent, pass variant:.
Solid: the default for your own messages.
Muted: the default for everyone else.
Pinned: tinted bubbles stand out from the conversation, like a mention or a pinned note.
Outline: a quieter surface for bots and receipts.
Ghost: no bubble. Long assistant replies read like a document instead of a chat bubble.
Couldn't send: the file is larger than 25 MB.
<%# Six surfaces for different roles. Color is never the only signal: pair it with text, alignment or an icon. %>
<div class="flex w-full max-w-md flex-col gap-3">
<%# Solid: your own messages %>
<div class="flex justify-end">
<p class="max-w-[80%] rounded-2xl rounded-br-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-white dark:bg-white dark:text-neutral-900">Solid: the default for your own messages.</p>
</div>
<%# Muted: other people %>
<div class="flex justify-start">
<p class="max-w-[80%] rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">Muted: the default for everyone else.</p>
</div>
<%# Tinted: highlight without shouting (pinned, mentions, the assistant) %>
<div class="flex justify-start">
<p class="max-w-[80%] rounded-2xl rounded-bl-md bg-red-50 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-red-950/60 dark:text-neutral-100">
<span class="font-medium">Pinned:</span> tinted bubbles stand out from the conversation, like a mention or a pinned note.
</p>
</div>
<%# Outline: bots, receipts, quoted content %>
<div class="flex justify-start">
<p class="max-w-[80%] rounded-2xl rounded-bl-md border border-black/10 bg-white px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:border-white/10 dark:bg-neutral-900 dark:text-neutral-100">Outline: a quieter surface for bots and receipts.</p>
</div>
<%# Ghost: no bubble at all, for long AI replies %>
<div class="flex justify-start">
<p class="text-sm leading-relaxed text-pretty text-neutral-900 dark:text-neutral-100">Ghost: no bubble. Long assistant replies read like a document instead of a chat bubble.</p>
</div>
<%# Destructive: the error is in the text, not only in the color %>
<div class="flex justify-end">
<p class="flex max-w-[80%] items-start gap-2 rounded-2xl rounded-br-md bg-red-50 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-red-800 dark:bg-red-500/15 dark:text-red-200">
<svg class="mt-0.5 size-4 shrink-0" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 16.25C13.0041 16.25 16.25 13.004 16.25 9C16.25 4.996 13.0041 1.75 9 1.75C4.9959 1.75 1.75 4.996 1.75 9C1.75 13.004 4.9959 16.25 9 16.25Z"></path><path d="M9 5.431V9.5"></path><path d="M9 13.417C8.448 13.417 8 12.968 8 12.417C8 11.866 8.448 11.417 9 11.417C9.552 11.417 10 11.866 10 12.417C10 12.968 9.552 13.417 9 13.417Z" fill="currentColor" stroke="none"></path></svg>
<span>Couldn't send: the file is larger than 25 MB.</span>
</p>
</div>
<%# Clickable bubbles: real <a> and <button> elements, so they get the right role, focus and keyboard support. %>
<%# Suggested replies are outline bubbles on your side; the accessible name is the bubble text. %>
<div class="flex justify-start">
<a href="#" class="max-w-[80%] rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 transition-colors duration-150 hover:bg-neutral-200 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 dark:bg-neutral-800 dark:text-neutral-100 dark:hover:bg-neutral-700 dark:focus-visible:outline-neutral-200">
Invoice #1042 is ready. <span class="font-medium underline underline-offset-2">View invoice</span>
</a>
</div>
<div class="flex flex-wrap justify-end gap-1.5" role="group" aria-label="Suggested replies">
<% ["Thanks!", "Can you resend it?", "Pay now"].each do |reply| %>
<button type="button" class="rounded-2xl border border-black/10 bg-white px-3.5 py-1.5 text-sm text-neutral-900 transition-colors duration-150 hover:bg-neutral-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 dark:border-white/10 dark:bg-neutral-900 dark:text-neutral-100 dark:hover:bg-neutral-800 dark:focus-visible:outline-neutral-200"><%= reply %></button>
<% end %>
</div>
</div>
Long Message
Long messages are clamped to six lines with a Show more button. The button uses aria-controls and aria-expanded, and collapsing scrolls the message back into view if its start went off screen.
Perfect, thanks for writing it up.
<%# Long messages are clamped to six lines with a Show more button. The button names what it controls (aria-controls) and reports its state (aria-expanded). %>
<%# Needs the message controller for message#expand. %>
<div class="flex w-full max-w-md flex-col gap-2" data-controller="message">
<div class="flex flex-col items-start">
<div class="max-w-[80%] rounded-2xl rounded-bl-md bg-neutral-100 p-1 text-sm text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">
<p id="message-4120-text" class="line-clamp-6 px-2.5 py-1 leading-relaxed text-pretty break-words data-expanded:line-clamp-none">
Quick recap of the planning call so nobody has to rewatch it. We're moving the launch to Thursday the 20th because the payments provider needs two more days to approve the new pricing tiers. Marketing keeps the announcement draft as is, but the screenshots need the new plan names. Support gets a short FAQ by Tuesday covering the migration from the legacy plans, what happens to annual subscribers, and how refunds work during the first week. Engineering freezes the release branch on Monday at noon; anything that misses the freeze ships the week after. I'll send the updated timeline to the whole team once the provider confirms.
</p>
<button type="button"
class="group/expand flex items-center gap-1 rounded-lg px-2.5 pt-0.5 pb-1 text-xs font-medium text-neutral-600 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-neutral-600 dark:text-neutral-300 dark:hover:text-white dark:focus-visible:outline-neutral-200"
aria-controls="message-4120-text"
aria-expanded="false"
data-action="message#expand">
<span class="group-aria-expanded/expand:hidden">Show more</span>
<span class="hidden group-aria-expanded/expand:inline">Show less</span>
<svg class="size-3 transition-transform duration-150 group-aria-expanded/expand:rotate-180 motion-reduce:transition-none" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4.5 6.75 9 11.25l4.5-4.5"></path></svg>
</button>
</div>
</div>
<div class="flex justify-end">
<p class="max-w-[80%] rounded-2xl rounded-br-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-white dark:bg-white dark:text-neutral-900">Perfect, thanks for writing it up.</p>
</div>
</div>
Attachment States
A scrolling, snapping row of photos with an edge fade (focusable, so keyboard users can scroll it), an upload with a real progress bar and a cancel button, a failed upload that states why, and a card whose title link covers the whole card while the download button stays clickable.
4 photos
<% file_icon = capture do %><svg class="size-5" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="5.75" y1="6.75" x2="7.75" y2="6.75"></line><line x1="5.75" y1="9.75" x2="12.25" y2="9.75"></line><line x1="5.75" y1="12.75" x2="12.25" y2="12.75"></line><path d="M2.75 14.25V3.75c0-1.105.895-2 2-2h5.586c.265 0 .52.105.707.293l3.914 3.914c.188.188.293.442.293.707v7.586c0 1.105-.895 2-2 2H4.75c-1.105 0-2-.895-2-2Z"></path><path d="M15.16 6.25h-3.41c-.552 0-1-.448-1-1V1.852"></path></svg><% end %>
<% icon_button = "relative z-10 flex size-8 shrink-0 items-center justify-center rounded-full text-neutral-500 transition-colors duration-150 hover:bg-neutral-100 hover:text-neutral-900 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-neutral-600 dark:text-neutral-400 dark:hover:bg-neutral-800 dark:hover:text-white dark:focus-visible:outline-neutral-200" %>
<% card = "relative flex w-72 max-w-[80%] items-center gap-3 rounded-2xl border p-2.5 shadow-xs" %>
<% photos = [
["photo-1501785888041-af3ef285b470", "A lake surrounded by mountains"],
["photo-1470071459604-3b5ec3a7fe05", "Fog over a green valley"],
["photo-1441974231531-c6227db76b6e", "Sunlight through a forest"],
["photo-1500534314209-a25ddb2bd429", "A path through tall grass"]
] %>
<div class="flex w-full max-w-md flex-col gap-4">
<%# Image group: a horizontally scrolling, snapping row. An edge only fades while there is more to scroll that way, %>
<%# using the Scroll Area controller and the scroll-fade-x utility from the Rails Blocks installation CSS. %>
<%# The row is focusable and labelled so keyboard users can scroll it with the arrow keys; the outline sits on the wrapper so the fade never hides it. %>
<div class="flex flex-col items-end gap-1">
<div class="max-w-[80%] rounded-2xl rounded-br-md has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-neutral-600 dark:has-focus-visible:outline-neutral-200"
data-controller="scroll-area" data-scroll-area-target="root">
<div class="scroll-fade-x flex snap-x snap-mandatory gap-1.5 overflow-x-auto overscroll-x-contain rounded-[inherit] outline-none [scrollbar-width:none]"
role="group" aria-label="4 photos" tabindex="0"
data-scroll-area-target="viewport" data-action="scroll->scroll-area#onViewportScroll">
<% photos.each do |id, alt| %>
<img class="aspect-[3/4] w-32 shrink-0 snap-start rounded-xl bg-neutral-200 object-cover dark:bg-neutral-700" src="https://images.unsplash.com/<%= id %>?w=256&h=340&fit=crop&auto=format&q=80" alt="<%= alt %>" width="128" height="170" loading="lazy">
<% end %>
</div>
</div>
<p class="text-xs text-neutral-500 dark:text-neutral-400">4 photos</p>
</div>
<%# Uploading: progress with a real progressbar, the title shimmers, and the upload can be cancelled. %>
<div class="flex flex-col items-end gap-1">
<div class="<%= card %> border-black/10 bg-white dark:border-white/10 dark:bg-neutral-900">
<span class="flex size-10 shrink-0 items-center justify-center rounded-md bg-neutral-100 text-neutral-500 dark:bg-neutral-800 dark:text-neutral-400"><%= file_icon %></span>
<span class="min-w-0 flex-1">
<span class="block truncate text-sm font-medium text-neutral-900 motion-safe:animate-pulse dark:text-neutral-100">q3-board-deck.pdf</span>
<span class="mt-1.5 block h-1 overflow-hidden rounded-full bg-neutral-200 dark:bg-neutral-700" role="progressbar" aria-label="Uploading q3-board-deck.pdf" aria-valuemin="0" aria-valuemax="100" aria-valuenow="64">
<span class="block h-full w-[64%] rounded-full bg-neutral-900 transition-[width] duration-300 dark:bg-white"></span>
</span>
<span class="mt-1 block text-xs tabular-nums text-neutral-500 dark:text-neutral-400">Uploading · 3.1 of 4.8 MB</span>
</span>
<button type="button" class="<%= icon_button %>" aria-label="Cancel upload">
<svg class="size-3.5" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" aria-hidden="true"><path d="m4 4 8 8"></path><path d="m12 4-8 8"></path></svg>
</button>
</div>
</div>
<%# Failed: destructive treatment, and the reason is written out so color is not the only signal. %>
<div class="flex flex-col items-end gap-1">
<div class="<%= card %> border-red-600/20 bg-red-50/50 dark:border-red-400/20 dark:bg-red-500/5">
<span class="flex size-10 shrink-0 items-center justify-center rounded-md bg-red-50 text-red-600 dark:bg-red-500/10 dark:text-red-400"><%= file_icon %></span>
<span class="min-w-0 flex-1">
<span class="block truncate text-sm font-medium text-neutral-900 dark:text-neutral-100">raw-footage.mov</span>
<span class="block text-xs text-red-700 dark:text-red-300">Too large: 1.2 GB, the limit is 500 MB</span>
</span>
<button type="button" class="<%= icon_button %>" aria-label="Retry upload of raw-footage.mov">
<svg class="size-4" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M16.2472 9.20422C16.1391 13.1138 12.9357 16.25 8.99998 16.25C5.98368 16.25 3.39809 14.408 2.30579 11.7883"></path><path d="M1.88 14.6949L2.28799 11.75L5.23199 12.157"></path><path d="M1.75281 8.79724C1.86021 4.88694 5.0638 1.75 9 1.75C12.0051 1.75 14.5826 3.5784 15.6819 6.1825"></path><path d="M16.12 3.30505L15.712 6.25L12.768 5.84302"></path></svg>
</button>
</div>
</div>
<%# Card with a trigger: the title link stretches over the whole card (after:inset-0), while the download button stays clickable on top. %>
<div class="flex flex-col items-start gap-1">
<div class="<%= card %> border-black/10 bg-white transition-colors duration-150 has-[a:hover]:bg-neutral-50 dark:border-white/10 dark:bg-neutral-900 dark:has-[a:hover]:bg-neutral-800">
<span class="flex size-10 shrink-0 items-center justify-center rounded-md bg-red-50 text-red-600 dark:bg-red-500/10 dark:text-red-400"><%= file_icon %></span>
<span class="min-w-0 flex-1">
<a href="#" class="block truncate text-sm font-medium text-neutral-900 after:absolute after:inset-0 after:rounded-2xl focus-visible:outline-none focus-visible:after:outline-2 focus-visible:after:outline-offset-2 focus-visible:after:outline-neutral-600 dark:text-neutral-100 dark:focus-visible:after:outline-neutral-200">sales-dashboard.pdf</a>
<span class="block text-xs text-neutral-500 dark:text-neutral-400">PDF · 2.4 MB</span>
</span>
<a href="#" download class="<%= icon_button %>" aria-label="Download sales-dashboard.pdf">
<svg class="size-4" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15.25 11.75v1.5c0 1.105-.895 2-2 2H4.75c-1.105 0-2-.895-2-2v-1.5"></path><polyline points="5.5 6.75 9 10.25 12.5 6.75"></polyline><line x1="9" y1="10.25" x2="9" y2="2.75"></line></svg>
</a>
</div>
</div>
</div>
AI Chat
Ask something. Your prompt is marked data-message-anchor, so it scrolls near the top with a peek of the previous answer, and the reply streams in below it instead of pushing it away. Scroll up while it streams and the thread stays where you put it; the jump button brings you back. On this page the replies are canned; in your app, stream them with Turbo Streams.
What does N+1 mean in Rails?
An N+1 happens when you load a list of records with one query, then run one more query for each record to load an association. Fifty posts become fifty-one queries.
Preload the association to collapse them into two queries:
Post.includes(:author).limit(50)
<%# An AI chat. Each prompt is marked data-message-anchor: when it is appended, the thread scrolls it near the top %>
<%# (keeping a peek of the previous answer) and the reply streams in below without pushing it away. %>
<%# Scroll up while a reply streams and the thread stays put; a jump button brings you back. %>
<%# Real apps: append the prompt and an empty reply with Turbo Streams, then stream the reply with turbo_stream.replace / update. %>
<% prompt_classes = "max-w-[85%] rounded-2xl rounded-br-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words whitespace-pre-line text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100" %>
<section
class="flex h-[32rem] w-full max-w-lg flex-col overflow-hidden rounded-2xl border border-black/10 bg-white shadow-sm dark:border-white/10 dark:bg-neutral-900"
aria-label="Chat with the assistant"
data-controller="message">
<div class="relative flex min-h-0 flex-1 flex-col">
<div id="ai-messages" class="flex flex-1 flex-col gap-6 overflow-y-auto px-5 py-5" role="log" aria-label="Messages" tabindex="0" data-message-target="list">
<div class="flex justify-end" data-message-outgoing data-message-anchor>
<p class="<%= prompt_classes %>">What does N+1 mean in Rails?</p>
</div>
<article class="flex flex-col gap-2" aria-label="Assistant reply">
<div class="space-y-3 text-sm leading-relaxed text-neutral-800 dark:text-neutral-200">
<p>An N+1 happens when you load a list of records with one query, then run one more query for each record to load an association. Fifty posts become fifty-one queries.</p>
<p>Preload the association to collapse them into two queries:</p>
<pre class="overflow-x-auto rounded-xl border border-black/10 bg-neutral-50 p-3 font-mono text-xs leading-relaxed text-neutral-800 dark:border-white/10 dark:bg-neutral-950 dark:text-neutral-200"><code>Post.includes(:author).limit(50)</code></pre>
</div>
</article>
</div>
<button type="button"
class="group/jump absolute bottom-3 left-1/2 flex -translate-x-1/2 items-center gap-1.5 rounded-full border border-black/10 bg-white p-2 text-xs font-medium text-neutral-900 shadow-md hover:bg-neutral-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 data-unread:py-1.5 data-unread:pr-3 data-unread:pl-2.5 dark:border-white/10 dark:bg-neutral-800 dark:text-white dark:hover:bg-neutral-700 dark:focus-visible:outline-neutral-200"
aria-label="Jump to latest message"
data-message-target="jump"
data-action="message#jumpToBottom"
hidden>
<svg class="size-3.5 rotate-180" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="9" y1="2.75" x2="9" y2="15.25"></line><polyline points="4.75 7 9 2.75 13.25 7"></polyline></svg>
<span class="hidden group-data-unread/jump:inline" aria-hidden="true">New messages</span>
</button>
</div>
<form class="p-3" data-action="submit->message#send">
<div class="flex items-end gap-2 rounded-2xl border border-black/10 bg-neutral-50 py-1.5 pr-1.5 pl-3.5 transition-colors duration-150 focus-within:border-neutral-400 focus-within:bg-white dark:border-white/10 dark:bg-neutral-800 dark:focus-within:border-neutral-500 dark:focus-within:bg-neutral-800">
<label for="ai-chat-input" class="sr-only">Ask the assistant</label>
<textarea
id="ai-chat-input"
name="prompt"
rows="1"
placeholder="Ask anything…"
enterkeyhint="send"
autocomplete="off"
class="max-h-36 min-h-8 flex-1 resize-none border-0 bg-transparent px-0 py-1.5 text-base leading-5 text-neutral-900 placeholder:text-neutral-500 focus:ring-0 focus:outline-none sm:text-sm dark:text-white dark:placeholder:text-neutral-400"
data-message-target="input"
data-action="input->message#resize keydown->message#composerKeydown"></textarea>
<button
type="submit"
disabled
class="relative flex size-8 shrink-0 items-center justify-center rounded-lg bg-neutral-800 text-white shadow-sm transition-colors duration-100 select-none after:absolute after:-inset-1 hover:bg-neutral-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white dark:text-neutral-800 dark:hover:bg-neutral-100 dark:focus-visible:outline-neutral-200"
aria-label="Send"
data-message-target="submit">
<svg class="size-4" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="9" y1="2.75" x2="9" y2="15.25"></line><polyline points="4.75 7 9 2.75 13.25 7"></polyline></svg>
</button>
</div>
</form>
<%# Each prompt starts a turn: data-message-anchor scrolls it near the top when it is appended. %>
<template data-message-target="outgoingTemplate">
<div class="flex justify-end" data-message-outgoing data-message-anchor>
<p class="<%= prompt_classes %>" data-message-slot="text"></p>
</div>
</template>
</section>
Tail Styles
Four ways to show which side a bubble comes from: a tightened corner (the default, works with every variant), an iMessage-style curved tail growing out of the rounded corner, a pointed wedge with a softened tip, or no tail at all. Curved and wedge tails sit on the last bubble of a group and are small SVGs filled with the bubble's color; the curved one traces the corner instead of overlapping it, so translucent bubbles stay even. With the ViewComponent, pass tail: :corner, :curved, :wedge or :none, and grouped messages put the tail on the right bubble for you.
Corner
Are we still on for 3?
Yes, see you there.
Curved
Are we still on for 3?
Yes, see you there.
Wedge
Are we still on for 3?
Yes, see you there.
None
Are we still on for 3?
Yes, see you there.
<%# Four tail styles. Pick one per app and use it everywhere. %>
<%# The curved and wedge tails are small SVGs filled with currentColor: give them the bubble's background as text color. %>
<%# The bubble needs `relative` and keeps its rounded corners. Both tails sit on the last bubble of a group only. %>
<%# Curved keeps the bubble's rounded corner and grows out of it, like iMessage. The path traces the corner (16px radius) so it never overlaps the bubble, which keeps translucent colors even. %>
<% curved_tail = capture do %><path d="M6 4C6 12 4.6 17 0 20C3.8 20.3 7.6 19.4 10.4 17.5C12.8 19.2 15.8 20 22 20A17 17 0 0 1 6 4Z"></path><% end %>
<%# Wedge: a straighter, pointed tail with a rounded tip. It also traces the rounded corner, so the bubble keeps it. %>
<% wedge_tail = capture do %><path d="M10 0C10 7 8 11 3 13.4C1 14.3 1.4 16 3.4 16H26A17 17 0 0 1 10 0Z"></path><% end %>
<% label_classes = "text-xs font-medium text-neutral-500 dark:text-neutral-400" %>
<div class="grid w-full max-w-2xl gap-x-10 gap-y-8 sm:grid-cols-2">
<%# Corner: the corner nearest the sender is tightened. Works with every variant, including outline. %>
<div class="flex flex-col gap-1.5">
<p class="<%= label_classes %>">Corner</p>
<div class="flex justify-start">
<p class="max-w-[80%] rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">Are we still on for 3?</p>
</div>
<div class="flex justify-end">
<p class="max-w-[80%] rounded-2xl rounded-br-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-white dark:bg-white dark:text-neutral-900">Yes, see you there.</p>
</div>
</div>
<%# Curved: an iMessage-style hook growing out of the rounded bottom corner. %>
<div class="flex flex-col gap-1.5">
<p class="<%= label_classes %>">Curved</p>
<div class="flex justify-start pl-2">
<p class="relative max-w-[80%] rounded-2xl bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">
Are we still on for 3?
<svg class="absolute bottom-0 -left-1.5 h-5 w-[22px] text-neutral-100 dark:text-neutral-800" viewBox="0 0 22 20" fill="currentColor" aria-hidden="true"><%= curved_tail %></svg>
</p>
</div>
<div class="flex justify-end pr-2">
<p class="relative max-w-[80%] rounded-2xl bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-white dark:bg-white dark:text-neutral-900">
Yes, see you there.
<svg class="absolute -right-1.5 bottom-0 h-5 w-[22px] -scale-x-100 text-neutral-900 dark:text-white" viewBox="0 0 22 20" fill="currentColor" aria-hidden="true"><%= curved_tail %></svg>
</p>
</div>
</div>
<%# Wedge: a pointed tail with a softened tip, growing out of the rounded bottom corner. %>
<div class="flex flex-col gap-1.5">
<p class="<%= label_classes %>">Wedge</p>
<div class="flex justify-start pl-3">
<p class="relative max-w-[80%] rounded-2xl bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">
Are we still on for 3?
<svg class="absolute bottom-0 -left-2.5 h-4 w-[26px] text-neutral-100 dark:text-neutral-800" viewBox="0 0 26 16" fill="currentColor" aria-hidden="true"><%= wedge_tail %></svg>
</p>
</div>
<div class="flex justify-end pr-3">
<p class="relative max-w-[80%] rounded-2xl bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-white dark:bg-white dark:text-neutral-900">
Yes, see you there.
<svg class="absolute -right-2.5 bottom-0 h-4 w-[26px] -scale-x-100 text-neutral-900 dark:text-white" viewBox="0 0 26 16" fill="currentColor" aria-hidden="true"><%= wedge_tail %></svg>
</p>
</div>
</div>
<%# None: fully rounded. Clean in group chats, where avatars and names already show who is speaking. %>
<div class="flex flex-col gap-1.5">
<p class="<%= label_classes %>">None</p>
<div class="flex justify-start">
<p class="max-w-[80%] rounded-2xl bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">Are we still on for 3?</p>
</div>
<div class="flex justify-end">
<p class="max-w-[80%] rounded-2xl bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-white dark:bg-white dark:text-neutral-900">Yes, see you there.</p>
</div>
</div>
</div>
Message Details
The small things people expect from a messaging app: the time and read receipt inside the bubble (an invisible spacer keeps them off the text), an edited label, a deleted message that keeps its place so replies still make sense, emoji-only messages shown large without a bubble and read once by screen readers, and a link preview card.
Did you get the photos from Saturday?
Yes! The one at the lake is my favorite. Read
Dinner is at 7:30, not 7.
Edited ·
This message was deleted
🎉❤️
<%# Details people expect from a messaging app: time inside the bubble, edited and deleted messages, big emoji and link previews. %>
<% double_check = capture do %><svg class="size-3.5 shrink-0" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points=".75 9.5 4.5 14.25 12.5 4"></polyline><polyline points="8.506 13.308 9.25 14.25 17.25 4"></polyline></svg><% end %>
<div class="flex w-full max-w-md flex-col gap-2">
<%# Time inside the bubble: an invisible spacer at the end of the text reserves room, %>
<%# so the time sits on the last line when it fits and wraps below it when it doesn't. %>
<div class="flex justify-start">
<p class="relative max-w-[80%] rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">
Did you get the photos from Saturday?
<span class="inline-block w-12" aria-hidden="true"></span>
<time datetime="2026-11-09T10:12" class="absolute right-3 bottom-1.5 text-[11px] text-neutral-500 tabular-nums dark:text-neutral-400">10:12</time>
</p>
</div>
<%# Outgoing with time and read receipt inside the bubble. The status is spelled out for screen readers. %>
<div class="flex justify-end">
<p class="relative max-w-[80%] rounded-2xl rounded-br-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-white dark:bg-white dark:text-neutral-900">
Yes! The one at the lake is my favorite.
<span class="inline-block w-16" aria-hidden="true"></span>
<span class="absolute right-3 bottom-1.5 flex items-center gap-1 text-[11px] text-white/60 tabular-nums dark:text-neutral-500">
<time datetime="2026-11-09T10:14">10:14</time>
<span class="text-sky-400 dark:text-sky-600"><%= double_check %></span>
<span class="sr-only">Read</span>
</span>
</p>
</div>
<%# Edited: a quiet label next to the time %>
<div class="flex flex-col items-end gap-1">
<p class="max-w-[80%] rounded-2xl rounded-br-md bg-neutral-900 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-white dark:bg-white dark:text-neutral-900">Dinner is at 7:30, not 7.</p>
<p class="text-xs text-neutral-500 dark:text-neutral-400">Edited · <time datetime="2026-11-09T10:16">10:16</time></p>
</div>
<%# Deleted: keeps its place in the thread so replies still make sense, without the content %>
<div class="flex justify-start">
<p class="flex max-w-[80%] items-center gap-1.5 rounded-2xl rounded-bl-md border border-dashed border-black/15 px-3.5 py-2 text-sm text-neutral-500 italic dark:border-white/15 dark:text-neutral-400">
<svg class="size-3.5 shrink-0" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="9" cy="9" r="7.25"></circle><path d="M3.87 14.13 14.13 3.87"></path></svg>
This message was deleted
</p>
</div>
<%# Emoji-only messages: no bubble, larger. role="img" with a label so the emoji are read once, meaningfully. %>
<div class="flex justify-end">
<p class="text-4xl leading-none select-none" role="img" aria-label="Party popper, red heart">🎉❤️</p>
</div>
<%# Link preview: the whole card is one link to the page; the message text keeps the raw URL. %>
<%# The image is the page's og:image (1200x630), fetched and cached by your server when the message is saved. %>
<div class="flex flex-col items-start gap-1">
<p class="max-w-[80%] rounded-2xl rounded-bl-md bg-neutral-100 px-3.5 py-2 text-sm leading-relaxed text-pretty break-words text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100">
This is the one I mentioned:
<a href="https://railsblocks.com" class="font-medium underline underline-offset-2 hover:no-underline">railsblocks.com</a>
</p>
<a href="https://railsblocks.com" class="group block w-72 max-w-[80%] overflow-hidden rounded-2xl rounded-l-md border border-black/10 bg-white transition-colors duration-150 hover:bg-neutral-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-600 dark:border-white/10 dark:bg-neutral-900 dark:hover:bg-neutral-800 dark:focus-visible:outline-neutral-200">
<img class="aspect-[1.91/1] w-full bg-neutral-200 object-cover dark:bg-neutral-700" src="https://railsblocks.com/assets/opengraph-eb5310cb5b513a6a434977993abdaa571cb7060821e56a1a482eaa5435b6aef4.png" alt="" width="1200" height="630" loading="lazy">
<span class="block px-3 py-2.5">
<span class="block text-xs text-neutral-500 dark:text-neutral-400">railsblocks.com</span>
<span class="mt-0.5 block truncate text-sm font-medium text-neutral-900 dark:text-neutral-100">Rails Blocks: UI components for Ruby on Rails</span>
<span class="mt-0.5 line-clamp-2 block text-xs text-neutral-500 dark:text-neutral-400">Copy-paste Tailwind and Stimulus components, ViewComponents and partials for your Rails app.</span>
</span>
</a>
</div>
</div>
Configuration
The controller clones new messages and reactions from <template> elements, so every class stays in your markup.
Controller Values
Targets
Actions and Events
Keyboard and Touch
Scroll Behavior
The thread never moves the reader against their intent. It follows new messages, and replies that grow while they stream in, only while the reader is at the bottom and not selecting text or moving through the thread with the keyboard. Otherwise it keeps the message they are reading in place when anything changes above or inside the view: older messages loaded above, images, code blocks, re-rendered messages. This works the same in every browser, including Safari, which has no native scroll anchoring.
data-message-anchoron an appended row (the user's prompt in an AI chat) scrolls it near the top with a peek of the previous message, and the answer grows into the screen below it.data-message-starton any row (an unread marker, the last user message) makes the thread open there instead of at the very bottom.- The jump button appears whenever the reader is away from the bottom and gets
data-unreadwhen messages arrive meanwhile.
Turbo Streams
Give the list an id, set data-message-optimistic-value="false" so the form submits to Rails, and broadcast new messages with broadcast_append_to conversation, target: "messages". Stream AI replies with broadcast_replace_to on the reply's row: replacements are never animated, and the thread follows them only while the reader is at the bottom. Render the current user's messages with data-message-outgoing (direction: :outgoing in the ViewComponent) so they always scroll into view and don't hide the typing indicator. Save reactions and actions from the message:react and message:action events.
Styling Hooks
The ViewComponent and the partial mark every part with data-slot, and the row with data-direction, data-position and data-variant. Restyle any part from the outside without copying the component, for example **:data-[slot=message-bubble]:rounded-3xl on the thread rounds every bubble, and **:data-[direction=outgoing]:**:data-[slot=message-bubble]:bg-red-600 recolors only your own messages.