mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-04 08:13:34 +00:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f1b3e6b7e | ||
|
|
749d173cf4 | ||
|
|
a7b45b5068 | ||
|
|
d26d1051f1 | ||
|
|
d99a9e1c46 | ||
|
|
8be2ef7b22 | ||
|
|
75a0d637ce | ||
|
|
a84ba7385b | ||
|
|
2fdd9e6a49 | ||
|
|
67a77419df | ||
|
|
4676738a14 | ||
|
|
444dfbc5dd | ||
|
|
5d075e02ab | ||
|
|
6edc623c13 | ||
|
|
027cd819f8 | ||
|
|
ef55e80c35 | ||
|
|
3666aac2a1 | ||
|
|
f58f75ae8b |
No files matched your search
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"mcp": {
|
||||
"nostr": {
|
||||
"type": "local",
|
||||
"command": ["npx", "-y", "@nostrbook/mcp@latest"]
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+18
-18
@@ -2816,9 +2816,9 @@
|
||||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/sdk": {
|
||||
"version": "1.25.1",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.25.1.tgz",
|
||||
"integrity": "sha512-yO28oVFFC7EBoiKdAn+VqRm+plcfv4v0xp6osG/VsCB0NlPZWi87ajbCZZ8f/RvOFLEu7//rSRmuZZ7lMoe3gQ==",
|
||||
"version": "1.25.2",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.25.2.tgz",
|
||||
"integrity": "sha512-LZFeo4F9M5qOhC/Uc1aQSrBHxMrvxett+9KLHt7OhcExtoiRN9DKgbZffMP/nxjutWDQpfMDfP3nkHI4X9ijww==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@hono/node-server": "^1.19.7",
|
||||
@@ -4389,9 +4389,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@remix-run/router": {
|
||||
"version": "1.23.0",
|
||||
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.0.tgz",
|
||||
"integrity": "sha512-O3rHJzAQKamUz1fvE0Qaw0xSFqsA/yafi2iqeE0pvdFtCO1viYx8QL6f3Ln/aCCTLxs68SLf0KPM9eSeM8yBnA==",
|
||||
"version": "1.23.2",
|
||||
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz",
|
||||
"integrity": "sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
@@ -12557,9 +12557,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.14.0",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz",
|
||||
"integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==",
|
||||
"version": "6.14.1",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz",
|
||||
"integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"side-channel": "^1.1.0"
|
||||
@@ -12829,12 +12829,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/react-router": {
|
||||
"version": "6.30.0",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.0.tgz",
|
||||
"integrity": "sha512-D3X8FyH9nBcTSHGdEKurK7r8OYE1kKFn3d/CF+CoxbSHkxU7o37+Uh7eAHRXr6k2tSExXYO++07PeXJtA/dEhQ==",
|
||||
"version": "6.30.3",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.3.tgz",
|
||||
"integrity": "sha512-XRnlbKMTmktBkjCLE8/XcZFlnHvr2Ltdr1eJX4idL55/9BbORzyZEaIkBFDhFGCEWBBItsVrDxwx3gnisMitdw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@remix-run/router": "1.23.0"
|
||||
"@remix-run/router": "1.23.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
@@ -12844,13 +12844,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/react-router-dom": {
|
||||
"version": "6.30.0",
|
||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.0.tgz",
|
||||
"integrity": "sha512-x30B78HV5tFk8ex0ITwzC9TTZMua4jGyA9IUlH1JLQYQTFyxr/ZxwOJq7evg1JX1qGVUcvhsmQSKdPncQrjTgA==",
|
||||
"version": "6.30.3",
|
||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.3.tgz",
|
||||
"integrity": "sha512-pxPcv1AczD4vso7G4Z3TKcvlxK7g7TNt3/FNGMhfqyntocvYKj+GCatfigGDjbLozC4baguJ0ReCigoDJXb0ag==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@remix-run/router": "1.23.0",
|
||||
"react-router": "6.30.0"
|
||||
"@remix-run/router": "1.23.2",
|
||||
"react-router": "6.30.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
|
||||
Binary file not shown.
+3
-2
@@ -28,7 +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 { NWCProvider } from '@/contexts/NWCContext';
|
||||
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
@@ -143,6 +143,7 @@ export function App() {
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<NostrSync />
|
||||
<NWCProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<DeploySettingsProvider>
|
||||
@@ -153,7 +154,6 @@ export function App() {
|
||||
<DynamicFavicon />
|
||||
<OfflineIndicator />
|
||||
<PWAUpdatePrompt />
|
||||
<BadgeAwardNotification />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
@@ -163,6 +163,7 @@ export function App() {
|
||||
</DeploySettingsProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NWCProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</ConsoleErrorProvider>
|
||||
|
||||
+4
-2
@@ -5,16 +5,17 @@ import { URLFragmentHandler } from "./components/URLFragmentHandler";
|
||||
|
||||
import Index from "./pages/Index";
|
||||
import Clone from "./pages/Clone";
|
||||
import Explore from "./pages/Explore";
|
||||
import Settings from "./pages/Settings";
|
||||
import Preferences from "./pages/Preferences";
|
||||
import NostrSettings from "./pages/NostrSettings";
|
||||
import AISettings from "./pages/AISettings";
|
||||
import GitSettings from "./pages/GitSettings";
|
||||
import DeploySettings from "./pages/DeploySettings";
|
||||
import WalletSettings from "./pages/WalletSettings";
|
||||
import SystemSettings from "./pages/SystemSettings";
|
||||
import StorageSettings from "./pages/StorageSettings";
|
||||
import AboutSettings from "./pages/AboutSettings";
|
||||
import BadgesSettings from "./pages/BadgesSettings";
|
||||
|
||||
import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import NetlifyOAuth from "./pages/NetlifyOAuth";
|
||||
@@ -38,6 +39,7 @@ export function AppRouter() {
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/giftcard" element={<Index />} />
|
||||
<Route path="/clone" element={<Clone />} />
|
||||
<Route path="/explore" element={<Explore />} />
|
||||
<Route path="/oauth/github" element={<GitHubOAuth />} />
|
||||
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
||||
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
||||
@@ -49,10 +51,10 @@ export function AppRouter() {
|
||||
<Route path="ai" element={<AISettings />} />
|
||||
<Route path="git" element={<GitSettings />} />
|
||||
<Route path="deploy" element={<DeploySettings />} />
|
||||
<Route path="wallet" element={<WalletSettings />} />
|
||||
<Route path="system" element={<SystemSettings />} />
|
||||
<Route path="storage" element={<StorageSettings />} />
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
<Route path="badges" element={<BadgesSettings />} />
|
||||
</Route>
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { Dialog, DialogContent, DialogTitle, DialogDescription } 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 { BADGE_ISSUER_PUBKEY } from '@/pages/BadgesSettings';
|
||||
|
||||
interface BadgeAwardModalProps {
|
||||
award?: NostrEvent | null;
|
||||
badgeDefinition?: NostrEvent | null;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function BadgeAwardModal({ award, badgeDefinition: providedBadgeDefinition, onClose }: BadgeAwardModalProps) {
|
||||
const { nostr } = useNostr();
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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;
|
||||
|
||||
// Play sound when badge is awarded (only when award is present, not just viewing badge definition)
|
||||
useEffect(() => {
|
||||
if (award && badgeDefinition && isModalOpen && !isLoading) {
|
||||
// Create audio element if it doesn't exist
|
||||
if (!audioRef.current) {
|
||||
audioRef.current = new Audio('/badgeAwarded.mp3');
|
||||
audioRef.current.volume = 0.5; // Set volume to 50%
|
||||
}
|
||||
|
||||
// Reset to beginning and play the sound
|
||||
audioRef.current.currentTime = 0;
|
||||
audioRef.current.play().catch((error) => {
|
||||
// Silently handle autoplay restrictions
|
||||
console.debug('Audio playback failed:', error);
|
||||
});
|
||||
}
|
||||
}, [award, badgeDefinition, isModalOpen, isLoading]);
|
||||
|
||||
// Return null after all hooks if we don't have a badge definition
|
||||
if (!badgeDefinition) return null;
|
||||
|
||||
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-[min(90vw,600px)] aspect-square bg-transparent [&>button]:hidden border-0 ring-0 outline-none shadow-none flex items-center justify-center p-[min(4vw,2rem)]">
|
||||
<DialogTitle className="sr-only">
|
||||
{award ? `Badge Awarded: ${badgeName}` : badgeName}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="sr-only">
|
||||
{description || `Badge: ${badgeName}`}
|
||||
</DialogDescription>
|
||||
<div className="flex flex-col items-center justify-center space-y-[min(4vw,2rem)] w-full h-full">
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Skeleton className="w-[min(60vw,384px)] aspect-square rounded-lg" />
|
||||
<div className="space-y-2 text-center w-full">
|
||||
<Skeleton className="h-[clamp(1.5rem,4vw,2rem)] w-[min(80%,16rem)] mx-auto" />
|
||||
<Skeleton className="h-[clamp(1rem,3vw,1.25rem)] w-[min(90%,20rem)] mx-auto" />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{/* Badge image */}
|
||||
<div className="relative aspect-square w-[min(60vw,384px)] 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-[min(1vw,0.75rem)] w-full px-4">
|
||||
<p className="text-[clamp(1.25rem,5vw,1.5rem)] font-semibold">{badgeName}</p>
|
||||
{description && (
|
||||
<p className="text-[clamp(0.875rem,3vw,1rem)] text-muted-foreground max-w-md mx-auto">
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
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} />;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders } from 'lucide-react';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders, Compass } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@@ -367,6 +367,13 @@ export function ProjectSidebar({
|
||||
<GitBranch className="h-4 w-4" />
|
||||
{t('importRepository')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => navigateAndClose('/explore')}
|
||||
className="flex items-center gap-2 w-full"
|
||||
>
|
||||
<Compass className="h-4 w-4" />
|
||||
{t('exploreApps')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setLabelsDialogOpen(true)}
|
||||
className="flex items-center gap-2 w-full"
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
import React, { useState } from 'react';
|
||||
import React, { useState, useRef, useEffect, memo } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { GitBranch, Loader2, EllipsisVertical, Edit } from 'lucide-react';
|
||||
import { GitBranch, Loader2, EllipsisVertical, Edit, Code, ExternalLink } from 'lucide-react';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import type { Repository } from '@/hooks/useUserRepositories';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
|
||||
@@ -23,13 +30,26 @@ import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { detectFork } from '@/lib/detectFork';
|
||||
import { NostrRepoEditDialog } from '@/components/NostrRepoEditDialog';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useOGImage } from '@/hooks/useOGImage';
|
||||
import { ZapDialog } from '@/components/ZapDialog';
|
||||
import { Zap } from 'lucide-react';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import type { NostrMetadata } from '@nostrify/nostrify';
|
||||
import { formatRelativeTime } from '@/lib/utils';
|
||||
|
||||
interface RepositoryCardProps {
|
||||
repo: Repository;
|
||||
/** Pre-fetched author metadata to avoid individual fetches */
|
||||
authorMetadata?: NostrMetadata;
|
||||
/** Callback when a tag is clicked - receives the tag value */
|
||||
onTagClick?: (tag: string) => void;
|
||||
}
|
||||
|
||||
export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
const { data: authorData } = useAuthor(repo.pubkey);
|
||||
function RepositoryCardInner({ repo, authorMetadata: preloadedMetadata, onTagClick }: RepositoryCardProps) {
|
||||
// Only fetch author data if not preloaded
|
||||
const { data: authorData } = useAuthor(preloadedMetadata ? undefined : repo.pubkey);
|
||||
const metadata = preloadedMetadata ?? authorData?.metadata;
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { settings: gitSettings } = useGitSettings();
|
||||
const navigate = useNavigate();
|
||||
@@ -39,10 +59,41 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const [isCloning, setIsCloning] = useState(false);
|
||||
const [editRepoOpen, setEditRepoOpen] = useState(false);
|
||||
const [imageError, setImageError] = useState(false);
|
||||
const [eventViewerOpen, setEventViewerOpen] = useState(false);
|
||||
const [isInViewport, setIsInViewport] = useState(false);
|
||||
const cardRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const displayName = authorData?.metadata?.name || genUserName(repo.pubkey);
|
||||
const profileImage = authorData?.metadata?.picture;
|
||||
// Lazy load OG images - only fetch when card is in viewport
|
||||
useEffect(() => {
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (entry.isIntersecting) {
|
||||
setIsInViewport(true);
|
||||
observer.disconnect();
|
||||
}
|
||||
},
|
||||
{ rootMargin: '100px' } // Start loading slightly before visible
|
||||
);
|
||||
|
||||
if (cardRef.current) {
|
||||
observer.observe(cardRef.current);
|
||||
}
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const displayName = metadata?.name || genUserName(repo.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
const isOwnRepo = user?.pubkey === repo.pubkey;
|
||||
const hasLightning = !!(metadata?.lud16 || metadata?.lud06);
|
||||
const canZap = user && !isOwnRepo && hasLightning;
|
||||
|
||||
// Get OG metadata from first web URL - only when in viewport
|
||||
const firstWebUrl = repo.webUrls?.[0];
|
||||
const { data: ogMetadata } = useOGImage(isInViewport ? firstWebUrl : undefined);
|
||||
const ogImageUrl = ogMetadata?.image ?? null;
|
||||
const ogDescription = ogMetadata?.description ?? null;
|
||||
|
||||
// Construct Nostr clone URL
|
||||
const nostrURI = new NostrURI({
|
||||
@@ -109,52 +160,117 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'user-repositories', user?.pubkey] });
|
||||
};
|
||||
|
||||
// Check if we have a valid OG image to show
|
||||
const hasValidImage = ogImageUrl && !imageError;
|
||||
|
||||
return (
|
||||
<Card className="h-full flex flex-col hover:shadow-lg transition-shadow">
|
||||
<Card ref={cardRef} className="h-full flex flex-col hover:shadow-lg transition-shadow">
|
||||
{/* Preview Image or Placeholder */}
|
||||
{hasValidImage && firstWebUrl ? (
|
||||
<a
|
||||
href={firstWebUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block aspect-video bg-muted overflow-hidden rounded-t-lg cursor-pointer hover:opacity-90 transition-opacity"
|
||||
>
|
||||
<img
|
||||
src={ogImageUrl}
|
||||
alt={`${repo.name} preview`}
|
||||
className="w-full h-full object-cover"
|
||||
onError={() => setImageError(true)}
|
||||
/>
|
||||
</a>
|
||||
) : (
|
||||
<div className="aspect-video bg-gradient-to-br from-primary to-accent rounded-t-lg flex items-center justify-center">
|
||||
<Code className="h-12 w-12 text-white" />
|
||||
</div>
|
||||
)}
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
{/* Header with name and menu */}
|
||||
<div className="mb-4 flex items-start justify-between">
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="font-semibold text-lg leading-tight mb-2 truncate">
|
||||
{repo.name}
|
||||
</h3>
|
||||
<div className="flex items-end gap-2 mb-2">
|
||||
<h3 className="font-semibold text-lg leading-tight truncate">
|
||||
{repo.name}
|
||||
</h3>
|
||||
<span className="text-sm text-muted-foreground shrink-0">
|
||||
{formatRelativeTime(repo.created_at)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{isOwnRepo && (
|
||||
<div className="flex items-center -mt-1 -mr-2 shrink-0">
|
||||
{canZap && (
|
||||
<ZapDialog target={repo as unknown as Event}>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8 text-amber-500 hover:text-amber-600 hover:bg-amber-500/10">
|
||||
<Zap className="h-4 w-4" />
|
||||
</Button>
|
||||
</ZapDialog>
|
||||
)}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8 -mt-1 -mr-2 shrink-0">
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<EllipsisVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setEditRepoOpen(true)} className="gap-2">
|
||||
<Edit className="h-4 w-4" />
|
||||
Edit Repository
|
||||
<DropdownMenuContent align="end">
|
||||
{firstWebUrl && (
|
||||
<DropdownMenuItem asChild className="gap-2">
|
||||
<a href={firstWebUrl} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
Open Website
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
)}
|
||||
<DropdownMenuItem onClick={() => setEventViewerOpen(true)} className="gap-2">
|
||||
<Code className="h-4 w-4" />
|
||||
View Event
|
||||
</DropdownMenuItem>
|
||||
{isOwnRepo && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => setEditRepoOpen(true)} className="gap-2">
|
||||
<Edit className="h-4 w-4" />
|
||||
Edit Repository
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Author */}
|
||||
<div className="mb-4">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Avatar className="h-4 w-4">
|
||||
<div className="flex items-center gap-3 text-sm">
|
||||
<Avatar className="h-10 w-10">
|
||||
{profileImage && (
|
||||
<AvatarImage src={profileImage} alt={displayName} />
|
||||
)}
|
||||
<AvatarFallback className="text-[8px]">
|
||||
<AvatarFallback className="text-xs">
|
||||
{displayName.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="truncate">{displayName}</span>
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onTagClick?.(displayName);
|
||||
}}
|
||||
className="truncate font-medium text-base text-foreground hover:text-primary hover:underline transition-colors text-left"
|
||||
>
|
||||
{displayName}
|
||||
</button>
|
||||
{metadata?.nip05 && (
|
||||
<span className="text-sm text-muted-foreground shrink-0">{metadata.nip05}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
{repo.description && (
|
||||
{(repo.description || ogDescription) && (
|
||||
<p className="text-sm text-muted-foreground line-clamp-2 mb-4">
|
||||
{repo.description}
|
||||
{repo.description || ogDescription}
|
||||
</p>
|
||||
)}
|
||||
|
||||
@@ -162,14 +278,21 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
{repo.repoTags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 mb-4">
|
||||
{repo.repoTags.slice(0, 3).map((tag, index) => (
|
||||
<Badge key={index} variant="secondary" className="text-xs">
|
||||
{tag}
|
||||
</Badge>
|
||||
<button
|
||||
key={index}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onTagClick?.(tag);
|
||||
}}
|
||||
className="text-sm text-primary hover:text-primary/80 hover:underline transition-colors font-medium"
|
||||
>
|
||||
#{tag}
|
||||
</button>
|
||||
))}
|
||||
{repo.repoTags.length > 3 && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
+{repo.repoTags.length - 3}
|
||||
</Badge>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -212,6 +335,31 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
repoIdentifier={repo.repoId}
|
||||
onSuccess={handleRepoEditSuccess}
|
||||
/>
|
||||
|
||||
{/* Event Viewer Dialog */}
|
||||
<Dialog open={eventViewerOpen} onOpenChange={setEventViewerOpen}>
|
||||
<DialogContent className="max-w-2xl max-h-[80vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Repository Event</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="overflow-y-auto flex-1 min-h-0">
|
||||
<pre className="text-xs p-4 rounded-lg overflow-x-auto">
|
||||
{JSON.stringify({
|
||||
id: repo.id,
|
||||
pubkey: repo.pubkey,
|
||||
created_at: repo.created_at,
|
||||
kind: repo.kind,
|
||||
tags: repo.tags,
|
||||
content: repo.content,
|
||||
sig: repo.sig,
|
||||
}, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Memoize to prevent re-renders when parent re-renders with same props
|
||||
export const RepositoryCard = memo(RepositoryCardInner);
|
||||
@@ -17,8 +17,6 @@ interface SettingsPageLayoutProps {
|
||||
children: ReactNode;
|
||||
/** Optional className for the content container */
|
||||
className?: string;
|
||||
/** Optional element to render next to the title */
|
||||
titleSuffix?: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -30,8 +28,7 @@ export function SettingsPageLayout({
|
||||
titleKey,
|
||||
descriptionKey,
|
||||
children,
|
||||
className = 'space-y-6',
|
||||
titleSuffix,
|
||||
className,
|
||||
}: SettingsPageLayoutProps) {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useIsMobile();
|
||||
@@ -51,10 +48,9 @@ export function SettingsPageLayout({
|
||||
{t('backToSettings')}
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex flex-wrap items-center gap-3">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Icon className="h-6 w-6 text-primary" />
|
||||
{t(titleKey)}
|
||||
{titleSuffix}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t(descriptionKey)}
|
||||
@@ -65,10 +61,9 @@ export function SettingsPageLayout({
|
||||
|
||||
{!isMobile && (
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex flex-wrap items-center gap-3">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Icon className="h-6 w-6 text-primary" />
|
||||
{t(titleKey)}
|
||||
{titleSuffix}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t(descriptionKey)}
|
||||
|
||||
@@ -251,7 +251,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
|
||||
useEffect(() => {
|
||||
if (target) {
|
||||
setComment('Zapped with MKStack!');
|
||||
setComment('Zapped from Shakespeare!');
|
||||
}
|
||||
}, [target]);
|
||||
|
||||
|
||||
@@ -13,6 +13,10 @@ import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
import { createRepositoryAnnouncementEvent } from '@/lib/announceRepository';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
@@ -110,6 +114,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { config } = useAppContext();
|
||||
const { nostr } = useNostr();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const { git } = useGit();
|
||||
|
||||
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
|
||||
const [isDeploying, setIsDeploying] = useState(false);
|
||||
@@ -323,6 +329,65 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
}
|
||||
|
||||
setDeployResult(result);
|
||||
|
||||
// Update repository announcement with deployment URL if using Nostr git
|
||||
try {
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const remoteUrl = await git.getRemoteURL(projectPath, 'origin');
|
||||
|
||||
if (remoteUrl && remoteUrl.startsWith('nostr://') && user) {
|
||||
const nostrURI = await NostrURI.parse(remoteUrl);
|
||||
|
||||
// Query for existing repository announcement
|
||||
const existingRepos = await nostr.query(
|
||||
[{ kinds: [30617], authors: [user.pubkey], '#d': [nostrURI.identifier], limit: 1 }],
|
||||
{ signal: AbortSignal.timeout(5000) }
|
||||
);
|
||||
|
||||
if (existingRepos.length > 0) {
|
||||
const existingEvent = existingRepos[0];
|
||||
|
||||
// Extract existing data from the event
|
||||
const description = existingEvent.tags.find(([tagName]) => tagName === 'description')?.[1];
|
||||
const webTag = existingEvent.tags.find(([tagName]) => tagName === 'web');
|
||||
const existingWebUrls = webTag ? webTag.slice(1) : [];
|
||||
const cloneTag = existingEvent.tags.find(([tagName]) => tagName === 'clone');
|
||||
const cloneUrls = cloneTag ? cloneTag.slice(1) : [];
|
||||
const relaysTag = existingEvent.tags.find(([tagName]) => tagName === 'relays');
|
||||
const relays = relaysTag ? relaysTag.slice(1) : [];
|
||||
const tTags = existingEvent.tags
|
||||
.filter(([tagName]) => tagName === 't')
|
||||
.map(([, value]) => value);
|
||||
const eucTag = existingEvent.tags.find(([tagName, , marker]) => tagName === 'r' && marker === 'euc');
|
||||
const earliestCommit = eucTag?.[1];
|
||||
const name = existingEvent.tags.find(([tagName]) => tagName === 'name')?.[1];
|
||||
|
||||
// Add deployment URL if not already present
|
||||
const deploymentUrl = result.url;
|
||||
const updatedWebUrls = existingWebUrls.includes(deploymentUrl)
|
||||
? existingWebUrls
|
||||
: [...existingWebUrls, deploymentUrl];
|
||||
|
||||
// Create updated repository announcement event
|
||||
const eventTemplate = createRepositoryAnnouncementEvent({
|
||||
repoId: nostrURI.identifier,
|
||||
name,
|
||||
description,
|
||||
webUrls: updatedWebUrls,
|
||||
cloneUrls,
|
||||
relays,
|
||||
tTags: tTags.length > 0 ? tTags : undefined,
|
||||
earliestCommit,
|
||||
});
|
||||
|
||||
// Publish the updated event
|
||||
await publishEvent(eventTemplate);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// Silently fail - updating web tag is not critical for deployment
|
||||
console.warn('Failed to update repository announcement with deployment URL:', err);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Deployment failed');
|
||||
} finally {
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useCurrentUser } from './useCurrentUser';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { BADGE_ISSUER_PUBKEY } from '@/pages/BadgesSettings';
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export function useFollowedRepositories(followedPubkeys: string[] = []) {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['nostr', 'followed-repositories', followedPubkeys.sort().join(',')],
|
||||
queryKey: ['nostr', 'followed-repositories', followedPubkeys],
|
||||
queryFn: async (): Promise<Repository[]> => {
|
||||
if (followedPubkeys.length === 0) {
|
||||
return [];
|
||||
@@ -50,10 +50,19 @@ export function useFollowedRepositories(followedPubkeys: string[] = []) {
|
||||
|
||||
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
|
||||
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
|
||||
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
|
||||
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
|
||||
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
|
||||
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
|
||||
|
||||
// Extract multi-value tags correctly (all values are in a single tag per NIP-34)
|
||||
const webTag = event.tags.find(tag => tag[0] === 'web');
|
||||
const webUrls = webTag ? webTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const cloneTag = event.tags.find(tag => tag[0] === 'clone');
|
||||
const cloneUrls = cloneTag ? cloneTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const relaysTag = event.tags.find(tag => tag[0] === 'relays');
|
||||
const relays = relaysTag ? relaysTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const maintainersTag = event.tags.find(tag => tag[0] === 'maintainers');
|
||||
const maintainers = maintainersTag ? maintainersTag.slice(1).filter(Boolean) : [];
|
||||
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
|
||||
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
|
||||
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useAppContext } from './useAppContext';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
|
||||
export interface OGMetadata {
|
||||
image: string | null;
|
||||
description: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to fetch Open Graph metadata from a web URL using CORS proxy
|
||||
* @param webUrl - The web URL to fetch OG metadata from
|
||||
* @returns Query result with OG image URL and description
|
||||
*/
|
||||
export function useOGImage(webUrl?: string) {
|
||||
const { config } = useAppContext();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['og-metadata', webUrl],
|
||||
queryFn: async (): Promise<OGMetadata> => {
|
||||
if (!webUrl) {
|
||||
return { image: null, description: null };
|
||||
}
|
||||
|
||||
try {
|
||||
// Use CORS proxy to fetch the HTML
|
||||
const proxiedUrl = proxyUrl(config.corsProxy, webUrl);
|
||||
const response = await fetch(proxiedUrl, {
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return { image: null, description: null };
|
||||
}
|
||||
|
||||
const html = await response.text();
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(html, 'text/html');
|
||||
|
||||
// Extract OG image
|
||||
let ogImage: string | null = null;
|
||||
const ogImageMeta = doc.querySelector('meta[property="og:image"]')?.getAttribute('content');
|
||||
if (ogImageMeta) {
|
||||
try {
|
||||
ogImage = new URL(ogImageMeta, webUrl).href;
|
||||
} catch {
|
||||
ogImage = ogImageMeta.startsWith('http') ? ogImageMeta : null;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to twitter:image if og:image not found
|
||||
if (!ogImage) {
|
||||
const twitterImage = doc.querySelector('meta[name="twitter:image"]')?.getAttribute('content');
|
||||
if (twitterImage) {
|
||||
try {
|
||||
ogImage = new URL(twitterImage, webUrl).href;
|
||||
} catch {
|
||||
ogImage = twitterImage.startsWith('http') ? twitterImage : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract OG description
|
||||
let ogDescription: string | null = null;
|
||||
const ogDescriptionMeta = doc.querySelector('meta[property="og:description"]')?.getAttribute('content');
|
||||
if (ogDescriptionMeta) {
|
||||
ogDescription = ogDescriptionMeta.trim();
|
||||
}
|
||||
|
||||
// Fallback to twitter:description if og:description not found
|
||||
if (!ogDescription) {
|
||||
const twitterDescription = doc.querySelector('meta[name="twitter:description"]')?.getAttribute('content');
|
||||
if (twitterDescription) {
|
||||
ogDescription = twitterDescription.trim();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
image: ogImage,
|
||||
description: ogDescription || null,
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn('Failed to fetch OG metadata:', error);
|
||||
return { image: null, description: null };
|
||||
}
|
||||
},
|
||||
enabled: !!webUrl,
|
||||
staleTime: 1000 * 60 * 60, // 1 hour
|
||||
retry: 1,
|
||||
});
|
||||
}
|
||||
@@ -55,10 +55,19 @@ export function useUserRepositories(userPubkey?: string) {
|
||||
try {
|
||||
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
|
||||
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
|
||||
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
|
||||
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
|
||||
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
|
||||
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
|
||||
|
||||
// Extract multi-value tags correctly (all values are in a single tag per NIP-34)
|
||||
const webTag = event.tags.find(tag => tag[0] === 'web');
|
||||
const webUrls = webTag ? webTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const cloneTag = event.tags.find(tag => tag[0] === 'clone');
|
||||
const cloneUrls = cloneTag ? cloneTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const relaysTag = event.tags.find(tag => tag[0] === 'relays');
|
||||
const relays = relaysTag ? relaysTag.slice(1).filter(Boolean) : [];
|
||||
|
||||
const maintainersTag = event.tags.find(tag => tag[0] === 'maintainers');
|
||||
const maintainers = maintainersTag ? maintainersTag.slice(1).filter(Boolean) : [];
|
||||
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
|
||||
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
|
||||
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
|
||||
|
||||
+41
-4
@@ -58,14 +58,51 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
||||
= openai.chat.completions.create.bind(openai.chat.completions);
|
||||
|
||||
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
|
||||
// OpenRouter usage accounting
|
||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
||||
if (provider.id === 'openrouter') {
|
||||
// OpenRouter-specific hacks
|
||||
if (provider.id === "openrouter" || provider.baseURL === "https://openrouter.ai/api/v1") {
|
||||
// Usage accounting field to get token usage and cost per request
|
||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
||||
(body as { usage?: { include?: boolean } }).usage = { include: true };
|
||||
|
||||
// Prompt caching for Claude models
|
||||
// https://openrouter.ai/docs/guides/best-practices/prompt-caching#anthropic-claude
|
||||
if (body.model.startsWith("anthropic/")) {
|
||||
// First normalize the message history to use content blocks
|
||||
body.messages = structuredClone(body.messages);
|
||||
body.messages = body.messages.map((m) => {
|
||||
if (m.role !== "function" && typeof m.content === "string") {
|
||||
return { ...m, content: [{ type: "text", text: m.content }] };
|
||||
} else {
|
||||
return m;
|
||||
}
|
||||
});
|
||||
|
||||
const systemMessage = body.messages.find((m) => m.role === "system");
|
||||
const nonSystemMessages = body.messages.filter((m) => m.role !== "system");
|
||||
const lastTwoMessages = nonSystemMessages.slice(-2);
|
||||
|
||||
if (systemMessage) {
|
||||
addCacheControl(systemMessage);
|
||||
}
|
||||
for (const msg of lastTwoMessages) {
|
||||
addCacheControl(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return createCompletion(body, options);
|
||||
}) as typeof createCompletion;
|
||||
|
||||
return openai;
|
||||
}
|
||||
}
|
||||
|
||||
/** Mutate msg to add an Anthropic `cache_control` property to its last text block */
|
||||
function addCacheControl(msg: OpenAI.Chat.Completions.ChatCompletionMessageParam) {
|
||||
if (Array.isArray(msg.content)) {
|
||||
const lastTextBlock = msg.content.findLast((b) => b.type === "text");
|
||||
if (lastTextBlock) {
|
||||
(lastTextBlock as { cache_control?: { type: "ephemeral" } })
|
||||
.cache_control = { type: "ephemeral" };
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -23,6 +23,14 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
||||
apiKeysURL: "https://openrouter.ai/settings/keys",
|
||||
tosURL: "https://openrouter.ai/terms",
|
||||
},
|
||||
{
|
||||
id: "opencode",
|
||||
name: "OpenCode Zen",
|
||||
baseURL: "https://opencode.ai/zen/v1",
|
||||
apiKeysURL: "https://opencode.ai/auth",
|
||||
tosURL: "https://opencode.ai/legal/terms-of-service",
|
||||
proxy: true,
|
||||
},
|
||||
{
|
||||
id: "ppq",
|
||||
name: "PayPerQ",
|
||||
|
||||
+2
-1
@@ -1107,7 +1107,8 @@ class GitHttp implements HttpClient {
|
||||
|
||||
constructor(proxy?: string, fetch?: typeof globalThis.fetch) {
|
||||
this.proxy = proxy;
|
||||
this.fetch = fetch ?? globalThis.fetch;
|
||||
// Bind fetch to globalThis to preserve context when called as this.fetch()
|
||||
this.fetch = fetch ?? globalThis.fetch.bind(globalThis);
|
||||
}
|
||||
|
||||
async request(request: GitHttpRequest): Promise<GitHttpResponse> {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket, Award } from 'lucide-react';
|
||||
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket, Wallet } from 'lucide-react';
|
||||
|
||||
export interface SettingsItem {
|
||||
id: string;
|
||||
@@ -29,12 +29,6 @@ export const getSettingsCategories = (t: (key: string) => string): SettingsCateg
|
||||
title: t('preferences'),
|
||||
href: '/settings/preferences',
|
||||
},
|
||||
{
|
||||
id: 'badges',
|
||||
icon: Award,
|
||||
title: t('badges'),
|
||||
href: '/settings/badges',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -65,6 +59,12 @@ export const getSettingsCategories = (t: (key: string) => string): SettingsCateg
|
||||
title: t('nostrSettings'),
|
||||
href: '/settings/nostr',
|
||||
},
|
||||
{
|
||||
id: 'wallet',
|
||||
icon: Wallet,
|
||||
title: t('walletSettings'),
|
||||
href: '/settings/wallet',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
+32
-7
@@ -106,12 +106,43 @@
|
||||
"deploySettingsDescription": "Configure deployment providers",
|
||||
"nostrSettings": "Nostr",
|
||||
"nostrSettingsDescription": "Configure relay connections and Nostr preferences",
|
||||
"walletSettings": "Wallet",
|
||||
"walletSettingsDescription": "Connect Lightning wallets for zaps",
|
||||
"currentStatus": "Current Status",
|
||||
"browserExtension": "Browser extension",
|
||||
"ready": "Ready",
|
||||
"notFound": "Not Found",
|
||||
"nostrWalletConnect": "Nostr Wallet Connect",
|
||||
"walletsConnected": "{{count}} wallet(s) connected",
|
||||
"remoteWalletConnection": "Remote wallet connection",
|
||||
"none": "None",
|
||||
"noWalletsConnected": "No wallets connected",
|
||||
"addNwcWalletToGetStarted": "Add an NWC wallet to get started",
|
||||
"lightningWallet": "Lightning Wallet",
|
||||
"nwcConnection": "NWC Connection",
|
||||
"setAsActive": "Set as active",
|
||||
"activeWalletChanged": "Active wallet changed",
|
||||
"selectedWalletNowActive": "The selected wallet is now active for zaps.",
|
||||
"installWeblnOrConnectNwc": "Install a WebLN extension or connect an NWC wallet to send zaps.",
|
||||
"connectNwcWallet": "Connect NWC Wallet",
|
||||
"enterConnectionStringFromWallet": "Enter your connection string from a compatible wallet.",
|
||||
"walletNameOptional": "Wallet Name (optional)",
|
||||
"myLightningWallet": "My Lightning Wallet",
|
||||
"connectionUri": "Connection URI",
|
||||
"connecting": "Connecting...",
|
||||
"connect": "Connect",
|
||||
"connectionUriRequired": "Connection URI required",
|
||||
"pleaseEnterValidNwcUri": "Please enter a valid NWC connection URI.",
|
||||
"storageSettings": "Storage",
|
||||
"storageSettingsDescription": "Export files and manage local data",
|
||||
"emailUpdates": "Email Updates",
|
||||
"emailUpdatesDescription": "Subscribe to Shakespeare updates and resources",
|
||||
"newProject": "New Project",
|
||||
"importRepository": "Import Repository",
|
||||
"explore": "Explore",
|
||||
"exploreApps": "Explore Apps",
|
||||
"exploreRepositories": "Explore repositories from the Nostr network",
|
||||
"pleaseLogInToExplore": "Please log in to explore repositories",
|
||||
"noProjectsYet": "No projects yet",
|
||||
"createFirstProject": "Create your first project to get started",
|
||||
"searchProjects": "Search projects...",
|
||||
@@ -561,11 +592,5 @@
|
||||
"failedToDuplicateProject": "Failed to duplicate project",
|
||||
"newProjectName": "New Project Name",
|
||||
"duplicateProjectDescription": "Create a copy of this project with a new name",
|
||||
"resume": "Resume",
|
||||
"badges": "Badges",
|
||||
"badgesDescription": "View and manage your earned badges and achievements",
|
||||
"noBadgesFound": "No badges found",
|
||||
"tokenProgress": "Tokens",
|
||||
"imageProgress": "Images",
|
||||
"nextBadgeAt": "Next badge at {{milestone}}"
|
||||
"resume": "Resume"
|
||||
}
|
||||
+32
-7
@@ -104,6 +104,33 @@
|
||||
"nostrSettingsDescription": "Saita haɗin relay da zaɓuɓɓukan Nostr",
|
||||
"storageSettings": "Ajiya",
|
||||
"storageSettingsDescription": "Fitar da fayiloli da sarrafa bayanan gida",
|
||||
"walletSettings": "Walat",
|
||||
"walletSettingsDescription": "Haɗa walat na Lightning don zaps",
|
||||
"currentStatus": "Matsayin Yanzu",
|
||||
"browserExtension": "Ƙari na bincike",
|
||||
"ready": "Shirye",
|
||||
"notFound": "Ba a Samu ba",
|
||||
"nostrWalletConnect": "Nostr Wallet Connect",
|
||||
"walletsConnected": "{{count}} walat da aka haɗa",
|
||||
"remoteWalletConnection": "Haɗin walat na nesa",
|
||||
"none": "Babu",
|
||||
"noWalletsConnected": "Babu walat da aka haɗa",
|
||||
"addNwcWalletToGetStarted": "Ƙara walat NWC don farawa",
|
||||
"lightningWallet": "Walat na Lightning",
|
||||
"nwcConnection": "Haɗin NWC",
|
||||
"setAsActive": "Saita a matsayin mai aiki",
|
||||
"activeWalletChanged": "Walat mai aiki ya canza",
|
||||
"selectedWalletNowActive": "Walat da aka zaɓa yanzu yana aiki don zaps.",
|
||||
"installWeblnOrConnectNwc": "Shigar da ƙarin WebLN ko haɗa walat NWC don aika zaps.",
|
||||
"connectNwcWallet": "Haɗa Walat NWC",
|
||||
"enterConnectionStringFromWallet": "Shigar da igiyar haɗin ku daga walat mai dacewa.",
|
||||
"walletNameOptional": "Sunan Walat (na zaɓi)",
|
||||
"myLightningWallet": "Walat na Lightning Na",
|
||||
"connectionUri": "URI Haɗi",
|
||||
"connecting": "Ana haɗawa...",
|
||||
"connect": "Haɗa",
|
||||
"connectionUriRequired": "URI haɗi yana buƙata",
|
||||
"pleaseEnterValidNwcUri": "Da fatan za a shigar da URI haɗin NWC mai inganci.",
|
||||
"emailUpdates": "Sabuntawar Imel",
|
||||
"emailUpdatesDescription": "Yi rajista don karbar sabuntawar Shakespeare da albarkatu",
|
||||
"newProject": "Sabon Aikin",
|
||||
@@ -140,6 +167,10 @@
|
||||
"unsavedChanges": "Canje-canjen da ba a ajiye ba",
|
||||
"saving": "Ana ajiyewa...",
|
||||
"languageLabel": "Harshe",
|
||||
"explore": "Bincika",
|
||||
"exploreApps": "Bincika Ayyuka",
|
||||
"exploreRepositories": "Bincika ma'ajiyar bayanai daga hanyar sadarwa ta Nostr",
|
||||
"pleaseLogInToExplore": "Da fatan za a shiga don bincika ma'ajiyar bayanai",
|
||||
"searchFiles": "Neman fayiloli...",
|
||||
"noFilesFound": "Babu fayilolin da aka samu",
|
||||
"noFilesFoundSearch": "Babu fayilolin da suka dace da bincikenku",
|
||||
@@ -477,11 +508,5 @@
|
||||
"failedToDuplicateProject": "An kasa kwafin aikin",
|
||||
"newProjectName": "Sunan Sabon Aikin",
|
||||
"duplicateProjectDescription": "Ƙirƙiri kwafin wannan aikin da sabon suna",
|
||||
"resume": "Ci gaba",
|
||||
"badges": "Tambari",
|
||||
"badgesDescription": "Duba da sarrafa tambarin da kuka samu da nasarorin",
|
||||
"noBadgesFound": "Ba a sami tambari ba",
|
||||
"tokenProgress": "Tokens",
|
||||
"imageProgress": "Hotuna",
|
||||
"nextBadgeAt": "Tambari na gaba a {{milestone}}"
|
||||
"resume": "Ci gaba"
|
||||
}
|
||||
+32
-7
@@ -104,6 +104,33 @@
|
||||
"nostrSettingsDescription": "Hazie njikọ relay na nhọrọ Nostr",
|
||||
"storageSettings": "Nchekwa",
|
||||
"storageSettingsDescription": "Bupụta faịlụ na jikwaa data mpaghara",
|
||||
"walletSettings": "Obere Akpa",
|
||||
"walletSettingsDescription": "Jikọọ obere akpa Lightning maka zaps",
|
||||
"currentStatus": "Ọnọdụ Ugbu A",
|
||||
"browserExtension": "Mgbatị ihe nchọgharị",
|
||||
"ready": "Njikere",
|
||||
"notFound": "Achọtaghị",
|
||||
"nostrWalletConnect": "Nostr Wallet Connect",
|
||||
"walletsConnected": "{{count}} obere akpa jikọrọ",
|
||||
"remoteWalletConnection": "Njikọ obere akpa dị anya",
|
||||
"none": "Ọ dịghị",
|
||||
"noWalletsConnected": "Enweghị obere akpa jikọrọ",
|
||||
"addNwcWalletToGetStarted": "Tinye obere akpa NWC iji malite",
|
||||
"lightningWallet": "Obere Akpa Lightning",
|
||||
"nwcConnection": "Njikọ NWC",
|
||||
"setAsActive": "Tọọ dị ka ọrụ",
|
||||
"activeWalletChanged": "Obere akpa na-arụ ọrụ agbanweela",
|
||||
"selectedWalletNowActive": "Obere akpa ahọpụtara na-arụ ọrụ ugbu a maka zaps.",
|
||||
"installWeblnOrConnectNwc": "Wụnye mgbatị WebLN ma ọ bụ jikọọ obere akpa NWC iji zipu zaps.",
|
||||
"connectNwcWallet": "Jikọọ Obere Akpa NWC",
|
||||
"enterConnectionStringFromWallet": "Tinye eriri njikọ gị site na obere akpa dakọtara.",
|
||||
"walletNameOptional": "Aha Obere Akpa (nhọrọ)",
|
||||
"myLightningWallet": "Obere Akpa Lightning M",
|
||||
"connectionUri": "URI Njikọ",
|
||||
"connecting": "Na-ejikọ...",
|
||||
"connect": "Jikọọ",
|
||||
"connectionUriRequired": "URI njikọ achọrọ",
|
||||
"pleaseEnterValidNwcUri": "Biko tinye URI njikọ NWC dị mma.",
|
||||
"emailUpdates": "Nmelite Email",
|
||||
"emailUpdatesDescription": "Debanye aha maka nmelite Shakespeare na akụrụngwa",
|
||||
"newProject": "Ọrụ Ọhụrụ",
|
||||
@@ -140,6 +167,10 @@
|
||||
"unsavedChanges": "Mgbanwe ndị na-echekwaghị",
|
||||
"saving": "Na-echekwa...",
|
||||
"languageLabel": "Asụsụ",
|
||||
"explore": "Chọpụta",
|
||||
"exploreApps": "Chọpụta Ngwa",
|
||||
"exploreRepositories": "Chọpụta ebe nchekwa sitere na netwọk Nostr",
|
||||
"pleaseLogInToExplore": "Biko banye iji chọpụta ebe nchekwa",
|
||||
"searchFiles": "Chọọ faịlụ...",
|
||||
"noFilesFound": "Ahụghị faịlụ ọ bụla",
|
||||
"noFilesFoundSearch": "Ahụghị faịlụ ọ bụla dabara na nchọgharị gị",
|
||||
@@ -474,11 +505,5 @@
|
||||
"failedToDuplicateProject": "Ọ dara ada imepụta ọrụ",
|
||||
"newProjectName": "Aha Ọrụ Ọhụrụ",
|
||||
"duplicateProjectDescription": "Mepụta oyiri nke ọrụ a na aha ọhụrụ",
|
||||
"resume": "Gaa n'ihu",
|
||||
"badges": "Baajị",
|
||||
"badgesDescription": "Lelee ma jikwaa baajị na mmeri gị",
|
||||
"noBadgesFound": "Achọtaghị baajị",
|
||||
"tokenProgress": "Tokens",
|
||||
"imageProgress": "Foto",
|
||||
"nextBadgeAt": "Baajị ọzọ na {{milestone}}"
|
||||
"resume": "Gaa n'ihu"
|
||||
}
|
||||
+32
-7
@@ -106,6 +106,33 @@
|
||||
"nostrSettingsDescription": "Configure conexões de relay e preferências do Nostr",
|
||||
"storageSettings": "Armazenamento",
|
||||
"storageSettingsDescription": "Exporte arquivos e gerencie dados locais",
|
||||
"walletSettings": "Carteira",
|
||||
"walletSettingsDescription": "Conecte carteiras Lightning para zaps",
|
||||
"currentStatus": "Status Atual",
|
||||
"browserExtension": "Extensão do navegador",
|
||||
"ready": "Pronto",
|
||||
"notFound": "Não Encontrado",
|
||||
"nostrWalletConnect": "Nostr Wallet Connect",
|
||||
"walletsConnected": "{{count}} carteira(s) conectada(s)",
|
||||
"remoteWalletConnection": "Conexão de carteira remota",
|
||||
"none": "Nenhum",
|
||||
"noWalletsConnected": "Nenhuma carteira conectada",
|
||||
"addNwcWalletToGetStarted": "Adicione uma carteira NWC para começar",
|
||||
"lightningWallet": "Carteira Lightning",
|
||||
"nwcConnection": "Conexão NWC",
|
||||
"setAsActive": "Definir como ativa",
|
||||
"activeWalletChanged": "Carteira ativa alterada",
|
||||
"selectedWalletNowActive": "A carteira selecionada está agora ativa para zaps.",
|
||||
"installWeblnOrConnectNwc": "Instale uma extensão WebLN ou conecte uma carteira NWC para enviar zaps.",
|
||||
"connectNwcWallet": "Conectar Carteira NWC",
|
||||
"enterConnectionStringFromWallet": "Digite sua string de conexão de uma carteira compatível.",
|
||||
"walletNameOptional": "Nome da Carteira (opcional)",
|
||||
"myLightningWallet": "Minha Carteira Lightning",
|
||||
"connectionUri": "URI de Conexão",
|
||||
"connecting": "Conectando...",
|
||||
"connect": "Conectar",
|
||||
"connectionUriRequired": "URI de conexão obrigatória",
|
||||
"pleaseEnterValidNwcUri": "Por favor, insira um URI de conexão NWC válido.",
|
||||
"emailUpdates": "Atualizações por Email",
|
||||
"emailUpdatesDescription": "Inscreva-se para receber atualizações e recursos do Shakespeare",
|
||||
"newProject": "Novo Projeto",
|
||||
@@ -142,6 +169,10 @@
|
||||
"unsavedChanges": "Alterações não salvas",
|
||||
"saving": "Salvando...",
|
||||
"languageLabel": "Linguagem",
|
||||
"explore": "Explorar",
|
||||
"exploreApps": "Explorar Aplicativos",
|
||||
"exploreRepositories": "Explorar repositórios da rede Nostr",
|
||||
"pleaseLogInToExplore": "Por favor, faça login para explorar repositórios",
|
||||
"searchFiles": "Buscar arquivos...",
|
||||
"noFilesFound": "Nenhum arquivo encontrado",
|
||||
"noFilesFoundSearch": "Nenhum arquivo encontrado correspondente à sua busca",
|
||||
@@ -486,11 +517,5 @@
|
||||
"failedToDuplicateProject": "Falha ao duplicar projeto",
|
||||
"newProjectName": "Nome do Novo Projeto",
|
||||
"duplicateProjectDescription": "Criar uma cópia deste projeto com um novo nome",
|
||||
"resume": "Retomar",
|
||||
"badges": "Distintivos",
|
||||
"badgesDescription": "Visualizar e gerenciar seus distintivos e conquistas",
|
||||
"noBadgesFound": "Nenhum distintivo encontrado",
|
||||
"tokenProgress": "Tokens",
|
||||
"imageProgress": "Imagens",
|
||||
"nextBadgeAt": "Próximo distintivo em {{milestone}}"
|
||||
"resume": "Retomar"
|
||||
}
|
||||
+32
-7
@@ -104,6 +104,33 @@
|
||||
"nostrSettingsDescription": "Tunto awọn asopọ relay ati awọn ayanfẹ Nostr",
|
||||
"storageSettings": "Ibi ipamọ",
|
||||
"storageSettingsDescription": "Gbe awọn faili jade ati ṣakoso data agbegbe",
|
||||
"walletSettings": "Apamọwọ",
|
||||
"walletSettingsDescription": "So awọn apamọwọ Lightning mọ fun zaps",
|
||||
"currentStatus": "Ipo Lọwọlọwọ",
|
||||
"browserExtension": "Afikun awoṣe",
|
||||
"ready": "Ṣetan",
|
||||
"notFound": "Ko Ri",
|
||||
"nostrWalletConnect": "Nostr Wallet Connect",
|
||||
"walletsConnected": "{{count}} apamọwọ ti a sopọ mọ",
|
||||
"remoteWalletConnection": "Asopọ apamọwọ latọna jijin",
|
||||
"none": "Ko si",
|
||||
"noWalletsConnected": "Ko si awọn apamọwọ ti a sopọ mọ",
|
||||
"addNwcWalletToGetStarted": "Fi apamọwọ NWC kun lati bẹrẹ",
|
||||
"lightningWallet": "Apamọwọ Lightning",
|
||||
"nwcConnection": "Asopọ NWC",
|
||||
"setAsActive": "Ṣeto bi ti nṣiṣẹ",
|
||||
"activeWalletChanged": "Apamọwọ ti nṣiṣẹ ti yipada",
|
||||
"selectedWalletNowActive": "Apamọwọ ti a yan ti nṣiṣẹ bayi fun zaps.",
|
||||
"installWeblnOrConnectNwc": "Fi afikun WebLN sori tabi sopọ apamọwọ NWC lati fi zaps ranṣẹ.",
|
||||
"connectNwcWallet": "Sopọ Apamọwọ NWC",
|
||||
"enterConnectionStringFromWallet": "Tẹ okun asopọ rẹ lati apamọwọ ti o baamu.",
|
||||
"walletNameOptional": "Orukọ Apamọwọ (aṣayan)",
|
||||
"myLightningWallet": "Apamọwọ Lightning Mi",
|
||||
"connectionUri": "URI Asopọ",
|
||||
"connecting": "N sopọ mọ...",
|
||||
"connect": "Sopọ mọ",
|
||||
"connectionUriRequired": "URI asopọ nilo",
|
||||
"pleaseEnterValidNwcUri": "Jọwọ tẹ URI asopọ NWC ti o tọ.",
|
||||
"emailUpdates": "Awọn Imudojuiwọn Imeeli",
|
||||
"emailUpdatesDescription": "Forukọsilẹ fun awọn imudojuiwọn Shakespeare ati awọn ohun elo",
|
||||
"newProject": "Iṣẹ akanṣe Tuntun",
|
||||
@@ -140,6 +167,10 @@
|
||||
"unsavedChanges": "Awọn iyipada ti a ko fi pamọ",
|
||||
"saving": "N fi pamọ...",
|
||||
"languageLabel": "Ede",
|
||||
"explore": "Ṣawari",
|
||||
"exploreApps": "Ṣawari Awọn Ohun Elo",
|
||||
"exploreRepositories": "Ṣawari awọn ibi ipamọ lati nẹtiwọki Nostr",
|
||||
"pleaseLogInToExplore": "Jọwọ wọle lati ṣawari awọn ibi ipamọ",
|
||||
"searchFiles": "Wa awọn faili...",
|
||||
"noFilesFound": "Ko si awọn faili ti a ri",
|
||||
"noFilesFoundSearch": "Ko si awọn faili ti o baamu wiwa rẹ",
|
||||
@@ -474,11 +505,5 @@
|
||||
"failedToDuplicateProject": "O kuna lati ṣe ẹda iṣẹ akanṣe",
|
||||
"newProjectName": "Orukọ Iṣẹ Akanṣe Tuntun",
|
||||
"duplicateProjectDescription": "Ṣẹda ẹda ti iṣẹ akanṣe yii pẹlu orukọ tuntun",
|
||||
"resume": "Tẹsiwaju",
|
||||
"badges": "Àmì-ẹ̀yẹ",
|
||||
"badgesDescription": "Wo ati ṣakoso àmì-ẹ̀yẹ àti àwọn àṣeyọrí rẹ",
|
||||
"noBadgesFound": "Ko ri àmì-ẹ̀yẹ",
|
||||
"tokenProgress": "Àwọn tókẹ̀n",
|
||||
"imageProgress": "Àwọn àwòrán",
|
||||
"nextBadgeAt": "Àmì-ẹ̀yẹ tó kàn ní {{milestone}}"
|
||||
"resume": "Tẹsiwaju"
|
||||
}
|
||||
+32
-7
@@ -106,6 +106,33 @@
|
||||
"nostrSettingsDescription": "配置中继连接和Nostr偏好",
|
||||
"storageSettings": "存储",
|
||||
"storageSettingsDescription": "导出文件和管理本地数据",
|
||||
"walletSettings": "钱包",
|
||||
"walletSettingsDescription": "连接闪电钱包以进行打赏",
|
||||
"currentStatus": "当前状态",
|
||||
"browserExtension": "浏览器扩展",
|
||||
"ready": "就绪",
|
||||
"notFound": "未找到",
|
||||
"nostrWalletConnect": "Nostr钱包连接",
|
||||
"walletsConnected": "已连接{{count}}个钱包",
|
||||
"remoteWalletConnection": "远程钱包连接",
|
||||
"none": "无",
|
||||
"noWalletsConnected": "未连接钱包",
|
||||
"addNwcWalletToGetStarted": "添加NWC钱包以开始使用",
|
||||
"lightningWallet": "闪电钱包",
|
||||
"nwcConnection": "NWC连接",
|
||||
"setAsActive": "设为活动",
|
||||
"activeWalletChanged": "活动钱包已更改",
|
||||
"selectedWalletNowActive": "所选钱包现在已激活用于打赏。",
|
||||
"installWeblnOrConnectNwc": "安装WebLN扩展或连接NWC钱包以发送打赏。",
|
||||
"connectNwcWallet": "连接NWC钱包",
|
||||
"enterConnectionStringFromWallet": "输入来自兼容钱包的连接字符串。",
|
||||
"walletNameOptional": "钱包名称(可选)",
|
||||
"myLightningWallet": "我的闪电钱包",
|
||||
"connectionUri": "连接URI",
|
||||
"connecting": "连接中...",
|
||||
"connect": "连接",
|
||||
"connectionUriRequired": "需要连接URI",
|
||||
"pleaseEnterValidNwcUri": "请输入有效的NWC连接URI。",
|
||||
"emailUpdates": "邮件更新",
|
||||
"emailUpdatesDescription": "订阅Shakespeare更新和资源",
|
||||
"newProject": "新项目",
|
||||
@@ -142,6 +169,10 @@
|
||||
"unsavedChanges": "未保存的更改",
|
||||
"saving": "保存中...",
|
||||
"languageLabel": "语言",
|
||||
"explore": "探索",
|
||||
"exploreApps": "探索应用",
|
||||
"exploreRepositories": "探索Nostr网络中的仓库",
|
||||
"pleaseLogInToExplore": "请登录以探索仓库",
|
||||
"searchFiles": "搜索文件...",
|
||||
"noFilesFound": "未找到文件",
|
||||
"noFilesFoundSearch": "未找到与您搜索匹配的文件",
|
||||
@@ -486,11 +517,5 @@
|
||||
"failedToDuplicateProject": "复制项目失败",
|
||||
"newProjectName": "新项目名称",
|
||||
"duplicateProjectDescription": "使用新名称创建此项目的副本",
|
||||
"resume": "继续",
|
||||
"badges": "徽章",
|
||||
"badgesDescription": "查看和管理您获得的徽章和成就",
|
||||
"noBadgesFound": "未找到徽章",
|
||||
"tokenProgress": "代币",
|
||||
"imageProgress": "图片",
|
||||
"nextBadgeAt": "下一个徽章需要 {{milestone}}"
|
||||
"resume": "继续"
|
||||
}
|
||||
@@ -1,535 +0,0 @@
|
||||
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";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { BadgeAwardModal } from '@/components/BadgeAwardModal';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useState, useMemo } from 'react';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
export const BADGE_ISSUER_NPUB = "npub1e0u5dfurw3dmd0n5lul873c5g3p89et6x372sa35spajcxjh4f6svcvahk";
|
||||
export const BADGE_ISSUER_PUBKEY = nip19.decode(BADGE_ISSUER_NPUB).data as string;
|
||||
|
||||
// Badge sync response from the server
|
||||
interface BadgeSyncResponse {
|
||||
object: 'badge_sync';
|
||||
synced: string[];
|
||||
stats: {
|
||||
generation_count: number;
|
||||
total_tokens: number;
|
||||
image_count: number;
|
||||
has_lightning_payment: boolean;
|
||||
giftcards_sent: number;
|
||||
max_giftcard_amount: number;
|
||||
};
|
||||
milestones?: {
|
||||
tokenMilestones: Array<{ threshold: number; type: 'generation' | 'tokens'; creditReward?: number }>;
|
||||
imageMilestones: Array<{ count: number; creditReward?: number }>;
|
||||
giftcardMilestones: Array<{ threshold: number; type: 'count' | 'amount'; creditReward?: number }>;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
function formatNumber(num: number): string {
|
||||
if (num >= 1_000_000_000) return `${(num / 1_000_000_000).toFixed(1)}B`;
|
||||
if (num >= 1_000_000) return `${(num / 1_000_000).toFixed(1)}M`;
|
||||
if (num >= 1_000) return `${(num / 1_000).toFixed(1)}K`;
|
||||
return num.toString();
|
||||
}
|
||||
|
||||
interface TokenMilestone {
|
||||
threshold: number;
|
||||
type: 'generation' | 'tokens';
|
||||
creditReward?: number;
|
||||
}
|
||||
|
||||
interface TokenProgressResult {
|
||||
progress: number;
|
||||
current: number;
|
||||
next: number;
|
||||
type: 'generation' | 'tokens';
|
||||
}
|
||||
|
||||
function getTokenMilestoneProgress(
|
||||
generationCount: number,
|
||||
totalTokens: number,
|
||||
milestones: TokenMilestone[]
|
||||
): TokenProgressResult | null {
|
||||
// Find the first uncompleted milestone
|
||||
for (let i = 0; i < milestones.length; i++) {
|
||||
const milestone = milestones[i];
|
||||
const currentValue = milestone.type === 'generation' ? generationCount : totalTokens;
|
||||
|
||||
if (currentValue < milestone.threshold) {
|
||||
// This is the next milestone to achieve
|
||||
const prevMilestone = i > 0 ? milestones[i - 1] : null;
|
||||
const prevThreshold = prevMilestone
|
||||
? (prevMilestone.type === milestone.type ? prevMilestone.threshold : 0)
|
||||
: 0;
|
||||
|
||||
const range = milestone.threshold - prevThreshold;
|
||||
const progressInRange = currentValue - prevThreshold;
|
||||
const progress = Math.min(100, Math.max(0, (progressInRange / range) * 100));
|
||||
|
||||
return {
|
||||
progress,
|
||||
current: currentValue,
|
||||
next: milestone.threshold,
|
||||
type: milestone.type,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// All milestones achieved
|
||||
return null;
|
||||
}
|
||||
|
||||
function getImageMilestoneProgress(
|
||||
imageCount: number,
|
||||
milestones: number[]
|
||||
): { progress: number; current: number; next: number } | null {
|
||||
// Find the first uncompleted milestone
|
||||
for (let i = 0; i < milestones.length; i++) {
|
||||
const milestone = milestones[i];
|
||||
|
||||
if (imageCount < milestone) {
|
||||
const prevThreshold = i > 0 ? milestones[i - 1] : 0;
|
||||
const range = milestone - prevThreshold;
|
||||
const progressInRange = imageCount - prevThreshold;
|
||||
const progress = Math.min(100, Math.max(0, (progressInRange / range) * 100));
|
||||
|
||||
return { progress, current: imageCount, next: milestone };
|
||||
}
|
||||
}
|
||||
|
||||
// All milestones achieved
|
||||
return null;
|
||||
}
|
||||
|
||||
function isCreditMilestone(milestone: number | null, creditMilestones: number[]): boolean {
|
||||
return milestone !== null && creditMilestones.includes(milestone);
|
||||
}
|
||||
|
||||
function BadgeCard({
|
||||
event,
|
||||
awarded,
|
||||
unlockDate,
|
||||
onClick
|
||||
}: {
|
||||
event: NostrEvent;
|
||||
awarded: boolean;
|
||||
unlockDate?: number | null;
|
||||
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];
|
||||
const imageTag = event.tags.find(([t]) => t === "image")?.[1];
|
||||
const thumbTags = event.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);
|
||||
|
||||
const formattedDate = unlockDate
|
||||
? new Date(unlockDate * 1000).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric'
|
||||
})
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Card
|
||||
className={cn(
|
||||
"transition-all bg-transparent border-none shadow-none h-full",
|
||||
awarded ? "cursor-pointer hover:scale-105" : ""
|
||||
)}
|
||||
onClick={awarded ? onClick : undefined}
|
||||
>
|
||||
<CardHeader className="text-center p-0 h-full flex flex-col">
|
||||
<div className="flex justify-center">
|
||||
{imageUrl ? (
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt={badgeName}
|
||||
className={cn(
|
||||
"w-32 h-32 rounded-lg object-cover",
|
||||
awarded ? "" : "opacity-50 grayscale blur-md"
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex flex-col flex-1 mt-4">
|
||||
{/* Title area - fixed height for 2 lines */}
|
||||
<div className="min-h-[3.5rem] flex items-start justify-center">
|
||||
{awarded ? (
|
||||
<CardTitle className="text-lg leading-tight line-clamp-2">
|
||||
{badgeName}
|
||||
</CardTitle>
|
||||
) : (
|
||||
<Lock className="h-5 w-5 text-muted-foreground mt-1" />
|
||||
)}
|
||||
</div>
|
||||
{/* Description area - fixed height for 2 lines */}
|
||||
{description && (
|
||||
<p className={cn(
|
||||
"text-sm min-h-[2.5rem] line-clamp-2 mt-1",
|
||||
awarded ? "text-muted-foreground" : "text-muted-foreground/70"
|
||||
)}>
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
{/* Unlock date - pushed to bottom */}
|
||||
<div className="mt-auto pt-2">
|
||||
{awarded && formattedDate && (
|
||||
<p className="text-xs text-muted-foreground/70">
|
||||
Unlocked {formattedDate}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function BadgesSettings() {
|
||||
const { t } = useTranslation();
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
const { settings } = useAISettings();
|
||||
const { config } = useAppContext();
|
||||
const queryClient = useQueryClient();
|
||||
const userPubkey = user?.pubkey;
|
||||
const [selectedBadge, setSelectedBadge] = useState<NostrEvent | null>(null);
|
||||
const [progressIndex, setProgressIndex] = useState(0);
|
||||
|
||||
// Find a Shakespeare provider (one with nostr auth) for badge sync
|
||||
const shakespeareProvider = useMemo(
|
||||
() => settings.providers.find(p => p.nostr),
|
||||
[settings.providers]
|
||||
);
|
||||
|
||||
// Badge sync query - calls the server to sync badges and get stats
|
||||
const { data: syncData } = useQuery({
|
||||
queryKey: ['badge-sync', userPubkey, shakespeareProvider?.id],
|
||||
queryFn: async (): Promise<BadgeSyncResponse> => {
|
||||
if (!shakespeareProvider || !user) {
|
||||
throw new Error('No provider or user available');
|
||||
}
|
||||
const ai = createAIClient(shakespeareProvider, user, config.corsProxy);
|
||||
const response = await ai.post('/badges/sync', {}) as BadgeSyncResponse;
|
||||
|
||||
// If any badges were synced, invalidate the badge awards query
|
||||
if (response.synced.length > 0) {
|
||||
queryClient.invalidateQueries({ queryKey: ['badge-awards', BADGE_ISSUER_PUBKEY, userPubkey] });
|
||||
}
|
||||
|
||||
return response;
|
||||
},
|
||||
enabled: !!user && !!shakespeareProvider,
|
||||
staleTime: 0, // Always refetch on mount for fresh progress
|
||||
gcTime: 5 * 60 * 1000, // Keep in cache for 5 min
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
// Get stats from sync response
|
||||
const stats = syncData?.stats;
|
||||
|
||||
// Get milestones from server (no fallbacks - if server doesn't provide, use empty arrays)
|
||||
const tokenMilestones = useMemo((): TokenMilestone[] => {
|
||||
return syncData?.milestones?.tokenMilestones || [];
|
||||
}, [syncData?.milestones]);
|
||||
|
||||
const imageMilestones = useMemo(() => {
|
||||
return syncData?.milestones?.imageMilestones.map(m => m.count) || [];
|
||||
}, [syncData?.milestones]);
|
||||
|
||||
// Get credit milestones (thresholds with credit rewards)
|
||||
const creditMilestones = useMemo(() => {
|
||||
return syncData?.milestones?.tokenMilestones
|
||||
.filter(m => m.creditReward !== undefined)
|
||||
.map(m => m.threshold) || [];
|
||||
}, [syncData?.milestones]);
|
||||
|
||||
const tokenProgress = stats
|
||||
? getTokenMilestoneProgress(stats.generation_count, stats.total_tokens, tokenMilestones)
|
||||
: null;
|
||||
const imageProgress = stats
|
||||
? getImageMilestoneProgress(stats.image_count, imageMilestones)
|
||||
: null;
|
||||
|
||||
const { data: badgeDefinitions, isLoading: isLoadingDefinitions } = useQuery({
|
||||
queryKey: ['badge-definitions', BADGE_ISSUER_PUBKEY],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
|
||||
const events = await nostr.query([{
|
||||
kinds: [30009],
|
||||
authors: [BADGE_ISSUER_PUBKEY],
|
||||
limit: 100,
|
||||
}], { signal });
|
||||
return events;
|
||||
},
|
||||
});
|
||||
|
||||
// Query for badge awards if user is logged in
|
||||
const { data: badgeAwards, isLoading: isLoadingAwards } = useQuery({
|
||||
queryKey: ['badge-awards', BADGE_ISSUER_PUBKEY, userPubkey],
|
||||
queryFn: async (c) => {
|
||||
if (!userPubkey) return [];
|
||||
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
|
||||
const events = await nostr.query([{
|
||||
kinds: [8],
|
||||
authors: [BADGE_ISSUER_PUBKEY],
|
||||
"#p": [userPubkey],
|
||||
limit: 100,
|
||||
}], { signal });
|
||||
return events;
|
||||
},
|
||||
enabled: !!userPubkey,
|
||||
});
|
||||
|
||||
// Create a map of awarded badges (a-tag -> first award date)
|
||||
const awardedBadges = new Map<string, number>();
|
||||
if (badgeAwards) {
|
||||
for (const award of badgeAwards) {
|
||||
const aTag = award.tags.find(([t]) => t === "a")?.[1];
|
||||
if (aTag) {
|
||||
// Store the earliest award date for this badge
|
||||
const existingDate = awardedBadges.get(aTag);
|
||||
if (!existingDate || award.created_at < existingDate) {
|
||||
awardedBadges.set(aTag, award.created_at);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to check if a badge is awarded
|
||||
const isBadgeAwarded = (badgeDefinition: NostrEvent): boolean => {
|
||||
if (!userPubkey) return false;
|
||||
const dTag = badgeDefinition.tags.find(([t]) => t === "d")?.[1];
|
||||
if (!dTag) return false;
|
||||
const aTag = `30009:${BADGE_ISSUER_PUBKEY}:${dTag}`;
|
||||
return awardedBadges.has(aTag);
|
||||
};
|
||||
|
||||
// Helper to get first award date for a badge
|
||||
const getFirstAwardDate = (badgeDefinition: NostrEvent): number | null => {
|
||||
if (!userPubkey) return null;
|
||||
const dTag = badgeDefinition.tags.find(([t]) => t === "d")?.[1];
|
||||
if (!dTag) return null;
|
||||
const aTag = `30009:${BADGE_ISSUER_PUBKEY}:${dTag}`;
|
||||
return awardedBadges.get(aTag) || null;
|
||||
};
|
||||
|
||||
// Sort badges: unlocked by first award date (earliest first), then locked badges
|
||||
const sortedBadgeDefinitions = badgeDefinitions ? [...badgeDefinitions].sort((a, b) => {
|
||||
const aAwarded = isBadgeAwarded(a);
|
||||
const bAwarded = isBadgeAwarded(b);
|
||||
|
||||
// If both are awarded, sort by first award date (earliest first)
|
||||
if (aAwarded && bAwarded) {
|
||||
const aDate = getFirstAwardDate(a) || 0;
|
||||
const bDate = getFirstAwardDate(b) || 0;
|
||||
return aDate - bDate;
|
||||
}
|
||||
|
||||
// If only one is awarded, awarded comes first
|
||||
if (aAwarded && !bAwarded) return -1;
|
||||
if (!aAwarded && bAwarded) return 1;
|
||||
|
||||
// Both are locked, maintain original order
|
||||
return 0;
|
||||
}) : [];
|
||||
|
||||
const isLoading = isLoadingDefinitions || (userPubkey && isLoadingAwards);
|
||||
|
||||
// Calculate badge counts
|
||||
const totalBadges = sortedBadgeDefinitions.length;
|
||||
const unlockedBadges = sortedBadgeDefinitions.filter(badge => isBadgeAwarded(badge)).length;
|
||||
const progressPercentage = totalBadges > 0 ? (unlockedBadges / totalBadges) * 100 : 0;
|
||||
|
||||
return (
|
||||
<SettingsPageLayout
|
||||
icon={Award}
|
||||
titleKey="badges"
|
||||
descriptionKey="badgesDescription"
|
||||
titleSuffix={
|
||||
!isLoading && totalBadges > 0 ? (
|
||||
<div className="flex flex-wrap items-center gap-3 ml-3">
|
||||
<Card className="bg-muted/50 border">
|
||||
<CardContent className="py-1.5 px-4">
|
||||
<p className="text-sm font-medium">
|
||||
<span className="text-foreground">{unlockedBadges}</span>
|
||||
<span className="text-muted-foreground"> / </span>
|
||||
<span className="text-foreground">{totalBadges}</span>
|
||||
<span className="text-muted-foreground"> unlocked</span>
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card className="bg-muted/50 border">
|
||||
<CardContent className="py-1.5 px-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Progress value={progressPercentage} className="h-1.5 w-24" />
|
||||
<span className="text-sm font-medium">{Math.round(progressPercentage)}%</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<BadgeAwardModal
|
||||
badgeDefinition={selectedBadge}
|
||||
onClose={() => setSelectedBadge(null)}
|
||||
/>
|
||||
|
||||
{/* Progress Tracking Section */}
|
||||
{stats && (() => {
|
||||
type ProgressItem =
|
||||
| { category: 'token'; progress: TokenProgressResult }
|
||||
| { category: 'image'; progress: { progress: number; current: number; next: number } };
|
||||
|
||||
const progressItems: ProgressItem[] = [];
|
||||
if (tokenProgress) {
|
||||
progressItems.push({ category: 'token', progress: tokenProgress });
|
||||
}
|
||||
if (imageProgress) {
|
||||
progressItems.push({ category: 'image', progress: imageProgress });
|
||||
}
|
||||
|
||||
if (progressItems.length === 0) return null;
|
||||
|
||||
const currentIndex = progressIndex % progressItems.length;
|
||||
const current = progressItems[currentIndex];
|
||||
|
||||
// Format progress display based on milestone type
|
||||
const formatProgress = () => {
|
||||
if (current.category === 'token') {
|
||||
const tokenProg = current.progress as TokenProgressResult;
|
||||
const next = tokenProg.next ?? 0;
|
||||
// For generation-based milestones, show simple numbers
|
||||
if (tokenProg.type === 'generation') {
|
||||
return `${tokenProg.current} / ${next}`;
|
||||
}
|
||||
// For token-based milestones, format large numbers
|
||||
return `${formatNumber(tokenProg.current)} / ${formatNumber(next)}`;
|
||||
}
|
||||
// Image progress - simple numbers
|
||||
return `${current.progress.current} / ${current.progress.next}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<Card
|
||||
className="mb-6 cursor-pointer hover:bg-muted/50 transition-colors"
|
||||
onClick={() => setProgressIndex(prev => prev + 1)}
|
||||
>
|
||||
<CardContent className="py-4">
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm font-medium">
|
||||
{current.category === 'token' ? t('tokenProgress') : t('imageProgress')}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{formatProgress()}
|
||||
</span>
|
||||
{current.category === 'token' && current.progress.next && isCreditMilestone(current.progress.next, creditMilestones) && (() => {
|
||||
const milestone = syncData?.milestones?.tokenMilestones.find(m => m.threshold === current.progress.next);
|
||||
const creditAmount = milestone?.creditReward ?? 0;
|
||||
// Only show badge if credit amount is greater than 0
|
||||
if (creditAmount <= 0) return null;
|
||||
return (
|
||||
<Badge variant="default" className="text-xs">
|
||||
${creditAmount} Credit
|
||||
</Badge>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
</div>
|
||||
<Progress value={current.progress.progress} className="h-2" />
|
||||
<div className="flex justify-between items-center">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('nextBadgeAt', { milestone: formatNumber(current.progress.next ?? 0) })}
|
||||
</p>
|
||||
{progressItems.length > 1 && (
|
||||
<div className="flex gap-1">
|
||||
{progressItems.map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={cn(
|
||||
"w-1.5 h-1.5 rounded-full transition-colors",
|
||||
i === currentIndex ? "bg-primary" : "bg-muted-foreground/30"
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})()}
|
||||
|
||||
<div className="space-y-4">
|
||||
{isLoading ? (
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<Card key={i}>
|
||||
<CardHeader className="text-center space-y-4">
|
||||
<div className="flex justify-center">
|
||||
<Skeleton className="w-32 h-32 rounded-lg" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-5 w-32 mx-auto" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4 mx-auto" />
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : sortedBadgeDefinitions && sortedBadgeDefinitions.length > 0 ? (
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{sortedBadgeDefinitions.map((event) => (
|
||||
<BadgeCard
|
||||
key={event.id}
|
||||
event={event}
|
||||
awarded={isBadgeAwarded(event)}
|
||||
unlockDate={getFirstAwardDate(event)}
|
||||
onClick={isBadgeAwarded(event) ? () => setSelectedBadge(event) : undefined}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<Award className="h-12 w-12 mx-auto text-muted-foreground" />
|
||||
<p className="text-muted-foreground">
|
||||
{t('noBadgesFound')}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</SettingsPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export default BadgesSettings;
|
||||
|
||||
+75
-359
@@ -1,32 +1,19 @@
|
||||
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { GitBranch, Loader2, AlertCircle, FileArchive, MoreHorizontal, Search } from 'lucide-react';
|
||||
import { GitBranch, Loader2, AlertCircle, FileArchive, MoreHorizontal } from 'lucide-react';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { ZipImportDialog } from '@/components/ZipImportDialog';
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useUserRepositories } from '@/hooks/useUserRepositories';
|
||||
import { useContacts } from '@/hooks/useContacts';
|
||||
import { useFollowedRepositories } from '@/hooks/useFollowedRepositories';
|
||||
import { RepositoryCard } from '@/components/RepositoryCard';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
|
||||
import type { Repository } from '@/hooks/useUserRepositories';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { NSchema as n } from '@nostrify/nostrify';
|
||||
import type { NostrMetadata } from '@nostrify/nostrify';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { detectFork } from '@/lib/detectFork';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
|
||||
export default function Clone() {
|
||||
const { t } = useTranslation();
|
||||
@@ -41,46 +28,6 @@ export default function Clone() {
|
||||
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
|
||||
const { user } = useCurrentUser();
|
||||
const { settings: gitSettings } = useGitSettings();
|
||||
const { data: repositories = [], isLoading: isLoadingRepos } = useUserRepositories(user?.pubkey);
|
||||
const { data: contacts = [] } = useContacts(user?.pubkey);
|
||||
const { data: followedRepositories = [], isLoading: isLoadingFollowedRepos } = useFollowedRepositories(contacts);
|
||||
const [activeTab, setActiveTab] = useState<'my-projects' | 'follows'>('my-projects');
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
|
||||
// Get unique pubkeys from all repositories
|
||||
const allRepos = useMemo(() => [...repositories, ...followedRepositories], [repositories, followedRepositories]);
|
||||
const uniquePubkeys = useMemo(() => {
|
||||
const pubkeys = new Set<string>();
|
||||
allRepos.forEach(repo => pubkeys.add(repo.pubkey));
|
||||
return Array.from(pubkeys);
|
||||
}, [allRepos]);
|
||||
|
||||
// Fetch author metadata for all unique pubkeys
|
||||
const { nostr } = useNostr();
|
||||
const { data: authorMetadataMap = new Map<string, NostrMetadata>() } = useQuery({
|
||||
queryKey: ['repository-authors', uniquePubkeys.sort().join(',')],
|
||||
queryFn: async () => {
|
||||
if (uniquePubkeys.length === 0) return new Map<string, NostrMetadata>();
|
||||
|
||||
const events = await nostr.query(
|
||||
[{ kinds: [0], authors: uniquePubkeys, limit: uniquePubkeys.length }],
|
||||
{ signal: AbortSignal.timeout(3000) }
|
||||
);
|
||||
|
||||
const metadataMap = new Map<string, NostrMetadata>();
|
||||
for (const event of events) {
|
||||
try {
|
||||
const metadata = n.json().pipe(n.metadata()).parse(event.content);
|
||||
metadataMap.set(event.pubkey, metadata);
|
||||
} catch {
|
||||
// If parsing fails, continue without metadata for this pubkey
|
||||
}
|
||||
}
|
||||
return metadataMap;
|
||||
},
|
||||
enabled: uniquePubkeys.length > 0,
|
||||
staleTime: 60000, // 1 minute
|
||||
});
|
||||
|
||||
useSeoMeta({
|
||||
title: `${t('importRepository')} - Shakespeare`,
|
||||
@@ -256,140 +203,83 @@ export default function Clone() {
|
||||
}
|
||||
};
|
||||
|
||||
// Filter repositories based on search query
|
||||
const filterRepositories = useCallback((repos: Repository[], query: string): Repository[] => {
|
||||
if (!query.trim()) {
|
||||
return repos;
|
||||
}
|
||||
|
||||
const lowerQuery = query.toLowerCase();
|
||||
|
||||
return repos.filter((repo) => {
|
||||
// Filter by repository name
|
||||
if (repo.name.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by description
|
||||
if (repo.description?.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by tags (hashtags)
|
||||
if (repo.repoTags.some(tag => tag.toLowerCase().includes(lowerQuery))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by hex pubkey
|
||||
if (repo.pubkey.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by npub (bech32 encoded pubkey)
|
||||
try {
|
||||
const npub = nip19.npubEncode(repo.pubkey);
|
||||
if (npub.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
// If encoding fails, skip npub search
|
||||
}
|
||||
|
||||
// Filter by author name
|
||||
const authorMetadata = authorMetadataMap.get(repo.pubkey);
|
||||
if (authorMetadata?.name?.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
}, [authorMetadataMap]);
|
||||
|
||||
// Filtered repositories for "My Projects" tab
|
||||
const filteredMyRepositories = useMemo(() => {
|
||||
return filterRepositories(repositories, searchQuery);
|
||||
}, [repositories, searchQuery, filterRepositories]);
|
||||
|
||||
// Filtered repositories for "Follows" tab
|
||||
const filteredFollowedRepositories = useMemo(() => {
|
||||
return filterRepositories(followedRepositories, searchQuery);
|
||||
}, [followedRepositories, searchQuery, filterRepositories]);
|
||||
|
||||
return (
|
||||
<AppLayout title={t('importRepository')}>
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<div className="text-center mb-8">
|
||||
<div className="text-4xl mb-4">
|
||||
<GitBranch className="h-12 w-12 mx-auto text-primary" />
|
||||
</div>
|
||||
<h1 className="text-3xl font-bold mb-3 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{t('importRepository')}
|
||||
</h1>
|
||||
<p className="text-lg text-muted-foreground">
|
||||
{t('cloneGitRepository')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
id="repo-url"
|
||||
type="text"
|
||||
placeholder="https://github.com/username/repository.git"
|
||||
value={repoUrl}
|
||||
onChange={(e) => {
|
||||
setRepoUrl(e.target.value);
|
||||
setError(null); // Clear error when user types
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={isCloning}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 p-3 bg-destructive/10 border border-destructive/20 rounded-md">
|
||||
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0" />
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
<div className="min-h-[calc(100vh-12rem)] flex items-center justify-center">
|
||||
<div className="max-w-2xl mx-auto w-full">
|
||||
<div className="text-center mb-8">
|
||||
<div className="text-4xl mb-4">
|
||||
<GitBranch className="h-12 w-12 mx-auto text-primary" />
|
||||
</div>
|
||||
)}
|
||||
<h1 className="text-3xl font-bold mb-3 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{t('importRepository')}
|
||||
</h1>
|
||||
<p className="text-lg text-muted-foreground">
|
||||
{t('cloneGitRepository')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={() => handleClone()}
|
||||
disabled={!repoUrl.trim() || isCloning}
|
||||
className="w-full focus-ring bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg"
|
||||
size="lg"
|
||||
>
|
||||
{isCloning ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{t('cloningRepository')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GitBranch className="mr-2 h-4 w-4" />
|
||||
{t('importRepository')}
|
||||
</>
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
id="repo-url"
|
||||
type="text"
|
||||
placeholder="https://github.com/username/repository.git"
|
||||
value={repoUrl}
|
||||
onChange={(e) => {
|
||||
setRepoUrl(e.target.value);
|
||||
setError(null); // Clear error when user types
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={isCloning}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 p-3 bg-destructive/10 border border-destructive/20 rounded-md">
|
||||
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0" />
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Import ZIP File Link */}
|
||||
<div className="mt-8 text-center">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="text-muted-foreground hover:text-primary hover:bg-transparent">
|
||||
<MoreHorizontal className="h-5 w-5" />
|
||||
<span className="sr-only">More options</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="center">
|
||||
<DropdownMenuItem
|
||||
className="flex items-center gap-2 w-full"
|
||||
onClick={() => setIsZipDialogOpen(true)}
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
Import ZIP File
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button
|
||||
onClick={() => handleClone()}
|
||||
disabled={!repoUrl.trim() || isCloning}
|
||||
className="w-full focus-ring bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80 shadow-lg"
|
||||
size="lg"
|
||||
>
|
||||
{isCloning ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{t('cloningRepository')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GitBranch className="mr-2 h-4 w-4" />
|
||||
{t('importRepository')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Import ZIP File Link */}
|
||||
<div className="mt-8 text-center">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="text-muted-foreground hover:text-primary hover:bg-transparent">
|
||||
<MoreHorizontal className="h-5 w-5" />
|
||||
<span className="sr-only">More options</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="center">
|
||||
<DropdownMenuItem
|
||||
className="flex items-center gap-2 w-full"
|
||||
onClick={() => setIsZipDialogOpen(true)}
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
Import ZIP File
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -399,180 +289,6 @@ export default function Clone() {
|
||||
open={isZipDialogOpen}
|
||||
onOpenChange={setIsZipDialogOpen}
|
||||
/>
|
||||
|
||||
{/* NIP-34 Repositories with Tabs */}
|
||||
{user && (
|
||||
<div className="mt-16 max-w-7xl mx-auto">
|
||||
<Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'my-projects' | 'follows')}>
|
||||
<div className="flex items-center gap-4 mb-6 flex-wrap">
|
||||
<TabsList>
|
||||
<TabsTrigger value="my-projects">
|
||||
My Projects
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="follows">
|
||||
Follows
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* Search Input */}
|
||||
{(repositories.length > 0 || followedRepositories.length > 0) && (
|
||||
<div className="relative flex-1 min-w-[200px] max-w-md">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Search repositories..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-9 h-10 text-sm"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<TabsContent value="my-projects">
|
||||
{isLoadingRepos ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<Card key={i} className="h-full flex flex-col">
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
<div className="flex items-start gap-3 mb-4">
|
||||
<Skeleton className="w-12 h-12 rounded-lg" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-5 w-32" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2 mb-4">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
<div className="flex gap-1 mb-4">
|
||||
<Skeleton className="h-5 w-16" />
|
||||
<Skeleton className="h-5 w-20" />
|
||||
</div>
|
||||
<div className="mt-auto flex gap-2">
|
||||
<Skeleton className="h-9 flex-1" />
|
||||
<Skeleton className="h-9 w-9" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : filteredMyRepositories.length > 0 ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{filteredMyRepositories.map((repo) => (
|
||||
<RepositoryCard key={repo.id} repo={repo} />
|
||||
))}
|
||||
</div>
|
||||
) : searchQuery.trim() ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<Search className="h-8 w-8 mx-auto mb-2 opacity-50 text-muted-foreground" />
|
||||
<p className="text-muted-foreground">
|
||||
No repositories found matching "{searchQuery}".
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setSearchQuery('')}
|
||||
>
|
||||
Clear search
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
No repositories found. Publish your first repository to Nostr to see it here.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="follows">
|
||||
{isLoadingFollowedRepos ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Card key={i} className="h-full flex flex-col">
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
<div className="flex items-start gap-3 mb-4">
|
||||
<Skeleton className="w-12 h-12 rounded-lg" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-5 w-32" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2 mb-4">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
<div className="flex gap-1 mb-4">
|
||||
<Skeleton className="h-5 w-16" />
|
||||
<Skeleton className="h-5 w-20" />
|
||||
</div>
|
||||
<div className="mt-auto flex gap-2">
|
||||
<Skeleton className="h-9 flex-1" />
|
||||
<Skeleton className="h-9 w-9" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : filteredFollowedRepositories.length > 0 ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{filteredFollowedRepositories.map((repo) => (
|
||||
<RepositoryCard key={repo.id} repo={repo} />
|
||||
))}
|
||||
</div>
|
||||
) : searchQuery.trim() ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<Search className="h-8 w-8 mx-auto mb-2 opacity-50 text-muted-foreground" />
|
||||
<p className="text-muted-foreground">
|
||||
No repositories found matching "{searchQuery}".
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setSearchQuery('')}
|
||||
>
|
||||
Clear search
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : contacts.length > 0 ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
None of the people you follow have published repositories yet.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
You're not following anyone yet. Follow people on Nostr to see their repositories here.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)}
|
||||
</AppLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
import { useState, useMemo, useDeferredValue } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Search, Compass } from 'lucide-react';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useUserRepositories } from '@/hooks/useUserRepositories';
|
||||
import { useContacts } from '@/hooks/useContacts';
|
||||
import { useFollowedRepositories } from '@/hooks/useFollowedRepositories';
|
||||
import { RepositoryCard } from '@/components/RepositoryCard';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { Repository } from '@/hooks/useUserRepositories';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { NSchema as n } from '@nostrify/nostrify';
|
||||
import type { NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
|
||||
export default function Explore() {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useCurrentUser();
|
||||
const { data: repositories = [], isLoading: isLoadingRepos } = useUserRepositories(user?.pubkey);
|
||||
const { data: contacts = [] } = useContacts(user?.pubkey);
|
||||
const { data: followedRepositories = [], isLoading: isLoadingFollowedRepos } = useFollowedRepositories(contacts);
|
||||
const [activeTab, setActiveTab] = useState<'my-projects' | 'follows'>('follows');
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
|
||||
// Defer search query to prevent blocking UI on every keystroke
|
||||
const deferredSearchQuery = useDeferredValue(searchQuery);
|
||||
|
||||
// Get unique pubkeys from all repositories
|
||||
const allRepos = useMemo(() => [...repositories, ...followedRepositories], [repositories, followedRepositories]);
|
||||
const uniquePubkeys = useMemo(() => {
|
||||
const pubkeys = new Set<string>();
|
||||
allRepos.forEach(repo => pubkeys.add(repo.pubkey));
|
||||
return Array.from(pubkeys);
|
||||
}, [allRepos]);
|
||||
|
||||
// Pre-compute npubs once to avoid expensive encoding on every search
|
||||
const npubMap = useMemo(() => {
|
||||
const map = new Map<string, string>();
|
||||
allRepos.forEach(repo => {
|
||||
if (!map.has(repo.pubkey)) {
|
||||
try {
|
||||
map.set(repo.pubkey, nip19.npubEncode(repo.pubkey));
|
||||
} catch {
|
||||
// ignore encoding failures
|
||||
}
|
||||
}
|
||||
});
|
||||
return map;
|
||||
}, [allRepos]);
|
||||
|
||||
// Fetch author metadata for all unique pubkeys
|
||||
const { nostr } = useNostr();
|
||||
const { data: authorMetadataMap = new Map<string, NostrMetadata>() } = useQuery({
|
||||
queryKey: ['repository-authors', uniquePubkeys],
|
||||
queryFn: async () => {
|
||||
if (uniquePubkeys.length === 0) return new Map<string, NostrMetadata>();
|
||||
|
||||
const events = await nostr.query(
|
||||
[{ kinds: [0], authors: uniquePubkeys, limit: uniquePubkeys.length }],
|
||||
{ signal: AbortSignal.timeout(3000) }
|
||||
);
|
||||
|
||||
const metadataMap = new Map<string, NostrMetadata>();
|
||||
for (const event of events) {
|
||||
try {
|
||||
const metadata = n.json().pipe(n.metadata()).parse(event.content);
|
||||
metadataMap.set(event.pubkey, metadata);
|
||||
} catch {
|
||||
// If parsing fails, continue without metadata for this pubkey
|
||||
}
|
||||
}
|
||||
return metadataMap;
|
||||
},
|
||||
enabled: uniquePubkeys.length > 0,
|
||||
staleTime: 60000, // 1 minute
|
||||
});
|
||||
|
||||
useSeoMeta({
|
||||
title: `${t('explore')} - Shakespeare`,
|
||||
description: t('exploreRepositories'),
|
||||
});
|
||||
|
||||
// Filter repositories based on search query - stable function with no dependencies
|
||||
const filterRepositories = (
|
||||
repos: Repository[],
|
||||
query: string,
|
||||
metadata: Map<string, NostrMetadata>,
|
||||
npubs: Map<string, string>
|
||||
): Repository[] => {
|
||||
if (!query.trim()) {
|
||||
return repos;
|
||||
}
|
||||
|
||||
const lowerQuery = query.toLowerCase();
|
||||
|
||||
return repos.filter((repo) => {
|
||||
// Filter by repository name
|
||||
if (repo.name.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by description
|
||||
if (repo.description?.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by tags (hashtags)
|
||||
if (repo.repoTags.some(tag => tag.toLowerCase().includes(lowerQuery))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by hex pubkey
|
||||
if (repo.pubkey.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by npub (pre-computed)
|
||||
const npub = npubs.get(repo.pubkey);
|
||||
if (npub?.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Filter by author name
|
||||
const authorMetadata = metadata.get(repo.pubkey);
|
||||
if (authorMetadata?.name?.toLowerCase().includes(lowerQuery)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
};
|
||||
|
||||
// Filtered repositories for "My Projects" tab - uses deferred query
|
||||
const filteredMyRepositories = useMemo(() => {
|
||||
return filterRepositories(repositories, deferredSearchQuery, authorMetadataMap, npubMap);
|
||||
}, [repositories, deferredSearchQuery, authorMetadataMap, npubMap]);
|
||||
|
||||
// Filtered repositories for "Follows" tab - uses deferred query
|
||||
const filteredFollowedRepositories = useMemo(() => {
|
||||
return filterRepositories(followedRepositories, deferredSearchQuery, authorMetadataMap, npubMap);
|
||||
}, [followedRepositories, deferredSearchQuery, authorMetadataMap, npubMap]);
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<AppLayout title={t('exploreApps')}>
|
||||
<div className="max-w-2xl mx-auto text-center py-12">
|
||||
<p className="text-lg text-muted-foreground">
|
||||
{t('pleaseLogInToExplore')}
|
||||
</p>
|
||||
</div>
|
||||
</AppLayout>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AppLayout title={t('exploreApps')}>
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<div className="mb-8">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<Compass className="h-8 w-8 text-primary flex-shrink-0" />
|
||||
<h1 className="text-3xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{t('exploreApps')}
|
||||
</h1>
|
||||
</div>
|
||||
<p className="text-lg text-muted-foreground">
|
||||
{t('exploreRepositories')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'my-projects' | 'follows')}>
|
||||
<div className="flex items-center gap-4 mb-6 flex-wrap">
|
||||
<TabsList>
|
||||
<TabsTrigger value="my-projects">
|
||||
My Projects
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="follows">
|
||||
Follows
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* Search Input */}
|
||||
{(repositories.length > 0 || followedRepositories.length > 0) && (
|
||||
<div className="relative flex-1 min-w-[200px] max-w-md">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Search repositories..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-9 h-10 text-sm"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<TabsContent value="my-projects">
|
||||
{isLoadingRepos ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<Card key={i} className="h-full flex flex-col">
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
<div className="flex items-start gap-3 mb-4">
|
||||
<Skeleton className="w-12 h-12 rounded-lg" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-5 w-32" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2 mb-4">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
<div className="flex gap-1 mb-4">
|
||||
<Skeleton className="h-5 w-16" />
|
||||
<Skeleton className="h-5 w-20" />
|
||||
</div>
|
||||
<div className="mt-auto flex gap-2">
|
||||
<Skeleton className="h-9 flex-1" />
|
||||
<Skeleton className="h-9 w-9" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : filteredMyRepositories.length > 0 ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{filteredMyRepositories.map((repo) => (
|
||||
<RepositoryCard
|
||||
key={repo.id}
|
||||
repo={repo}
|
||||
authorMetadata={authorMetadataMap.get(repo.pubkey)}
|
||||
onTagClick={(tag) => setSearchQuery(tag)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : searchQuery.trim() ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<Search className="h-8 w-8 mx-auto mb-2 opacity-50 text-muted-foreground" />
|
||||
<p className="text-muted-foreground">
|
||||
No repositories found matching "{searchQuery}".
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setSearchQuery('')}
|
||||
>
|
||||
Clear search
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
No repositories found. Publish your first repository to Nostr to see it here.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="follows">
|
||||
{isLoadingFollowedRepos ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Card key={i} className="h-full flex flex-col">
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
<div className="flex items-start gap-3 mb-4">
|
||||
<Skeleton className="w-12 h-12 rounded-lg" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-5 w-32" />
|
||||
<Skeleton className="h-4 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2 mb-4">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
<div className="flex gap-1 mb-4">
|
||||
<Skeleton className="h-5 w-16" />
|
||||
<Skeleton className="h-5 w-20" />
|
||||
</div>
|
||||
<div className="mt-auto flex gap-2">
|
||||
<Skeleton className="h-9 flex-1" />
|
||||
<Skeleton className="h-9 w-9" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : filteredFollowedRepositories.length > 0 ? (
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{filteredFollowedRepositories.map((repo) => (
|
||||
<RepositoryCard
|
||||
key={repo.id}
|
||||
repo={repo}
|
||||
authorMetadata={authorMetadataMap.get(repo.pubkey)}
|
||||
onTagClick={(tag) => setSearchQuery(tag)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : searchQuery.trim() ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<Search className="h-8 w-8 mx-auto mb-2 opacity-50 text-muted-foreground" />
|
||||
<p className="text-muted-foreground">
|
||||
No repositories found matching "{searchQuery}".
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setSearchQuery('')}
|
||||
>
|
||||
Clear search
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : contacts.length > 0 ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
None of the people you follow have published repositories yet.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
You're not following anyone yet. Follow people on Nostr to see their repositories here.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</AppLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { SettingsPageLayout } from '@/components/SettingsPageLayout';
|
||||
|
||||
export function WalletSettings() {
|
||||
const { t } = useTranslation();
|
||||
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
||||
const [connectionUri, setConnectionUri] = useState('');
|
||||
const [alias, setAlias] = useState('');
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
const { toast } = useToast();
|
||||
|
||||
const {
|
||||
connections,
|
||||
activeConnection,
|
||||
connectionInfo,
|
||||
addConnection,
|
||||
removeConnection,
|
||||
setActiveConnection
|
||||
} = useNWC();
|
||||
|
||||
const { webln } = useWallet();
|
||||
|
||||
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
|
||||
|
||||
const handleAddConnection = async () => {
|
||||
if (!connectionUri.trim()) {
|
||||
toast({
|
||||
title: t('connectionUriRequired'),
|
||||
description: t('pleaseEnterValidNwcUri'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsConnecting(true);
|
||||
try {
|
||||
const success = await addConnection(connectionUri.trim(), alias.trim() || undefined);
|
||||
if (success) {
|
||||
setConnectionUri('');
|
||||
setAlias('');
|
||||
setAddDialogOpen(false);
|
||||
}
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveConnection = (connectionString: string) => {
|
||||
removeConnection(connectionString);
|
||||
};
|
||||
|
||||
const handleSetActive = (connectionString: string) => {
|
||||
setActiveConnection(connectionString);
|
||||
toast({
|
||||
title: t('activeWalletChanged'),
|
||||
description: t('selectedWalletNowActive'),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsPageLayout
|
||||
icon={Wallet}
|
||||
titleKey="walletSettings"
|
||||
descriptionKey="walletSettingsDescription"
|
||||
>
|
||||
{/* Current Status */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="font-medium">{t('currentStatus')}</h3>
|
||||
<div className="grid gap-3">
|
||||
{/* WebLN */}
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<Globe className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">WebLN</p>
|
||||
<p className="text-xs text-muted-foreground">{t('browserExtension')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{webln && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={webln ? "default" : "secondary"} className="text-xs">
|
||||
{webln ? t('ready') : t('notFound')}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
{/* NWC */}
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">{t('nostrWalletConnect')}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{connections.length > 0
|
||||
? t('walletsConnected', { count: connections.length })
|
||||
: t('remoteWalletConnection')
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{hasNWC && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={hasNWC ? "default" : "secondary"} className="text-xs">
|
||||
{hasNWC ? t('ready') : t('none')}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* NWC Management */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-medium">{t('nostrWalletConnect')}</h3>
|
||||
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
{t('add')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Connected Wallets List */}
|
||||
{connections.length === 0 ? (
|
||||
<div className="text-center py-6 text-muted-foreground border border-dashed rounded-lg">
|
||||
<WalletMinimal className="h-8 w-8 mx-auto mb-2 opacity-50" />
|
||||
<p className="text-sm">{t('noWalletsConnected')}</p>
|
||||
<p className="text-xs mt-1">{t('addNwcWalletToGetStarted')}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{connections.map((connection) => {
|
||||
const info = connectionInfo[connection.connectionString];
|
||||
const isActive = activeConnection === connection.connectionString;
|
||||
return (
|
||||
<div
|
||||
key={connection.connectionString}
|
||||
className={`flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
{connection.alias || info?.alias || t('lightningWallet')}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('nwcConnection')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{isActive && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
{!isActive && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleSetActive(connection.connectionString)}
|
||||
title={t('setAsActive')}
|
||||
>
|
||||
<Zap className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleRemoveConnection(connection.connectionString)}
|
||||
title={t('remove')}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Help */}
|
||||
{!webln && connections.length === 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="text-center py-4 space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('installWeblnOrConnectNwc')}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Add Wallet Dialog */}
|
||||
<Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('connectNwcWallet')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t('enterConnectionStringFromWallet')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div>
|
||||
<Label htmlFor="alias">{t('walletNameOptional')}</Label>
|
||||
<Input
|
||||
id="alias"
|
||||
placeholder={t('myLightningWallet')}
|
||||
value={alias}
|
||||
onChange={(e) => setAlias(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="connection-uri">{t('connectionUri')}</Label>
|
||||
<Textarea
|
||||
id="connection-uri"
|
||||
placeholder="nostr+walletconnect://..."
|
||||
value={connectionUri}
|
||||
onChange={(e) => setConnectionUri(e.target.value)}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
onClick={handleAddConnection}
|
||||
disabled={isConnecting || !connectionUri.trim()}
|
||||
className="w-full"
|
||||
>
|
||||
{isConnecting ? t('connecting') : t('connect')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</SettingsPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export default WalletSettings;
|
||||
+1
-1
@@ -29,7 +29,7 @@ export default defineConfig(() => ({
|
||||
plugins: [
|
||||
react(),
|
||||
VitePWA({
|
||||
includeAssets: ['shakespeare.svg', 'shakespeare-192x192.png', 'shakespeare-512x512.png', 'sine.mp3', 'badgeAwarded.mp3'],
|
||||
includeAssets: ['shakespeare.svg', 'shakespeare-192x192.png', 'shakespeare-512x512.png', 'sine.mp3'],
|
||||
manifest: false, // Use existing manifest.webmanifest from public folder
|
||||
workbox: {
|
||||
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2,wasm,mp3}'],
|
||||
|
||||
Reference in new issue
Block a user