From bc19d08a8ad4ecf9e0781e4bde52be57d71c8f61 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Tue, 30 Dec 2025 21:48:54 -0800 Subject: [PATCH] badge notification and modal --- src/App.tsx | 2 + src/components/BadgeAwardModal.tsx | 111 ++++++++++++++++++++++ src/components/BadgeAwardNotification.tsx | 14 +++ src/hooks/useBadgeAwardNotifications.ts | 106 +++++++++++++++++++++ src/locales/en.json | 5 +- src/pages/BadgesSettings.tsx | 56 ++++++++--- 6 files changed, 279 insertions(+), 15 deletions(-) create mode 100644 src/components/BadgeAwardModal.tsx create mode 100644 src/components/BadgeAwardNotification.tsx create mode 100644 src/hooks/useBadgeAwardNotifications.ts diff --git a/src/App.tsx b/src/App.tsx index a5af3b43..0eccb0a6 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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() { + diff --git a/src/components/BadgeAwardModal.tsx b/src/components/BadgeAwardModal.tsx new file mode 100644 index 00000000..0721cb64 --- /dev/null +++ b/src/components/BadgeAwardModal.tsx @@ -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 ( + !open && onClose()}> + +
+ {isLoading ? ( + <> + +
+ + +
+ + ) : ( + <> + {/* Badge image */} +
+ {imageUrl ? ( + {badgeName} + ) : ( + + )} +
+ + {/* Title */} +
+ {award &&

Badge Awarded!

} +

{badgeName}

+ {description && ( +

+ {description} +

+ )} +
+ + )} +
+
+
+ ); +} + diff --git a/src/components/BadgeAwardNotification.tsx b/src/components/BadgeAwardNotification.tsx new file mode 100644 index 00000000..f825aeb8 --- /dev/null +++ b/src/components/BadgeAwardNotification.tsx @@ -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 ; +} + diff --git a/src/hooks/useBadgeAwardNotifications.ts b/src/hooks/useBadgeAwardNotifications.ts new file mode 100644 index 00000000..d54b02f3 --- /dev/null +++ b/src/hooks/useBadgeAwardNotifications.ts @@ -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(null); + const abortControllerRef = useRef(null); + const isMountedRef = useRef(true); + const subscriptionStartTimeRef = useRef(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, + }; +} + diff --git a/src/locales/en.json b/src/locales/en.json index 31ae3827..8157e801 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -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" } diff --git a/src/pages/BadgesSettings.tsx b/src/pages/BadgesSettings.tsx index da3e4178..42d26464 100644 --- a/src/pages/BadgesSettings.tsx +++ b/src/pages/BadgesSettings.tsx @@ -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 ( - + - {imageUrl && ( -
+
+ {imageUrl ? ( {badgeName} -
- )} + ) : null} +
- - {badgeName} - + {awarded ? ( + + {badgeName} + + ) : ( +
+ +
+ )} {description && (

{description} @@ -57,6 +79,7 @@ export function BadgesSettings() { const { nostr } = useNostr(); const { user } = useCurrentUser(); const userPubkey = user?.pubkey; + const [selectedBadge, setSelectedBadge] = useState(null); const { data: badgeDefinitions, isLoading: isLoadingDefinitions } = useQuery({ queryKey: ['badge-definitions', BADGE_ISSUER_PUBKEY], @@ -117,6 +140,10 @@ export function BadgesSettings() { titleKey="badges" descriptionKey="badgesDescription" > + setSelectedBadge(null)} + />

{isLoading ? (
@@ -142,6 +169,7 @@ export function BadgesSettings() { key={event.id} event={event} awarded={isBadgeAwarded(event)} + onClick={isBadgeAwarded(event) ? () => setSelectedBadge(event) : undefined} /> ))}