feat: chat reactions

This commit is contained in:
gosangam
2026-08-30 01:51:52 +05:30
parent 0f382ed885
commit 8c7afe596d
19 changed files with 662 additions and 53 deletions
+10 -1
View File
@@ -37,6 +37,7 @@ export function ChatComposer({
replyTo,
onCancelReply,
onSend,
onTyping,
conversationId,
disabled = false,
placeholder = "Message…",
@@ -45,6 +46,8 @@ export function ChatComposer({
conversationId: string;
replyTo: ChatMessage | null;
onCancelReply: () => void;
/** Called on each keystroke; throttled by the caller. */
onTyping?: () => void;
onSend: (
body: string,
replyToId?: string,
@@ -257,7 +260,13 @@ export function ChatComposer({
value={value}
disabled={disabled}
placeholder={placeholder}
onChange={(e) => setValue(e.target.value)}
onChange={(e) => {
setValue(e.target.value);
// Fired on every keystroke; the handler throttles itself, so the
// thread hears "still typing" every few seconds rather than per
// character.
onTyping?.();
}}
onKeyDown={(e) => {
// Enter sends on a physical keyboard; Shift+Enter makes a newline.
// On touch keyboards Enter must insert a newline instead — there is
+9 -1
View File
@@ -18,6 +18,7 @@ import { LinkPreviewCard } from "@/components/chat/link-preview-card";
import { MediaGrid } from "@/components/chat/media-grid";
import { MediaLightbox } from "@/components/chat/media-lightbox";
import { QuoteCard } from "@/components/chat/quote-card";
import { cn } from "@/lib/utils";
import { SharedPostCard } from "@/components/chat/shared-post-card";
import { attachmentUrl, type Attachment } from "@/lib/chat";
@@ -52,7 +53,14 @@ export function MessageAttachments({
return (
<>
<div className="mt-1 flex flex-col gap-1.5">
<div
className={cn(
"flex flex-col gap-1.5",
// Separates attachments from body text above them. A shared post
// leads its bubble, so there is nothing to separate from.
attachments.some((a) => a.kind === "entity") ? undefined : "mt-1",
)}
>
{media.length > 0 && (
<MediaGrid items={media} onOpen={(i) => setLightboxAt(i)} />
)}
+30 -2
View File
@@ -40,16 +40,23 @@ const CLAIM_PX = 10;
const LONG_PRESS_MS = 450;
/** Movement that cancels a long press — a drag is not a hold. */
const LONG_PRESS_SLOP_PX = 8;
/** Longest gap between two taps still read as a double tap. */
const DOUBLE_TAP_MS = 300;
/** How far the second tap may land from the first. */
const DOUBLE_TAP_SLOP_PX = 24;
export function MessageGestures({
onReply,
onMenu,
onDoubleTap,
disabled = false,
children,
}: {
onReply: () => void;
/** Opens the context menu at the given viewport point. */
onMenu: (point: { x: number; y: number }) => void;
/** Two quick taps in the same spot — sends a heart. */
onDoubleTap?: () => void;
disabled?: boolean;
children: React.ReactNode;
}) {
@@ -61,6 +68,8 @@ export function MessageGestures({
const holdTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
// Set once a long press fires, so the release doesn't also trigger a reply.
const consumed = useRef(false);
// When and where the last tap landed, for pairing it with the next one.
const lastTap = useRef<{ t: number; x: number; y: number } | null>(null);
const cancelHold = useCallback(() => {
if (holdTimer.current) {
@@ -124,10 +133,29 @@ export function MessageGestures({
setOffset(Math.max(0, Math.min(travel, MAX_PX)));
};
const onPointerUp = () => {
const onPointerUp = (e: React.PointerEvent) => {
cancelHold();
// A long press already acted; releasing must not also fire a reply.
if (!consumed.current && claimed.current && offset >= TRIGGER_PX) onReply();
if (!consumed.current && claimed.current && offset >= TRIGGER_PX) {
onReply();
lastTap.current = null;
} else if (!consumed.current && !claimed.current && onDoubleTap) {
// A stationary tap. Paired with a recent nearby one, it is a double tap.
// Tracked here rather than with onDoubleClick so touch and mouse behave
// the same, and so a swipe or a long press can never count as a tap.
const now = Date.now();
const prev = lastTap.current;
const near =
prev !== null &&
Math.abs(e.clientX - prev.x) < DOUBLE_TAP_SLOP_PX &&
Math.abs(e.clientY - prev.y) < DOUBLE_TAP_SLOP_PX;
if (prev && near && now - prev.t < DOUBLE_TAP_MS) {
lastTap.current = null;
onDoubleTap();
} else {
lastTap.current = { t: now, x: e.clientX, y: e.clientY };
}
}
reset();
};
+124 -24
View File
@@ -13,6 +13,7 @@ import { MessageText } from "@/components/chat/message-text";
import { MessageAttachments } from "@/components/chat/message-attachments";
import { MessageTicks } from "@/components/chat/message-ticks";
import { tickState } from "@/lib/chat-format";
import { HEART_EMOJI } from "@/components/chat/reaction-row";
import { cn } from "@/lib/utils";
import type { ChatMessage, ChatPeer, Receipts, ReplyPreview } from "@/lib/chat";
@@ -24,6 +25,22 @@ function clockTime(iso: string): string {
});
}
/**
* True when a message carries a shared post, which renders as a standalone
* card rather than bubble content.
*/
function sharesAnEntity(m: ChatMessage): boolean {
return (m.attachments ?? []).some((a) => a.kind === "entity");
}
/** Distinct emoji shown before the rest collapse into "+N". */
const MAX_TRAIL_EMOJI = 4;
/** People who reacted, across all emoji. */
function totalReactions(m: ChatMessage): number {
return (m.reactions ?? []).reduce((n, r) => n + r.count, 0);
}
function bubbleCorners(mine: boolean, index: number, total: number): string {
if (total === 1) return "rounded-2xl";
const first = index === 0;
@@ -45,12 +62,10 @@ function bubbleCorners(mine: boolean, index: number, total: number): string {
*/
function QuotedReply({
reply,
mine,
selfId,
nameFor,
}: {
reply: ReplyPreview;
mine: boolean;
selfId: string;
nameFor: (senderId: string | null | undefined) => string;
}) {
@@ -63,12 +78,11 @@ function QuotedReply({
: reply.sender_name || nameFor(reply.sender_id);
return (
<div
className={cn(
"mb-1 rounded-lg border-l-2 px-2 py-1 text-xs",
mine
? "border-primary-foreground/50 bg-black/10 text-primary-foreground/90 dark:text-white/90"
: "border-primary/50 bg-background/60 text-muted-foreground",
)}
// Neutral on both sides: this now sits on the page background rather
// than inside a bubble, so the old primary-foreground treatment (white
// text, for a primary bubble) would be invisible in light mode.
// Spacing comes from the column's gap — no margin of its own.
className="w-full rounded-lg border-l-2 border-primary/40 bg-muted/60 px-2 py-1 text-xs text-muted-foreground"
>
<span className="block font-medium">{who}</span>
<span className="line-clamp-1 break-words">
@@ -90,6 +104,8 @@ export function MessageGroup({
starredIds,
onRetry,
nameFor,
onReact,
onTrailClick,
}: {
messages: ChatMessage[];
mine: boolean;
@@ -109,6 +125,10 @@ export function MessageGroup({
onRetry: (message: ChatMessage) => void;
/** Names a quoted sender; supplied by the thread's participant list. */
nameFor: (senderId: string | null | undefined) => string;
/** Set or toggle a reaction. Picking an existing one removes it. */
onReact: (message: ChatMessage, emoji: string) => void;
/** Tapping the trail: retract if you reacted, otherwise show who did. */
onTrailClick: (message: ChatMessage) => void;
}) {
const last = messages[messages.length - 1];
@@ -153,7 +173,27 @@ export function MessageGroup({
disabled={!!m.deleted_at || !!m.pending}
onReply={() => onReply(m)}
onMenu={(point) => onMenu(m, point)}
onDoubleTap={() => onReact(m, HEART_EMOJI)}
>
{m.reply_to && !m.deleted_at && (
<div
className={cn(
"flex w-full",
mine ? "justify-end" : "justify-start",
)}
>
{/* Outside the bubble, above it: the quote is context for the
reply, not part of what was said. Capped to the bubble's
own width so the two read as one stack. */}
<div className="max-w-[78%]">
<QuotedReply
reply={m.reply_to}
selfId={selfId}
nameFor={nameFor}
/>
</div>
</div>
)}
<div
className={cn(
"flex w-full",
@@ -162,31 +202,51 @@ export function MessageGroup({
>
<div
className={cn(
"group/bubble relative max-w-[78%] px-3 py-2 text-sm",
"group/bubble relative max-w-[78%] text-sm",
bubbleCorners(mine, i, messages.length),
m.deleted_at
? "bg-muted italic text-muted-foreground"
: mine
? "bg-primary text-primary-foreground dark:text-white"
: "bg-muted text-foreground",
// A shared post is a card in its own right: it brings its
// own border, rounding and background, so the bubble drops
// its chrome rather than drawing a second frame around it.
// Any caption gets the padding back on its own line below.
sharesAnEntity(m)
? "overflow-hidden bg-transparent"
: cn(
"px-3 py-2",
m.deleted_at
? "bg-muted italic text-muted-foreground"
: mine
? "bg-primary text-primary-foreground dark:text-white"
: "bg-muted text-foreground",
),
)}
>
{m.reply_to && !m.deleted_at && (
<QuotedReply
reply={m.reply_to}
mine={mine}
selfId={selfId}
nameFor={nameFor}
/>
)}
{m.deleted_at ? (
<span>This message was deleted</span>
) : (
<>
{/* A shared post leads and its caption follows, the way
the post itself reads. Everything else keeps text
first, with attachments beneath it. */}
{sharesAnEntity(m) && (
<MessageAttachments attachments={m.attachments} />
)}
{m.body && (
<MessageText body={m.body} entities={m.entities} />
<span
className={cn(
"block",
// The bubble gave up its padding for the card, so a
// caption supplies its own.
sharesAnEntity(m)
? "rounded-b-lg border border-t-0 border-border px-3 py-2"
: undefined,
)}
>
<MessageText body={m.body} entities={m.entities} />
</span>
)}
{!sharesAnEntity(m) && (
<MessageAttachments attachments={m.attachments} />
)}
<MessageAttachments attachments={m.attachments} />
{/* An optimistic bubble for a captionless attachment has
nothing to draw until the server answers — say so rather
than render an empty box. */}
@@ -224,6 +284,46 @@ export function MessageGroup({
)}
</div>
</div>
{m.reactions?.length > 0 && (
<button
type="button"
// ONE control, not one per emoji. Two different jobs depending
// on whether you are in the reaction list already: if you have
// reacted, this retracts it; if you have not, it opens the
// list of who reacted. Per-chip toggling would make "see who
// reacted" unreachable for anyone who had.
onClick={() => onTrailClick(m)}
aria-label={
m.reactions.some((r) => r.mine)
? "Remove your reaction"
: "See who reacted"
}
className={cn(
"-mt-1 inline-flex items-center gap-0.5 rounded-full border bg-background px-1.5 py-0.5 text-xs",
mine ? "self-end mr-1" : "self-start ml-1",
m.reactions.some((r) => r.mine)
? "border-primary/40 bg-primary/10"
: "border-border",
)}
>
{m.reactions.slice(0, MAX_TRAIL_EMOJI).map((r) => (
<span key={r.emoji}>{r.emoji}</span>
))}
{m.reactions.length > MAX_TRAIL_EMOJI && (
<span className="tabular-nums text-muted-foreground">
+{m.reactions.length - MAX_TRAIL_EMOJI}
</span>
)}
{/* Total people, not distinct emoji — "😂❤️ 5" reads as five
reactions, which is what it is. */}
{totalReactions(m) > 1 && (
<span className="ml-0.5 tabular-nums text-muted-foreground">
{totalReactions(m)}
</span>
)}
</button>
)}
</MessageGestures>
))}
+23
View File
@@ -55,6 +55,9 @@ export function MessageList({
starredIds,
onRetry,
nameFor,
typingNames,
onReact,
onTrailClick,
}: {
/** Ascending by seq — oldest first. */
messages: ChatMessage[];
@@ -71,6 +74,11 @@ export function MessageList({
starredIds: Set<string>;
onRetry: (message: ChatMessage) => void;
nameFor: (senderId: string | null | undefined) => string;
/** Who is composing right now. Empty when nobody is. */
typingNames: string[];
onReact: (message: ChatMessage, emoji: string) => void;
/** Tapping the reaction trail. */
onTrailClick: (message: ChatMessage) => void;
}) {
const scrollRef = useRef<HTMLDivElement>(null);
const atBottomRef = useRef(true);
@@ -173,10 +181,25 @@ export function MessageList({
starredIds={starredIds}
onRetry={onRetry}
nameFor={nameFor}
onReact={onReact}
onTrailClick={onTrailClick}
/>
),
)}
</div>
{typingNames.length > 0 && (
<p
aria-live="polite"
className="px-1 pt-2 text-xs italic text-muted-foreground"
>
{typingNames.length === 1
? `${typingNames[0]} is typing…`
: `${typingNames.slice(0, 2).join(", ")}${
typingNames.length > 2 ? " and others" : ""
} are typing…`}
</p>
)}
</div>
);
}
+19 -1
View File
@@ -18,6 +18,7 @@ import {
StarOff,
Trash2,
} from "lucide-react";
import { ReactionRow } from "@/components/chat/reaction-row";
import { cn } from "@/lib/utils";
export type MenuPoint = { x: number; y: number };
@@ -38,11 +39,17 @@ const MARGIN = 8;
export function MessageMenu({
point,
starred,
myReaction,
onReact,
actions,
onClose,
}: {
point: MenuPoint;
starred: boolean;
/** The viewer's current emoji on this message, if any. */
myReaction?: string;
/** Picking the same emoji again is a toggle — the caller decides. */
onReact: (emoji: string) => void;
actions: MessageMenuActions;
onClose: () => void;
}) {
@@ -89,8 +96,19 @@ export function MessageMenu({
// min-w-56 rather than something tighter: "Delete for everyone" is the
// longest label and, with its icon and padding, was wrapping or sitting
// flush against the edge at a narrower width.
className="fixed z-50 min-w-56 overflow-hidden rounded-xl border border-border bg-background py-1 shadow-lg"
className="fixed z-50 min-w-56 overflow-hidden rounded-xl border border-border bg-background pb-1 shadow-lg"
>
{/* Reactions lead: they are the most common thing to want from a
long press, and putting them in this menu keeps one gesture
responsible for one surface. */}
<ReactionRow
current={myReaction}
onPick={(emoji) => {
onReact(emoji);
onClose();
}}
/>
<Item icon={<Reply className="size-4" />} onClick={run(actions.onReply)}>
Reply
</Item>
+15 -16
View File
@@ -9,10 +9,16 @@
*
* The path is always app-relative — the BFF rejects anything else — so this
* can navigate with the router rather than leaving the app.
*
* Styling is deliberately bare. This sits INSIDE a chat bubble, which already
* supplies the padding, the background and the rounding; giving the quote its
* own would draw a second bubble within the first. A left rule and italics are
* enough to say "quotation", and every colour is inherited so the same markup
* reads correctly on your own primary-coloured bubble and on the muted one
* opposite.
*/
import { useRouter } from "next/navigation";
import { Quote } from "lucide-react";
import type { Attachment } from "@/lib/chat";
export function QuoteCard({ attachment }: { attachment: Attachment }) {
@@ -25,23 +31,16 @@ export function QuoteCard({ attachment }: { attachment: Attachment }) {
type="button"
onClick={() => path && router.push(path)}
disabled={!path}
className="mt-1 block w-full rounded-lg border-l-2 border-primary bg-primary/5 px-3 py-2 text-left transition-colors hover:bg-primary/10 disabled:cursor-default disabled:hover:bg-primary/5"
className="block w-full border-l-2 border-current/30 pl-2.5 text-left transition-opacity hover:opacity-80 disabled:cursor-default disabled:hover:opacity-100"
>
<span className="flex items-start gap-2">
<Quote className="mt-0.5 size-3.5 shrink-0 text-primary" aria-hidden />
<span className="min-w-0 flex-1">
{/* The passage is the point, so it leads; the reference follows in
the quieter role a citation normally takes. */}
<span className="block text-sm italic leading-relaxed text-foreground">
{passage}
</span>
{attachment.title && (
<span className="mt-1 block truncate text-xs font-medium text-primary">
{attachment.title}
</span>
)}
{/* The passage leads; the citation follows in the quieter role a
reference normally takes. */}
<span className="block text-sm italic leading-snug">{passage}</span>
{attachment.title && (
<span className="mt-0.5 block truncate text-xs opacity-70">
{attachment.title}
</span>
</span>
)}
</button>
);
}
+101
View File
@@ -0,0 +1,101 @@
"use client";
/**
* The emoji row at the top of a message's long-press menu.
*
* Five quick reactions plus a "+" that opens the full set — a drawer on
* mobile, a modal on desktop, reusing ResponsiveDialog so it behaves like
* every other chat surface.
*
* It sits inside the context menu rather than being its own popover: long
* press is one gesture, and two surfaces competing for it would mean neither
* felt reliable.
*/
import { useState } from "react";
import { Plus } from "lucide-react";
import { EMOJI_GROUPS } from "@/components/ui/emoji-picker";
import { ResponsiveDialog } from "@/components/chat/responsive-dialog";
import { cn } from "@/lib/utils";
/** What a double-tap sends. Matches the server's own default. */
export const HEART_EMOJI = "❤️";
/** The five offered without opening the full set. */
export const QUICK_REACTIONS = [HEART_EMOJI, "😂", "🙏", "😮", "😢"];
export function ReactionRow({
current,
onPick,
}: {
/** The viewer's existing reaction, so it can be shown as selected. */
current?: string;
/** Picking the current emoji again clears it — the caller decides. */
onPick: (emoji: string) => void;
}) {
const [browsing, setBrowsing] = useState(false);
return (
<>
<div className="flex items-center gap-1 border-b border-border px-2 py-2">
{QUICK_REACTIONS.map((emoji) => (
<button
key={emoji}
type="button"
onClick={() => onPick(emoji)}
aria-label={`React ${emoji}`}
aria-pressed={current === emoji}
className={cn(
"inline-flex size-9 items-center justify-center rounded-full text-lg transition-colors",
current === emoji ? "bg-primary/15" : "hover:bg-muted",
)}
>
{emoji}
</button>
))}
<button
type="button"
onClick={() => setBrowsing(true)}
aria-label="More reactions"
className="inline-flex size-9 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
>
<Plus className="size-4" />
</button>
</div>
{browsing && (
<ResponsiveDialog
title="Pick a reaction"
description="Choose any emoji to react with."
onClose={() => setBrowsing(false)}
>
<div className="space-y-4 p-4">
{EMOJI_GROUPS.map((group) => (
<section key={group.label}>
<h3 className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
{group.label}
</h3>
<div className="grid grid-cols-8 gap-1">
{group.emojis.map((emoji) => (
<button
key={emoji}
type="button"
onClick={() => {
setBrowsing(false);
onPick(emoji);
}}
aria-label={`React ${emoji}`}
className="inline-flex size-9 items-center justify-center rounded-md text-lg hover:bg-muted"
>
{emoji}
</button>
))}
</div>
</section>
))}
</div>
</ResponsiveDialog>
)}
</>
);
}
+83
View File
@@ -0,0 +1,83 @@
"use client";
/**
* Who reacted to a message, and with what.
*
* Fetched on open rather than shipped with every message: the thread renders
* from grouped counts, and sending the full membership of every reaction on
* every page would grow with the room.
*/
import { useEffect, useState } from "react";
import { UserAvatar } from "@/components/ui/user-avatar";
import { ResponsiveDialog } from "@/components/chat/responsive-dialog";
import { chat, type ReactionDetail } from "@/lib/chat";
export function ReactionsDrawer({
conversationId,
messageId,
onClose,
}: {
conversationId: string;
messageId: string;
onClose: () => void;
}) {
const [rows, setRows] = useState<ReactionDetail[] | null>(null);
useEffect(() => {
let cancelled = false;
chat
.reactionDetails(conversationId, messageId)
.then((r) => {
if (!cancelled) setRows(r);
})
.catch(() => {
if (!cancelled) setRows([]);
});
return () => {
cancelled = true;
};
}, [conversationId, messageId]);
return (
<ResponsiveDialog
title="Reactions"
description={
rows === null
? "Loading…"
: `${rows.length} ${rows.length === 1 ? "person" : "people"} reacted.`
}
onClose={onClose}
>
{rows === null ? (
<p className="p-4 text-sm text-muted-foreground">Loading…</p>
) : rows.length === 0 ? (
<p className="p-4 text-sm text-muted-foreground">No reactions.</p>
) : (
<ul className="divide-y divide-border">
{rows.map((r) => (
<li
key={r.user.id}
className="flex items-center gap-3 px-4 py-2.5"
>
<UserAvatar
src={r.user.avatar_url}
name={r.user.name}
className="size-9 shrink-0"
/>
<div className="min-w-0 flex-1">
<p className="truncate text-sm text-foreground">{r.user.name}</p>
<p className="truncate text-xs text-muted-foreground">
@{r.user.handle}
</p>
</div>
<span className="shrink-0 text-lg" aria-label={r.emoji}>
{r.emoji}
</span>
</li>
))}
</ul>
)}
</ResponsiveDialog>
);
}
+2 -2
View File
@@ -19,7 +19,7 @@ export function SharedPostCard({ attachment }: { attachment: Attachment }) {
if (!post || attachment.entity_unavailable) {
return (
<div className="mt-1 flex items-center gap-2 rounded-lg border border-border bg-muted/30 px-3 py-2.5">
<div className="flex items-center gap-2 rounded-lg border border-border bg-muted/30 px-3 py-2.5">
<ImageOff className="size-4 shrink-0 text-muted-foreground" aria-hidden />
<span className="text-sm text-muted-foreground">
This post is no longer available
@@ -31,7 +31,7 @@ export function SharedPostCard({ attachment }: { attachment: Attachment }) {
return (
<Link
href={`/u/${encodeURIComponent(post.author_handle)}/posts#post-${post.id}`}
className="mt-1 block overflow-hidden rounded-lg border border-border bg-card transition-colors hover:bg-muted/40"
className="block overflow-hidden rounded-lg border border-border bg-card transition-colors hover:bg-muted/40"
>
<span className="flex items-center gap-2 px-3 py-2">
<UserAvatar