badge notification and modal

This commit is contained in:
lemonknowsall committed 2026-01-07 19:46:00 -08:00
1 parent 575536eb35
commit bc19d08a8a
6 files changed
+279 -15

No files matched your search

+2
View File
@@ -28,6 +28,7 @@ import { DynamicFavicon } from '@/components/DynamicFavicon';
import { OfflineIndicator } from '@/components/OfflineIndicator';
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { BadgeAwardNotification } from '@/components/BadgeAwardNotification';
import AppRouter from './AppRouter';
@@ -152,6 +153,7 @@ export function App() {
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<BadgeAwardNotification />
<Suspense>
<AppRouter />
</Suspense>
+111
View File
@@ -0,0 +1,111 @@
import { Dialog, DialogContent } from "@/components/ui/dialog";
import { Award } from "lucide-react";
import type { NostrEvent } from '@nostrify/nostrify';
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from '@/lib/utils';
const BADGE_ISSUER_PUBKEY = "804a5a94d972d2218d2cc8712881e6f00df09fe7a1a269ccbf916e5c8c17efcc";
interface BadgeAwardModalProps {
award?: NostrEvent | null;
badgeDefinition?: NostrEvent | null;
onClose: () => void;
}
export function BadgeAwardModal({ award, badgeDefinition: providedBadgeDefinition, onClose }: BadgeAwardModalProps) {
const { nostr } = useNostr();
// If we have a badge definition directly, use it
// Otherwise, extract from award event
let dTag: string | undefined;
if (providedBadgeDefinition) {
dTag = providedBadgeDefinition.tags.find(([t]) => t === "d")?.[1];
} else if (award) {
const aTag = award.tags.find(([t]) => t === "a")?.[1];
if (aTag) {
const [kindStr, pubkey, parsedDTag] = aTag.split(':');
if (kindStr === '30009' && pubkey === BADGE_ISSUER_PUBKEY && parsedDTag) {
dTag = parsedDTag;
}
}
}
if (!dTag && !providedBadgeDefinition) return null;
// Fetch badge definition if we don't have it directly
const { data: fetchedBadgeDefinition, isLoading } = useQuery({
queryKey: ['badge-definition', BADGE_ISSUER_PUBKEY, dTag],
queryFn: async (c) => {
if (!dTag) return null;
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
const events = await nostr.query([{
kinds: [30009],
authors: [BADGE_ISSUER_PUBKEY],
"#d": [dTag],
limit: 1,
}], { signal });
return events[0] || null;
},
enabled: !!dTag && !providedBadgeDefinition,
});
const badgeDefinition = providedBadgeDefinition || fetchedBadgeDefinition;
const isModalOpen = !!award || !!providedBadgeDefinition;
const nameTag = badgeDefinition?.tags?.find(([t]) => t === "name")?.[1];
const descriptionTag = badgeDefinition?.tags?.find(([t]) => t === "description")?.[1];
const imageTag = badgeDefinition?.tags?.find(([t]) => t === "image")?.[1];
const thumbTags = badgeDefinition?.tags?.filter(([t]) => t === "thumb") || [];
const badgeName = nameTag || dTag || "Unnamed Badge";
const description = descriptionTag || "";
const imageUrl = imageTag || (thumbTags.length > 0 ? thumbTags[thumbTags.length - 1]?.[1] : null);
return (
<Dialog open={isModalOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="w-[600px] h-[600px] aspect-square bg-transparent [&>button]:hidden border-0 ring-0 outline-none shadow-none flex items-center justify-center p-0">
<div className="flex flex-col items-center justify-center space-y-8 w-full h-full px-8">
{isLoading ? (
<>
<Skeleton className="h-96 w-96 rounded-lg" />
<div className="space-y-2 text-center">
<Skeleton className="h-8 w-64 mx-auto" />
<Skeleton className="h-5 w-80 mx-auto" />
</div>
</>
) : (
<>
{/* Badge image */}
<div className="relative aspect-square w-96 before:absolute before:inset-0 before:rounded-lg before:bg-white/30 before:blur-2xl before:animate-pulse before:-z-10">
{imageUrl ? (
<img
src={imageUrl}
alt={badgeName}
className="h-full w-full rounded-lg object-cover shadow-2xl"
/>
) : (
<Award className="h-full w-full text-primary drop-shadow-lg" />
)}
</div>
{/* Title */}
<div className="text-center space-y-3">
{award && <h2 className="text-3xl font-bold">Badge Awarded!</h2>}
<p className="text-2xl font-semibold">{badgeName}</p>
{description && (
<p className="text-base text-muted-foreground max-w-md">
{description}
</p>
)}
</div>
</>
)}
</div>
</DialogContent>
</Dialog>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { useBadgeAwardNotifications } from '@/hooks/useBadgeAwardNotifications';
import { BadgeAwardModal } from './BadgeAwardModal';
/**
* Global badge award notification component.
* Listens for badge awards and displays a modal when a new badge is received.
* This component should be placed at the App level to work globally.
*/
export function BadgeAwardNotification() {
const { newAward, clearNewAward } = useBadgeAwardNotifications();
return <BadgeAwardModal award={newAward} onClose={clearNewAward} />;
}
+106
View File
@@ -0,0 +1,106 @@
import { useEffect, useRef, useState } from 'react';
import { useNostr } from '@nostrify/react';
import { useCurrentUser } from './useCurrentUser';
import type { NostrEvent } from '@nostrify/nostrify';
const BADGE_ISSUER_PUBKEY = "804a5a94d972d2218d2cc8712881e6f00df09fe7a1a269ccbf916e5c8c17efcc";
export function useBadgeAwardNotifications() {
const { nostr } = useNostr();
const { user } = useCurrentUser();
const [newAward, setNewAward] = useState<NostrEvent | null>(null);
const abortControllerRef = useRef<AbortController | null>(null);
const isMountedRef = useRef(true);
const subscriptionStartTimeRef = useRef<number | null>(null);
useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
useEffect(() => {
if (!user?.pubkey) {
// Clear subscription if user logs out
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
return;
}
// Create abort controller for this subscription
const abortController = new AbortController();
abortControllerRef.current = abortController;
// Set the subscription start time to now, so we only get new events
const subscriptionStartTime = Math.floor(Date.now() / 1000);
subscriptionStartTimeRef.current = subscriptionStartTime;
// Set up subscription for new badge awards
const setupSubscription = async () => {
try {
const subscription = nostr.req([{
kinds: [8],
authors: [BADGE_ISSUER_PUBKEY],
"#p": [user.pubkey],
since: subscriptionStartTime, // Only get events from now onwards
}]);
// Process messages from the subscription
// Messages are in format: [type, subscriptionId, event]
for await (const msg of subscription) {
// Check if subscription was aborted or component unmounted
if (abortController.signal.aborted || !isMountedRef.current) {
break;
}
// Handle EVENT messages (msg[0] === 'EVENT')
if (msg[0] === 'EVENT') {
const event = msg[2] as NostrEvent;
// Only show if component is still mounted and not aborted
if (isMountedRef.current && !abortController.signal.aborted) {
setNewAward(event);
}
}
// EOSE (End of Stored Events) - subscription is complete for initial query
// We continue listening for new events, so we don't break here
if (msg[0] === 'EOSE') {
// Initial query complete, now listening for new events
continue;
}
}
} catch (error) {
// Subscription closed or error - this is normal on cleanup
// Ignore errors if we aborted or unmounted
if (abortController.signal.aborted || !isMountedRef.current) {
return;
}
console.error('Error in badge award subscription:', error);
}
};
setupSubscription();
// Cleanup on unmount or user change
return () => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
};
}, [nostr, user?.pubkey]);
const clearNewAward = () => {
setNewAward(null);
};
return {
newAward,
clearNewAward,
};
}
+4 -1
View File
@@ -561,5 +561,8 @@
"failedToDuplicateProject": "Failed to duplicate project",
"newProjectName": "New Project Name",
"duplicateProjectDescription": "Create a copy of this project with a new name",
"resume": "Resume"
"resume": "Resume",
"badges": "Badges",
"badgesDescription": "View and manage your earned badges and achievements",
"noBadgesFound": "No badges found"
}
+42 -14
View File
@@ -1,4 +1,4 @@
import { Award } from "lucide-react";
import { Award, Lock } from "lucide-react";
import { useTranslation } from 'react-i18next';
import { SettingsPageLayout } from '@/components/SettingsPageLayout';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
@@ -6,12 +6,22 @@ import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import { Skeleton } from "@/components/ui/skeleton";
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { BadgeAwardModal } from '@/components/BadgeAwardModal';
import { cn } from '@/lib/utils';
import { useState } from 'react';
import type { NostrEvent } from '@nostrify/nostrify';
const BADGE_ISSUER_PUBKEY = "804a5a94d972d2218d2cc8712881e6f00df09fe7a1a269ccbf916e5c8c17efcc";
function BadgeCard({ event, awarded }: { event: NostrEvent; awarded: boolean }) {
function BadgeCard({
event,
awarded,
onClick
}: {
event: NostrEvent;
awarded: boolean;
onClick?: () => void;
}) {
const dTag = event.tags.find(([t]) => t === "d")?.[1];
const nameTag = event.tags.find(([t]) => t === "name")?.[1];
const descriptionTag = event.tags.find(([t]) => t === "description")?.[1];
@@ -23,24 +33,36 @@ function BadgeCard({ event, awarded }: { event: NostrEvent; awarded: boolean })
const imageUrl = imageTag || (thumbTags.length > 0 ? thumbTags[thumbTags.length - 1]?.[1] : null);
return (
<Card className={cn(
"transition-all bg-transparent border-none shadow-none",
awarded ? "" : "opacity-50 grayscale"
)}>
<Card
className={cn(
"transition-all bg-transparent border-none shadow-none",
awarded ? "cursor-pointer hover:scale-105" : ""
)}
onClick={awarded ? onClick : undefined}
>
<CardHeader className="text-center space-y-4 p-0">
{imageUrl && (
<div className="flex justify-center">
<div className="flex justify-center">
{imageUrl ? (
<img
src={imageUrl}
alt={badgeName}
className="w-32 h-32 rounded-lg object-cover"
className={cn(
"w-32 h-32 rounded-lg object-cover",
awarded ? "" : "opacity-50 grayscale blur-md"
)}
/>
</div>
)}
) : null}
</div>
<div className="space-y-2">
<CardTitle className={cn("text-lg", awarded ? "" : "text-muted-foreground")}>
{badgeName}
</CardTitle>
{awarded ? (
<CardTitle className="text-lg">
{badgeName}
</CardTitle>
) : (
<div className="flex items-center justify-center">
<Lock className="h-5 w-5 text-muted-foreground" />
</div>
)}
{description && (
<p className={cn("text-sm", awarded ? "text-muted-foreground" : "text-muted-foreground/70")}>
{description}
@@ -57,6 +79,7 @@ export function BadgesSettings() {
const { nostr } = useNostr();
const { user } = useCurrentUser();
const userPubkey = user?.pubkey;
const [selectedBadge, setSelectedBadge] = useState<NostrEvent | null>(null);
const { data: badgeDefinitions, isLoading: isLoadingDefinitions } = useQuery({
queryKey: ['badge-definitions', BADGE_ISSUER_PUBKEY],
@@ -117,6 +140,10 @@ export function BadgesSettings() {
titleKey="badges"
descriptionKey="badgesDescription"
>
<BadgeAwardModal
badgeDefinition={selectedBadge}
onClose={() => setSelectedBadge(null)}
/>
<div className="space-y-4">
{isLoading ? (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
@@ -142,6 +169,7 @@ export function BadgesSettings() {
key={event.id}
event={event}
awarded={isBadgeAwarded(event)}
onClick={isBadgeAwarded(event) ? () => setSelectedBadge(event) : undefined}
/>
))}
</div>