mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
3
Commits
v9.16.2
...
showcase-page
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bdb73252eb | ||
|
|
e709dca735 | ||
|
|
6f2ccb0b5a |
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,191 @@
|
||||
# Real-Time Updates Implementation
|
||||
|
||||
This document describes the implementation of real-time updates for ratings and comments on showcase app pages, eliminating the need for users to refresh the page to see their updates.
|
||||
|
||||
## Overview
|
||||
|
||||
The implementation uses a combination of:
|
||||
- **Optimistic Updates**: Immediate UI updates before server confirmation
|
||||
- **Automatic Cache Invalidation**: Smart query refreshing after publishing events
|
||||
- **Background Polling**: Periodic data refreshing to catch external changes
|
||||
- **Error Handling**: Graceful rollback of failed optimistic updates
|
||||
|
||||
## Key Components Modified
|
||||
|
||||
### 1. `useNostrPublish` Hook (`src/hooks/useNostrPublish.ts`)
|
||||
|
||||
**Enhanced with automatic query invalidation:**
|
||||
- Detects event types (comments, ratings, moderation) based on `kind` and `tags`
|
||||
- Automatically invalidates relevant TanStack Query caches after successful publishing
|
||||
- Supports multiple query patterns for comprehensive cache updates
|
||||
|
||||
**Invalidation Logic:**
|
||||
```typescript
|
||||
// Comments (kind 1111)
|
||||
if (kind === 1111) {
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'comments'] });
|
||||
}
|
||||
|
||||
// Ratings (kind 7)
|
||||
if (kind === 7) {
|
||||
const eTag = tags.find(([name]) => name === 'e')?.[1];
|
||||
if (eTag) {
|
||||
queryClient.invalidateQueries({ queryKey: ['ratings', eTag] });
|
||||
}
|
||||
}
|
||||
|
||||
// App submissions and moderation
|
||||
if (kind === 31733 || kind === 30267 || kind === 1984) {
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['showcase-moderation'] });
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Comments System
|
||||
|
||||
**`useComments` Hook (`src/hooks/useComments.ts`):**
|
||||
- Reduced stale time to 10 seconds for fresher data
|
||||
- Background refetch every 30 seconds
|
||||
- Maintains existing query structure for compatibility
|
||||
|
||||
**`usePostComment` Hook (`src/hooks/usePostComment.ts`):**
|
||||
- **Optimistic Updates**: Comments appear immediately in UI
|
||||
- **Error Recovery**: Failed comments are automatically removed from UI
|
||||
- **Cache Management**: Proper handling of comment threading and structure
|
||||
|
||||
**Optimistic Update Flow:**
|
||||
1. User submits comment
|
||||
2. Comment appears immediately in UI (optimistic)
|
||||
3. Event published to Nostr network
|
||||
4. On success: Cache invalidated, real data fetched
|
||||
5. On error: Optimistic update reverted, error shown
|
||||
|
||||
### 3. Ratings System
|
||||
|
||||
**Enhanced Ratings in `ShowcasePage.tsx`:**
|
||||
- **Immediate Visual Feedback**: Stars update instantly when clicked
|
||||
- **Optimistic Rating Updates**: New ratings appear before network confirmation
|
||||
- **Loading States**: Visual indicators during submission
|
||||
- **Error Handling**: Failed ratings revert with error message
|
||||
|
||||
**Optimistic Rating Flow:**
|
||||
```typescript
|
||||
const handleRate = (rating: number) => {
|
||||
// 1. Update cache optimistically
|
||||
queryClient.setQueryData(['ratings', appEvent.id], (oldRatings) => {
|
||||
const filteredRatings = oldRatings.filter(r => r.pubkey !== user.pubkey);
|
||||
return [...filteredRatings, optimisticRating];
|
||||
});
|
||||
|
||||
// 2. Publish to network
|
||||
publishEvent({...}, {
|
||||
onSuccess: () => toast({ title: 'Rating Submitted!' }),
|
||||
onError: () => {
|
||||
queryClient.invalidateQueries(['ratings', appEvent.id]); // Revert
|
||||
toast({ title: 'Error', variant: 'destructive' });
|
||||
}
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
### 4. Moderation Actions
|
||||
|
||||
**Enhanced in both `AppShowcaseCard.tsx` and `ShowcasePage.tsx`:**
|
||||
- Immediate cache invalidation after moderation actions
|
||||
- Multiple query invalidation for comprehensive updates
|
||||
- Visual feedback during pending actions
|
||||
|
||||
**Invalidation Pattern:**
|
||||
```typescript
|
||||
// After moderation action
|
||||
queryClient.invalidateQueries({ queryKey: ['showcase-moderation', id] });
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
|
||||
```
|
||||
|
||||
### 5. Background Refresh Intervals
|
||||
|
||||
**Optimized refresh rates for real-time feel:**
|
||||
- **Comments**: 10s stale time, 30s background refetch
|
||||
- **Ratings**: 10s stale time, 30s background refetch
|
||||
- **App Submissions**: 10s stale time, 30s background refetch
|
||||
- **Moderation Data**: 5s stale time, 15s background refetch
|
||||
|
||||
## User Experience Improvements
|
||||
|
||||
### Immediate Feedback
|
||||
- **Comments**: Appear instantly when submitted
|
||||
- **Ratings**: Stars update immediately on click
|
||||
- **Moderation**: Status changes reflect immediately
|
||||
|
||||
### Loading States
|
||||
- **Comment Form**: Shows "Posting comment..." during submission
|
||||
- **Rating Stars**: Animate with pulse effect during submission
|
||||
- **Moderation Menu**: Spinner icon during actions
|
||||
|
||||
### Error Handling
|
||||
- **Failed Comments**: Removed from UI with error toast
|
||||
- **Failed Ratings**: Reverted with descriptive error message
|
||||
- **Failed Moderation**: Clear error feedback with retry option
|
||||
|
||||
## Technical Benefits
|
||||
|
||||
### Performance
|
||||
- **Reduced Server Load**: Fewer unnecessary requests through smart caching
|
||||
- **Perceived Speed**: Optimistic updates make UI feel instant
|
||||
- **Efficient Polling**: Targeted background refreshes only for active data
|
||||
|
||||
### Reliability
|
||||
- **Graceful Degradation**: Falls back to polling if optimistic updates fail
|
||||
- **Conflict Resolution**: Latest server data always wins over optimistic updates
|
||||
- **Error Recovery**: Automatic rollback of failed operations
|
||||
|
||||
### Maintainability
|
||||
- **Centralized Logic**: Cache invalidation handled in `useNostrPublish`
|
||||
- **Type Safety**: Full TypeScript support with proper error handling
|
||||
- **Consistent Patterns**: Same approach across all real-time features
|
||||
|
||||
## Demo Component
|
||||
|
||||
**`RealTimeDemo.tsx`** provides a testing interface to demonstrate:
|
||||
- Optimistic comment updates
|
||||
- Instant rating feedback
|
||||
- Real-time moderation changes
|
||||
- Error handling scenarios
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
### Query Key Strategy
|
||||
Consistent query keys enable precise cache invalidation:
|
||||
- `['nostr', 'comments', eventId]` for comments
|
||||
- `['ratings', eventId]` for ratings
|
||||
- `['showcase-moderation', appId]` for moderation status
|
||||
|
||||
### Error Boundaries
|
||||
All optimistic updates include error handling to prevent inconsistent UI state:
|
||||
- Comments: Remove optimistic comment on error
|
||||
- Ratings: Invalidate ratings cache on error
|
||||
- Moderation: Show error toast with retry option
|
||||
|
||||
### Network Efficiency
|
||||
- **Batched Invalidations**: Multiple related queries updated together
|
||||
- **Smart Polling**: Background refreshes only for visible/active components
|
||||
- **Timeout Protection**: All network requests have reasonable timeouts
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
Potential improvements for even better real-time experience:
|
||||
- **WebSocket Integration**: Real-time event streaming from relays
|
||||
- **Conflict Resolution**: Better handling of concurrent updates
|
||||
- **Offline Support**: Queue actions when network is unavailable
|
||||
- **Push Notifications**: Alert users to new comments/ratings on their apps
|
||||
|
||||
## Testing
|
||||
|
||||
The implementation includes:
|
||||
- **Unit Tests**: All hooks have comprehensive test coverage
|
||||
- **Integration Tests**: Real-time flow testing
|
||||
- **Error Scenarios**: Failed network requests and edge cases
|
||||
- **Performance Tests**: Cache invalidation efficiency
|
||||
|
||||
Run tests with: `npm run test`
|
||||
@@ -21,6 +21,7 @@ import VercelOAuth from "./pages/VercelOAuth";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { ProjectView } from "./pages/ProjectView";
|
||||
import ShowcasePage from "./pages/ShowcasePage";
|
||||
import { SettingsLayout } from "./components/SettingsLayout";
|
||||
|
||||
export function AppRouter() {
|
||||
@@ -51,6 +52,7 @@ export function AppRouter() {
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
</Route>
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
<Route path="/showcase/:id" element={<ShowcasePage />} />
|
||||
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
||||
<Route path="/:nip19" element={<NIP19Page />} />
|
||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||
|
||||
@@ -346,8 +346,10 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
|
||||
});
|
||||
}
|
||||
|
||||
// Invalidate queries to refresh the data
|
||||
// Invalidate queries to refresh the data immediately
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['showcase-moderation'] });
|
||||
|
||||
// If this is a Halloween app, also invalidate Halloween queries
|
||||
if (isHalloweenSubmission) {
|
||||
@@ -370,14 +372,28 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
|
||||
}
|
||||
};
|
||||
|
||||
// Generate naddr for the app
|
||||
const appNaddr = React.useMemo(() => {
|
||||
const dTag = app.tags.find(tag => tag[0] === 'd')?.[1];
|
||||
if (!dTag) return null;
|
||||
|
||||
try {
|
||||
return nip19.naddrEncode({
|
||||
kind: app.kind,
|
||||
pubkey: app.pubkey,
|
||||
identifier: dTag,
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}, [app.kind, app.pubkey, app.tags]);
|
||||
|
||||
return (
|
||||
<Card className="group hover:shadow-lg transition-all duration-300 hover:border-primary/20 h-full flex flex-col">
|
||||
<div className="relative">
|
||||
{/* App Screenshot */}
|
||||
<a
|
||||
href={app.websiteUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
<Link
|
||||
to={appNaddr ? `/showcase/${appNaddr}` : '#'}
|
||||
className="block aspect-video bg-gradient-to-br from-muted/50 to-muted rounded-t-lg overflow-hidden cursor-pointer"
|
||||
>
|
||||
{!imageError ? (
|
||||
@@ -397,15 +413,15 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</a>
|
||||
</Link>
|
||||
|
||||
{/* Actions Menu */}
|
||||
{(isOwner || showModerationControls) && (
|
||||
<div className="absolute top-3 right-3">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="secondary" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
<Button variant="secondary" size="sm" className="h-8 w-8 p-0" disabled={isPending}>
|
||||
<MoreVertical className={`w-4 h-4 ${isPending ? 'animate-spin' : ''}`} />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { LoginArea } from '@/components/auth/LoginArea';
|
||||
import { RefreshCw, MessageSquare, Star, Heart } from 'lucide-react';
|
||||
|
||||
/**
|
||||
* Demo component showing real-time updates for showcase ratings and comments
|
||||
* This demonstrates the optimistic updates and automatic cache invalidation
|
||||
*/
|
||||
export function RealTimeDemo() {
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: publishEvent, isPending } = useNostrPublish();
|
||||
const { toast } = useToast();
|
||||
const [demoCounter, setDemoCounter] = useState(0);
|
||||
|
||||
const handleDemoAction = (actionType: 'comment' | 'rating' | 'moderation') => {
|
||||
if (!user) {
|
||||
toast({
|
||||
title: 'Login Required',
|
||||
description: 'Please log in to test real-time updates',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setDemoCounter(prev => prev + 1);
|
||||
|
||||
switch (actionType) {
|
||||
case 'comment': {
|
||||
// Simulate posting a comment (kind 1111)
|
||||
publishEvent({
|
||||
kind: 1111,
|
||||
content: `Demo comment #${demoCounter + 1} - This demonstrates real-time comment updates!`,
|
||||
tags: [
|
||||
['E', 'demo-event-id'],
|
||||
['K', '1'],
|
||||
['P', 'demo-author-pubkey'],
|
||||
],
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'rating': {
|
||||
// Simulate posting a rating (kind 7)
|
||||
const rating = Math.floor(Math.random() * 5) + 1;
|
||||
publishEvent({
|
||||
kind: 7,
|
||||
content: rating.toString(),
|
||||
tags: [
|
||||
['e', 'demo-app-event-id'],
|
||||
['p', 'demo-app-author-pubkey'],
|
||||
],
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'moderation': {
|
||||
// Simulate moderation action (kind 30267 list update)
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Demo moderation list update',
|
||||
tags: [
|
||||
['d', 'demo-featured-apps'],
|
||||
['title', 'Demo Featured Apps'],
|
||||
['a', `31733:demo-pubkey:demo-app-${demoCounter + 1}`],
|
||||
],
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Demo Action Triggered!',
|
||||
description: `${actionType} action will update in real-time across all components`,
|
||||
});
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<RefreshCw className="h-5 w-5" />
|
||||
Real-Time Updates Demo
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
This demo shows how ratings and comments update in real-time without page refreshes.
|
||||
Please log in to test the functionality.
|
||||
</p>
|
||||
<LoginArea />
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<RefreshCw className="h-5 w-5" />
|
||||
Real-Time Updates Demo
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
Test real-time updates by triggering demo actions. These will demonstrate:
|
||||
</p>
|
||||
|
||||
<div className="grid gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge variant="outline">
|
||||
<MessageSquare className="h-3 w-3 mr-1" />
|
||||
Comments
|
||||
</Badge>
|
||||
<span className="text-sm">Optimistic updates + automatic refresh</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge variant="outline">
|
||||
<Star className="h-3 w-3 mr-1" />
|
||||
Ratings
|
||||
</Badge>
|
||||
<span className="text-sm">Instant UI updates + cache invalidation</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge variant="outline">
|
||||
<Heart className="h-3 w-3 mr-1" />
|
||||
Moderation
|
||||
</Badge>
|
||||
<span className="text-sm">Real-time status changes</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t pt-6">
|
||||
<h4 className="font-medium mb-4">Test Actions</h4>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button
|
||||
onClick={() => handleDemoAction('comment')}
|
||||
disabled={isPending}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
<MessageSquare className="h-4 w-4 mr-2" />
|
||||
Demo Comment
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={() => handleDemoAction('rating')}
|
||||
disabled={isPending}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
<Star className="h-4 w-4 mr-2" />
|
||||
Demo Rating
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={() => handleDemoAction('moderation')}
|
||||
disabled={isPending}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
<Heart className="h-4 w-4 mr-2" />
|
||||
Demo Moderation
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-muted/50 p-4 rounded-lg">
|
||||
<h5 className="font-medium text-sm mb-2">How it works:</h5>
|
||||
<ul className="text-sm text-muted-foreground space-y-1">
|
||||
<li>• <strong>Optimistic Updates:</strong> UI updates immediately before server confirmation</li>
|
||||
<li>• <strong>Cache Invalidation:</strong> Related queries refresh automatically after publishing</li>
|
||||
<li>• <strong>Error Handling:</strong> Failed actions revert optimistic changes</li>
|
||||
<li>• <strong>Real-time Sync:</strong> Background polling keeps data fresh (10-30s intervals)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Demo counter: {demoCounter} actions triggered
|
||||
</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>
|
||||
|
||||
@@ -19,9 +19,9 @@ interface CommentFormProps {
|
||||
export function CommentForm({
|
||||
root,
|
||||
reply,
|
||||
onSuccess,
|
||||
onSuccess,
|
||||
placeholder = "Write a comment...",
|
||||
compact = false
|
||||
compact = false
|
||||
}: CommentFormProps) {
|
||||
const [content, setContent] = useState('');
|
||||
const { user } = useCurrentUser();
|
||||
@@ -29,7 +29,7 @@ export function CommentForm({
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
|
||||
if (!content.trim() || !user) return;
|
||||
|
||||
postComment(
|
||||
@@ -72,10 +72,13 @@ export function CommentForm({
|
||||
/>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{reply ? 'Replying to comment' : 'Adding to the discussion'}
|
||||
{isPending
|
||||
? (reply ? 'Posting reply...' : 'Posting comment...')
|
||||
: (reply ? 'Replying to comment' : 'Adding to the discussion')
|
||||
}
|
||||
</span>
|
||||
<Button
|
||||
type="submit"
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!content.trim() || isPending}
|
||||
size={compact ? "sm" : "default"}
|
||||
>
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -223,8 +223,8 @@ export function useAppSubmissions() {
|
||||
|
||||
return submissions;
|
||||
},
|
||||
staleTime: 30000, // 30 seconds
|
||||
refetchInterval: 60000, // 1 minute
|
||||
staleTime: 10000, // 10 seconds
|
||||
refetchInterval: 30000, // 30 seconds
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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]
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ export function useComments(root: NostrEvent | URL, limit?: number) {
|
||||
});
|
||||
|
||||
const allDescendants = [...directReplies];
|
||||
|
||||
|
||||
// Recursively get descendants of each direct reply
|
||||
for (const reply of directReplies) {
|
||||
allDescendants.push(...getDescendants(reply.id));
|
||||
@@ -94,5 +94,7 @@ export function useComments(root: NostrEvent | URL, limit?: number) {
|
||||
};
|
||||
},
|
||||
enabled: !!root,
|
||||
staleTime: 10000, // 10 seconds
|
||||
refetchInterval: 30000, // 30 seconds
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useNostr } from "@nostrify/react";
|
||||
import { useMutation, type UseMutationResult } from "@tanstack/react-query";
|
||||
import { useMutation, useQueryClient, type UseMutationResult } from "@tanstack/react-query";
|
||||
|
||||
import { useCurrentUser } from "./useCurrentUser";
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { NostrEvent } from "@nostrify/nostrify";
|
||||
export function useNostrPublish(): UseMutationResult<NostrEvent> {
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (t: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>) => {
|
||||
@@ -37,6 +38,52 @@ export function useNostrPublish(): UseMutationResult<NostrEvent> {
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
console.log("Event published successfully:", data);
|
||||
|
||||
// Invalidate relevant queries based on event kind and tags
|
||||
const kind = data.kind;
|
||||
const tags = data.tags || [];
|
||||
|
||||
// Comments (kind 1111)
|
||||
if (kind === 1111) {
|
||||
// Invalidate all comment queries
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'comments'] });
|
||||
}
|
||||
|
||||
// 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] });
|
||||
}
|
||||
}
|
||||
|
||||
// App submissions (kind 31733)
|
||||
if (kind === 31733) {
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
|
||||
}
|
||||
|
||||
// Moderation lists (kind 30267)
|
||||
if (kind === 30267) {
|
||||
const dTag = tags.find(([name]) => name === 'd')?.[1];
|
||||
if (dTag?.includes('soapbox-')) {
|
||||
// Invalidate app submissions and showcase queries
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['showcase-moderation'] });
|
||||
}
|
||||
}
|
||||
|
||||
// Reports (kind 1984)
|
||||
if (kind === 1984) {
|
||||
// Invalidate app submissions and moderation queries
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['showcase-moderation'] });
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { NKinds, type NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
interface PostCommentParams {
|
||||
@@ -11,6 +12,7 @@ interface PostCommentParams {
|
||||
/** Post a NIP-22 (kind 1111) comment on an event. */
|
||||
export function usePostComment() {
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const { user } = useCurrentUser();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
@@ -82,10 +84,61 @@ export function usePostComment() {
|
||||
|
||||
return event;
|
||||
},
|
||||
onMutate: async ({ root, reply, content }) => {
|
||||
if (!user) return;
|
||||
|
||||
const queryKey = ['nostr', 'comments', root instanceof URL ? root.toString() : root.id];
|
||||
|
||||
// Cancel any outgoing refetches
|
||||
await queryClient.cancelQueries({ queryKey });
|
||||
|
||||
// Snapshot the previous value
|
||||
const previousComments = queryClient.getQueryData(queryKey);
|
||||
|
||||
// Optimistically update the cache
|
||||
queryClient.setQueryData(queryKey, (old: unknown) => {
|
||||
if (!old || typeof old !== 'object') return old;
|
||||
|
||||
const commentsData = old as { allComments?: NostrEvent[]; topLevelComments?: NostrEvent[] };
|
||||
|
||||
// Create optimistic comment
|
||||
const optimisticComment: NostrEvent = {
|
||||
id: `temp-${Date.now()}`,
|
||||
pubkey: user.pubkey,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 1111,
|
||||
tags: [], // Tags will be filled properly by the actual event
|
||||
content,
|
||||
sig: ''
|
||||
};
|
||||
|
||||
// Add to allComments
|
||||
const newAllComments = [...(commentsData.allComments || []), optimisticComment];
|
||||
|
||||
// Add to topLevelComments if it's a top-level comment (no reply)
|
||||
const newTopLevelComments = !reply
|
||||
? [optimisticComment, ...(commentsData.topLevelComments || [])]
|
||||
: commentsData.topLevelComments;
|
||||
|
||||
return {
|
||||
...commentsData,
|
||||
allComments: newAllComments,
|
||||
topLevelComments: newTopLevelComments,
|
||||
};
|
||||
});
|
||||
|
||||
// Return a context object with the snapshotted value
|
||||
return { previousComments };
|
||||
},
|
||||
onError: (err, variables, context) => {
|
||||
// If the mutation fails, use the context returned from onMutate to roll back
|
||||
const queryKey = ['nostr', 'comments', variables.root instanceof URL ? variables.root.toString() : variables.root.id];
|
||||
queryClient.setQueryData(queryKey, context?.previousComments);
|
||||
},
|
||||
onSuccess: (_, { root }) => {
|
||||
// Invalidate and refetch comments
|
||||
// Invalidate and refetch comments to get the real data
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['comments', root instanceof URL ? root.toString() : root.id]
|
||||
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id]
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,986 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useParams, Link, useNavigate } from 'react-router-dom';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { CommentsSection } from '@/components/comments/CommentsSection';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import {
|
||||
ExternalLink,
|
||||
User,
|
||||
Star,
|
||||
ArrowLeft,
|
||||
Edit,
|
||||
MoreVertical,
|
||||
StarOff,
|
||||
Eye,
|
||||
EyeOff,
|
||||
CheckCircle,
|
||||
XCircle,
|
||||
Home,
|
||||
} from 'lucide-react';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
// Kind 31733 for app submissions
|
||||
const APP_SUBMISSION_KIND = 31733;
|
||||
|
||||
// The moderator npub and hex
|
||||
const MODERATOR_NPUB = 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc';
|
||||
const MODERATOR_HEX = (() => {
|
||||
try {
|
||||
const decoded = nip19.decode(MODERATOR_NPUB);
|
||||
return decoded.type === 'npub' ? decoded.data : '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
})();
|
||||
|
||||
export default function ShowcasePage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
const { toast } = useToast();
|
||||
const { mutate: publishEvent, isPending } = useNostrPublish();
|
||||
const queryClient = useQueryClient();
|
||||
const [imageError, setImageError] = useState(false);
|
||||
|
||||
// Decode the naddr to get the app submission
|
||||
const appData = React.useMemo(() => {
|
||||
if (!id) return null;
|
||||
try {
|
||||
const decoded = nip19.decode(id);
|
||||
if (decoded.type === 'naddr') {
|
||||
return decoded.data;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to decode naddr:', error);
|
||||
}
|
||||
return null;
|
||||
}, [id]);
|
||||
|
||||
// Fetch the app submission event
|
||||
const { data: appEvent, isLoading } = useQuery({
|
||||
queryKey: ['showcase-app', id],
|
||||
queryFn: async () => {
|
||||
if (!appData) return null;
|
||||
|
||||
const events = await nostr.query(
|
||||
[
|
||||
{
|
||||
kinds: [appData.kind],
|
||||
authors: [appData.pubkey],
|
||||
'#d': [appData.identifier],
|
||||
limit: 1,
|
||||
},
|
||||
],
|
||||
{ signal: AbortSignal.timeout(3000) }
|
||||
);
|
||||
|
||||
return events[0] || null;
|
||||
},
|
||||
enabled: !!appData,
|
||||
});
|
||||
|
||||
// Fetch moderation lists
|
||||
const { data: moderationData } = useQuery({
|
||||
queryKey: ['showcase-moderation', id],
|
||||
queryFn: async () => {
|
||||
if (!appEvent) return null;
|
||||
|
||||
const [moderatorListEvents, reportEvents] = await Promise.all([
|
||||
nostr.query(
|
||||
[
|
||||
{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': [
|
||||
'soapbox-featured-apps',
|
||||
'soapbox-approved-apps',
|
||||
'soapbox-homepage-apps',
|
||||
],
|
||||
limit: 3,
|
||||
},
|
||||
],
|
||||
{ signal: AbortSignal.timeout(1000) }
|
||||
),
|
||||
nostr.query(
|
||||
[
|
||||
{
|
||||
kinds: [1984],
|
||||
authors: [MODERATOR_HEX],
|
||||
limit: 1000,
|
||||
},
|
||||
],
|
||||
{ signal: AbortSignal.timeout(1000) }
|
||||
),
|
||||
]);
|
||||
|
||||
// Process moderation lists
|
||||
const featuredList = moderatorListEvents.find((e) =>
|
||||
e.tags.find((tag) => tag[0] === 'd' && tag[1] === 'soapbox-featured-apps')
|
||||
);
|
||||
const approvedList = moderatorListEvents.find((e) =>
|
||||
e.tags.find((tag) => tag[0] === 'd' && tag[1] === 'soapbox-approved-apps')
|
||||
);
|
||||
const homepageList = moderatorListEvents.find((e) =>
|
||||
e.tags.find((tag) => tag[0] === 'd' && tag[1] === 'soapbox-homepage-apps')
|
||||
);
|
||||
|
||||
const dTag = appEvent.tags.find((tag) => tag[0] === 'd')?.[1];
|
||||
const appCoordinate = `${APP_SUBMISSION_KIND}:${appEvent.pubkey}:${dTag}`;
|
||||
|
||||
const isFeatured = featuredList?.tags.some(
|
||||
(tag) => tag[0] === 'a' && tag[1] === appCoordinate
|
||||
);
|
||||
const isApproved = approvedList?.tags.some(
|
||||
(tag) => tag[0] === 'a' && tag[1] === appCoordinate
|
||||
);
|
||||
const isHomepage = homepageList?.tags.some(
|
||||
(tag) => tag[0] === 'a' && tag[1] === appCoordinate
|
||||
);
|
||||
|
||||
// Check if hidden
|
||||
const appReports = new Map<string, { hidden: number; unhidden: number }>();
|
||||
for (const report of reportEvents) {
|
||||
const aTag = report.tags.find((tag) => tag[0] === 'a');
|
||||
if (!aTag || !aTag[1]) continue;
|
||||
|
||||
const reportCoord = aTag[1];
|
||||
if (reportCoord !== appCoordinate) continue;
|
||||
|
||||
const reportType = aTag[2];
|
||||
const moderationLabel = report.tags.find(
|
||||
(tag) => tag[0] === 'l' && tag[2] === 'soapbox.moderation'
|
||||
)?.[1];
|
||||
|
||||
if (moderationLabel === 'hidden' && (reportType === 'spam' || reportType === 'other')) {
|
||||
if (!appReports.has(reportCoord)) {
|
||||
appReports.set(reportCoord, { hidden: 0, unhidden: 0 });
|
||||
}
|
||||
appReports.get(reportCoord)!.hidden = Math.max(
|
||||
appReports.get(reportCoord)!.hidden,
|
||||
report.created_at
|
||||
);
|
||||
} else if (moderationLabel === 'unhidden' && reportType === 'other') {
|
||||
if (!appReports.has(reportCoord)) {
|
||||
appReports.set(reportCoord, { hidden: 0, unhidden: 0 });
|
||||
}
|
||||
appReports.get(reportCoord)!.unhidden = Math.max(
|
||||
appReports.get(reportCoord)!.unhidden,
|
||||
report.created_at
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const reports = appReports.get(appCoordinate);
|
||||
const isHidden = reports && reports.hidden > reports.unhidden;
|
||||
|
||||
return { isFeatured, isApproved, isHomepage, isHidden };
|
||||
},
|
||||
enabled: !!appEvent,
|
||||
staleTime: 5000, // 5 seconds
|
||||
refetchInterval: 15000, // 15 seconds
|
||||
});
|
||||
|
||||
// Parse app data from event
|
||||
const app = React.useMemo(() => {
|
||||
if (!appEvent) return null;
|
||||
|
||||
const appName = appEvent.tags.find((tag) => tag[0] === 'title')?.[1] || '';
|
||||
const websiteUrl = appEvent.tags.find((tag) => tag[0] === 'website')?.[1] || '';
|
||||
const repositoryUrl = appEvent.tags.find((tag) => tag[0] === 'repository')?.[1] || '';
|
||||
const appIconUrl = appEvent.tags.find((tag) => tag[0] === 'icon')?.[1] || '';
|
||||
const screenshotUrl = appEvent.tags.find((tag) => tag[0] === 'screenshot')?.[1] || '';
|
||||
const authorNpub = appEvent.tags.find((tag) => tag[0] === 'author')?.[1] || appEvent.pubkey;
|
||||
const appTags = appEvent.tags.filter((tag) => tag[0] === 'app-tag').map((tag) => tag[1]);
|
||||
|
||||
return {
|
||||
appName,
|
||||
websiteUrl,
|
||||
repositoryUrl,
|
||||
description: appEvent.content,
|
||||
appIconUrl,
|
||||
screenshotUrl,
|
||||
authorNpub,
|
||||
appTags,
|
||||
};
|
||||
}, [appEvent]);
|
||||
|
||||
// Get author pubkey
|
||||
const authorPubkey = React.useMemo(() => {
|
||||
if (!app?.authorNpub) return appEvent?.pubkey || '';
|
||||
|
||||
try {
|
||||
if (app.authorNpub.length === 64 && /^[0-9a-f]+$/i.test(app.authorNpub)) {
|
||||
return app.authorNpub;
|
||||
}
|
||||
|
||||
const decoded = nip19.decode(app.authorNpub);
|
||||
return decoded.type === 'npub' ? decoded.data : appEvent?.pubkey || '';
|
||||
} catch {
|
||||
return appEvent?.pubkey || '';
|
||||
}
|
||||
}, [app?.authorNpub, appEvent?.pubkey]);
|
||||
|
||||
const { data: authorData } = useAuthor(authorPubkey);
|
||||
|
||||
const isOwner = user?.pubkey === appEvent?.pubkey;
|
||||
const isModerator = user?.pubkey === MODERATOR_HEX;
|
||||
|
||||
// Moderation actions
|
||||
const handleModerationAction = async (
|
||||
action: 'feature' | 'unfeature' | 'approve' | 'unapprove' | 'hide' | 'unhide' | 'homepage' | 'unhomepage'
|
||||
) => {
|
||||
if (!isModerator || !user || !appEvent) return;
|
||||
|
||||
const dTag = appEvent.tags.find((tag) => tag[0] === 'd')?.[1];
|
||||
if (!dTag) {
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Cannot perform moderation action: missing app identifier',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const appCoordinate = `${APP_SUBMISSION_KIND}:${appEvent.pubkey}:${dTag}`;
|
||||
|
||||
try {
|
||||
if (action === 'homepage' || action === 'unhomepage') {
|
||||
const currentHomepageLists = await nostr.query(
|
||||
[
|
||||
{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-homepage-apps'],
|
||||
limit: 1,
|
||||
},
|
||||
],
|
||||
{ signal: AbortSignal.timeout(3000) }
|
||||
);
|
||||
|
||||
const currentHomepageList = currentHomepageLists.reduce(
|
||||
(latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
const currentHomepageApps = new Set<string>();
|
||||
if (currentHomepageList) {
|
||||
currentHomepageList.tags
|
||||
.filter((tag) => tag[0] === 'a')
|
||||
.forEach((tag) => currentHomepageApps.add(tag[1]));
|
||||
}
|
||||
|
||||
if (action === 'homepage') {
|
||||
currentHomepageApps.add(appCoordinate);
|
||||
} else {
|
||||
currentHomepageApps.delete(appCoordinate);
|
||||
}
|
||||
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Soapbox homepage apps curated by moderators',
|
||||
tags: [
|
||||
['d', 'soapbox-homepage-apps'],
|
||||
['title', 'Soapbox Homepage Apps'],
|
||||
['description', 'Apps displayed on the Soapbox homepage'],
|
||||
...Array.from(currentHomepageApps).map((coord) => ['a', coord]),
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
|
||||
if (action === 'homepage') {
|
||||
const currentApprovedLists = await nostr.query(
|
||||
[
|
||||
{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-approved-apps'],
|
||||
limit: 1,
|
||||
},
|
||||
],
|
||||
{ signal: AbortSignal.timeout(3000) }
|
||||
);
|
||||
|
||||
const currentApprovedList = currentApprovedLists.reduce(
|
||||
(latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
const currentApprovedApps = new Set<string>();
|
||||
if (currentApprovedList) {
|
||||
currentApprovedList.tags
|
||||
.filter((tag) => tag[0] === 'a')
|
||||
.forEach((tag) => currentApprovedApps.add(tag[1]));
|
||||
}
|
||||
|
||||
currentApprovedApps.add(appCoordinate);
|
||||
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Soapbox approved apps curated by moderators',
|
||||
tags: [
|
||||
['d', 'soapbox-approved-apps'],
|
||||
['title', 'Soapbox Approved Apps'],
|
||||
['description', 'Apps approved for the Soapbox showcase'],
|
||||
...Array.from(currentApprovedApps).map((coord) => ['a', coord]),
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
}
|
||||
} else if (action === 'feature' || action === 'unfeature') {
|
||||
const currentFeaturedLists = await nostr.query(
|
||||
[
|
||||
{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-featured-apps'],
|
||||
limit: 1,
|
||||
},
|
||||
],
|
||||
{ signal: AbortSignal.timeout(3000) }
|
||||
);
|
||||
|
||||
const currentFeaturedList = currentFeaturedLists.reduce(
|
||||
(latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
const currentFeaturedApps = new Set<string>();
|
||||
if (currentFeaturedList) {
|
||||
currentFeaturedList.tags
|
||||
.filter((tag) => tag[0] === 'a')
|
||||
.forEach((tag) => currentFeaturedApps.add(tag[1]));
|
||||
}
|
||||
|
||||
if (action === 'feature') {
|
||||
currentFeaturedApps.add(appCoordinate);
|
||||
} else {
|
||||
currentFeaturedApps.delete(appCoordinate);
|
||||
}
|
||||
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Soapbox featured apps curated by moderators',
|
||||
tags: [
|
||||
['d', 'soapbox-featured-apps'],
|
||||
['title', 'Soapbox Featured Apps'],
|
||||
['description', 'Apps featured in the Soapbox showcase'],
|
||||
...Array.from(currentFeaturedApps).map((coord) => ['a', coord]),
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
|
||||
if (action === 'feature') {
|
||||
const currentApprovedLists = await nostr.query(
|
||||
[
|
||||
{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-approved-apps'],
|
||||
limit: 1,
|
||||
},
|
||||
],
|
||||
{ signal: AbortSignal.timeout(3000) }
|
||||
);
|
||||
|
||||
const currentApprovedList = currentApprovedLists.reduce(
|
||||
(latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
const currentApprovedApps = new Set<string>();
|
||||
if (currentApprovedList) {
|
||||
currentApprovedList.tags
|
||||
.filter((tag) => tag[0] === 'a')
|
||||
.forEach((tag) => currentApprovedApps.add(tag[1]));
|
||||
}
|
||||
|
||||
currentApprovedApps.add(appCoordinate);
|
||||
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Soapbox approved apps curated by moderators',
|
||||
tags: [
|
||||
['d', 'soapbox-approved-apps'],
|
||||
['title', 'Soapbox Approved Apps'],
|
||||
['description', 'Apps approved for the Soapbox showcase'],
|
||||
...Array.from(currentApprovedApps).map((coord) => ['a', coord]),
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
}
|
||||
} else if (action === 'approve' || action === 'unapprove') {
|
||||
const currentApprovedLists = await nostr.query(
|
||||
[
|
||||
{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-approved-apps'],
|
||||
limit: 1,
|
||||
},
|
||||
],
|
||||
{ signal: AbortSignal.timeout(3000) }
|
||||
);
|
||||
|
||||
const currentApprovedList = currentApprovedLists.reduce(
|
||||
(latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
const currentApprovedApps = new Set<string>();
|
||||
if (currentApprovedList) {
|
||||
currentApprovedList.tags
|
||||
.filter((tag) => tag[0] === 'a')
|
||||
.forEach((tag) => currentApprovedApps.add(tag[1]));
|
||||
}
|
||||
|
||||
if (action === 'approve') {
|
||||
currentApprovedApps.add(appCoordinate);
|
||||
} else {
|
||||
currentApprovedApps.delete(appCoordinate);
|
||||
}
|
||||
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Soapbox approved apps curated by moderators',
|
||||
tags: [
|
||||
['d', 'soapbox-approved-apps'],
|
||||
['title', 'Soapbox Approved Apps'],
|
||||
['description', 'Apps approved for the Soapbox showcase'],
|
||||
...Array.from(currentApprovedApps).map((coord) => ['a', coord]),
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
} else if (action === 'hide' || action === 'unhide') {
|
||||
publishEvent({
|
||||
kind: 1984,
|
||||
content: `App ${action}den by moderator: "${app?.appName}"`,
|
||||
tags: [
|
||||
['a', appCoordinate, action === 'hide' ? 'spam' : 'other'],
|
||||
['p', appEvent.pubkey],
|
||||
['L', 'soapbox.moderation'],
|
||||
['l', action === 'hide' ? 'hidden' : 'unhidden', 'soapbox.moderation'],
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
}
|
||||
|
||||
// Invalidate queries immediately for real-time updates
|
||||
queryClient.invalidateQueries({ queryKey: ['showcase-moderation', id] });
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
|
||||
|
||||
toast({
|
||||
title: 'Success!',
|
||||
description: `App "${app?.appName}" ${action}d successfully`,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Moderation action failed:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: `Failed to ${action} app "${app?.appName}"`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (!id || !appData) {
|
||||
return (
|
||||
<AppLayout>
|
||||
<div className="container mx-auto px-4 py-8 max-w-5xl">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<p className="text-muted-foreground">Invalid showcase app identifier</p>
|
||||
<Button asChild variant="outline" className="mt-4">
|
||||
<Link to="/">
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
Back to Home
|
||||
</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</AppLayout>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLoading || !appEvent || !app) {
|
||||
return (
|
||||
<AppLayout>
|
||||
<div className="container mx-auto px-4 py-8 max-w-5xl">
|
||||
<div className="mb-6">
|
||||
<Skeleton className="h-10 w-32" />
|
||||
</div>
|
||||
|
||||
<Card className="mb-8">
|
||||
<Skeleton className="aspect-video rounded-t-lg" />
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-start gap-4 mb-4">
|
||||
<Skeleton className="w-16 h-16 rounded-lg" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-8 w-64" />
|
||||
<Skeleton className="h-4 w-32" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2 mb-4">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
<div className="flex gap-2 mb-4">
|
||||
<Skeleton className="h-6 w-20" />
|
||||
<Skeleton className="h-6 w-24" />
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Skeleton className="h-10 flex-1" />
|
||||
<Skeleton className="h-10 w-32" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Skeleton className="h-64 w-full" />
|
||||
</div>
|
||||
</AppLayout>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AppLayout>
|
||||
<div className="container mx-auto px-4 py-8 max-w-5xl">
|
||||
{/* Back button */}
|
||||
<div className="mb-6">
|
||||
<Button variant="ghost" onClick={() => navigate(-1)}>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* App Details Card */}
|
||||
<Card className="mb-8">
|
||||
<div className="relative">
|
||||
{/* Screenshot */}
|
||||
<div className="aspect-video bg-gradient-to-br from-muted/50 to-muted rounded-t-lg overflow-hidden">
|
||||
{!imageError ? (
|
||||
<img
|
||||
src={app.screenshotUrl}
|
||||
alt={`${app.appName} screenshot`}
|
||||
className="w-full h-full object-cover"
|
||||
onError={() => setImageError(true)}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
|
||||
<div className="text-center">
|
||||
<div className="w-16 h-16 mx-auto mb-2 bg-muted rounded-lg flex items-center justify-center">
|
||||
<ExternalLink className="w-8 h-8" />
|
||||
</div>
|
||||
<p className="text-sm">Screenshot unavailable</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Actions Menu */}
|
||||
{(isOwner || isModerator) && (
|
||||
<div className="absolute top-4 right-4">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="secondary" size="sm" className="h-9 w-9 p-0">
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{isOwner && (
|
||||
<DropdownMenuItem>
|
||||
<Edit className="w-4 h-4 mr-2" />
|
||||
Edit App
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{isModerator && moderationData && (
|
||||
<>
|
||||
{!moderationData.isApproved && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleModerationAction('approve')}
|
||||
disabled={isPending}
|
||||
>
|
||||
<CheckCircle className="w-4 h-4 mr-2" />
|
||||
Approve
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{moderationData.isApproved && !moderationData.isFeatured && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleModerationAction('unapprove')}
|
||||
disabled={isPending}
|
||||
>
|
||||
<XCircle className="w-4 h-4 mr-2" />
|
||||
Unapprove
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
handleModerationAction(moderationData.isFeatured ? 'unfeature' : 'feature')
|
||||
}
|
||||
disabled={isPending}
|
||||
>
|
||||
{moderationData.isFeatured ? (
|
||||
<>
|
||||
<StarOff className="w-4 h-4 mr-2" />
|
||||
Un-feature
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Star className="w-4 h-4 mr-2" />
|
||||
Feature
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
handleModerationAction(moderationData.isHomepage ? 'unhomepage' : 'homepage')
|
||||
}
|
||||
disabled={isPending}
|
||||
>
|
||||
{moderationData.isHomepage ? (
|
||||
<>
|
||||
<Home className="w-4 h-4 mr-2" />
|
||||
Remove from Homepage
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Home className="w-4 h-4 mr-2" />
|
||||
Add to Homepage
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
handleModerationAction(moderationData.isHidden ? 'unhide' : 'hide')
|
||||
}
|
||||
disabled={isPending}
|
||||
>
|
||||
{moderationData.isHidden ? (
|
||||
<>
|
||||
<Eye className="w-4 h-4 mr-2" />
|
||||
Unhide
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<EyeOff className="w-4 h-4 mr-2" />
|
||||
Hide
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<CardContent className="p-6">
|
||||
{/* App Header */}
|
||||
<div className="flex items-start gap-4 mb-4">
|
||||
<div className="w-16 h-16 rounded-lg overflow-hidden bg-muted flex-shrink-0">
|
||||
<img
|
||||
src={app.appIconUrl}
|
||||
alt={`${app.appName} icon`}
|
||||
className="w-full h-full object-cover"
|
||||
onError={(e) => {
|
||||
const target = e.target as HTMLImageElement;
|
||||
target.style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h1 className="text-3xl font-bold text-foreground mb-2">{app.appName}</h1>
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<div className="w-6 h-6 rounded-full overflow-hidden bg-muted flex-shrink-0">
|
||||
{authorData?.metadata?.picture ? (
|
||||
<img
|
||||
src={authorData.metadata.picture}
|
||||
alt={`${authorData.metadata.name || 'Author'} avatar`}
|
||||
className="w-full h-full object-cover"
|
||||
onError={(e) => {
|
||||
const target = e.target as HTMLImageElement;
|
||||
target.style.display = 'none';
|
||||
target.parentElement!.innerHTML =
|
||||
'<div class="w-full h-full flex items-center justify-center"><svg class="w-3 h-3 text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd"></path></svg></div>';
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center">
|
||||
<User className="w-3 h-3 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<span>
|
||||
by{' '}
|
||||
<a
|
||||
href={`https://ditto.pub/${app.authorNpub || nip19.npubEncode(authorPubkey)}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:text-primary/80 transition-colors hover:underline"
|
||||
>
|
||||
{authorData?.metadata?.name ||
|
||||
authorData?.metadata?.display_name ||
|
||||
'Anonymous'}
|
||||
</a>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<p className="text-muted-foreground mb-4 whitespace-pre-wrap">{app.description}</p>
|
||||
|
||||
{/* Tags */}
|
||||
{app.appTags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2 mb-6">
|
||||
{app.appTags.map((tag, index) => (
|
||||
<Badge key={index} variant="secondary">
|
||||
{tag}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Link
|
||||
to={`/clone?url=${encodeURIComponent(app.repositoryUrl)}`}
|
||||
className="flex-1 min-w-[200px]"
|
||||
>
|
||||
<img
|
||||
src="/badge.svg"
|
||||
alt="Edit with Shakespeare"
|
||||
className="h-10 hover:opacity-80 transition-opacity"
|
||||
/>
|
||||
</Link>
|
||||
<Button variant="default" size="lg" asChild>
|
||||
<a href={app.websiteUrl} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="w-4 h-4 mr-2" />
|
||||
Visit Website
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Ratings Section */}
|
||||
<Card className="mb-8">
|
||||
<CardHeader>
|
||||
<h2 className="text-2xl font-bold flex items-center gap-2">
|
||||
<Star className="w-6 h-6 text-yellow-500" />
|
||||
Ratings
|
||||
</h2>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<RatingsSection appEvent={appEvent} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Comments Section */}
|
||||
<CommentsSection
|
||||
root={appEvent}
|
||||
title="Comments"
|
||||
emptyStateMessage="No comments yet"
|
||||
emptyStateSubtitle="Be the first to share your thoughts about this app!"
|
||||
/>
|
||||
</div>
|
||||
</AppLayout>
|
||||
);
|
||||
}
|
||||
|
||||
// Ratings Section Component
|
||||
function RatingsSection({ appEvent }: { appEvent: NostrEvent }) {
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: publishEvent, isPending } = useNostrPublish();
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Fetch ratings (kind 7 reactions with rating content)
|
||||
const { data: ratings = [], isLoading } = useQuery({
|
||||
queryKey: ['ratings', appEvent.id],
|
||||
queryFn: async () => {
|
||||
const events = await nostr.query(
|
||||
[
|
||||
{
|
||||
kinds: [7],
|
||||
'#e': [appEvent.id],
|
||||
limit: 500,
|
||||
},
|
||||
],
|
||||
{ signal: AbortSignal.timeout(3000) }
|
||||
);
|
||||
|
||||
// Filter for numeric ratings (1-5)
|
||||
return events.filter((e) => {
|
||||
const rating = parseInt(e.content);
|
||||
return !isNaN(rating) && rating >= 1 && rating <= 5;
|
||||
});
|
||||
},
|
||||
staleTime: 10000, // 10 seconds
|
||||
refetchInterval: 30000, // 30 seconds
|
||||
});
|
||||
|
||||
// Calculate average rating
|
||||
const averageRating = React.useMemo(() => {
|
||||
if (ratings.length === 0) return 0;
|
||||
const sum = ratings.reduce((acc, r) => acc + parseInt(r.content), 0);
|
||||
return sum / ratings.length;
|
||||
}, [ratings]);
|
||||
|
||||
// Check if user has already rated
|
||||
const userRating = React.useMemo(() => {
|
||||
if (!user) return null;
|
||||
const userRatingEvent = ratings.find((r) => r.pubkey === user.pubkey);
|
||||
return userRatingEvent ? parseInt(userRatingEvent.content) : null;
|
||||
}, [ratings, user]);
|
||||
|
||||
const handleRate = (rating: number) => {
|
||||
if (!user) {
|
||||
toast({
|
||||
title: 'Login Required',
|
||||
description: 'Please log in to rate this app',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Optimistic update
|
||||
const optimisticRating = {
|
||||
id: `temp-${Date.now()}`,
|
||||
pubkey: user.pubkey,
|
||||
content: rating.toString(),
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 7,
|
||||
tags: [['e', appEvent.id], ['p', appEvent.pubkey]],
|
||||
sig: ''
|
||||
};
|
||||
|
||||
// Update cache optimistically
|
||||
queryClient.setQueryData(['ratings', appEvent.id], (oldRatings: NostrEvent[] = []) => {
|
||||
// Remove any existing rating from this user
|
||||
const filteredRatings = oldRatings.filter(r => r.pubkey !== user.pubkey);
|
||||
// Add the new rating
|
||||
return [...filteredRatings, optimisticRating];
|
||||
});
|
||||
|
||||
publishEvent({
|
||||
kind: 7,
|
||||
content: rating.toString(),
|
||||
tags: [
|
||||
['e', appEvent.id],
|
||||
['p', appEvent.pubkey],
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
}, {
|
||||
onSuccess: () => {
|
||||
toast({
|
||||
title: 'Rating Submitted!',
|
||||
description: `You rated this app ${rating} star${rating > 1 ? 's' : ''}`,
|
||||
});
|
||||
},
|
||||
onError: () => {
|
||||
// Revert optimistic update on error
|
||||
queryClient.invalidateQueries({ queryKey: ['ratings', appEvent.id] });
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Failed to submit rating. Please try again.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-8 w-48" />
|
||||
<Skeleton className="h-12 w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Average Rating Display */}
|
||||
<div className="text-center">
|
||||
<div className="text-5xl font-bold mb-2">
|
||||
{averageRating > 0 ? averageRating.toFixed(1) : 'No ratings yet'}
|
||||
</div>
|
||||
{averageRating > 0 && (
|
||||
<div className="flex items-center justify-center gap-1 mb-2">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<Star
|
||||
key={i}
|
||||
className={`w-6 h-6 ${
|
||||
i < Math.round(averageRating)
|
||||
? 'fill-yellow-500 text-yellow-500'
|
||||
: 'text-gray-300'
|
||||
}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{ratings.length} {ratings.length === 1 ? 'rating' : 'ratings'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* User Rating Input */}
|
||||
<div className="border-t pt-6">
|
||||
<p className="text-sm font-medium mb-3">
|
||||
{userRating ? 'Your rating:' : 'Rate this app:'}
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
{Array.from({ length: 5 }).map((_, i) => {
|
||||
const starValue = i + 1;
|
||||
return (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => handleRate(starValue)}
|
||||
className="transition-transform hover:scale-110 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
disabled={!user || isPending}
|
||||
>
|
||||
<Star
|
||||
className={`w-10 h-10 ${
|
||||
userRating && starValue <= userRating
|
||||
? 'fill-yellow-500 text-yellow-500'
|
||||
: 'text-gray-300 hover:text-yellow-500'
|
||||
} ${isPending ? 'animate-pulse' : ''}`}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{!user && (
|
||||
<p className="text-xs text-muted-foreground mt-2">Log in to rate this app</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user