Simplify nostr-comments skill and add 3-dots actions menu

- Drop the outer Card wrapper, title, and counter from CommentsSection; it
  now renders as a lightweight space-y-6 container matching starpoint.
- Drop the Card wrapper and 'Adding to the discussion' label from
  CommentForm; use a rounded Textarea + right-aligned 'Post' button.
- Add a per-comment 3-dots menu with 'Open in Ditto' (opens nevent on
  ditto.pub) and 'Delete' (NIP-09 kind 5, shown only for own comments,
  confirmed via AlertDialog, optimistically removes from the cached
  useComments result via queryClient.setQueriesData).
- Remove the obsolete title prop from SKILL.md docs and examples.
This commit is contained in:
Alex Gleason committed 2026-04-26 20:09:29 -05:00
1 parent 76dc27a513
commit 83c0ed42af
4 files changed
+238 -138

No files matched your search

+20 -21
View File
@@ -5,7 +5,7 @@ description: Implement Nostr comment systems, add discussion features to posts/a
# Adding Nostr Comments Sections
This skill provides a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event, URL, hashtag, or NIP-73 external content identifier. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
This skill provides a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event, URL, hashtag, or NIP-73 external content identifier. The `CommentsSection` component renders a lightweight, inline commenting interface with threaded replies, user authentication, and a per-comment actions menu (Open in Ditto, Delete own comment).
**The comment system is not included in the project by default.** When the user wants comment functionality, follow the setup instructions below to install the files.
@@ -37,14 +37,18 @@ The comment components depend on pieces that already ship with the template:
- `@/components/NoteContent` — renders comment text (used by `Comment.tsx`)
- `@/components/auth/LoginArea` — shown to logged-out users (used by `CommentForm.tsx`)
- `@/components/ui/alert-dialog` — confirms deletion (used by `Comment.tsx`)
- `@/hooks/useAuthor` — fetches comment author profile (used by `Comment.tsx`)
- `@/hooks/useCurrentUser` — determines whether to show the composer (used by `CommentForm.tsx`)
- `@/hooks/useNostrPublish` — publishes kind 1111 events (used by `usePostComment.ts`)
- `@/hooks/useCurrentUser` — determines whether to show the composer and the Delete action (used by `CommentForm.tsx`, `Comment.tsx`)
- `@/hooks/useNostrPublish` — publishes kind 1111 comments and kind 5 deletion requests (used by `usePostComment.ts`, `Comment.tsx`)
- `@/hooks/useToast` — user feedback on delete success/failure (used by `Comment.tsx`)
All of these are standard in the template; no extra work is needed beyond copying the skill files.
## Basic Usage
`CommentsSection` renders without an outer card, title, or header — it's just the composer followed by the threaded comment list. Wrap it in whatever page layout you want:
```tsx
import { CommentsSection } from "@/components/comments/CommentsSection";
@@ -54,13 +58,23 @@ function ArticlePage({ article }: { article: NostrEvent }) {
{/* Your article content */}
<div>{/* article content */}</div>
{/* Comments section */}
<CommentsSection root={article} />
{/* Comments section — add your own heading if needed */}
<section className="space-y-4">
<h2 className="text-lg font-semibold">Comments</h2>
<CommentsSection root={article} />
</section>
</div>
);
}
```
## Per-Comment Actions Menu
Each comment has a 3-dots menu with:
- **Open in Ditto** — opens the comment at `https://ditto.pub/<nevent>` in a new tab so users can view replies, react, or zap via Ditto.
- **Delete** — only shown when the logged-in user is the comment's author. Publishes a NIP-09 (kind 5) deletion request tagging the comment's `id` and `kind`, then optimistically removes the comment from the cached query result via `queryClient.setQueriesData`. Deletion is not guaranteed across the network — the `AlertDialog` confirmation makes this clear to the user.
## Props and Customization
The `CommentsSection` component accepts the following props:
@@ -69,16 +83,14 @@ The `CommentsSection` component accepts the following props:
- `NostrEvent` — comment on a Nostr event (kind 1 note, long-form article, etc.)
- `URL` — comment on an external identifier: web URLs (`new URL("https://...")`) or any NIP-73 identifier except hashtags (e.g. `new URL("isbn:9780765382030")`, `new URL("iso3166:US")`)
- `#${string}` — NIP-73 hashtag only (e.g. `"#bitcoin"`); this template string type is exclusively for hashtags and must not be used for other NIP-73 identifiers
- **`title`**: Custom title for the comments section (default: "Comments")
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
- **`className`**: Additional CSS classes for styling
- **`className`**: Additional CSS classes applied to the outer `<div>` (it's a plain `space-y-6` container, no card/border)
- **`limit`**: Maximum number of comments to load (default: 500)
```tsx
<CommentsSection
root={event}
title="Discussion"
emptyStateMessage="Start the conversation"
emptyStateSubtitle="Share your thoughts about this post"
className="mt-8"
@@ -93,7 +105,6 @@ The comments system supports commenting on external URLs, making it useful for w
```tsx
<CommentsSection
root={new URL("https://example.com/article")}
title="Comments on this article"
/>
```
@@ -105,13 +116,11 @@ Pass a hashtag string (`#${string}` format) to attach comments to a topic. The h
// Comments for the #bitcoin hashtag
<CommentsSection
root="#bitcoin"
title="Bitcoin Discussion"
/>
// Comments for a community-specific tag
<CommentsSection
root="#nostr"
title="Nostr Community"
/>
```
@@ -125,7 +134,6 @@ NIP-73 defines a standard set of external content IDs. All NIP-73 identifiers (e
// ISBN must be without hyphens
<CommentsSection
root={new URL("isbn:9780765382030")}
title="Book Discussion"
/>
```
@@ -135,13 +143,11 @@ NIP-73 defines a standard set of external content IDs. All NIP-73 identifiers (e
// Podcast feed
<CommentsSection
root={new URL("podcast:guid:c90e609a-df1e-596a-bd5e-57bcc8aad6cc")}
title="Podcast Discussion"
/>
// Podcast episode
<CommentsSection
root={new URL("podcast:item:guid:d98d189b-dc7b-45b1-8720-d4b98690f31f")}
title="Episode Discussion"
/>
```
@@ -151,7 +157,6 @@ NIP-73 defines a standard set of external content IDs. All NIP-73 identifiers (e
// ISAN without version part
<CommentsSection
root={new URL("isan:0000-0000-401A-0000-7")}
title="Movie Discussion"
/>
```
@@ -161,7 +166,6 @@ NIP-73 defines a standard set of external content IDs. All NIP-73 identifiers (e
// Geohash must be lowercase
<CommentsSection
root={new URL("geo:ezs42e44yx96")}
title="Location Discussion"
/>
```
@@ -171,13 +175,11 @@ NIP-73 defines a standard set of external content IDs. All NIP-73 identifiers (e
// ISO 3166 codes must be uppercase
<CommentsSection
root={new URL("iso3166:US")}
title="USA Discussion"
/>
// Subdivision (state/province)
<CommentsSection
root={new URL("iso3166:US-CA")}
title="California Discussion"
/>
```
@@ -187,7 +189,6 @@ NIP-73 defines a standard set of external content IDs. All NIP-73 identifiers (e
// DOI must be lowercase
<CommentsSection
root={new URL("doi:10.1000/xyz123")}
title="Paper Discussion"
/>
```
@@ -197,12 +198,10 @@ NIP-73 defines a standard set of external content IDs. All NIP-73 identifiers (e
// Bitcoin transaction
<CommentsSection
root={new URL("bitcoin:tx:a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d")}
title="Transaction Discussion"
/>
// Ethereum address
<CommentsSection
root={new URL("ethereum:1:address:0xd8da6bf26964af9d7eed9e03e53415d37aa96045")}
title="Address Discussion"
/>
```
@@ -4,14 +4,41 @@ import { NostrEvent } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor';
import { useComments } from '@/hooks/useComments';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useToast } from '@/hooks/useToast';
import { useQueryClient } from '@tanstack/react-query';
import { CommentForm } from './CommentForm';
import { NoteContent } from '@/components/NoteContent';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { DropdownMenu, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { MessageSquare, ChevronDown, ChevronRight, MoreHorizontal } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
MessageSquare,
ChevronDown,
ChevronRight,
MoreHorizontal,
ExternalLink,
Trash2,
} from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import { genUserName } from '@/lib/genUserName';
@@ -26,18 +53,73 @@ 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 [showDeleteDialog, setShowDeleteDialog] = useState(false);
const author = useAuthor(comment.pubkey);
const { data: commentsData } = useComments(root, limit);
const { user } = useCurrentUser();
const { mutate: publishEvent, isPending: isDeleting } = useNostrPublish();
const { toast } = useToast();
const queryClient = useQueryClient();
const metadata = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(comment.pubkey)
const displayName = metadata?.name ?? genUserName(comment.pubkey);
const timeAgo = formatDistanceToNow(new Date(comment.created_at * 1000), { addSuffix: true });
const nevent = nip19.neventEncode({ id: comment.id, author: comment.pubkey, kind: comment.kind });
const isOwnComment = user?.pubkey === comment.pubkey;
// Get direct replies to this comment
const replies = commentsData?.getDirectReplies(comment.id) || [];
const hasReplies = replies.length > 0;
const handleDelete = () => {
publishEvent(
{
kind: 5,
content: '',
tags: [
['e', comment.id],
['k', comment.kind.toString()],
],
},
{
onSuccess: () => {
toast({ title: 'Comment deleted' });
setShowDeleteDialog(false);
// Optimistically remove the deleted comment from every cached useComments
// result. Relays may honor the kind 5 deletion request on refetch, but
// that's not guaranteed — this keeps the UI consistent immediately.
queryClient.setQueriesData<ReturnType<typeof useComments>['data']>(
{ queryKey: ['nostr', 'comments'] },
(oldData) => {
if (!oldData) return oldData;
const allComments = oldData.allComments.filter((c) => c.id !== comment.id);
const topLevelComments = oldData.topLevelComments.filter(
(c) => c.id !== comment.id,
);
return {
...oldData,
allComments,
topLevelComments,
getDescendants: (id: string) =>
oldData.getDescendants(id).filter((c) => c.id !== comment.id),
getDirectReplies: (id: string) =>
oldData.getDirectReplies(id).filter((c) => c.id !== comment.id),
};
},
);
},
onError: (error) => {
toast({
title: 'Failed to delete comment',
description: error.message,
variant: 'destructive',
});
},
},
);
};
return (
<div className={`space-y-3 ${depth > 0 ? 'ml-6 border-l-2 border-muted pl-4' : ''}`}>
<Card className="bg-card/50">
@@ -55,7 +137,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"
>
@@ -83,7 +165,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>
@@ -112,6 +194,33 @@ export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: Comme
<MoreHorizontal className="h-3 w-3" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem asChild>
<a
href={`https://ditto.pub/${nevent}`}
target="_blank"
rel="noopener noreferrer"
>
<ExternalLink className="h-3.5 w-3.5 mr-2" />
Open in Ditto
</a>
</DropdownMenuItem>
{isOwnComment && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onSelect={(e) => {
e.preventDefault();
setShowDeleteDialog(true);
}}
className="text-destructive focus:text-destructive"
>
<Trash2 className="h-3.5 w-3.5 mr-2" />
Delete
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
@@ -148,6 +257,33 @@ export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: Comme
</CollapsibleContent>
</Collapsible>
)}
{/* Delete confirmation */}
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete comment?</AlertDialogTitle>
<AlertDialogDescription>
This publishes a NIP-09 deletion request (kind 5). Relays and clients that
honor deletion requests will hide this comment, but deletion is not
guaranteed across the network.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => {
e.preventDefault();
handleDelete();
}}
disabled={isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting ? 'Deleting…' : 'Delete'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
}
@@ -1,12 +1,12 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent } from '@/components/ui/card';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { usePostComment } from '@/hooks/usePostComment';
import { LoginArea } from '@/components/auth/LoginArea';
import { NostrEvent } from '@nostrify/nostrify';
import { MessageSquare, Send } from 'lucide-react';
import { MessageSquare } from 'lucide-react';
import { cn } from '@/lib/utils';
interface CommentFormProps {
root: NostrEvent | URL | `#${string}`;
@@ -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(
@@ -45,46 +45,37 @@ export function CommentForm({
if (!user) {
return (
<Card className={compact ? "border-dashed" : ""}>
<CardContent className={compact ? "p-4" : "p-6"}>
<div className="text-center space-y-4">
<div className="flex items-center justify-center space-x-2 text-muted-foreground">
<MessageSquare className="h-5 w-5" />
<span>Sign in to {reply ? 'reply' : 'comment'}</span>
</div>
<LoginArea />
<div className={cn("rounded-2xl border border-dashed bg-muted/30", compact ? "p-4" : "p-6")}>
<div className="text-center space-y-4">
<div className="flex items-center justify-center space-x-2 text-muted-foreground">
<MessageSquare className="h-5 w-5" />
<span>Sign in to {reply ? 'reply' : 'comment'}</span>
</div>
</CardContent>
</Card>
<LoginArea />
</div>
</div>
);
}
return (
<Card className={compact ? "border-dashed" : ""}>
<CardContent className={compact ? "p-4" : "p-6"}>
<form onSubmit={handleSubmit} className="space-y-4">
<Textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder={placeholder}
className={compact ? "min-h-[80px]" : "min-h-[100px]"}
disabled={isPending}
/>
<div className="flex justify-between items-center">
<span className="text-sm text-muted-foreground">
{reply ? 'Replying to comment' : 'Adding to the discussion'}
</span>
<Button
type="submit"
disabled={!content.trim() || isPending}
size={compact ? "sm" : "default"}
>
<Send className="h-4 w-4 mr-2" />
{isPending ? 'Posting...' : (reply ? 'Reply' : 'Comment')}
</Button>
</div>
</form>
</CardContent>
</Card>
<form onSubmit={handleSubmit} className="space-y-3">
<Textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder={placeholder}
className={cn("rounded-2xl resize-none", compact ? "min-h-[80px]" : "min-h-[100px]")}
disabled={isPending}
/>
<div className="flex justify-end">
<Button
type="submit"
disabled={!content.trim() || isPending}
size={compact ? "sm" : "default"}
className="rounded-full px-6"
>
{isPending ? 'Posting…' : 'Post'}
</Button>
</div>
</form>
);
}
}
@@ -1,5 +1,4 @@
import { useComments } from '@/hooks/useComments';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { MessageSquare } from 'lucide-react';
import { cn } from '@/lib/utils';
@@ -9,16 +8,14 @@ import { Comment } from './Comment';
interface CommentsSectionProps {
root: NostrEvent | URL | `#${string}`;
title?: string;
emptyStateMessage?: string;
emptyStateSubtitle?: string;
className?: string;
limit?: number;
}
export function CommentsSection({
export function CommentsSection({
root,
title = "Comments",
emptyStateMessage = "No comments yet",
emptyStateSubtitle = "Be the first to share your thoughts!",
className,
@@ -29,72 +26,49 @@ export function CommentsSection({
if (error) {
return (
<Card className="rounded-none sm:rounded-lg mx-0 sm:mx-0">
<CardContent className="px-2 py-6 sm:p-6">
<div className="text-center text-muted-foreground">
<MessageSquare className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p>Failed to load comments</p>
</div>
</CardContent>
</Card>
<div className={cn("text-center text-muted-foreground py-6", className)}>
<MessageSquare className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p>Failed to load comments</p>
</div>
);
}
return (
<Card className={cn("rounded-none sm:rounded-lg mx-0 sm:mx-0", className)}>
<CardHeader className="px-2 pt-6 pb-4 sm:p-6">
<CardTitle className="flex items-center space-x-2">
<MessageSquare className="h-5 w-5" />
<span>{title}</span>
{!isLoading && (
<span className="text-sm font-normal text-muted-foreground">
({comments.length})
</span>
)}
</CardTitle>
</CardHeader>
<CardContent className="px-2 pb-6 pt-4 sm:p-6 sm:pt-0 space-y-6">
{/* Comment Form */}
<CommentForm root={root} />
<div className={cn("space-y-6", className)}>
<CommentForm root={root} />
{/* Comments List */}
{isLoading ? (
<div className="space-y-4">
{[...Array(3)].map((_, i) => (
<Card key={i} className="bg-card/50">
<CardContent className="p-4">
<div className="space-y-3">
<div className="flex items-center space-x-3">
<Skeleton className="h-8 w-8 rounded-full" />
<div className="space-y-1">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
</div>
<Skeleton className="h-16 w-full" />
</div>
</CardContent>
</Card>
))}
</div>
) : comments.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
<MessageSquare className="h-12 w-12 mx-auto mb-4 opacity-30" />
<p className="text-lg font-medium mb-2">{emptyStateMessage}</p>
<p className="text-sm">{emptyStateSubtitle}</p>
</div>
) : (
<div className="space-y-4">
{comments.map((comment) => (
<Comment
key={comment.id}
root={root}
comment={comment}
/>
))}
</div>
)}
</CardContent>
</Card>
{isLoading ? (
<div className="space-y-4">
{[...Array(3)].map((_, i) => (
<div key={i} className="space-y-3">
<div className="flex items-center space-x-3">
<Skeleton className="h-8 w-8 rounded-full" />
<div className="space-y-1">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
</div>
<Skeleton className="h-16 w-full" />
</div>
))}
</div>
) : comments.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
<MessageSquare className="h-12 w-12 mx-auto mb-4 opacity-30" />
<p className="text-lg font-medium mb-2">{emptyStateMessage}</p>
<p className="text-sm">{emptyStateSubtitle}</p>
</div>
) : (
<div className="space-y-4">
{comments.map((comment) => (
<Comment
key={comment.id}
root={root}
comment={comment}
/>
))}
</div>
)}
</div>
);
}
}