Add emoji reaction particles (#890)

This commit is contained in:
klopez4212
2026-06-08 15:37:47 +01:00
committed by GitHub
parent 32039b9a25
commit fdcbb696fe
8 changed files with 825 additions and 37 deletions

View File

@@ -52,6 +52,9 @@ export function InboxMessageRow({
() => toTimelineMessage(message),
[message],
);
const [badgeBurstEmoji, setBadgeBurstEmoji] = React.useState<string | null>(
null,
);
const {
reactions,
canToggle: canToggleReactions,
@@ -92,11 +95,13 @@ export function InboxMessageRow({
onReactionSelect={
canToggleReactions ? handleReactionSelect : undefined
}
onReactionBadgeBurstRequest={
reactionPending ? undefined : setBadgeBurstEmoji
}
onReply={
canReply ? () => onSelectReplyTarget(message) : undefined
}
reactionErrorMessage={reactionErrorMessage}
reactionPending={reactionPending}
reactions={reactions}
/>
</div>
@@ -134,6 +139,12 @@ export function InboxMessageRow({
onSelect={(emoji) => {
void handleReactionSelect(emoji);
}}
burstEmojiOnRender={badgeBurstEmoji}
onBurstEmojiRendered={(emoji) => {
setBadgeBurstEmoji((current) =>
current === emoji ? null : current,
);
}}
pending={reactionPending}
reactions={reactions}
/>

View File

@@ -39,8 +39,8 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/shared/ui/dropdown-menu";
import { isPositiveEmojiParticle } from "@/shared/ui/EmojiBurstProvider";
import { Popover, PopoverContent, PopoverTrigger } from "@/shared/ui/popover";
import { Spinner } from "@/shared/ui/spinner";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/shared/ui/tooltip";
function copyToClipboard(text: string, successMessage: string) {
@@ -263,12 +263,12 @@ export function MessageActionBar({
onEdit,
onFollowThread,
onMarkUnread,
onReactionBadgeBurstRequest,
onReactionSelect,
onReply,
onUnfollowThread,
reactionErrorMessage = null,
reactions,
reactionPending = false,
isFollowingThread,
}: {
/** Channel UUID — required for the "Copy link" action; when omitted the
@@ -279,12 +279,12 @@ export function MessageActionBar({
onEdit?: (message: TimelineMessage) => void;
onFollowThread?: (message: TimelineMessage) => void;
onMarkUnread?: (message: TimelineMessage) => void;
onReactionBadgeBurstRequest?: (emoji: string) => void;
onReactionSelect?: (emoji: string) => Promise<void>;
onReply?: (message: TimelineMessage) => void;
onUnfollowThread?: (message: TimelineMessage) => void;
reactionErrorMessage?: string | null;
reactions: TimelineReaction[];
reactionPending?: boolean;
isFollowingThread?: boolean;
}) {
const [isReactionPickerOpen, setIsReactionPickerOpen] = React.useState(false);
@@ -307,6 +307,10 @@ export function MessageActionBar({
const selectedReactionCount = reactions.filter(
(reaction) => reaction.reactedByCurrentUser,
).length;
const wouldAddReaction = (emoji: string) =>
!reactions.some(
(reaction) => reaction.emoji === emoji && reaction.reactedByCurrentUser,
);
return (
<div
@@ -334,7 +338,6 @@ export function MessageActionBar({
aria-label="Open reactions"
className="h-6 w-6 rounded-full p-0"
data-testid={`react-message-${message.id}`}
disabled={reactionPending}
size="sm"
type="button"
variant={
@@ -343,11 +346,7 @@ export function MessageActionBar({
: "ghost"
}
>
{reactionPending ? (
<Spinner className="h-3 w-3" />
) : (
<SmilePlus className="h-3 w-3" />
)}
<SmilePlus className="h-3 w-3" />
</Button>
</PopoverTrigger>
</TooltipTrigger>
@@ -374,6 +373,12 @@ export function MessageActionBar({
}
// `value` is already a `native` glyph or a `:shortcode:` for
// custom emoji; the toggle mutation resolves the URL.
if (
wouldAddReaction(value) &&
isPositiveEmojiParticle(value)
) {
onReactionBadgeBurstRequest?.(value);
}
void onReactionSelect(value).finally(() => {
setIsReactionPickerOpen(false);
});

View File

@@ -6,8 +6,11 @@ import type { TimelineReaction } from "@/features/messages/types";
import { cn } from "@/shared/lib/cn";
import { emojiDisplayName } from "@/shared/lib/emojiName";
import { rewriteRelayUrl } from "@/shared/lib/mediaUrl";
import {
isPositiveEmojiParticle,
useEmojiBurst,
} from "@/shared/ui/EmojiBurstProvider";
import { Popover, PopoverContent, PopoverTrigger } from "@/shared/ui/popover";
import { Spinner } from "@/shared/ui/spinner";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/shared/ui/tooltip";
const REACTION_PILL_BASE_CLASSES =
@@ -15,6 +18,38 @@ const REACTION_PILL_BASE_CLASSES =
const REACTION_GLYPH_CLASSES = "h-3.5 w-3.5 translate-y-px text-sm";
const REACTION_PILL_HOVER_CLASSES =
"hover:bg-primary/10 hover:text-foreground focus-visible:bg-primary/10 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring";
const BADGE_BURST_STABLE_FRAMES = 2;
const BADGE_BURST_MAX_FRAMES = 12;
const BADGE_BURST_RECT_EPSILON = 0.5;
type BadgeBurstRect = {
height: number;
left: number;
top: number;
width: number;
};
function toBadgeBurstRect(rect: DOMRect): BadgeBurstRect {
return {
height: rect.height,
left: rect.left,
top: rect.top,
width: rect.width,
};
}
function isSameBadgeBurstRect(
left: BadgeBurstRect | null,
right: BadgeBurstRect,
) {
return (
left !== null &&
Math.abs(left.left - right.left) <= BADGE_BURST_RECT_EPSILON &&
Math.abs(left.top - right.top) <= BADGE_BURST_RECT_EPSILON &&
Math.abs(left.width - right.width) <= BADGE_BURST_RECT_EPSILON &&
Math.abs(left.height - right.height) <= BADGE_BURST_RECT_EPSILON
);
}
/**
* Render a reaction's emoji: a custom (image) emoji when `emojiUrl` is set,
@@ -99,6 +134,8 @@ export function MessageReactions({
pending,
onSelect,
className,
burstEmojiOnRender = null,
onBurstEmojiRendered,
}: {
messageId: string;
reactions: TimelineReaction[];
@@ -106,7 +143,96 @@ export function MessageReactions({
pending: boolean;
onSelect: (emoji: string) => void;
className?: string;
burstEmojiOnRender?: string | null;
onBurstEmojiRendered?: (emoji: string) => void;
}) {
const { burstEmoji } = useEmojiBurst();
const [pendingBadgeBurstEmoji, setPendingBadgeBurstEmoji] = React.useState<
string | null
>(null);
const pillRefs = React.useRef(new Map<string, HTMLButtonElement>());
const deliveredBadgeBurstRef = React.useRef<string | null>(null);
const badgeBurstEmoji = burstEmojiOnRender ?? pendingBadgeBurstEmoji;
const registerPill = React.useCallback(
(emoji: string, element: HTMLButtonElement | null) => {
if (element) {
pillRefs.current.set(emoji, element);
} else {
pillRefs.current.delete(emoji);
}
},
[],
);
React.useEffect(() => {
if (!badgeBurstEmoji) {
deliveredBadgeBurstRef.current = null;
return;
}
if (
deliveredBadgeBurstRef.current === badgeBurstEmoji ||
!isPositiveEmojiParticle(badgeBurstEmoji)
) {
return;
}
const reaction = reactions.find(
(candidate) =>
candidate.emoji === badgeBurstEmoji && candidate.reactedByCurrentUser,
);
if (!reaction || !pillRefs.current.get(badgeBurstEmoji)) return;
let frameId: number | null = null;
let frameCount = 0;
let stableFrameCount = 0;
let previousRect: BadgeBurstRect | null = null;
const cancelFrame = () => {
if (frameId === null) return;
window.cancelAnimationFrame(frameId);
frameId = null;
};
const emitFromSettledBadge = () => {
frameId = null;
const pill = pillRefs.current.get(badgeBurstEmoji);
if (!pill || !document.documentElement.contains(pill)) return;
const nextRect = toBadgeBurstRect(pill.getBoundingClientRect());
if (!nextRect.width && !nextRect.height) return;
stableFrameCount = isSameBadgeBurstRect(previousRect, nextRect)
? stableFrameCount + 1
: 0;
previousRect = nextRect;
frameCount += 1;
if (
stableFrameCount < BADGE_BURST_STABLE_FRAMES &&
frameCount < BADGE_BURST_MAX_FRAMES
) {
frameId = window.requestAnimationFrame(emitFromSettledBadge);
return;
}
deliveredBadgeBurstRef.current = badgeBurstEmoji;
burstEmoji(badgeBurstEmoji, {
clientX: nextRect.left + nextRect.width / 2,
clientY: nextRect.top + nextRect.height / 2,
});
setPendingBadgeBurstEmoji((current) =>
current === badgeBurstEmoji ? null : current,
);
onBurstEmojiRendered?.(badgeBurstEmoji);
};
frameId = window.requestAnimationFrame(emitFromSettledBadge);
return cancelFrame;
}, [badgeBurstEmoji, burstEmoji, onBurstEmojiRendered, reactions]);
if (reactions.length === 0) {
return null;
}
@@ -125,6 +251,7 @@ export function MessageReactions({
canToggle={canToggle}
pending={pending}
reaction={reaction}
registerPill={registerPill}
onSelect={onSelect}
/>
))}
@@ -133,6 +260,8 @@ export function MessageReactions({
messageId={messageId}
onSelect={onSelect}
pending={pending}
reactions={reactions}
requestBadgeBurst={setPendingBadgeBurstEmoji}
/>
) : null}
</div>
@@ -143,12 +272,20 @@ function InlineReactionPicker({
messageId,
onSelect,
pending,
reactions,
requestBadgeBurst,
}: {
messageId: string;
onSelect: (emoji: string) => void;
pending: boolean;
reactions: TimelineReaction[];
requestBadgeBurst: (emoji: string) => void;
}) {
const [open, setOpen] = React.useState(false);
const wouldAddReaction = (emoji: string) =>
!reactions.some(
(reaction) => reaction.emoji === emoji && reaction.reactedByCurrentUser,
);
return (
<Popover onOpenChange={setOpen} open={open}>
@@ -173,11 +310,7 @@ function InlineReactionPicker({
disabled={pending}
type="button"
>
{pending ? (
<Spinner className="h-4 w-4" />
) : (
<SmilePlus className="h-4 w-4" />
)}
<SmilePlus className="h-4 w-4" />
</button>
</PopoverTrigger>
</TooltipTrigger>
@@ -192,6 +325,9 @@ function InlineReactionPicker({
<EmojiPicker
autoFocus
onSelect={(value) => {
if (wouldAddReaction(value) && isPositiveEmojiParticle(value)) {
requestBadgeBurst(value);
}
onSelect(value);
setOpen(false);
}}
@@ -205,13 +341,16 @@ function ReactionPill({
reaction,
canToggle,
pending,
registerPill,
onSelect,
}: {
reaction: TimelineReaction;
canToggle: boolean;
pending: boolean;
registerPill: (emoji: string, element: HTMLButtonElement | null) => void;
onSelect: (emoji: string) => void;
}) {
const { burstEmoji } = useEmojiBurst();
const [open, setOpen] = React.useState(false);
const openTimeout = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const closeTimeout = React.useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -248,6 +387,13 @@ function ReactionPill({
return clearTimers;
}, [clearTimers]);
const setPillRef = React.useCallback(
(element: HTMLButtonElement | null) => {
registerPill(reaction.emoji, element);
},
[reaction.emoji, registerPill],
);
const pillClasses = cn(
REACTION_PILL_BASE_CLASSES,
"min-w-12 justify-center gap-1.5 px-2",
@@ -261,8 +407,14 @@ function ReactionPill({
: "cursor-default",
);
const handleClick = () => {
const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
if (!canToggle) return;
if (
!reaction.reactedByCurrentUser &&
isPositiveEmojiParticle(reaction.emoji)
) {
burstEmoji(reaction.emoji, event);
}
onSelect(reaction.emoji);
};
@@ -277,6 +429,7 @@ function ReactionPill({
className={pillClasses}
disabled={!canToggle || pending}
onClick={handleClick}
ref={setPillRef}
type="button"
>
<EmojiGlyph reaction={reaction} className={REACTION_GLYPH_CLASSES} />
@@ -303,6 +456,7 @@ function ReactionPill({
className={pillClasses}
disabled={!canToggle || pending}
onClick={handleClick}
ref={setPillRef}
type="button"
>
<EmojiGlyph

View File

@@ -67,6 +67,9 @@ export const MessageRow = React.memo(
const [expandedDiffId, setExpandedDiffId] = React.useState<string | null>(
null,
);
const [badgeBurstEmoji, setBadgeBurstEmoji] = React.useState<string | null>(
null,
);
const {
reactions,
canToggle: canToggleReactions,
@@ -219,13 +222,15 @@ export const MessageRow = React.memo(
onEdit={onEdit}
onFollowThread={onFollowThread}
onMarkUnread={onMarkUnread}
onReactionBadgeBurstRequest={
reactionPending ? undefined : setBadgeBurstEmoji
}
onReactionSelect={
canToggleReactions ? handleReactionSelect : undefined
}
onReply={onReply}
onUnfollowThread={onUnfollowThread}
reactionErrorMessage={reactionErrorMessage}
reactionPending={reactionPending}
reactions={reactions}
/>
</div>
@@ -258,6 +263,12 @@ export const MessageRow = React.memo(
reactions={reactions}
canToggle={canToggleReactions}
pending={reactionPending}
burstEmojiOnRender={badgeBurstEmoji}
onBurstEmojiRendered={(emoji) => {
setBadgeBurstEmoji((current) =>
current === emoji ? null : current,
);
}}
onSelect={(emoji) => {
void handleReactionSelect(emoji);
}}

View File

@@ -10,12 +10,12 @@ import { resolveUserLabel } from "@/features/profile/lib/identity";
import { UserProfilePopover } from "@/features/profile/ui/UserProfilePopover";
import { cn } from "@/shared/lib/cn";
import { Button } from "@/shared/ui/button";
import { isPositiveEmojiParticle } from "@/shared/ui/EmojiBurstProvider";
import {
MENTION_CHIP_BASE_CLASSES,
MENTION_CHIP_HOVER_CLASSES,
} from "@/shared/ui/mentionChip";
import { Popover, PopoverContent, PopoverTrigger } from "@/shared/ui/popover";
import { Spinner } from "@/shared/ui/spinner";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/shared/ui/tooltip";
import { UserAvatar } from "@/shared/ui/UserAvatar";
import { MessageTimestamp } from "./MessageTimestamp";
@@ -287,6 +287,9 @@ export const SystemMessageRow = React.memo(function SystemMessageRow({
remove: boolean,
) => Promise<void>;
}) {
const [badgeBurstEmoji, setBadgeBurstEmoji] = React.useState<string | null>(
null,
);
const [isReactionPickerOpen, setIsReactionPickerOpen] = React.useState(false);
const {
reactions,
@@ -313,6 +316,11 @@ export const SystemMessageRow = React.memo(function SystemMessageRow({
return null;
}
const wouldAddReaction = (emoji: string) =>
!reactions.some(
(reaction) => reaction.emoji === emoji && reaction.reactedByCurrentUser,
);
return (
<div
className="group/message relative rounded-2xl px-3 py-2 transition-colors hover:bg-muted/50 focus-within:bg-muted/50"
@@ -345,6 +353,12 @@ export const SystemMessageRow = React.memo(function SystemMessageRow({
canToggle={canToggleReactions}
pending={reactionPending}
className="mt-0.5 pt-0.5"
burstEmojiOnRender={badgeBurstEmoji}
onBurstEmojiRendered={(emoji) => {
setBadgeBurstEmoji((current) =>
current === emoji ? null : current,
);
}}
onSelect={(emoji) => {
void handleReactionSelect(emoji);
}}
@@ -380,16 +394,11 @@ export const SystemMessageRow = React.memo(function SystemMessageRow({
<Button
aria-label="Open reactions"
className="h-6 w-6 rounded-full p-0"
disabled={reactionPending}
size="sm"
type="button"
variant={isReactionPickerOpen ? "secondary" : "ghost"}
>
{reactionPending ? (
<Spinner className="h-3 w-3" />
) : (
<SmilePlus className="h-3 w-3" />
)}
<SmilePlus className="h-3 w-3" />
</Button>
</PopoverTrigger>
</TooltipTrigger>
@@ -410,6 +419,13 @@ export const SystemMessageRow = React.memo(function SystemMessageRow({
) : null}
<EmojiPicker
onSelect={(value) => {
if (
!reactionPending &&
wouldAddReaction(value) &&
isPositiveEmojiParticle(value)
) {
setBadgeBurstEmoji(value);
}
void handleReactionSelect(value).finally(() => {
setIsReactionPickerOpen(false);
});

View File

@@ -1,9 +1,13 @@
import * as React from "react";
import { useQueryClient } from "@tanstack/react-query";
import { customEmojiQueryKey } from "@/features/custom-emoji/hooks";
import type {
TimelineMessage,
TimelineReaction,
} from "@/features/messages/types";
import { reactionEmojiUrl } from "@/shared/api/customEmoji";
import type { CustomEmoji } from "@/shared/lib/remarkCustomEmoji";
type ReactionHandler = {
/** Reactions sorted by count (desc) then emoji (asc). */
@@ -18,6 +22,69 @@ type ReactionHandler = {
select: (emoji: string) => Promise<void>;
};
function sortReactions(reactions: TimelineReaction[]): TimelineReaction[] {
return [...reactions].sort((left, right) => {
if (left.count !== right.count) {
return right.count - left.count;
}
return left.emoji.localeCompare(right.emoji);
});
}
function applyOptimisticReaction(
reactions: TimelineReaction[],
emoji: string,
remove: boolean,
emojiUrl?: string,
): TimelineReaction[] {
const existing = reactions.find((reaction) => reaction.emoji === emoji);
if (remove) {
if (!existing?.reactedByCurrentUser) return reactions;
const nextCount = Math.max(0, existing.count - 1);
if (nextCount === 0) {
return reactions.filter((reaction) => reaction.emoji !== emoji);
}
return reactions.map((reaction) =>
reaction.emoji === emoji
? {
...reaction,
count: nextCount,
reactedByCurrentUser: false,
users: reaction.users.filter((user) => user.displayName !== "You"),
}
: reaction,
);
}
if (existing) {
if (existing.reactedByCurrentUser) return reactions;
return reactions.map((reaction) =>
reaction.emoji === emoji
? {
...reaction,
count: reaction.count + 1,
reactedByCurrentUser: true,
}
: reaction,
);
}
return [
...reactions,
{
emoji,
emojiUrl,
count: 1,
reactedByCurrentUser: true,
users: [{ pubkey: "", displayName: "You", avatarUrl: null }],
},
];
}
/**
* Shared reaction state + toggle logic used by both MessageRow and
* SystemMessageRow. Keeps the pending/error/sorting concerns in one place.
@@ -30,17 +97,22 @@ export function useReactionHandler(
remove: boolean,
) => Promise<void>,
): ReactionHandler {
const queryClient = useQueryClient();
const [pending, setPending] = React.useState(false);
const [errorMessage, setErrorMessage] = React.useState<string | null>(null);
const sourceReactions = message.reactions;
const [optimisticState, setOptimisticState] = React.useState<{
reactions: TimelineReaction[];
sourceReactions: TimelineReaction[] | undefined;
} | null>(null);
const optimisticReactions =
optimisticState && optimisticState.sourceReactions === sourceReactions
? optimisticState.reactions
: null;
const reactions = React.useMemo(() => {
return [...(message.reactions ?? [])].sort((left, right) => {
if (left.count !== right.count) {
return right.count - left.count;
}
return left.emoji.localeCompare(right.emoji);
});
}, [message.reactions]);
return sortReactions(optimisticReactions ?? sourceReactions ?? []);
}, [sourceReactions, optimisticReactions]);
const canToggle = Boolean(onToggleReaction && !message.pending);
@@ -56,9 +128,30 @@ export function useReactionHandler(
setErrorMessage(null);
setPending(true);
const emojiUrl = reactionEmojiUrl(
emoji,
queryClient.getQueryData<CustomEmoji[]>(customEmojiQueryKey),
);
setOptimisticState((current) => {
const baseReactions =
current && current.sourceReactions === sourceReactions
? current.reactions
: reactions;
return {
reactions: applyOptimisticReaction(
baseReactions,
emoji,
remove,
emojiUrl,
),
sourceReactions,
};
});
try {
await onToggleReaction(message, emoji, remove);
} catch (error) {
setOptimisticState(null);
const nextMessage =
error instanceof Error
? error.message
@@ -69,7 +162,14 @@ export function useReactionHandler(
setPending(false);
}
},
[message, onToggleReaction, pending, reactions],
[
message,
onToggleReaction,
pending,
queryClient,
reactions,
sourceReactions,
],
);
return { reactions, canToggle, pending, errorMessage, select };