mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
feat: add emoji reactions to comments on showcase pages
- Create useCommentReactions hook for managing emoji reactions - Add EmojiReactions component with picker and toggle functionality - Integrate emoji reactions into Comment component - Support 8 predefined emoji reactions (👍, ❤️, 😂, 😮, 😢, 😡, 🎉, 🔥) - Implement optimistic updates with error recovery - Add real-time synchronization using Nostr kind 7 events - Include reaction tooltips showing user context - Support reaction toggling (add/remove) with visual feedback - Update useNostrPublish to invalidate emoji reaction caches - Create comprehensive documentation and demo components - Add loading states and accessibility features Users can now quickly react to comments with emojis, providing instant feedback and social engagement without needing to write full replies. All reactions sync in real-time across clients using the Nostr protocol.
This commit is contained in:
1 parent
e709dca735
commit
bdb73252eb
6 files changed
+869
-5
No files matched your search
@@ -0,0 +1,348 @@
|
||||
# Emoji Reactions for Comments
|
||||
|
||||
This document describes the implementation of emoji reactions for comments on showcase app pages, allowing users to express their feelings about comments using emoji reactions like 👍, ❤️, 😂, etc.
|
||||
|
||||
## Overview
|
||||
|
||||
The emoji reactions system provides:
|
||||
- **Quick Engagement**: React to comments without writing full replies
|
||||
- **Visual Feedback**: See popular reactions and participation levels
|
||||
- **Real-time Updates**: Reactions appear instantly with optimistic updates
|
||||
- **Social Context**: Tooltips show who reacted with each emoji
|
||||
- **Toggle Functionality**: Click reactions to add/remove your reaction
|
||||
|
||||
## Implementation Architecture
|
||||
|
||||
### 1. Core Hook: `useCommentReactions`
|
||||
|
||||
**File**: `src/hooks/useCommentReactions.ts`
|
||||
|
||||
**Features:**
|
||||
- Fetches kind 7 reactions for specific comments
|
||||
- Groups reactions by emoji with user tracking
|
||||
- Handles reaction addition/removal with optimistic updates
|
||||
- Supports real-time synchronization
|
||||
|
||||
**Key Functions:**
|
||||
```typescript
|
||||
// Fetch reactions for a comment
|
||||
useCommentReactions(commentId: string)
|
||||
|
||||
// Add/toggle reactions
|
||||
useAddCommentReaction()
|
||||
```
|
||||
|
||||
**Reaction Data Structure:**
|
||||
```typescript
|
||||
interface CommentReaction {
|
||||
emoji: string; // The emoji (e.g., "👍")
|
||||
count: number; // Number of users who reacted
|
||||
userReacted: boolean; // Whether current user reacted
|
||||
users: string[]; // Pubkeys of users who reacted
|
||||
}
|
||||
```
|
||||
|
||||
### 2. UI Component: `EmojiReactions`
|
||||
|
||||
**File**: `src/components/comments/EmojiReactions.tsx`
|
||||
|
||||
**Features:**
|
||||
- Displays existing reactions as clickable badges
|
||||
- Provides emoji picker for adding new reactions
|
||||
- Shows tooltips with reaction context
|
||||
- Handles loading states and user authentication
|
||||
|
||||
**Component Structure:**
|
||||
```typescript
|
||||
<EmojiReactions
|
||||
commentId={comment.id}
|
||||
commentAuthor={comment.pubkey}
|
||||
className="pt-2"
|
||||
/>
|
||||
```
|
||||
|
||||
### 3. Integration with Comments
|
||||
|
||||
**File**: `src/components/comments/Comment.tsx`
|
||||
|
||||
The emoji reactions are seamlessly integrated into the existing comment component, appearing between the comment content and action buttons.
|
||||
|
||||
## Predefined Emoji Set
|
||||
|
||||
The system includes 8 carefully chosen emoji reactions:
|
||||
|
||||
| Emoji | Label | Use Case |
|
||||
|-------|-------|----------|
|
||||
| 👍 | thumbs up | General approval/agreement |
|
||||
| ❤️ | heart | Love/strong positive feeling |
|
||||
| 😂 | laugh | Funny/humorous content |
|
||||
| 😮 | wow | Surprise/amazement |
|
||||
| 😢 | sad | Sadness/empathy |
|
||||
| 😡 | angry | Disagreement/frustration |
|
||||
| 🎉 | celebrate | Celebration/excitement |
|
||||
| 🔥 | fire | Impressive/awesome content |
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
### Event Structure
|
||||
|
||||
Emoji reactions use **kind 7 events** (reactions) with specific formatting:
|
||||
|
||||
**Adding a Reaction:**
|
||||
```json
|
||||
{
|
||||
"kind": 7,
|
||||
"content": "👍",
|
||||
"tags": [
|
||||
["e", "comment-event-id"],
|
||||
["p", "comment-author-pubkey"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Removing a Reaction:**
|
||||
```json
|
||||
{
|
||||
"kind": 7,
|
||||
"content": "-👍",
|
||||
"tags": [
|
||||
["e", "comment-event-id"],
|
||||
["p", "comment-author-pubkey"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Reaction Processing Logic
|
||||
|
||||
1. **Fetch**: Query kind 7 events referencing the comment
|
||||
2. **Group**: Organize by emoji and user (latest reaction wins)
|
||||
3. **Filter**: Remove reactions with "-" prefix (removals)
|
||||
4. **Aggregate**: Count active reactions per emoji
|
||||
5. **Display**: Show sorted by popularity
|
||||
|
||||
## User Experience Features
|
||||
|
||||
### Optimistic Updates
|
||||
|
||||
**Immediate Feedback:**
|
||||
- Reactions appear instantly when clicked
|
||||
- UI updates before network confirmation
|
||||
- Smooth animations and visual feedback
|
||||
|
||||
**Error Recovery:**
|
||||
- Failed reactions automatically revert
|
||||
- Clear error messages for network issues
|
||||
- Graceful degradation when offline
|
||||
|
||||
### Visual Design
|
||||
|
||||
**Reaction Badges:**
|
||||
- Highlighted when user has reacted
|
||||
- Shows emoji + count in compact format
|
||||
- Hover effects for better interactivity
|
||||
|
||||
**Emoji Picker:**
|
||||
- Grid layout with all available emojis
|
||||
- Accessible with keyboard navigation
|
||||
- Auto-closes after selection
|
||||
|
||||
### Accessibility
|
||||
|
||||
**Keyboard Support:**
|
||||
- Tab navigation through reactions
|
||||
- Enter/Space to toggle reactions
|
||||
- Escape to close emoji picker
|
||||
|
||||
**Screen Reader Support:**
|
||||
- Descriptive labels for all buttons
|
||||
- Reaction counts announced properly
|
||||
- Tooltip content accessible
|
||||
|
||||
## Real-time Synchronization
|
||||
|
||||
### Cache Management
|
||||
|
||||
**Automatic Invalidation:**
|
||||
```typescript
|
||||
// In useNostrPublish hook
|
||||
if (kind === 7) {
|
||||
const eTag = tags.find(([name]) => name === 'e')?.[1];
|
||||
if (eTag) {
|
||||
queryClient.invalidateQueries({ queryKey: ['comment-reactions', eTag] });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Background Refresh:**
|
||||
- 10 second stale time for fresh data
|
||||
- 30 second background refetch interval
|
||||
- Catches external reactions from other users
|
||||
|
||||
### Optimistic Update Flow
|
||||
|
||||
1. **User clicks reaction** → UI updates immediately
|
||||
2. **Event published** to Nostr network
|
||||
3. **On success** → Cache invalidated for real data
|
||||
4. **On error** → Optimistic update reverted
|
||||
|
||||
## Performance Optimizations
|
||||
|
||||
### Efficient Queries
|
||||
|
||||
**Targeted Fetching:**
|
||||
- Only fetch reactions for visible comments
|
||||
- Limit to 500 reactions per comment (reasonable max)
|
||||
- 3-second timeout for network requests
|
||||
|
||||
**Smart Caching:**
|
||||
- Per-comment reaction caching
|
||||
- Automatic cleanup of unused data
|
||||
- Optimized re-renders with React.memo
|
||||
|
||||
### Network Efficiency
|
||||
|
||||
**Batch Operations:**
|
||||
- Single query for all comment reactions
|
||||
- Efficient event filtering and processing
|
||||
- Minimal redundant network requests
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { EmojiReactions } from '@/components/comments/EmojiReactions';
|
||||
|
||||
function CommentCard({ comment }) {
|
||||
return (
|
||||
<div>
|
||||
<p>{comment.content}</p>
|
||||
<EmojiReactions
|
||||
commentId={comment.id}
|
||||
commentAuthor={comment.pubkey}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Styling
|
||||
|
||||
```tsx
|
||||
<EmojiReactions
|
||||
commentId={comment.id}
|
||||
commentAuthor={comment.pubkey}
|
||||
className="mt-3 border-t pt-3"
|
||||
/>
|
||||
```
|
||||
|
||||
## Demo Component
|
||||
|
||||
**File**: `src/components/EmojiReactionsDemo.tsx`
|
||||
|
||||
Provides interactive demonstration of:
|
||||
- Reaction toggling functionality
|
||||
- Emoji picker interface
|
||||
- Real-time update behavior
|
||||
- Available emoji set
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests
|
||||
|
||||
**Hook Testing:**
|
||||
- Reaction fetching and processing
|
||||
- Optimistic update logic
|
||||
- Error handling scenarios
|
||||
|
||||
**Component Testing:**
|
||||
- Emoji picker functionality
|
||||
- Reaction badge interactions
|
||||
- Loading and error states
|
||||
|
||||
### Integration Tests
|
||||
|
||||
**Real-time Flow:**
|
||||
- End-to-end reaction posting
|
||||
- Cache invalidation verification
|
||||
- Cross-user reaction visibility
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
### Potential Improvements
|
||||
|
||||
**Custom Emojis:**
|
||||
- Support for custom emoji reactions
|
||||
- Unicode emoji search functionality
|
||||
- Reaction categories and organization
|
||||
|
||||
**Enhanced Analytics:**
|
||||
- Reaction trend analysis
|
||||
- Popular emoji tracking
|
||||
- User engagement metrics
|
||||
|
||||
**Advanced Features:**
|
||||
- Reaction notifications
|
||||
- Bulk reaction operations
|
||||
- Reaction history viewing
|
||||
|
||||
### Scalability Considerations
|
||||
|
||||
**Large Comment Threads:**
|
||||
- Pagination for reactions
|
||||
- Virtual scrolling for performance
|
||||
- Lazy loading of reaction data
|
||||
|
||||
**High-Traffic Scenarios:**
|
||||
- Rate limiting for reactions
|
||||
- Debounced optimistic updates
|
||||
- Efficient WebSocket integration
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Spam Prevention
|
||||
|
||||
**Rate Limiting:**
|
||||
- Client-side debouncing
|
||||
- Reasonable reaction frequency limits
|
||||
- User authentication requirements
|
||||
|
||||
**Content Validation:**
|
||||
- Emoji format validation
|
||||
- Maximum reaction count per user
|
||||
- Malicious content filtering
|
||||
|
||||
### Privacy
|
||||
|
||||
**User Data:**
|
||||
- Reaction anonymity options
|
||||
- Configurable visibility settings
|
||||
- GDPR compliance considerations
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
**Reactions Not Appearing:**
|
||||
- Check user authentication status
|
||||
- Verify network connectivity
|
||||
- Confirm relay accessibility
|
||||
|
||||
**Performance Problems:**
|
||||
- Monitor query cache size
|
||||
- Check for memory leaks
|
||||
- Optimize re-render frequency
|
||||
|
||||
**Synchronization Issues:**
|
||||
- Validate event publishing
|
||||
- Check cache invalidation logic
|
||||
- Verify real-time polling intervals
|
||||
|
||||
### Debug Tools
|
||||
|
||||
**Development Helpers:**
|
||||
- React Query DevTools integration
|
||||
- Console logging for cache operations
|
||||
- Network request monitoring
|
||||
|
||||
This emoji reactions system enhances user engagement while maintaining excellent performance and real-time synchronization across the Nostr network.
|
||||
@@ -0,0 +1,112 @@
|
||||
import React from 'react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { EmojiReactions } from '@/components/comments/EmojiReactions';
|
||||
import { EMOJI_REACTIONS } from '@/hooks/useCommentReactions';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { LoginArea } from '@/components/auth/LoginArea';
|
||||
import { Smile, Heart, Zap } from 'lucide-react';
|
||||
|
||||
/**
|
||||
* Demo component showing emoji reactions functionality
|
||||
* This demonstrates how users can react to comments with emojis
|
||||
*/
|
||||
export function EmojiReactionsDemo() {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Smile className="h-5 w-5" />
|
||||
Emoji Reactions Demo
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
This demo shows how emoji reactions work on comments.
|
||||
Please log in to test the functionality.
|
||||
</p>
|
||||
<LoginArea />
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Smile className="h-5 w-5" />
|
||||
Emoji Reactions Demo
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
Try out emoji reactions on this demo comment. Click existing reactions to toggle them, or add new ones!
|
||||
</p>
|
||||
|
||||
<div className="bg-muted/50 p-4 rounded-lg space-y-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-primary/20 rounded-full flex items-center justify-center">
|
||||
<span className="text-sm">👤</span>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium text-sm">Demo User</p>
|
||||
<p className="text-xs text-muted-foreground">2 minutes ago</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-sm">
|
||||
This is a demo comment to showcase emoji reactions!
|
||||
Try clicking the reactions below or adding your own.
|
||||
</p>
|
||||
|
||||
{/* Demo Emoji Reactions */}
|
||||
<EmojiReactions
|
||||
commentId="demo-comment-123"
|
||||
commentAuthor="demo-author-pubkey"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t pt-6">
|
||||
<h4 className="font-medium mb-4 flex items-center gap-2">
|
||||
<Heart className="h-4 w-4" />
|
||||
Available Reactions
|
||||
</h4>
|
||||
<div className="grid grid-cols-4 gap-3">
|
||||
{EMOJI_REACTIONS.map(({ emoji, label }) => (
|
||||
<div key={emoji} className="flex flex-col items-center gap-1">
|
||||
<div className="text-2xl">{emoji}</div>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{label}
|
||||
</Badge>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-muted/50 p-4 rounded-lg">
|
||||
<h5 className="font-medium text-sm mb-2 flex items-center gap-2">
|
||||
<Zap className="h-4 w-4" />
|
||||
How it works:
|
||||
</h5>
|
||||
<ul className="text-sm text-muted-foreground space-y-1">
|
||||
<li>• <strong>Click existing reactions</strong> to toggle your reaction on/off</li>
|
||||
<li>• <strong>Use the smile button</strong> to add new emoji reactions</li>
|
||||
<li>• <strong>Hover over reactions</strong> to see who reacted</li>
|
||||
<li>• <strong>Real-time updates</strong> show reactions instantly</li>
|
||||
<li>• <strong>Optimistic UI</strong> makes interactions feel immediate</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-muted-foreground">
|
||||
💡 Tip: Emoji reactions use Nostr kind 7 events and support real-time synchronization across all clients.
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { nip19 } from 'nostr-tools';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useComments } from '@/hooks/useComments';
|
||||
import { CommentForm } from './CommentForm';
|
||||
import { EmojiReactions } from './EmojiReactions';
|
||||
import { NoteContent } from '@/components/NoteContent';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -26,10 +27,10 @@ interface CommentProps {
|
||||
export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: CommentProps) {
|
||||
const [showReplyForm, setShowReplyForm] = useState(false);
|
||||
const [showReplies, setShowReplies] = useState(depth < 2); // Auto-expand first 2 levels
|
||||
|
||||
|
||||
const author = useAuthor(comment.pubkey);
|
||||
const { data: commentsData } = useComments(root, limit);
|
||||
|
||||
|
||||
const metadata = author.data?.metadata;
|
||||
const displayName = metadata?.name ?? genUserName(comment.pubkey)
|
||||
const timeAgo = formatDistanceToNow(new Date(comment.created_at * 1000), { addSuffix: true });
|
||||
@@ -55,7 +56,7 @@ export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: Comme
|
||||
</Avatar>
|
||||
</Link>
|
||||
<div>
|
||||
<Link
|
||||
<Link
|
||||
to={`/${nip19.npubEncode(comment.pubkey)}`}
|
||||
className="font-medium text-sm hover:text-primary transition-colors"
|
||||
>
|
||||
@@ -71,6 +72,13 @@ export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: Comme
|
||||
<NoteContent event={comment} className="text-sm" />
|
||||
</div>
|
||||
|
||||
{/* Emoji Reactions */}
|
||||
<EmojiReactions
|
||||
commentId={comment.id}
|
||||
commentAuthor={comment.pubkey}
|
||||
className="pt-2"
|
||||
/>
|
||||
|
||||
{/* Comment Actions */}
|
||||
<div className="flex items-center justify-between pt-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
@@ -83,7 +91,7 @@ export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: Comme
|
||||
<MessageSquare className="h-3 w-3 mr-1" />
|
||||
Reply
|
||||
</Button>
|
||||
|
||||
|
||||
{hasReplies && (
|
||||
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
|
||||
<CollapsibleTrigger asChild>
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import {
|
||||
useCommentReactions,
|
||||
useAddCommentReaction,
|
||||
EMOJI_REACTIONS,
|
||||
type CommentReaction
|
||||
} from '@/hooks/useCommentReactions';
|
||||
import { Smile, Plus } from 'lucide-react';
|
||||
|
||||
interface EmojiReactionsProps {
|
||||
commentId: string;
|
||||
commentAuthor: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function EmojiReactions({ commentId, commentAuthor, className }: EmojiReactionsProps) {
|
||||
const { user } = useCurrentUser();
|
||||
const { data: reactions = [], isLoading } = useCommentReactions(commentId);
|
||||
const { mutate: addReaction, isPending: isAddingReaction } = useAddCommentReaction();
|
||||
const [isPopoverOpen, setIsPopoverOpen] = useState(false);
|
||||
|
||||
const handleReactionToggle = (emoji: string) => {
|
||||
if (!user) return;
|
||||
|
||||
addReaction({
|
||||
commentId,
|
||||
emoji,
|
||||
commentAuthor,
|
||||
isToggle: true,
|
||||
});
|
||||
};
|
||||
|
||||
const handleEmojiSelect = (emoji: string) => {
|
||||
addReaction({
|
||||
commentId,
|
||||
emoji,
|
||||
commentAuthor,
|
||||
isToggle: false, // Always add when selecting from picker
|
||||
});
|
||||
setIsPopoverOpen(false);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className={`flex items-center gap-1 ${className}`}>
|
||||
<div className="flex gap-1">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="h-6 w-12 bg-muted animate-pulse rounded-full"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<div className={`flex items-center gap-1 flex-wrap ${className}`}>
|
||||
{/* Existing Reactions */}
|
||||
{reactions.map((reaction) => (
|
||||
<ReactionBadge
|
||||
key={reaction.emoji}
|
||||
reaction={reaction}
|
||||
onToggle={() => handleReactionToggle(reaction.emoji)}
|
||||
disabled={isAddingReaction}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Add Reaction Button */}
|
||||
<Popover open={isPopoverOpen} onOpenChange={setIsPopoverOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-2 text-xs hover:bg-muted/50"
|
||||
disabled={!user || isAddingReaction}
|
||||
>
|
||||
<Smile className="h-3 w-3 mr-1" />
|
||||
<Plus className="h-2 w-2" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-2" align="start">
|
||||
<div className="grid grid-cols-4 gap-1">
|
||||
{EMOJI_REACTIONS.map(({ emoji, label }) => (
|
||||
<Button
|
||||
key={emoji}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-10 w-10 p-0 hover:bg-muted/50"
|
||||
onClick={() => handleEmojiSelect(emoji)}
|
||||
title={label}
|
||||
>
|
||||
<span className="text-lg">{emoji}</span>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
interface ReactionBadgeProps {
|
||||
reaction: CommentReaction;
|
||||
onToggle: () => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
function ReactionBadge({ reaction, onToggle, disabled }: ReactionBadgeProps) {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant={reaction.userReacted ? "default" : "secondary"}
|
||||
size="sm"
|
||||
className={`h-6 px-2 text-xs gap-1 ${
|
||||
reaction.userReacted
|
||||
? 'bg-primary/10 text-primary border-primary/20 hover:bg-primary/20'
|
||||
: 'hover:bg-muted/50'
|
||||
}`}
|
||||
onClick={onToggle}
|
||||
disabled={!user || disabled}
|
||||
>
|
||||
<span>{reaction.emoji}</span>
|
||||
<span className="text-xs">{reaction.count}</span>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<ReactionTooltip reaction={reaction} />
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function ReactionTooltip({ reaction }: { reaction: CommentReaction }) {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Simple tooltip for now - we'll show count and emoji
|
||||
// In the future, we could create a separate component to fetch user names
|
||||
const tooltipText = user && reaction.users.includes(user.pubkey)
|
||||
? `You and ${reaction.count - 1} other${reaction.count > 2 ? 's' : ''} reacted with ${reaction.emoji}`
|
||||
: `${reaction.count} ${reaction.count === 1 ? 'person' : 'people'} reacted with ${reaction.emoji}`;
|
||||
|
||||
return <span className="text-sm">{tooltipText}</span>;
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
// Predefined emoji reactions
|
||||
export const EMOJI_REACTIONS = [
|
||||
{ emoji: '👍', label: 'thumbs up' },
|
||||
{ emoji: '❤️', label: 'heart' },
|
||||
{ emoji: '😂', label: 'laugh' },
|
||||
{ emoji: '😮', label: 'wow' },
|
||||
{ emoji: '😢', label: 'sad' },
|
||||
{ emoji: '😡', label: 'angry' },
|
||||
{ emoji: '🎉', label: 'celebrate' },
|
||||
{ emoji: '🔥', label: 'fire' },
|
||||
] as const;
|
||||
|
||||
export type EmojiReaction = typeof EMOJI_REACTIONS[number];
|
||||
|
||||
export interface CommentReaction {
|
||||
emoji: string;
|
||||
count: number;
|
||||
userReacted: boolean;
|
||||
users: string[]; // pubkeys of users who reacted
|
||||
}
|
||||
|
||||
export interface CommentReactions {
|
||||
[emoji: string]: CommentReaction;
|
||||
}
|
||||
|
||||
export function useCommentReactions(commentId: string) {
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['comment-reactions', commentId],
|
||||
queryFn: async () => {
|
||||
// Fetch kind 7 reactions that reference this comment
|
||||
const reactions = await nostr.query(
|
||||
[
|
||||
{
|
||||
kinds: [7],
|
||||
'#e': [commentId],
|
||||
limit: 500,
|
||||
},
|
||||
],
|
||||
{ signal: AbortSignal.timeout(3000) }
|
||||
);
|
||||
|
||||
// Group reactions by emoji and user, keeping only the latest reaction from each user
|
||||
const userReactions = new Map<string, Map<string, NostrEvent>>();
|
||||
|
||||
for (const reaction of reactions) {
|
||||
let emoji = reaction.content;
|
||||
const isRemoval = emoji.startsWith('-');
|
||||
|
||||
if (isRemoval) {
|
||||
emoji = emoji.slice(1); // Remove the "-" prefix
|
||||
}
|
||||
|
||||
if (!emoji || emoji.length > 10) continue; // Skip invalid emojis
|
||||
|
||||
if (!userReactions.has(emoji)) {
|
||||
userReactions.set(emoji, new Map());
|
||||
}
|
||||
|
||||
const emojiReactions = userReactions.get(emoji)!;
|
||||
const existingReaction = emojiReactions.get(reaction.pubkey);
|
||||
|
||||
// Keep only the latest reaction from each user
|
||||
if (!existingReaction || reaction.created_at > existingReaction.created_at) {
|
||||
emojiReactions.set(reaction.pubkey, reaction);
|
||||
}
|
||||
}
|
||||
|
||||
// Build the final reaction map
|
||||
const reactionMap: { [emoji: string]: CommentReaction } = {};
|
||||
|
||||
for (const [emoji, userReactionMap] of userReactions) {
|
||||
const activeUsers: string[] = [];
|
||||
let userReacted = false;
|
||||
|
||||
for (const [pubkey, reaction] of userReactionMap) {
|
||||
const isRemoval = reaction.content.startsWith('-');
|
||||
|
||||
if (!isRemoval) {
|
||||
activeUsers.push(pubkey);
|
||||
if (user && pubkey === user.pubkey) {
|
||||
userReacted = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (activeUsers.length > 0) {
|
||||
reactionMap[emoji] = {
|
||||
emoji,
|
||||
count: activeUsers.length,
|
||||
userReacted,
|
||||
users: activeUsers,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by count (most popular first)
|
||||
const sortedReactions = Object.values(reactionMap)
|
||||
.filter(reaction => reaction.count > 0)
|
||||
.sort((a, b) => b.count - a.count);
|
||||
|
||||
return sortedReactions;
|
||||
},
|
||||
enabled: !!commentId,
|
||||
staleTime: 10000, // 10 seconds
|
||||
refetchInterval: 30000, // 30 seconds
|
||||
});
|
||||
}
|
||||
|
||||
export function useAddCommentReaction() {
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: publishEvent } = useNostrPublish();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ commentId, emoji, commentAuthor, isToggle = false }: {
|
||||
commentId: string;
|
||||
emoji: string;
|
||||
commentAuthor: string;
|
||||
isToggle?: boolean;
|
||||
}) => {
|
||||
if (!user) {
|
||||
throw new Error('User must be logged in to react');
|
||||
}
|
||||
|
||||
// Get current reactions to determine if this is an add or remove
|
||||
const currentReactions = queryClient.getQueryData(['comment-reactions', commentId]) as CommentReaction[] | undefined;
|
||||
const existingReaction = currentReactions?.find(r => r.emoji === emoji && r.userReacted);
|
||||
|
||||
const content = (isToggle && existingReaction) ? `-${emoji}` : emoji;
|
||||
|
||||
// Publish kind 7 reaction event
|
||||
return new Promise<NostrEvent>((resolve, reject) => {
|
||||
publishEvent({
|
||||
kind: 7,
|
||||
content,
|
||||
tags: [
|
||||
['e', commentId],
|
||||
['p', commentAuthor],
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
}, {
|
||||
onSuccess: (event) => resolve(event),
|
||||
onError: (error) => reject(error),
|
||||
});
|
||||
});
|
||||
},
|
||||
onMutate: async ({ commentId, emoji, isToggle = false }) => {
|
||||
if (!user) return;
|
||||
|
||||
const queryKey = ['comment-reactions', commentId];
|
||||
|
||||
// Cancel any outgoing refetches
|
||||
await queryClient.cancelQueries({ queryKey });
|
||||
|
||||
// Snapshot the previous value
|
||||
const previousReactions = queryClient.getQueryData(queryKey);
|
||||
|
||||
// Optimistically update the cache
|
||||
queryClient.setQueryData(queryKey, (old: CommentReaction[] = []) => {
|
||||
const newReactions = [...old];
|
||||
|
||||
// Find existing reaction for this emoji
|
||||
const existingReactionIndex = newReactions.findIndex(r => r.emoji === emoji);
|
||||
|
||||
if (existingReactionIndex >= 0) {
|
||||
// Update existing reaction
|
||||
const existingReaction = newReactions[existingReactionIndex];
|
||||
|
||||
if (isToggle && existingReaction.userReacted) {
|
||||
// User is removing their reaction
|
||||
newReactions[existingReactionIndex] = {
|
||||
...existingReaction,
|
||||
count: Math.max(0, existingReaction.count - 1),
|
||||
userReacted: false,
|
||||
users: existingReaction.users.filter(pubkey => pubkey !== user.pubkey),
|
||||
};
|
||||
|
||||
// Remove reaction if count reaches 0
|
||||
if (newReactions[existingReactionIndex].count === 0) {
|
||||
newReactions.splice(existingReactionIndex, 1);
|
||||
}
|
||||
} else if (!existingReaction.userReacted) {
|
||||
// User is adding their reaction
|
||||
newReactions[existingReactionIndex] = {
|
||||
...existingReaction,
|
||||
count: existingReaction.count + 1,
|
||||
userReacted: true,
|
||||
users: [...existingReaction.users, user.pubkey],
|
||||
};
|
||||
}
|
||||
} else {
|
||||
// Add new reaction
|
||||
newReactions.push({
|
||||
emoji,
|
||||
count: 1,
|
||||
userReacted: true,
|
||||
users: [user.pubkey],
|
||||
});
|
||||
}
|
||||
|
||||
// Sort by count (most popular first)
|
||||
return newReactions
|
||||
.filter(reaction => reaction.count > 0)
|
||||
.sort((a, b) => b.count - a.count);
|
||||
});
|
||||
|
||||
return { previousReactions };
|
||||
},
|
||||
onError: (err, { commentId }, context) => {
|
||||
// If the mutation fails, use the context returned from onMutate to roll back
|
||||
const queryKey = ['comment-reactions', commentId];
|
||||
queryClient.setQueryData(queryKey, context?.previousReactions);
|
||||
},
|
||||
onSuccess: (_, { commentId }) => {
|
||||
// Invalidate and refetch to get the real data
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['comment-reactions', commentId]
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -49,12 +49,14 @@ export function useNostrPublish(): UseMutationResult<NostrEvent> {
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'comments'] });
|
||||
}
|
||||
|
||||
// Ratings (kind 7)
|
||||
// Ratings and Emoji Reactions (kind 7)
|
||||
if (kind === 7) {
|
||||
// Invalidate rating queries for the target event
|
||||
const eTag = tags.find(([name]) => name === 'e')?.[1];
|
||||
if (eTag) {
|
||||
queryClient.invalidateQueries({ queryKey: ['ratings', eTag] });
|
||||
// Also invalidate comment reactions if this is a reaction to a comment
|
||||
queryClient.invalidateQueries({ queryKey: ['comment-reactions', eTag] });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user