Compare commits

..
Author SHA1 Message Date
shakespeare.diy 262414257a Fix ESLint errors: remove unused navigate imports
Removed unused `useNavigate` imports from:
- PushReminderDialog.tsx
- PushWarningButton.tsx

These were causing ESLint errors. The navigate hook was imported
but never used in either component.

ESLint should now pass without errors.
2025-11-14 10:17:52 -06:00
shakespeare.diy c25517a58f Remove debug logging and restore production settings
- Removed all console.log debug statements
- Changed MESSAGE_THRESHOLD back to 5 (from 2 for testing)
- Cleaned up code for production

Push reminder features are now fully functional:
- Warning icon appears in header when there's unpushed work
- Popup appears after 5 messages if conditions are met
- 5-minute cooldown between reminders
- User can disable in Settings > Preferences
2025-11-11 14:06:43 -06:00
shakespeare.diy a7164c0292 Fix push reminder not showing - remove initial cooldown
The issue was that DEFAULT_STATE set lastInteraction to Date.now(),
which meant the 5-minute cooldown started immediately on first load,
preventing reminders from ever showing.

Changes:
- Set initial lastInteraction to 0 instead of Date.now()
- Don't reset lastInteraction when switching projects (keep cooldown)
- This allows reminders to show immediately after threshold is met

Users may need to clear localStorage key 'push-reminder-state' to
reset if they already have the old state saved.
2025-11-11 14:01:46 -06:00
shakespeare.diy 66a37ec92c Add debug logging and lower threshold for testing push reminders
- Reduced MESSAGE_THRESHOLD from 5 to 2 for easier testing
- Added console.log statements to track:
  - Message counter increments
  - shouldShowReminder checks and conditions
  - Git status (uncommitted changes, commits ahead, remotes)
- Added useEffect to watch shouldShowReminder changes
- Fixed async state update issue by watching effect dependency

This will help debug why the reminder dialog may not be appearing.
2025-11-11 13:58:18 -06:00
shakespeare.diy 5de01c6130 Add push reminder features to encourage users to push code
Implements two key features to prevent data loss:

1. Push Warning Button
   - Icon button in project header that appears when:
     - No remote is configured
     - There are commits ahead of remote
     - There are uncommitted changes
   - Click opens Git dialog for one-click push or remote configuration
   - Visual indicators with tooltips showing status

2. Periodic Push Reminder Dialog
   - Dismissible popup appears after 5 messages if there's unpushed work
   - Shows different content based on git status:
     - No remote: Prompts to configure remote
     - Commits ahead: Prompts to push
     - Uncommitted changes: Prompts to commit and push
   - Can be disabled with "Don't show again" checkbox
   - Setting in Preferences to re-enable reminders
   - Respects 5-minute cooldown between reminders

3. User Preferences
   - Added "Push reminders" toggle in Settings > Preferences
   - Enabled by default to encourage best practices
   - Stored in local storage for persistence

Technical implementation:
- Created usePushReminder hook for state management
- Tracks message count and last interaction timestamp
- Integrates with existing useGitStatus hook
- Added onMessageSent callback to ChatPane
- PushWarningButton component with icon/full variants
- PushReminderDialog with contextual messaging
- Translations added to English locale
2025-11-11 13:43:16 -06:00
22 changed files with 531 additions and 2382 deletions

No files matched your search

-348
View File
@@ -1,348 +0,0 @@
# 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.
-191
View File
@@ -1,191 +0,0 @@
# 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`
-2
View File
@@ -21,7 +21,6 @@ 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() {
@@ -52,7 +51,6 @@ 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 */}
+8 -24
View File
@@ -346,10 +346,8 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
});
}
// Invalidate queries to refresh the data immediately
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
// Invalidate queries to refresh the data
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
queryClient.invalidateQueries({ queryKey: ['showcase-moderation'] });
// If this is a Halloween app, also invalidate Halloween queries
if (isHalloweenSubmission) {
@@ -372,28 +370,14 @@ 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 */}
<Link
to={appNaddr ? `/showcase/${appNaddr}` : '#'}
<a
href={app.websiteUrl}
target="_blank"
rel="noopener noreferrer"
className="block aspect-video bg-gradient-to-br from-muted/50 to-muted rounded-t-lg overflow-hidden cursor-pointer"
>
{!imageError ? (
@@ -413,15 +397,15 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
</div>
</div>
)}
</Link>
</a>
{/* 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" disabled={isPending}>
<MoreVertical className={`w-4 h-4 ${isPending ? 'animate-spin' : ''}`} />
<Button variant="secondary" size="sm" className="h-8 w-8 p-0">
<MoreVertical className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
-112
View File
@@ -1,112 +0,0 @@
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>
);
}
+176
View File
@@ -0,0 +1,176 @@
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { GitBranch, Upload, AlertTriangle, X } from 'lucide-react';
import { useGitStatus } from '@/hooks/useGitStatus';
import { GitDialog } from '@/components/GitDialog';
interface PushReminderDialogProps {
projectId: string;
open: boolean;
onOpenChange: (open: boolean) => void;
onDisableReminders: () => void;
onDismiss: () => void;
}
export function PushReminderDialog({
projectId,
open,
onOpenChange,
onDisableReminders,
onDismiss,
}: PushReminderDialogProps) {
const [dontShowAgain, setDontShowAgain] = useState(false);
const [isGitDialogOpen, setIsGitDialogOpen] = useState(false);
const { data: gitStatus } = useGitStatus(projectId);
// Close the reminder dialog when git dialog opens
useEffect(() => {
if (isGitDialogOpen) {
onOpenChange(false);
onDismiss();
}
}, [isGitDialogOpen, onOpenChange, onDismiss]);
if (!gitStatus?.isGitRepo) {
return null;
}
const hasNoRemote = gitStatus.remotes.length === 0;
const hasCommitsAhead = gitStatus.ahead > 0;
const hasUncommittedChanges = gitStatus.hasUncommittedChanges;
const handleDismiss = () => {
if (dontShowAgain) {
onDisableReminders();
}
onDismiss();
onOpenChange(false);
};
const handlePrimaryAction = () => {
if (dontShowAgain) {
onDisableReminders();
}
if (hasNoRemote) {
// Close reminder dialog and open git dialog
onOpenChange(false);
setIsGitDialogOpen(true);
} else {
// Close reminder dialog and open git dialog for push
onOpenChange(false);
setIsGitDialogOpen(true);
}
};
// Determine dialog content based on git status
let icon = AlertTriangle;
let iconColor = 'text-amber-600 dark:text-amber-500';
let title = '';
let description = '';
let primaryActionLabel = '';
if (hasNoRemote) {
icon = GitBranch;
iconColor = 'text-yellow-600 dark:text-yellow-500';
title = 'No Remote Repository Configured';
description = 'Your work is only stored locally in your browser. Configure a remote repository to prevent data loss if you clear your browser data.';
primaryActionLabel = 'Configure Remote';
} else if (hasCommitsAhead) {
icon = Upload;
iconColor = 'text-blue-600 dark:text-blue-500';
title = 'Unpushed Commits';
description = `You have ${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} that ${gitStatus.ahead !== 1 ? 'haven\'t' : 'hasn\'t'} been pushed to your remote repository. Push your changes to prevent data loss.`;
primaryActionLabel = 'Push Changes';
} else if (hasUncommittedChanges) {
icon = AlertTriangle;
iconColor = 'text-amber-600 dark:text-amber-500';
title = 'Uncommitted Changes';
description = `You have ${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}. Commit and push your changes to keep your work safe.`;
primaryActionLabel = 'Commit & Push';
}
const Icon = icon;
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<div className="flex items-start gap-3">
<div className={`rounded-full p-2 bg-muted ${iconColor}`}>
<Icon className="h-5 w-5" />
</div>
<div className="flex-1">
<DialogTitle className="text-left">{title}</DialogTitle>
<DialogDescription className="text-left mt-2">
{description}
</DialogDescription>
</div>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 -mt-1"
onClick={handleDismiss}
>
<X className="h-4 w-4" />
</Button>
</div>
</DialogHeader>
<div className="flex items-start gap-2 p-3 rounded-md bg-muted/50 border">
<Checkbox
id="dont-show"
checked={dontShowAgain}
onCheckedChange={(checked) => setDontShowAgain(checked === true)}
/>
<div className="grid gap-1.5 leading-none">
<Label
htmlFor="dont-show"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Don't show this again
</Label>
<p className="text-xs text-muted-foreground">
You can re-enable push reminders in Settings &gt; Preferences
</p>
</div>
</div>
<DialogFooter className="flex-col sm:flex-row gap-2">
<Button
variant="outline"
onClick={handleDismiss}
className="w-full sm:w-auto"
>
Remind Me Later
</Button>
<Button
onClick={handlePrimaryAction}
className="w-full sm:w-auto"
>
{primaryActionLabel}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Git Dialog - opened when user clicks primary action */}
<GitDialog
projectId={projectId}
open={isGitDialogOpen}
onOpenChange={setIsGitDialogOpen}
/>
</>
);
}
+138
View File
@@ -0,0 +1,138 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { GitDialog } from '@/components/GitDialog';
import { AlertTriangle, Upload, GitBranch } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useGitStatus } from '@/hooks/useGitStatus';
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip';
interface PushWarningButtonProps {
projectId: string;
className?: string;
variant?: 'icon' | 'full';
}
export function PushWarningButton({
projectId,
className,
variant = 'icon'
}: PushWarningButtonProps) {
const [isGitDialogOpen, setIsGitDialogOpen] = useState(false);
const { data: gitStatus } = useGitStatus(projectId);
if (!gitStatus?.isGitRepo) {
return null;
}
// Determine warning state
const hasNoRemote = gitStatus.remotes.length === 0;
const hasUncommittedChanges = gitStatus.hasUncommittedChanges;
const hasCommitsAhead = gitStatus.ahead > 0;
// Don't show if everything is synced
if (!hasNoRemote && !hasUncommittedChanges && !hasCommitsAhead) {
return null;
}
// Determine icon and message
let icon = AlertTriangle;
let message = '';
let action = '';
if (hasNoRemote) {
icon = GitBranch;
message = 'No remote configured';
action = 'Configure remote to prevent data loss';
} else if (hasCommitsAhead) {
icon = Upload;
message = `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} not pushed`;
action = 'Push to remote';
} else if (hasUncommittedChanges) {
icon = AlertTriangle;
message = `${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}`;
action = 'Commit and push your changes';
}
const Icon = icon;
const handleClick = () => {
if (hasNoRemote) {
// If no remote, open git dialog to configure
setIsGitDialogOpen(true);
} else {
// If remote exists, open git dialog for push/commit
setIsGitDialogOpen(true);
}
};
if (variant === 'icon') {
return (
<>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="sm"
onClick={handleClick}
className={cn(
"h-8 w-8 p-0",
hasNoRemote && "text-yellow-600 hover:text-yellow-700 dark:text-yellow-500 dark:hover:text-yellow-400",
hasCommitsAhead && "text-blue-600 hover:text-blue-700 dark:text-blue-500 dark:hover:text-blue-400",
hasUncommittedChanges && !hasCommitsAhead && "text-amber-600 hover:text-amber-700 dark:text-amber-500 dark:hover:text-amber-400",
className
)}
>
<Icon className="h-4 w-4 animate-pulse" />
</Button>
</TooltipTrigger>
<TooltipContent>
<div className="space-y-1">
<p className="font-medium">{message}</p>
<p className="text-xs text-muted-foreground">{action}</p>
</div>
</TooltipContent>
</Tooltip>
</TooltipProvider>
<GitDialog
projectId={projectId}
open={isGitDialogOpen}
onOpenChange={setIsGitDialogOpen}
/>
</>
);
}
// Full button variant
return (
<>
<Button
variant="outline"
size="sm"
onClick={handleClick}
className={cn(
"gap-2 border-2",
hasNoRemote && "border-yellow-500/50 bg-yellow-50 hover:bg-yellow-100 dark:bg-yellow-950/20 dark:hover:bg-yellow-950/30 text-yellow-700 dark:text-yellow-400",
hasCommitsAhead && "border-blue-500/50 bg-blue-50 hover:bg-blue-100 dark:bg-blue-950/20 dark:hover:bg-blue-950/30 text-blue-700 dark:text-blue-400",
hasUncommittedChanges && !hasCommitsAhead && "border-amber-500/50 bg-amber-50 hover:bg-amber-100 dark:bg-amber-950/20 dark:hover:bg-amber-950/30 text-amber-700 dark:text-amber-400",
className
)}
>
<Icon className="h-4 w-4 animate-pulse" />
<span className="text-sm font-medium">{message}</span>
</Button>
<GitDialog
projectId={projectId}
open={isGitDialogOpen}
onOpenChange={setIsGitDialogOpen}
/>
</>
);
}
-195
View File
@@ -1,195 +0,0 @@
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>
);
}
+8 -1
View File
@@ -52,6 +52,7 @@ interface ChatPaneProps {
onNewChat: () => void;
onFirstInteraction?: () => void;
onLoadingChange?: (isLoading: boolean) => void;
onMessageSent?: () => void;
isLoading?: boolean;
isBuildLoading?: boolean;
consoleError?: ProjectPreviewConsoleError | null;
@@ -67,6 +68,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onNewChat,
onFirstInteraction,
onLoadingChange,
onMessageSent,
isLoading: externalIsLoading,
isBuildLoading: externalIsBuildLoading,
consoleError,
@@ -478,7 +480,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
await sendMessage(messageContent, modelToUse);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
// Notify parent that a message was sent (for push reminder tracking)
if (onMessageSent) {
onMessageSent();
}
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath, onMessageSent]);
// Handle textarea focus - show onboarding if not configured
const handleTextareaFocus = useCallback(() => {
+4 -12
View File
@@ -5,7 +5,6 @@ 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';
@@ -27,10 +26,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 });
@@ -56,7 +55,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"
>
@@ -72,13 +71,6 @@ 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">
@@ -91,7 +83,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>
+6 -9
View File
@@ -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,13 +72,10 @@ export function CommentForm({
/>
<div className="flex justify-between items-center">
<span className="text-sm text-muted-foreground">
{isPending
? (reply ? 'Posting reply...' : 'Posting comment...')
: (reply ? 'Replying to comment' : 'Adding to the discussion')
}
{reply ? 'Replying to comment' : 'Adding to the discussion'}
</span>
<Button
type="submit"
<Button
type="submit"
disabled={!content.trim() || isPending}
size={compact ? "sm" : "default"}
>
-163
View File
@@ -1,163 +0,0 @@
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>;
}
+2 -2
View File
@@ -223,8 +223,8 @@ export function useAppSubmissions() {
return submissions;
},
staleTime: 10000, // 10 seconds
refetchInterval: 30000, // 30 seconds
staleTime: 30000, // 30 seconds
refetchInterval: 60000, // 1 minute
});
}
-231
View File
@@ -1,231 +0,0 @@
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]
});
},
});
}
+1 -3
View File
@@ -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,7 +94,5 @@ export function useComments(root: NostrEvent | URL, limit?: number) {
};
},
enabled: !!root,
staleTime: 10000, // 10 seconds
refetchInterval: 30000, // 30 seconds
});
}
+1 -48
View File
@@ -1,5 +1,5 @@
import { useNostr } from "@nostrify/react";
import { useMutation, useQueryClient, type UseMutationResult } from "@tanstack/react-query";
import { useMutation, type UseMutationResult } from "@tanstack/react-query";
import { useCurrentUser } from "./useCurrentUser";
@@ -8,7 +8,6 @@ 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'>) => {
@@ -38,52 +37,6 @@ 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'] });
}
},
});
}
+2 -55
View File
@@ -1,6 +1,5 @@
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 {
@@ -12,7 +11,6 @@ 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({
@@ -84,61 +82,10 @@ 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 to get the real data
// Invalidate and refetch comments
queryClient.invalidateQueries({
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id]
queryKey: ['comments', root instanceof URL ? root.toString() : root.id]
});
},
});
+118
View File
@@ -0,0 +1,118 @@
import { useEffect, useCallback } from 'react';
import { useLocalStorage } from './useLocalStorage';
import { useGitStatus } from './useGitStatus';
interface PushReminderState {
/** Whether push reminders are enabled */
enabled: boolean;
/** Number of messages since last push */
messagesSinceLastPush: number;
/** Timestamp when user last pushed or dismissed a reminder */
lastInteraction: number;
/** Project ID being tracked */
currentProjectId: string | null;
}
const DEFAULT_STATE: PushReminderState = {
enabled: true,
messagesSinceLastPush: 0,
lastInteraction: 0, // Start at 0 so reminders can show immediately
currentProjectId: null,
};
/** Number of messages before showing push reminder */
const MESSAGE_THRESHOLD = 5;
/** Minimum time in ms between showing reminders (5 minutes) */
const MIN_REMINDER_INTERVAL = 5 * 60 * 1000;
export function usePushReminder(projectId: string | null) {
const [state, setState] = useLocalStorage<PushReminderState>(
'push-reminder-state',
DEFAULT_STATE
);
const { data: gitStatus } = useGitStatus(projectId);
// Reset counter when switching projects
useEffect(() => {
if (projectId && state.currentProjectId !== projectId) {
setState((prev) => ({
...prev,
currentProjectId: projectId,
messagesSinceLastPush: 0,
// Don't reset lastInteraction - keep the cooldown across project switches
}));
}
}, [projectId, state.currentProjectId, setState]);
// Check if should show reminder
const shouldShowReminder = useCallback(() => {
if (!state.enabled || !projectId || !gitStatus?.isGitRepo) {
return false;
}
// Don't show if user recently interacted with push reminder
const timeSinceLastInteraction = Date.now() - state.lastInteraction;
if (timeSinceLastInteraction < MIN_REMINDER_INTERVAL) {
return false;
}
// Show if:
// 1. There are uncommitted changes OR commits ahead of remote OR no remote configured
// 2. Enough messages have been sent since last interaction
const hasUnpushedWork =
gitStatus.hasUncommittedChanges ||
gitStatus.ahead > 0 ||
gitStatus.remotes.length === 0;
const enoughMessages = state.messagesSinceLastPush >= MESSAGE_THRESHOLD;
return hasUnpushedWork && enoughMessages;
}, [state, projectId, gitStatus]);
// Increment message counter
const incrementMessages = useCallback(() => {
if (!state.enabled || !projectId) return;
setState((prev) => ({
...prev,
messagesSinceLastPush: prev.messagesSinceLastPush + 1,
}));
}, [state.enabled, projectId, setState]);
// Reset counter (called after push or dismiss)
const resetReminder = useCallback(() => {
setState((prev) => ({
...prev,
messagesSinceLastPush: 0,
lastInteraction: Date.now(),
}));
}, [setState]);
// Enable/disable reminders
const setEnabled = useCallback((enabled: boolean) => {
setState((prev) => ({
...prev,
enabled,
messagesSinceLastPush: 0,
lastInteraction: Date.now(),
}));
}, [setState]);
// Check if there's unpushed work that should trigger warning icon
const hasUnpushedWork = gitStatus?.isGitRepo && (
gitStatus.hasUncommittedChanges ||
gitStatus.ahead > 0 ||
gitStatus.remotes.length === 0
);
return {
shouldShowReminder: shouldShowReminder(),
incrementMessages,
resetReminder,
enabled: state.enabled,
setEnabled,
hasUnpushedWork: hasUnpushedWork || false,
gitStatus,
};
}
+2
View File
@@ -57,6 +57,8 @@
"temporaryDirectoryDescription": "Filesystem path for temporary files",
"sentryDsn": "Sentry DSN",
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
"pushReminders": "Push reminders",
"pushRemindersDescription": "Show periodic reminders to push your code to a remote repository to prevent data loss.",
"shareErrorReports": "Share error reports",
"shareErrorReportsDescription": "Help improve this app by automatically sending crash and error reports.",
"english": "English",
+22
View File
@@ -8,12 +8,14 @@ import { Label } from "@/components/ui/label";
import { useIsMobile } from "@/hooks/useIsMobile";
import { useNavigate } from "react-router-dom";
import { useAppContext } from "@/hooks/useAppContext";
import { usePushReminder } from "@/hooks/usePushReminder";
export function Preferences() {
const { t } = useTranslation();
const isMobile = useIsMobile();
const navigate = useNavigate();
const { config, updateConfig } = useAppContext();
const pushReminder = usePushReminder(null);
return (
<div className="p-6 space-y-6">
@@ -73,6 +75,26 @@ export function Preferences() {
</p>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="push-reminders" className="text-sm font-medium">
{t('pushReminders')}
</Label>
</div>
<Switch
id="push-reminders"
checked={pushReminder.enabled}
onCheckedChange={(checked) => {
pushReminder.setEnabled(checked);
}}
/>
</div>
<p className="text-sm text-muted-foreground">
{t('pushRemindersDescription')}
</p>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
+43
View File
@@ -15,11 +15,14 @@ import { useNavigate } from 'react-router-dom';
import { ActionsMenu } from '@/components/ActionsMenu';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { PushWarningButton } from '@/components/PushWarningButton';
import { PushReminderDialog } from '@/components/PushReminderDialog';
import { StarButton } from '@/components/StarButton';
import { useBuildProject } from '@/hooks/useBuildProject';
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
import { useConsoleError } from '@/hooks/useConsoleError';
import { useAutoBuild } from '@/hooks/useAutoBuild';
import { usePushReminder } from '@/hooks/usePushReminder';
export function ProjectView() {
const { projectId } = useParams<{ projectId: string }>();
@@ -30,6 +33,7 @@ export function ProjectView() {
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
const [isAILoading, setIsAILoading] = useState(false);
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
const [isPushReminderOpen, setIsPushReminderOpen] = useState(false);
// Use console error state from provider
const { consoleError, dismissConsoleError, clearErrors } = useConsoleError();
@@ -43,6 +47,7 @@ export function ProjectView() {
const build = useBuildProject(projectId!);
const { data: isPreviewable = false } = useIsProjectPreviewable(projectId!);
const pushReminder = usePushReminder(projectId || null);
// Enable auto-build for previewable projects
useAutoBuild({
@@ -105,6 +110,18 @@ export function ProjectView() {
setIsAILoading(loading);
};
// Handle message sent - increment push reminder counter
const handleMessageSent = useCallback(() => {
pushReminder.incrementMessages();
}, [pushReminder]);
// Watch for when we should show the reminder (after state updates)
useEffect(() => {
if (pushReminder.shouldShowReminder && !isPushReminderOpen) {
setIsPushReminderOpen(true);
}
}, [pushReminder.shouldShowReminder, isPushReminderOpen]);
// Handle first user interaction to enable audio context
const handleFirstInteraction = () => {
// This will be handled automatically by the useKeepAlive hook
@@ -165,6 +182,7 @@ export function ProjectView() {
<div className="flex items-center gap-2">
{project ? (
<>
<PushWarningButton projectId={project.id} className="h-8" />
<StarButton
projectId={project.id}
projectName={project.name}
@@ -227,6 +245,7 @@ export function ProjectView() {
onNewChat={handleNewChat}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
onMessageSent={handleMessageSent}
isLoading={isAILoading}
isBuildLoading={build.isPending}
consoleError={consoleError}
@@ -307,6 +326,17 @@ export function ProjectView() {
onProjectDeleted={handleProjectDeleted}
/>
)}
{/* Push Reminder Dialog */}
{project && (
<PushReminderDialog
projectId={project.id}
open={isPushReminderOpen}
onOpenChange={setIsPushReminderOpen}
onDisableReminders={() => pushReminder.setEnabled(false)}
onDismiss={pushReminder.resetReminder}
/>
)}
</div>
);
}
@@ -374,6 +404,7 @@ export function ProjectView() {
<div className="flex items-center gap-2">
{project ? (
<>
<PushWarningButton projectId={project.id} className="h-8" />
<StarButton
projectId={project.id}
projectName={project.name}
@@ -408,6 +439,7 @@ export function ProjectView() {
onNewChat={handleNewChat}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
onMessageSent={handleMessageSent}
isLoading={isAILoading}
isBuildLoading={build.isPending}
consoleError={consoleError}
@@ -461,6 +493,17 @@ export function ProjectView() {
onProjectDeleted={handleProjectDeleted}
/>
)}
{/* Push Reminder Dialog */}
{project && (
<PushReminderDialog
projectId={project.id}
open={isPushReminderOpen}
onOpenChange={setIsPushReminderOpen}
onDisableReminders={() => pushReminder.setEnabled(false)}
onDismiss={pushReminder.resetReminder}
/>
)}
</div>
);
}
-986
View File
@@ -1,986 +0,0 @@
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>
);
}