mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-03 16:13:34 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
346cea5f89 | ||
|
|
3d97870b59 |
No files matched your search
@@ -1,337 +0,0 @@
|
|||||||
---
|
|
||||||
name: ai-chat
|
|
||||||
description: Build AI-powered chat interfaces, implement streaming responses, or integrate with Shakespeare AI.
|
|
||||||
---
|
|
||||||
|
|
||||||
# AI Integration with Shakespeare API
|
|
||||||
|
|
||||||
Use the `useShakespeare` hook for AI chat completions with Nostr authentication. The API dynamically provides available models, so you should query them at runtime rather than hardcoding model names.
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { useShakespeare, type ChatMessage, type Model } from '@/hooks/useShakespeare';
|
|
||||||
|
|
||||||
const {
|
|
||||||
sendChatMessage,
|
|
||||||
sendStreamingMessage,
|
|
||||||
getAvailableModels,
|
|
||||||
isLoading,
|
|
||||||
error,
|
|
||||||
isAuthenticated
|
|
||||||
} = useShakespeare();
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Model Selector Component
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
function ModelSelector({ onModelSelect }: { onModelSelect: (modelId: string) => void }) {
|
|
||||||
const { getAvailableModels, isLoading } = useShakespeare();
|
|
||||||
const [models, setModels] = useState<Model[]>([]);
|
|
||||||
const [selectedModel, setSelectedModel] = useState<string>('');
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const fetchModels = async () => {
|
|
||||||
try {
|
|
||||||
const response = await getAvailableModels();
|
|
||||||
// Sort models by total cost (cheapest first)
|
|
||||||
const sortedModels = response.data.sort((a, b) => {
|
|
||||||
const costA = parseFloat(a.pricing.prompt) + parseFloat(a.pricing.completion);
|
|
||||||
const costB = parseFloat(b.pricing.prompt) + parseFloat(b.pricing.completion);
|
|
||||||
return costA - costB;
|
|
||||||
});
|
|
||||||
setModels(sortedModels);
|
|
||||||
|
|
||||||
// Select the cheapest model by default
|
|
||||||
if (sortedModels.length > 0) {
|
|
||||||
const cheapestModel = sortedModels[0];
|
|
||||||
setSelectedModel(cheapestModel.id);
|
|
||||||
onModelSelect(cheapestModel.id);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Failed to fetch models:', err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
fetchModels();
|
|
||||||
}, [getAvailableModels, onModelSelect]);
|
|
||||||
|
|
||||||
const handleModelChange = (modelId: string) => {
|
|
||||||
setSelectedModel(modelId);
|
|
||||||
onModelSelect(modelId);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<label htmlFor="model-select">Choose Model:</label>
|
|
||||||
<select
|
|
||||||
id="model-select"
|
|
||||||
value={selectedModel}
|
|
||||||
onChange={(e) => handleModelChange(e.target.value)}
|
|
||||||
disabled={isLoading}
|
|
||||||
>
|
|
||||||
<option value="">Select a model...</option>
|
|
||||||
{models.map((model, index) => {
|
|
||||||
const totalCost = parseFloat(model.pricing.prompt) + parseFloat(model.pricing.completion);
|
|
||||||
const isCheapest = index === 0;
|
|
||||||
return (
|
|
||||||
<option key={model.id} value={model.id}>
|
|
||||||
{model.name} - {isCheapest ? "Cheapest" : `$${totalCost.toFixed(6)}/token`}
|
|
||||||
</option>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Basic Chat Example
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
function AIChat() {
|
|
||||||
const { sendChatMessage, isLoading, error, isAuthenticated } = useShakespeare();
|
|
||||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
|
||||||
const [input, setInput] = useState('');
|
|
||||||
const [selectedModel, setSelectedModel] = useState<string>('');
|
|
||||||
|
|
||||||
const handleSend = async () => {
|
|
||||||
if (!input.trim() || !selectedModel) return;
|
|
||||||
|
|
||||||
const newMessages = [...messages, { role: 'user', content: input }];
|
|
||||||
setMessages(newMessages);
|
|
||||||
setInput('');
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await sendChatMessage(newMessages, selectedModel);
|
|
||||||
setMessages(prev => [...prev, {
|
|
||||||
role: 'assistant',
|
|
||||||
content: response.choices[0].message.content as string
|
|
||||||
}]);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Chat error:', err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!isAuthenticated) return <div>Please log in to use AI</div>;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="max-w-2xl mx-auto p-4">
|
|
||||||
{error && <div className="text-red-500 mb-4">{error}</div>}
|
|
||||||
|
|
||||||
{/* Model Selection */}
|
|
||||||
<div className="mb-4">
|
|
||||||
<ModelSelector onModelSelect={setSelectedModel} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2 mb-4">
|
|
||||||
{messages.map((msg, i) => (
|
|
||||||
<div key={i} className={`p-2 rounded ${msg.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'}`}>
|
|
||||||
<strong>{msg.role}:</strong> {msg.content}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<input
|
|
||||||
value={input}
|
|
||||||
onChange={(e) => setInput(e.target.value)}
|
|
||||||
onKeyPress={(e) => e.key === 'Enter' && handleSend()}
|
|
||||||
className="flex-1 p-2 border rounded"
|
|
||||||
disabled={isLoading || !selectedModel}
|
|
||||||
placeholder={!selectedModel ? "Select a model first..." : "Type your message..."}
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
onClick={handleSend}
|
|
||||||
disabled={isLoading || !selectedModel}
|
|
||||||
className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
|
|
||||||
>
|
|
||||||
Send
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Streaming Chat Example
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
function StreamingChat() {
|
|
||||||
const { sendStreamingMessage } = useShakespeare();
|
|
||||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
|
||||||
const [currentResponse, setCurrentResponse] = useState('');
|
|
||||||
const [selectedModel, setSelectedModel] = useState<string>('');
|
|
||||||
|
|
||||||
const handleStreaming = async (content: string) => {
|
|
||||||
if (!selectedModel) return;
|
|
||||||
|
|
||||||
setCurrentResponse('');
|
|
||||||
const newMessages = [...messages, { role: 'user', content }];
|
|
||||||
setMessages(newMessages);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await sendStreamingMessage(newMessages, selectedModel, (chunk) => {
|
|
||||||
setCurrentResponse(prev => prev + chunk);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add the complete response to messages
|
|
||||||
if (currentResponse.trim()) {
|
|
||||||
setMessages(prev => [...prev, {
|
|
||||||
role: 'assistant',
|
|
||||||
content: currentResponse
|
|
||||||
}]);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Streaming error:', err);
|
|
||||||
} finally {
|
|
||||||
setCurrentResponse('');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
{/* Model selection UI */}
|
|
||||||
<div className="mb-4">
|
|
||||||
<ModelSelector onModelSelect={setSelectedModel} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Chat interface */}
|
|
||||||
{/* ... rest of your chat UI */}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Model Information
|
|
||||||
|
|
||||||
Models are dynamically fetched from the Shakespeare API and include:
|
|
||||||
|
|
||||||
- **Model ID**: Unique identifier for the model
|
|
||||||
- **Name**: Human-readable model name
|
|
||||||
- **Description**: Model capabilities and use cases
|
|
||||||
- **Context Window**: Maximum token limit for conversations
|
|
||||||
- **Pricing**: Cost per token for prompt and completion
|
|
||||||
- **Free Models**: Models with `pricing.prompt === "0"` and `pricing.completion === "0"`
|
|
||||||
|
|
||||||
#### Key Points
|
|
||||||
|
|
||||||
- **Dynamic Model Discovery**: Always fetch available models using `getAvailableModels()`
|
|
||||||
- **Authentication Required**: User must be logged in with Nostr account
|
|
||||||
- **Free vs Premium**: Check pricing to determine if model requires credits
|
|
||||||
- **Error Handling**: Handle `isLoading` and `error` states appropriately
|
|
||||||
- **Model Selection**: Provide UI for users to choose between available models
|
|
||||||
|
|
||||||
## Implementation Patterns and Best Practices
|
|
||||||
|
|
||||||
### Dialog Component Patterns
|
|
||||||
|
|
||||||
When using Dialog components, always ensure accessibility compliance by including required elements:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
|
|
||||||
|
|
||||||
// ✅ Correct - Always include DialogHeader with DialogTitle
|
|
||||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
|
||||||
<DialogContent>
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Dialog Title</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Optional description for screen readers
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
{/* Dialog content */}
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
```
|
|
||||||
|
|
||||||
**Important**: Even if you want to hide the title visually, use the `VisuallyHidden` component to maintain accessibility:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
|
|
||||||
|
|
||||||
<DialogHeader>
|
|
||||||
<VisuallyHidden>
|
|
||||||
<DialogTitle>Hidden Title for Screen Readers</DialogTitle>
|
|
||||||
</VisuallyHidden>
|
|
||||||
</DialogHeader>
|
|
||||||
```
|
|
||||||
|
|
||||||
### Streaming Response Handling
|
|
||||||
|
|
||||||
When implementing streaming chat interfaces, always accumulate streamed content in a local variable before clearing the streaming state to prevent content loss:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
const handleStreamingResponse = async () => {
|
|
||||||
let streamedContent = ''; // ✅ Use local variable to accumulate content
|
|
||||||
|
|
||||||
try {
|
|
||||||
await sendStreamingMessage(messages, model, (chunk) => {
|
|
||||||
streamedContent += chunk; // ✅ Accumulate in local variable
|
|
||||||
setCurrentStreamingMessage(streamedContent); // Update UI
|
|
||||||
});
|
|
||||||
|
|
||||||
// ✅ Save accumulated content to persistent state
|
|
||||||
if (streamedContent.trim()) {
|
|
||||||
const assistantMessage: MessageDisplay = {
|
|
||||||
id: Date.now().toString(),
|
|
||||||
role: 'assistant',
|
|
||||||
content: streamedContent, // ✅ Use accumulated content
|
|
||||||
timestamp: new Date()
|
|
||||||
};
|
|
||||||
setMessages(prev => [...prev, assistantMessage]);
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
setCurrentStreamingMessage(''); // ✅ Clear streaming state after saving
|
|
||||||
}
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
### Error Boundary Patterns
|
|
||||||
|
|
||||||
Always wrap AI components with error boundaries and provide user-friendly error messages for common failure scenarios:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { ErrorBoundary } from '@/components/ErrorBoundary';
|
|
||||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
|
||||||
|
|
||||||
function AIChatWithErrorBoundary() {
|
|
||||||
return (
|
|
||||||
<ErrorBoundary
|
|
||||||
fallback={
|
|
||||||
<div className="p-4">
|
|
||||||
<Alert variant="destructive">
|
|
||||||
<AlertCircle className="h-4 w-4" />
|
|
||||||
<AlertDescription>
|
|
||||||
Something went wrong with the AI chat. Please refresh the page and try again.
|
|
||||||
</AlertDescription>
|
|
||||||
</Alert>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<AIChat />
|
|
||||||
</ErrorBoundary>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// In your AI component, handle specific error types gracefully:
|
|
||||||
function useAIWithErrorHandling() {
|
|
||||||
const { sendChatMessage, error, clearError } = useShakespeare();
|
|
||||||
|
|
||||||
const sendMessage = async (messages: ChatMessage[], modelId: string) => {
|
|
||||||
try {
|
|
||||||
await sendChatMessage(messages, modelId);
|
|
||||||
} catch (err) {
|
|
||||||
// Handle specific error types with user-friendly messages
|
|
||||||
if (err.message.includes('401')) {
|
|
||||||
throw new Error('Authentication failed. Please log in again.');
|
|
||||||
} else if (err.message.includes('402')) {
|
|
||||||
throw new Error('Insufficient credits. Please add credits to use premium features.');
|
|
||||||
} else if (err.message.includes('network')) {
|
|
||||||
throw new Error('Network error. Please check your internet connection.');
|
|
||||||
}
|
|
||||||
throw err; // Re-throw for error boundary
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return { sendMessage, error, clearError };
|
|
||||||
}
|
|
||||||
```
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
---
|
|
||||||
name: nostr-comments
|
|
||||||
description: Implement Nostr comment systems, add discussion features to posts/articles, or build community interaction features.
|
|
||||||
---
|
|
||||||
|
|
||||||
# Adding Nostr Comments Sections
|
|
||||||
|
|
||||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
|
||||||
|
|
||||||
## Basic Usage
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
|
||||||
|
|
||||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
|
||||||
return (
|
|
||||||
<div className="space-y-6">
|
|
||||||
{/* Your article content */}
|
|
||||||
<div>{/* article content */}</div>
|
|
||||||
|
|
||||||
{/* Comments section */}
|
|
||||||
<CommentsSection root={article} />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Props and Customization
|
|
||||||
|
|
||||||
The `CommentsSection` component accepts the following props:
|
|
||||||
|
|
||||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
|
||||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
|
||||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
|
||||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
|
||||||
- **`className`**: Additional CSS classes for styling
|
|
||||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<CommentsSection
|
|
||||||
root={event}
|
|
||||||
title="Discussion"
|
|
||||||
emptyStateMessage="Start the conversation"
|
|
||||||
emptyStateSubtitle="Share your thoughts about this post"
|
|
||||||
className="mt-8"
|
|
||||||
limit={100}
|
|
||||||
/>
|
|
||||||
```
|
|
||||||
|
|
||||||
## Commenting on URLs
|
|
||||||
|
|
||||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
<CommentsSection
|
|
||||||
root={new URL("https://example.com/article")}
|
|
||||||
title="Comments on this article"
|
|
||||||
/>
|
|
||||||
```
|
|
||||||
@@ -1,478 +0,0 @@
|
|||||||
---
|
|
||||||
name: nostr-direct-messages
|
|
||||||
description: Implement Nostr direct messaging features, build chat interfaces, or work with encrypted peer-to-peer communication (NIP-04 and NIP-17).
|
|
||||||
---
|
|
||||||
|
|
||||||
# Direct Messaging on Nostr
|
|
||||||
|
|
||||||
This project includes a complete direct messaging system supporting both NIP-04 (legacy) and NIP-17 (modern, more private) encrypted messages with real-time subscriptions, optimistic updates, and a persistent cache-first local storage.
|
|
||||||
|
|
||||||
**The DM system is not enabled by default** - follow the setup instructions below to add messaging functionality to your application.
|
|
||||||
|
|
||||||
## Setup Instructions
|
|
||||||
|
|
||||||
### 1. Add DMProvider to Your App
|
|
||||||
|
|
||||||
First, add the `DMProvider` to your app's provider tree in `src/App.tsx`:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
// Add these imports at the top of src/App.tsx
|
|
||||||
import { DMProvider, type DMConfig } from '@/components/DMProvider';
|
|
||||||
import { PROTOCOL_MODE } from '@/lib/dmConstants';
|
|
||||||
|
|
||||||
// Add this configuration before your App component
|
|
||||||
const dmConfig: DMConfig = {
|
|
||||||
// Enable or disable DMs entirely
|
|
||||||
enabled: true, // Set to true to enable messaging functionality
|
|
||||||
|
|
||||||
// Choose one protocol mode:
|
|
||||||
// PROTOCOL_MODE.NIP04_ONLY - Force NIP-04 (legacy) only
|
|
||||||
// PROTOCOL_MODE.NIP17_ONLY - Force NIP-17 (private) only
|
|
||||||
// PROTOCOL_MODE.NIP04_OR_NIP17 - Allow users to choose between NIP-04 and NIP-17 (defaults to NIP-17)
|
|
||||||
protocolMode: PROTOCOL_MODE.NIP17_ONLY, // Recommended for new apps
|
|
||||||
};
|
|
||||||
|
|
||||||
// Then wrap your app components with DMProvider:
|
|
||||||
export function App() {
|
|
||||||
return (
|
|
||||||
<UnheadProvider head={head}>
|
|
||||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
|
|
||||||
<QueryClientProvider client={queryClient}>
|
|
||||||
<NostrLoginProvider storageKey='nostr:login'>
|
|
||||||
<NostrProvider>
|
|
||||||
<NostrSync />
|
|
||||||
<DMProvider config={dmConfig}>
|
|
||||||
<TooltipProvider>
|
|
||||||
<Toaster />
|
|
||||||
<Suspense>
|
|
||||||
<AppRouter />
|
|
||||||
</Suspense>
|
|
||||||
</TooltipProvider>
|
|
||||||
</DMProvider>
|
|
||||||
</NostrProvider>
|
|
||||||
</NostrLoginProvider>
|
|
||||||
</QueryClientProvider>
|
|
||||||
</AppProvider>
|
|
||||||
</UnheadProvider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. Configure DM Settings
|
|
||||||
|
|
||||||
The `DMConfig` object supports the following options:
|
|
||||||
|
|
||||||
- `enabled` (boolean, default: `false`) - Enable/disable entire DM system. When false, no messages are loaded, stored, or processed.
|
|
||||||
- `protocolMode` (ProtocolMode, default: `PROTOCOL_MODE.NIP17_ONLY`) - Which protocols to support:
|
|
||||||
- `PROTOCOL_MODE.NIP04_ONLY` - Legacy encryption only
|
|
||||||
- `PROTOCOL_MODE.NIP17_ONLY` - Modern private messages (recommended)
|
|
||||||
- `PROTOCOL_MODE.NIP04_OR_NIP17` - Support both protocols (for backwards compatibility)
|
|
||||||
|
|
||||||
**Note**: The DM system uses domain-based IndexedDB naming (`nostr-dm-store-${hostname}`) to prevent conflicts between multiple apps on the same domain.
|
|
||||||
|
|
||||||
## Quick Start
|
|
||||||
|
|
||||||
### 1. Send Messages
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { useDMContext } from '@/hooks/useDMContext';
|
|
||||||
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
|
||||||
|
|
||||||
function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
|
|
||||||
const { sendMessage } = useDMContext();
|
|
||||||
const [content, setContent] = useState('');
|
|
||||||
|
|
||||||
const handleSend = async () => {
|
|
||||||
await sendMessage({
|
|
||||||
recipientPubkey,
|
|
||||||
content,
|
|
||||||
protocol: MESSAGE_PROTOCOL.NIP17, // Uses NIP-44 encryption + gift wrapping
|
|
||||||
});
|
|
||||||
setContent('');
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
|
|
||||||
<textarea
|
|
||||||
value={content}
|
|
||||||
onChange={(e) => setContent(e.target.value)}
|
|
||||||
placeholder="Type a message..."
|
|
||||||
/>
|
|
||||||
<button type="submit">Send</button>
|
|
||||||
</form>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. Display Conversations
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { useDMContext } from '@/hooks/useDMContext';
|
|
||||||
import { useAuthor } from '@/hooks/useAuthor';
|
|
||||||
import { genUserName } from '@/lib/genUserName';
|
|
||||||
|
|
||||||
function ConversationList({ onSelectConversation }: { onSelectConversation: (pubkey: string) => void }) {
|
|
||||||
const { conversations, isLoading } = useDMContext();
|
|
||||||
|
|
||||||
if (isLoading) {
|
|
||||||
return <div>Loading conversations...</div>;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-2">
|
|
||||||
{conversations.map((conversation) => (
|
|
||||||
<ConversationItem
|
|
||||||
key={conversation.pubkey}
|
|
||||||
conversation={conversation}
|
|
||||||
onClick={() => onSelectConversation(conversation.pubkey)}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ConversationItem({ conversation, onClick }: {
|
|
||||||
conversation: ConversationSummary;
|
|
||||||
onClick: () => void;
|
|
||||||
}) {
|
|
||||||
const author = useAuthor(conversation.pubkey);
|
|
||||||
const displayName = author.data?.metadata?.name || genUserName(conversation.pubkey);
|
|
||||||
const avatarUrl = author.data?.metadata?.picture;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<button onClick={onClick} className="w-full p-3 hover:bg-accent rounded-lg">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<Avatar>
|
|
||||||
<AvatarImage src={avatarUrl} />
|
|
||||||
<AvatarFallback>{displayName.slice(0, 2).toUpperCase()}</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
<div className="flex-1 text-left">
|
|
||||||
<div className="font-medium">{displayName}</div>
|
|
||||||
<div className="text-sm text-muted-foreground truncate">
|
|
||||||
{conversation.lastMessage?.decryptedContent || 'No messages yet'}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. Display Messages in a Conversation
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { useConversationMessages } from '@/hooks/useConversationMessages';
|
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
|
||||||
|
|
||||||
function MessageThread({ conversationPubkey }: { conversationPubkey: string }) {
|
|
||||||
const { user } = useCurrentUser();
|
|
||||||
const { messages, hasMoreMessages, loadEarlierMessages } = useConversationMessages(conversationPubkey);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex flex-col space-y-2">
|
|
||||||
{hasMoreMessages && (
|
|
||||||
<button onClick={loadEarlierMessages} className="text-sm text-muted-foreground">
|
|
||||||
Load earlier messages
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{messages.map((message) => {
|
|
||||||
const isFromMe = message.pubkey === user?.pubkey;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={message.id}
|
|
||||||
className={cn(
|
|
||||||
"flex",
|
|
||||||
isFromMe ? "justify-end" : "justify-start"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className={cn(
|
|
||||||
"max-w-[70%] rounded-lg px-4 py-2",
|
|
||||||
isFromMe ? "bg-primary text-primary-foreground" : "bg-muted"
|
|
||||||
)}>
|
|
||||||
{message.error ? (
|
|
||||||
<span className="text-red-500">🔒 {message.error}</span>
|
|
||||||
) : (
|
|
||||||
<p className="whitespace-pre-wrap break-words">
|
|
||||||
{message.decryptedContent}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{message.isSending && (
|
|
||||||
<span className="text-xs opacity-50">Sending...</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Using the Complete Messaging Interface
|
|
||||||
|
|
||||||
For a fully-featured messaging UI out of the box, use the `DMMessagingInterface` component:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { DMMessagingInterface } from "@/components/dm/DMMessagingInterface";
|
|
||||||
|
|
||||||
function MessagesPage() {
|
|
||||||
return (
|
|
||||||
<div className="container mx-auto p-4 h-screen">
|
|
||||||
<DMMessagingInterface />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
The `DMMessagingInterface` component provides a complete messaging UI with:
|
|
||||||
- Conversation list with Active/Requests tabs
|
|
||||||
- Message thread view with pagination
|
|
||||||
- Compose area with file upload support
|
|
||||||
- Real-time message updates
|
|
||||||
- Mobile-responsive layout (shows one panel at a time on mobile)
|
|
||||||
|
|
||||||
It requires no props and works automatically when wrapped in `DMProvider`.
|
|
||||||
|
|
||||||
**For custom layouts**, see the "Building Custom Messaging UIs" section below for individual components (`DMConversationList`, `DMChatArea`, `DMStatusInfo`).
|
|
||||||
|
|
||||||
## Sending Files with Messages
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { useDMContext } from '@/hooks/useDMContext';
|
|
||||||
import { useUploadFile } from '@/hooks/useUploadFile';
|
|
||||||
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
|
||||||
import type { FileAttachment } from '@/contexts/DMContext';
|
|
||||||
|
|
||||||
function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
|
|
||||||
const { sendMessage } = useDMContext();
|
|
||||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
|
||||||
const [content, setContent] = useState('');
|
|
||||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
|
||||||
|
|
||||||
const handleSend = async () => {
|
|
||||||
let attachments: FileAttachment[] | undefined;
|
|
||||||
|
|
||||||
// Upload file if one is selected
|
|
||||||
if (selectedFile) {
|
|
||||||
const tags = await uploadFile(selectedFile);
|
|
||||||
|
|
||||||
attachments = [{
|
|
||||||
url: tags[0][1], // URL from first tag
|
|
||||||
mimeType: selectedFile.type,
|
|
||||||
size: selectedFile.size,
|
|
||||||
name: selectedFile.name,
|
|
||||||
tags: tags
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
|
|
||||||
await sendMessage({
|
|
||||||
recipientPubkey,
|
|
||||||
content,
|
|
||||||
protocol: MESSAGE_PROTOCOL.NIP17,
|
|
||||||
attachments,
|
|
||||||
});
|
|
||||||
|
|
||||||
setContent('');
|
|
||||||
setSelectedFile(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
|
|
||||||
<textarea
|
|
||||||
value={content}
|
|
||||||
onChange={(e) => setContent(e.target.value)}
|
|
||||||
placeholder="Type a message..."
|
|
||||||
/>
|
|
||||||
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{selectedFile && <div>Selected: {selectedFile.name}</div>}
|
|
||||||
|
|
||||||
<button type="submit" disabled={isUploading}>
|
|
||||||
{isUploading ? 'Uploading...' : 'Send'}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Protocol Comparison
|
|
||||||
|
|
||||||
### NIP-04 (Legacy)
|
|
||||||
- **Encryption**: NIP-04 (simpler, older)
|
|
||||||
- **Metadata**: Sender and recipient visible to relays
|
|
||||||
- **Event Kind**: Kind 4
|
|
||||||
- **Use When**: Compatibility with older clients
|
|
||||||
|
|
||||||
### NIP-17 (Modern & Private)
|
|
||||||
- **Encryption**: NIP-44 (stronger)
|
|
||||||
- **Metadata**: Hidden via gift wrapping (NIP-59)
|
|
||||||
- **Event Kinds**: Kind 14 (text), Kind 15 (files)
|
|
||||||
- **Wrapped In**: Kind 1059 (Gift Wrap) with ephemeral keys
|
|
||||||
- **Use When**: Maximum privacy (recommended)
|
|
||||||
|
|
||||||
**Key Privacy Features of NIP-17:**
|
|
||||||
- Sender identity hidden (uses random ephemeral keys)
|
|
||||||
- Timestamps randomized (±2 days) to hide send time
|
|
||||||
- Dual gift wraps (recipient + sender) for message history
|
|
||||||
|
|
||||||
## Advanced Features
|
|
||||||
|
|
||||||
### Conversation Categorization
|
|
||||||
|
|
||||||
The system automatically categorizes conversations:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
const { conversations } = useDMContext();
|
|
||||||
|
|
||||||
// Filter by category
|
|
||||||
const knownConversations = conversations.filter(c => c.isKnown);
|
|
||||||
const requestConversations = conversations.filter(c => c.isRequest);
|
|
||||||
|
|
||||||
// isKnown = true if user has sent at least one message
|
|
||||||
// isRequest = true if only received messages, never replied
|
|
||||||
```
|
|
||||||
|
|
||||||
### Loading States
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
const { isLoading, loadingPhase, scanProgress } = useDMContext();
|
|
||||||
|
|
||||||
// Check overall loading state
|
|
||||||
if (isLoading) {
|
|
||||||
console.log('Current phase:', loadingPhase);
|
|
||||||
// LOADING_PHASES.CACHE - Loading from local cache
|
|
||||||
// LOADING_PHASES.RELAYS - Querying relays
|
|
||||||
// LOADING_PHASES.SUBSCRIPTIONS - Setting up real-time updates
|
|
||||||
// LOADING_PHASES.READY - Fully loaded
|
|
||||||
}
|
|
||||||
|
|
||||||
// Display scan progress for large message histories
|
|
||||||
if (scanProgress.nip17) {
|
|
||||||
console.log(`NIP-17: ${scanProgress.nip17.current} messages - ${scanProgress.nip17.status}`);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Clear Cache and Refresh
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { useDMContext } from '@/hooks/useDMContext';
|
|
||||||
|
|
||||||
function SettingsButton() {
|
|
||||||
const { clearCacheAndRefetch } = useDMContext();
|
|
||||||
|
|
||||||
const handleClearCache = async () => {
|
|
||||||
await clearCacheAndRefetch();
|
|
||||||
// Clears IndexedDB cache and reloads all messages from relays
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<button onClick={handleClearCache}>
|
|
||||||
Clear Message Cache
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Architecture Notes
|
|
||||||
|
|
||||||
### Data Flow
|
|
||||||
1. **Cache First**: Messages load instantly from encrypted IndexedDB cache
|
|
||||||
2. **Background Sync**: New messages fetched from relays in parallel
|
|
||||||
3. **Real-time Updates**: WebSocket subscriptions for live messages
|
|
||||||
4. **Optimistic UI**: Sent messages appear immediately, confirmed on relay response
|
|
||||||
|
|
||||||
### Storage
|
|
||||||
- **IndexedDB**: All messages stored locally with NIP-44 encryption
|
|
||||||
- **Per-User Storage**: Separate encrypted store for each logged-in user
|
|
||||||
- **Automatic Sync**: Debounced writes (15s) + immediate on new messages
|
|
||||||
|
|
||||||
### Performance
|
|
||||||
- **Parallel Queries**: NIP-04 and NIP-17 messages fetched simultaneously
|
|
||||||
- **Batched Loading**: Messages loaded in batches (1000/batch, 20k limit)
|
|
||||||
- **Pagination**: Conversation messages paginated (25/page)
|
|
||||||
- **Deduplication**: Automatic filtering of duplicate messages by ID
|
|
||||||
|
|
||||||
### Security
|
|
||||||
- **NIP-44 Encryption**: Modern authenticated encryption for all NIP-17 messages
|
|
||||||
- **Local Encryption**: IndexedDB storage encrypted with user's NIP-44 key
|
|
||||||
- **Ephemeral Keys**: Random keys for NIP-17 gift wraps (sender anonymity)
|
|
||||||
- **No Plaintext**: Decrypted content never persisted unencrypted
|
|
||||||
- **Domain Isolation**: IndexedDB databases are namespaced by hostname to prevent data conflicts
|
|
||||||
|
|
||||||
## Building Custom Messaging UIs
|
|
||||||
|
|
||||||
For advanced use cases, you can use the individual DM components to build custom layouts:
|
|
||||||
|
|
||||||
### Available Components
|
|
||||||
|
|
||||||
**`DMConversationList`** - Conversation sidebar with tabs
|
|
||||||
```tsx
|
|
||||||
import { DMConversationList } from '@/components/dm/DMConversationList';
|
|
||||||
|
|
||||||
<DMConversationList
|
|
||||||
selectedPubkey={selectedPubkey}
|
|
||||||
onSelectConversation={(pubkey) => setSelectedPubkey(pubkey)}
|
|
||||||
onStatusClick={() => setShowStatus(true)} // optional
|
|
||||||
className="h-full"
|
|
||||||
/>
|
|
||||||
```
|
|
||||||
|
|
||||||
**`DMChatArea`** - Message thread and compose area
|
|
||||||
```tsx
|
|
||||||
import { DMChatArea } from '@/components/dm/DMChatArea';
|
|
||||||
|
|
||||||
<DMChatArea
|
|
||||||
pubkey={selectedPubkey}
|
|
||||||
onBack={() => setSelectedPubkey(null)} // optional, for mobile back button
|
|
||||||
className="h-full"
|
|
||||||
/>
|
|
||||||
```
|
|
||||||
|
|
||||||
**`DMStatusInfo`** - Debug/status panel
|
|
||||||
```tsx
|
|
||||||
import { DMStatusInfo } from '@/components/dm/DMStatusInfo';
|
|
||||||
|
|
||||||
<DMStatusInfo clearCacheAndRefetch={clearCacheAndRefetch} />
|
|
||||||
```
|
|
||||||
|
|
||||||
### Custom Layout Example
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { useState } from 'react';
|
|
||||||
import { DMConversationList } from '@/components/dm/DMConversationList';
|
|
||||||
import { DMChatArea } from '@/components/dm/DMChatArea';
|
|
||||||
|
|
||||||
function CustomMessagingLayout() {
|
|
||||||
const [selectedPubkey, setSelectedPubkey] = useState<string | null>(null);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex h-screen">
|
|
||||||
{/* Custom sidebar */}
|
|
||||||
<aside className="w-64 border-r">
|
|
||||||
<DMConversationList
|
|
||||||
selectedPubkey={selectedPubkey}
|
|
||||||
onSelectConversation={setSelectedPubkey}
|
|
||||||
/>
|
|
||||||
</aside>
|
|
||||||
|
|
||||||
{/* Custom main area */}
|
|
||||||
<main className="flex-1">
|
|
||||||
{selectedPubkey ? (
|
|
||||||
<DMChatArea pubkey={selectedPubkey} />
|
|
||||||
) : (
|
|
||||||
<div className="flex items-center justify-center h-full">
|
|
||||||
<p>Select a conversation to start messaging</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
---
|
|
||||||
name: nostr-infinite-scroll
|
|
||||||
description: Build feed interfaces, implement pagination for Nostr events, or create social media-style infinite scroll experiences.
|
|
||||||
---
|
|
||||||
|
|
||||||
# Infinite Scroll for Nostr Feeds
|
|
||||||
|
|
||||||
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { useNostr } from '@nostrify/react';
|
|
||||||
import { useInfiniteQuery } from '@tanstack/react-query';
|
|
||||||
|
|
||||||
export function useGlobalFeed() {
|
|
||||||
const { nostr } = useNostr();
|
|
||||||
|
|
||||||
return useInfiniteQuery({
|
|
||||||
queryKey: ['global-feed'],
|
|
||||||
queryFn: async ({ pageParam, signal }) => {
|
|
||||||
const filter = { kinds: [1], limit: 20 };
|
|
||||||
if (pageParam) filter.until = pageParam;
|
|
||||||
|
|
||||||
const events = await nostr.query([filter], {
|
|
||||||
signal: AbortSignal.any([signal, AbortSignal.timeout(1500)])
|
|
||||||
});
|
|
||||||
|
|
||||||
return events;
|
|
||||||
},
|
|
||||||
getNextPageParam: (lastPage) => {
|
|
||||||
if (lastPage.length === 0) return undefined;
|
|
||||||
return lastPage[lastPage.length - 1].created_at - 1; // Subtract 1 since 'until' is inclusive
|
|
||||||
},
|
|
||||||
initialPageParam: undefined,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Example usage with intersection observer for automatic loading:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { useInView } from 'react-intersection-observer';
|
|
||||||
import { useMemo } from 'react';
|
|
||||||
|
|
||||||
function GlobalFeed() {
|
|
||||||
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
|
|
||||||
const { ref, inView } = useInView();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (inView && hasNextPage && !isFetchingNextPage) {
|
|
||||||
fetchNextPage();
|
|
||||||
}
|
|
||||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]);
|
|
||||||
|
|
||||||
// Remove duplicate events by ID
|
|
||||||
const posts = useMemo(() => {
|
|
||||||
const seen = new Set();
|
|
||||||
return data?.pages.flat().filter(event => {
|
|
||||||
if (!event.id || seen.has(event.id)) return false;
|
|
||||||
seen.add(event.id);
|
|
||||||
return true;
|
|
||||||
}) || [];
|
|
||||||
}, [data?.pages]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{posts.map((post) => (
|
|
||||||
<PostCard key={post.id} post={post} />
|
|
||||||
))}
|
|
||||||
{hasNextPage && (
|
|
||||||
<div ref={ref} className="py-4">
|
|
||||||
{isFetchingNextPage && <Skeleton className="h-20 w-full" />}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
Symlink
+1
@@ -0,0 +1 @@
|
|||||||
|
CONTEXT.md
|
||||||
Symlink
+1
@@ -0,0 +1 @@
|
|||||||
|
../CONTEXT.md
|
||||||
@@ -7,13 +7,10 @@ yarn-error.log*
|
|||||||
pnpm-debug.log*
|
pnpm-debug.log*
|
||||||
lerna-debug.log*
|
lerna-debug.log*
|
||||||
|
|
||||||
|
|
||||||
node_modules
|
node_modules
|
||||||
dist
|
dist
|
||||||
dist-ssr
|
dist-ssr
|
||||||
*.local
|
*.local
|
||||||
.ai/
|
|
||||||
yarn.lock
|
|
||||||
|
|
||||||
# Editor directories and files
|
# Editor directories and files
|
||||||
.idea
|
.idea
|
||||||
@@ -26,8 +23,3 @@ yarn.lock
|
|||||||
|
|
||||||
# Vercel
|
# Vercel
|
||||||
.vercel
|
.vercel
|
||||||
|
|
||||||
# Secrets
|
|
||||||
.env
|
|
||||||
.env.*
|
|
||||||
!.env.example
|
|
||||||
+7
-4
@@ -5,13 +5,16 @@ default:
|
|||||||
timeout: 1 minute
|
timeout: 1 minute
|
||||||
|
|
||||||
stages:
|
stages:
|
||||||
- test
|
- build
|
||||||
- deploy
|
- deploy
|
||||||
|
|
||||||
test:
|
build:
|
||||||
stage: test
|
stage: build
|
||||||
script:
|
script:
|
||||||
- npm run test
|
- npm run build
|
||||||
|
only:
|
||||||
|
variables:
|
||||||
|
- $CI_DEFAULT_BRANCH != $CI_COMMIT_REF_NAME
|
||||||
|
|
||||||
pages:
|
pages:
|
||||||
stage: deploy
|
stage: deploy
|
||||||
|
|||||||
Symlink
+1
@@ -0,0 +1 @@
|
|||||||
|
CONTEXT.md
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# jsr registry should not be edited or removed
|
||||||
|
.npmrc
|
||||||
|
|
||||||
|
# vite client types are needed
|
||||||
|
src/vite-env.d.ts
|
||||||
|
|
||||||
|
# tsconfig is stable and working correctly, so should not be edited
|
||||||
|
tsconfig.json
|
||||||
|
tsconfig.app.json
|
||||||
|
tsconfig.node.json
|
||||||
|
|
||||||
|
# postcss config for Tailwind is stable and working correctly, so should not be edited unless upgrading Tailwind to v4
|
||||||
|
postcss.config.js
|
||||||
|
|
||||||
|
# vite config is stable and usually should not need to be edited
|
||||||
|
vite.config.ts
|
||||||
@@ -1,14 +1,9 @@
|
|||||||
{
|
{
|
||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"js-dev": {
|
|
||||||
"type": "stdio",
|
|
||||||
"command": "npx",
|
|
||||||
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
|
|
||||||
},
|
|
||||||
"nostr": {
|
"nostr": {
|
||||||
"type": "stdio",
|
"type": "stdio",
|
||||||
"command": "npx",
|
"command": "npx",
|
||||||
"args": ["-y", "@nostrbook/mcp@latest"]
|
"args": ["-y", "xjsr", "@nostrbook/mcp"]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Vendored
+1
-6
@@ -1,14 +1,9 @@
|
|||||||
{
|
{
|
||||||
"servers": {
|
"servers": {
|
||||||
"js-dev": {
|
|
||||||
"type": "stdio",
|
|
||||||
"command": "npx",
|
|
||||||
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
|
|
||||||
},
|
|
||||||
"nostr": {
|
"nostr": {
|
||||||
"type": "stdio",
|
"type": "stdio",
|
||||||
"command": "npx",
|
"command": "npx",
|
||||||
"args": ["-y", "@nostrbook/mcp@latest"]
|
"args": ["-y", "xjsr", "@nostrbook/mcp"]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+78
-438
@@ -18,8 +18,6 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
|||||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||||
- `/src/components/dm/`: Direct messaging UI components (DMMessagingInterface, DMConversationList, DMChatArea)
|
|
||||||
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
|
|
||||||
- `/src/hooks/`: Custom hooks including:
|
- `/src/hooks/`: Custom hooks including:
|
||||||
- `useNostr`: Core Nostr protocol integration
|
- `useNostr`: Core Nostr protocol integration
|
||||||
- `useAuthor`: Fetch user profile data by pubkey
|
- `useAuthor`: Fetch user profile data by pubkey
|
||||||
@@ -33,23 +31,14 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
|||||||
- `useLoggedInAccounts`: Manage multiple accounts
|
- `useLoggedInAccounts`: Manage multiple accounts
|
||||||
- `useLoginActions`: Authentication actions
|
- `useLoginActions`: Authentication actions
|
||||||
- `useIsMobile`: Responsive design helper
|
- `useIsMobile`: Responsive design helper
|
||||||
- `useZaps`: Lightning zap functionality with payment processing
|
|
||||||
- `useWallet`: Unified wallet detection (WebLN + NWC)
|
|
||||||
- `useNWC`: Nostr Wallet Connect connection management
|
|
||||||
- `useNWCContext`: Access NWC context provider
|
|
||||||
- `useShakespeare`: AI chat completions with Shakespeare AI API
|
|
||||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||||
- `/src/lib/`: Utility functions and shared logic
|
- `/src/lib/`: Utility functions and shared logic
|
||||||
- `/src/contexts/`: React context providers (AppContext, NWCContext, DMContext)
|
- `/src/contexts/`: React context providers (AppContext)
|
||||||
- `useDMContext`: Hook exported from DMContext for direct messaging (NIP-04 & NIP-17)
|
|
||||||
- `useConversationMessages`: Hook exported from DMContext for paginated messages
|
|
||||||
- `/src/test/`: Testing utilities including TestApp component
|
- `/src/test/`: Testing utilities including TestApp component
|
||||||
- `/public/`: Static assets
|
- `/public/`: Static assets
|
||||||
- `App.tsx`: Main app component with provider setup (**CRITICAL**: this file is **already configured** with `QueryClientProvider`, `NostrProvider`, `UnheadProvider` and other important providers - **read this file before making changes**. Changes are usually not necessary unless adding new providers. Changing this file may break the application)
|
- `App.tsx`: Main app component with provider setup
|
||||||
- `AppRouter.tsx`: React Router configuration
|
- `AppRouter.tsx`: React Router configuration
|
||||||
|
|
||||||
**CRITICAL**: Always read the files mentioned above before making changes, as they contain important setup and configuration for the application. Never directly write to these files without first reading their contents.
|
|
||||||
|
|
||||||
## UI Components
|
## UI Components
|
||||||
|
|
||||||
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
||||||
@@ -92,6 +81,7 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
|
|||||||
- **Sidebar**: Navigation sidebar component
|
- **Sidebar**: Navigation sidebar component
|
||||||
- **Skeleton**: Loading placeholder
|
- **Skeleton**: Loading placeholder
|
||||||
- **Slider**: Input for selecting a value from a range
|
- **Slider**: Input for selecting a value from a range
|
||||||
|
- **Sonner**: Toast notification manager
|
||||||
- **Switch**: Toggle switch control
|
- **Switch**: Toggle switch control
|
||||||
- **Table**: Data table with headers and rows
|
- **Table**: Data table with headers and rows
|
||||||
- **Tabs**: Tabbed interface component
|
- **Tabs**: Tabbed interface component
|
||||||
@@ -105,20 +95,24 @@ These components follow a consistent pattern using React's `forwardRef` and use
|
|||||||
|
|
||||||
## System Prompt Management
|
## System Prompt Management
|
||||||
|
|
||||||
The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||||
|
|
||||||
1. Edit AGENTS.md directly
|
1. Edit CONTEXT.md directly
|
||||||
2. The changes take effect in the next session
|
2. The changes take effect in the next session
|
||||||
|
|
||||||
|
## "Vibed with MKStack"
|
||||||
|
|
||||||
|
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
||||||
|
|
||||||
## Nostr Protocol Integration
|
## Nostr Protocol Integration
|
||||||
|
|
||||||
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
||||||
|
|
||||||
### Nostr Implementation Guidelines
|
### Nostr Implementation Guidelines
|
||||||
|
|
||||||
- Always check the full list of existing NIPs before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||||
- If any existing kind or NIP might offer the required functionality, read the relevant NIPs to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||||
- Only generate new kind numbers if no existing suitable kinds are found after comprehensive research.
|
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||||
|
|
||||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||||
|
|
||||||
@@ -126,7 +120,7 @@ Knowing when to create a new kind versus reusing an existing kind requires caref
|
|||||||
|
|
||||||
When implementing features that could use existing NIPs, follow this decision framework:
|
When implementing features that could use existing NIPs, follow this decision framework:
|
||||||
|
|
||||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Get an overview of all NIPs, and then read specific NIPs and kind documentation to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||||
|
|
||||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||||
|
|
||||||
@@ -143,9 +137,6 @@ When implementing features that could use existing NIPs, follow this decision fr
|
|||||||
- No existing NIP covers the core functionality
|
- No existing NIP covers the core functionality
|
||||||
- The data structure is fundamentally different from existing patterns
|
- The data structure is fundamentally different from existing patterns
|
||||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||||
- If you have a tool available to generate a kind, you **MUST** call the tool to generate a new kind rather than picking an arbitrary number
|
|
||||||
|
|
||||||
6. **Custom Kind Publishing**: When publishing events with custom generated kinds, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
|
||||||
|
|
||||||
**Example Decision Process**:
|
**Example Decision Process**:
|
||||||
```
|
```
|
||||||
@@ -220,7 +211,7 @@ const events = await nostr.query([{
|
|||||||
kinds: [1],
|
kinds: [1],
|
||||||
'#t': ['farming'],
|
'#t': ['farming'],
|
||||||
limit: 20
|
limit: 20
|
||||||
}]);
|
}], { signal });
|
||||||
```
|
```
|
||||||
|
|
||||||
### Kind Ranges
|
### Kind Ranges
|
||||||
@@ -270,104 +261,6 @@ The file `NIP.md` is used by this project to define a custom Nostr protocol docu
|
|||||||
|
|
||||||
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
|
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
|
||||||
|
|
||||||
### Nostr Security Model
|
|
||||||
|
|
||||||
**CRITICAL**: Nostr is permissionless - **anyone can publish any event**. When implementing admin/moderation systems or any feature that should only trust specific users, you MUST filter queries by the `authors` field. Without author filtering, anyone can publish events claiming to be admin actions, moderator decisions, or trusted content.
|
|
||||||
|
|
||||||
#### Using the `authors` Filter
|
|
||||||
|
|
||||||
**Always filter by authors when querying:**
|
|
||||||
- **Admin/moderator actions** - MUST filter by trusted admin pubkeys
|
|
||||||
- **Addressable events (kinds 30000-39999)** - MUST include author to prevent anyone from publishing events with the same d-tag
|
|
||||||
- **Any privileged operations** - Filter by trusted pubkeys only
|
|
||||||
|
|
||||||
**✅ Secure - Filtering by trusted authors:**
|
|
||||||
```typescript
|
|
||||||
import { ADMIN_PUBKEYS } from '@/lib/admins';
|
|
||||||
|
|
||||||
// Query organizer appointments - ONLY accept events from admins
|
|
||||||
const events = await nostr.query([{
|
|
||||||
kinds: [30078],
|
|
||||||
authors: ADMIN_PUBKEYS, // CRITICAL: Only trust admin authors
|
|
||||||
'#d': ['pathos-organizers'],
|
|
||||||
limit: 1
|
|
||||||
}]);
|
|
||||||
```
|
|
||||||
|
|
||||||
**❌ INSECURE - No author filtering:**
|
|
||||||
```typescript
|
|
||||||
// DANGER: This accepts events from ANYONE who publishes kind 30078
|
|
||||||
// An attacker could appoint themselves as an organizer
|
|
||||||
const events = await nostr.query([{
|
|
||||||
kinds: [30078],
|
|
||||||
'#d': ['pathos-organizers'],
|
|
||||||
limit: 1
|
|
||||||
}]);
|
|
||||||
```
|
|
||||||
|
|
||||||
**Addressable Events Example:**
|
|
||||||
```typescript
|
|
||||||
// For addressable events, ALWAYS include the author in your filter
|
|
||||||
// This prevents attackers from publishing events with the same d-tag
|
|
||||||
const article = await nostr.query([{
|
|
||||||
kinds: [30023], // Long-form article
|
|
||||||
authors: [authorPubkey], // CRITICAL: Verify the author
|
|
||||||
'#d': ['my-article-slug'],
|
|
||||||
limit: 1
|
|
||||||
}]);
|
|
||||||
```
|
|
||||||
|
|
||||||
**URL Routing for Addressable/Replaceable Events:**
|
|
||||||
|
|
||||||
When creating URL paths for addressable or replaceable events, always include the author in the URL structure:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
// ❌ INSECURE: Missing author - anyone could publish an event with this d-tag
|
|
||||||
<Route path="/article/:slug" element={<Article />} />
|
|
||||||
// URL: /article/hello-world
|
|
||||||
|
|
||||||
// ✅ SECURE: Includes author - can safely filter by both author and d-tag
|
|
||||||
<Route path="/article/:npub/:slug" element={<Article />} />
|
|
||||||
// URL: /article/npub1abc.../hello-world
|
|
||||||
```
|
|
||||||
|
|
||||||
This ensures your route parameters provide both the author pubkey and the d-tag identifier needed to create a secure query filter.
|
|
||||||
|
|
||||||
**NIP-72 Community Moderation Example:**
|
|
||||||
|
|
||||||
When implementing moderated communities (NIP-72), you must query the community definition to get the moderator list, then filter approval events by those moderators:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
// Step 1: Query the community definition to get moderators
|
|
||||||
const communityEvents = await nostr.query([{
|
|
||||||
kinds: [34550],
|
|
||||||
authors: [communityOwnerPubkey], // CRITICAL: Only trust the community owner
|
|
||||||
'#d': [communityId],
|
|
||||||
limit: 1,
|
|
||||||
}]);
|
|
||||||
|
|
||||||
if (communityEvents.length === 0) return [];
|
|
||||||
|
|
||||||
// Step 2: Extract moderator pubkeys from p tags
|
|
||||||
const moderatorPubkeys = communityEvents[0].tags
|
|
||||||
.filter(([name, _, __, role]) => name === 'p' && role === 'moderator')
|
|
||||||
.map(([_, pubkey]) => pubkey);
|
|
||||||
|
|
||||||
// Step 3: Query approval events - ONLY from trusted moderators
|
|
||||||
const approvals = await nostr.query([{
|
|
||||||
kinds: [4550],
|
|
||||||
authors: moderatorPubkeys, // CRITICAL: Only accept approvals from moderators
|
|
||||||
'#a': [`34550:${communityOwnerPubkey}:${communityId}`],
|
|
||||||
limit: 100,
|
|
||||||
}]);
|
|
||||||
```
|
|
||||||
|
|
||||||
Without filtering approvals by the moderator list, anyone could publish kind 4550 events claiming to approve posts for the community.
|
|
||||||
|
|
||||||
#### When Author Filtering Is NOT Required
|
|
||||||
|
|
||||||
Author filtering is not needed for public user-generated content where anyone should be able to post (kind 1 notes, reactions, discovery queries, public feeds, etc.).
|
|
||||||
|
|
||||||
### The `useNostr` Hook
|
### The `useNostr` Hook
|
||||||
|
|
||||||
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
||||||
@@ -382,85 +275,6 @@ function useCustomHook() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Connecting to Multiple Nostr Relays
|
|
||||||
|
|
||||||
By default, the `nostr` object from `useNostr` uses a pool configuration that reads data from 1 relay and publishes to all configured relays. However, you can connect to specific relays or groups of relays for more granular control:
|
|
||||||
|
|
||||||
#### Single Relay Connection
|
|
||||||
|
|
||||||
To read and publish from one specific relay, use `nostr.relay()` with a WebSocket URL:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { useNostr } from '@nostrify/react';
|
|
||||||
|
|
||||||
function useSpecificRelay() {
|
|
||||||
const { nostr } = useNostr();
|
|
||||||
|
|
||||||
// Connect to a specific relay
|
|
||||||
const relay = nostr.relay('wss://relay.damus.io');
|
|
||||||
|
|
||||||
// Query from this specific relay only
|
|
||||||
const events = await relay.query([{ kinds: [1], limit: 20 }]);
|
|
||||||
|
|
||||||
// Publish to this specific relay only
|
|
||||||
await relay.event({ kind: 1, content: 'Hello from specific relay!' });
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Multiple Relay Group
|
|
||||||
|
|
||||||
To read and publish from a specific set of relays, use `nostr.group()` with an array of relay URLs:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { useNostr } from '@nostrify/react';
|
|
||||||
|
|
||||||
function useRelayGroup() {
|
|
||||||
const { nostr } = useNostr();
|
|
||||||
|
|
||||||
// Create a group of specific relays
|
|
||||||
const relayGroup = nostr.group([
|
|
||||||
'wss://relay.damus.io',
|
|
||||||
'wss://relay.nostr.band',
|
|
||||||
'wss://nos.lol'
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Query from all relays in the group
|
|
||||||
const events = await relayGroup.query([{ kinds: [1], limit: 20 }]);
|
|
||||||
|
|
||||||
// Publish to all relays in the group
|
|
||||||
await relayGroup.event({ kind: 1, content: 'Hello from relay group!' });
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### API Consistency
|
|
||||||
|
|
||||||
Both `relay` and `group` objects have the same API as the main `nostr` object, including:
|
|
||||||
|
|
||||||
- `.query()` - Query events with filters
|
|
||||||
- `.req()` - Create subscriptions
|
|
||||||
- `.event()` - Publish events
|
|
||||||
- All other Nostr protocol methods
|
|
||||||
|
|
||||||
#### Use Cases
|
|
||||||
|
|
||||||
**Single Relay (`nostr.relay()`):**
|
|
||||||
- Testing specific relay behavior
|
|
||||||
- Querying relay-specific content
|
|
||||||
- Debugging connectivity issues
|
|
||||||
- Working with specialized relays
|
|
||||||
|
|
||||||
**Relay Group (`nostr.group()`):**
|
|
||||||
- Querying from trusted relay sets
|
|
||||||
- Publishing to specific communities
|
|
||||||
- Load balancing across relay subsets
|
|
||||||
- Geographic relay optimization
|
|
||||||
|
|
||||||
**Default Pool (`nostr`):**
|
|
||||||
- General application queries
|
|
||||||
- Maximum reach for publishing
|
|
||||||
- Default user experience
|
|
||||||
- Simplified relay management
|
|
||||||
|
|
||||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||||
|
|
||||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||||
@@ -475,14 +289,15 @@ function usePosts() {
|
|||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ['posts'],
|
queryKey: ['posts'],
|
||||||
queryFn: async (c) => {
|
queryFn: async (c) => {
|
||||||
const events = await nostr.query([{ kinds: [1], limit: 20 }]);
|
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||||
|
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
|
||||||
return events; // these events could be transformed into another format
|
return events; // these events could be transformed into another format
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Efficient Query Design
|
#### Efficient Query Design
|
||||||
|
|
||||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||||
|
|
||||||
@@ -495,7 +310,7 @@ const events = await nostr.query([
|
|||||||
'#e': [eventId],
|
'#e': [eventId],
|
||||||
limit: 150,
|
limit: 150,
|
||||||
}
|
}
|
||||||
]);
|
], { signal });
|
||||||
|
|
||||||
// Separate by type in JavaScript
|
// Separate by type in JavaScript
|
||||||
const notes = events.filter((e) => e.kind === 1);
|
const notes = events.filter((e) => e.kind === 1);
|
||||||
@@ -507,9 +322,9 @@ const genericReposts = events.filter((e) => e.kind === 16);
|
|||||||
```typescript
|
```typescript
|
||||||
// This creates unnecessary load and can trigger rate limiting
|
// This creates unnecessary load and can trigger rate limiting
|
||||||
const [notes, reposts, genericReposts] = await Promise.all([
|
const [notes, reposts, genericReposts] = await Promise.all([
|
||||||
nostr.query([{ kinds: [1], '#e': [eventId] }]),
|
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
|
||||||
nostr.query([{ kinds: [6], '#e': [eventId] }]),
|
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
|
||||||
nostr.query([{ kinds: [16], '#e': [eventId] }]),
|
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
|
||||||
]);
|
]);
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -522,7 +337,7 @@ const [notes, reposts, genericReposts] = await Promise.all([
|
|||||||
|
|
||||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||||
|
|
||||||
### Event Validation
|
#### Event Validation
|
||||||
|
|
||||||
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
||||||
|
|
||||||
@@ -563,7 +378,8 @@ function useCalendarEvents() {
|
|||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ['calendar-events'],
|
queryKey: ['calendar-events'],
|
||||||
queryFn: async (c) => {
|
queryFn: async (c) => {
|
||||||
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }]);
|
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||||
|
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
|
||||||
|
|
||||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||||
return events.filter(validateCalendarEvent);
|
return events.filter(validateCalendarEvent);
|
||||||
@@ -592,7 +408,7 @@ function Post({ event }: { event: NostrEvent }) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### `NostrMetadata` type
|
#### `NostrMetadata` type
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
/** Kind 0 metadata. */
|
/** Kind 0 metadata. */
|
||||||
@@ -672,89 +488,23 @@ function MyComponent() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs and switching between accounts. It should not be wrapped in any conditional logic.
|
||||||
|
|
||||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
`LoginArea` displays a "Log in" button when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||||
|
|
||||||
**Important**: Social applications should include a profile menu button in the main interface (typically in headers/navigation) to provide access to account settings, profile editing, and logout functionality. Don't only show `LoginArea` in logged-out states.
|
|
||||||
|
|
||||||
### `npub`, `naddr`, and other Nostr addresses
|
### `npub`, `naddr`, and other Nostr addresses
|
||||||
|
|
||||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
Nostr defines a set identifiers in NIP-19. Their prefixes:
|
||||||
|
|
||||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
- `npub`: public keys
|
||||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
- `nsec`: private keys
|
||||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
- `note`: note ids
|
||||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
- `nprofile`: a nostr profile
|
||||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
- `nevent`: a nostr event
|
||||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
- `naddr`: a nostr replaceable event coordinate
|
||||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
- `nrelay`: a nostr relay (deprecated)
|
||||||
|
|
||||||
#### Key Differences Between Similar Identifiers
|
NIP-19 identifiers include a prefix, the number "1", then a base32-encoded data string.
|
||||||
|
|
||||||
**`note1` vs `nevent1`:**
|
|
||||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
|
||||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
|
||||||
- Use `note1` for simple references to text notes and threads
|
|
||||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
|
||||||
|
|
||||||
**`npub1` vs `nprofile1`:**
|
|
||||||
- `npub1`: Contains only the public key (32 bytes)
|
|
||||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
|
||||||
- Use `npub1` for simple user references
|
|
||||||
- Use `nprofile1` when you need to include relay hints or display name context
|
|
||||||
|
|
||||||
#### NIP-19 Routing Implementation
|
|
||||||
|
|
||||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
|
||||||
|
|
||||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
|
||||||
|
|
||||||
**How it works:**
|
|
||||||
|
|
||||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
|
||||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
|
||||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
|
||||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
|
||||||
- `note1`: Note section with placeholder for kind:1 text note view
|
|
||||||
- `nevent1`: Event section with placeholder for any event type view
|
|
||||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
|
||||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
|
||||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
|
||||||
|
|
||||||
**Example URLs that work automatically:**
|
|
||||||
- `/npub1abc123...` - User profile (needs implementation)
|
|
||||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
|
||||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
|
||||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
|
||||||
|
|
||||||
**Features included:**
|
|
||||||
- Basic NIP-19 identifier decoding and routing
|
|
||||||
- Type-specific sections for different identifier types
|
|
||||||
- Error handling for invalid identifiers
|
|
||||||
- Responsive container structure
|
|
||||||
- Comments indicating where to implement specific views
|
|
||||||
|
|
||||||
**Error handling:**
|
|
||||||
- Invalid NIP-19 format → 404 NotFound
|
|
||||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
|
||||||
- Empty or missing identifiers → 404 NotFound
|
|
||||||
|
|
||||||
To implement NIP-19 routing in your Nostr application:
|
|
||||||
|
|
||||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
|
||||||
2. **The route is already configured** in `AppRouter.tsx`
|
|
||||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
|
||||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
|
||||||
|
|
||||||
#### Event Type Distinctions
|
|
||||||
|
|
||||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
|
||||||
|
|
||||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
|
||||||
- The event is not a kind:1 text note
|
|
||||||
- You need to include relay hints for better discoverability
|
|
||||||
- You want to include author context
|
|
||||||
|
|
||||||
#### Use in Filters
|
#### Use in Filters
|
||||||
|
|
||||||
@@ -764,6 +514,7 @@ The base Nostr protocol uses hex string identifiers when filtering by event IDs
|
|||||||
// ❌ Wrong: naddr is not decoded
|
// ❌ Wrong: naddr is not decoded
|
||||||
const events = await nostr.query(
|
const events = await nostr.query(
|
||||||
[{ ids: [naddr] }],
|
[{ ids: [naddr] }],
|
||||||
|
{ signal }
|
||||||
);
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -791,23 +542,26 @@ const events = await nostr.query(
|
|||||||
authors: [naddr.pubkey],
|
authors: [naddr.pubkey],
|
||||||
'#d': [naddr.identifier],
|
'#d': [naddr.identifier],
|
||||||
}],
|
}],
|
||||||
|
{ signal }
|
||||||
);
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Implementation Guidelines
|
#### Use in URL Paths
|
||||||
|
|
||||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
For URL routing, use NIP-19 identifiers as path parameters (e.g., `/:nip19`) to create secure, universal links to Nostr events. Decode the identifier and render the appropriate component based on the type:
|
||||||
2. **Use the appropriate identifier type** based on your needs:
|
|
||||||
- Use `note1` for kind:1 text notes specifically
|
- Regular events: Use `/nevent1...` paths
|
||||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
- Replaceable/addressable events: Use `/naddr1...` paths
|
||||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
|
||||||
3. **Handle different identifier types** appropriately:
|
Always use `naddr` identifiers for addressable events instead of just the `d` tag value, as `naddr` contains the author pubkey needed to create secure filters. This prevents security issues where malicious actors could publish events with the same `d` tag to override content.
|
||||||
- `npub1`/`nprofile1`: Display user profiles
|
|
||||||
- `note1`: Display kind:1 text notes specifically
|
```ts
|
||||||
- `nevent1`: Display any event with optional relay context
|
// Secure routing with naddr
|
||||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
const decoded = nip19.decode(params.nip19);
|
||||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
if (decoded.type === 'naddr' && decoded.data.kind === 30024) {
|
||||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
// Render ArticlePage component
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Nostr Edit Profile
|
### Nostr Edit Profile
|
||||||
|
|
||||||
@@ -897,46 +651,16 @@ export function Post(/* ...props */) {
|
|||||||
|
|
||||||
## App Configuration
|
## App Configuration
|
||||||
|
|
||||||
The project includes an `AppProvider` that manages global application state including theme and NIP-65 relay configuration. The default configuration includes:
|
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
const defaultConfig: AppConfig = {
|
const defaultConfig: AppConfig = {
|
||||||
theme: "light",
|
theme: "light",
|
||||||
relayMetadata: {
|
relayUrl: "wss://relay.nostr.band",
|
||||||
relays: [
|
|
||||||
{ url: 'wss://relay.ditto.pub', read: true, write: true },
|
|
||||||
{ url: 'wss://relay.primal.net', read: true, write: true },
|
|
||||||
{ url: 'wss://relay.damus.io', read: true, write: true },
|
|
||||||
],
|
|
||||||
updatedAt: 0,
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
The app uses NIP-65 compatible relay management with automatic sync when users log in. Local storage persists user preferences and relay configurations.
|
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||||
|
|
||||||
### Relay Management
|
|
||||||
|
|
||||||
The project includes a complete NIP-65 relay management system:
|
|
||||||
|
|
||||||
- **RelayListManager**: Component for managing multiple relays with read/write permissions
|
|
||||||
- **NostrSync**: Automatically syncs user's NIP-65 relay list when they log in
|
|
||||||
- **Automatic Publishing**: Changes to relay configuration are automatically published as NIP-65 events when the user is logged in
|
|
||||||
|
|
||||||
Use the `RelayListManager` component to provide relay management interfaces:
|
|
||||||
|
|
||||||
```tsx
|
|
||||||
import { RelayListManager } from '@/components/RelayListManager';
|
|
||||||
|
|
||||||
function SettingsPage() {
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<h2>Relay Settings</h2>
|
|
||||||
<RelayListManager />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Routing
|
## Routing
|
||||||
|
|
||||||
@@ -990,9 +714,10 @@ The router includes automatic scroll-to-top functionality and a 404 NotFound pag
|
|||||||
|
|
||||||
### Empty States and No Content Found
|
### Empty States and No Content Found
|
||||||
|
|
||||||
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with helpful messaging. The application uses NIP-65 relay management, so users can manage their relays through the settings or relay management interface.
|
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
|
import { RelaySelector } from '@/components/RelaySelector';
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
|
||||||
// Empty state example
|
// Empty state example
|
||||||
@@ -1001,74 +726,37 @@ import { Card, CardContent } from '@/components/ui/card';
|
|||||||
<CardContent className="py-12 px-8 text-center">
|
<CardContent className="py-12 px-8 text-center">
|
||||||
<div className="max-w-sm mx-auto space-y-6">
|
<div className="max-w-sm mx-auto space-y-6">
|
||||||
<p className="text-muted-foreground">
|
<p className="text-muted-foreground">
|
||||||
No results found. Try checking your relay connections or wait a moment for content to load.
|
No results found. Try another relay?
|
||||||
</p>
|
</p>
|
||||||
|
<RelaySelector className="w-full" />
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
```
|
```
|
||||||
|
|
||||||
## CRITICAL Design Standards
|
## Design Customization
|
||||||
|
|
||||||
- Create breathtaking, immersive designs that feel like bespoke masterpieces, rivaling the polish of Apple, Stripe, or luxury brands
|
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||||
- Designs must be production-ready, fully featured, with no placeholders unless explicitly requested, ensuring every element serves a functional and aesthetic purpose
|
|
||||||
- Avoid generic or templated aesthetics at all costs; every design must have a unique, brand-specific visual signature that feels custom-crafted
|
|
||||||
- Headers must be dynamic, immersive, and storytelling-driven, using layered visuals, motion, and symbolic elements to reflect the brand’s identity—never use simple “icon and text” combos
|
|
||||||
- Incorporate purposeful, lightweight animations for scroll reveals, micro-interactions (e.g., hover, click, transitions), and section transitions to create a sense of delight and fluidity
|
|
||||||
|
|
||||||
### Design Principles
|
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
|
||||||
|
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
|
||||||
- Achieve Apple-level refinement with meticulous attention to detail, ensuring designs evoke strong emotions (e.g., wonder, inspiration, energy) through color, motion, and composition
|
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
|
||||||
- Deliver fully functional interactive components with intuitive feedback states, ensuring every element has a clear purpose and enhances user engagement
|
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
|
||||||
- **Generate custom images liberally** when image generation tools are available - this is ALWAYS preferred over stock photography for creating unique, brand-specific visuals that perfectly match the design intent
|
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
|
||||||
- Ensure designs feel alive and modern with dynamic elements like gradients, glows, or parallax effects, avoiding static or flat aesthetics
|
|
||||||
- Before finalizing, ask: "Would this design make Apple or Stripe designers pause and take notice?" If not, iterate until it does
|
|
||||||
|
|
||||||
### Avoid Generic Design
|
|
||||||
|
|
||||||
- No basic layouts (e.g., text-on-left, image-on-right) without significant custom polish, such as dynamic backgrounds, layered visuals, or interactive elements
|
|
||||||
- No simplistic headers; they must be immersive, animated, and reflective of the brand’s core identity and mission
|
|
||||||
- No designs that could be mistaken for free templates or overused patterns; every element must feel intentional and tailored
|
|
||||||
|
|
||||||
### Interaction Patterns
|
|
||||||
|
|
||||||
- Use progressive disclosure for complex forms or content to guide users intuitively and reduce cognitive load
|
|
||||||
- Incorporate contextual menus, smart tooltips, and visual cues to enhance navigation and usability
|
|
||||||
- Implement drag-and-drop, hover effects, and transitions with clear, dynamic visual feedback to elevate the user experience
|
|
||||||
- Support power users with keyboard shortcuts, ARIA labels, and focus states for accessibility and efficiency
|
|
||||||
- Add subtle parallax effects or scroll-triggered animations to create depth and engagement without overwhelming the user
|
|
||||||
|
|
||||||
### Technical Requirements
|
|
||||||
|
|
||||||
- Curated color FRpalette (3-5 evocative colors + neutrals) that aligns with the brand’s emotional tone and creates a memorable impact
|
|
||||||
- Ensure a minimum 4.5:1 contrast ratio for all text and interactive elements to meet accessibility standards
|
|
||||||
- Use expressive, readable fonts (18px+ for body text, 40px+ for headlines) with a clear hierarchy; pair a modern sans-serif (e.g., Inter) with an elegant serif (e.g., Playfair Display) for personality
|
|
||||||
- Design for full responsiveness, ensuring flawless performance and aesthetics across all screen sizes (mobile, tablet, desktop)
|
|
||||||
- Adhere to WCAG 2.1 AA guidelines, including keyboard navigation, screen reader support, and reduced motion options
|
|
||||||
- Follow an 8px grid system for consistent spacing, padding, and alignment to ensure visual harmony
|
|
||||||
- Add depth with subtle shadows, gradients, glows, and rounded corners (e.g., 16px radius) to create a polished, modern aesthetic
|
|
||||||
- Optimize animations and interactions to be lightweight and performant, ensuring smooth experiences across devices
|
|
||||||
|
|
||||||
### Components
|
|
||||||
|
|
||||||
- Design reusable, modular components with consistent styling, behavior, and feedback states (e.g., hover, active, focus, error)
|
|
||||||
- Include purposeful animations (e.g., scale-up on hover, fade-in on scroll) to guide attention and enhance interactivity without distraction
|
|
||||||
- Ensure full accessibility support with keyboard navigation, ARIA labels, and visible focus states (e.g., a glowing outline in an accent color)
|
|
||||||
- Use custom icons or illustrations for components to reinforce the brand’s visual identity
|
|
||||||
|
|
||||||
### Adding Fonts
|
### Adding Fonts
|
||||||
|
|
||||||
To add custom fonts, follow these steps:
|
To add custom fonts, follow these steps:
|
||||||
|
|
||||||
1. **Install a font package** using npm:
|
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||||
|
|
||||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||||
- For Inter Variable: `@fontsource-variable/inter`
|
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||||
- For Roboto: `@fontsource/roboto`
|
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||||
- For Outfit Variable: `@fontsource-variable/outfit`
|
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||||
- For Poppins: `@fontsource/poppins`
|
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||||
- For Open Sans: `@fontsource/open-sans`
|
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||||
|
|
||||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||||
|
|
||||||
@@ -1120,34 +808,10 @@ When users specify color schemes:
|
|||||||
- Follow shadcn/ui patterns for component variants
|
- Follow shadcn/ui patterns for component variants
|
||||||
- Implement responsive design with Tailwind breakpoints
|
- Implement responsive design with Tailwind breakpoints
|
||||||
- Add hover and focus states for interactive elements
|
- Add hover and focus states for interactive elements
|
||||||
- When using negative z-index (e.g., `-z-10`) for background images or decorative elements, **always add `isolate` to the parent container** to create a local stacking context. Without `isolate`, negative z-index pushes elements behind the page's background color, making them invisible.
|
|
||||||
|
|
||||||
## Writing Tests vs Running Tests
|
## Writing Tests
|
||||||
|
|
||||||
There is an important distinction between **writing new tests** and **running existing tests**:
|
**Important for AI Assistants**: Only create tests when the user is experiencing a specific problem or explicitly requests tests. Do not proactively write tests for new features or components unless the user is having issues that require testing to diagnose or resolve.
|
||||||
|
|
||||||
### Writing Tests (Creating New Test Files)
|
|
||||||
|
|
||||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
|
||||||
|
|
||||||
1. **The user explicitly asks for tests** to be written in their message
|
|
||||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
|
||||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
|
||||||
|
|
||||||
**Never write tests because:**
|
|
||||||
- Tool results show test failures (these are not user requests)
|
|
||||||
- You think tests would be helpful
|
|
||||||
- New features or components are created
|
|
||||||
- Existing functionality needs verification
|
|
||||||
|
|
||||||
### Running Tests (Executing the Test Suite)
|
|
||||||
|
|
||||||
**ALWAYS run the test script** after making any code changes. This is mandatory regardless of whether you wrote new tests or not.
|
|
||||||
|
|
||||||
- **You must run the test script** to validate your changes
|
|
||||||
- **Your task is not complete** until the test script passes without errors
|
|
||||||
- **This applies to all changes** - bug fixes, new features, refactoring, or any code modifications
|
|
||||||
- **The test script includes** TypeScript compilation, ESLint checks, and existing test validation
|
|
||||||
|
|
||||||
### Test Setup
|
### Test Setup
|
||||||
|
|
||||||
@@ -1178,32 +842,8 @@ describe('MyComponent', () => {
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
## Validating Your Changes
|
## Testing Your Changes
|
||||||
|
|
||||||
**CRITICAL**: After making any code changes, you must validate your work by running available validation tools.
|
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||||
|
|
||||||
**Your task is not considered finished until the code successfully type-checks and builds without errors.**
|
**Your task is not considered finished until this test passes without errors.**
|
||||||
|
|
||||||
### Validation Priority Order
|
|
||||||
|
|
||||||
Run available tools in this priority order:
|
|
||||||
|
|
||||||
1. **Type Checking** (Required): Ensure TypeScript compilation succeeds
|
|
||||||
2. **Building/Compilation** (Required): Verify the project builds successfully
|
|
||||||
3. **Linting** (Recommended): Check code style and catch potential issues
|
|
||||||
4. **Tests** (If Available): Run existing test suite
|
|
||||||
5. **Git Commit** (Required): Create a commit with your changes when finished
|
|
||||||
|
|
||||||
**Minimum Requirements:**
|
|
||||||
- Code must type-check without errors
|
|
||||||
- Code must build/compile successfully
|
|
||||||
- Fix any critical linting errors that would break functionality
|
|
||||||
- Create a git commit when your changes are complete
|
|
||||||
|
|
||||||
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
|
|
||||||
|
|
||||||
### Using Git
|
|
||||||
|
|
||||||
If git is available in your environment (through a `shell` tool, or other git-specific tools), you should utilize `git log` to understand project history. Use `git status` and `git diff` to check the status of your changes, and if you make a mistake use `git checkout` to restore files.
|
|
||||||
|
|
||||||
When your changes are complete and validated, create a git commit with a descriptive message summarizing your changes.
|
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
# NIP-GNOME: Gnome Speak Translation Protocol
|
||||||
|
|
||||||
|
`draft` `optional`
|
||||||
|
|
||||||
|
## Abstract
|
||||||
|
|
||||||
|
This NIP defines a client-side translation protocol for converting kind 1 (Short Text Note) events into "Gnome Speak" - a whimsical fantasy language that transforms regular text into gnome-themed vocabulary and expressions.
|
||||||
|
|
||||||
|
## Motivation
|
||||||
|
|
||||||
|
To create an immersive and entertaining experience for users of gnome-themed Nostr clients, where all text content is automatically translated into a consistent fantasy language that maintains readability while adding magical woodland charm.
|
||||||
|
|
||||||
|
## Specification
|
||||||
|
|
||||||
|
### Translation Scope
|
||||||
|
|
||||||
|
- **MUST** translate all kind 1 events (Short Text Notes) into Gnome Speak
|
||||||
|
- **SHOULD NOT** translate other event kinds to maintain protocol compatibility
|
||||||
|
- **MUST** preserve original URLs, Nostr references (npub, note, etc.), and hashtags without translation
|
||||||
|
- **SHOULD** maintain the semantic meaning of the original text
|
||||||
|
|
||||||
|
### Translation Rules
|
||||||
|
|
||||||
|
#### Vocabulary Substitution
|
||||||
|
|
||||||
|
Common words are replaced with gnome-themed equivalents:
|
||||||
|
|
||||||
|
- Greetings: `hello` → `greetings, fellow earth-dweller`
|
||||||
|
- Technology: `computer` → `thinking-box of metal and magic`
|
||||||
|
- Time: `today` → `this blessed sun-cycle`
|
||||||
|
- Actions: `go` → `venture forth`
|
||||||
|
- People: `friend` → `companion of the woodland path`
|
||||||
|
|
||||||
|
#### Gnome Expressions
|
||||||
|
|
||||||
|
- Exclamations are enhanced with gnome phrases: `!` → `! By my pointy hat!`
|
||||||
|
- Sentence starters may be added: `In the sacred grove, ...`
|
||||||
|
- Sentence endings may be appended: `...as the ancients foretold.`
|
||||||
|
|
||||||
|
#### Special Formatting
|
||||||
|
|
||||||
|
- Bitcoin/crypto terms: `bitcoin` → `✨golden acorns of the digital realm✨`
|
||||||
|
- Nostr terms: `nostr` → `🍄message-mushroom🍄`
|
||||||
|
- Greetings: `gm` → `🌅when dew kisses the earth🌅`
|
||||||
|
|
||||||
|
### Implementation
|
||||||
|
|
||||||
|
#### Client Behavior
|
||||||
|
|
||||||
|
Clients implementing this NIP:
|
||||||
|
|
||||||
|
1. **MUST** detect kind 1 events
|
||||||
|
2. **MUST** apply Gnome Speak translation before displaying content
|
||||||
|
3. **SHOULD** preserve original content for editing/replying
|
||||||
|
4. **MAY** provide toggle to view original content
|
||||||
|
5. **SHOULD** indicate when content has been translated
|
||||||
|
|
||||||
|
#### Content Preservation
|
||||||
|
|
||||||
|
- Original event content **MUST** remain unchanged in storage/transmission
|
||||||
|
- Translation occurs only at display time
|
||||||
|
- Replies and quotes **SHOULD** reference original content, not translated
|
||||||
|
|
||||||
|
#### Tag Usage
|
||||||
|
|
||||||
|
Clients **MAY** add a `t` tag with value `gnome` to indicate gnome-themed content:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"kind": 1,
|
||||||
|
"content": "Hello world!",
|
||||||
|
"tags": [["t", "gnome"]],
|
||||||
|
...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Example
|
||||||
|
|
||||||
|
Original event:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"kind": 1,
|
||||||
|
"content": "Good morning! Having coffee and checking bitcoin prices.",
|
||||||
|
"tags": [],
|
||||||
|
...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Displayed as:
|
||||||
|
```
|
||||||
|
"When dew kisses the earth! Partaking of bitter bean brew and witnessing ✨golden acorns of the digital realm✨ values, blessed by the forest spirits."
|
||||||
|
```
|
||||||
|
|
||||||
|
## Rationale
|
||||||
|
|
||||||
|
This approach provides:
|
||||||
|
|
||||||
|
1. **Immersive Experience**: Creates a consistent fantasy atmosphere
|
||||||
|
2. **Protocol Compatibility**: No changes to underlying Nostr protocol
|
||||||
|
3. **Reversibility**: Original content always preserved
|
||||||
|
4. **Interoperability**: Non-gnome clients display original content normally
|
||||||
|
|
||||||
|
## Security Considerations
|
||||||
|
|
||||||
|
- Translation is purely cosmetic and doesn't affect event integrity
|
||||||
|
- Original content validation remains unchanged
|
||||||
|
- No additional attack vectors introduced
|
||||||
|
|
||||||
|
## Implementation Status
|
||||||
|
|
||||||
|
This NIP is implemented in Gnome Nostr client as a client-side translation layer.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- [NIP-01: Basic protocol flow description](https://github.com/nostr-protocol/nips/blob/master/01.md)
|
||||||
|
- [NIP-10: Text Notes and Threads](https://github.com/nostr-protocol/nips/blob/master/10.md)
|
||||||
@@ -1,238 +1,79 @@
|
|||||||
# MKStack
|
# 🍄 Gnome Nostr - The Sacred Network of Woodland Folk
|
||||||
|
|
||||||
**The Complete Framework for Building Nostr Clients with AI**
|
A magical Nostr client where all text notes (kind 1 events) are automatically translated into the ancient gnome tongue! Connect with fellow earth-dwellers across the message-mushroom network.
|
||||||
|
|
||||||
MKStack is an AI-powered framework for building Nostr applications with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify. Build powerful Nostr applications with AI-first development - from social feeds to private messaging, MKStack provides everything you need to create decentralized apps on the Nostr protocol.
|
## ✨ Features
|
||||||
|
|
||||||
## 🚀 Quick Start
|
- **🍄 Gnome Speak Translation**: All kind 1 events are automatically translated into whimsical gnome language
|
||||||
|
- **🌲 Forest-Themed UI**: Beautiful gnome-inspired design with earthy colors and woodland aesthetics
|
||||||
|
- **🔗 Full Nostr Compatibility**: Works with any Nostr relay and preserves all protocol functionality
|
||||||
|
- **📱 Responsive Design**: Works perfectly on desktop and mobile devices
|
||||||
|
- **🌙 Dark/Light Mode**: Toggle between day forest and night forest themes
|
||||||
|
- **⚡ Lightning Fast**: Built with modern React, Vite, and TailwindCSS
|
||||||
|
|
||||||
Build your Nostr app in 3 simple steps:
|
## 🎭 Gnome Speak Examples
|
||||||
|
|
||||||
### 1. Install & Create
|
Regular text is magically transformed:
|
||||||
```bash
|
|
||||||
npm install -g @getstacks/stacks
|
|
||||||
stacks mkstack
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. Build with AI
|
- `"Hello world!"` → `"Greetings, fellow earth-dweller world! By my pointy hat!"`
|
||||||
```bash
|
- `"Good morning everyone"` → `"🌅When dew kisses the earth🌅 all forest folk"`
|
||||||
stacks agent
|
- `"I love bitcoin"` → `"I cherish like precious gems ✨golden acorns of the digital realm✨"`
|
||||||
# Tell Dork AI what you want: "Build a group chat application"
|
- `"This is about #nostr"` → `"This is a woodland proclamation about #nostr"` (hashtags preserved)
|
||||||
```
|
|
||||||
|
|
||||||
### 3. Deploy Instantly
|
## 🛡️ Protocol Preservation
|
||||||
```bash
|
|
||||||
npm run deploy
|
|
||||||
# ✅ App deployed to NostrDeploy.com!
|
|
||||||
```
|
|
||||||
|
|
||||||
## ✨ What Makes MKStack Special
|
While the display is transformed into gnome speak, the underlying Nostr protocol remains unchanged:
|
||||||
|
|
||||||
- **🤖 AI-First Development**: Build complete Nostr apps with just one prompt using Dork AI agent
|
- ✅ URLs are preserved and linkified
|
||||||
- **⚡ 8 Minutes Average**: From idea to deployed application in minutes, not months
|
- ✅ Nostr references (npub, note, etc.) work normally
|
||||||
- **🔗 50+ NIPs Supported**: Comprehensive Nostr protocol implementation
|
- ✅ Hashtags remain functional for filtering
|
||||||
- **🎨 Beautiful UI**: 48+ shadcn/ui components with light/dark theme support
|
- ✅ Original content is preserved for replies and quotes
|
||||||
- **🔐 Built-in Security**: NIP-07 browser signing, NIP-44 encryption, event validation
|
- ✅ Compatible with all other Nostr clients
|
||||||
- **💰 Payments Ready**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Wallet Connect (NIP-47)
|
|
||||||
- **📱 Production Ready**: TypeScript, testing, deployment, and responsive design included
|
|
||||||
|
|
||||||
## 🛠 Technology Stack
|
## 🏗️ Technical Details
|
||||||
|
|
||||||
- **React 18.x**: Stable version with hooks, concurrent rendering, and improved performance
|
- **Framework**: React 18 with TypeScript
|
||||||
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
|
- **Styling**: TailwindCSS with custom gnome theme
|
||||||
- **Vite**: Fast build tool and development server
|
- **Nostr**: Nostrify for protocol integration
|
||||||
- **shadcn/ui**: 48+ unstyled, accessible UI components built with Radix UI
|
- **Font**: Comfortaa Variable for whimsical feel
|
||||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
- **Build**: Vite for fast development and production builds
|
||||||
- **React Router**: Client-side routing with BrowserRouter
|
|
||||||
- **TanStack Query**: Data fetching, caching, and state management
|
|
||||||
- **TypeScript**: Type-safe JavaScript development
|
|
||||||
|
|
||||||
## 🎯 Real-World Examples
|
## 🌟 Custom NIP
|
||||||
|
|
||||||
### Built with One Prompt
|
This client implements a custom translation protocol documented in `NIP.md`. The translation:
|
||||||
|
|
||||||
Each of these applications was created with just a single prompt to Dork AI:
|
- Only affects kind 1 events (Short Text Notes)
|
||||||
|
- Preserves URLs, Nostr references, and hashtags
|
||||||
|
- Maintains semantic meaning while adding magical charm
|
||||||
|
- Is purely client-side - no protocol changes required
|
||||||
|
|
||||||
- **Group Chat Application**: `"Build me a group chat application"`
|
## 🚀 Getting Started
|
||||||
- [Live Demo](https://groupchat-74z9j26wq-mks-projects-1f1254c4.vercel.app/)
|
|
||||||
|
|
||||||
- **Decentralized Goodreads**: `"Build a decentralized goodreads alternative. Use OpenLibrary API for book data."`
|
1. **Clone the repository**
|
||||||
- [Live Demo](https://bookstr123-87phkwjcy-mks-projects-1f1254c4.vercel.app/)
|
2. **Install dependencies**: `npm install`
|
||||||
|
3. **Start development**: `npm run dev`
|
||||||
|
4. **Build for production**: `npm run build`
|
||||||
|
|
||||||
- **Chess Game**: `"Build a chess game with NIP 64"`
|
## 🎨 Customization
|
||||||
- [Live Demo](https://chess-l0d7ms7m3-mks-projects-1f1254c4.vercel.app/chess)
|
|
||||||
|
|
||||||
### Production Apps
|
The gnome vocabulary can be extended in `src/lib/gnomeSpeak.ts`. Add new word mappings to enhance the magical transformation!
|
||||||
|
|
||||||
Real Nostr applications built using MKStack:
|
|
||||||
|
|
||||||
- **[Chorus](https://chorus.community/)**: Facebook-style groups on Nostr with built-in eCash wallet
|
|
||||||
- **[Blobbi](https://www.blobbi.pet/)**: Digital pet companions that live forever on the decentralized web
|
|
||||||
- **[Treasures](https://treasures.to/)**: Decentralized geocaching adventure powered by Nostr
|
|
||||||
|
|
||||||
[Browse more apps made with MKStack →](https://nostrhub.io/apps/t/mkstack/)
|
|
||||||
|
|
||||||
## 🔧 Core Features
|
|
||||||
|
|
||||||
### Authentication & Users
|
|
||||||
- `LoginArea` component with account switching
|
|
||||||
- `useCurrentUser` hook for authentication state
|
|
||||||
- `useAuthor` hook for fetching user profiles
|
|
||||||
- NIP-07 browser signing support
|
|
||||||
- Multi-account management
|
|
||||||
|
|
||||||
### Nostr Protocol Support
|
|
||||||
- **Social Features**: User profiles (NIP-01), follow lists (NIP-02), reactions (NIP-25), reposts (NIP-18)
|
|
||||||
- **Messaging**: Private DMs (NIP-17), public chat (NIP-28), group chat (NIP-29), encryption (NIP-44)
|
|
||||||
- **Payments**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Nutzaps (NIP-61), Wallet Connect (NIP-47)
|
|
||||||
- **Content**: Long-form articles (NIP-23), file metadata (NIP-94), live events (NIP-53), calendars (NIP-52)
|
|
||||||
|
|
||||||
### Data Management
|
|
||||||
- `useNostr` hook for querying and publishing
|
|
||||||
- `useNostrPublish` hook with automatic client tagging
|
|
||||||
- Event validation and filtering
|
|
||||||
- Infinite scroll with TanStack Query
|
|
||||||
- Multi-relay support
|
|
||||||
|
|
||||||
### UI Components
|
|
||||||
- 48+ shadcn/ui components (buttons, forms, dialogs, etc.)
|
|
||||||
- `NoteContent` component for rich text rendering
|
|
||||||
- `EditProfileForm` for profile management
|
|
||||||
- `RelaySelector` for relay switching
|
|
||||||
- `CommentsSection` for threaded discussions
|
|
||||||
- Light/dark theme system
|
|
||||||
|
|
||||||
### Media & Files
|
|
||||||
- `useUploadFile` hook with Blossom server integration
|
|
||||||
- NIP-94 compatible file metadata
|
|
||||||
- Image and video support
|
|
||||||
- File attachment to events
|
|
||||||
|
|
||||||
### Advanced Features
|
|
||||||
- NIP-19 identifier routing (`npub1`, `note1`, `nevent1`, `naddr1`)
|
|
||||||
- Cryptographic operations (encryption/decryption)
|
|
||||||
- Lightning payments and zaps
|
|
||||||
- Real-time event subscriptions
|
|
||||||
- Responsive design with mobile support
|
|
||||||
|
|
||||||
## 🤖 AI Development with Dork
|
|
||||||
|
|
||||||
MKStack includes Dork, a built-in AI agent that understands your codebase and Nostr protocols:
|
|
||||||
|
|
||||||
### Supported AI Providers
|
|
||||||
|
|
||||||
Configure your AI provider with `stacks configure`:
|
|
||||||
|
|
||||||
- **OpenRouter** ([openrouter.ai](https://openrouter.ai/)): Enter your API key from settings
|
|
||||||
- **Routstr** ([routstr.com](https://www.routstr.com/)): Use Cashu tokens for payment
|
|
||||||
- **PayPerQ** ([ppq.ai](https://ppq.ai/)): OpenAI-compatible API
|
|
||||||
|
|
||||||
### How Dork Works
|
|
||||||
|
|
||||||
- **Context-Aware**: Understands your entire codebase and project structure
|
|
||||||
- **Nostr Expert**: Built-in knowledge of 50+ NIPs and best practices
|
|
||||||
- **Instant Implementation**: Makes changes directly to your code following React/TypeScript best practices
|
|
||||||
|
|
||||||
Example prompts:
|
|
||||||
```bash
|
|
||||||
"Add user profiles with avatars and bio"
|
|
||||||
"Implement NIP-17 private messaging"
|
|
||||||
"Add a dark mode toggle"
|
|
||||||
"Create a marketplace with NIP-15"
|
|
||||||
```
|
|
||||||
|
|
||||||
## 📁 Project Structure
|
|
||||||
|
|
||||||
```
|
|
||||||
src/
|
|
||||||
├── components/ # UI components
|
|
||||||
│ ├── ui/ # shadcn/ui components (48+ available)
|
|
||||||
│ ├── auth/ # Authentication components
|
|
||||||
│ └── comments/ # Comment system components
|
|
||||||
├── hooks/ # Custom React hooks
|
|
||||||
│ ├── useNostr # Core Nostr integration
|
|
||||||
│ ├── useAuthor # User profile data
|
|
||||||
│ ├── useCurrentUser # Authentication state
|
|
||||||
│ ├── useNostrPublish # Event publishing
|
|
||||||
│ ├── useUploadFile # File uploads
|
|
||||||
│ └── useZaps # Lightning payments
|
|
||||||
├── pages/ # Page components
|
|
||||||
├── lib/ # Utility functions
|
|
||||||
├── contexts/ # React context providers
|
|
||||||
└── test/ # Testing utilities
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🎨 UI Components
|
|
||||||
|
|
||||||
MKStack includes 48+ shadcn/ui components:
|
|
||||||
|
|
||||||
**Layout**: Card, Separator, Sheet, Sidebar, ScrollArea, Resizable
|
|
||||||
**Navigation**: Breadcrumb, NavigationMenu, Menubar, Tabs, Pagination
|
|
||||||
**Forms**: Button, Input, Textarea, Select, Checkbox, RadioGroup, Switch, Slider
|
|
||||||
**Feedback**: Alert, AlertDialog, Toast, Progress, Skeleton
|
|
||||||
**Overlay**: Dialog, Popover, HoverCard, Tooltip, ContextMenu, DropdownMenu
|
|
||||||
**Data Display**: Table, Avatar, Badge, Calendar, Chart, Carousel
|
|
||||||
**And many more...
|
|
||||||
|
|
||||||
## 🔐 Security & Best Practices
|
|
||||||
|
|
||||||
- **Never use `any` type**: Always use proper TypeScript types
|
|
||||||
- **Event validation**: Filter events through validator functions for custom kinds
|
|
||||||
- **Efficient queries**: Minimize separate queries to avoid rate limiting
|
|
||||||
- **Proper error handling**: Graceful handling of invalid NIP-19 identifiers
|
|
||||||
- **Secure authentication**: Use signer interface, never request private keys directly
|
|
||||||
|
|
||||||
## 📱 Responsive Design
|
|
||||||
|
|
||||||
- Mobile-first approach with Tailwind breakpoints
|
|
||||||
- `useIsMobile` hook for responsive behavior
|
|
||||||
- Touch-friendly interactions
|
|
||||||
- Optimized for all screen sizes
|
|
||||||
|
|
||||||
## 🧪 Testing
|
|
||||||
|
|
||||||
- Vitest with jsdom environment
|
|
||||||
- React Testing Library with jest-dom matchers
|
|
||||||
- `TestApp` component provides all necessary context providers
|
|
||||||
- Mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
|
||||||
|
|
||||||
## 🚀 Deployment
|
|
||||||
|
|
||||||
Built-in deployment to NostrDeploy.com:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm run deploy
|
|
||||||
```
|
|
||||||
|
|
||||||
Your app goes live instantly with:
|
|
||||||
- Automatic builds
|
|
||||||
- CDN distribution
|
|
||||||
- HTTPS support
|
|
||||||
- Custom domains available
|
|
||||||
|
|
||||||
## 📚 Documentation
|
|
||||||
|
|
||||||
For detailed documentation on building Nostr applications with MKStack:
|
|
||||||
|
|
||||||
- [Tutorial](https://soapbox.pub/blog/mkstack-tutorial)
|
|
||||||
- [Nostr Protocol Documentation](https://nostr.com)
|
|
||||||
- [shadcn/ui Components](https://ui.shadcn.com)
|
|
||||||
|
|
||||||
## 🤝 Contributing
|
## 🤝 Contributing
|
||||||
|
|
||||||
MKStack is open source and welcomes contributions. The framework is designed to be:
|
Contributions are welcome! Whether you want to:
|
||||||
|
- Add more gnome vocabulary
|
||||||
|
- Improve the forest-themed UI
|
||||||
|
- Fix bugs or add features
|
||||||
|
- Enhance the translation algorithm
|
||||||
|
|
||||||
- **Extensible**: Easy to add new NIPs and features
|
Feel free to open issues and pull requests.
|
||||||
- **Maintainable**: Clean architecture with TypeScript
|
|
||||||
- **Testable**: Comprehensive testing setup included
|
|
||||||
- **Documented**: Clear patterns and examples
|
|
||||||
|
|
||||||
## 📄 License
|
## 📜 License
|
||||||
|
|
||||||
Open source - build amazing Nostr applications and help grow the decentralized web!
|
This project is open source and available under the MIT License.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**"Vibed with MKStack"** - [Learn more about MKStack](https://soapbox.pub/mkstack)
|
*Vibed with [MKStack](https://soapbox.pub/mkstack) • Blessed by the forest spirits 🍄✨*
|
||||||
|
|
||||||
*Build your Nostr app in minutes, not months. Start with AI, deploy instantly.*
|
**May your mushrooms grow tall and your acorns be golden!** 🌰✨
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"model": "claude-sonnet-4",
|
||||||
|
"temperature": 0.2,
|
||||||
|
"mcpServers": {
|
||||||
|
"js-dev": {
|
||||||
|
"type": "stdio",
|
||||||
|
"command": "npx",
|
||||||
|
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
|
||||||
|
},
|
||||||
|
"nostr": {
|
||||||
|
"type": "stdio",
|
||||||
|
"command": "npx",
|
||||||
|
"args": ["-y", "@nostrbook/mcp@latest"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,6 +17,7 @@ export default tseslint.config(
|
|||||||
globals: globals.browser,
|
globals: globals.browser,
|
||||||
},
|
},
|
||||||
linterOptions: {
|
linterOptions: {
|
||||||
|
noInlineConfig: true, // Prevents all eslint-disable comments
|
||||||
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
|
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
|
||||||
},
|
},
|
||||||
plugins: {
|
plugins: {
|
||||||
|
|||||||
@@ -4,6 +4,11 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||||
|
<title>Gnome Nostr - The Sacred Network of Woodland Folk</title>
|
||||||
|
<meta name="description" content="A magical Nostr client where all messages are translated into the ancient gnome tongue. Connect with fellow earth-dwellers across the message-mushroom network!">
|
||||||
|
<meta property="og:type" content="website">
|
||||||
|
<meta property="og:title" content="Gnome Nostr - The Sacred Network of Woodland Folk">
|
||||||
|
<meta property="og:description" content="A magical Nostr client where all messages are translated into the ancient gnome tongue. Connect with fellow earth-dwellers across the message-mushroom network!">
|
||||||
<link rel="manifest" href="/manifest.webmanifest">
|
<link rel="manifest" href="/manifest.webmanifest">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
{
|
|
||||||
"$schema": "https://opencode.ai/config.json",
|
|
||||||
"mcp": {
|
|
||||||
"nostr": {
|
|
||||||
"type": "local",
|
|
||||||
"command": ["npx", "-y", "@nostrbook/mcp@latest"]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Generated
+405
-661
File diff suppressed because it is too large.
Load diff
+13
-17
@@ -4,16 +4,16 @@
|
|||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "npm i --silent && vite",
|
"dev": "npm i && vite",
|
||||||
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
|
"build": "npm i && vite build && cp dist/index.html dist/404.html",
|
||||||
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'"
|
"test": "npm i && tsc -p tsconfig.app.json --noEmit && eslint && vitest run && vite build",
|
||||||
|
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fontsource-variable/inter": "^5.2.6",
|
"@fontsource-variable/comfortaa": "^5.2.6",
|
||||||
"@getalby/sdk": "^7.0.0",
|
"@hookform/resolvers": "^3.9.0",
|
||||||
"@hookform/resolvers": "^5.2.2",
|
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.1",
|
||||||
"@nostrify/nostrify": "^0.49.2",
|
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.5",
|
||||||
"@nostrify/react": "^0.2.24",
|
|
||||||
"@radix-ui/react-accordion": "^1.2.0",
|
"@radix-ui/react-accordion": "^1.2.0",
|
||||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||||
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
||||||
@@ -44,29 +44,27 @@
|
|||||||
"@tanstack/react-query": "^5.56.2",
|
"@tanstack/react-query": "^5.56.2",
|
||||||
"@unhead/addons": "^2.0.10",
|
"@unhead/addons": "^2.0.10",
|
||||||
"@unhead/react": "^2.0.10",
|
"@unhead/react": "^2.0.10",
|
||||||
"buffer": "^6.0.3",
|
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"cmdk": "^1.0.0",
|
"cmdk": "^1.0.0",
|
||||||
"date-fns": "^3.6.0",
|
"date-fns": "^3.6.0",
|
||||||
"embla-carousel-react": "^8.3.0",
|
"embla-carousel-react": "^8.3.0",
|
||||||
"idb": "^8.0.3",
|
|
||||||
"input-otp": "^1.2.4",
|
"input-otp": "^1.2.4",
|
||||||
"lucide-react": "^0.462.0",
|
"lucide-react": "^0.462.0",
|
||||||
"nostr-tools": "^2.21.0",
|
"next-themes": "^0.3.0",
|
||||||
"qrcode": "^1.5.4",
|
"nostr-tools": "^2.13.0",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-day-picker": "^8.10.1",
|
"react-day-picker": "^8.10.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
"react-hook-form": "^7.71.1",
|
"react-hook-form": "^7.53.0",
|
||||||
"react-intersection-observer": "^9.16.0",
|
|
||||||
"react-resizable-panels": "^2.1.3",
|
"react-resizable-panels": "^2.1.3",
|
||||||
"react-router-dom": "^6.26.2",
|
"react-router-dom": "^6.26.2",
|
||||||
"recharts": "^2.12.7",
|
"recharts": "^2.12.7",
|
||||||
|
"sonner": "^1.5.0",
|
||||||
"tailwind-merge": "^2.5.2",
|
"tailwind-merge": "^2.5.2",
|
||||||
"tailwindcss-animate": "^1.0.7",
|
"tailwindcss-animate": "^1.0.7",
|
||||||
"vaul": "^0.9.3",
|
"vaul": "^0.9.3",
|
||||||
"zod": "^4.3.6"
|
"zod": "^3.25.71"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.9.0",
|
"@eslint/js": "^9.9.0",
|
||||||
@@ -76,11 +74,9 @@
|
|||||||
"@testing-library/jest-dom": "^6.6.3",
|
"@testing-library/jest-dom": "^6.6.3",
|
||||||
"@testing-library/react": "^16.3.0",
|
"@testing-library/react": "^16.3.0",
|
||||||
"@types/node": "^22.5.5",
|
"@types/node": "^22.5.5",
|
||||||
"@types/qrcode": "^1.5.5",
|
|
||||||
"@types/react": "^18.3.1",
|
"@types/react": "^18.3.1",
|
||||||
"@types/react-dom": "^18.3.1",
|
"@types/react-dom": "^18.3.1",
|
||||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||||
"@webbtc/webln-types": "^3.0.0",
|
|
||||||
"autoprefixer": "^10.4.20",
|
"autoprefixer": "^10.4.20",
|
||||||
"eslint": "^9.9.0",
|
"eslint": "^9.9.0",
|
||||||
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
||||||
|
|||||||
+1
-2
@@ -1,2 +1 @@
|
|||||||
/assets/* /assets/:splat 200
|
/* /index.html 200
|
||||||
/* /index.html 200
|
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"name": "Gnome Nostr - The Sacred Network of Woodland Folk",
|
||||||
|
"short_name": "Gnome Nostr",
|
||||||
|
"description": "A magical Nostr client where all messages are translated into the ancient gnome tongue. Connect with fellow earth-dwellers across the message-mushroom network!",
|
||||||
|
"start_url": "/",
|
||||||
|
"display": "standalone",
|
||||||
|
"background_color": "#f0f5f0",
|
||||||
|
"theme_color": "#d97706",
|
||||||
|
"icons": [
|
||||||
|
{
|
||||||
|
"src": "/icon-192.png",
|
||||||
|
"sizes": "192x192",
|
||||||
|
"type": "image/png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "/icon-512.png",
|
||||||
|
"sizes": "512x512",
|
||||||
|
"type": "image/png"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
User-agent: *
|
|
||||||
Allow: /
|
|
||||||
+32
@@ -0,0 +1,32 @@
|
|||||||
|
version: 1.0.0
|
||||||
|
title: Nostr Client Development
|
||||||
|
description: A recipe for building Nostr client applications
|
||||||
|
instructions: Create a Nostr client application according to the user's request.
|
||||||
|
extensions:
|
||||||
|
- type: builtin
|
||||||
|
name: developer
|
||||||
|
display_name: Developer Tools
|
||||||
|
timeout: 300
|
||||||
|
bundled: true
|
||||||
|
- type: stdio
|
||||||
|
name: nostr
|
||||||
|
cmd: npx
|
||||||
|
args:
|
||||||
|
- -y
|
||||||
|
- xjsr
|
||||||
|
- "@nostrbook/mcp"
|
||||||
|
envs: {}
|
||||||
|
timeout: 20
|
||||||
|
description: null
|
||||||
|
bundled: null
|
||||||
|
- type: stdio
|
||||||
|
name: fetch
|
||||||
|
cmd: uvx
|
||||||
|
args:
|
||||||
|
- mcp-server-fetch
|
||||||
|
envs: {}
|
||||||
|
timeout: 20
|
||||||
|
description: null
|
||||||
|
bundled: null
|
||||||
|
author:
|
||||||
|
contact: Alex Gleason <[email protected]>
|
||||||
+17
-20
@@ -6,12 +6,11 @@ import { createHead, UnheadProvider } from '@unhead/react/client';
|
|||||||
import { InferSeoMetaPlugin } from '@unhead/addons';
|
import { InferSeoMetaPlugin } from '@unhead/addons';
|
||||||
import { Suspense } from 'react';
|
import { Suspense } from 'react';
|
||||||
import NostrProvider from '@/components/NostrProvider';
|
import NostrProvider from '@/components/NostrProvider';
|
||||||
import { NostrSync } from '@/components/NostrSync';
|
|
||||||
import { Toaster } from "@/components/ui/toaster";
|
import { Toaster } from "@/components/ui/toaster";
|
||||||
|
import { Toaster as Sonner } from "@/components/ui/sonner";
|
||||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||||
import { NostrLoginProvider } from '@nostrify/react/login';
|
import { NostrLoginProvider } from '@nostrify/react/login';
|
||||||
import { AppProvider } from '@/components/AppProvider';
|
import { AppProvider } from '@/components/AppProvider';
|
||||||
import { NWCProvider } from '@/contexts/NWCContext';
|
|
||||||
import { AppConfig } from '@/contexts/AppContext';
|
import { AppConfig } from '@/contexts/AppContext';
|
||||||
import AppRouter from './AppRouter';
|
import AppRouter from './AppRouter';
|
||||||
|
|
||||||
@@ -33,32 +32,30 @@ const queryClient = new QueryClient({
|
|||||||
|
|
||||||
const defaultConfig: AppConfig = {
|
const defaultConfig: AppConfig = {
|
||||||
theme: "light",
|
theme: "light",
|
||||||
relayMetadata: {
|
relayUrl: "wss://relay.primal.net",
|
||||||
relays: [
|
|
||||||
{ url: 'wss://relay.ditto.pub', read: true, write: true },
|
|
||||||
{ url: 'wss://relay.nostr.band', read: true, write: true },
|
|
||||||
{ url: 'wss://relay.damus.io', read: true, write: true },
|
|
||||||
],
|
|
||||||
updatedAt: 0,
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const presetRelays = [
|
||||||
|
{ url: 'wss://ditto.pub/relay', name: 'Ditto' },
|
||||||
|
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
|
||||||
|
{ url: 'wss://relay.damus.io', name: 'Damus' },
|
||||||
|
{ url: 'wss://relay.primal.net', name: 'Primal' },
|
||||||
|
];
|
||||||
|
|
||||||
export function App() {
|
export function App() {
|
||||||
return (
|
return (
|
||||||
<UnheadProvider head={head}>
|
<UnheadProvider head={head}>
|
||||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
|
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<NostrLoginProvider storageKey='nostr:login'>
|
<NostrLoginProvider storageKey='nostr:login'>
|
||||||
<NostrProvider>
|
<NostrProvider>
|
||||||
<NostrSync />
|
<TooltipProvider>
|
||||||
<NWCProvider>
|
<Toaster />
|
||||||
<TooltipProvider>
|
<Sonner />
|
||||||
<Toaster />
|
<Suspense>
|
||||||
<Suspense>
|
<AppRouter />
|
||||||
<AppRouter />
|
</Suspense>
|
||||||
</Suspense>
|
</TooltipProvider>
|
||||||
</TooltipProvider>
|
|
||||||
</NWCProvider>
|
|
||||||
</NostrProvider>
|
</NostrProvider>
|
||||||
</NostrLoginProvider>
|
</NostrLoginProvider>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { BrowserRouter, Route, Routes } from "react-router-dom";
|
|||||||
import { ScrollToTop } from "./components/ScrollToTop";
|
import { ScrollToTop } from "./components/ScrollToTop";
|
||||||
|
|
||||||
import Index from "./pages/Index";
|
import Index from "./pages/Index";
|
||||||
import { NIP19Page } from "./pages/NIP19Page";
|
|
||||||
import NotFound from "./pages/NotFound";
|
import NotFound from "./pages/NotFound";
|
||||||
|
|
||||||
export function AppRouter() {
|
export function AppRouter() {
|
||||||
@@ -11,8 +10,6 @@ export function AppRouter() {
|
|||||||
<ScrollToTop />
|
<ScrollToTop />
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/" element={<Index />} />
|
<Route path="/" element={<Index />} />
|
||||||
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
|
||||||
<Route path="/:nip19" element={<NIP19Page />} />
|
|
||||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||||
<Route path="*" element={<NotFound />} />
|
<Route path="*" element={<NotFound />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { ReactNode, useEffect } from 'react';
|
import { ReactNode, useEffect } from 'react';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||||
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext';
|
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
|
||||||
|
|
||||||
interface AppProviderProps {
|
interface AppProviderProps {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
@@ -9,54 +9,46 @@ interface AppProviderProps {
|
|||||||
storageKey: string;
|
storageKey: string;
|
||||||
/** Default app configuration */
|
/** Default app configuration */
|
||||||
defaultConfig: AppConfig;
|
defaultConfig: AppConfig;
|
||||||
|
/** Optional list of preset relays to display in the RelaySelector */
|
||||||
|
presetRelays?: { name: string; url: string }[];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Zod schema for RelayMetadata validation
|
|
||||||
const RelayMetadataSchema = z.object({
|
|
||||||
relays: z.array(z.object({
|
|
||||||
url: z.url(),
|
|
||||||
read: z.boolean(),
|
|
||||||
write: z.boolean(),
|
|
||||||
})),
|
|
||||||
updatedAt: z.number(),
|
|
||||||
}) satisfies z.ZodType<RelayMetadata>;
|
|
||||||
|
|
||||||
// Zod schema for AppConfig validation
|
// Zod schema for AppConfig validation
|
||||||
const AppConfigSchema = z.object({
|
const AppConfigSchema: z.ZodType<AppConfig> = z.object({
|
||||||
theme: z.enum(['dark', 'light', 'system']),
|
theme: z.enum(['dark', 'light', 'system']),
|
||||||
relayMetadata: RelayMetadataSchema,
|
relayUrl: z.string().url(),
|
||||||
}) satisfies z.ZodType<AppConfig>;
|
});
|
||||||
|
|
||||||
export function AppProvider(props: AppProviderProps) {
|
export function AppProvider(props: AppProviderProps) {
|
||||||
const {
|
const {
|
||||||
children,
|
children,
|
||||||
storageKey,
|
storageKey,
|
||||||
defaultConfig,
|
defaultConfig,
|
||||||
|
presetRelays,
|
||||||
} = props;
|
} = props;
|
||||||
|
|
||||||
// App configuration state with localStorage persistence
|
// App configuration state with localStorage persistence
|
||||||
const [rawConfig, setConfig] = useLocalStorage<Partial<AppConfig>>(
|
const [config, setConfig] = useLocalStorage<AppConfig>(
|
||||||
storageKey,
|
storageKey,
|
||||||
{},
|
defaultConfig,
|
||||||
{
|
{
|
||||||
serialize: JSON.stringify,
|
serialize: JSON.stringify,
|
||||||
deserialize: (value: string) => {
|
deserialize: (value: string) => {
|
||||||
const parsed = JSON.parse(value);
|
const parsed = JSON.parse(value);
|
||||||
return AppConfigSchema.partial().parse(parsed);
|
return AppConfigSchema.parse(parsed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
// Generic config updater with callback pattern
|
// Generic config updater with callback pattern
|
||||||
const updateConfig = (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => {
|
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
|
||||||
setConfig(updater);
|
setConfig(updater);
|
||||||
};
|
};
|
||||||
|
|
||||||
const config = { ...defaultConfig, ...rawConfig };
|
|
||||||
|
|
||||||
const appContextValue: AppContextType = {
|
const appContextValue: AppContextType = {
|
||||||
config,
|
config,
|
||||||
updateConfig,
|
updateConfig,
|
||||||
|
presetRelays,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Apply theme effects to document
|
// Apply theme effects to document
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -1,113 +0,0 @@
|
|||||||
import { Component, ErrorInfo, ReactNode } from 'react';
|
|
||||||
|
|
||||||
interface ErrorBoundaryState {
|
|
||||||
hasError: boolean;
|
|
||||||
error: Error | null;
|
|
||||||
errorInfo: ErrorInfo | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ErrorBoundaryProps {
|
|
||||||
children: ReactNode;
|
|
||||||
fallback?: ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
|
|
||||||
constructor(props: ErrorBoundaryProps) {
|
|
||||||
super(props);
|
|
||||||
this.state = {
|
|
||||||
hasError: false,
|
|
||||||
error: null,
|
|
||||||
errorInfo: null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
|
|
||||||
return {
|
|
||||||
hasError: true,
|
|
||||||
error,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
|
|
||||||
console.error('Error caught by ErrorBoundary:', error, errorInfo);
|
|
||||||
|
|
||||||
this.setState({
|
|
||||||
error,
|
|
||||||
errorInfo,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
handleReset = () => {
|
|
||||||
this.setState({
|
|
||||||
hasError: false,
|
|
||||||
error: null,
|
|
||||||
errorInfo: null,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
render() {
|
|
||||||
if (this.state.hasError) {
|
|
||||||
if (this.props.fallback) {
|
|
||||||
return this.props.fallback;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-background flex items-center justify-center p-4">
|
|
||||||
<div className="max-w-md w-full space-y-4">
|
|
||||||
<div className="text-center">
|
|
||||||
<h2 className="text-2xl font-bold text-foreground mb-2">
|
|
||||||
Something went wrong
|
|
||||||
</h2>
|
|
||||||
<p className="text-muted-foreground">
|
|
||||||
An unexpected error occurred. The error has been reported.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="bg-muted p-4 rounded-lg">
|
|
||||||
<details className="text-sm">
|
|
||||||
<summary className="cursor-pointer font-medium text-foreground">
|
|
||||||
Error details
|
|
||||||
</summary>
|
|
||||||
<div className="mt-2 space-y-2">
|
|
||||||
<div>
|
|
||||||
<strong className="text-foreground">Message:</strong>
|
|
||||||
<p className="text-muted-foreground mt-1">
|
|
||||||
{this.state.error?.message}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
{this.state.error?.stack && (
|
|
||||||
<div>
|
|
||||||
<strong className="text-foreground">Stack trace:</strong>
|
|
||||||
<pre className="text-xs text-muted-foreground mt-1 overflow-auto max-h-32">
|
|
||||||
{this.state.error.stack}
|
|
||||||
</pre>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</details>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<button
|
|
||||||
onClick={this.handleReset}
|
|
||||||
className="flex-1 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors"
|
|
||||||
>
|
|
||||||
Try again
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => window.location.reload()}
|
|
||||||
className="flex-1 px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90 transition-colors"
|
|
||||||
>
|
|
||||||
Reload page
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.props.children;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Send, Sparkles, Leaf } from 'lucide-react';
|
||||||
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
|
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||||
|
import { useAuthor } from '@/hooks/useAuthor';
|
||||||
|
import { genUserName } from '@/lib/genUserName';
|
||||||
|
import { translateToGnomeSpeak } from '@/lib/gnomeSpeak';
|
||||||
|
import { useToast } from '@/hooks/useToast';
|
||||||
|
|
||||||
|
export function GnomeComposer() {
|
||||||
|
const [content, setContent] = useState('');
|
||||||
|
const [isPreviewMode, setIsPreviewMode] = useState(false);
|
||||||
|
const { user } = useCurrentUser();
|
||||||
|
const { mutate: createEvent, isPending } = useNostrPublish();
|
||||||
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
const author = useAuthor(user?.pubkey || '');
|
||||||
|
const metadata = author.data?.metadata;
|
||||||
|
const displayName = metadata?.name ?? (user?.pubkey ? genUserName(user.pubkey) : 'Anonymous Gnome');
|
||||||
|
const profileImage = metadata?.picture;
|
||||||
|
|
||||||
|
const handleSubmit = () => {
|
||||||
|
if (!content.trim()) {
|
||||||
|
toast({
|
||||||
|
title: "Empty woodland proclamation!",
|
||||||
|
description: "Even gnomes need something to say to the forest folk.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
toast({
|
||||||
|
title: "Authentication required",
|
||||||
|
description: "You must be logged in to share woodland wisdom.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
createEvent(
|
||||||
|
{
|
||||||
|
kind: 1,
|
||||||
|
content: content.trim(),
|
||||||
|
tags: [['t', 'gnome']] // Tag all posts as gnome content
|
||||||
|
},
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
setContent('');
|
||||||
|
setIsPreviewMode(false);
|
||||||
|
toast({
|
||||||
|
title: "Woodland proclamation sent! 🍄",
|
||||||
|
description: "Your message has been carried by the forest winds to all the message-mushrooms.",
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
toast({
|
||||||
|
title: "Forest spirits are troubled",
|
||||||
|
description: `Failed to send your proclamation: ${error.message}`,
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const gnomeTranslatedContent = content ? translateToGnomeSpeak(content) : '';
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return (
|
||||||
|
<Card className="mb-6 border-2 border-dashed border-muted">
|
||||||
|
<CardContent className="py-8 text-center">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="text-4xl">🍄</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="font-semibold mb-2">Join the Forest Council</h3>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Log in to share your woodland wisdom with fellow gnomes across the message-mushroom network!
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="mb-6 border-2 border-primary/20 shadow-lg">
|
||||||
|
<CardHeader className="pb-3">
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
<Avatar className="h-10 w-10 border-2 border-primary/30">
|
||||||
|
<AvatarImage src={profileImage} alt={displayName} />
|
||||||
|
<AvatarFallback className="bg-primary text-primary-foreground font-bold">
|
||||||
|
{displayName.slice(0, 2).toUpperCase()}
|
||||||
|
</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="flex-1">
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<CardTitle className="text-lg">Share Woodland Wisdom</CardTitle>
|
||||||
|
<Badge variant="secondary" className="gnome-wiggle">
|
||||||
|
🍄 Gnome Speak
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Your words will be translated into the ancient gnome tongue
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<label className="text-sm font-medium">Your Message:</label>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setIsPreviewMode(!isPreviewMode)}
|
||||||
|
className="text-xs"
|
||||||
|
>
|
||||||
|
<Sparkles className="h-3 w-3 mr-1" />
|
||||||
|
{isPreviewMode ? 'Edit' : 'Preview Gnome Speak'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!isPreviewMode ? (
|
||||||
|
<Textarea
|
||||||
|
value={content}
|
||||||
|
onChange={(e) => setContent(e.target.value)}
|
||||||
|
placeholder="Share your thoughts with the forest folk... (will be translated to gnome speak)"
|
||||||
|
className="min-h-[100px] resize-none border-2 border-border/50 focus:border-primary/50"
|
||||||
|
maxLength={280}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="min-h-[100px] p-3 border-2 border-accent/30 rounded-md bg-accent/5">
|
||||||
|
<p className="text-sm text-muted-foreground mb-2 font-medium">
|
||||||
|
🍄 Gnome Speak Translation:
|
||||||
|
</p>
|
||||||
|
<div className="text-sm leading-relaxed">
|
||||||
|
{gnomeTranslatedContent || (
|
||||||
|
<span className="text-muted-foreground italic">
|
||||||
|
Your gnome translation will appear here...
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||||
|
<span>
|
||||||
|
{content.length}/280 characters
|
||||||
|
</span>
|
||||||
|
{content && (
|
||||||
|
<span className="text-accent">
|
||||||
|
✨ Will be auto-translated to gnome speak
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between pt-2">
|
||||||
|
<div className="flex items-center space-x-2 text-xs text-muted-foreground">
|
||||||
|
<Leaf className="h-3 w-3" />
|
||||||
|
<span>Broadcasting to message-mushroom network</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={!content.trim() || isPending}
|
||||||
|
className="font-medium"
|
||||||
|
>
|
||||||
|
{isPending ? (
|
||||||
|
<>
|
||||||
|
<Sparkles className="h-4 w-4 mr-2 animate-spin" />
|
||||||
|
Sending to Forest...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Send className="h-4 w-4 mr-2" />
|
||||||
|
Share Wisdom
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useNostr } from '@nostrify/react';
|
||||||
|
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||||
|
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Heart, MessageCircle, Repeat2 } from 'lucide-react';
|
||||||
|
import { useAuthor } from '@/hooks/useAuthor';
|
||||||
|
import { genUserName } from '@/lib/genUserName';
|
||||||
|
import { NoteContent } from '@/components/NoteContent';
|
||||||
|
import { RelaySelector } from '@/components/RelaySelector';
|
||||||
|
import type { NostrEvent } from '@nostrify/nostrify';
|
||||||
|
|
||||||
|
function GnomePost({ event }: { event: NostrEvent }) {
|
||||||
|
const author = useAuthor(event.pubkey);
|
||||||
|
const metadata = author.data?.metadata;
|
||||||
|
|
||||||
|
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||||
|
const profileImage = metadata?.picture;
|
||||||
|
const about = metadata?.about;
|
||||||
|
|
||||||
|
// Format timestamp
|
||||||
|
const timestamp = new Date(event.created_at * 1000);
|
||||||
|
const timeAgo = formatTimeAgo(timestamp);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="mb-4 border-2 border-border/50 hover:border-primary/30 transition-all duration-300 hover:shadow-lg mushroom-glow">
|
||||||
|
<CardHeader className="pb-3">
|
||||||
|
<div className="flex items-start space-x-3">
|
||||||
|
<Avatar className="h-12 w-12 border-2 border-primary/20">
|
||||||
|
<AvatarImage src={profileImage} alt={displayName} />
|
||||||
|
<AvatarFallback className="bg-secondary text-secondary-foreground font-bold">
|
||||||
|
{displayName.slice(0, 2).toUpperCase()}
|
||||||
|
</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<h3 className="font-semibold text-foreground truncate">
|
||||||
|
{displayName}
|
||||||
|
</h3>
|
||||||
|
<Badge variant="secondary" className="text-xs gnome-wiggle">
|
||||||
|
🍄 Gnome
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
{about && (
|
||||||
|
<p className="text-sm text-muted-foreground truncate mt-1">
|
||||||
|
{about}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<p className="text-xs text-muted-foreground mt-1">
|
||||||
|
{timeAgo} • via message-mushroom 🍄
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent className="pt-0">
|
||||||
|
<div className="mb-4">
|
||||||
|
<NoteContent event={event} className="text-sm leading-relaxed" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Gnome-themed interaction buttons */}
|
||||||
|
<div className="flex items-center space-x-6 pt-2 border-t border-border/30">
|
||||||
|
<Button variant="ghost" size="sm" className="text-muted-foreground hover:text-primary group">
|
||||||
|
<Heart className="h-4 w-4 mr-1 group-hover:fill-current transition-all" />
|
||||||
|
<span className="text-xs">Sprinkle Fairy Dust</span>
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button variant="ghost" size="sm" className="text-muted-foreground hover:text-accent group">
|
||||||
|
<MessageCircle className="h-4 w-4 mr-1" />
|
||||||
|
<span className="text-xs">Forest Whisper</span>
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button variant="ghost" size="sm" className="text-muted-foreground hover:text-secondary group">
|
||||||
|
<Repeat2 className="h-4 w-4 mr-1" />
|
||||||
|
<span className="text-xs">Spread Seeds</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function GnomePostSkeleton() {
|
||||||
|
return (
|
||||||
|
<Card className="mb-4">
|
||||||
|
<CardHeader className="pb-3">
|
||||||
|
<div className="flex items-start space-x-3">
|
||||||
|
<Skeleton className="h-12 w-12 rounded-full" />
|
||||||
|
<div className="flex-1 space-y-2">
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<Skeleton className="h-4 w-24" />
|
||||||
|
<Skeleton className="h-5 w-16" />
|
||||||
|
</div>
|
||||||
|
<Skeleton className="h-3 w-32" />
|
||||||
|
<Skeleton className="h-3 w-20" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="pt-0">
|
||||||
|
<div className="space-y-2 mb-4">
|
||||||
|
<Skeleton className="h-4 w-full" />
|
||||||
|
<Skeleton className="h-4 w-4/5" />
|
||||||
|
<Skeleton className="h-4 w-3/5" />
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center space-x-6 pt-2 border-t border-border/30">
|
||||||
|
<Skeleton className="h-8 w-20" />
|
||||||
|
<Skeleton className="h-8 w-20" />
|
||||||
|
<Skeleton className="h-8 w-20" />
|
||||||
|
<Skeleton className="h-8 w-20" />
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTimeAgo(date: Date): string {
|
||||||
|
const now = new Date();
|
||||||
|
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
|
||||||
|
|
||||||
|
if (diffInSeconds < 60) {
|
||||||
|
return 'just now';
|
||||||
|
} else if (diffInSeconds < 3600) {
|
||||||
|
const minutes = Math.floor(diffInSeconds / 60);
|
||||||
|
return `${minutes}m ago`;
|
||||||
|
} else if (diffInSeconds < 86400) {
|
||||||
|
const hours = Math.floor(diffInSeconds / 3600);
|
||||||
|
return `${hours}h ago`;
|
||||||
|
} else {
|
||||||
|
const days = Math.floor(diffInSeconds / 86400);
|
||||||
|
return `${days}d ago`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function GnomeFeed() {
|
||||||
|
const { nostr } = useNostr();
|
||||||
|
|
||||||
|
const { data: posts, isLoading, error } = useQuery({
|
||||||
|
queryKey: ['gnome-feed'],
|
||||||
|
queryFn: async (c) => {
|
||||||
|
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
|
||||||
|
|
||||||
|
// Query for kind 1 events (text notes) that will be translated to gnome speak
|
||||||
|
const events = await nostr.query([
|
||||||
|
{
|
||||||
|
kinds: [1],
|
||||||
|
limit: 50,
|
||||||
|
}
|
||||||
|
], { signal });
|
||||||
|
|
||||||
|
// Sort by creation time (newest first)
|
||||||
|
return events.sort((a, b) => b.created_at - a.created_at);
|
||||||
|
},
|
||||||
|
refetchInterval: 30000, // Refetch every 30 seconds
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<div className="col-span-full">
|
||||||
|
<Card className="border-dashed border-destructive/50">
|
||||||
|
<CardContent className="py-12 px-8 text-center">
|
||||||
|
<div className="max-w-sm mx-auto space-y-6">
|
||||||
|
<div className="text-4xl">🍄💔</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="font-semibold text-destructive mb-2">
|
||||||
|
The forest spirits are troubled!
|
||||||
|
</h3>
|
||||||
|
<p className="text-muted-foreground mb-4">
|
||||||
|
Unable to connect to the message-mushroom network. The woodland whispers have gone silent.
|
||||||
|
</p>
|
||||||
|
<RelaySelector className="w-full" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{Array.from({ length: 5 }).map((_, i) => (
|
||||||
|
<GnomePostSkeleton key={i} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!posts || posts.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="col-span-full">
|
||||||
|
<Card className="border-dashed">
|
||||||
|
<CardContent className="py-12 px-8 text-center">
|
||||||
|
<div className="max-w-sm mx-auto space-y-6">
|
||||||
|
<div className="text-6xl gnome-wiggle">🍄</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="font-semibold mb-2">
|
||||||
|
The forest is quiet today...
|
||||||
|
</h3>
|
||||||
|
<p className="text-muted-foreground mb-4">
|
||||||
|
No woodland proclamations found. Perhaps the gnomes are all busy tending their gardens? Try another message-mushroom relay to discover more forest folk!
|
||||||
|
</p>
|
||||||
|
<RelaySelector className="w-full" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{posts.map((post) => (
|
||||||
|
<GnomePost key={post.id} event={post} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { LoginArea } from '@/components/auth/LoginArea';
|
||||||
|
import { RelaySelector } from '@/components/RelaySelector';
|
||||||
|
import { useTheme } from '@/hooks/useTheme';
|
||||||
|
import { Moon, Sun, Leaf, TreePine, Sparkles } from 'lucide-react';
|
||||||
|
|
||||||
|
export function GnomeHeader() {
|
||||||
|
const { theme, setTheme } = useTheme();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="mb-6 border-2 border-primary/30 bg-gradient-to-r from-primary/5 via-accent/5 to-secondary/5">
|
||||||
|
<CardContent className="py-6">
|
||||||
|
<div className="flex flex-col space-y-4">
|
||||||
|
{/* Main header */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center space-x-4">
|
||||||
|
<div className="text-3xl gnome-wiggle">🍄</div>
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||||
|
Gnome Nostr
|
||||||
|
</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
The sacred network of woodland folk
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
<Badge variant="secondary" className="hidden md:flex items-center space-x-1">
|
||||||
|
<Sparkles className="h-3 w-3" />
|
||||||
|
<span>Gnome Speak</span>
|
||||||
|
</Badge>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
|
||||||
|
className="text-muted-foreground hover:text-foreground"
|
||||||
|
>
|
||||||
|
{theme === 'light' ? (
|
||||||
|
<Moon className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<Sun className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
<span className="hidden sm:inline ml-1">
|
||||||
|
{theme === 'light' ? 'Night Forest' : 'Day Forest'}
|
||||||
|
</span>
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<LoginArea className="max-w-48" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Info and controls bar */}
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between space-y-3 sm:space-y-0 pt-3 border-t border-border/30">
|
||||||
|
<div className="flex items-center space-x-4 text-xs text-muted-foreground">
|
||||||
|
<div className="flex items-center space-x-1">
|
||||||
|
<TreePine className="h-3 w-3" />
|
||||||
|
<span className="hidden sm:inline">Text notes translated to gnome speak</span>
|
||||||
|
<span className="sm:hidden">Gnome translation active</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<Leaf className="h-3 w-3 text-muted-foreground" />
|
||||||
|
<span className="text-xs text-muted-foreground">Relay:</span>
|
||||||
|
<RelaySelector className="max-w-48" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Welcome message */}
|
||||||
|
<div className="bg-accent/10 border border-accent/20 rounded-lg p-4 text-center">
|
||||||
|
<p className="text-sm text-accent-foreground">
|
||||||
|
<span className="font-medium">🌟 Welcome to the enchanted forest!</span>
|
||||||
|
<br />
|
||||||
|
<span className="text-xs text-muted-foreground mt-1 block">
|
||||||
|
All text notes are magically translated into the ancient gnome tongue.
|
||||||
|
Share your woodland wisdom with fellow earth-dwellers!
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useEffect, useRef } from 'react';
|
import React, { useEffect, useRef } from 'react';
|
||||||
import { NostrEvent, NostrFilter, NPool, NRelay1 } from '@nostrify/nostrify';
|
import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify';
|
||||||
import { NostrContext } from '@nostrify/react';
|
import { NostrContext } from '@nostrify/react';
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
@@ -10,7 +10,7 @@ interface NostrProviderProps {
|
|||||||
|
|
||||||
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||||
const { children } = props;
|
const { children } = props;
|
||||||
const { config } = useAppContext();
|
const { config, presetRelays } = useAppContext();
|
||||||
|
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
@@ -18,13 +18,13 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
|||||||
const pool = useRef<NPool | undefined>(undefined);
|
const pool = useRef<NPool | undefined>(undefined);
|
||||||
|
|
||||||
// Use refs so the pool always has the latest data
|
// Use refs so the pool always has the latest data
|
||||||
const relayMetadata = useRef(config.relayMetadata);
|
const relayUrl = useRef<string>(config.relayUrl);
|
||||||
|
|
||||||
// Invalidate Nostr queries when relay metadata changes
|
// Update refs when config changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
relayMetadata.current = config.relayMetadata;
|
relayUrl.current = config.relayUrl;
|
||||||
queryClient.invalidateQueries({ queryKey: ['nostr'] });
|
queryClient.resetQueries();
|
||||||
}, [config.relayMetadata, queryClient]);
|
}, [config.relayUrl, queryClient]);
|
||||||
|
|
||||||
// Initialize NPool only once
|
// Initialize NPool only once
|
||||||
if (!pool.current) {
|
if (!pool.current) {
|
||||||
@@ -32,27 +32,21 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
|||||||
open(url: string) {
|
open(url: string) {
|
||||||
return new NRelay1(url);
|
return new NRelay1(url);
|
||||||
},
|
},
|
||||||
reqRouter(filters: NostrFilter[]) {
|
reqRouter(filters) {
|
||||||
const routes = new Map<string, NostrFilter[]>();
|
return new Map([[relayUrl.current, filters]]);
|
||||||
|
|
||||||
// Route to all read relays
|
|
||||||
const readRelays = relayMetadata.current.relays
|
|
||||||
.filter(r => r.read)
|
|
||||||
.map(r => r.url);
|
|
||||||
|
|
||||||
for (const url of readRelays) {
|
|
||||||
routes.set(url, filters);
|
|
||||||
}
|
|
||||||
|
|
||||||
return routes;
|
|
||||||
},
|
},
|
||||||
eventRouter(_event: NostrEvent) {
|
eventRouter(_event: NostrEvent) {
|
||||||
// Get write relays from metadata
|
// Publish to the selected relay
|
||||||
const writeRelays = relayMetadata.current.relays
|
const allRelays = new Set<string>([relayUrl.current]);
|
||||||
.filter(r => r.write)
|
|
||||||
.map(r => r.url);
|
|
||||||
|
|
||||||
const allRelays = new Set<string>(writeRelays);
|
// Also publish to the preset relays, capped to 5
|
||||||
|
for (const { url } of (presetRelays ?? [])) {
|
||||||
|
allRelays.add(url);
|
||||||
|
|
||||||
|
if (allRelays.size >= 5) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return [...allRelays];
|
return [...allRelays];
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,62 +0,0 @@
|
|||||||
import { useEffect } from 'react';
|
|
||||||
import { useNostr } from '@nostrify/react';
|
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* NostrSync - Syncs user's Nostr data
|
|
||||||
*
|
|
||||||
* This component runs globally to sync various Nostr data when the user logs in.
|
|
||||||
* Currently syncs:
|
|
||||||
* - NIP-65 relay list (kind 10002)
|
|
||||||
*/
|
|
||||||
export function NostrSync() {
|
|
||||||
const { nostr } = useNostr();
|
|
||||||
const { user } = useCurrentUser();
|
|
||||||
const { config, updateConfig } = useAppContext();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!user) return;
|
|
||||||
|
|
||||||
const syncRelaysFromNostr = async () => {
|
|
||||||
try {
|
|
||||||
const events = await nostr.query(
|
|
||||||
[{ kinds: [10002], authors: [user.pubkey], limit: 1 }],
|
|
||||||
{ signal: AbortSignal.timeout(5000) }
|
|
||||||
);
|
|
||||||
|
|
||||||
if (events.length > 0) {
|
|
||||||
const event = events[0];
|
|
||||||
|
|
||||||
// Only update if the event is newer than our stored data
|
|
||||||
if (event.created_at > config.relayMetadata.updatedAt) {
|
|
||||||
const fetchedRelays = event.tags
|
|
||||||
.filter(([name]) => name === 'r')
|
|
||||||
.map(([_, url, marker]) => ({
|
|
||||||
url,
|
|
||||||
read: !marker || marker === 'read',
|
|
||||||
write: !marker || marker === 'write',
|
|
||||||
}));
|
|
||||||
|
|
||||||
if (fetchedRelays.length > 0) {
|
|
||||||
console.log('Syncing relay list from Nostr:', fetchedRelays);
|
|
||||||
updateConfig((current) => ({
|
|
||||||
...current,
|
|
||||||
relayMetadata: {
|
|
||||||
relays: fetchedRelays,
|
|
||||||
updatedAt: event.created_at,
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to sync relays from Nostr:', error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
syncRelaysFromNostr();
|
|
||||||
}, [user, config.relayMetadata.updatedAt, nostr, updateConfig]);
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
@@ -22,9 +22,10 @@ describe('NoteContent', () => {
|
|||||||
</TestApp>
|
</TestApp>
|
||||||
);
|
);
|
||||||
|
|
||||||
const link = screen.getByRole('link', { name: 'https://example.com' });
|
// The URL should still be linkified even after gnome translation
|
||||||
|
const link = screen.getByRole('link', { name: /https:\/\/example/ });
|
||||||
expect(link).toBeInTheDocument();
|
expect(link).toBeInTheDocument();
|
||||||
expect(link).toHaveAttribute('href', 'https://example.com');
|
expect(link.getAttribute('href')).toMatch(/https:\/\/example/);
|
||||||
expect(link).toHaveAttribute('target', '_blank');
|
expect(link).toHaveAttribute('target', '_blank');
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -93,6 +94,7 @@ describe('NoteContent', () => {
|
|||||||
</TestApp>
|
</TestApp>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Hashtags are preserved during gnome translation
|
||||||
const nostrHashtag = screen.getByRole('link', { name: '#nostr' });
|
const nostrHashtag = screen.getByRole('link', { name: '#nostr' });
|
||||||
const bitcoinHashtag = screen.getByRole('link', { name: '#bitcoin' });
|
const bitcoinHashtag = screen.getByRole('link', { name: '#bitcoin' });
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { nip19 } from 'nostr-tools';
|
|||||||
import { useAuthor } from '@/hooks/useAuthor';
|
import { useAuthor } from '@/hooks/useAuthor';
|
||||||
import { genUserName } from '@/lib/genUserName';
|
import { genUserName } from '@/lib/genUserName';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
import { translateToGnomeSpeak, shouldTranslateToGnomeSpeak } from '@/lib/gnomeSpeak';
|
||||||
|
|
||||||
interface NoteContentProps {
|
interface NoteContentProps {
|
||||||
event: NostrEvent;
|
event: NostrEvent;
|
||||||
@@ -18,7 +19,11 @@ export function NoteContent({
|
|||||||
}: NoteContentProps) {
|
}: NoteContentProps) {
|
||||||
// Process the content to render mentions, links, etc.
|
// Process the content to render mentions, links, etc.
|
||||||
const content = useMemo(() => {
|
const content = useMemo(() => {
|
||||||
const text = event.content;
|
// Translate to gnome speak if it's a kind 1 event
|
||||||
|
const originalText = event.content;
|
||||||
|
const text = shouldTranslateToGnomeSpeak(event.kind)
|
||||||
|
? translateToGnomeSpeak(originalText)
|
||||||
|
: originalText;
|
||||||
|
|
||||||
// Regex to find URLs, Nostr references, and hashtags
|
// Regex to find URLs, Nostr references, and hashtags
|
||||||
const regex = /(https?:\/\/[^\s]+)|nostr:(npub1|note1|nprofile1|nevent1)([023456789acdefghjklmnpqrstuvwxyz]+)|(#\w+)/g;
|
const regex = /(https?:\/\/[^\s]+)|nostr:(npub1|note1|nprofile1|nevent1)([023456789acdefghjklmnpqrstuvwxyz]+)|(#\w+)/g;
|
||||||
@@ -45,7 +50,7 @@ export function NoteContent({
|
|||||||
href={url}
|
href={url}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="text-blue-500 hover:underline break-all"
|
className="text-blue-500 hover:underline"
|
||||||
>
|
>
|
||||||
{url}
|
{url}
|
||||||
</a>
|
</a>
|
||||||
@@ -61,18 +66,13 @@ export function NoteContent({
|
|||||||
parts.push(
|
parts.push(
|
||||||
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
|
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
|
||||||
);
|
);
|
||||||
} else if (decoded.type === 'nprofile') {
|
|
||||||
const pubkey = decoded.data.pubkey;
|
|
||||||
parts.push(
|
|
||||||
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
|
|
||||||
);
|
|
||||||
} else {
|
} else {
|
||||||
// For other types, just show as a link
|
// For other types, just show as a link
|
||||||
parts.push(
|
parts.push(
|
||||||
<Link
|
<Link
|
||||||
key={`nostr-${keyCounter++}`}
|
key={`nostr-${keyCounter++}`}
|
||||||
to={`/${nostrId}`}
|
to={`/${nostrId}`}
|
||||||
className="text-blue-500 hover:underline break-all"
|
className="text-blue-500 hover:underline"
|
||||||
>
|
>
|
||||||
{fullMatch}
|
{fullMatch}
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
@@ -1,286 +0,0 @@
|
|||||||
import { useState, useEffect } from 'react';
|
|
||||||
import { Plus, X, Wifi, Settings } from 'lucide-react';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Label } from '@/components/ui/label';
|
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Switch } from '@/components/ui/switch';
|
|
||||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
|
||||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
|
||||||
import { useToast } from '@/hooks/useToast';
|
|
||||||
|
|
||||||
interface Relay {
|
|
||||||
url: string;
|
|
||||||
read: boolean;
|
|
||||||
write: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function RelayListManager() {
|
|
||||||
const { config, updateConfig } = useAppContext();
|
|
||||||
const { user } = useCurrentUser();
|
|
||||||
const { mutate: publishEvent } = useNostrPublish();
|
|
||||||
const { toast } = useToast();
|
|
||||||
|
|
||||||
const [relays, setRelays] = useState<Relay[]>(config.relayMetadata.relays);
|
|
||||||
const [newRelayUrl, setNewRelayUrl] = useState('');
|
|
||||||
|
|
||||||
// Sync local state with config when it changes (e.g., from NostrProvider sync)
|
|
||||||
useEffect(() => {
|
|
||||||
setRelays(config.relayMetadata.relays);
|
|
||||||
}, [config.relayMetadata.relays]);
|
|
||||||
|
|
||||||
const normalizeRelayUrl = (url: string): string => {
|
|
||||||
url = url.trim();
|
|
||||||
try {
|
|
||||||
return new URL(url).toString();
|
|
||||||
} catch {
|
|
||||||
try {
|
|
||||||
return new URL(`wss://${url}`).toString();
|
|
||||||
} catch {
|
|
||||||
return url;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const isValidRelayUrl = (url: string): boolean => {
|
|
||||||
const trimmed = url.trim();
|
|
||||||
if (!trimmed) return false;
|
|
||||||
|
|
||||||
const normalized = normalizeRelayUrl(trimmed);
|
|
||||||
try {
|
|
||||||
new URL(normalized);
|
|
||||||
return true;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleAddRelay = () => {
|
|
||||||
if (!isValidRelayUrl(newRelayUrl)) {
|
|
||||||
toast({
|
|
||||||
title: 'Invalid relay URL',
|
|
||||||
description: 'Please enter a valid relay URL (e.g., wss://relay.example.com)',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const normalized = normalizeRelayUrl(newRelayUrl);
|
|
||||||
|
|
||||||
if (relays.some(r => r.url === normalized)) {
|
|
||||||
toast({
|
|
||||||
title: 'Relay already exists',
|
|
||||||
description: 'This relay is already in your list.',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const newRelays = [...relays, { url: normalized, read: true, write: true }];
|
|
||||||
setRelays(newRelays);
|
|
||||||
setNewRelayUrl('');
|
|
||||||
|
|
||||||
saveRelays(newRelays);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleRemoveRelay = (url: string) => {
|
|
||||||
const newRelays = relays.filter(r => r.url !== url);
|
|
||||||
setRelays(newRelays);
|
|
||||||
saveRelays(newRelays);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleToggleRead = (url: string) => {
|
|
||||||
const newRelays = relays.map(r =>
|
|
||||||
r.url === url ? { ...r, read: !r.read } : r
|
|
||||||
);
|
|
||||||
setRelays(newRelays);
|
|
||||||
saveRelays(newRelays);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleToggleWrite = (url: string) => {
|
|
||||||
const newRelays = relays.map(r =>
|
|
||||||
r.url === url ? { ...r, write: !r.write } : r
|
|
||||||
);
|
|
||||||
setRelays(newRelays);
|
|
||||||
saveRelays(newRelays);
|
|
||||||
};
|
|
||||||
|
|
||||||
const saveRelays = (newRelays: Relay[]) => {
|
|
||||||
const now = Math.floor(Date.now() / 1000);
|
|
||||||
|
|
||||||
// Update local config
|
|
||||||
updateConfig((current) => ({
|
|
||||||
...current,
|
|
||||||
relayMetadata: {
|
|
||||||
relays: newRelays,
|
|
||||||
updatedAt: now,
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Publish to Nostr if user is logged in
|
|
||||||
if (user) {
|
|
||||||
publishNIP65RelayList(newRelays);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const publishNIP65RelayList = (relayList: Relay[]) => {
|
|
||||||
const tags = relayList.map(relay => {
|
|
||||||
if (relay.read && relay.write) {
|
|
||||||
return ['r', relay.url];
|
|
||||||
} else if (relay.read) {
|
|
||||||
return ['r', relay.url, 'read'];
|
|
||||||
} else if (relay.write) {
|
|
||||||
return ['r', relay.url, 'write'];
|
|
||||||
}
|
|
||||||
// If neither read nor write, don't include (shouldn't happen)
|
|
||||||
return null;
|
|
||||||
}).filter((tag): tag is string[] => tag !== null);
|
|
||||||
|
|
||||||
publishEvent(
|
|
||||||
{
|
|
||||||
kind: 10002,
|
|
||||||
content: '',
|
|
||||||
tags,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
onSuccess: () => {
|
|
||||||
toast({
|
|
||||||
title: 'Relay list published',
|
|
||||||
description: 'Your relay list has been published to Nostr.',
|
|
||||||
});
|
|
||||||
},
|
|
||||||
onError: (error) => {
|
|
||||||
console.error('Failed to publish relay list:', error);
|
|
||||||
toast({
|
|
||||||
title: 'Failed to publish relay list',
|
|
||||||
description: 'There was an error publishing your relay list to Nostr.',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const renderRelayUrl = (url: string): string => {
|
|
||||||
try {
|
|
||||||
const parsed = new URL(url);
|
|
||||||
if (parsed.protocol === 'wss:') {
|
|
||||||
if (parsed.pathname === '/') {
|
|
||||||
return parsed.host;
|
|
||||||
} else {
|
|
||||||
return parsed.host + parsed.pathname;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return parsed.href;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
return url;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{/* Relay List */}
|
|
||||||
<div className="space-y-2">
|
|
||||||
{relays.map((relay) => (
|
|
||||||
<div
|
|
||||||
key={relay.url}
|
|
||||||
className="flex items-center gap-3 p-3 rounded-md border bg-muted/20"
|
|
||||||
>
|
|
||||||
<Wifi className="h-4 w-4 text-muted-foreground shrink-0" />
|
|
||||||
<span className="font-mono text-sm flex-1 truncate" title={relay.url}>
|
|
||||||
{renderRelayUrl(relay.url)}
|
|
||||||
</span>
|
|
||||||
|
|
||||||
{/* Settings Popover */}
|
|
||||||
<Popover>
|
|
||||||
<PopoverTrigger asChild>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
className="size-5 text-muted-foreground hover:text-foreground shrink-0"
|
|
||||||
>
|
|
||||||
<Settings className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</PopoverTrigger>
|
|
||||||
<PopoverContent className="w-48" align="end">
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<Label htmlFor={`read-${relay.url}`} className="text-sm cursor-pointer">
|
|
||||||
Read
|
|
||||||
</Label>
|
|
||||||
<Switch
|
|
||||||
id={`read-${relay.url}`}
|
|
||||||
checked={relay.read}
|
|
||||||
onCheckedChange={() => handleToggleRead(relay.url)}
|
|
||||||
className="data-[state=checked]:bg-green-500 scale-75"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<Label htmlFor={`write-${relay.url}`} className="text-sm cursor-pointer">
|
|
||||||
Write
|
|
||||||
</Label>
|
|
||||||
<Switch
|
|
||||||
id={`write-${relay.url}`}
|
|
||||||
checked={relay.write}
|
|
||||||
onCheckedChange={() => handleToggleWrite(relay.url)}
|
|
||||||
className="data-[state=checked]:bg-blue-500 scale-75"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</PopoverContent>
|
|
||||||
</Popover>
|
|
||||||
|
|
||||||
{/* Remove Button */}
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
onClick={() => handleRemoveRelay(relay.url)}
|
|
||||||
className="size-5 text-muted-foreground hover:text-destructive hover:bg-transparent shrink-0"
|
|
||||||
disabled={relays.length <= 1}
|
|
||||||
>
|
|
||||||
<X className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Add Relay Form */}
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<div className="flex-1">
|
|
||||||
<Label htmlFor="new-relay-url" className="sr-only">
|
|
||||||
Relay URL
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="new-relay-url"
|
|
||||||
placeholder="Enter relay URL (e.g., wss://relay.example.com)"
|
|
||||||
value={newRelayUrl}
|
|
||||||
onChange={(e) => setNewRelayUrl(e.target.value)}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === 'Enter') {
|
|
||||||
handleAddRelay();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
onClick={handleAddRelay}
|
|
||||||
disabled={!newRelayUrl.trim()}
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className="h-10 shrink-0"
|
|
||||||
>
|
|
||||||
<Plus className="h-4 w-4 mr-2" />
|
|
||||||
Add Relay
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{!user && (
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
Log in to sync your relay list with Nostr
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
import { Check, ChevronsUpDown, Wifi, Plus } from "lucide-react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Command,
|
||||||
|
CommandEmpty,
|
||||||
|
CommandGroup,
|
||||||
|
CommandInput,
|
||||||
|
CommandItem,
|
||||||
|
CommandList,
|
||||||
|
} from "@/components/ui/command";
|
||||||
|
import {
|
||||||
|
Popover,
|
||||||
|
PopoverContent,
|
||||||
|
PopoverTrigger,
|
||||||
|
} from "@/components/ui/popover";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useAppContext } from "@/hooks/useAppContext";
|
||||||
|
|
||||||
|
interface RelaySelectorProps {
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RelaySelector(props: RelaySelectorProps) {
|
||||||
|
const { className } = props;
|
||||||
|
const { config, updateConfig, presetRelays = [] } = useAppContext();
|
||||||
|
|
||||||
|
const selectedRelay = config.relayUrl;
|
||||||
|
const setSelectedRelay = (relay: string) => {
|
||||||
|
updateConfig((current) => ({ ...current, relayUrl: relay }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [inputValue, setInputValue] = useState("");
|
||||||
|
|
||||||
|
const selectedOption = presetRelays.find((option) => option.url === selectedRelay);
|
||||||
|
|
||||||
|
// Function to normalize relay URL by adding wss:// if no protocol is present
|
||||||
|
const normalizeRelayUrl = (url: string): string => {
|
||||||
|
const trimmed = url.trim();
|
||||||
|
if (!trimmed) return trimmed;
|
||||||
|
|
||||||
|
// Check if it already has a protocol
|
||||||
|
if (trimmed.includes('://')) {
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add wss:// prefix
|
||||||
|
return `wss://${trimmed}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle adding a custom relay
|
||||||
|
const handleAddCustomRelay = (url: string) => {
|
||||||
|
setSelectedRelay?.(normalizeRelayUrl(url));
|
||||||
|
setOpen(false);
|
||||||
|
setInputValue("");
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check if input value looks like a valid relay URL
|
||||||
|
const isValidRelayInput = (value: string): boolean => {
|
||||||
|
const trimmed = value.trim();
|
||||||
|
if (!trimmed) return false;
|
||||||
|
|
||||||
|
// Basic validation - should contain at least a domain-like structure
|
||||||
|
const normalized = normalizeRelayUrl(trimmed);
|
||||||
|
try {
|
||||||
|
new URL(normalized);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Popover open={open} onOpenChange={setOpen}>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
role="combobox"
|
||||||
|
aria-expanded={open}
|
||||||
|
className={cn("justify-between", className)}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Wifi className="h-4 w-4" />
|
||||||
|
<span className="truncate">
|
||||||
|
{selectedOption
|
||||||
|
? selectedOption.name
|
||||||
|
: selectedRelay
|
||||||
|
? selectedRelay.replace(/^wss?:\/\//, '')
|
||||||
|
: "Select relay..."
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-[300px] p-0">
|
||||||
|
<Command>
|
||||||
|
<CommandInput
|
||||||
|
placeholder="Search relays or type URL..."
|
||||||
|
value={inputValue}
|
||||||
|
onValueChange={setInputValue}
|
||||||
|
/>
|
||||||
|
<CommandList>
|
||||||
|
<CommandEmpty>
|
||||||
|
{inputValue && isValidRelayInput(inputValue) ? (
|
||||||
|
<CommandItem
|
||||||
|
onSelect={() => handleAddCustomRelay(inputValue)}
|
||||||
|
className="cursor-pointer"
|
||||||
|
>
|
||||||
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<span className="font-medium">Add custom relay</span>
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
{normalizeRelayUrl(inputValue)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</CommandItem>
|
||||||
|
) : (
|
||||||
|
<div className="py-6 text-center text-sm text-muted-foreground">
|
||||||
|
{inputValue ? "Invalid relay URL" : "No relay found."}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CommandEmpty>
|
||||||
|
<CommandGroup>
|
||||||
|
{presetRelays
|
||||||
|
.filter((option) =>
|
||||||
|
!inputValue ||
|
||||||
|
option.name.toLowerCase().includes(inputValue.toLowerCase()) ||
|
||||||
|
option.url.toLowerCase().includes(inputValue.toLowerCase())
|
||||||
|
)
|
||||||
|
.map((option) => (
|
||||||
|
<CommandItem
|
||||||
|
key={option.url}
|
||||||
|
value={option.url}
|
||||||
|
onSelect={(currentValue) => {
|
||||||
|
setSelectedRelay(normalizeRelayUrl(currentValue));
|
||||||
|
setOpen(false);
|
||||||
|
setInputValue("");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Check
|
||||||
|
className={cn(
|
||||||
|
"mr-2 h-4 w-4",
|
||||||
|
selectedRelay === option.url ? "opacity-100" : "opacity-0"
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<span className="font-medium">{option.name}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">{option.url}</span>
|
||||||
|
</div>
|
||||||
|
</CommandItem>
|
||||||
|
))}
|
||||||
|
{inputValue && isValidRelayInput(inputValue) && (
|
||||||
|
<CommandItem
|
||||||
|
onSelect={() => handleAddCustomRelay(inputValue)}
|
||||||
|
className="cursor-pointer border-t"
|
||||||
|
>
|
||||||
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<span className="font-medium">Add custom relay</span>
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
{normalizeRelayUrl(inputValue)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</CommandItem>
|
||||||
|
)}
|
||||||
|
</CommandGroup>
|
||||||
|
</CommandList>
|
||||||
|
</Command>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,393 +0,0 @@
|
|||||||
import { useState, forwardRef } from 'react';
|
|
||||||
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X } from 'lucide-react';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
DialogTrigger,
|
|
||||||
} from '@/components/ui/dialog';
|
|
||||||
import {
|
|
||||||
Drawer,
|
|
||||||
DrawerContent,
|
|
||||||
DrawerDescription,
|
|
||||||
DrawerHeader,
|
|
||||||
DrawerTitle,
|
|
||||||
DrawerTrigger,
|
|
||||||
DrawerClose,
|
|
||||||
} from '@/components/ui/drawer';
|
|
||||||
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 { useNWC } from '@/hooks/useNWCContext';
|
|
||||||
import { useWallet } from '@/hooks/useWallet';
|
|
||||||
import { useToast } from '@/hooks/useToast';
|
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
|
||||||
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
|
|
||||||
import type { WebLNProvider } from "@webbtc/webln-types";
|
|
||||||
|
|
||||||
interface WalletModalProps {
|
|
||||||
children?: React.ReactNode;
|
|
||||||
className?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extracted AddWalletContent to prevent re-renders
|
|
||||||
const AddWalletContent = forwardRef<HTMLDivElement, {
|
|
||||||
alias: string;
|
|
||||||
setAlias: (value: string) => void;
|
|
||||||
connectionUri: string;
|
|
||||||
setConnectionUri: (value: string) => void;
|
|
||||||
}>(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (
|
|
||||||
<div className="space-y-4 px-4" ref={ref}>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="alias">Wallet Name (optional)</Label>
|
|
||||||
<Input
|
|
||||||
id="alias"
|
|
||||||
placeholder="My Lightning Wallet"
|
|
||||||
value={alias}
|
|
||||||
onChange={(e) => setAlias(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Label htmlFor="connection-uri">Connection URI</Label>
|
|
||||||
<Textarea
|
|
||||||
id="connection-uri"
|
|
||||||
placeholder="nostr+walletconnect://..."
|
|
||||||
value={connectionUri}
|
|
||||||
onChange={(e) => setConnectionUri(e.target.value)}
|
|
||||||
rows={3}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
));
|
|
||||||
AddWalletContent.displayName = 'AddWalletContent';
|
|
||||||
|
|
||||||
// Extracted WalletContent to prevent re-renders
|
|
||||||
const WalletContent = forwardRef<HTMLDivElement, {
|
|
||||||
webln: WebLNProvider | null;
|
|
||||||
hasNWC: boolean;
|
|
||||||
connections: NWCConnection[];
|
|
||||||
connectionInfo: Record<string, NWCInfo>;
|
|
||||||
activeConnection: string | null;
|
|
||||||
handleSetActive: (cs: string) => void;
|
|
||||||
handleRemoveConnection: (cs: string) => void;
|
|
||||||
setAddDialogOpen: (open: boolean) => void;
|
|
||||||
}>(({
|
|
||||||
webln,
|
|
||||||
hasNWC,
|
|
||||||
connections,
|
|
||||||
connectionInfo,
|
|
||||||
activeConnection,
|
|
||||||
handleSetActive,
|
|
||||||
handleRemoveConnection,
|
|
||||||
setAddDialogOpen
|
|
||||||
}, ref) => (
|
|
||||||
<div className="space-y-6 px-4 pb-4" ref={ref}>
|
|
||||||
{/* Current Status */}
|
|
||||||
<div className="space-y-3">
|
|
||||||
<h3 className="font-medium">Current Status</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">Browser extension</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 ? "Ready" : "Not Found"}
|
|
||||||
</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">Nostr Wallet Connect</p>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{connections.length > 0
|
|
||||||
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
|
|
||||||
: "Remote wallet connection"
|
|
||||||
}
|
|
||||||
</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 ? "Ready" : "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">Nostr Wallet Connect</h3>
|
|
||||||
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
|
|
||||||
<Plus className="h-4 w-4 mr-1" />
|
|
||||||
Add
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
{/* Connected Wallets List */}
|
|
||||||
{connections.length === 0 ? (
|
|
||||||
<div className="text-center py-6 text-muted-foreground">
|
|
||||||
<p className="text-sm">No wallets connected</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 || 'Lightning Wallet'}
|
|
||||||
</p>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
NWC Connection
|
|
||||||
</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)}
|
|
||||||
>
|
|
||||||
<Zap className="h-3 w-3" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="ghost"
|
|
||||||
onClick={() => handleRemoveConnection(connection.connectionString)}
|
|
||||||
>
|
|
||||||
<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">
|
|
||||||
Install a WebLN extension or connect a NWC wallet for zaps.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
));
|
|
||||||
WalletContent.displayName = 'WalletContent';
|
|
||||||
|
|
||||||
export function WalletModal({ children, className }: WalletModalProps) {
|
|
||||||
const [open, setOpen] = useState(false);
|
|
||||||
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
|
||||||
const [connectionUri, setConnectionUri] = useState('');
|
|
||||||
const [alias, setAlias] = useState('');
|
|
||||||
const [isConnecting, setIsConnecting] = useState(false);
|
|
||||||
const isMobile = useIsMobile();
|
|
||||||
|
|
||||||
const {
|
|
||||||
connections,
|
|
||||||
activeConnection,
|
|
||||||
connectionInfo,
|
|
||||||
addConnection,
|
|
||||||
removeConnection,
|
|
||||||
setActiveConnection
|
|
||||||
} = useNWC();
|
|
||||||
|
|
||||||
const { webln } = useWallet();
|
|
||||||
|
|
||||||
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
|
|
||||||
const { toast } = useToast();
|
|
||||||
|
|
||||||
const handleAddConnection = async () => {
|
|
||||||
if (!connectionUri.trim()) {
|
|
||||||
toast({
|
|
||||||
title: 'Connection URI required',
|
|
||||||
description: 'Please enter a valid NWC connection URI.',
|
|
||||||
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: 'Active wallet changed',
|
|
||||||
description: 'The selected wallet is now active for zaps.',
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const walletContentProps = {
|
|
||||||
webln,
|
|
||||||
hasNWC,
|
|
||||||
connections,
|
|
||||||
connectionInfo,
|
|
||||||
activeConnection,
|
|
||||||
handleSetActive,
|
|
||||||
handleRemoveConnection,
|
|
||||||
setAddDialogOpen,
|
|
||||||
};
|
|
||||||
|
|
||||||
const addWalletDialog = (
|
|
||||||
<Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
|
|
||||||
<DialogContent className="sm:max-w-[425px]">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Connect NWC Wallet</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Enter your connection string from a compatible wallet.
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
<AddWalletContent
|
|
||||||
alias={alias}
|
|
||||||
setAlias={setAlias}
|
|
||||||
connectionUri={connectionUri}
|
|
||||||
setConnectionUri={setConnectionUri}
|
|
||||||
/>
|
|
||||||
<DialogFooter className="px-4">
|
|
||||||
<Button
|
|
||||||
onClick={handleAddConnection}
|
|
||||||
disabled={isConnecting || !connectionUri.trim()}
|
|
||||||
className="w-full"
|
|
||||||
>
|
|
||||||
{isConnecting ? 'Connecting...' : 'Connect'}
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
);
|
|
||||||
|
|
||||||
if (isMobile) {
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Drawer open={open} onOpenChange={setOpen}>
|
|
||||||
<DrawerTrigger asChild>
|
|
||||||
{children || (
|
|
||||||
<Button variant="outline" size="sm" className={className}>
|
|
||||||
<Wallet className="h-4 w-4 mr-2" />
|
|
||||||
Wallet Settings
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</DrawerTrigger>
|
|
||||||
<DrawerContent className="h-full">
|
|
||||||
<DrawerHeader className="text-center relative">
|
|
||||||
<DrawerClose asChild>
|
|
||||||
<Button variant="ghost" size="sm" className="absolute right-4 top-4">
|
|
||||||
<X className="h-4 w-4" />
|
|
||||||
<span className="sr-only">Close</span>
|
|
||||||
</Button>
|
|
||||||
</DrawerClose>
|
|
||||||
<DrawerTitle className="flex items-center justify-center gap-2 pt-2">
|
|
||||||
<Wallet className="h-5 w-5" />
|
|
||||||
Lightning Wallet
|
|
||||||
</DrawerTitle>
|
|
||||||
<DrawerDescription>
|
|
||||||
Connect your lightning wallet to send zaps instantly.
|
|
||||||
</DrawerDescription>
|
|
||||||
</DrawerHeader>
|
|
||||||
<div className="overflow-y-auto">
|
|
||||||
<WalletContent {...walletContentProps} />
|
|
||||||
</div>
|
|
||||||
</DrawerContent>
|
|
||||||
</Drawer>
|
|
||||||
{/* Render Add Wallet as a separate Drawer for mobile */}
|
|
||||||
<Drawer open={addDialogOpen} onOpenChange={setAddDialogOpen}>
|
|
||||||
<DrawerContent>
|
|
||||||
<DrawerHeader>
|
|
||||||
<DrawerTitle>Connect NWC Wallet</DrawerTitle>
|
|
||||||
<DrawerDescription>
|
|
||||||
Enter your connection string from a compatible wallet.
|
|
||||||
</DrawerDescription>
|
|
||||||
</DrawerHeader>
|
|
||||||
<AddWalletContent
|
|
||||||
alias={alias}
|
|
||||||
setAlias={setAlias}
|
|
||||||
connectionUri={connectionUri}
|
|
||||||
setConnectionUri={setConnectionUri}
|
|
||||||
/>
|
|
||||||
<div className="p-4">
|
|
||||||
<Button
|
|
||||||
onClick={handleAddConnection}
|
|
||||||
disabled={isConnecting || !connectionUri.trim()}
|
|
||||||
className="w-full"
|
|
||||||
>
|
|
||||||
{isConnecting ? 'Connecting...' : 'Connect'}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</DrawerContent>
|
|
||||||
</Drawer>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Dialog open={open} onOpenChange={setOpen}>
|
|
||||||
<DialogTrigger asChild>
|
|
||||||
{children || (
|
|
||||||
<Button variant="outline" size="sm" className={className}>
|
|
||||||
<Wallet className="h-4 w-4 mr-2" />
|
|
||||||
Wallet Settings
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</DialogTrigger>
|
|
||||||
<DialogContent className="sm:max-w-[500px] max-h-[80vh] overflow-y-auto">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle className="flex items-center gap-2">
|
|
||||||
<Wallet className="h-5 w-5" />
|
|
||||||
Lightning Wallet
|
|
||||||
</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Connect your lightning wallet to send zaps instantly.
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
<WalletContent {...walletContentProps} />
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
{addWalletDialog}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
import { ZapDialog } from '@/components/ZapDialog';
|
|
||||||
import { useZaps } from '@/hooks/useZaps';
|
|
||||||
import { useWallet } from '@/hooks/useWallet';
|
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
|
||||||
import { useAuthor } from '@/hooks/useAuthor';
|
|
||||||
import { Zap } from 'lucide-react';
|
|
||||||
import type { Event } from 'nostr-tools';
|
|
||||||
|
|
||||||
interface ZapButtonProps {
|
|
||||||
target: Event;
|
|
||||||
className?: string;
|
|
||||||
showCount?: boolean;
|
|
||||||
zapData?: { count: number; totalSats: number; isLoading?: boolean };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ZapButton({
|
|
||||||
target,
|
|
||||||
className = "text-xs ml-1",
|
|
||||||
showCount = true,
|
|
||||||
zapData: externalZapData
|
|
||||||
}: ZapButtonProps) {
|
|
||||||
const { user } = useCurrentUser();
|
|
||||||
const { data: author } = useAuthor(target?.pubkey || '');
|
|
||||||
const { webln, activeNWC } = useWallet();
|
|
||||||
|
|
||||||
// Only fetch data if not provided externally
|
|
||||||
const { totalSats: fetchedTotalSats, isLoading } = useZaps(
|
|
||||||
externalZapData ? [] : target ?? [], // Empty array prevents fetching if external data provided
|
|
||||||
webln,
|
|
||||||
activeNWC
|
|
||||||
);
|
|
||||||
|
|
||||||
// Don't show zap button if user is not logged in, is the author, or author has no lightning address
|
|
||||||
if (!user || !target || user.pubkey === target.pubkey || (!author?.metadata?.lud16 && !author?.metadata?.lud06)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Use external data if provided, otherwise use fetched data
|
|
||||||
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
|
|
||||||
const showLoading = externalZapData?.isLoading || isLoading;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ZapDialog target={target}>
|
|
||||||
<div className={`flex items-center gap-1 ${className}`}>
|
|
||||||
<Zap className="h-4 w-4" />
|
|
||||||
<span className="text-xs">
|
|
||||||
{showLoading ? (
|
|
||||||
'...'
|
|
||||||
) : showCount && totalSats > 0 ? (
|
|
||||||
`${totalSats.toLocaleString()}`
|
|
||||||
) : (
|
|
||||||
'Zap'
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</ZapDialog>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,463 +0,0 @@
|
|||||||
import { useState, useEffect, useRef, forwardRef } from 'react';
|
|
||||||
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X } from 'lucide-react';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
DialogTrigger,
|
|
||||||
} from '@/components/ui/dialog';
|
|
||||||
import {
|
|
||||||
Drawer,
|
|
||||||
DrawerContent,
|
|
||||||
DrawerDescription,
|
|
||||||
DrawerHeader,
|
|
||||||
DrawerTitle,
|
|
||||||
DrawerTrigger,
|
|
||||||
DrawerClose,
|
|
||||||
} from '@/components/ui/drawer';
|
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Label } from '@/components/ui/label';
|
|
||||||
import { Textarea } from '@/components/ui/textarea';
|
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
|
||||||
import { Separator } from '@/components/ui/separator';
|
|
||||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
|
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
|
||||||
import { useAuthor } from '@/hooks/useAuthor';
|
|
||||||
import { useToast } from '@/hooks/useToast';
|
|
||||||
import { useZaps } from '@/hooks/useZaps';
|
|
||||||
import { useWallet } from '@/hooks/useWallet';
|
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
|
||||||
import type { Event } from 'nostr-tools';
|
|
||||||
import QRCode from 'qrcode';
|
|
||||||
import type { WebLNProvider } from "@webbtc/webln-types";
|
|
||||||
|
|
||||||
interface ZapDialogProps {
|
|
||||||
target: Event;
|
|
||||||
children?: React.ReactNode;
|
|
||||||
className?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const presetAmounts = [
|
|
||||||
{ amount: 1, icon: Sparkle },
|
|
||||||
{ amount: 50, icon: Sparkles },
|
|
||||||
{ amount: 100, icon: Zap },
|
|
||||||
{ amount: 250, icon: Star },
|
|
||||||
{ amount: 1000, icon: Rocket },
|
|
||||||
];
|
|
||||||
|
|
||||||
interface ZapContentProps {
|
|
||||||
invoice: string | null;
|
|
||||||
amount: number | string;
|
|
||||||
comment: string;
|
|
||||||
isZapping: boolean;
|
|
||||||
qrCodeUrl: string;
|
|
||||||
copied: boolean;
|
|
||||||
webln: WebLNProvider | null;
|
|
||||||
handleZap: () => void;
|
|
||||||
handleCopy: () => void;
|
|
||||||
openInWallet: () => void;
|
|
||||||
setAmount: (amount: number | string) => void;
|
|
||||||
setComment: (comment: string) => void;
|
|
||||||
inputRef: React.RefObject<HTMLInputElement>;
|
|
||||||
zap: (amount: number, comment: string) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Moved ZapContent outside of ZapDialog to prevent re-renders causing focus loss
|
|
||||||
const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
|
||||||
invoice,
|
|
||||||
amount,
|
|
||||||
comment,
|
|
||||||
isZapping,
|
|
||||||
qrCodeUrl,
|
|
||||||
copied,
|
|
||||||
webln,
|
|
||||||
handleZap,
|
|
||||||
handleCopy,
|
|
||||||
openInWallet,
|
|
||||||
setAmount,
|
|
||||||
setComment,
|
|
||||||
inputRef,
|
|
||||||
zap,
|
|
||||||
}, ref) => (
|
|
||||||
<div ref={ref}>
|
|
||||||
{invoice ? (
|
|
||||||
<div className="flex flex-col h-full min-h-0">
|
|
||||||
{/* Payment amount display */}
|
|
||||||
<div className="text-center pt-4">
|
|
||||||
<div className="text-2xl font-bold">{amount} sats</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Separator className="my-4" />
|
|
||||||
|
|
||||||
<div className="flex flex-col justify-center min-h-0 flex-1 px-2">
|
|
||||||
{/* QR Code */}
|
|
||||||
<div className="flex justify-center">
|
|
||||||
<Card className="p-3 [@media(max-height:680px)]:max-w-[65vw] max-w-[95vw] mx-auto">
|
|
||||||
<CardContent className="p-0 flex justify-center">
|
|
||||||
{qrCodeUrl ? (
|
|
||||||
<img
|
|
||||||
src={qrCodeUrl}
|
|
||||||
alt="Lightning Invoice QR Code"
|
|
||||||
className="w-full h-auto aspect-square max-w-full object-contain"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<div className="w-full aspect-square bg-muted animate-pulse rounded" />
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Invoice input */}
|
|
||||||
<div className="space-y-2 mt-4">
|
|
||||||
<Label htmlFor="invoice">Lightning Invoice</Label>
|
|
||||||
<div className="flex gap-2 min-w-0">
|
|
||||||
<Input
|
|
||||||
id="invoice"
|
|
||||||
value={invoice}
|
|
||||||
readOnly
|
|
||||||
className="font-mono text-xs min-w-0 flex-1 overflow-hidden text-ellipsis"
|
|
||||||
onClick={(e) => e.currentTarget.select()}
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="icon"
|
|
||||||
onClick={handleCopy}
|
|
||||||
className="shrink-0"
|
|
||||||
>
|
|
||||||
{copied ? (
|
|
||||||
<Check className="h-4 w-4 text-green-600" />
|
|
||||||
) : (
|
|
||||||
<Copy className="h-4 w-4" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Payment buttons */}
|
|
||||||
<div className="space-y-3 mt-4">
|
|
||||||
{webln && (
|
|
||||||
<Button
|
|
||||||
onClick={() => {
|
|
||||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
|
||||||
zap(finalAmount, comment);
|
|
||||||
}}
|
|
||||||
disabled={isZapping}
|
|
||||||
className="w-full"
|
|
||||||
size="lg"
|
|
||||||
>
|
|
||||||
<Zap className="h-4 w-4 mr-2" />
|
|
||||||
{isZapping ? "Processing..." : "Pay with WebLN"}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
onClick={openInWallet}
|
|
||||||
className="w-full"
|
|
||||||
size="lg"
|
|
||||||
>
|
|
||||||
<ExternalLink className="h-4 w-4 mr-2" />
|
|
||||||
Open in Lightning Wallet
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<div className="text-xs sm:text-[.65rem] text-muted-foreground text-center">
|
|
||||||
Scan the QR code or copy the invoice to pay with any Lightning wallet.
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<div className="grid gap-3 px-4 py-4 w-full overflow-hidden">
|
|
||||||
<ToggleGroup
|
|
||||||
type="single"
|
|
||||||
value={String(amount)}
|
|
||||||
onValueChange={(value) => {
|
|
||||||
if (value) {
|
|
||||||
setAmount(parseInt(value, 10));
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
className="grid grid-cols-5 gap-1 w-full"
|
|
||||||
>
|
|
||||||
{presetAmounts.map(({ amount: presetAmount, icon: Icon }) => (
|
|
||||||
<ToggleGroupItem
|
|
||||||
key={presetAmount}
|
|
||||||
value={String(presetAmount)}
|
|
||||||
className="flex flex-col h-auto min-w-0 text-xs px-1 py-2"
|
|
||||||
>
|
|
||||||
<Icon className="h-4 w-4 mb-1" />
|
|
||||||
<span className="truncate">{presetAmount}</span>
|
|
||||||
</ToggleGroupItem>
|
|
||||||
))}
|
|
||||||
</ToggleGroup>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="h-px flex-1 bg-muted" />
|
|
||||||
<span className="text-xs text-muted-foreground">OR</span>
|
|
||||||
<div className="h-px flex-1 bg-muted" />
|
|
||||||
</div>
|
|
||||||
<Input
|
|
||||||
ref={inputRef}
|
|
||||||
id="custom-amount"
|
|
||||||
type="number"
|
|
||||||
placeholder="Custom amount"
|
|
||||||
value={amount}
|
|
||||||
onChange={(e) => setAmount(e.target.value)}
|
|
||||||
className="w-full text-sm"
|
|
||||||
/>
|
|
||||||
<Textarea
|
|
||||||
id="custom-comment"
|
|
||||||
placeholder="Add a comment (optional)"
|
|
||||||
value={comment}
|
|
||||||
onChange={(e) => setComment(e.target.value)}
|
|
||||||
className="w-full resize-none text-sm"
|
|
||||||
rows={2}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="px-4 pb-4">
|
|
||||||
<Button onClick={handleZap} className="w-full" disabled={isZapping} size="default">
|
|
||||||
{isZapping ? (
|
|
||||||
'Creating invoice...'
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Zap className="h-4 w-4 mr-2" />
|
|
||||||
Zap {amount} sats
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
));
|
|
||||||
ZapContent.displayName = 'ZapContent';
|
|
||||||
|
|
||||||
export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
|
||||||
const [open, setOpen] = useState(false);
|
|
||||||
const { user } = useCurrentUser();
|
|
||||||
const { data: author } = useAuthor(target.pubkey);
|
|
||||||
const { toast } = useToast();
|
|
||||||
const { webln, activeNWC } = useWallet();
|
|
||||||
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
|
|
||||||
const [amount, setAmount] = useState<number | string>(100);
|
|
||||||
const [comment, setComment] = useState<string>('');
|
|
||||||
const [copied, setCopied] = useState(false);
|
|
||||||
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
|
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
|
||||||
const isMobile = useIsMobile();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (target) {
|
|
||||||
setComment('Zapped with MKStack!');
|
|
||||||
}
|
|
||||||
}, [target]);
|
|
||||||
|
|
||||||
// Generate QR code
|
|
||||||
useEffect(() => {
|
|
||||||
let isCancelled = false;
|
|
||||||
|
|
||||||
const generateQR = async () => {
|
|
||||||
if (!invoice) {
|
|
||||||
setQrCodeUrl('');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const url = await QRCode.toDataURL(invoice.toUpperCase(), {
|
|
||||||
width: 512,
|
|
||||||
margin: 2,
|
|
||||||
color: {
|
|
||||||
dark: '#000000',
|
|
||||||
light: '#FFFFFF',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!isCancelled) {
|
|
||||||
setQrCodeUrl(url);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
if (!isCancelled) {
|
|
||||||
console.error('Failed to generate QR code:', err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
generateQR();
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
isCancelled = true;
|
|
||||||
};
|
|
||||||
}, [invoice]);
|
|
||||||
|
|
||||||
const handleCopy = async () => {
|
|
||||||
if (invoice) {
|
|
||||||
await navigator.clipboard.writeText(invoice);
|
|
||||||
setCopied(true);
|
|
||||||
toast({
|
|
||||||
title: 'Invoice copied',
|
|
||||||
description: 'Lightning invoice copied to clipboard',
|
|
||||||
});
|
|
||||||
setTimeout(() => setCopied(false), 2000);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const openInWallet = () => {
|
|
||||||
if (invoice) {
|
|
||||||
const lightningUrl = `lightning:${invoice}`;
|
|
||||||
window.open(lightningUrl, '_blank');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (open) {
|
|
||||||
setAmount(100);
|
|
||||||
setInvoice(null);
|
|
||||||
setCopied(false);
|
|
||||||
setQrCodeUrl('');
|
|
||||||
} else {
|
|
||||||
// Clean up state when dialog closes
|
|
||||||
setAmount(100);
|
|
||||||
setInvoice(null);
|
|
||||||
setCopied(false);
|
|
||||||
setQrCodeUrl('');
|
|
||||||
}
|
|
||||||
}, [open, setInvoice]);
|
|
||||||
|
|
||||||
const handleZap = () => {
|
|
||||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
|
||||||
zap(finalAmount, comment);
|
|
||||||
};
|
|
||||||
|
|
||||||
const contentProps = {
|
|
||||||
invoice,
|
|
||||||
amount,
|
|
||||||
comment,
|
|
||||||
isZapping,
|
|
||||||
qrCodeUrl,
|
|
||||||
copied,
|
|
||||||
webln,
|
|
||||||
handleZap,
|
|
||||||
handleCopy,
|
|
||||||
openInWallet,
|
|
||||||
setAmount,
|
|
||||||
setComment,
|
|
||||||
inputRef,
|
|
||||||
zap,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!user || user.pubkey === target.pubkey || !author?.metadata?.lud06 && !author?.metadata?.lud16) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isMobile) {
|
|
||||||
// Use drawer for entire mobile flow, make it full-screen when showing invoice
|
|
||||||
return (
|
|
||||||
<Drawer
|
|
||||||
open={open}
|
|
||||||
onOpenChange={(newOpen) => {
|
|
||||||
// Reset invoice when closing
|
|
||||||
if (!newOpen) {
|
|
||||||
setInvoice(null);
|
|
||||||
setQrCodeUrl('');
|
|
||||||
}
|
|
||||||
setOpen(newOpen);
|
|
||||||
}}
|
|
||||||
dismissible={true} // Always allow dismissal via drag
|
|
||||||
snapPoints={invoice ? [0.5, 0.75, 0.98] : [0.98]}
|
|
||||||
activeSnapPoint={invoice ? 0.98 : 0.98}
|
|
||||||
modal={true}
|
|
||||||
shouldScaleBackground={false}
|
|
||||||
fadeFromIndex={0}
|
|
||||||
>
|
|
||||||
<DrawerTrigger asChild>
|
|
||||||
<div className={`cursor-pointer ${className || ''}`}>
|
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
</DrawerTrigger>
|
|
||||||
<DrawerContent
|
|
||||||
key={invoice ? 'payment' : 'form'}
|
|
||||||
className={cn(
|
|
||||||
"transition-all duration-300",
|
|
||||||
invoice ? "h-full max-h-screen" : "max-h-[98vh]"
|
|
||||||
)}
|
|
||||||
data-testid="zap-modal"
|
|
||||||
>
|
|
||||||
<DrawerHeader className="text-center relative">
|
|
||||||
{/* Back button when showing invoice */}
|
|
||||||
{invoice && (
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => {
|
|
||||||
setInvoice(null);
|
|
||||||
setQrCodeUrl('');
|
|
||||||
}}
|
|
||||||
className="absolute left-4 top-4 flex items-center gap-2"
|
|
||||||
>
|
|
||||||
<ArrowLeft className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Close button */}
|
|
||||||
<DrawerClose asChild>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
className="absolute right-4 top-4"
|
|
||||||
>
|
|
||||||
<X className="h-4 w-4" />
|
|
||||||
<span className="sr-only">Close</span>
|
|
||||||
</Button>
|
|
||||||
</DrawerClose>
|
|
||||||
|
|
||||||
<DrawerTitle className="text-lg break-words pt-2">
|
|
||||||
{invoice ? 'Lightning Payment' : 'Send a Zap'}
|
|
||||||
</DrawerTitle>
|
|
||||||
<DrawerDescription className="text-sm break-words text-center">
|
|
||||||
{invoice ? (
|
|
||||||
'Pay with Bitcoin Lightning Network'
|
|
||||||
) : (
|
|
||||||
'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
|
|
||||||
)}
|
|
||||||
</DrawerDescription>
|
|
||||||
</DrawerHeader>
|
|
||||||
<div className="flex-1 overflow-y-auto px-4 pb-4">
|
|
||||||
<ZapContent {...contentProps} />
|
|
||||||
</div>
|
|
||||||
</DrawerContent>
|
|
||||||
</Drawer>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Dialog open={open} onOpenChange={setOpen}>
|
|
||||||
<DialogTrigger asChild>
|
|
||||||
<div className={`cursor-pointer ${className || ''}`}>
|
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
</DialogTrigger>
|
|
||||||
<DialogContent className="sm:max-w-[425px] max-h-[95vh] overflow-hidden" data-testid="zap-modal">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle className="text-lg break-words">
|
|
||||||
{invoice ? 'Lightning Payment' : 'Send a Zap'}
|
|
||||||
</DialogTitle>
|
|
||||||
<DialogDescription className="text-sm text-center break-words">
|
|
||||||
{invoice ? (
|
|
||||||
'Pay with Bitcoin Lightning Network'
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
<div className="overflow-y-auto">
|
|
||||||
<ZapContent {...contentProps} />
|
|
||||||
</div>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu.tsx';
|
} from '@/components/ui/dropdown-menu.tsx';
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
|
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
|
||||||
|
import { RelaySelector } from '@/components/RelaySelector';
|
||||||
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
|
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
|
||||||
import { genUserName } from '@/lib/genUserName';
|
import { genUserName } from '@/lib/genUserName';
|
||||||
|
|
||||||
@@ -41,6 +42,9 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
|
|||||||
</button>
|
</button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
|
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
|
||||||
|
<div className='font-medium text-sm px-2 py-1.5'>Switch Relay</div>
|
||||||
|
<RelaySelector className="w-full" />
|
||||||
|
<DropdownMenuSeparator />
|
||||||
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
|
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
|
||||||
{otherUsers.map((user) => (
|
{otherUsers.map((user) => (
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
||||||
|
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
import { User } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button.tsx';
|
import { Button } from '@/components/ui/button.tsx';
|
||||||
import LoginDialog from './LoginDialog';
|
import LoginDialog from './LoginDialog';
|
||||||
import SignupDialog from './SignupDialog';
|
import SignupDialog from './SignupDialog';
|
||||||
@@ -28,26 +29,20 @@ export function LoginArea({ className }: LoginAreaProps) {
|
|||||||
{currentUser ? (
|
{currentUser ? (
|
||||||
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
|
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
|
||||||
) : (
|
) : (
|
||||||
<div className="flex gap-3 justify-center">
|
<Button
|
||||||
<Button
|
onClick={() => setLoginDialogOpen(true)}
|
||||||
onClick={() => setLoginDialogOpen(true)}
|
className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in'
|
||||||
className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in'
|
>
|
||||||
>
|
<User className='w-4 h-4' />
|
||||||
<span className='truncate'>Log in</span>
|
<span className='truncate'>Log in</span>
|
||||||
</Button><Button
|
</Button>
|
||||||
onClick={() => setSignupDialogOpen(true)}
|
|
||||||
variant="outline"
|
|
||||||
className="flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all"
|
|
||||||
>
|
|
||||||
<span>Sign up</span>
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<LoginDialog
|
<LoginDialog
|
||||||
isOpen={loginDialogOpen}
|
isOpen={loginDialogOpen}
|
||||||
onClose={() => setLoginDialogOpen(false)}
|
onClose={() => setLoginDialogOpen(false)}
|
||||||
onLogin={handleLogin}
|
onLogin={handleLogin}
|
||||||
|
onSignup={() => setSignupDialogOpen(true)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<SignupDialog
|
<SignupDialog
|
||||||
|
|||||||
+153
-273
@@ -1,141 +1,75 @@
|
|||||||
// NOTE: This file is stable and usually should not be modified.
|
// NOTE: This file is stable and usually should not be modified.
|
||||||
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
||||||
|
|
||||||
import React, { useRef, useState, useEffect } from 'react';
|
import React, { useRef, useState } from 'react';
|
||||||
import { Upload, AlertTriangle, ChevronDown } from 'lucide-react';
|
import { Shield, Upload } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button.tsx';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input.tsx';
|
||||||
import { Dialog, DialogContent, DialogHeader } from "@/components/ui/dialog";
|
import {
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
Dialog,
|
||||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
DialogContent,
|
||||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog.tsx';
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs.tsx';
|
||||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||||
import { DialogTitle } from '@radix-ui/react-dialog';
|
|
||||||
|
|
||||||
interface LoginDialogProps {
|
interface LoginDialogProps {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onLogin: () => void;
|
onLogin: () => void;
|
||||||
|
onSignup?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const validateNsec = (nsec: string) => {
|
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
|
||||||
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
|
|
||||||
};
|
|
||||||
|
|
||||||
const validateBunkerUri = (uri: string) => {
|
|
||||||
return uri.startsWith('bunker://');
|
|
||||||
};
|
|
||||||
|
|
||||||
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) => {
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [isFileLoading, setIsFileLoading] = useState(false);
|
|
||||||
const [nsec, setNsec] = useState('');
|
const [nsec, setNsec] = useState('');
|
||||||
const [bunkerUri, setBunkerUri] = useState('');
|
const [bunkerUri, setBunkerUri] = useState('');
|
||||||
const [errors, setErrors] = useState<{
|
|
||||||
nsec?: string;
|
|
||||||
bunker?: string;
|
|
||||||
file?: string;
|
|
||||||
extension?: string;
|
|
||||||
}>({});
|
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
const login = useLoginActions();
|
const login = useLoginActions();
|
||||||
|
|
||||||
// Reset all state when dialog opens/closes
|
const handleExtensionLogin = () => {
|
||||||
useEffect(() => {
|
|
||||||
if (isOpen) {
|
|
||||||
// Reset state when dialog opens
|
|
||||||
setIsLoading(false);
|
|
||||||
setIsFileLoading(false);
|
|
||||||
setNsec('');
|
|
||||||
setBunkerUri('');
|
|
||||||
setErrors({});
|
|
||||||
// Reset file input
|
|
||||||
if (fileInputRef.current) {
|
|
||||||
fileInputRef.current.value = '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [isOpen]);
|
|
||||||
|
|
||||||
const handleExtensionLogin = async () => {
|
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setErrors(prev => ({ ...prev, extension: undefined }));
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!('nostr' in window)) {
|
if (!('nostr' in window)) {
|
||||||
throw new Error('Nostr extension not found. Please install a NIP-07 extension.');
|
throw new Error('Nostr extension not found. Please install a NIP-07 extension.');
|
||||||
}
|
}
|
||||||
await login.extension();
|
login.extension();
|
||||||
onLogin();
|
onLogin();
|
||||||
onClose();
|
onClose();
|
||||||
} catch (e: unknown) {
|
} catch (error) {
|
||||||
const error = e as Error;
|
|
||||||
console.error('Bunker login failed:', error);
|
|
||||||
console.error('Nsec login failed:', error);
|
|
||||||
console.error('Extension login failed:', error);
|
console.error('Extension login failed:', error);
|
||||||
setErrors(prev => ({
|
|
||||||
...prev,
|
|
||||||
extension: error instanceof Error ? error.message : 'Extension login failed'
|
|
||||||
}));
|
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const executeLogin = (key: string) => {
|
|
||||||
setIsLoading(true);
|
|
||||||
setErrors({});
|
|
||||||
|
|
||||||
// Use a timeout to allow the UI to update before the synchronous login call
|
|
||||||
setTimeout(() => {
|
|
||||||
try {
|
|
||||||
login.nsec(key);
|
|
||||||
onLogin();
|
|
||||||
onClose();
|
|
||||||
} catch {
|
|
||||||
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
}, 50);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleKeyLogin = () => {
|
const handleKeyLogin = () => {
|
||||||
if (!nsec.trim()) {
|
if (!nsec.trim()) return;
|
||||||
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!validateNsec(nsec)) {
|
|
||||||
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
executeLogin(nsec);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleBunkerLogin = async () => {
|
|
||||||
if (!bunkerUri.trim()) {
|
|
||||||
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!validateBunkerUri(bunkerUri)) {
|
|
||||||
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setErrors(prev => ({ ...prev, bunker: undefined }));
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await login.bunker(bunkerUri);
|
login.nsec(nsec);
|
||||||
onLogin();
|
onLogin();
|
||||||
onClose();
|
onClose();
|
||||||
// Clear the URI from memory
|
} catch (error) {
|
||||||
setBunkerUri('');
|
console.error('Nsec login failed:', error);
|
||||||
} catch {
|
} finally {
|
||||||
setErrors(prev => ({
|
setIsLoading(false);
|
||||||
...prev,
|
}
|
||||||
bunker: 'Failed to connect to bunker. Please check the URI.'
|
};
|
||||||
}));
|
|
||||||
|
const handleBunkerLogin = () => {
|
||||||
|
if (!bunkerUri.trim() || !bunkerUri.startsWith('bunker://')) return;
|
||||||
|
setIsLoading(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
login.bunker(bunkerUri);
|
||||||
|
onLogin();
|
||||||
|
onClose();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Bunker login failed:', error);
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
@@ -145,196 +79,142 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) =
|
|||||||
const file = e.target.files?.[0];
|
const file = e.target.files?.[0];
|
||||||
if (!file) return;
|
if (!file) return;
|
||||||
|
|
||||||
setIsFileLoading(true);
|
|
||||||
setErrors({});
|
|
||||||
|
|
||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
reader.onload = (event) => {
|
reader.onload = (event) => {
|
||||||
setIsFileLoading(false);
|
|
||||||
const content = event.target?.result as string;
|
const content = event.target?.result as string;
|
||||||
if (content) {
|
setNsec(content.trim());
|
||||||
const trimmedContent = content.trim();
|
|
||||||
if (validateNsec(trimmedContent)) {
|
|
||||||
executeLogin(trimmedContent);
|
|
||||||
} else {
|
|
||||||
setErrors({ file: 'File does not contain a valid secret key.' });
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
setErrors({ file: 'Could not read file content.' });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
reader.onerror = () => {
|
|
||||||
setIsFileLoading(false);
|
|
||||||
setErrors({ file: 'Failed to read file.' });
|
|
||||||
};
|
};
|
||||||
reader.readAsText(file);
|
reader.readAsText(file);
|
||||||
};
|
};
|
||||||
|
|
||||||
const hasExtension = 'nostr' in window;
|
const handleSignupClick = () => {
|
||||||
const [isMoreOptionsOpen, setIsMoreOptionsOpen] = useState(false);
|
onClose();
|
||||||
|
if (onSignup) {
|
||||||
const renderTabs = () => (
|
onSignup();
|
||||||
<Tabs defaultValue="key" className="w-full">
|
}
|
||||||
<TabsList className="grid w-full grid-cols-2 bg-muted/80 rounded-lg mb-4">
|
};
|
||||||
<TabsTrigger value="key" className="flex items-center gap-2">
|
|
||||||
<span>Secret Key</span>
|
|
||||||
</TabsTrigger>
|
|
||||||
<TabsTrigger value="bunker" className="flex items-center gap-2">
|
|
||||||
<span>Remote Signer</span>
|
|
||||||
</TabsTrigger>
|
|
||||||
</TabsList>
|
|
||||||
|
|
||||||
<TabsContent value='key' className='space-y-4'>
|
|
||||||
<form onSubmit={(e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
handleKeyLogin();
|
|
||||||
}} className='space-y-4'>
|
|
||||||
<div className='space-y-2'>
|
|
||||||
<Input
|
|
||||||
id='nsec'
|
|
||||||
type="password"
|
|
||||||
value={nsec}
|
|
||||||
onChange={(e) => {
|
|
||||||
setNsec(e.target.value);
|
|
||||||
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
|
|
||||||
}}
|
|
||||||
className={`rounded-lg ${
|
|
||||||
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
|
|
||||||
}`}
|
|
||||||
placeholder='nsec1...'
|
|
||||||
autoComplete="off"
|
|
||||||
/>
|
|
||||||
{errors.nsec && (
|
|
||||||
<p className="text-sm text-red-500">{errors.nsec}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex space-x-2">
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
size="lg"
|
|
||||||
disabled={isLoading || !nsec.trim()}
|
|
||||||
className="flex-1"
|
|
||||||
>
|
|
||||||
{isLoading ? 'Verifying...' : 'Log in'}
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
accept=".txt"
|
|
||||||
className="hidden"
|
|
||||||
ref={fileInputRef}
|
|
||||||
onChange={handleFileUpload}
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
size="lg"
|
|
||||||
onClick={() => fileInputRef.current?.click()}
|
|
||||||
disabled={isLoading || isFileLoading}
|
|
||||||
className="px-3"
|
|
||||||
>
|
|
||||||
<Upload className="w-4 h-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{errors.file && (
|
|
||||||
<p className="text-sm text-red-500 text-center">{errors.file}</p>
|
|
||||||
)}
|
|
||||||
</form>
|
|
||||||
</TabsContent>
|
|
||||||
|
|
||||||
<TabsContent value='bunker' className='space-y-4'>
|
|
||||||
<form onSubmit={(e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
handleBunkerLogin();
|
|
||||||
}} className='space-y-4'>
|
|
||||||
<div className='space-y-2'>
|
|
||||||
<Input
|
|
||||||
id='bunkerUri'
|
|
||||||
value={bunkerUri}
|
|
||||||
onChange={(e) => {
|
|
||||||
setBunkerUri(e.target.value);
|
|
||||||
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
|
|
||||||
}}
|
|
||||||
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
|
|
||||||
errors.bunker ? 'border-red-500' : ''
|
|
||||||
}`}
|
|
||||||
placeholder='bunker://'
|
|
||||||
autoComplete="off"
|
|
||||||
/>
|
|
||||||
{errors.bunker && (
|
|
||||||
<p className="text-sm text-red-500">{errors.bunker}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
size="lg"
|
|
||||||
className='w-full'
|
|
||||||
disabled={isLoading || !bunkerUri.trim()}
|
|
||||||
>
|
|
||||||
{isLoading ? 'Connecting...' : 'Log in'}
|
|
||||||
</Button>
|
|
||||||
</form>
|
|
||||||
</TabsContent>
|
|
||||||
</Tabs>
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||||
<DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-6 overflow-hidden rounded-2xl overflow-y-auto">
|
<DialogContent className='sm:max-w-md p-0 overflow-hidden rounded-2xl'>
|
||||||
<DialogHeader className="px-6 pt-6">
|
<DialogHeader className='px-6 pt-6 pb-0 relative'>
|
||||||
<DialogTitle className="text-lg font-semibold leading-none tracking-tight text-center">
|
<DialogTitle className='text-xl font-semibold text-center'>Log in</DialogTitle>
|
||||||
Log in
|
<DialogDescription className='text-center text-muted-foreground mt-2'>
|
||||||
</DialogTitle>
|
Access your account securely with your preferred method
|
||||||
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
<div className="flex size-40 text-8xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
|
<div className='px-6 py-8 space-y-6'>
|
||||||
🔑
|
<Tabs defaultValue={'nostr' in window ? 'extension' : 'key'} className='w-full'>
|
||||||
</div>
|
<TabsList className='grid grid-cols-3 mb-6'>
|
||||||
|
<TabsTrigger value='extension'>Extension</TabsTrigger>
|
||||||
|
<TabsTrigger value='key'>Nsec</TabsTrigger>
|
||||||
|
<TabsTrigger value='bunker'>Bunker</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
|
||||||
|
<TabsContent value='extension' className='space-y-4'>
|
||||||
|
<div className='text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800'>
|
||||||
|
<Shield className='w-12 h-12 mx-auto mb-3 text-primary' />
|
||||||
|
<p className='text-sm text-gray-600 dark:text-gray-300 mb-4'>
|
||||||
|
Login with one click using the browser extension
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
className='w-full rounded-full py-6'
|
||||||
|
onClick={handleExtensionLogin}
|
||||||
|
disabled={isLoading}
|
||||||
|
>
|
||||||
|
{isLoading ? 'Logging in...' : 'Login with Extension'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value='key' className='space-y-4'>
|
||||||
|
<div className='space-y-4'>
|
||||||
|
<div className='space-y-2'>
|
||||||
|
<label htmlFor='nsec' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
|
||||||
|
Enter your nsec
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
type='password'
|
||||||
|
id='nsec'
|
||||||
|
value={nsec}
|
||||||
|
onChange={(e) => setNsec(e.target.value)}
|
||||||
|
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary'
|
||||||
|
placeholder='nsec1...'
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className='text-center'>
|
||||||
|
<p className='text-sm mb-2 text-gray-600 dark:text-gray-400'>Or upload a key file</p>
|
||||||
|
<input
|
||||||
|
type='file'
|
||||||
|
accept='.txt'
|
||||||
|
className='hidden'
|
||||||
|
ref={fileInputRef}
|
||||||
|
onChange={handleFileUpload}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
className='w-full dark:border-gray-700 dark:bg-gray-800 dark:hover:bg-gray-700'
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
>
|
||||||
|
<Upload className='w-4 h-4 mr-2' />
|
||||||
|
Upload Nsec File
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
className='w-full rounded-full py-6 mt-4'
|
||||||
|
onClick={handleKeyLogin}
|
||||||
|
disabled={isLoading || !nsec.trim()}
|
||||||
|
>
|
||||||
|
{isLoading ? 'Verifying...' : 'Login with Nsec'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value='bunker' className='space-y-4'>
|
||||||
|
<div className='space-y-2'>
|
||||||
|
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
|
||||||
|
Bunker URI
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id='bunkerUri'
|
||||||
|
value={bunkerUri}
|
||||||
|
onChange={(e) => setBunkerUri(e.target.value)}
|
||||||
|
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary'
|
||||||
|
placeholder='bunker://'
|
||||||
|
/>
|
||||||
|
{bunkerUri && !bunkerUri.startsWith('bunker://') && (
|
||||||
|
<p className='text-red-500 text-xs'>URI must start with bunker://</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className='px-6 pb-6 space-y-4 overflow-y-auto'>
|
|
||||||
{/* Extension Login Button - shown if extension is available */}
|
|
||||||
{hasExtension && (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{errors.extension && (
|
|
||||||
<Alert variant="destructive">
|
|
||||||
<AlertTriangle className="h-4 w-4" />
|
|
||||||
<AlertDescription>{errors.extension}</AlertDescription>
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
<Button
|
<Button
|
||||||
className="w-full h-12 px-9"
|
className='w-full rounded-full py-6'
|
||||||
onClick={handleExtensionLogin}
|
onClick={handleBunkerLogin}
|
||||||
disabled={isLoading}
|
disabled={isLoading || !bunkerUri.trim() || !bunkerUri.startsWith('bunker://')}
|
||||||
>
|
>
|
||||||
{isLoading ? 'Logging in...' : 'Log in with Extension'}
|
{isLoading ? 'Connecting...' : 'Login with Bunker'}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</TabsContent>
|
||||||
)}
|
</Tabs>
|
||||||
|
|
||||||
{/* Tabs - wrapped in collapsible if extension is available, otherwise shown directly */}
|
<div className='text-center text-sm'>
|
||||||
{hasExtension ? (
|
<p className='text-gray-600 dark:text-gray-400'>
|
||||||
<Collapsible className="space-y-4" open={isMoreOptionsOpen} onOpenChange={setIsMoreOptionsOpen}>
|
Don't have an account?{' '}
|
||||||
<CollapsibleTrigger asChild>
|
<button
|
||||||
<button className="w-full flex items-center justify-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors">
|
onClick={handleSignupClick}
|
||||||
<span>More Options</span>
|
className='text-primary hover:underline font-medium'
|
||||||
<ChevronDown className={`w-4 h-4 transition-transform ${isMoreOptionsOpen ? 'rotate-180' : ''}`} />
|
>
|
||||||
</button>
|
Sign up
|
||||||
</CollapsibleTrigger>
|
</button>
|
||||||
|
</p>
|
||||||
<CollapsibleContent>
|
</div>
|
||||||
{renderTabs()}
|
|
||||||
</CollapsibleContent>
|
|
||||||
</Collapsible>
|
|
||||||
) : (
|
|
||||||
renderTabs()
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default LoginDialog;
|
export default LoginDialog;
|
||||||
@@ -1,17 +1,19 @@
|
|||||||
// NOTE: This file is stable and usually should not be modified.
|
// NOTE: This file is stable and usually should not be modified.
|
||||||
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
||||||
|
|
||||||
import React, { useState, useEffect, useRef } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { Download, Upload, Eye, EyeOff } from 'lucide-react';
|
import { Download, Key } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button.tsx';
|
||||||
import { Input } from '@/components/ui/input';
|
import {
|
||||||
import { Textarea } from '@/components/ui/textarea';
|
Dialog,
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
DialogContent,
|
||||||
import { toast } from '@/hooks/useToast';
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog.tsx';
|
||||||
|
import { toast } from '@/hooks/useToast.ts';
|
||||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
import { generateSecretKey, nip19 } from 'nostr-tools';
|
||||||
import { useUploadFile } from '@/hooks/useUploadFile';
|
|
||||||
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
|
|
||||||
|
|
||||||
interface SignupDialogProps {
|
interface SignupDialogProps {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
@@ -19,339 +21,143 @@ interface SignupDialogProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
|
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
|
||||||
const [step, setStep] = useState<'generate' | 'download' | 'profile'>('generate');
|
const [step, setStep] = useState<'generate' | 'download' | 'done'>('generate');
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [nsec, setNsec] = useState('');
|
const [nsec, setNsec] = useState('');
|
||||||
const [showKey, setShowKey] = useState(false);
|
|
||||||
const [profileData, setProfileData] = useState({
|
|
||||||
name: '',
|
|
||||||
about: '',
|
|
||||||
picture: ''
|
|
||||||
});
|
|
||||||
const login = useLoginActions();
|
const login = useLoginActions();
|
||||||
const { mutateAsync: publishEvent, isPending: isPublishing } = useNostrPublish();
|
|
||||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
|
||||||
const avatarFileInputRef = useRef<HTMLInputElement>(null);
|
|
||||||
|
|
||||||
// Generate a proper nsec key using nostr-tools
|
// Generate a proper nsec key using nostr-tools
|
||||||
const generateKey = () => {
|
const generateKey = () => {
|
||||||
const sk = generateSecretKey();
|
setIsLoading(true);
|
||||||
setNsec(nip19.nsecEncode(sk));
|
|
||||||
setStep('download');
|
|
||||||
};
|
|
||||||
|
|
||||||
const downloadKey = () => {
|
|
||||||
try {
|
|
||||||
// Create a blob with the key text
|
|
||||||
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
|
|
||||||
const url = globalThis.URL.createObjectURL(blob);
|
|
||||||
|
|
||||||
const decoded = nip19.decode(nsec);
|
|
||||||
if (decoded.type !== 'nsec') {
|
|
||||||
throw new Error('Invalid nsec key');
|
|
||||||
}
|
|
||||||
|
|
||||||
const pubkey = getPublicKey(decoded.data);
|
|
||||||
const npub = nip19.npubEncode(pubkey);
|
|
||||||
const filename = `nostr-${location.hostname.replaceAll(/\./g, '-')}-${npub.slice(5, 9)}.nsec.txt`;
|
|
||||||
|
|
||||||
// Create a temporary link element and trigger download
|
|
||||||
const a = document.createElement('a');
|
|
||||||
a.href = url;
|
|
||||||
a.download = filename;
|
|
||||||
a.style.display = 'none';
|
|
||||||
document.body.appendChild(a);
|
|
||||||
a.click();
|
|
||||||
|
|
||||||
// Clean up immediately
|
|
||||||
globalThis.URL.revokeObjectURL(url);
|
|
||||||
document.body.removeChild(a);
|
|
||||||
|
|
||||||
// Continue to profile step
|
|
||||||
login.nsec(nsec);
|
|
||||||
setStep('profile');
|
|
||||||
} catch {
|
|
||||||
toast({
|
|
||||||
title: 'Download failed',
|
|
||||||
description: 'Could not download the key file. Please copy it manually.',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const file = e.target.files?.[0];
|
|
||||||
if (!file) return;
|
|
||||||
|
|
||||||
// Reset file input
|
|
||||||
e.target.value = '';
|
|
||||||
|
|
||||||
// Validate file type
|
|
||||||
if (!file.type.startsWith('image/')) {
|
|
||||||
toast({
|
|
||||||
title: 'Invalid file type',
|
|
||||||
description: 'Please select an image file for your avatar.',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate file size (max 5MB)
|
|
||||||
if (file.size > 5 * 1024 * 1024) {
|
|
||||||
toast({
|
|
||||||
title: 'File too large',
|
|
||||||
description: 'Avatar image must be smaller than 5MB.',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const tags = await uploadFile(file);
|
// Generate a new secret key
|
||||||
// Get the URL from the first tag
|
const sk = generateSecretKey();
|
||||||
const url = tags[0]?.[1];
|
|
||||||
if (url) {
|
|
||||||
setProfileData(prev => ({ ...prev, picture: url }));
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
toast({
|
|
||||||
title: 'Upload failed',
|
|
||||||
description: 'Failed to upload avatar. Please try again.',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const finishSignup = async (skipProfile = false) => {
|
// Convert to nsec format
|
||||||
try {
|
setNsec(nip19.nsecEncode(sk));
|
||||||
// Publish profile if user provided information
|
setStep('download');
|
||||||
if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) {
|
} catch (error) {
|
||||||
const metadata: Record<string, string> = {};
|
console.error('Failed to generate key:', error);
|
||||||
if (profileData.name) metadata.name = profileData.name;
|
|
||||||
if (profileData.about) metadata.about = profileData.about;
|
|
||||||
if (profileData.picture) metadata.picture = profileData.picture;
|
|
||||||
|
|
||||||
await publishEvent({
|
|
||||||
kind: 0,
|
|
||||||
content: JSON.stringify(metadata),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
toast({
|
toast({
|
||||||
title: 'Profile Setup Failed',
|
title: 'Error',
|
||||||
description: 'Your account was created but profile setup failed. You can update it later.',
|
description: 'Failed to generate key. Please try again.',
|
||||||
variant: 'destructive',
|
variant: 'destructive',
|
||||||
});
|
});
|
||||||
} finally {
|
} finally {
|
||||||
onClose();
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getTitle = () => {
|
const downloadKey = () => {
|
||||||
if (step === 'generate') return 'Sign up';
|
// Create a blob with the key text
|
||||||
if (step === 'download') return 'Secret Key';
|
const blob = new Blob([nsec], { type: 'text/plain' });
|
||||||
if (step === 'profile') return 'Create Your Profile';
|
const url = globalThis.URL.createObjectURL(blob);
|
||||||
|
|
||||||
|
// Create a temporary link element and trigger download
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = 'nsec.txt';
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
|
||||||
|
// Clean up
|
||||||
|
globalThis.URL.revokeObjectURL(url);
|
||||||
|
document.body.removeChild(a);
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: 'Key downloaded',
|
||||||
|
description: 'Your key has been downloaded. Keep it safe!',
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Reset state when dialog opens
|
const finishSignup = () => {
|
||||||
useEffect(() => {
|
login.nsec(nsec);
|
||||||
if (isOpen) {
|
|
||||||
setStep('generate');
|
setStep('done');
|
||||||
setNsec('');
|
onClose();
|
||||||
setShowKey(false);
|
|
||||||
setProfileData({ name: '', about: '', picture: '' });
|
toast({
|
||||||
}
|
title: 'Account created',
|
||||||
}, [isOpen]);
|
description: 'You are now logged in.',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||||
<DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-6 overflow-hidden rounded-2xl overflow-y-auto">
|
<DialogContent className='sm:max-w-md p-0 overflow-hidden rounded-2xl'>
|
||||||
<DialogHeader className="px-6 pt-6">
|
<DialogHeader className='px-6 pt-6 pb-0 relative'>
|
||||||
<DialogTitle className="text-lg font-semibold leading-none tracking-tight text-center">
|
<DialogTitle className='text-xl font-semibold text-center'>
|
||||||
{getTitle()}
|
{step === 'generate' && 'Create Your Account'}
|
||||||
|
{step === 'download' && 'Download Your Key'}
|
||||||
|
{step === 'done' && 'Setting Up Your Account'}
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
|
<DialogDescription className='text-center text-muted-foreground mt-2'>
|
||||||
|
{step === 'generate' && 'Generate a secure key for your account'}
|
||||||
|
{step === 'download' && "Keep your key safe - you'll need it to log in"}
|
||||||
|
{step === 'done' && 'Finalizing your account setup'}
|
||||||
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
<div className='px-6 pb-6 space-y-4 overflow-y-auto flex-1'>
|
<div className='px-6 py-8 space-y-6'>
|
||||||
{/* Generate Step */}
|
|
||||||
{step === 'generate' && (
|
{step === 'generate' && (
|
||||||
<div className='text-center space-y-6'>
|
<div className='text-center space-y-6'>
|
||||||
<div className="flex size-40 text-8xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
|
<div className='p-4 rounded-lg bg-gray-50 dark:bg-gray-800 flex items-center justify-center'>
|
||||||
🔑
|
<Key className='w-16 h-16 text-primary' />
|
||||||
</div>
|
</div>
|
||||||
|
<p className='text-sm text-gray-600 dark:text-gray-300'>
|
||||||
<Button className="w-full h-12 px-9" onClick={generateKey}>
|
We'll generate a secure key for your account. You'll need this key to log in later.
|
||||||
Generate key
|
</p>
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Download Step */}
|
|
||||||
{step === 'download' && (
|
|
||||||
<div className='space-y-4'>
|
|
||||||
<div className="flex size-16 text-4xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
|
|
||||||
🔑
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="relative">
|
|
||||||
<Input
|
|
||||||
type={showKey ? "text" : "password"}
|
|
||||||
value={nsec}
|
|
||||||
readOnly
|
|
||||||
className="pr-10 font-mono text-sm"
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
|
|
||||||
onClick={() => setShowKey(!showKey)}
|
|
||||||
>
|
|
||||||
{showKey ? (
|
|
||||||
<EyeOff className="h-4 w-4 text-muted-foreground" />
|
|
||||||
) : (
|
|
||||||
<Eye className="h-4 w-4 text-muted-foreground" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
className="w-full h-12 px-9"
|
className='w-full rounded-full py-6'
|
||||||
onClick={downloadKey}
|
onClick={generateKey}
|
||||||
|
disabled={isLoading}
|
||||||
>
|
>
|
||||||
<Download className="size-4" />
|
{isLoading ? 'Generating key...' : 'Generate my key'}
|
||||||
Download key
|
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<div className='mx-auto max-w-sm'>
|
|
||||||
<div className='p-3 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-800'>
|
|
||||||
<div className='flex items-center gap-2 mb-1'>
|
|
||||||
<span className='text-xs font-semibold text-amber-800 dark:text-amber-200'>
|
|
||||||
Important Warning
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<p className='text-xs text-amber-900 dark:text-amber-300'>
|
|
||||||
This key is your primary and only means of accessing your account. Store it safely and securely. Please download your key to continue.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Profile Step */}
|
{step === 'download' && (
|
||||||
{step === 'profile' && (
|
<div className='space-y-6'>
|
||||||
<div className='text-center space-y-4'>
|
<div className='p-4 rounded-lg border bg-gray-50 dark:bg-gray-800 overflow-auto'>
|
||||||
{/* Publishing status indicator */}
|
<code className='text-xs break-all'>{nsec}</code>
|
||||||
{isPublishing && (
|
|
||||||
<div className='p-4 rounded-lg bg-muted border'>
|
|
||||||
<div className='flex items-center justify-center gap-3'>
|
|
||||||
<div className='w-5 h-5 border-2 border-primary border-t-transparent rounded-full animate-spin' />
|
|
||||||
<span className='text-sm font-medium'>
|
|
||||||
Publishing your profile...
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Profile form */}
|
|
||||||
<div className={`space-y-4 text-left ${isPublishing ? 'opacity-50 pointer-events-none' : ''}`}>
|
|
||||||
<div className='space-y-2'>
|
|
||||||
<label htmlFor='profile-name' className='text-sm font-medium'>
|
|
||||||
Display Name
|
|
||||||
</label>
|
|
||||||
<Input
|
|
||||||
id='profile-name'
|
|
||||||
value={profileData.name}
|
|
||||||
onChange={(e) => setProfileData(prev => ({ ...prev, name: e.target.value }))}
|
|
||||||
placeholder='Your name'
|
|
||||||
disabled={isPublishing}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className='space-y-2'>
|
|
||||||
<label htmlFor='profile-about' className='text-sm font-medium'>
|
|
||||||
Bio
|
|
||||||
</label>
|
|
||||||
<Textarea
|
|
||||||
id='profile-about'
|
|
||||||
value={profileData.about}
|
|
||||||
onChange={(e) => setProfileData(prev => ({ ...prev, about: e.target.value }))}
|
|
||||||
placeholder='Tell others about yourself...'
|
|
||||||
className='resize-none'
|
|
||||||
rows={3}
|
|
||||||
disabled={isPublishing}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className='space-y-2'>
|
|
||||||
<label htmlFor='profile-picture' className='text-sm font-medium'>
|
|
||||||
Avatar
|
|
||||||
</label>
|
|
||||||
<div className='flex gap-2'>
|
|
||||||
<Input
|
|
||||||
id='profile-picture'
|
|
||||||
value={profileData.picture}
|
|
||||||
onChange={(e) => setProfileData(prev => ({ ...prev, picture: e.target.value }))}
|
|
||||||
placeholder='https://example.com/your-avatar.jpg'
|
|
||||||
className='flex-1'
|
|
||||||
disabled={isPublishing}
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
type='file'
|
|
||||||
accept='image/*'
|
|
||||||
className='hidden'
|
|
||||||
ref={avatarFileInputRef}
|
|
||||||
onChange={handleAvatarUpload}
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
type='button'
|
|
||||||
variant='outline'
|
|
||||||
size='icon'
|
|
||||||
onClick={() => avatarFileInputRef.current?.click()}
|
|
||||||
disabled={isUploading || isPublishing}
|
|
||||||
title='Upload avatar image'
|
|
||||||
>
|
|
||||||
{isUploading ? (
|
|
||||||
<div className='w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin' />
|
|
||||||
) : (
|
|
||||||
<Upload className='w-4 h-4' />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Action buttons */}
|
<div className='text-sm text-gray-600 dark:text-gray-300 space-y-2'>
|
||||||
<div className='space-y-3'>
|
<p className='font-medium text-red-500'>Important:</p>
|
||||||
<Button
|
<ul className='list-disc pl-5 space-y-1'>
|
||||||
className='w-full'
|
<li>This is your only way to access your account</li>
|
||||||
onClick={() => finishSignup(false)}
|
<li>Store it somewhere safe</li>
|
||||||
disabled={isPublishing || isUploading}
|
<li>Never share this key with anyone</li>
|
||||||
>
|
</ul>
|
||||||
{isPublishing ? (
|
</div>
|
||||||
<>
|
|
||||||
<div className='w-4 h-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin' />
|
|
||||||
Creating Profile...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
'Create profile'
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
|
<div className='flex flex-col space-y-3'>
|
||||||
<Button
|
<Button
|
||||||
variant='outline'
|
variant='outline'
|
||||||
className='w-full'
|
className='w-full'
|
||||||
onClick={() => finishSignup(true)}
|
onClick={downloadKey}
|
||||||
disabled={isPublishing || isUploading}
|
|
||||||
>
|
>
|
||||||
{isPublishing ? (
|
<Download className='w-4 h-4 mr-2' />
|
||||||
'Setting up account...'
|
Download Key
|
||||||
) : (
|
</Button>
|
||||||
'Skip for now'
|
|
||||||
)}
|
<Button
|
||||||
|
className='w-full rounded-full py-6'
|
||||||
|
onClick={finishSignup}
|
||||||
|
>
|
||||||
|
I've saved my key, continue
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{step === 'done' && (
|
||||||
|
<div className='flex justify-center items-center py-8'>
|
||||||
|
<div className='animate-spin rounded-full h-12 w-12 border-b-2 border-primary'></div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|||||||
@@ -1,153 +0,0 @@
|
|||||||
import { useState } from 'react';
|
|
||||||
import { Link } from 'react-router-dom';
|
|
||||||
import { NostrEvent } from '@nostrify/nostrify';
|
|
||||||
import { nip19 } from 'nostr-tools';
|
|
||||||
import { useAuthor } from '@/hooks/useAuthor';
|
|
||||||
import { useComments } from '@/hooks/useComments';
|
|
||||||
import { CommentForm } from './CommentForm';
|
|
||||||
import { NoteContent } from '@/components/NoteContent';
|
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
|
||||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
|
||||||
import { DropdownMenu, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
|
||||||
import { MessageSquare, ChevronDown, ChevronRight, MoreHorizontal } from 'lucide-react';
|
|
||||||
import { formatDistanceToNow } from 'date-fns';
|
|
||||||
import { genUserName } from '@/lib/genUserName';
|
|
||||||
|
|
||||||
interface CommentProps {
|
|
||||||
root: NostrEvent | URL;
|
|
||||||
comment: NostrEvent;
|
|
||||||
depth?: number;
|
|
||||||
maxDepth?: number;
|
|
||||||
limit?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: CommentProps) {
|
|
||||||
const [showReplyForm, setShowReplyForm] = useState(false);
|
|
||||||
const [showReplies, setShowReplies] = useState(depth < 2); // Auto-expand first 2 levels
|
|
||||||
|
|
||||||
const author = useAuthor(comment.pubkey);
|
|
||||||
const { data: commentsData } = useComments(root, limit);
|
|
||||||
|
|
||||||
const metadata = author.data?.metadata;
|
|
||||||
const displayName = metadata?.name ?? genUserName(comment.pubkey)
|
|
||||||
const timeAgo = formatDistanceToNow(new Date(comment.created_at * 1000), { addSuffix: true });
|
|
||||||
|
|
||||||
// Get direct replies to this comment
|
|
||||||
const replies = commentsData?.getDirectReplies(comment.id) || [];
|
|
||||||
const hasReplies = replies.length > 0;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={`space-y-3 ${depth > 0 ? 'ml-6 border-l-2 border-muted pl-4' : ''}`}>
|
|
||||||
<Card className="bg-card/50">
|
|
||||||
<CardContent className="p-4">
|
|
||||||
<div className="space-y-3">
|
|
||||||
{/* Comment Header */}
|
|
||||||
<div className="flex items-start justify-between">
|
|
||||||
<div className="flex items-center space-x-3">
|
|
||||||
<Link to={`/${nip19.npubEncode(comment.pubkey)}`}>
|
|
||||||
<Avatar className="h-8 w-8 hover:ring-2 hover:ring-primary/30 transition-all cursor-pointer">
|
|
||||||
<AvatarImage src={metadata?.picture} />
|
|
||||||
<AvatarFallback className="text-xs">
|
|
||||||
{displayName.charAt(0)}
|
|
||||||
</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
</Link>
|
|
||||||
<div>
|
|
||||||
<Link
|
|
||||||
to={`/${nip19.npubEncode(comment.pubkey)}`}
|
|
||||||
className="font-medium text-sm hover:text-primary transition-colors"
|
|
||||||
>
|
|
||||||
{displayName}
|
|
||||||
</Link>
|
|
||||||
<p className="text-xs text-muted-foreground">{timeAgo}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Comment Content */}
|
|
||||||
<div className="text-sm">
|
|
||||||
<NoteContent event={comment} className="text-sm" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Comment Actions */}
|
|
||||||
<div className="flex items-center justify-between pt-2">
|
|
||||||
<div className="flex items-center space-x-2">
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => setShowReplyForm(!showReplyForm)}
|
|
||||||
className="h-8 px-2 text-xs"
|
|
||||||
>
|
|
||||||
<MessageSquare className="h-3 w-3 mr-1" />
|
|
||||||
Reply
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
{hasReplies && (
|
|
||||||
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
|
|
||||||
<CollapsibleTrigger asChild>
|
|
||||||
<Button variant="ghost" size="sm" className="h-8 px-2 text-xs">
|
|
||||||
{showReplies ? (
|
|
||||||
<ChevronDown className="h-3 w-3 mr-1" />
|
|
||||||
) : (
|
|
||||||
<ChevronRight className="h-3 w-3 mr-1" />
|
|
||||||
)}
|
|
||||||
{replies.length} {replies.length === 1 ? 'reply' : 'replies'}
|
|
||||||
</Button>
|
|
||||||
</CollapsibleTrigger>
|
|
||||||
</Collapsible>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Comment menu */}
|
|
||||||
<DropdownMenu>
|
|
||||||
<DropdownMenuTrigger asChild>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
className="h-8 px-2 text-xs"
|
|
||||||
aria-label="Comment options"
|
|
||||||
>
|
|
||||||
<MoreHorizontal className="h-3 w-3" />
|
|
||||||
</Button>
|
|
||||||
</DropdownMenuTrigger>
|
|
||||||
</DropdownMenu>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Reply Form */}
|
|
||||||
{showReplyForm && (
|
|
||||||
<div className="ml-6">
|
|
||||||
<CommentForm
|
|
||||||
root={root}
|
|
||||||
reply={comment}
|
|
||||||
onSuccess={() => setShowReplyForm(false)}
|
|
||||||
placeholder="Write a reply..."
|
|
||||||
compact
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Replies */}
|
|
||||||
{hasReplies && (
|
|
||||||
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
|
|
||||||
<CollapsibleContent className="space-y-3">
|
|
||||||
{replies.map((reply) => (
|
|
||||||
<Comment
|
|
||||||
key={reply.id}
|
|
||||||
root={root}
|
|
||||||
comment={reply}
|
|
||||||
depth={depth + 1}
|
|
||||||
maxDepth={maxDepth}
|
|
||||||
limit={limit}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</CollapsibleContent>
|
|
||||||
</Collapsible>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
import { useState } from 'react';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Textarea } from '@/components/ui/textarea';
|
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
|
||||||
import { usePostComment } from '@/hooks/usePostComment';
|
|
||||||
import { LoginArea } from '@/components/auth/LoginArea';
|
|
||||||
import { NostrEvent } from '@nostrify/nostrify';
|
|
||||||
import { MessageSquare, Send } from 'lucide-react';
|
|
||||||
|
|
||||||
interface CommentFormProps {
|
|
||||||
root: NostrEvent | URL;
|
|
||||||
reply?: NostrEvent | URL;
|
|
||||||
onSuccess?: () => void;
|
|
||||||
placeholder?: string;
|
|
||||||
compact?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function CommentForm({
|
|
||||||
root,
|
|
||||||
reply,
|
|
||||||
onSuccess,
|
|
||||||
placeholder = "Write a comment...",
|
|
||||||
compact = false
|
|
||||||
}: CommentFormProps) {
|
|
||||||
const [content, setContent] = useState('');
|
|
||||||
const { user } = useCurrentUser();
|
|
||||||
const { mutate: postComment, isPending } = usePostComment();
|
|
||||||
|
|
||||||
const handleSubmit = (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
|
|
||||||
if (!content.trim() || !user) return;
|
|
||||||
|
|
||||||
postComment(
|
|
||||||
{ content: content.trim(), root, reply },
|
|
||||||
{
|
|
||||||
onSuccess: () => {
|
|
||||||
setContent('');
|
|
||||||
onSuccess?.();
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
return (
|
|
||||||
<Card className={compact ? "border-dashed" : ""}>
|
|
||||||
<CardContent className={compact ? "p-4" : "p-6"}>
|
|
||||||
<div className="text-center space-y-4">
|
|
||||||
<div className="flex items-center justify-center space-x-2 text-muted-foreground">
|
|
||||||
<MessageSquare className="h-5 w-5" />
|
|
||||||
<span>Sign in to {reply ? 'reply' : 'comment'}</span>
|
|
||||||
</div>
|
|
||||||
<LoginArea />
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className={compact ? "border-dashed" : ""}>
|
|
||||||
<CardContent className={compact ? "p-4" : "p-6"}>
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-4">
|
|
||||||
<Textarea
|
|
||||||
value={content}
|
|
||||||
onChange={(e) => setContent(e.target.value)}
|
|
||||||
placeholder={placeholder}
|
|
||||||
className={compact ? "min-h-[80px]" : "min-h-[100px]"}
|
|
||||||
disabled={isPending}
|
|
||||||
/>
|
|
||||||
<div className="flex justify-between items-center">
|
|
||||||
<span className="text-sm text-muted-foreground">
|
|
||||||
{reply ? 'Replying to comment' : 'Adding to the discussion'}
|
|
||||||
</span>
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
disabled={!content.trim() || isPending}
|
|
||||||
size={compact ? "sm" : "default"}
|
|
||||||
>
|
|
||||||
<Send className="h-4 w-4 mr-2" />
|
|
||||||
{isPending ? 'Posting...' : (reply ? 'Reply' : 'Comment')}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
import { useComments } from '@/hooks/useComments';
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
|
||||||
import { MessageSquare } from 'lucide-react';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import type { NostrEvent } from '@nostrify/nostrify';
|
|
||||||
import { CommentForm } from './CommentForm';
|
|
||||||
import { Comment } from './Comment';
|
|
||||||
|
|
||||||
interface CommentsSectionProps {
|
|
||||||
root: NostrEvent | URL;
|
|
||||||
title?: string;
|
|
||||||
emptyStateMessage?: string;
|
|
||||||
emptyStateSubtitle?: string;
|
|
||||||
className?: string;
|
|
||||||
limit?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function CommentsSection({
|
|
||||||
root,
|
|
||||||
title = "Comments",
|
|
||||||
emptyStateMessage = "No comments yet",
|
|
||||||
emptyStateSubtitle = "Be the first to share your thoughts!",
|
|
||||||
className,
|
|
||||||
limit = 500,
|
|
||||||
}: CommentsSectionProps) {
|
|
||||||
const { data: commentsData, isLoading, error } = useComments(root, limit);
|
|
||||||
const comments = commentsData?.topLevelComments || [];
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
return (
|
|
||||||
<Card className="rounded-none sm:rounded-lg mx-0 sm:mx-0">
|
|
||||||
<CardContent className="px-2 py-6 sm:p-6">
|
|
||||||
<div className="text-center text-muted-foreground">
|
|
||||||
<MessageSquare className="h-8 w-8 mx-auto mb-2 opacity-50" />
|
|
||||||
<p>Failed to load comments</p>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className={cn("rounded-none sm:rounded-lg mx-0 sm:mx-0", className)}>
|
|
||||||
<CardHeader className="px-2 pt-6 pb-4 sm:p-6">
|
|
||||||
<CardTitle className="flex items-center space-x-2">
|
|
||||||
<MessageSquare className="h-5 w-5" />
|
|
||||||
<span>{title}</span>
|
|
||||||
{!isLoading && (
|
|
||||||
<span className="text-sm font-normal text-muted-foreground">
|
|
||||||
({comments.length})
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="px-2 pb-6 pt-4 sm:p-6 sm:pt-0 space-y-6">
|
|
||||||
{/* Comment Form */}
|
|
||||||
<CommentForm root={root} />
|
|
||||||
|
|
||||||
{/* Comments List */}
|
|
||||||
{isLoading ? (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{[...Array(3)].map((_, i) => (
|
|
||||||
<Card key={i} className="bg-card/50">
|
|
||||||
<CardContent className="p-4">
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div className="flex items-center space-x-3">
|
|
||||||
<Skeleton className="h-8 w-8 rounded-full" />
|
|
||||||
<div className="space-y-1">
|
|
||||||
<Skeleton className="h-4 w-24" />
|
|
||||||
<Skeleton className="h-3 w-16" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<Skeleton className="h-16 w-full" />
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : comments.length === 0 ? (
|
|
||||||
<div className="text-center py-8 text-muted-foreground">
|
|
||||||
<MessageSquare className="h-12 w-12 mx-auto mb-4 opacity-30" />
|
|
||||||
<p className="text-lg font-medium mb-2">{emptyStateMessage}</p>
|
|
||||||
<p className="text-sm">{emptyStateSubtitle}</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{comments.map((comment) => (
|
|
||||||
<Comment
|
|
||||||
key={comment.id}
|
|
||||||
root={root}
|
|
||||||
comment={comment}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,409 +0,0 @@
|
|||||||
import { useState, useRef, useEffect, useCallback, memo } from 'react';
|
|
||||||
import { useConversationMessages } from '@/hooks/useConversationMessages';
|
|
||||||
import { useDMContext } from '@/hooks/useDMContext';
|
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
|
||||||
import { useAuthor } from '@/hooks/useAuthor';
|
|
||||||
import { genUserName } from '@/lib/genUserName';
|
|
||||||
import { MESSAGE_PROTOCOL, PROTOCOL_MODE, type MessageProtocol } from '@/lib/dmConstants';
|
|
||||||
import { formatConversationTime, formatFullDateTime } from '@/lib/dmUtils';
|
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Card } from '@/components/ui/card';
|
|
||||||
import { Textarea } from '@/components/ui/textarea';
|
|
||||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
|
||||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
|
||||||
import { ArrowLeft, Send, Loader2, AlertTriangle, Key, ShieldCheck } from 'lucide-react';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { NoteContent } from '@/components/NoteContent';
|
|
||||||
import type { NostrEvent } from '@nostrify/nostrify';
|
|
||||||
|
|
||||||
interface DMChatAreaProps {
|
|
||||||
pubkey: string | null;
|
|
||||||
onBack?: () => void;
|
|
||||||
className?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const MessageBubble = memo(({
|
|
||||||
message,
|
|
||||||
isFromCurrentUser
|
|
||||||
}: {
|
|
||||||
message: {
|
|
||||||
id: string;
|
|
||||||
pubkey: string;
|
|
||||||
kind: number;
|
|
||||||
tags: string[][];
|
|
||||||
decryptedContent?: string;
|
|
||||||
decryptedEvent?: NostrEvent;
|
|
||||||
error?: string;
|
|
||||||
created_at: number;
|
|
||||||
isSending?: boolean;
|
|
||||||
};
|
|
||||||
isFromCurrentUser: boolean;
|
|
||||||
}) => {
|
|
||||||
// For NIP-17, use inner message kind (14/15); for NIP-04, use message kind (4)
|
|
||||||
const actualKind = message.decryptedEvent?.kind || message.kind;
|
|
||||||
const isNIP4Message = message.kind === 4;
|
|
||||||
const isFileAttachment = actualKind === 15; // Kind 15 = files/attachments
|
|
||||||
|
|
||||||
// Create a NostrEvent object for NoteContent (only used for kind 15)
|
|
||||||
// For NIP-17 file attachments, use the decryptedEvent which has the actual tags
|
|
||||||
const messageEvent: NostrEvent = message.decryptedEvent || {
|
|
||||||
id: message.id,
|
|
||||||
pubkey: message.pubkey,
|
|
||||||
created_at: message.created_at,
|
|
||||||
kind: message.kind,
|
|
||||||
tags: message.tags,
|
|
||||||
content: message.decryptedContent || '',
|
|
||||||
sig: '', // Not needed for display
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={cn("flex mb-4", isFromCurrentUser ? "justify-end" : "justify-start")}>
|
|
||||||
<div className={cn(
|
|
||||||
"max-w-[70%] rounded-lg px-4 py-2",
|
|
||||||
isFromCurrentUser
|
|
||||||
? "bg-primary text-primary-foreground"
|
|
||||||
: "bg-muted"
|
|
||||||
)}>
|
|
||||||
{message.error ? (
|
|
||||||
<Tooltip delayDuration={200}>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<p className="text-sm italic opacity-70 cursor-help">🔒 Failed to decrypt</p>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent>
|
|
||||||
<p className="text-xs">{message.error}</p>
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
) : isFileAttachment ? (
|
|
||||||
// Kind 15: Use NoteContent to render files/media with imeta tags
|
|
||||||
<div className="text-sm">
|
|
||||||
<NoteContent event={messageEvent} className="whitespace-pre-wrap break-words" />
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
// Kind 4 (NIP-04) and Kind 14 (NIP-17 text): Display plain text
|
|
||||||
<p className="text-sm whitespace-pre-wrap break-words">
|
|
||||||
{message.decryptedContent}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
<div className="flex items-center gap-2 mt-1">
|
|
||||||
<TooltipProvider>
|
|
||||||
<Tooltip delayDuration={200}>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<span className={cn(
|
|
||||||
"text-xs opacity-70 cursor-default",
|
|
||||||
isFromCurrentUser ? "text-primary-foreground" : "text-muted-foreground"
|
|
||||||
)}>
|
|
||||||
{formatConversationTime(message.created_at)}
|
|
||||||
</span>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent>
|
|
||||||
<p className="text-xs">{formatFullDateTime(message.created_at)}</p>
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</TooltipProvider>
|
|
||||||
|
|
||||||
<TooltipProvider>
|
|
||||||
<Tooltip delayDuration={200}>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<span className={cn(
|
|
||||||
"flex-shrink-0 opacity-50",
|
|
||||||
isFromCurrentUser ? "text-primary-foreground" : "text-muted-foreground"
|
|
||||||
)}>
|
|
||||||
{message.kind === 4 ? (
|
|
||||||
<Key className="h-3 w-3" />
|
|
||||||
) : (
|
|
||||||
<ShieldCheck className="h-3 w-3" />
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent>
|
|
||||||
<p className="text-xs">
|
|
||||||
{message.kind === 4 && "NIP-04 Kind 4 (Legacy DM)"}
|
|
||||||
{message.kind === 14 && "NIP-17 Kind 14 (Private Message)"}
|
|
||||||
{message.kind === 15 && "NIP-17 Kind 15 (Media)"}
|
|
||||||
{message.kind !== 4 && message.kind !== 14 && message.kind !== 15 && `Kind ${message.kind}`}
|
|
||||||
</p>
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</TooltipProvider>
|
|
||||||
{isNIP4Message && (
|
|
||||||
<TooltipProvider>
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<div className="flex-shrink-0">
|
|
||||||
<AlertTriangle className="h-3 w-3 text-yellow-600 dark:text-yellow-500" />
|
|
||||||
</div>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent>
|
|
||||||
<p className="text-xs">Uses outdated NIP-04 encryption</p>
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</TooltipProvider>
|
|
||||||
)}
|
|
||||||
{message.isSending && (
|
|
||||||
<Loader2 className="h-3 w-3 animate-spin opacity-70" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
MessageBubble.displayName = 'MessageBubble';
|
|
||||||
|
|
||||||
const ChatHeader = ({ pubkey, onBack }: { pubkey: string; onBack?: () => void }) => {
|
|
||||||
const author = useAuthor(pubkey);
|
|
||||||
const metadata = author.data?.metadata;
|
|
||||||
|
|
||||||
const displayName = metadata?.name || genUserName(pubkey);
|
|
||||||
const avatarUrl = metadata?.picture;
|
|
||||||
const initials = displayName.slice(0, 2).toUpperCase();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="p-4 border-b flex items-center gap-3">
|
|
||||||
{onBack && (
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
onClick={onBack}
|
|
||||||
className="md:hidden"
|
|
||||||
>
|
|
||||||
<ArrowLeft className="h-5 w-5" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Avatar className="h-10 w-10">
|
|
||||||
<AvatarImage src={avatarUrl} alt={displayName} />
|
|
||||||
<AvatarFallback>{initials}</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<h2 className="font-semibold truncate">{displayName}</h2>
|
|
||||||
{metadata?.nip05 && (
|
|
||||||
<p className="text-xs text-muted-foreground truncate">{metadata.nip05}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const EmptyState = ({ isLoading }: { isLoading: boolean }) => {
|
|
||||||
return (
|
|
||||||
<div className="h-full flex items-center justify-center p-8">
|
|
||||||
<div className="text-center text-muted-foreground max-w-sm">
|
|
||||||
{isLoading ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
|
|
||||||
<p className="text-sm">Loading conversations...</p>
|
|
||||||
<p className="text-xs mt-2">
|
|
||||||
Fetching encrypted messages from relays
|
|
||||||
</p>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<p className="text-sm">Select a conversation to start messaging</p>
|
|
||||||
<p className="text-xs mt-2">
|
|
||||||
Your messages are encrypted and stored locally
|
|
||||||
</p>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const DMChatArea = ({ pubkey, onBack, className }: DMChatAreaProps) => {
|
|
||||||
const { user } = useCurrentUser();
|
|
||||||
const { sendMessage, protocolMode, isLoading } = useDMContext();
|
|
||||||
const { messages, hasMoreMessages, loadEarlierMessages } = useConversationMessages(pubkey || '');
|
|
||||||
|
|
||||||
const [messageText, setMessageText] = useState('');
|
|
||||||
const [isSending, setIsSending] = useState(false);
|
|
||||||
const [isLoadingMore, setIsLoadingMore] = useState(false);
|
|
||||||
|
|
||||||
// Determine default protocol based on mode
|
|
||||||
const getDefaultProtocol = () => {
|
|
||||||
if (protocolMode === PROTOCOL_MODE.NIP04_ONLY) return MESSAGE_PROTOCOL.NIP04;
|
|
||||||
if (protocolMode === PROTOCOL_MODE.NIP17_ONLY) return MESSAGE_PROTOCOL.NIP17;
|
|
||||||
if (protocolMode === PROTOCOL_MODE.NIP04_OR_NIP17) return MESSAGE_PROTOCOL.NIP17;
|
|
||||||
// Fallback to NIP-17 for any unexpected mode
|
|
||||||
return MESSAGE_PROTOCOL.NIP17;
|
|
||||||
};
|
|
||||||
|
|
||||||
const [selectedProtocol, setSelectedProtocol] = useState<MessageProtocol>(getDefaultProtocol());
|
|
||||||
const scrollAreaRef = useRef<HTMLDivElement>(null);
|
|
||||||
|
|
||||||
// Determine if selection is allowed
|
|
||||||
const allowSelection = protocolMode === PROTOCOL_MODE.NIP04_OR_NIP17;
|
|
||||||
|
|
||||||
// Auto-scroll to bottom when new messages arrive
|
|
||||||
useEffect(() => {
|
|
||||||
if (scrollAreaRef.current) {
|
|
||||||
const scrollContainer = scrollAreaRef.current.querySelector('[data-radix-scroll-area-viewport]');
|
|
||||||
if (scrollContainer) {
|
|
||||||
scrollContainer.scrollTop = scrollContainer.scrollHeight;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [messages.length]);
|
|
||||||
|
|
||||||
const handleSend = useCallback(async () => {
|
|
||||||
if (!messageText.trim() || !pubkey || !user) return;
|
|
||||||
|
|
||||||
setIsSending(true);
|
|
||||||
try {
|
|
||||||
await sendMessage({
|
|
||||||
recipientPubkey: pubkey,
|
|
||||||
content: messageText.trim(),
|
|
||||||
protocol: selectedProtocol,
|
|
||||||
});
|
|
||||||
setMessageText('');
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to send message:', error);
|
|
||||||
} finally {
|
|
||||||
setIsSending(false);
|
|
||||||
}
|
|
||||||
}, [messageText, pubkey, user, sendMessage, selectedProtocol]);
|
|
||||||
|
|
||||||
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
|
||||||
if (e.key === 'Enter' && !e.shiftKey) {
|
|
||||||
e.preventDefault();
|
|
||||||
handleSend();
|
|
||||||
}
|
|
||||||
}, [handleSend]);
|
|
||||||
|
|
||||||
const handleLoadMore = useCallback(async () => {
|
|
||||||
if (!scrollAreaRef.current || isLoadingMore) return;
|
|
||||||
|
|
||||||
const scrollContainer = scrollAreaRef.current.querySelector('[data-radix-scroll-area-viewport]');
|
|
||||||
if (!scrollContainer) return;
|
|
||||||
|
|
||||||
// Store current scroll position and height
|
|
||||||
const previousScrollHeight = scrollContainer.scrollHeight;
|
|
||||||
const previousScrollTop = scrollContainer.scrollTop;
|
|
||||||
|
|
||||||
setIsLoadingMore(true);
|
|
||||||
|
|
||||||
// Load more messages
|
|
||||||
loadEarlierMessages();
|
|
||||||
|
|
||||||
// Wait for DOM to update, then restore relative scroll position
|
|
||||||
setTimeout(() => {
|
|
||||||
if (scrollContainer) {
|
|
||||||
const newScrollHeight = scrollContainer.scrollHeight;
|
|
||||||
const heightDifference = newScrollHeight - previousScrollHeight;
|
|
||||||
scrollContainer.scrollTop = previousScrollTop + heightDifference;
|
|
||||||
}
|
|
||||||
setIsLoadingMore(false);
|
|
||||||
}, 0);
|
|
||||||
}, [loadEarlierMessages, isLoadingMore]);
|
|
||||||
|
|
||||||
if (!pubkey) {
|
|
||||||
return (
|
|
||||||
<Card className={cn("h-full", className)}>
|
|
||||||
<EmptyState isLoading={isLoading} />
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
return (
|
|
||||||
<Card className={cn("h-full flex items-center justify-center", className)}>
|
|
||||||
<div className="text-center text-muted-foreground">
|
|
||||||
<p className="text-sm">Please log in to view messages</p>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className={cn("h-full flex flex-col", className)}>
|
|
||||||
<ChatHeader pubkey={pubkey} onBack={onBack} />
|
|
||||||
|
|
||||||
<ScrollArea ref={scrollAreaRef} className="flex-1 p-4">
|
|
||||||
{messages.length === 0 ? (
|
|
||||||
<div className="h-full flex items-center justify-center">
|
|
||||||
<div className="text-center text-muted-foreground">
|
|
||||||
<p className="text-sm">No messages yet</p>
|
|
||||||
<p className="text-xs mt-1">Send a message to start the conversation</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div>
|
|
||||||
{hasMoreMessages && (
|
|
||||||
<div className="flex justify-center mb-4">
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={handleLoadMore}
|
|
||||||
disabled={isLoadingMore}
|
|
||||||
className="text-xs"
|
|
||||||
>
|
|
||||||
{isLoadingMore ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="h-3 w-3 animate-spin mr-2" />
|
|
||||||
Loading...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
'Load Earlier Messages'
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{messages.map((message) => (
|
|
||||||
<MessageBubble
|
|
||||||
key={message.id}
|
|
||||||
message={message}
|
|
||||||
isFromCurrentUser={message.pubkey === user.pubkey}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</ScrollArea>
|
|
||||||
|
|
||||||
<div className="p-4 border-t">
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<Textarea
|
|
||||||
value={messageText}
|
|
||||||
onChange={(e) => setMessageText(e.target.value)}
|
|
||||||
onKeyDown={handleKeyDown}
|
|
||||||
placeholder="Type a message... (Enter to send, Shift+Enter for new line)"
|
|
||||||
className="min-h-[80px] resize-none"
|
|
||||||
disabled={isSending}
|
|
||||||
/>
|
|
||||||
<div className="flex flex-col gap-2">
|
|
||||||
<Button
|
|
||||||
onClick={handleSend}
|
|
||||||
disabled={!messageText.trim() || isSending}
|
|
||||||
size="icon"
|
|
||||||
className="h-[44px] w-[90px]"
|
|
||||||
>
|
|
||||||
{isSending ? (
|
|
||||||
<Loader2 className="h-5 w-5 animate-spin" />
|
|
||||||
) : (
|
|
||||||
<Send className="h-5 w-5" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
<Select
|
|
||||||
value={selectedProtocol}
|
|
||||||
onValueChange={(value) => setSelectedProtocol(value as MessageProtocol)}
|
|
||||||
disabled={!allowSelection}
|
|
||||||
>
|
|
||||||
<SelectTrigger className="h-[32px] w-[90px] text-xs px-2">
|
|
||||||
<SelectValue />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value={MESSAGE_PROTOCOL.NIP17} className="text-xs">
|
|
||||||
NIP-17
|
|
||||||
</SelectItem>
|
|
||||||
<SelectItem value={MESSAGE_PROTOCOL.NIP04} className="text-xs">
|
|
||||||
NIP-04
|
|
||||||
</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -1,266 +0,0 @@
|
|||||||
import { useMemo, useState, memo } from 'react';
|
|
||||||
import { AlertTriangle, Info, Loader2 } from 'lucide-react';
|
|
||||||
import { useDMContext } from '@/hooks/useDMContext';
|
|
||||||
import { useAuthor } from '@/hooks/useAuthor';
|
|
||||||
import { genUserName } from '@/lib/genUserName';
|
|
||||||
import { formatConversationTime, formatFullDateTime } from '@/lib/dmUtils';
|
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Card } from '@/components/ui/card';
|
|
||||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
|
||||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { LOADING_PHASES } from '@/lib/dmConstants';
|
|
||||||
|
|
||||||
interface DMConversationListProps {
|
|
||||||
selectedPubkey: string | null;
|
|
||||||
onSelectConversation: (pubkey: string) => void;
|
|
||||||
className?: string;
|
|
||||||
onStatusClick?: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ConversationItemProps {
|
|
||||||
pubkey: string;
|
|
||||||
isSelected: boolean;
|
|
||||||
onClick: () => void;
|
|
||||||
lastMessage: { decryptedContent?: string; error?: string } | null;
|
|
||||||
lastActivity: number;
|
|
||||||
hasNIP4Messages: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ConversationItemComponent = ({
|
|
||||||
pubkey,
|
|
||||||
isSelected,
|
|
||||||
onClick,
|
|
||||||
lastMessage,
|
|
||||||
lastActivity,
|
|
||||||
hasNIP4Messages
|
|
||||||
}: ConversationItemProps) => {
|
|
||||||
const author = useAuthor(pubkey);
|
|
||||||
const metadata = author.data?.metadata;
|
|
||||||
|
|
||||||
const displayName = metadata?.name || genUserName(pubkey);
|
|
||||||
const avatarUrl = metadata?.picture;
|
|
||||||
const initials = displayName.slice(0, 2).toUpperCase();
|
|
||||||
|
|
||||||
const lastMessagePreview = lastMessage?.error
|
|
||||||
? '🔒 Encrypted message'
|
|
||||||
: lastMessage?.decryptedContent || 'No messages yet';
|
|
||||||
|
|
||||||
// Show skeleton only for name/avatar while loading (we already have message data)
|
|
||||||
const isLoadingProfile = author.isLoading && !metadata;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
onClick={onClick}
|
|
||||||
className={cn(
|
|
||||||
"w-full text-left p-3 rounded-lg transition-colors hover:bg-accent block overflow-hidden",
|
|
||||||
isSelected && "bg-accent"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="flex items-start gap-3 max-w-full">
|
|
||||||
{isLoadingProfile ? (
|
|
||||||
<Skeleton className="h-10 w-10 rounded-full flex-shrink-0" />
|
|
||||||
) : (
|
|
||||||
<Avatar className="h-10 w-10 flex-shrink-0">
|
|
||||||
<AvatarImage src={avatarUrl} alt={displayName} />
|
|
||||||
<AvatarFallback>{initials}</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex-1 min-w-0">
|
|
||||||
<div className="flex items-center justify-between gap-2 mb-1">
|
|
||||||
<div className="flex items-center gap-1.5 min-w-0 flex-1">
|
|
||||||
{isLoadingProfile ? (
|
|
||||||
<Skeleton className="h-[1.25rem] w-24" />
|
|
||||||
) : (
|
|
||||||
<span className="font-medium text-sm truncate">{displayName}</span>
|
|
||||||
)}
|
|
||||||
{hasNIP4Messages && (
|
|
||||||
<TooltipProvider>
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<div className="flex-shrink-0">
|
|
||||||
<AlertTriangle className="h-3.5 w-3.5 text-yellow-600 dark:text-yellow-500" />
|
|
||||||
</div>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent side="left">
|
|
||||||
<p className="text-xs max-w-[200px]">Some messages use outdated NIP-04 encryption</p>
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</TooltipProvider>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<TooltipProvider>
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<span className="text-xs text-muted-foreground whitespace-nowrap flex-shrink-0 cursor-default">
|
|
||||||
{formatConversationTime(lastActivity)}
|
|
||||||
</span>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent side="left">
|
|
||||||
<p className="text-xs">{formatFullDateTime(lastActivity)}</p>
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</TooltipProvider>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<p className="text-sm text-muted-foreground truncate">
|
|
||||||
{lastMessagePreview}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const ConversationItem = memo(ConversationItemComponent);
|
|
||||||
ConversationItem.displayName = 'ConversationItem';
|
|
||||||
|
|
||||||
const ConversationListSkeleton = () => {
|
|
||||||
return (
|
|
||||||
<div className="space-y-2 p-4">
|
|
||||||
{[1, 2, 3, 4, 5].map((i) => (
|
|
||||||
<div key={i} className="flex items-start gap-3 p-3">
|
|
||||||
<Skeleton className="h-10 w-10 rounded-full flex-shrink-0" />
|
|
||||||
<div className="flex-1 space-y-2">
|
|
||||||
<div className="flex justify-between">
|
|
||||||
<Skeleton className="h-4 w-24" />
|
|
||||||
<Skeleton className="h-3 w-12" />
|
|
||||||
</div>
|
|
||||||
<Skeleton className="h-3 w-full" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const DMConversationList = ({
|
|
||||||
selectedPubkey,
|
|
||||||
onSelectConversation,
|
|
||||||
className,
|
|
||||||
onStatusClick
|
|
||||||
}: DMConversationListProps) => {
|
|
||||||
const { conversations, isLoading, loadingPhase } = useDMContext();
|
|
||||||
const [activeTab, setActiveTab] = useState<'known' | 'requests'>('known');
|
|
||||||
|
|
||||||
// Filter conversations by type
|
|
||||||
const { knownConversations, requestConversations } = useMemo(() => {
|
|
||||||
return {
|
|
||||||
knownConversations: conversations.filter(c => c.isKnown),
|
|
||||||
requestConversations: conversations.filter(c => c.isRequest),
|
|
||||||
};
|
|
||||||
}, [conversations]);
|
|
||||||
|
|
||||||
// Get the current list based on active tab
|
|
||||||
const currentConversations = activeTab === 'known' ? knownConversations : requestConversations;
|
|
||||||
|
|
||||||
// Show skeleton during initial load (cache + relays) if we have no conversations yet
|
|
||||||
const isInitialLoad = (loadingPhase === LOADING_PHASES.CACHE || loadingPhase === LOADING_PHASES.RELAYS) && conversations.length === 0;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className={cn("h-full flex flex-col overflow-hidden", className)}>
|
|
||||||
{/* Header - always visible */}
|
|
||||||
<div className="p-4 border-b flex-shrink-0 flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<h2 className="font-semibold text-lg">Messages</h2>
|
|
||||||
{(loadingPhase === LOADING_PHASES.CACHE ||
|
|
||||||
loadingPhase === LOADING_PHASES.RELAYS ||
|
|
||||||
loadingPhase === LOADING_PHASES.SUBSCRIPTIONS) && (
|
|
||||||
<TooltipProvider>
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipTrigger asChild>
|
|
||||||
<div className="flex items-center">
|
|
||||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
|
||||||
</div>
|
|
||||||
</TooltipTrigger>
|
|
||||||
<TooltipContent>
|
|
||||||
<p className="text-xs">
|
|
||||||
{loadingPhase === LOADING_PHASES.CACHE && 'Loading from cache...'}
|
|
||||||
{loadingPhase === LOADING_PHASES.RELAYS && 'Querying relays for new messages...'}
|
|
||||||
{loadingPhase === LOADING_PHASES.SUBSCRIPTIONS && 'Setting up subscriptions...'}
|
|
||||||
</p>
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</TooltipProvider>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{onStatusClick && (
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
className="h-8 w-8"
|
|
||||||
onClick={onStatusClick}
|
|
||||||
aria-label="View messaging status"
|
|
||||||
>
|
|
||||||
<Info className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Tab buttons - always visible */}
|
|
||||||
<div className="px-2 pt-2 flex-shrink-0">
|
|
||||||
<div className="grid grid-cols-2 gap-1 bg-muted p-1 rounded-lg">
|
|
||||||
<button
|
|
||||||
onClick={() => setActiveTab('known')}
|
|
||||||
className={cn(
|
|
||||||
"text-xs py-2 px-3 rounded-md transition-colors",
|
|
||||||
activeTab === 'known'
|
|
||||||
? "bg-background shadow-sm font-medium"
|
|
||||||
: "text-muted-foreground hover:text-foreground"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
Active {knownConversations.length > 0 && `(${knownConversations.length})`}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => setActiveTab('requests')}
|
|
||||||
className={cn(
|
|
||||||
"text-xs py-2 px-3 rounded-md transition-colors",
|
|
||||||
activeTab === 'requests'
|
|
||||||
? "bg-background shadow-sm font-medium"
|
|
||||||
: "text-muted-foreground hover:text-foreground"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
Requests {requestConversations.length > 0 && `(${requestConversations.length})`}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Content area - show skeleton during initial load, otherwise show conversations */}
|
|
||||||
<div className="flex-1 min-h-0 mt-2 overflow-hidden">
|
|
||||||
{(isLoading || isInitialLoad) ? (
|
|
||||||
<ConversationListSkeleton />
|
|
||||||
) : conversations.length === 0 ? (
|
|
||||||
<div className="flex items-center justify-center h-full text-center text-muted-foreground px-4">
|
|
||||||
<div>
|
|
||||||
<p className="text-sm">No conversations yet</p>
|
|
||||||
<p className="text-xs mt-1">Start a new conversation to get started</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : currentConversations.length === 0 ? (
|
|
||||||
<div className="flex items-center justify-center h-32 text-center text-muted-foreground px-4">
|
|
||||||
<p className="text-sm">No {activeTab} conversations</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<ScrollArea className="h-full block">
|
|
||||||
<div className="block w-full px-2 py-2 space-y-1">
|
|
||||||
{currentConversations.map((conversation) => (
|
|
||||||
<ConversationItem
|
|
||||||
key={conversation.pubkey}
|
|
||||||
pubkey={conversation.pubkey}
|
|
||||||
isSelected={selectedPubkey === conversation.pubkey}
|
|
||||||
onClick={() => onSelectConversation(conversation.pubkey)}
|
|
||||||
lastMessage={conversation.lastMessage}
|
|
||||||
lastActivity={conversation.lastActivity}
|
|
||||||
hasNIP4Messages={conversation.hasNIP4Messages}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</ScrollArea>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
import { useState, useCallback } from 'react';
|
|
||||||
import { DMConversationList } from '@/components/dm/DMConversationList';
|
|
||||||
import { DMChatArea } from '@/components/dm/DMChatArea';
|
|
||||||
import { DMStatusInfo } from '@/components/dm/DMStatusInfo';
|
|
||||||
import { useDMContext } from '@/hooks/useDMContext';
|
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from '@/components/ui/dialog';
|
|
||||||
|
|
||||||
interface DMMessagingInterfaceProps {
|
|
||||||
className?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const DMMessagingInterface = ({ className }: DMMessagingInterfaceProps) => {
|
|
||||||
const [selectedPubkey, setSelectedPubkey] = useState<string | null>(null);
|
|
||||||
const [statusModalOpen, setStatusModalOpen] = useState(false);
|
|
||||||
const isMobile = useIsMobile();
|
|
||||||
const { clearCacheAndRefetch } = useDMContext();
|
|
||||||
|
|
||||||
// On mobile, show only one panel at a time
|
|
||||||
const showConversationList = !isMobile || !selectedPubkey;
|
|
||||||
const showChatArea = !isMobile || selectedPubkey;
|
|
||||||
|
|
||||||
const handleSelectConversation = useCallback((pubkey: string) => {
|
|
||||||
setSelectedPubkey(pubkey);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleBack = useCallback(() => {
|
|
||||||
setSelectedPubkey(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
{/* Status Modal */}
|
|
||||||
<Dialog open={statusModalOpen} onOpenChange={setStatusModalOpen}>
|
|
||||||
<DialogContent className="max-w-md">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Messaging Status</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
View loading status, cache info, and connection details
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
<DMStatusInfo clearCacheAndRefetch={clearCacheAndRefetch} />
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
|
|
||||||
<div className={cn("flex gap-4 overflow-hidden", className)}>
|
|
||||||
{/* Conversation List - Left Sidebar */}
|
|
||||||
<div className={cn(
|
|
||||||
"md:w-80 md:flex-shrink-0",
|
|
||||||
isMobile && !showConversationList && "hidden",
|
|
||||||
isMobile && showConversationList && "w-full"
|
|
||||||
)}>
|
|
||||||
<DMConversationList
|
|
||||||
selectedPubkey={selectedPubkey}
|
|
||||||
onSelectConversation={handleSelectConversation}
|
|
||||||
className="h-full"
|
|
||||||
onStatusClick={() => setStatusModalOpen(true)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Chat Area - Right Panel */}
|
|
||||||
<div className={cn(
|
|
||||||
"flex-1 md:min-w-0",
|
|
||||||
isMobile && !showChatArea && "hidden",
|
|
||||||
isMobile && showChatArea && "w-full"
|
|
||||||
)}>
|
|
||||||
<DMChatArea
|
|
||||||
pubkey={selectedPubkey}
|
|
||||||
onBack={isMobile ? handleBack : undefined}
|
|
||||||
className="h-full"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
@@ -1,214 +0,0 @@
|
|||||||
import { useState } from 'react';
|
|
||||||
import { RefreshCw, Database, Wifi, CheckCircle2, Loader2 } from 'lucide-react';
|
|
||||||
import { useDMContext } from '@/hooks/useDMContext';
|
|
||||||
import { LOADING_PHASES } from '@/lib/dmConstants';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
import { Separator } from '@/components/ui/separator';
|
|
||||||
import { useToast } from '@/hooks/useToast';
|
|
||||||
|
|
||||||
interface DMStatusInfoProps {
|
|
||||||
clearCacheAndRefetch?: () => Promise<void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const DMStatusInfo = ({ clearCacheAndRefetch }: DMStatusInfoProps) => {
|
|
||||||
const [isClearing, setIsClearing] = useState(false);
|
|
||||||
const { toast } = useToast();
|
|
||||||
const {
|
|
||||||
loadingPhase,
|
|
||||||
subscriptions,
|
|
||||||
scanProgress,
|
|
||||||
isDoingInitialLoad,
|
|
||||||
lastSync,
|
|
||||||
conversations,
|
|
||||||
} = useDMContext();
|
|
||||||
|
|
||||||
const handleClearCache = async () => {
|
|
||||||
if (!clearCacheAndRefetch) return;
|
|
||||||
|
|
||||||
setIsClearing(true);
|
|
||||||
try {
|
|
||||||
await clearCacheAndRefetch();
|
|
||||||
toast({
|
|
||||||
title: 'Cache cleared',
|
|
||||||
description: 'Refetching messages from relays...',
|
|
||||||
});
|
|
||||||
setIsClearing(false);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error clearing cache:', error);
|
|
||||||
toast({
|
|
||||||
title: 'Error',
|
|
||||||
description: 'Failed to clear cache. Please try again.',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
setIsClearing(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getLoadingPhaseInfo = () => {
|
|
||||||
switch (loadingPhase) {
|
|
||||||
case LOADING_PHASES.IDLE:
|
|
||||||
return { label: 'Idle', description: 'Not yet initialized', icon: Loader2, color: 'text-muted-foreground' };
|
|
||||||
case LOADING_PHASES.CACHE:
|
|
||||||
return { label: 'Loading from cache', description: 'Reading cached messages...', icon: Database, color: 'text-blue-500' };
|
|
||||||
case LOADING_PHASES.RELAYS:
|
|
||||||
return { label: 'Loading from relays', description: 'Fetching messages from Nostr relays...', icon: Wifi, color: 'text-yellow-500' };
|
|
||||||
case LOADING_PHASES.SUBSCRIPTIONS:
|
|
||||||
return { label: 'Connecting subscriptions', description: 'Setting up real-time message sync...', icon: RefreshCw, color: 'text-orange-500' };
|
|
||||||
case LOADING_PHASES.READY:
|
|
||||||
return { label: 'Ready', description: 'All systems operational', icon: CheckCircle2, color: 'text-green-500' };
|
|
||||||
default:
|
|
||||||
return { label: 'Unknown', description: 'Status unknown', icon: Loader2, color: 'text-muted-foreground' };
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const phaseInfo = getLoadingPhaseInfo();
|
|
||||||
const PhaseIcon = phaseInfo.icon;
|
|
||||||
|
|
||||||
const formatTimestamp = (timestamp: number | null) => {
|
|
||||||
if (!timestamp) return 'Never';
|
|
||||||
const date = new Date(timestamp * 1000);
|
|
||||||
const now = new Date();
|
|
||||||
const diffMs = now.getTime() - date.getTime();
|
|
||||||
const diffMins = Math.floor(diffMs / 60000);
|
|
||||||
|
|
||||||
if (diffMins < 1) return 'Just now';
|
|
||||||
if (diffMins < 60) return `${diffMins}m ago`;
|
|
||||||
if (diffMins < 1440) return `${Math.floor(diffMins / 60)}h ago`;
|
|
||||||
return date.toLocaleDateString();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{/* Loading Phase */}
|
|
||||||
<Card>
|
|
||||||
<CardContent className="pt-6">
|
|
||||||
<div className="flex items-start gap-3">
|
|
||||||
<PhaseIcon className={`h-5 w-5 ${phaseInfo.color} ${loadingPhase !== LOADING_PHASES.READY ? 'animate-pulse' : ''}`} />
|
|
||||||
<div className="flex-1 space-y-1">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<p className="font-medium">{phaseInfo.label}</p>
|
|
||||||
{isDoingInitialLoad && (
|
|
||||||
<Badge variant="secondary" className="text-xs">
|
|
||||||
Initial Load
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<p className="text-sm text-muted-foreground">{phaseInfo.description}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Scan Progress */}
|
|
||||||
{(scanProgress.nip4 !== null || scanProgress.nip17 !== null) && (
|
|
||||||
<Card>
|
|
||||||
<CardContent className="pt-6">
|
|
||||||
<div className="space-y-3">
|
|
||||||
<p className="text-sm font-medium">Scanning Messages</p>
|
|
||||||
{scanProgress.nip4 !== null && (
|
|
||||||
<div className="space-y-1">
|
|
||||||
<div className="flex items-center justify-between text-xs">
|
|
||||||
<span className="text-muted-foreground">NIP-4 (Legacy)</span>
|
|
||||||
<span className="text-muted-foreground">{scanProgress.nip4.current} events</span>
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-muted-foreground">{scanProgress.nip4.status}</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{scanProgress.nip17 !== null && (
|
|
||||||
<div className="space-y-1">
|
|
||||||
<div className="flex items-center justify-between text-xs">
|
|
||||||
<span className="text-muted-foreground">NIP-17 (Private)</span>
|
|
||||||
<span className="text-muted-foreground">{scanProgress.nip17.current} events</span>
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-muted-foreground">{scanProgress.nip17.status}</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Subscriptions */}
|
|
||||||
<Card>
|
|
||||||
<CardContent className="pt-6">
|
|
||||||
<div className="space-y-3">
|
|
||||||
<p className="text-sm font-medium">Real-time Subscriptions</p>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<span className="text-sm text-muted-foreground">NIP-4 (Legacy DMs)</span>
|
|
||||||
<Badge variant={subscriptions.isNIP4Connected ? 'default' : 'secondary'}>
|
|
||||||
{subscriptions.isNIP4Connected ? 'Connected' : 'Disconnected'}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<span className="text-sm text-muted-foreground">NIP-17 (Private DMs)</span>
|
|
||||||
<Badge variant={subscriptions.isNIP17Connected ? 'default' : 'secondary'}>
|
|
||||||
{subscriptions.isNIP17Connected ? 'Connected' : 'Disconnected'}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Cache Info */}
|
|
||||||
<Card>
|
|
||||||
<CardContent className="pt-6">
|
|
||||||
<div className="space-y-3">
|
|
||||||
<p className="text-sm font-medium">Cache Information</p>
|
|
||||||
<div className="space-y-2 text-sm">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<span className="text-muted-foreground">Conversations</span>
|
|
||||||
<span className="font-medium">{conversations.length}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<span className="text-muted-foreground">Last NIP-4 sync</span>
|
|
||||||
<span className="font-medium">{formatTimestamp(lastSync.nip4)}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<span className="text-muted-foreground">Last NIP-17 sync</span>
|
|
||||||
<span className="font-medium">{formatTimestamp(lastSync.nip17)}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* Actions */}
|
|
||||||
{clearCacheAndRefetch && (
|
|
||||||
<>
|
|
||||||
<Separator />
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div className="space-y-1">
|
|
||||||
<p className="text-sm font-medium">Cache Management</p>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
Clear all cached messages and refetch from relays. This will force a fresh sync.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
onClick={handleClearCache}
|
|
||||||
disabled={isClearing}
|
|
||||||
variant="outline"
|
|
||||||
className="w-full"
|
|
||||||
>
|
|
||||||
{isClearing ? (
|
|
||||||
<>
|
|
||||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
|
||||||
Clearing...
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<RefreshCw className="mr-2 h-4 w-4" />
|
|
||||||
Clear Cache & Refetch
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
@@ -9,7 +9,7 @@ export const buttonVariants = cva(
|
|||||||
destructive:
|
destructive:
|
||||||
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||||
outline:
|
outline:
|
||||||
"border border-input hover:bg-accent hover:text-accent-foreground",
|
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
||||||
secondary:
|
secondary:
|
||||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ const DialogContent = React.forwardRef<
|
|||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||||
<X className="size-5" />
|
<X className="h-4 w-4" />
|
||||||
<span className="sr-only">Close</span>
|
<span className="sr-only">Close</span>
|
||||||
</DialogPrimitive.Close>
|
</DialogPrimitive.Close>
|
||||||
</DialogPrimitive.Content>
|
</DialogPrimitive.Content>
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ const ScrollArea = React.forwardRef<
|
|||||||
className={cn("relative overflow-hidden", className)}
|
className={cn("relative overflow-hidden", className)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit] [&>div]:!block [&>div]:!w-full">
|
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
|
||||||
{children}
|
{children}
|
||||||
</ScrollAreaPrimitive.Viewport>
|
</ScrollAreaPrimitive.Viewport>
|
||||||
<ScrollBar />
|
<ScrollBar />
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { useTheme } from "next-themes"
|
||||||
|
import { Toaster as Sonner } from "sonner"
|
||||||
|
|
||||||
|
type ToasterProps = React.ComponentProps<typeof Sonner>
|
||||||
|
|
||||||
|
const Toaster = ({ ...props }: ToasterProps) => {
|
||||||
|
const { theme = "system" } = useTheme()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Sonner
|
||||||
|
theme={theme as ToasterProps["theme"]}
|
||||||
|
className="toaster group"
|
||||||
|
toastOptions={{
|
||||||
|
classNames: {
|
||||||
|
toast:
|
||||||
|
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
|
||||||
|
description: "group-[.toast]:text-muted-foreground",
|
||||||
|
actionButton:
|
||||||
|
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
|
||||||
|
cancelButton:
|
||||||
|
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Toaster }
|
||||||
@@ -2,25 +2,20 @@ import { createContext } from "react";
|
|||||||
|
|
||||||
export type Theme = "dark" | "light" | "system";
|
export type Theme = "dark" | "light" | "system";
|
||||||
|
|
||||||
export interface RelayMetadata {
|
|
||||||
/** List of relays with read/write permissions */
|
|
||||||
relays: { url: string; read: boolean; write: boolean }[];
|
|
||||||
/** Unix timestamp of when the relay list was last updated */
|
|
||||||
updatedAt: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AppConfig {
|
export interface AppConfig {
|
||||||
/** Current theme */
|
/** Current theme */
|
||||||
theme: Theme;
|
theme: Theme;
|
||||||
/** NIP-65 relay list metadata */
|
/** Selected relay URL */
|
||||||
relayMetadata: RelayMetadata;
|
relayUrl: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AppContextType {
|
export interface AppContextType {
|
||||||
/** Current application configuration */
|
/** Current application configuration */
|
||||||
config: AppConfig;
|
config: AppConfig;
|
||||||
/** Update configuration using a callback that receives current config and returns new config */
|
/** Update configuration using a callback that receives current config and returns new config */
|
||||||
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
|
updateConfig: (updater: (currentConfig: AppConfig) => AppConfig) => void;
|
||||||
|
/** Optional list of preset relays to display in the RelaySelector */
|
||||||
|
presetRelays?: { name: string; url: string }[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export const AppContext = createContext<AppContextType | undefined>(undefined);
|
export const AppContext = createContext<AppContextType | undefined>(undefined);
|
||||||
@@ -1,138 +0,0 @@
|
|||||||
import { createContext } from 'react';
|
|
||||||
import { type LoadingPhase, type ProtocolMode } from '@/lib/dmConstants';
|
|
||||||
import { type NostrEvent } from '@nostrify/nostrify';
|
|
||||||
import type { MessageProtocol } from '@/lib/dmConstants';
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// DM Types and Constants
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
interface ParticipantData {
|
|
||||||
messages: DecryptedMessage[];
|
|
||||||
lastActivity: number;
|
|
||||||
lastMessage: DecryptedMessage | null;
|
|
||||||
hasNIP4: boolean;
|
|
||||||
hasNIP17: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
type MessagesState = Map<string, ParticipantData>;
|
|
||||||
|
|
||||||
interface LastSyncData {
|
|
||||||
nip4: number | null;
|
|
||||||
nip17: number | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SubscriptionStatus {
|
|
||||||
isNIP4Connected: boolean;
|
|
||||||
isNIP17Connected: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ScanProgress {
|
|
||||||
current: number;
|
|
||||||
status: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ScanProgressState {
|
|
||||||
nip4: ScanProgress | null;
|
|
||||||
nip17: ScanProgress | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ConversationSummary {
|
|
||||||
id: string;
|
|
||||||
pubkey: string;
|
|
||||||
lastMessage: DecryptedMessage | null;
|
|
||||||
lastActivity: number;
|
|
||||||
hasNIP4Messages: boolean;
|
|
||||||
hasNIP17Messages: boolean;
|
|
||||||
isKnown: boolean;
|
|
||||||
isRequest: boolean;
|
|
||||||
lastMessageFromUser: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface DecryptedMessage extends NostrEvent {
|
|
||||||
decryptedContent?: string;
|
|
||||||
error?: string;
|
|
||||||
isSending?: boolean;
|
|
||||||
clientFirstSeen?: number;
|
|
||||||
decryptedEvent?: NostrEvent; // For NIP-17: the inner kind 14/15 event
|
|
||||||
originalGiftWrapId?: string; // Store gift wrap ID for NIP-17 deduplication
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* File attachment for direct messages (NIP-92 compatible).
|
|
||||||
*
|
|
||||||
* All fields are required. Use with `useUploadFile` hook to upload files
|
|
||||||
* and generate the proper tags format.
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```tsx
|
|
||||||
* import { useUploadFile } from '@/hooks/useUploadFile';
|
|
||||||
* import type { FileAttachment } from '@/contexts/DMContext';
|
|
||||||
*
|
|
||||||
* const { mutateAsync: uploadFile } = useUploadFile();
|
|
||||||
*
|
|
||||||
* const tags = await uploadFile(file);
|
|
||||||
* const attachment: FileAttachment = {
|
|
||||||
* url: tags[0][1],
|
|
||||||
* mimeType: file.type,
|
|
||||||
* size: file.size,
|
|
||||||
* name: file.name,
|
|
||||||
* tags: tags
|
|
||||||
* };
|
|
||||||
*
|
|
||||||
* await sendMessage({
|
|
||||||
* recipientPubkey: 'hex-pubkey',
|
|
||||||
* content: 'Check out this file!',
|
|
||||||
* attachments: [attachment]
|
|
||||||
* });
|
|
||||||
* ```
|
|
||||||
*
|
|
||||||
* @property url - Blossom server URL where file is hosted
|
|
||||||
* @property mimeType - MIME type of the file (e.g., 'image/png')
|
|
||||||
* @property size - File size in bytes
|
|
||||||
* @property name - Original filename
|
|
||||||
* @property tags - NIP-94 file metadata tags (includes hashes)
|
|
||||||
*/
|
|
||||||
export interface FileAttachment {
|
|
||||||
url: string;
|
|
||||||
mimeType: string;
|
|
||||||
size: number;
|
|
||||||
name: string;
|
|
||||||
tags: string[][];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Direct Messaging context interface providing access to all DM functionality.
|
|
||||||
*
|
|
||||||
* @property messages - Raw message state (Map of pubkey -> participant data)
|
|
||||||
* @property isLoading - True during initial load phases
|
|
||||||
* @property loadingPhase - Current loading phase (CACHE, RELAYS, SUBSCRIPTIONS, READY, IDLE)
|
|
||||||
* @property isDoingInitialLoad - True only during cache/relay loading (not subscriptions)
|
|
||||||
* @property lastSync - Unix timestamps of last successful sync for each protocol
|
|
||||||
* @property subscriptions - Connection status for real-time message subscriptions
|
|
||||||
* @property conversations - Array of conversation summaries sorted by last activity
|
|
||||||
* @property sendMessage - Send an encrypted direct message (NIP-04 or NIP-17)
|
|
||||||
* @property protocolMode - Current protocol mode (NIP04_ONLY, NIP17_ONLY, or BOTH)
|
|
||||||
* @property scanProgress - Progress info for large message history scans
|
|
||||||
* @property clearCacheAndRefetch - Clear IndexedDB cache and reload all messages from relays
|
|
||||||
*/
|
|
||||||
export interface DMContextType {
|
|
||||||
messages: MessagesState;
|
|
||||||
isLoading: boolean;
|
|
||||||
loadingPhase: LoadingPhase;
|
|
||||||
isDoingInitialLoad: boolean;
|
|
||||||
lastSync: LastSyncData;
|
|
||||||
subscriptions: SubscriptionStatus;
|
|
||||||
conversations: ConversationSummary[];
|
|
||||||
sendMessage: (params: {
|
|
||||||
recipientPubkey: string;
|
|
||||||
content: string;
|
|
||||||
protocol?: MessageProtocol;
|
|
||||||
attachments?: FileAttachment[];
|
|
||||||
}) => Promise<void>;
|
|
||||||
protocolMode: ProtocolMode;
|
|
||||||
scanProgress: ScanProgressState;
|
|
||||||
clearCacheAndRefetch: () => Promise<void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const DMContext = createContext<DMContextType | null>(null);
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
import { ReactNode } from 'react';
|
|
||||||
import { useNWCInternal as useNWCHook } from '@/hooks/useNWC';
|
|
||||||
import { NWCContext } from '@/hooks/useNWCContext';
|
|
||||||
|
|
||||||
export function NWCProvider({ children }: { children: ReactNode }) {
|
|
||||||
const nwc = useNWCHook();
|
|
||||||
return <NWCContext.Provider value={nwc}>{children}</NWCContext.Provider>;
|
|
||||||
}
|
|
||||||
@@ -28,7 +28,6 @@ export function useAuthor(pubkey: string | undefined) {
|
|||||||
return { event };
|
return { event };
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
staleTime: 5 * 60 * 1000, // Keep cached data fresh for 5 minutes
|
|
||||||
retry: 3,
|
retry: 3,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
import { NKinds, NostrEvent, NostrFilter } from '@nostrify/nostrify';
|
|
||||||
import { useNostr } from '@nostrify/react';
|
|
||||||
import { useQuery } from '@tanstack/react-query';
|
|
||||||
|
|
||||||
export function useComments(root: NostrEvent | URL, limit?: number) {
|
|
||||||
const { nostr } = useNostr();
|
|
||||||
|
|
||||||
return useQuery({
|
|
||||||
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id, limit],
|
|
||||||
queryFn: async (c) => {
|
|
||||||
const filter: NostrFilter = { kinds: [1111] };
|
|
||||||
|
|
||||||
if (root instanceof URL) {
|
|
||||||
filter['#I'] = [root.toString()];
|
|
||||||
} else if (NKinds.addressable(root.kind)) {
|
|
||||||
const d = root.tags.find(([name]) => name === 'd')?.[1] ?? '';
|
|
||||||
filter['#A'] = [`${root.kind}:${root.pubkey}:${d}`];
|
|
||||||
} else if (NKinds.replaceable(root.kind)) {
|
|
||||||
filter['#A'] = [`${root.kind}:${root.pubkey}:`];
|
|
||||||
} else {
|
|
||||||
filter['#E'] = [root.id];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof limit === 'number') {
|
|
||||||
filter.limit = limit;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Query for all kind 1111 comments that reference this addressable event regardless of depth
|
|
||||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
|
|
||||||
const events = await nostr.query([filter], { signal });
|
|
||||||
|
|
||||||
// Helper function to get tag value
|
|
||||||
const getTagValue = (event: NostrEvent, tagName: string): string | undefined => {
|
|
||||||
const tag = event.tags.find(([name]) => name === tagName);
|
|
||||||
return tag?.[1];
|
|
||||||
};
|
|
||||||
|
|
||||||
// Filter top-level comments (those with lowercase tag matching the root)
|
|
||||||
const topLevelComments = events.filter(comment => {
|
|
||||||
if (root instanceof URL) {
|
|
||||||
return getTagValue(comment, 'i') === root.toString();
|
|
||||||
} else if (NKinds.addressable(root.kind)) {
|
|
||||||
const d = getTagValue(root, 'd') ?? '';
|
|
||||||
return getTagValue(comment, 'a') === `${root.kind}:${root.pubkey}:${d}`;
|
|
||||||
} else if (NKinds.replaceable(root.kind)) {
|
|
||||||
return getTagValue(comment, 'a') === `${root.kind}:${root.pubkey}:`;
|
|
||||||
} else {
|
|
||||||
return getTagValue(comment, 'e') === root.id;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Helper function to get all descendants of a comment
|
|
||||||
const getDescendants = (parentId: string): NostrEvent[] => {
|
|
||||||
const directReplies = events.filter(comment => {
|
|
||||||
const eTag = getTagValue(comment, 'e');
|
|
||||||
return eTag === parentId;
|
|
||||||
});
|
|
||||||
|
|
||||||
const allDescendants = [...directReplies];
|
|
||||||
|
|
||||||
// Recursively get descendants of each direct reply
|
|
||||||
for (const reply of directReplies) {
|
|
||||||
allDescendants.push(...getDescendants(reply.id));
|
|
||||||
}
|
|
||||||
|
|
||||||
return allDescendants;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Create a map of comment ID to its descendants
|
|
||||||
const commentDescendants = new Map<string, NostrEvent[]>();
|
|
||||||
for (const comment of events) {
|
|
||||||
commentDescendants.set(comment.id, getDescendants(comment.id));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sort top-level comments by creation time (newest first)
|
|
||||||
const sortedTopLevel = topLevelComments.sort((a, b) => b.created_at - a.created_at);
|
|
||||||
|
|
||||||
return {
|
|
||||||
allComments: events,
|
|
||||||
topLevelComments: sortedTopLevel,
|
|
||||||
getDescendants: (commentId: string) => {
|
|
||||||
const descendants = commentDescendants.get(commentId) || [];
|
|
||||||
// Sort descendants by creation time (oldest first for threaded display)
|
|
||||||
return descendants.sort((a, b) => a.created_at - b.created_at);
|
|
||||||
},
|
|
||||||
getDirectReplies: (commentId: string) => {
|
|
||||||
const directReplies = events.filter(comment => {
|
|
||||||
const eTag = getTagValue(comment, 'e');
|
|
||||||
return eTag === commentId;
|
|
||||||
});
|
|
||||||
// Sort direct replies by creation time (oldest first for threaded display)
|
|
||||||
return directReplies.sort((a, b) => a.created_at - b.created_at);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
},
|
|
||||||
enabled: !!root,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
||||||
import { useDMContext } from "@/hooks/useDMContext";
|
|
||||||
|
|
||||||
const MESSAGES_PER_PAGE = 25;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hook to access paginated messages for a specific conversation.
|
|
||||||
*
|
|
||||||
* Returns the most recent messages (default 25) with the ability to load earlier messages.
|
|
||||||
* Automatically resets to default page size when switching conversations.
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```tsx
|
|
||||||
* import { useConversationMessages } from '@/contexts/DMContext';
|
|
||||||
*
|
|
||||||
* function MessageThread({ recipientPubkey }: { recipientPubkey: string }) {
|
|
||||||
* const {
|
|
||||||
* messages,
|
|
||||||
* hasMoreMessages,
|
|
||||||
* loadEarlierMessages,
|
|
||||||
* totalCount
|
|
||||||
* } = useConversationMessages(recipientPubkey);
|
|
||||||
*
|
|
||||||
* return (
|
|
||||||
* <div>
|
|
||||||
* {hasMoreMessages && (
|
|
||||||
* <button onClick={loadEarlierMessages}>
|
|
||||||
* Load Earlier ({totalCount - messages.length} more)
|
|
||||||
* </button>
|
|
||||||
* )}
|
|
||||||
* {messages.map(msg => (
|
|
||||||
* <div key={msg.id}>{msg.decryptedContent}</div>
|
|
||||||
* ))}
|
|
||||||
* </div>
|
|
||||||
* );
|
|
||||||
* }
|
|
||||||
* ```
|
|
||||||
*
|
|
||||||
* @param conversationId - The pubkey of the conversation participant
|
|
||||||
* @returns Paginated message data with loading function
|
|
||||||
*/
|
|
||||||
export function useConversationMessages(conversationId: string) {
|
|
||||||
const { messages: allMessages } = useDMContext();
|
|
||||||
const [visibleCount, setVisibleCount] = useState(MESSAGES_PER_PAGE);
|
|
||||||
|
|
||||||
const result = useMemo(() => {
|
|
||||||
const conversationData = allMessages.get(conversationId);
|
|
||||||
|
|
||||||
if (!conversationData) {
|
|
||||||
return {
|
|
||||||
messages: [],
|
|
||||||
hasMoreMessages: false,
|
|
||||||
totalCount: 0,
|
|
||||||
lastMessage: null,
|
|
||||||
lastActivity: 0,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const totalMessages = conversationData.messages.length;
|
|
||||||
const hasMore = totalMessages > visibleCount;
|
|
||||||
|
|
||||||
// Return the most recent N messages (slice from the end)
|
|
||||||
const visibleMessages = conversationData.messages.slice(-visibleCount);
|
|
||||||
|
|
||||||
return {
|
|
||||||
messages: visibleMessages,
|
|
||||||
hasMoreMessages: hasMore,
|
|
||||||
totalCount: totalMessages,
|
|
||||||
lastMessage: conversationData.lastMessage,
|
|
||||||
lastActivity: conversationData.lastActivity,
|
|
||||||
};
|
|
||||||
}, [allMessages, conversationId, visibleCount]);
|
|
||||||
|
|
||||||
const loadEarlierMessages = useCallback(() => {
|
|
||||||
setVisibleCount(prev => prev + MESSAGES_PER_PAGE);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Reset visible count when conversation changes
|
|
||||||
useEffect(() => {
|
|
||||||
setVisibleCount(MESSAGES_PER_PAGE);
|
|
||||||
}, [conversationId]);
|
|
||||||
|
|
||||||
return {
|
|
||||||
...result,
|
|
||||||
loadEarlierMessages,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
import { useContext } from "react";
|
|
||||||
import { DMContext, DMContextType } from "@/contexts/DMContext";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hook to access the direct messaging system.
|
|
||||||
*
|
|
||||||
* Provides access to conversations, message sending, loading states, and cache management.
|
|
||||||
* Must be used within a DMProvider.
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```tsx
|
|
||||||
* import { useDMContext } from '@/hooks/useDMContext';
|
|
||||||
* import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
|
||||||
*
|
|
||||||
* function MyComponent() {
|
|
||||||
* const { conversations, sendMessage, isLoading } = useDMContext();
|
|
||||||
*
|
|
||||||
* // Send a message
|
|
||||||
* await sendMessage({
|
|
||||||
* recipientPubkey: 'hex-pubkey',
|
|
||||||
* content: 'Hello!',
|
|
||||||
* protocol: MESSAGE_PROTOCOL.NIP17
|
|
||||||
* });
|
|
||||||
*
|
|
||||||
* // Display conversations
|
|
||||||
* return (
|
|
||||||
* <div>
|
|
||||||
* {isLoading ? 'Loading...' : conversations.map(c => (
|
|
||||||
* <div key={c.pubkey}>{c.lastMessage?.decryptedContent}</div>
|
|
||||||
* ))}
|
|
||||||
* </div>
|
|
||||||
* );
|
|
||||||
* }
|
|
||||||
* ```
|
|
||||||
*
|
|
||||||
* @returns DMContextType - The direct messaging context
|
|
||||||
* @throws Error if used outside DMProvider
|
|
||||||
*/
|
|
||||||
export function useDMContext(): DMContextType {
|
|
||||||
const context = useContext(DMContext);
|
|
||||||
if (!context) {
|
|
||||||
throw new Error('useDMContext must be used within DMProvider');
|
|
||||||
}
|
|
||||||
return context;
|
|
||||||
}
|
|
||||||
+12
-12
@@ -1,19 +1,19 @@
|
|||||||
import { useEffect, useState } from "react"
|
import * as React from "react"
|
||||||
|
|
||||||
const MOBILE_BREAKPOINT = 768;
|
const MOBILE_BREAKPOINT = 768
|
||||||
|
|
||||||
export function useIsMobile(): boolean {
|
export function useIsMobile() {
|
||||||
const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT);
|
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||||
|
|
||||||
useEffect(() => {
|
React.useEffect(() => {
|
||||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
||||||
const onChange = () => {
|
const onChange = () => {
|
||||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||||
}
|
}
|
||||||
mql.addEventListener("change", onChange);
|
mql.addEventListener("change", onChange)
|
||||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||||
return () => mql.removeEventListener("change", onChange);
|
return () => mql.removeEventListener("change", onChange)
|
||||||
}, []);
|
}, [])
|
||||||
|
|
||||||
return !!isMobile;
|
return !!isMobile
|
||||||
}
|
}
|
||||||
@@ -15,7 +15,7 @@ export function useLoggedInAccounts() {
|
|||||||
const { logins, setLogin, removeLogin } = useNostrLogin();
|
const { logins, setLogin, removeLogin } = useNostrLogin();
|
||||||
|
|
||||||
const { data: authors = [] } = useQuery({
|
const { data: authors = [] } = useQuery({
|
||||||
queryKey: ['nostr', 'logins', logins.map((l) => l.id).join(';')],
|
queryKey: ['logins', logins.map((l) => l.id).join(';')],
|
||||||
queryFn: async ({ signal }) => {
|
queryFn: async ({ signal }) => {
|
||||||
const events = await nostr.query(
|
const events = await nostr.query(
|
||||||
[{ kinds: [0], authors: logins.map((l) => l.pubkey) }],
|
[{ kinds: [0], authors: logins.map((l) => l.pubkey) }],
|
||||||
|
|||||||
@@ -1,221 +0,0 @@
|
|||||||
import { useState, useCallback } from 'react';
|
|
||||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
|
||||||
import { useToast } from '@/hooks/useToast';
|
|
||||||
import { LN } from '@getalby/sdk';
|
|
||||||
|
|
||||||
export interface NWCConnection {
|
|
||||||
connectionString: string;
|
|
||||||
alias?: string;
|
|
||||||
isConnected: boolean;
|
|
||||||
client?: LN;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface NWCInfo {
|
|
||||||
alias?: string;
|
|
||||||
color?: string;
|
|
||||||
pubkey?: string;
|
|
||||||
network?: string;
|
|
||||||
methods?: string[];
|
|
||||||
notifications?: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useNWCInternal() {
|
|
||||||
const { toast } = useToast();
|
|
||||||
const [connections, setConnections] = useLocalStorage<NWCConnection[]>('nwc-connections', []);
|
|
||||||
const [activeConnection, setActiveConnection] = useLocalStorage<string | null>('nwc-active-connection', null);
|
|
||||||
const [connectionInfo, setConnectionInfo] = useState<Record<string, NWCInfo>>({});
|
|
||||||
|
|
||||||
// Add new connection
|
|
||||||
const addConnection = async (uri: string, alias?: string): Promise<boolean> => {
|
|
||||||
const parseNWCUri = (uri: string): { connectionString: string } | null => {
|
|
||||||
try {
|
|
||||||
if (!uri.startsWith('nostr+walletconnect://') && !uri.startsWith('nostrwalletconnect://')) {
|
|
||||||
console.error('Invalid NWC URI protocol:', { protocol: uri.split('://')[0] });
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return { connectionString: uri };
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to parse NWC URI:', error);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const parsed = parseNWCUri(uri);
|
|
||||||
if (!parsed) {
|
|
||||||
toast({
|
|
||||||
title: 'Invalid NWC URI',
|
|
||||||
description: 'Please check the connection string and try again.',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const existingConnection = connections.find(c => c.connectionString === parsed.connectionString);
|
|
||||||
if (existingConnection) {
|
|
||||||
toast({
|
|
||||||
title: 'Connection already exists',
|
|
||||||
description: 'This wallet is already connected.',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
let timeoutId: NodeJS.Timeout | undefined;
|
|
||||||
const testPromise = new Promise((resolve, reject) => {
|
|
||||||
try {
|
|
||||||
const client = new LN(parsed.connectionString);
|
|
||||||
resolve(client);
|
|
||||||
} catch (error) {
|
|
||||||
reject(error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
|
||||||
timeoutId = setTimeout(() => reject(new Error('Connection test timeout')), 10000);
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
await Promise.race([testPromise, timeoutPromise]) as LN;
|
|
||||||
if (timeoutId) clearTimeout(timeoutId);
|
|
||||||
} catch (error) {
|
|
||||||
if (timeoutId) clearTimeout(timeoutId);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
|
|
||||||
const connection: NWCConnection = {
|
|
||||||
connectionString: parsed.connectionString,
|
|
||||||
alias: alias || 'NWC Wallet',
|
|
||||||
isConnected: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
setConnectionInfo(prev => ({
|
|
||||||
...prev,
|
|
||||||
[parsed.connectionString]: {
|
|
||||||
alias: connection.alias,
|
|
||||||
methods: ['pay_invoice'],
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
const newConnections = [...connections, connection];
|
|
||||||
setConnections(newConnections);
|
|
||||||
|
|
||||||
if (connections.length === 0 || !activeConnection)
|
|
||||||
setActiveConnection(parsed.connectionString);
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: 'Wallet connected',
|
|
||||||
description: `Successfully connected to ${connection.alias}.`,
|
|
||||||
});
|
|
||||||
|
|
||||||
return true;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('NWC connection failed:', error);
|
|
||||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: 'Connection failed',
|
|
||||||
description: `Could not connect to the wallet: ${errorMessage}`,
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Remove connection
|
|
||||||
const removeConnection = (connectionString: string) => {
|
|
||||||
const filtered = connections.filter(c => c.connectionString !== connectionString);
|
|
||||||
setConnections(filtered);
|
|
||||||
|
|
||||||
if (activeConnection === connectionString) {
|
|
||||||
const newActive = filtered.length > 0 ? filtered[0].connectionString : null;
|
|
||||||
setActiveConnection(newActive);
|
|
||||||
}
|
|
||||||
|
|
||||||
setConnectionInfo(prev => {
|
|
||||||
const newInfo = { ...prev };
|
|
||||||
delete newInfo[connectionString];
|
|
||||||
return newInfo;
|
|
||||||
});
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: 'Wallet disconnected',
|
|
||||||
description: 'The wallet connection has been removed.',
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
// Get active connection
|
|
||||||
const getActiveConnection = useCallback((): NWCConnection | null => {
|
|
||||||
if (!activeConnection && connections.length > 0) {
|
|
||||||
setActiveConnection(connections[0].connectionString);
|
|
||||||
return connections[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!activeConnection) return null;
|
|
||||||
|
|
||||||
const found = connections.find(c => c.connectionString === activeConnection);
|
|
||||||
return found || null;
|
|
||||||
}, [activeConnection, connections, setActiveConnection]);
|
|
||||||
|
|
||||||
// Send payment using the SDK
|
|
||||||
const sendPayment = useCallback(async (
|
|
||||||
connection: NWCConnection,
|
|
||||||
invoice: string
|
|
||||||
): Promise<{ preimage: string }> => {
|
|
||||||
if (!connection.connectionString) {
|
|
||||||
throw new Error('Invalid connection: missing connection string');
|
|
||||||
}
|
|
||||||
|
|
||||||
let client: LN;
|
|
||||||
try {
|
|
||||||
client = new LN(connection.connectionString);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to create NWC client:', error);
|
|
||||||
throw new Error(`Failed to create NWC client: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
let timeoutId: NodeJS.Timeout | undefined;
|
|
||||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
|
||||||
timeoutId = setTimeout(() => reject(new Error('Payment timeout after 15 seconds')), 15000);
|
|
||||||
});
|
|
||||||
|
|
||||||
const paymentPromise = client.pay(invoice);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await Promise.race([paymentPromise, timeoutPromise]) as { preimage: string };
|
|
||||||
if (timeoutId) clearTimeout(timeoutId);
|
|
||||||
return response;
|
|
||||||
} catch (error) {
|
|
||||||
if (timeoutId) clearTimeout(timeoutId);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('NWC payment failed:', error);
|
|
||||||
|
|
||||||
if (error instanceof Error) {
|
|
||||||
if (error.message.includes('timeout')) {
|
|
||||||
throw new Error('Payment timed out. Please try again.');
|
|
||||||
} else if (error.message.includes('insufficient')) {
|
|
||||||
throw new Error('Insufficient balance in connected wallet.');
|
|
||||||
} else if (error.message.includes('invalid')) {
|
|
||||||
throw new Error('Invalid invoice or connection. Please check your wallet.');
|
|
||||||
} else {
|
|
||||||
throw new Error(`Payment failed: ${error.message}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error('Payment failed with unknown error');
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return {
|
|
||||||
connections,
|
|
||||||
activeConnection,
|
|
||||||
connectionInfo,
|
|
||||||
addConnection,
|
|
||||||
removeConnection,
|
|
||||||
setActiveConnection,
|
|
||||||
getActiveConnection,
|
|
||||||
sendPayment,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
import { useContext } from 'react';
|
|
||||||
import { createContext } from 'react';
|
|
||||||
import { useNWCInternal } from '@/hooks/useNWC';
|
|
||||||
|
|
||||||
type NWCContextType = ReturnType<typeof useNWCInternal>;
|
|
||||||
|
|
||||||
export const NWCContext = createContext<NWCContextType | null>(null);
|
|
||||||
|
|
||||||
export function useNWC(): NWCContextType {
|
|
||||||
const context = useContext(NWCContext);
|
|
||||||
if (!context) {
|
|
||||||
throw new Error('useNWC must be used within a NWCProvider');
|
|
||||||
}
|
|
||||||
return context;
|
|
||||||
}
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
|
||||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
|
||||||
import { NKinds, type NostrEvent } from '@nostrify/nostrify';
|
|
||||||
|
|
||||||
interface PostCommentParams {
|
|
||||||
root: NostrEvent | URL; // The root event to comment on
|
|
||||||
reply?: NostrEvent | URL; // Optional reply to another comment
|
|
||||||
content: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Post a NIP-22 (kind 1111) comment on an event. */
|
|
||||||
export function usePostComment() {
|
|
||||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: async ({ root, reply, content }: PostCommentParams) => {
|
|
||||||
const tags: string[][] = [];
|
|
||||||
|
|
||||||
// d-tag identifiers
|
|
||||||
const dRoot = root instanceof URL ? '' : root.tags.find(([name]) => name === 'd')?.[1] ?? '';
|
|
||||||
const dReply = reply instanceof URL ? '' : reply?.tags.find(([name]) => name === 'd')?.[1] ?? '';
|
|
||||||
|
|
||||||
// Root event tags
|
|
||||||
if (root instanceof URL) {
|
|
||||||
tags.push(['I', root.toString()]);
|
|
||||||
} else if (NKinds.addressable(root.kind)) {
|
|
||||||
tags.push(['A', `${root.kind}:${root.pubkey}:${dRoot}`]);
|
|
||||||
} else if (NKinds.replaceable(root.kind)) {
|
|
||||||
tags.push(['A', `${root.kind}:${root.pubkey}:`]);
|
|
||||||
} else {
|
|
||||||
tags.push(['E', root.id]);
|
|
||||||
}
|
|
||||||
if (root instanceof URL) {
|
|
||||||
tags.push(['K', root.hostname]);
|
|
||||||
} else {
|
|
||||||
tags.push(['K', root.kind.toString()]);
|
|
||||||
tags.push(['P', root.pubkey]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reply event tags
|
|
||||||
if (reply) {
|
|
||||||
if (reply instanceof URL) {
|
|
||||||
tags.push(['i', reply.toString()]);
|
|
||||||
} else if (NKinds.addressable(reply.kind)) {
|
|
||||||
tags.push(['a', `${reply.kind}:${reply.pubkey}:${dReply}`]);
|
|
||||||
} else if (NKinds.replaceable(reply.kind)) {
|
|
||||||
tags.push(['a', `${reply.kind}:${reply.pubkey}:`]);
|
|
||||||
} else {
|
|
||||||
tags.push(['e', reply.id]);
|
|
||||||
}
|
|
||||||
if (reply instanceof URL) {
|
|
||||||
tags.push(['k', reply.hostname]);
|
|
||||||
} else {
|
|
||||||
tags.push(['k', reply.kind.toString()]);
|
|
||||||
tags.push(['p', reply.pubkey]);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// If this is a top-level comment, use the root event's tags
|
|
||||||
if (root instanceof URL) {
|
|
||||||
tags.push(['i', root.toString()]);
|
|
||||||
} else if (NKinds.addressable(root.kind)) {
|
|
||||||
tags.push(['a', `${root.kind}:${root.pubkey}:${dRoot}`]);
|
|
||||||
} else if (NKinds.replaceable(root.kind)) {
|
|
||||||
tags.push(['a', `${root.kind}:${root.pubkey}:`]);
|
|
||||||
} else {
|
|
||||||
tags.push(['e', root.id]);
|
|
||||||
}
|
|
||||||
if (root instanceof URL) {
|
|
||||||
tags.push(['k', root.hostname]);
|
|
||||||
} else {
|
|
||||||
tags.push(['k', root.kind.toString()]);
|
|
||||||
tags.push(['p', root.pubkey]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const event = await publishEvent({
|
|
||||||
kind: 1111,
|
|
||||||
content,
|
|
||||||
tags,
|
|
||||||
});
|
|
||||||
|
|
||||||
return event;
|
|
||||||
},
|
|
||||||
onSuccess: (_, { root }) => {
|
|
||||||
// Invalidate and refetch comments
|
|
||||||
queryClient.invalidateQueries({
|
|
||||||
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id]
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,372 +0,0 @@
|
|||||||
import { useCallback, useState } from 'react';
|
|
||||||
import { useCurrentUser } from './useCurrentUser';
|
|
||||||
import type { NUser } from '@nostrify/react/login';
|
|
||||||
|
|
||||||
// Types for Shakespeare API (compatible with OpenAI ChatCompletionMessageParam)
|
|
||||||
export interface ChatMessage {
|
|
||||||
role: 'user' | 'assistant' | 'system';
|
|
||||||
content: string | Array<{
|
|
||||||
type: 'text' | 'image_url';
|
|
||||||
text?: string;
|
|
||||||
image_url?: {
|
|
||||||
url: string;
|
|
||||||
};
|
|
||||||
}>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ChatCompletionRequest {
|
|
||||||
model: string;
|
|
||||||
messages: ChatMessage[];
|
|
||||||
stream?: boolean;
|
|
||||||
temperature?: number;
|
|
||||||
max_tokens?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ChatCompletionResponse {
|
|
||||||
id: string;
|
|
||||||
object: string;
|
|
||||||
created: number;
|
|
||||||
model: string;
|
|
||||||
choices: Array<{
|
|
||||||
index: number;
|
|
||||||
message: ChatMessage;
|
|
||||||
finish_reason: string;
|
|
||||||
}>;
|
|
||||||
usage: {
|
|
||||||
prompt_tokens: number;
|
|
||||||
completion_tokens: number;
|
|
||||||
total_tokens: number;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Model {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
object: string;
|
|
||||||
owned_by: string;
|
|
||||||
created: number;
|
|
||||||
context_window: number;
|
|
||||||
pricing: {
|
|
||||||
prompt: string;
|
|
||||||
completion: string;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ModelsResponse {
|
|
||||||
object: string;
|
|
||||||
data: Model[];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Configuration
|
|
||||||
const SHAKESPEARE_API_URL = 'https://ai.shakespeare.diy/v1';
|
|
||||||
|
|
||||||
// Helper function to create NIP-98 token
|
|
||||||
async function createNIP98Token(
|
|
||||||
method: string,
|
|
||||||
url: string,
|
|
||||||
body?: unknown,
|
|
||||||
user?: NUser
|
|
||||||
): Promise<string> {
|
|
||||||
if (!user?.signer) {
|
|
||||||
throw new Error('User signer is required for NIP-98 authentication');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create the tags array
|
|
||||||
const tags: string[][] = [
|
|
||||||
['u', url],
|
|
||||||
['method', method]
|
|
||||||
];
|
|
||||||
|
|
||||||
// Add payload hash for requests with body (following NIP-98 spec)
|
|
||||||
if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
|
|
||||||
const bodyString = JSON.stringify(body);
|
|
||||||
const encoder = new TextEncoder();
|
|
||||||
const data = encoder.encode(bodyString);
|
|
||||||
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
|
|
||||||
const payloadHash = Array.from(new Uint8Array(hashBuffer))
|
|
||||||
.map(b => b.toString(16).padStart(2, '0'))
|
|
||||||
.join('');
|
|
||||||
tags.push(['payload', payloadHash]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create the HTTP request event
|
|
||||||
const event = await user.signer.signEvent({
|
|
||||||
kind: 27235, // NIP-98 HTTP Auth
|
|
||||||
content: '',
|
|
||||||
tags,
|
|
||||||
created_at: Math.floor(Date.now() / 1000)
|
|
||||||
});
|
|
||||||
|
|
||||||
// Return the token (base64 encoded event)
|
|
||||||
return btoa(JSON.stringify(event));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper function to handle API errors with user-friendly messages
|
|
||||||
async function handleAPIError(response: Response) {
|
|
||||||
if (response.status === 401) {
|
|
||||||
throw new Error('Authentication failed. Please make sure you are logged in with a Nostr account.');
|
|
||||||
} else if (response.status === 402) {
|
|
||||||
throw new Error('Insufficient credits. Please add credits to your account to use premium models, or use the free "tybalt" model.');
|
|
||||||
} else if (response.status === 400) {
|
|
||||||
try {
|
|
||||||
const error = await response.json();
|
|
||||||
if (error.error?.type === 'invalid_request_error') {
|
|
||||||
// Handle specific validation errors
|
|
||||||
if (error.error.code === 'minimum_amount_not_met') {
|
|
||||||
throw new Error(`Minimum credit amount is $${error.error.minimum_amount}. Please increase your payment amount.`);
|
|
||||||
} else if (error.error.code === 'unsupported_method') {
|
|
||||||
throw new Error('Payment method not supported. Please use "stripe" or "lightning".');
|
|
||||||
} else if (error.error.code === 'invalid_url') {
|
|
||||||
throw new Error('Invalid redirect URL provided for Stripe payment.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new Error(`Invalid request: ${error.error?.message || error.details || error.error || 'Please check your request parameters.'}`);
|
|
||||||
} catch {
|
|
||||||
throw new Error('Invalid request. Please check your parameters and try again.');
|
|
||||||
}
|
|
||||||
} else if (response.status === 404) {
|
|
||||||
throw new Error('Resource not found. Please check the payment ID or try again.');
|
|
||||||
} else if (response.status >= 500) {
|
|
||||||
throw new Error('Server error. Please try again in a few moments.');
|
|
||||||
} else if (!response.ok) {
|
|
||||||
try {
|
|
||||||
const errorData = await response.json();
|
|
||||||
throw new Error(`API error: ${errorData.error?.message || errorData.details || errorData.error || response.statusText}`);
|
|
||||||
} catch {
|
|
||||||
throw new Error(`Network error: ${response.statusText}. Please check your connection and try again.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useShakespeare() {
|
|
||||||
const { user } = useCurrentUser();
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
// Clear error helper
|
|
||||||
const clearError = useCallback(() => {
|
|
||||||
setError(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Chat completion function
|
|
||||||
const sendChatMessage = useCallback(async (
|
|
||||||
messages: ChatMessage[],
|
|
||||||
model: string = 'shakespeare',
|
|
||||||
options?: Partial<ChatCompletionRequest>
|
|
||||||
): Promise<ChatCompletionResponse> => {
|
|
||||||
if (!user) {
|
|
||||||
throw new Error('User must be logged in to use AI features');
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsLoading(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const requestBody: ChatCompletionRequest = {
|
|
||||||
model,
|
|
||||||
messages,
|
|
||||||
...options
|
|
||||||
};
|
|
||||||
|
|
||||||
const token = await createNIP98Token(
|
|
||||||
'POST',
|
|
||||||
`${SHAKESPEARE_API_URL}/chat/completions`,
|
|
||||||
requestBody,
|
|
||||||
user
|
|
||||||
);
|
|
||||||
|
|
||||||
const response = await fetch(`${SHAKESPEARE_API_URL}/chat/completions`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Authorization': `Nostr ${token}`,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify(requestBody),
|
|
||||||
});
|
|
||||||
|
|
||||||
await handleAPIError(response);
|
|
||||||
return await response.json();
|
|
||||||
} catch (err) {
|
|
||||||
let errorMessage = 'An unexpected error occurred';
|
|
||||||
|
|
||||||
if (err instanceof Error) {
|
|
||||||
errorMessage = err.message;
|
|
||||||
} else if (typeof err === 'string') {
|
|
||||||
errorMessage = err;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add context for common issues
|
|
||||||
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
|
|
||||||
errorMessage = 'Network error: Please check your internet connection and try again.';
|
|
||||||
} else if (errorMessage.includes('signer')) {
|
|
||||||
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
|
|
||||||
}
|
|
||||||
|
|
||||||
setError(errorMessage);
|
|
||||||
throw new Error(errorMessage);
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
}, [user]);
|
|
||||||
|
|
||||||
// Streaming chat completion function
|
|
||||||
const sendStreamingMessage = useCallback(async (
|
|
||||||
messages: ChatMessage[],
|
|
||||||
model: string = 'shakespeare',
|
|
||||||
onChunk: (chunk: string) => void,
|
|
||||||
options?: Partial<ChatCompletionRequest>
|
|
||||||
): Promise<void> => {
|
|
||||||
if (!user) {
|
|
||||||
throw new Error('User must be logged in to use AI features');
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsLoading(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const requestBody: ChatCompletionRequest = {
|
|
||||||
model,
|
|
||||||
messages,
|
|
||||||
stream: true,
|
|
||||||
...options
|
|
||||||
};
|
|
||||||
|
|
||||||
const token = await createNIP98Token(
|
|
||||||
'POST',
|
|
||||||
`${SHAKESPEARE_API_URL}/chat/completions`,
|
|
||||||
requestBody,
|
|
||||||
user
|
|
||||||
);
|
|
||||||
|
|
||||||
const response = await fetch(`${SHAKESPEARE_API_URL}/chat/completions`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Authorization': `Nostr ${token}`,
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify(requestBody),
|
|
||||||
});
|
|
||||||
|
|
||||||
await handleAPIError(response);
|
|
||||||
|
|
||||||
if (!response.body) {
|
|
||||||
throw new Error('No response body');
|
|
||||||
}
|
|
||||||
|
|
||||||
const reader = response.body.getReader();
|
|
||||||
const decoder = new TextDecoder();
|
|
||||||
|
|
||||||
try {
|
|
||||||
while (true) {
|
|
||||||
const { done, value } = await reader.read();
|
|
||||||
if (done) break;
|
|
||||||
|
|
||||||
const chunk = decoder.decode(value);
|
|
||||||
const lines = chunk.split('\n');
|
|
||||||
|
|
||||||
for (const line of lines) {
|
|
||||||
if (line.startsWith('data: ')) {
|
|
||||||
const data = line.slice(6);
|
|
||||||
if (data === '[DONE]') return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const parsed = JSON.parse(data);
|
|
||||||
const content = parsed.choices?.[0]?.delta?.content;
|
|
||||||
if (content) {
|
|
||||||
onChunk(content);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Ignore parsing errors for incomplete chunks
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
reader.releaseLock();
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
let errorMessage = 'An unexpected error occurred';
|
|
||||||
|
|
||||||
if (err instanceof Error) {
|
|
||||||
errorMessage = err.message;
|
|
||||||
} else if (typeof err === 'string') {
|
|
||||||
errorMessage = err;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add context for common issues
|
|
||||||
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
|
|
||||||
errorMessage = 'Network error: Please check your internet connection and try again.';
|
|
||||||
} else if (errorMessage.includes('signer')) {
|
|
||||||
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
|
|
||||||
}
|
|
||||||
|
|
||||||
setError(errorMessage);
|
|
||||||
throw new Error(errorMessage);
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
}, [user]);
|
|
||||||
|
|
||||||
// Get available models
|
|
||||||
const getAvailableModels = useCallback(async (): Promise<ModelsResponse> => {
|
|
||||||
if (!user) {
|
|
||||||
throw new Error('User must be logged in to use AI features');
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsLoading(true);
|
|
||||||
setError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const token = await createNIP98Token(
|
|
||||||
'GET',
|
|
||||||
`${SHAKESPEARE_API_URL}/models`,
|
|
||||||
undefined,
|
|
||||||
user
|
|
||||||
);
|
|
||||||
|
|
||||||
const response = await fetch(`${SHAKESPEARE_API_URL}/models`, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
'Authorization': `Nostr ${token}`,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
await handleAPIError(response);
|
|
||||||
return await response.json();
|
|
||||||
} catch (err) {
|
|
||||||
let errorMessage = 'An unexpected error occurred';
|
|
||||||
|
|
||||||
if (err instanceof Error) {
|
|
||||||
errorMessage = err.message;
|
|
||||||
} else if (typeof err === 'string') {
|
|
||||||
errorMessage = err;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add context for common issues
|
|
||||||
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
|
|
||||||
errorMessage = 'Network error: Please check your internet connection and try again.';
|
|
||||||
} else if (errorMessage.includes('signer')) {
|
|
||||||
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
|
|
||||||
}
|
|
||||||
|
|
||||||
setError(errorMessage);
|
|
||||||
throw new Error(errorMessage);
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
}, [user]);
|
|
||||||
|
|
||||||
return {
|
|
||||||
// State
|
|
||||||
isLoading,
|
|
||||||
error,
|
|
||||||
isAuthenticated: !!user,
|
|
||||||
|
|
||||||
// Actions
|
|
||||||
sendChatMessage,
|
|
||||||
sendStreamingMessage,
|
|
||||||
getAvailableModels,
|
|
||||||
clearError,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
import { useMemo } from 'react';
|
|
||||||
import { useNWC } from '@/hooks/useNWCContext';
|
|
||||||
import type { WebLNProvider } from '@webbtc/webln-types';
|
|
||||||
|
|
||||||
export interface WalletStatus {
|
|
||||||
hasNWC: boolean;
|
|
||||||
webln: WebLNProvider | null;
|
|
||||||
activeNWC: ReturnType<typeof useNWC>['getActiveConnection'] extends () => infer T ? T : null;
|
|
||||||
preferredMethod: 'nwc' | 'webln' | 'manual';
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useWallet() {
|
|
||||||
const { connections, getActiveConnection } = useNWC();
|
|
||||||
|
|
||||||
// Get the active connection directly - no memoization to avoid stale state
|
|
||||||
const activeNWC = getActiveConnection();
|
|
||||||
|
|
||||||
// Access WebLN directly from browser global scope
|
|
||||||
const webln = (globalThis as { webln?: WebLNProvider }).webln || null;
|
|
||||||
|
|
||||||
// Calculate status values reactively
|
|
||||||
const hasNWC = useMemo(() => {
|
|
||||||
return connections.length > 0 && connections.some(c => c.isConnected);
|
|
||||||
}, [connections]);
|
|
||||||
|
|
||||||
// Determine preferred payment method
|
|
||||||
const preferredMethod: WalletStatus['preferredMethod'] = activeNWC
|
|
||||||
? 'nwc'
|
|
||||||
: webln
|
|
||||||
? 'webln'
|
|
||||||
: 'manual';
|
|
||||||
|
|
||||||
const status: WalletStatus = {
|
|
||||||
hasNWC,
|
|
||||||
webln,
|
|
||||||
activeNWC,
|
|
||||||
preferredMethod,
|
|
||||||
};
|
|
||||||
|
|
||||||
return status;
|
|
||||||
}
|
|
||||||
@@ -1,350 +0,0 @@
|
|||||||
import { useState, useMemo, useEffect, useCallback } from 'react';
|
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
|
||||||
import { useAuthor } from '@/hooks/useAuthor';
|
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
|
||||||
import { useToast } from '@/hooks/useToast';
|
|
||||||
import { useNWC } from '@/hooks/useNWCContext';
|
|
||||||
import type { NWCConnection } from '@/hooks/useNWC';
|
|
||||||
import { nip57 } from 'nostr-tools';
|
|
||||||
import type { Event } from 'nostr-tools';
|
|
||||||
import type { WebLNProvider } from '@webbtc/webln-types';
|
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
|
||||||
import { useNostr } from '@nostrify/react';
|
|
||||||
import type { NostrEvent } from '@nostrify/nostrify';
|
|
||||||
|
|
||||||
export function useZaps(
|
|
||||||
target: Event | Event[],
|
|
||||||
webln: WebLNProvider | null,
|
|
||||||
_nwcConnection: NWCConnection | null,
|
|
||||||
onZapSuccess?: () => void
|
|
||||||
) {
|
|
||||||
const { nostr } = useNostr();
|
|
||||||
const { toast } = useToast();
|
|
||||||
const { user } = useCurrentUser();
|
|
||||||
const { config } = useAppContext();
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
|
|
||||||
// Handle the case where an empty array is passed (from ZapButton when external data is provided)
|
|
||||||
const actualTarget = Array.isArray(target) ? (target.length > 0 ? target[0] : null) : target;
|
|
||||||
|
|
||||||
const author = useAuthor(actualTarget?.pubkey);
|
|
||||||
const { sendPayment, getActiveConnection } = useNWC();
|
|
||||||
const [isZapping, setIsZapping] = useState(false);
|
|
||||||
const [invoice, setInvoice] = useState<string | null>(null);
|
|
||||||
|
|
||||||
// Cleanup state when component unmounts
|
|
||||||
useEffect(() => {
|
|
||||||
return () => {
|
|
||||||
setIsZapping(false);
|
|
||||||
setInvoice(null);
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const { data: zapEvents, ...query } = useQuery<NostrEvent[], Error>({
|
|
||||||
queryKey: ['zaps', actualTarget?.id],
|
|
||||||
staleTime: 30000, // 30 seconds
|
|
||||||
refetchInterval: (query) => {
|
|
||||||
// Only refetch if the query is currently being observed (component is mounted)
|
|
||||||
return query.getObserversCount() > 0 ? 60000 : false;
|
|
||||||
},
|
|
||||||
queryFn: async (c) => {
|
|
||||||
if (!actualTarget) return [];
|
|
||||||
|
|
||||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
|
|
||||||
|
|
||||||
// Query for zap receipts for this specific event
|
|
||||||
if (actualTarget.kind >= 30000 && actualTarget.kind < 40000) {
|
|
||||||
// Addressable event
|
|
||||||
const identifier = actualTarget.tags.find((t) => t[0] === 'd')?.[1] || '';
|
|
||||||
const events = await nostr.query([{
|
|
||||||
kinds: [9735],
|
|
||||||
'#a': [`${actualTarget.kind}:${actualTarget.pubkey}:${identifier}`],
|
|
||||||
}], { signal });
|
|
||||||
return events;
|
|
||||||
} else {
|
|
||||||
// Regular event
|
|
||||||
const events = await nostr.query([{
|
|
||||||
kinds: [9735],
|
|
||||||
'#e': [actualTarget.id],
|
|
||||||
}], { signal });
|
|
||||||
return events;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
enabled: !!actualTarget?.id,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Process zap events into simple counts and totals
|
|
||||||
const { zapCount, totalSats, zaps } = useMemo(() => {
|
|
||||||
if (!zapEvents || !Array.isArray(zapEvents) || !actualTarget) {
|
|
||||||
return { zapCount: 0, totalSats: 0, zaps: [] };
|
|
||||||
}
|
|
||||||
|
|
||||||
let count = 0;
|
|
||||||
let sats = 0;
|
|
||||||
|
|
||||||
zapEvents.forEach(zap => {
|
|
||||||
count++;
|
|
||||||
|
|
||||||
// Try multiple methods to extract the amount:
|
|
||||||
|
|
||||||
// Method 1: amount tag (from zap request, sometimes copied to receipt)
|
|
||||||
const amountTag = zap.tags.find(([name]) => name === 'amount')?.[1];
|
|
||||||
if (amountTag) {
|
|
||||||
const millisats = parseInt(amountTag);
|
|
||||||
sats += Math.floor(millisats / 1000);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Method 2: Extract from bolt11 invoice
|
|
||||||
const bolt11Tag = zap.tags.find(([name]) => name === 'bolt11')?.[1];
|
|
||||||
if (bolt11Tag) {
|
|
||||||
try {
|
|
||||||
const invoiceSats = nip57.getSatoshisAmountFromBolt11(bolt11Tag);
|
|
||||||
sats += invoiceSats;
|
|
||||||
return;
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('Failed to parse bolt11 amount:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Method 3: Parse from description (zap request JSON)
|
|
||||||
const descriptionTag = zap.tags.find(([name]) => name === 'description')?.[1];
|
|
||||||
if (descriptionTag) {
|
|
||||||
try {
|
|
||||||
const zapRequest = JSON.parse(descriptionTag);
|
|
||||||
const requestAmountTag = zapRequest.tags?.find(([name]: string[]) => name === 'amount')?.[1];
|
|
||||||
if (requestAmountTag) {
|
|
||||||
const millisats = parseInt(requestAmountTag);
|
|
||||||
sats += Math.floor(millisats / 1000);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('Failed to parse description JSON:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
console.warn('Could not extract amount from zap receipt:', zap.id);
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
return { zapCount: count, totalSats: sats, zaps: zapEvents };
|
|
||||||
}, [zapEvents, actualTarget]);
|
|
||||||
|
|
||||||
const zap = async (amount: number, comment: string) => {
|
|
||||||
if (amount <= 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsZapping(true);
|
|
||||||
setInvoice(null); // Clear any previous invoice at the start
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
toast({
|
|
||||||
title: 'Login required',
|
|
||||||
description: 'You must be logged in to send a zap.',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
setIsZapping(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!actualTarget) {
|
|
||||||
toast({
|
|
||||||
title: 'Event not found',
|
|
||||||
description: 'Could not find the event to zap.',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
setIsZapping(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (!author.data || !author.data?.metadata || !author.data?.event ) {
|
|
||||||
toast({
|
|
||||||
title: 'Author not found',
|
|
||||||
description: 'Could not find the author of this item.',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
setIsZapping(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { lud06, lud16 } = author.data.metadata;
|
|
||||||
if (!lud06 && !lud16) {
|
|
||||||
toast({
|
|
||||||
title: 'Lightning address not found',
|
|
||||||
description: 'The author does not have a lightning address configured.',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
setIsZapping(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get zap endpoint using the old reliable method
|
|
||||||
const zapEndpoint = await nip57.getZapEndpoint(author.data.event);
|
|
||||||
if (!zapEndpoint) {
|
|
||||||
toast({
|
|
||||||
title: 'Zap endpoint not found',
|
|
||||||
description: 'Could not find a zap endpoint for the author.',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
setIsZapping(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create zap request - use appropriate event format based on kind
|
|
||||||
// For addressable events (30000-39999), pass the object to get 'a' tag
|
|
||||||
// For all other events, pass the ID string to get 'e' tag
|
|
||||||
const event = (actualTarget.kind >= 30000 && actualTarget.kind < 40000)
|
|
||||||
? actualTarget
|
|
||||||
: actualTarget.id;
|
|
||||||
|
|
||||||
const zapAmount = amount * 1000; // convert to millisats
|
|
||||||
|
|
||||||
const zapRequest = nip57.makeZapRequest({
|
|
||||||
profile: actualTarget.pubkey,
|
|
||||||
event: event,
|
|
||||||
amount: zapAmount,
|
|
||||||
relays: config.relayMetadata.relays.map(r => r.url),
|
|
||||||
comment
|
|
||||||
});
|
|
||||||
|
|
||||||
// Sign the zap request (but don't publish to relays - only send to LNURL endpoint)
|
|
||||||
if (!user.signer) {
|
|
||||||
throw new Error('No signer available');
|
|
||||||
}
|
|
||||||
const signedZapRequest = await user.signer.signEvent(zapRequest);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const res = await fetch(`${zapEndpoint}?amount=${zapAmount}&nostr=${encodeURI(JSON.stringify(signedZapRequest))}`);
|
|
||||||
const responseData = await res.json();
|
|
||||||
|
|
||||||
if (!res.ok) {
|
|
||||||
throw new Error(`HTTP ${res.status}: ${responseData.reason || 'Unknown error'}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const newInvoice = responseData.pr;
|
|
||||||
if (!newInvoice || typeof newInvoice !== 'string') {
|
|
||||||
throw new Error('Lightning service did not return a valid invoice');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the current active NWC connection dynamically
|
|
||||||
const currentNWCConnection = getActiveConnection();
|
|
||||||
|
|
||||||
// Try NWC first if available and properly connected
|
|
||||||
if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) {
|
|
||||||
try {
|
|
||||||
await sendPayment(currentNWCConnection, newInvoice);
|
|
||||||
|
|
||||||
// Clear states immediately on success
|
|
||||||
setIsZapping(false);
|
|
||||||
setInvoice(null);
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: 'Zap successful!',
|
|
||||||
description: `You sent ${amount} sats via NWC to the author.`,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Invalidate zap queries to refresh counts
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['zaps'] });
|
|
||||||
|
|
||||||
// Close dialog last to ensure clean state
|
|
||||||
onZapSuccess?.();
|
|
||||||
return;
|
|
||||||
} catch (nwcError) {
|
|
||||||
console.error('NWC payment failed, falling back:', nwcError);
|
|
||||||
|
|
||||||
// Show specific NWC error to user for debugging
|
|
||||||
const errorMessage = nwcError instanceof Error ? nwcError.message : 'Unknown NWC error';
|
|
||||||
toast({
|
|
||||||
title: 'NWC payment failed',
|
|
||||||
description: `${errorMessage}. Falling back to other payment methods...`,
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (webln) { // Try WebLN next
|
|
||||||
try {
|
|
||||||
// For native WebLN, we may need to enable it first
|
|
||||||
let webLnProvider = webln;
|
|
||||||
if (webln.enable && typeof webln.enable === 'function') {
|
|
||||||
const enabledProvider = await webln.enable();
|
|
||||||
// Some implementations return the provider, others return void
|
|
||||||
// Cast to WebLNProvider to handle both cases
|
|
||||||
const provider = enabledProvider as WebLNProvider | undefined;
|
|
||||||
if (provider) {
|
|
||||||
webLnProvider = provider;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await webLnProvider.sendPayment(newInvoice);
|
|
||||||
|
|
||||||
// Clear states immediately on success
|
|
||||||
setIsZapping(false);
|
|
||||||
setInvoice(null);
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: 'Zap successful!',
|
|
||||||
description: `You sent ${amount} sats to the author.`,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Invalidate zap queries to refresh counts
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['zaps'] });
|
|
||||||
|
|
||||||
// Close dialog last to ensure clean state
|
|
||||||
onZapSuccess?.();
|
|
||||||
} catch (weblnError) {
|
|
||||||
console.error('WebLN payment failed, falling back:', weblnError);
|
|
||||||
|
|
||||||
// Show specific WebLN error to user for debugging
|
|
||||||
const errorMessage = weblnError instanceof Error ? weblnError.message : 'Unknown WebLN error';
|
|
||||||
toast({
|
|
||||||
title: 'WebLN payment failed',
|
|
||||||
description: `${errorMessage}. Falling back to other payment methods...`,
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
|
|
||||||
setInvoice(newInvoice);
|
|
||||||
setIsZapping(false);
|
|
||||||
}
|
|
||||||
} else { // Default - show QR code and manual Lightning URI
|
|
||||||
setInvoice(newInvoice);
|
|
||||||
setIsZapping(false);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Zap error:', err);
|
|
||||||
toast({
|
|
||||||
title: 'Zap failed',
|
|
||||||
description: (err as Error).message,
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
setIsZapping(false);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Zap error:', err);
|
|
||||||
toast({
|
|
||||||
title: 'Zap failed',
|
|
||||||
description: (err as Error).message,
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
setIsZapping(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const resetInvoice = useCallback(() => {
|
|
||||||
setInvoice(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return {
|
|
||||||
zaps,
|
|
||||||
zapCount,
|
|
||||||
totalSats,
|
|
||||||
...query,
|
|
||||||
zap,
|
|
||||||
isZapping,
|
|
||||||
invoice,
|
|
||||||
setInvoice,
|
|
||||||
resetInvoice,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
+116
-62
@@ -4,89 +4,85 @@
|
|||||||
|
|
||||||
@layer base {
|
@layer base {
|
||||||
:root {
|
:root {
|
||||||
--background: 0 0% 100%;
|
/* Gnome Forest Theme - Light Mode */
|
||||||
--foreground: 222.2 84% 4.9%;
|
--background: 120 20% 97%; /* Very light sage green */
|
||||||
|
--foreground: 120 15% 15%; /* Dark forest green */
|
||||||
|
|
||||||
--card: 0 0% 100%;
|
--card: 120 25% 95%; /* Light moss green */
|
||||||
--card-foreground: 222.2 84% 4.9%;
|
--card-foreground: 120 15% 15%;
|
||||||
|
|
||||||
--popover: 0 0% 100%;
|
--popover: 120 25% 95%;
|
||||||
--popover-foreground: 222.2 84% 4.9%;
|
--popover-foreground: 120 15% 15%;
|
||||||
|
|
||||||
--primary: 222.2 47.4% 11.2%;
|
--primary: 25 85% 55%; /* Warm mushroom orange */
|
||||||
--primary-foreground: 210 40% 98%;
|
--primary-foreground: 120 25% 95%;
|
||||||
|
|
||||||
--secondary: 210 40% 96.1%;
|
--secondary: 120 30% 85%; /* Soft forest green */
|
||||||
--secondary-foreground: 222.2 47.4% 11.2%;
|
--secondary-foreground: 120 15% 15%;
|
||||||
|
|
||||||
--muted: 210 40% 96.1%;
|
--muted: 120 20% 90%; /* Light moss */
|
||||||
--muted-foreground: 215.4 16.3% 46.9%;
|
--muted-foreground: 120 10% 45%; /* Medium forest green */
|
||||||
|
|
||||||
--accent: 210 40% 96.1%;
|
--accent: 45 90% 70%; /* Golden acorn yellow */
|
||||||
--accent-foreground: 222.2 47.4% 11.2%;
|
--accent-foreground: 120 15% 15%;
|
||||||
|
|
||||||
--destructive: 0 84.2% 60.2%;
|
--destructive: 0 84.2% 60.2%; /* Red mushroom */
|
||||||
--destructive-foreground: 210 40% 98%;
|
--destructive-foreground: 120 25% 95%;
|
||||||
|
|
||||||
--border: 214.3 31.8% 91.4%;
|
--border: 120 25% 85%; /* Soft green border */
|
||||||
--input: 214.3 31.8% 91.4%;
|
--input: 120 25% 90%; /* Light input background */
|
||||||
--ring: 222.2 84% 4.9%;
|
--ring: 25 85% 55%; /* Mushroom orange focus ring */
|
||||||
|
|
||||||
--radius: 0.75rem;
|
--radius: 0.75rem; /* More rounded for organic feel */
|
||||||
|
|
||||||
--sidebar-background: 0 0% 98%;
|
--sidebar-background: 120 30% 92%;
|
||||||
|
--sidebar-foreground: 120 15% 20%;
|
||||||
--sidebar-foreground: 240 5.3% 26.1%;
|
--sidebar-primary: 25 85% 55%;
|
||||||
|
--sidebar-primary-foreground: 120 25% 95%;
|
||||||
--sidebar-primary: 240 5.9% 10%;
|
--sidebar-accent: 120 25% 88%;
|
||||||
|
--sidebar-accent-foreground: 120 15% 15%;
|
||||||
--sidebar-primary-foreground: 0 0% 98%;
|
--sidebar-border: 120 25% 80%;
|
||||||
|
--sidebar-ring: 25 85% 55%;
|
||||||
--sidebar-accent: 240 4.8% 95.9%;
|
|
||||||
|
|
||||||
--sidebar-accent-foreground: 240 5.9% 10%;
|
|
||||||
|
|
||||||
--sidebar-border: 220 13% 91%;
|
|
||||||
|
|
||||||
--sidebar-ring: 217.2 91.2% 59.8%;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.dark {
|
.dark {
|
||||||
--background: 222.2 84% 4.9%;
|
/* Gnome Forest Theme - Dark Mode (Night in the Forest) */
|
||||||
--foreground: 210 40% 98%;
|
--background: 120 25% 8%; /* Deep forest night */
|
||||||
|
--foreground: 120 20% 85%; /* Light moss green */
|
||||||
|
|
||||||
--card: 222.2 84% 4.9%;
|
--card: 120 20% 12%; /* Dark forest floor */
|
||||||
--card-foreground: 210 40% 98%;
|
--card-foreground: 120 20% 85%;
|
||||||
|
|
||||||
--popover: 222.2 84% 4.9%;
|
--popover: 120 20% 12%;
|
||||||
--popover-foreground: 210 40% 98%;
|
--popover-foreground: 120 20% 85%;
|
||||||
|
|
||||||
--primary: 210 40% 98%;
|
--primary: 25 85% 65%; /* Bright mushroom orange */
|
||||||
--primary-foreground: 222.2 47.4% 11.2%;
|
--primary-foreground: 120 20% 12%;
|
||||||
|
|
||||||
--secondary: 217.2 32.6% 17.5%;
|
--secondary: 120 15% 20%; /* Dark moss */
|
||||||
--secondary-foreground: 210 40% 98%;
|
--secondary-foreground: 120 20% 85%;
|
||||||
|
|
||||||
--muted: 217.2 32.6% 17.5%;
|
--muted: 120 15% 18%; /* Dark undergrowth */
|
||||||
--muted-foreground: 215 20.2% 65.1%;
|
--muted-foreground: 120 15% 60%; /* Medium light green */
|
||||||
|
|
||||||
--accent: 217.2 32.6% 17.5%;
|
--accent: 45 90% 75%; /* Bright golden acorn */
|
||||||
--accent-foreground: 210 40% 98%;
|
--accent-foreground: 120 20% 12%;
|
||||||
|
|
||||||
--destructive: 0 62.8% 30.6%;
|
--destructive: 0 75% 55%; /* Dark red mushroom */
|
||||||
--destructive-foreground: 210 40% 98%;
|
--destructive-foreground: 120 20% 85%;
|
||||||
|
|
||||||
--border: 217.2 32.6% 17.5%;
|
--border: 120 20% 20%; /* Dark forest border */
|
||||||
--input: 217.2 32.6% 17.5%;
|
--input: 120 20% 15%; /* Dark input background */
|
||||||
--ring: 212.7 26.8% 83.9%;
|
--ring: 25 85% 65%; /* Bright mushroom focus ring */
|
||||||
--sidebar-background: 240 5.9% 10%;
|
|
||||||
--sidebar-foreground: 240 4.8% 95.9%;
|
--sidebar-background: 120 25% 10%;
|
||||||
--sidebar-primary: 224.3 76.3% 48%;
|
--sidebar-foreground: 120 20% 80%;
|
||||||
--sidebar-primary-foreground: 0 0% 100%;
|
--sidebar-primary: 25 85% 65%;
|
||||||
--sidebar-accent: 240 3.7% 15.9%;
|
--sidebar-primary-foreground: 120 20% 12%;
|
||||||
--sidebar-accent-foreground: 240 4.8% 95.9%;
|
--sidebar-accent: 120 20% 18%;
|
||||||
--sidebar-border: 240 3.7% 15.9%;
|
--sidebar-accent-foreground: 120 20% 85%;
|
||||||
--sidebar-ring: 217.2 91.2% 59.8%;
|
--sidebar-border: 120 20% 20%;
|
||||||
|
--sidebar-ring: 25 85% 65%;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,5 +93,63 @@
|
|||||||
|
|
||||||
body {
|
body {
|
||||||
@apply bg-background text-foreground;
|
@apply bg-background text-foreground;
|
||||||
|
background-image:
|
||||||
|
radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.1) 0%, transparent 50%),
|
||||||
|
radial-gradient(circle at 80% 20%, rgba(255, 119, 48, 0.1) 0%, transparent 50%),
|
||||||
|
radial-gradient(circle at 40% 40%, rgba(120, 200, 120, 0.05) 0%, transparent 50%);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Gnome-specific animations and effects */
|
||||||
|
@keyframes gnome-wiggle {
|
||||||
|
0%, 100% { transform: rotate(-1deg); }
|
||||||
|
50% { transform: rotate(1deg); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes mushroom-glow {
|
||||||
|
0%, 100% { box-shadow: 0 0 5px rgba(255, 119, 48, 0.3); }
|
||||||
|
50% { box-shadow: 0 0 15px rgba(255, 119, 48, 0.5); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes forest-shimmer {
|
||||||
|
0% { background-position: -200% 0; }
|
||||||
|
100% { background-position: 200% 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.gnome-wiggle {
|
||||||
|
animation: gnome-wiggle 2s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mushroom-glow {
|
||||||
|
animation: mushroom-glow 3s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.forest-shimmer {
|
||||||
|
background: linear-gradient(
|
||||||
|
90deg,
|
||||||
|
transparent,
|
||||||
|
rgba(120, 200, 120, 0.2),
|
||||||
|
transparent
|
||||||
|
);
|
||||||
|
background-size: 200% 100%;
|
||||||
|
animation: forest-shimmer 3s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Custom scrollbar for gnome theme */
|
||||||
|
::-webkit-scrollbar {
|
||||||
|
width: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-track {
|
||||||
|
background: hsl(var(--muted));
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-thumb {
|
||||||
|
background: hsl(var(--primary));
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: hsl(var(--accent));
|
||||||
|
}
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
import type { NostrEvent } from '@nostrify/nostrify';
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Message Protocol Types
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
export const MESSAGE_PROTOCOL = {
|
|
||||||
NIP04: 'nip04',
|
|
||||||
NIP17: 'nip17',
|
|
||||||
UNKNOWN: 'unknown',
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
export type MessageProtocol = typeof MESSAGE_PROTOCOL[keyof typeof MESSAGE_PROTOCOL];
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Protocol Mode (for user selection)
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
export const PROTOCOL_MODE = {
|
|
||||||
NIP04_ONLY: 'nip04_only',
|
|
||||||
NIP17_ONLY: 'nip17_only',
|
|
||||||
NIP04_OR_NIP17: 'nip04_or_nip17',
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
export type ProtocolMode = typeof PROTOCOL_MODE[keyof typeof PROTOCOL_MODE];
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Loading Phases
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
export const LOADING_PHASES = {
|
|
||||||
IDLE: 'idle',
|
|
||||||
CACHE: 'cache',
|
|
||||||
RELAYS: 'relays',
|
|
||||||
SUBSCRIPTIONS: 'subscriptions',
|
|
||||||
READY: 'ready',
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
export type LoadingPhase = typeof LOADING_PHASES[keyof typeof LOADING_PHASES];
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Protocol Configuration
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
export const PROTOCOL_CONFIG = {
|
|
||||||
[MESSAGE_PROTOCOL.NIP04]: {
|
|
||||||
label: 'NIP-04',
|
|
||||||
description: 'Legacy DMs',
|
|
||||||
kind: 4,
|
|
||||||
},
|
|
||||||
[MESSAGE_PROTOCOL.NIP17]: {
|
|
||||||
label: 'NIP-17',
|
|
||||||
description: 'Private DMs',
|
|
||||||
kind: 1059,
|
|
||||||
},
|
|
||||||
[MESSAGE_PROTOCOL.UNKNOWN]: {
|
|
||||||
label: 'Unknown',
|
|
||||||
description: 'Unknown protocol',
|
|
||||||
kind: 0,
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Helper Functions
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the message protocol from an event kind
|
|
||||||
*/
|
|
||||||
export function getMessageProtocol(event: NostrEvent): MessageProtocol {
|
|
||||||
switch (event.kind) {
|
|
||||||
case 4:
|
|
||||||
return MESSAGE_PROTOCOL.NIP04;
|
|
||||||
case 1059:
|
|
||||||
return MESSAGE_PROTOCOL.NIP17;
|
|
||||||
default:
|
|
||||||
return MESSAGE_PROTOCOL.UNKNOWN;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if a protocol is valid for sending messages
|
|
||||||
*/
|
|
||||||
export function isValidSendProtocol(protocol: MessageProtocol): boolean {
|
|
||||||
return protocol === MESSAGE_PROTOCOL.NIP04 || protocol === MESSAGE_PROTOCOL.NIP17;
|
|
||||||
}
|
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
import { openDB, type IDBPDatabase } from 'idb';
|
|
||||||
import type { NostrEvent } from '@nostrify/nostrify';
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// IndexedDB Schema
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
// Use domain-based naming to avoid conflicts between apps on same domain
|
|
||||||
const getDBName = () => {
|
|
||||||
// Use hostname for unique DB per app (e.g., 'nostr-dm-store-localhost', 'nostr-dm-store-myapp.com')
|
|
||||||
const hostname = typeof window !== 'undefined' ? window.location.hostname : 'default';
|
|
||||||
return `nostr-dm-store-${hostname}`;
|
|
||||||
};
|
|
||||||
const DB_NAME = getDBName();
|
|
||||||
const DB_VERSION = 1;
|
|
||||||
const STORE_NAME = 'messages';
|
|
||||||
|
|
||||||
interface StoredParticipant {
|
|
||||||
messages: NostrEvent[];
|
|
||||||
lastActivity: number;
|
|
||||||
hasNIP4: boolean;
|
|
||||||
hasNIP17: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface MessageStore {
|
|
||||||
participants: Record<string, StoredParticipant>;
|
|
||||||
lastSync: {
|
|
||||||
nip4: number | null;
|
|
||||||
nip17: number | null;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Database Operations
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Open the IndexedDB database
|
|
||||||
*/
|
|
||||||
async function openDatabase(): Promise<IDBPDatabase> {
|
|
||||||
return openDB(DB_NAME, DB_VERSION, {
|
|
||||||
upgrade(db) {
|
|
||||||
// Create the messages store if it doesn't exist
|
|
||||||
if (!db.objectStoreNames.contains(STORE_NAME)) {
|
|
||||||
db.createObjectStore(STORE_NAME);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Write messages to IndexedDB for a specific user
|
|
||||||
* Messages are stored in their original encrypted form (kind 4 or kind 13)
|
|
||||||
*/
|
|
||||||
export async function writeMessagesToDB(
|
|
||||||
userPubkey: string,
|
|
||||||
messageStore: MessageStore
|
|
||||||
): Promise<void> {
|
|
||||||
try {
|
|
||||||
const db = await openDatabase();
|
|
||||||
|
|
||||||
// Store messages in their original encrypted form (no NIP-44 wrapper needed)
|
|
||||||
// Each message content is already encrypted by the sender
|
|
||||||
await db.put(STORE_NAME, messageStore, userPubkey);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[MessageStore] ❌ Error writing to IndexedDB:', error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Read messages from IndexedDB for a specific user
|
|
||||||
* Messages are stored in their original encrypted form (kind 4 or kind 13)
|
|
||||||
*/
|
|
||||||
export async function readMessagesFromDB(
|
|
||||||
userPubkey: string
|
|
||||||
): Promise<MessageStore | undefined> {
|
|
||||||
try {
|
|
||||||
const db = await openDatabase();
|
|
||||||
const data = await db.get(STORE_NAME, userPubkey);
|
|
||||||
|
|
||||||
if (!data) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
return data as MessageStore;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[MessageStore] Error reading from IndexedDB:', error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Delete messages from IndexedDB for a specific user
|
|
||||||
*/
|
|
||||||
export async function deleteMessagesFromDB(userPubkey: string): Promise<void> {
|
|
||||||
try {
|
|
||||||
const db = await openDatabase();
|
|
||||||
await db.delete(STORE_NAME, userPubkey);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[MessageStore] Error deleting from IndexedDB:', error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Clear all messages from IndexedDB
|
|
||||||
*/
|
|
||||||
export async function clearAllMessages(): Promise<void> {
|
|
||||||
try {
|
|
||||||
const db = await openDatabase();
|
|
||||||
await db.clear(STORE_NAME);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[MessageStore] Error clearing IndexedDB:', error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
import type { NostrEvent } from '@nostrify/nostrify';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validate that an event is a proper DM event
|
|
||||||
*/
|
|
||||||
export function validateDMEvent(event: NostrEvent): boolean {
|
|
||||||
// Must be kind 4 (NIP-04 DM)
|
|
||||||
if (event.kind !== 4) return false;
|
|
||||||
|
|
||||||
// Must have a 'p' tag
|
|
||||||
const hasRecipient = event.tags?.some(([name]) => name === 'p');
|
|
||||||
if (!hasRecipient) return false;
|
|
||||||
|
|
||||||
// Must have content (even if encrypted)
|
|
||||||
if (!event.content) return false;
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the recipient pubkey from a DM event
|
|
||||||
*/
|
|
||||||
export function getRecipientPubkey(event: NostrEvent): string | undefined {
|
|
||||||
return event.tags?.find(([name]) => name === 'p')?.[1];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the conversation partner pubkey from a DM event
|
|
||||||
* (the other person in the conversation, not the current user)
|
|
||||||
*/
|
|
||||||
export function getConversationPartner(event: NostrEvent, userPubkey: string): string | undefined {
|
|
||||||
const isFromUser = event.pubkey === userPubkey;
|
|
||||||
|
|
||||||
if (isFromUser) {
|
|
||||||
// If we sent it, the partner is the recipient
|
|
||||||
return getRecipientPubkey(event);
|
|
||||||
} else {
|
|
||||||
// If they sent it, the partner is the author
|
|
||||||
return event.pubkey;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Format timestamp for display (matches Signal/WhatsApp/Telegram pattern)
|
|
||||||
* Today: Show time (e.g., "2:45 PM")
|
|
||||||
* Yesterday: "Yesterday"
|
|
||||||
* This week: Day name (e.g., "Mon")
|
|
||||||
* This year: Month and day (e.g., "Jan 15")
|
|
||||||
* Older: Full date (e.g., "Jan 15, 2024")
|
|
||||||
*/
|
|
||||||
export function formatConversationTime(timestamp: number): string {
|
|
||||||
const date = new Date(timestamp * 1000);
|
|
||||||
const now = new Date();
|
|
||||||
|
|
||||||
// Start of today (midnight)
|
|
||||||
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
|
||||||
|
|
||||||
// Start of yesterday
|
|
||||||
const yesterdayStart = new Date(todayStart);
|
|
||||||
yesterdayStart.setDate(yesterdayStart.getDate() - 1);
|
|
||||||
|
|
||||||
// Start of this week (assuming week starts on Sunday, adjust if needed)
|
|
||||||
const weekStart = new Date(todayStart);
|
|
||||||
weekStart.setDate(weekStart.getDate() - weekStart.getDay());
|
|
||||||
|
|
||||||
if (date >= todayStart) {
|
|
||||||
// Today: Show time (e.g., "2:45 PM")
|
|
||||||
return date.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
|
|
||||||
} else if (date >= yesterdayStart) {
|
|
||||||
// Yesterday
|
|
||||||
return 'Yesterday';
|
|
||||||
} else if (date >= weekStart) {
|
|
||||||
// This week: Show day name (e.g., "Monday")
|
|
||||||
return date.toLocaleDateString(undefined, { weekday: 'short' });
|
|
||||||
} else if (date.getFullYear() === now.getFullYear()) {
|
|
||||||
// This year: Show month and day (e.g., "Jan 15")
|
|
||||||
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
|
|
||||||
} else {
|
|
||||||
// Older: Show full date (e.g., "Jan 15, 2024")
|
|
||||||
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Format timestamp as full date and time for tooltips
|
|
||||||
* e.g., "Mon, Jan 15, 2024, 2:45 PM"
|
|
||||||
*/
|
|
||||||
export function formatFullDateTime(timestamp: number): string {
|
|
||||||
const date = new Date(timestamp * 1000);
|
|
||||||
return date.toLocaleString(undefined, {
|
|
||||||
weekday: 'short',
|
|
||||||
year: 'numeric',
|
|
||||||
month: 'short',
|
|
||||||
day: 'numeric',
|
|
||||||
hour: 'numeric',
|
|
||||||
minute: '2-digit'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { translateToGnomeSpeak, shouldTranslateToGnomeSpeak } from './gnomeSpeak';
|
||||||
|
|
||||||
|
describe('gnomeSpeak', () => {
|
||||||
|
describe('shouldTranslateToGnomeSpeak', () => {
|
||||||
|
it('returns true for kind 1 events', () => {
|
||||||
|
expect(shouldTranslateToGnomeSpeak(1)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns false for other event kinds', () => {
|
||||||
|
expect(shouldTranslateToGnomeSpeak(0)).toBe(false);
|
||||||
|
expect(shouldTranslateToGnomeSpeak(3)).toBe(false);
|
||||||
|
expect(shouldTranslateToGnomeSpeak(1111)).toBe(false);
|
||||||
|
expect(shouldTranslateToGnomeSpeak(30023)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('translateToGnomeSpeak', () => {
|
||||||
|
it('translates basic words to gnome speak', () => {
|
||||||
|
const result = translateToGnomeSpeak('Hello world! This is good.');
|
||||||
|
expect(result).toContain('Greetings, fellow');
|
||||||
|
expect(result).toContain('splendid as');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves URLs during translation', () => {
|
||||||
|
const result = translateToGnomeSpeak('Check out https://example.com for good info');
|
||||||
|
expect(result).toMatch(/https:\/\/example/);
|
||||||
|
expect(result).toContain('splendid as');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves nostr references during translation', () => {
|
||||||
|
const result = translateToGnomeSpeak('Follow nostr:npub1zg69v7ys40x77y352eufp27daufrg4ncjz4ummcjx3t83y9tehhsqepuh0 for good content');
|
||||||
|
expect(result).toContain('nostr:npub1zg69v7ys40x77y352eufp27daufrg4ncjz4ummcjx3t83y9tehhsqepuh0');
|
||||||
|
expect(result).toContain('splendid as');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves hashtags during translation', () => {
|
||||||
|
const result = translateToGnomeSpeak('This is about #nostr and #bitcoin development');
|
||||||
|
expect(result).toContain('#nostr');
|
||||||
|
expect(result).toContain('#bitcoin');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('adds gnome-specific formatting for special terms', () => {
|
||||||
|
const result = translateToGnomeSpeak('I love bitcoin and gm everyone!');
|
||||||
|
expect(result).toContain('golden acorns of the digital realm');
|
||||||
|
expect(result).toContain('🌅when dew kisses the earth🌅');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles empty or invalid input', () => {
|
||||||
|
expect(translateToGnomeSpeak('')).toBe('');
|
||||||
|
expect(translateToGnomeSpeak(null as unknown as string)).toBe(null);
|
||||||
|
expect(translateToGnomeSpeak(undefined as unknown as string)).toBe(undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('capitalizes sentences properly', () => {
|
||||||
|
const result = translateToGnomeSpeak('hello world. this is good.');
|
||||||
|
expect(result).toMatch(/^[A-Z]/); // Should start with capital letter
|
||||||
|
expect(result).toMatch(/\. [A-Z]/); // Should capitalize after periods
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,923 @@
|
|||||||
|
/**
|
||||||
|
* Gnome Speak Translator
|
||||||
|
* Transforms regular text into whimsical gnome language
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Common gnome words and phrases
|
||||||
|
const gnomeVocabulary: Record<string, string> = {
|
||||||
|
// Greetings and expressions
|
||||||
|
'hello': 'greetings, fellow earth-dweller',
|
||||||
|
'hi': 'huzzah',
|
||||||
|
'hey': 'ho there',
|
||||||
|
'howdy': 'well met, forest-friend',
|
||||||
|
'welcome': 'blessed be your arrival',
|
||||||
|
'goodbye': 'may your mushrooms grow tall',
|
||||||
|
'bye': 'farewell, friend of the forest',
|
||||||
|
'farewell': 'until the paths cross again',
|
||||||
|
'thanks': 'blessings of the garden upon you',
|
||||||
|
'thank you': 'may the roots remember your kindness',
|
||||||
|
'please': 'if it pleases the woodland spirits',
|
||||||
|
'sorry': 'forgive this humble gnome',
|
||||||
|
'excuse me': 'pardon this forest-dweller',
|
||||||
|
'yes': 'aye, by my pointy hat',
|
||||||
|
'yeah': 'indeed, forest-friend',
|
||||||
|
'yep': 'certainly, woodland-companion',
|
||||||
|
'absolutely': 'as sure as ancient-oaks',
|
||||||
|
'definitely': 'certain as sunrise',
|
||||||
|
'certainly': 'without doubt, earth-friend',
|
||||||
|
'sure': 'as reliable as mountain-stones',
|
||||||
|
'no': 'nay, not even for all the acorns in the forest',
|
||||||
|
'nope': 'negative, forest-friend',
|
||||||
|
'never': 'not in a thousand-seasons',
|
||||||
|
'maybe': 'perhaps, if the mushrooms align',
|
||||||
|
'perhaps': 'possibly, when stars-align',
|
||||||
|
'possibly': 'might be, if spirits-will',
|
||||||
|
'probably': 'likely as autumn-leaves-falling',
|
||||||
|
'ok': 'very well, tiny friend',
|
||||||
|
'okay': 'indeed, little earth-dweller',
|
||||||
|
'alright': 'acceptable to forest-council',
|
||||||
|
'fine': 'satisfactory as spring-weather',
|
||||||
|
'wow': 'by the ancient-spirits',
|
||||||
|
'whoa': 'sacred mushrooms preserve-us',
|
||||||
|
'oh': 'woodland-spirits witness',
|
||||||
|
'oops': 'clumsy as startled-squirrels',
|
||||||
|
'darn': 'cursed as wilted-flowers',
|
||||||
|
|
||||||
|
// Common descriptive words
|
||||||
|
'good': 'splendid as morning dew',
|
||||||
|
'great': 'magnificent as ancient oak',
|
||||||
|
'awesome': 'wondrous as fairy rings',
|
||||||
|
'amazing': 'astounding as dragon sightings',
|
||||||
|
'incredible': 'miraculous as talking trees',
|
||||||
|
'wonderful': 'marvelous as rainbow bridges',
|
||||||
|
'excellent': 'superb as crystal caves',
|
||||||
|
'fantastic': 'enchanting as unicorn meadows',
|
||||||
|
'perfect': 'flawless as crystal dewdrops',
|
||||||
|
'beautiful': 'lovely as blooming flowers',
|
||||||
|
'pretty': 'charming as flower petals',
|
||||||
|
'gorgeous': 'stunning as sunset glades',
|
||||||
|
'handsome': 'dashing as noble stags',
|
||||||
|
'nice': 'pleasant as garden breeze',
|
||||||
|
'sweet': 'endearing as honey-flavored-words',
|
||||||
|
'cool': 'refreshing as spring water',
|
||||||
|
'hot': 'blazing as dragon breath',
|
||||||
|
'warm': 'cozy as hearth embers',
|
||||||
|
'cold': 'frigid as mountain peaks',
|
||||||
|
'bad': 'cursed as wilted leaves',
|
||||||
|
'terrible': 'dreadful as goblin raids',
|
||||||
|
'horrible': 'ghastly as poisoned wells',
|
||||||
|
'awful': 'abysmal as barren wastelands',
|
||||||
|
'ugly': 'unsightly as rotting stumps',
|
||||||
|
'hideous': 'repulsive as swamp creatures',
|
||||||
|
'disgusting': 'revolting as rotten-smell-smellers',
|
||||||
|
'gross': 'sickening as filth-encountering',
|
||||||
|
'big': 'enormous as giant toadstools',
|
||||||
|
'large': 'vast as forest clearings',
|
||||||
|
'huge': 'colossal as mountain trolls',
|
||||||
|
'massive': 'immense as ancient trees',
|
||||||
|
'giant': 'titanic as elder dragons',
|
||||||
|
'small': 'tiny as acorn caps',
|
||||||
|
'little': 'wee as dewdrops',
|
||||||
|
'tiny': 'minuscule as fairy footprints',
|
||||||
|
'miniature': 'pocket-sized as gnome homes',
|
||||||
|
'fast': 'swift as woodland sprites',
|
||||||
|
'quick': 'rapid as darting squirrels',
|
||||||
|
'speedy': 'fleet as racing rabbits',
|
||||||
|
'slow': 'leisurely as growing moss',
|
||||||
|
'sluggish': 'plodding as sleepy bears',
|
||||||
|
'new': 'fresh as spring shoots',
|
||||||
|
'old': 'ancient as elder trees',
|
||||||
|
'young': 'youthful as new growth',
|
||||||
|
'fresh': 'crisp as dawn air',
|
||||||
|
'stale': 'aged as ancient crumbs',
|
||||||
|
'clean': 'pure as mountain springs',
|
||||||
|
'dirty': 'soiled as muddy paths',
|
||||||
|
'rich': 'wealthy as treasure hoards',
|
||||||
|
'poor': 'humble as simple folk',
|
||||||
|
'expensive': 'costly as rare gems',
|
||||||
|
'cheap': 'affordable as common stones',
|
||||||
|
'free': 'unbound as forest winds',
|
||||||
|
'easy': 'simple as breathing air',
|
||||||
|
'difficult': 'challenging as mountain climbing',
|
||||||
|
'hard': 'tough as ancient bark',
|
||||||
|
'soft': 'gentle as rabbit fur',
|
||||||
|
'strong': 'mighty as bear strength',
|
||||||
|
'weak': 'frail as spider silk',
|
||||||
|
'heavy': 'weighty as boulder loads',
|
||||||
|
'light': 'airy as dandelion fluff',
|
||||||
|
'dark': 'shadowy as deep cave',
|
||||||
|
'bright': 'radiant as summer sun',
|
||||||
|
'loud': 'noisy as thunder crashes',
|
||||||
|
'quiet': 'silent as falling snow',
|
||||||
|
'busy': 'active as worker ants',
|
||||||
|
'lazy': 'idle as sunbathing cats',
|
||||||
|
'tired': 'weary as day\'s end',
|
||||||
|
'awake': 'alert as watchful owls',
|
||||||
|
'alive': 'living with forest vitality',
|
||||||
|
'dead': 'lifeless as fallen logs',
|
||||||
|
'healthy': 'robust as oak trees',
|
||||||
|
'sick': 'ailing like withered plants',
|
||||||
|
'safe': 'secure as burrow homes',
|
||||||
|
'dangerous': 'perilous as cliff edges',
|
||||||
|
'careful': 'cautious as deer at streams',
|
||||||
|
'careless': 'reckless as storm winds',
|
||||||
|
'smart': 'clever as cunning foxes',
|
||||||
|
'stupid': 'mindlessly as senseless acts',
|
||||||
|
'wise': 'sage as ancient owls',
|
||||||
|
'foolish': 'unwise as reckless youth',
|
||||||
|
'funny': 'amusing as playful otters',
|
||||||
|
'serious': 'grave as solemn ceremonies',
|
||||||
|
'strange': 'odd as two-headed mushrooms',
|
||||||
|
'normal': 'ordinary as daily sunrise',
|
||||||
|
'special': 'unique as snowflake patterns',
|
||||||
|
'different': 'distinct as individual leaves',
|
||||||
|
'same': 'identical as twin acorns',
|
||||||
|
'similar': 'alike as sister streams',
|
||||||
|
'equal': 'equivalent as balanced scales',
|
||||||
|
'fair': 'just as forest law',
|
||||||
|
'unfair': 'unjust as stolen honey',
|
||||||
|
'true': 'accurate as gnome-wisdom',
|
||||||
|
'false': 'untrue as winter promises',
|
||||||
|
'right': 'correct as compass needles',
|
||||||
|
'wrong': 'mistaken as lost travelers',
|
||||||
|
'correct': 'proper as forest protocol',
|
||||||
|
'important': 'significant as ancient laws',
|
||||||
|
'interesting': 'fascinating as rare discoveries',
|
||||||
|
'boring': 'dull as watching grass grow',
|
||||||
|
'fun': 'enjoyable as harvest festivals',
|
||||||
|
'lucky': 'fortunate as four-leaf clovers',
|
||||||
|
'unlucky': 'cursed as broken mirrors',
|
||||||
|
'successful': 'triumphant as victorious warriors',
|
||||||
|
'popular': 'beloved as festival leaders',
|
||||||
|
'famous': 'renowned as legendary heroes',
|
||||||
|
'unknown': 'mysterious as hidden valleys',
|
||||||
|
|
||||||
|
// Emotions and feelings
|
||||||
|
'happy': 'merry as spring festivals',
|
||||||
|
'joyful': 'gleeful as dancing pixies',
|
||||||
|
'cheerful': 'bright as sunny meadows',
|
||||||
|
'excited': 'thrilled as treasure hunters',
|
||||||
|
'delighted': 'pleased as successful gardeners',
|
||||||
|
'ecstatic': 'overjoyed as festival winners',
|
||||||
|
'elated': 'uplifted as soaring-eagles',
|
||||||
|
'content': 'satisfied as well-fed-bears',
|
||||||
|
'pleased': 'gratified as successful-gardeners',
|
||||||
|
'glad': 'happy as singing-birds',
|
||||||
|
'relieved': 'unburdened as dropped-heavy-packs',
|
||||||
|
'grateful': 'thankful as rain-blessed-crops',
|
||||||
|
'proud': 'dignified as royal stags',
|
||||||
|
'confident': 'assured as mountain peaks',
|
||||||
|
'brave': 'courageous as warrior bears',
|
||||||
|
'bold': 'daring as cliff-climbing-goats',
|
||||||
|
'calm': 'peaceful as still ponds',
|
||||||
|
'relaxed': 'at-ease as sunbathing-cats',
|
||||||
|
'peaceful': 'tranquil as morning-meadows',
|
||||||
|
'sad': 'melancholy as autumn rain',
|
||||||
|
'unhappy': 'sorrowful as wilting flowers',
|
||||||
|
'depressed': 'gloomy as storm clouds',
|
||||||
|
'miserable': 'wretched as lost wanderers',
|
||||||
|
'heartbroken': 'shattered as fallen-bird-eggs',
|
||||||
|
'lonely': 'isolated as single-trees',
|
||||||
|
'hurt': 'wounded as thorn-pricked-paws',
|
||||||
|
'angry': 'wrathful as disturbed badgers',
|
||||||
|
'mad': 'furious as territorial bears',
|
||||||
|
'furious': 'enraged as protective mothers',
|
||||||
|
'annoyed': 'vexed as pestered squirrels',
|
||||||
|
'irritated': 'bothered as interrupted naps',
|
||||||
|
'frustrated': 'blocked like dammed-streams',
|
||||||
|
'afraid': 'fearful as startled mice',
|
||||||
|
'scared': 'frightened as hunted-rabbits',
|
||||||
|
'terrified': 'petrified as stone-statues',
|
||||||
|
'nervous': 'jittery as caffeine-buzzed-squirrels',
|
||||||
|
'worried': 'concerned as protective-parents',
|
||||||
|
'anxious': 'worried as storm-watching-sailors',
|
||||||
|
'surprised': 'astonished as sudden storms',
|
||||||
|
'shocked': 'stunned as lightning-struck-trees',
|
||||||
|
'amazed': 'astounded as miracle-witnesses',
|
||||||
|
'confused': 'puzzled as riddle-hearers',
|
||||||
|
'lost': 'directionless as pathless-wanderers',
|
||||||
|
'curious': 'inquisitive as exploring-kittens',
|
||||||
|
'interested': 'engaged as story-listeners',
|
||||||
|
'bored': 'uninterested as sleepy-sloths',
|
||||||
|
'jealous': 'envious as covetous-dragons',
|
||||||
|
'envious': 'resentful as have-nots',
|
||||||
|
'greedy': 'grasping as hoarding-squirrels',
|
||||||
|
'selfish': 'self-centered as narcissistic-peacocks',
|
||||||
|
'generous': 'giving as abundant-fruit-trees',
|
||||||
|
'kind': 'gentle as mother\'s touch',
|
||||||
|
'mean': 'nasty as stinging-nettles',
|
||||||
|
'cruel': 'harsh as winter-storms',
|
||||||
|
'embarrassed': 'ashamed as public-mistake-makers',
|
||||||
|
'guilty': 'remorseful as wrongdoing-confessors',
|
||||||
|
'ashamed': 'dishonored as oath-breakers',
|
||||||
|
|
||||||
|
// Actions and verbs
|
||||||
|
'go': 'venture forth',
|
||||||
|
'come': 'approach the sacred circle',
|
||||||
|
'see': 'witness with gnome-eyes',
|
||||||
|
'look': 'gaze upon',
|
||||||
|
'watch': 'observe like sentinel-owls',
|
||||||
|
'listen': 'hear the whispers of the wind',
|
||||||
|
'hear': 'perceive with gnome-ears',
|
||||||
|
'speak': 'utter in ancient dialect',
|
||||||
|
'talk': 'speak in the ancient tongue',
|
||||||
|
'say': 'declare to forest council',
|
||||||
|
'tell': 'relate tales by firelight',
|
||||||
|
'ask': 'inquire of the wise ones',
|
||||||
|
'answer': 'respond with woodland-wisdom',
|
||||||
|
'think': 'ponder in the mushroom circle',
|
||||||
|
'know': 'hold wisdom in thy cap',
|
||||||
|
'learn': 'gather knowledge like berries',
|
||||||
|
'teach': 'share wisdom of the ancients',
|
||||||
|
'understand': 'comprehend with woodland wisdom',
|
||||||
|
'remember': 'recall from memory-moss',
|
||||||
|
'forget': 'lose to the mists of time',
|
||||||
|
'believe': 'trust in forest magic',
|
||||||
|
'hope': 'wish upon evening stars',
|
||||||
|
'feel': 'sense with gnome-heart',
|
||||||
|
'love': 'cherish like precious gems',
|
||||||
|
'like': 'fancy as favorite flowers',
|
||||||
|
'hate': 'despise like garden pests',
|
||||||
|
'want': 'desire like moths seek flame',
|
||||||
|
'need': 'require like flowers need rain',
|
||||||
|
'have': 'possess like territorial-bears',
|
||||||
|
'get': 'obtain through forest cunning',
|
||||||
|
'give': 'bestow gifts of the heart',
|
||||||
|
'take': 'gather like squirrels in autumn',
|
||||||
|
'put': 'place with gnomish care',
|
||||||
|
'make': 'craft with gnomish hands',
|
||||||
|
'do': 'perform with woodland-skill',
|
||||||
|
'work': 'toil in the earth',
|
||||||
|
'play': 'frolic like woodland creatures',
|
||||||
|
'help': 'lend aid to fellow forest-folk',
|
||||||
|
'try': 'attempt with gnomish determination',
|
||||||
|
'use': 'employ with woodland wisdom',
|
||||||
|
'find': 'discover hidden treasures',
|
||||||
|
'lose': 'misplace in the deep woods',
|
||||||
|
'keep': 'guard like dragon\'s treasure',
|
||||||
|
'save': 'preserve like squirrels save nuts',
|
||||||
|
'spend': 'use like autumn leaves falling',
|
||||||
|
'buy': 'trade for with shiny pebbles',
|
||||||
|
'sell': 'barter in the market grove',
|
||||||
|
'pay': 'offer tribute to forest spirits',
|
||||||
|
'win': 'triumph like mighty oak',
|
||||||
|
'start': 'begin the woodland journey',
|
||||||
|
'stop': 'halt like deer sensing danger',
|
||||||
|
'end': 'conclude like sunset',
|
||||||
|
'finish': 'complete like harvest-gathering',
|
||||||
|
'begin': 'commence the forest-quest',
|
||||||
|
'continue': 'proceed along woodland-path',
|
||||||
|
'change': 'transform like caterpillars',
|
||||||
|
'move': 'shift like dancing leaves',
|
||||||
|
'stay': 'remain rooted like ancient trees',
|
||||||
|
'leave': 'depart on woodland winds',
|
||||||
|
'return': 'come back to the sacred grove',
|
||||||
|
'arrive': 'reach journey\'s end',
|
||||||
|
'travel': 'journey through wild lands',
|
||||||
|
'visit': 'call upon forest friends',
|
||||||
|
'meet': 'encounter on woodland paths',
|
||||||
|
'follow': 'walk the same forest path',
|
||||||
|
'lead': 'guide like wise elders',
|
||||||
|
'run': 'scamper through the underbrush',
|
||||||
|
'walk': 'stroll the forest paths',
|
||||||
|
'sit': 'perch upon mushroom throne',
|
||||||
|
'stand': 'rise like proud saplings',
|
||||||
|
'sleep': 'rest in the embrace of moss',
|
||||||
|
'wake': 'greet the morning sun',
|
||||||
|
'eat': 'partake of nature\'s gifts',
|
||||||
|
'drink': 'sip the sacred waters',
|
||||||
|
'cook': 'prepare over gnome-fires',
|
||||||
|
'read': 'decipher the runes of knowledge',
|
||||||
|
'write': 'inscribe upon bark and stone',
|
||||||
|
'build': 'construct like industrious beavers',
|
||||||
|
'break': 'shatter like brittle ice',
|
||||||
|
'fix': 'mend with gnomish skill',
|
||||||
|
'open': 'unseal like blooming flowers',
|
||||||
|
'close': 'shut like evening blossoms',
|
||||||
|
'turn': 'rotate like seasons changing',
|
||||||
|
'carry': 'bear like pack mules',
|
||||||
|
'hold': 'grasp with gnomish grip',
|
||||||
|
'throw': 'hurl like catapult stones',
|
||||||
|
'catch': 'capture like spider webs',
|
||||||
|
'send': 'dispatch like messenger birds',
|
||||||
|
'bring': 'carry like busy ants',
|
||||||
|
'show': 'reveal like dawn breaking',
|
||||||
|
'hide': 'conceal in forest-shadows',
|
||||||
|
'wait': 'pause like patient stones',
|
||||||
|
'hurry': 'rush like urgent-messengers',
|
||||||
|
'choose': 'select like wise owls',
|
||||||
|
'decide': 'determine by mushroom council',
|
||||||
|
'plan': 'scheme like clever foxes',
|
||||||
|
'create': 'birth from gnomish imagination',
|
||||||
|
'destroy': 'unmake like winter storms',
|
||||||
|
'grow': 'flourish like spring gardens',
|
||||||
|
'die': 'return to the eternal soil',
|
||||||
|
'live': 'dwell in harmony with nature',
|
||||||
|
'happen': 'occur by woodland chance',
|
||||||
|
'seem': 'appear like morning mist',
|
||||||
|
'become': 'transform into',
|
||||||
|
'remain': 'stay like enduring-stones',
|
||||||
|
'appear': 'manifest like forest-spirits',
|
||||||
|
'disappear': 'vanish like morning-mist',
|
||||||
|
'exist': 'be present in forest-realm',
|
||||||
|
'matter': 'be important as ancient oaks',
|
||||||
|
'care': 'tend like garden keeper',
|
||||||
|
'worry': 'fret like anxious rabbits',
|
||||||
|
'call': 'summon with woodland voice',
|
||||||
|
'let': 'allow the forest spirits',
|
||||||
|
'allow': 'permit by gnomish law',
|
||||||
|
'join': 'unite like flowing streams',
|
||||||
|
'share': 'spread like dandelion seeds',
|
||||||
|
'agree': 'harmonize like bird songs',
|
||||||
|
'disagree': 'clash like thunder storms',
|
||||||
|
'fight': 'battle like fierce badgers',
|
||||||
|
'argue': 'quarrel like territorial squirrels',
|
||||||
|
'discuss': 'debate in council circles',
|
||||||
|
'explain': 'clarify like morning light',
|
||||||
|
'describe': 'paint word-pictures',
|
||||||
|
'compare': 'measure against ancient standards',
|
||||||
|
'include': 'embrace within the circle',
|
||||||
|
'exclude': 'banish from sacred-grove',
|
||||||
|
'add': 'include like gathering-berries',
|
||||||
|
'remove': 'extract like pulling-weeds',
|
||||||
|
'increase': 'grow like expanding-trees',
|
||||||
|
'decrease': 'shrink like autumn-leaves',
|
||||||
|
'improve': 'enhance like garden-tending',
|
||||||
|
'develop': 'cultivate like patient farmers',
|
||||||
|
'manage': 'oversee like head gardener',
|
||||||
|
'control': 'command like forest kings',
|
||||||
|
'organize': 'arrange like busy bees',
|
||||||
|
'prepare': 'ready like winter-preparations',
|
||||||
|
'provide': 'supply from nature\'s storehouse',
|
||||||
|
'offer': 'present like gift-bearing visitors',
|
||||||
|
'accept': 'receive with grateful heart',
|
||||||
|
'refuse': 'decline like stubborn-mules',
|
||||||
|
'reject': 'spurn like bitter-berries',
|
||||||
|
'receive': 'welcome like spring rain',
|
||||||
|
'support': 'uphold like sturdy roots',
|
||||||
|
'oppose': 'resist like stubborn stones',
|
||||||
|
'protect': 'shield like mother bears',
|
||||||
|
'attack': 'assault like angry wasps',
|
||||||
|
'defend': 'guard like loyal hounds',
|
||||||
|
'escape': 'flee like startled rabbits',
|
||||||
|
'avoid': 'evade like nimble deer',
|
||||||
|
'reach': 'extend like growing vines',
|
||||||
|
'touch': 'contact with gentle-paws',
|
||||||
|
'push': 'shove like rolling boulders',
|
||||||
|
'pull': 'draw like flowing streams',
|
||||||
|
'lift': 'raise like morning mist',
|
||||||
|
'drop': 'release like autumn leaves',
|
||||||
|
'pick': 'select like berry gatherers',
|
||||||
|
'enter': 'cross the sacred threshold',
|
||||||
|
'exit': 'depart through hidden doors',
|
||||||
|
'pass': 'traverse like mountain paths',
|
||||||
|
'cross': 'bridge like fallen-logs',
|
||||||
|
'climb': 'ascend like squirrel-acrobats',
|
||||||
|
'jump': 'leap like bounding-deer',
|
||||||
|
'fall': 'tumble like rolling-acorns',
|
||||||
|
'swim': 'glide like graceful-fish',
|
||||||
|
'dance': 'move like wind-blown-leaves',
|
||||||
|
'sing': 'vocalize like morning-birds',
|
||||||
|
'laugh': 'chortle like amused-gnomes',
|
||||||
|
'cry': 'weep like rain-clouds',
|
||||||
|
'smile': 'grin like happy-sunflowers',
|
||||||
|
'frown': 'scowl like storm-clouds',
|
||||||
|
|
||||||
|
// Technology terms (gnome-ified)
|
||||||
|
'computer': 'thinking-box of metal and magic',
|
||||||
|
'laptop': 'portable wisdom-chest',
|
||||||
|
'phone': 'speaking-crystal',
|
||||||
|
'smartphone': 'clever communication-gem',
|
||||||
|
'internet': 'the great web of knowledge',
|
||||||
|
'website': 'digital mushroom ring',
|
||||||
|
'email': 'letter-sprite delivery',
|
||||||
|
'password': 'secret gnome-word',
|
||||||
|
'app': 'magical tool-sprite',
|
||||||
|
'software': 'spell-weaving programs',
|
||||||
|
'program': 'coded spell-sequence',
|
||||||
|
'code': 'mystical rune-writing',
|
||||||
|
'bug': 'mischievous code-gremlin',
|
||||||
|
'update': 'spell-enhancement ritual',
|
||||||
|
'download': 'summon from the ether',
|
||||||
|
'upload': 'send to the cloud-spirits',
|
||||||
|
'file': 'digital scroll-bundle',
|
||||||
|
'delete': 'banish to the void',
|
||||||
|
'bitcoin': 'golden acorns of the digital realm',
|
||||||
|
'crypto': 'mystical coin-magic',
|
||||||
|
'blockchain': 'the eternal ledger of the earth spirits',
|
||||||
|
'nostr': 'the sacred network of gnome-kind',
|
||||||
|
'relay': 'message-mushroom',
|
||||||
|
'post': 'woodland proclamation',
|
||||||
|
'message': 'whisper carried by wind',
|
||||||
|
'chat': 'friendly forest-chatter',
|
||||||
|
'comment': 'thoughtful tree-response',
|
||||||
|
'reply': 'echo from the grove',
|
||||||
|
'mention': 'call by woodland-name',
|
||||||
|
'tag': 'forest-marker label',
|
||||||
|
'hashtag': 'topic-gathering symbol',
|
||||||
|
'follower': 'path-walking companion',
|
||||||
|
'friend': 'woodland-path companion',
|
||||||
|
'user': 'forest-path wanderer',
|
||||||
|
'account': 'woodland-identity record',
|
||||||
|
'profile': 'forest-dweller description',
|
||||||
|
'avatar': 'spirit-image representation',
|
||||||
|
'feed': 'stream of woodland-news',
|
||||||
|
'trending': 'popular as festival-topics',
|
||||||
|
'viral': 'spreading like wildfire-news',
|
||||||
|
|
||||||
|
// Time and nature
|
||||||
|
'today': 'this blessed sun-cycle',
|
||||||
|
'tomorrow': 'the next dawn',
|
||||||
|
'yesterday': 'the previous twilight',
|
||||||
|
'now': 'this very forest-moment',
|
||||||
|
'soon': 'before the next acorn-fall',
|
||||||
|
'later': 'after the sun-shift',
|
||||||
|
'early': 'with the first bird-songs',
|
||||||
|
'late': 'when shadows grow long',
|
||||||
|
'morning': 'when dew kisses the earth',
|
||||||
|
'afternoon': 'when sun reaches tree-tops',
|
||||||
|
'evening': 'when fireflies dance',
|
||||||
|
'night': 'when the moon watches over',
|
||||||
|
'day': 'sun-blessed time',
|
||||||
|
'week': 'seven turnings of the earth',
|
||||||
|
'month': 'one moon-cycle',
|
||||||
|
'year': 'full journey round the sun',
|
||||||
|
'time': 'the eternal forest-flow',
|
||||||
|
'moment': 'brief woodland-instant',
|
||||||
|
'hour': 'sun-shadow measurement',
|
||||||
|
'minute': 'tiny time-fragment',
|
||||||
|
'second': 'heartbeat-duration',
|
||||||
|
'season': 'nature\'s changing-mood',
|
||||||
|
'spring': 'time of awakening-growth',
|
||||||
|
'summer': 'season of abundant-warmth',
|
||||||
|
'autumn': 'harvest of golden-leaves',
|
||||||
|
'winter': 'the great forest-slumber',
|
||||||
|
'weather': 'sky-spirit\'s current-mood',
|
||||||
|
'rain': 'sky-tears blessing the earth',
|
||||||
|
'snow': 'winter\'s white forest-blanket',
|
||||||
|
'sun': 'the great golden-eye',
|
||||||
|
'moon': 'night\'s silver-guardian',
|
||||||
|
'stars': 'celestial navigation-gems',
|
||||||
|
'sky': 'the endless blue-canopy',
|
||||||
|
'cloud': 'sky-spirit\'s fluffy-messenger',
|
||||||
|
'wind': 'breath of the forest-spirits',
|
||||||
|
'storm': 'sky-spirits\' angry-dance',
|
||||||
|
'thunder': 'voice of the cloud-giants',
|
||||||
|
'lightning': 'sky-fire\'s brilliant-flash',
|
||||||
|
'rainbow': 'bridge between earth and sky',
|
||||||
|
'nature': 'the great mother-spirit',
|
||||||
|
'earth': 'our beloved soil-mother',
|
||||||
|
'world': 'the vast forest-realm',
|
||||||
|
'ground': 'the solid earth-foundation',
|
||||||
|
'soil': 'the life-giving dirt-magic',
|
||||||
|
'rock': 'earth\'s ancient bone-structure',
|
||||||
|
'stone': 'small piece of mountain-heart',
|
||||||
|
'mountain': 'earth\'s reaching-toward-sky',
|
||||||
|
'hill': 'gentle earth-rise',
|
||||||
|
'valley': 'earth\'s peaceful-embrace',
|
||||||
|
'forest': 'the sacred tree-gathering',
|
||||||
|
'tree': 'earth\'s reaching-toward-light',
|
||||||
|
'branch': 'tree\'s extending-arm',
|
||||||
|
'leaf': 'tree\'s breathing-surface',
|
||||||
|
'root': 'tree\'s earth-drinking-finger',
|
||||||
|
'flower': 'plant\'s colorful-celebration',
|
||||||
|
'grass': 'earth\'s green-carpet',
|
||||||
|
'plant': 'earth\'s growing-child',
|
||||||
|
'garden': 'tended plant-paradise',
|
||||||
|
'water': 'life-giving crystal liquid',
|
||||||
|
'river': 'flowing water-pathway',
|
||||||
|
'lake': 'earth\'s water-mirror',
|
||||||
|
'ocean': 'vast water-wilderness',
|
||||||
|
'fire': 'dancing heat-spirit',
|
||||||
|
'flame': 'fire\'s reaching-tongue',
|
||||||
|
'smoke': 'fire\'s gray-breath',
|
||||||
|
'wood': 'tree\'s gift-material',
|
||||||
|
'animal': 'forest-dwelling-creature',
|
||||||
|
'bird': 'sky-dancing-singer',
|
||||||
|
'fish': 'water-dwelling-swimmer',
|
||||||
|
'dog': 'loyal four-legged-friend',
|
||||||
|
'cat': 'independent whisker-hunter',
|
||||||
|
'horse': 'noble four-legged-runner',
|
||||||
|
'cow': 'gentle milk-giving-beast',
|
||||||
|
'pig': 'round mud-loving-creature',
|
||||||
|
'chicken': 'feathered egg-laying-bird',
|
||||||
|
'bear': 'mighty forest-guardian',
|
||||||
|
'wolf': 'pack-hunting-howler',
|
||||||
|
'deer': 'graceful forest-leaper',
|
||||||
|
'rabbit': 'quick-hopping-nibbler',
|
||||||
|
'squirrel': 'tree-climbing-nut-gatherer',
|
||||||
|
'mouse': 'tiny cheese-seeking-creature',
|
||||||
|
'rat': 'clever tunnel-dwelling-survivor',
|
||||||
|
'snake': 'slithering ground-crawler',
|
||||||
|
'spider': 'web-weaving-hunter',
|
||||||
|
'bee': 'buzzing honey-maker',
|
||||||
|
'butterfly': 'colorful flower-dancer',
|
||||||
|
'ant': 'industrious colony-worker',
|
||||||
|
'fly': 'annoying buzzing-pest',
|
||||||
|
'mosquito': 'blood-seeking-tiny-vampire',
|
||||||
|
'frog': 'pond-dwelling-croaker',
|
||||||
|
'turtle': 'shell-carrying-slow-walker',
|
||||||
|
'owl': 'wise night-hunting-watcher',
|
||||||
|
'eagle': 'majestic sky-soaring-hunter',
|
||||||
|
'dragon': 'legendary fire-breathing-beast',
|
||||||
|
'unicorn': 'mythical horn-bearing-horse',
|
||||||
|
'fairy': 'tiny magical-forest-sprite',
|
||||||
|
'elf': 'pointed-ear-woodland-dweller',
|
||||||
|
'dwarf': 'bearded mountain-tunnel-digger',
|
||||||
|
'wizard': 'spell-casting-wise-elder',
|
||||||
|
'witch': 'potion-brewing-magic-user',
|
||||||
|
'ghost': 'transparent spirit-being',
|
||||||
|
'monster': 'frightening creature-of-darkness',
|
||||||
|
|
||||||
|
// Food and sustenance
|
||||||
|
'food': 'earth\'s bounty',
|
||||||
|
'meal': 'feast of forest-gifts',
|
||||||
|
'breakfast': 'dawn\'s energy-awakening',
|
||||||
|
'lunch': 'midday sustenance-break',
|
||||||
|
'dinner': 'evening\'s nourishment-gathering',
|
||||||
|
'snack': 'small between-meal-nibble',
|
||||||
|
'hungry': 'craving earth\'s-nourishment',
|
||||||
|
'thirsty': 'needing liquid-refreshment',
|
||||||
|
'full': 'satisfied with belly-bounty',
|
||||||
|
'coffee': 'bitter bean brew',
|
||||||
|
'tea': 'leaf-water of wisdom',
|
||||||
|
'milk': 'cow\'s white-gift',
|
||||||
|
'juice': 'fruit\'s liquid-essence',
|
||||||
|
'beer': 'grain\'s fermented-celebration',
|
||||||
|
'wine': 'grape\'s aged-transformation',
|
||||||
|
'bread': 'grain-gift of the fields',
|
||||||
|
'cake': 'sweet celebration-tower',
|
||||||
|
'cookie': 'small sweet-disk',
|
||||||
|
'pizza': 'flat bread with toppings-garden',
|
||||||
|
'meat': 'animal\'s protein-gift',
|
||||||
|
'vegetable': 'earth\'s colorful-children',
|
||||||
|
'fruit': 'tree\'s sweet-offering',
|
||||||
|
'apple': 'red orb of crisp-sweetness',
|
||||||
|
'banana': 'yellow crescent-fruit',
|
||||||
|
'orange': 'citrus sun-sphere',
|
||||||
|
'cheese': 'milk\'s aged-transformation',
|
||||||
|
'egg': 'bird\'s oval-creation',
|
||||||
|
'honey': 'bee\'s golden-sweetness',
|
||||||
|
'sugar': 'cane\'s crystallized-sweetness',
|
||||||
|
'salt': 'sea\'s mineral-gift',
|
||||||
|
'spicy': 'fire-tongue-sensation',
|
||||||
|
'delicious': 'wonderfully tasty-pleasure',
|
||||||
|
'tasty': 'pleasing to tongue-senses',
|
||||||
|
'yummy': 'delightfully satisfying-flavor',
|
||||||
|
|
||||||
|
// People and relationships
|
||||||
|
'person': 'wanderer of the mortal realm',
|
||||||
|
'people': 'fellow earth-dwellers',
|
||||||
|
'human': 'tall-folk',
|
||||||
|
'man': 'bearded earth-walker',
|
||||||
|
'woman': 'graceful forest-daughter',
|
||||||
|
'child': 'young sprout',
|
||||||
|
'baby': 'tiny seedling',
|
||||||
|
'boy': 'male young-sprout',
|
||||||
|
'girl': 'female young-blossom',
|
||||||
|
'family': 'clan of the same burrow',
|
||||||
|
'mother': 'nurturing life-bringer',
|
||||||
|
'father': 'protecting life-provider',
|
||||||
|
'parent': 'life-giving-elder',
|
||||||
|
'son': 'male offspring-sprout',
|
||||||
|
'daughter': 'female offspring-blossom',
|
||||||
|
'brother': 'male sibling-companion',
|
||||||
|
'sister': 'female sibling-friend',
|
||||||
|
'husband': 'male life-bond-companion',
|
||||||
|
'wife': 'female life-bond-companion',
|
||||||
|
'boyfriend': 'courting male-companion',
|
||||||
|
'girlfriend': 'courting female-companion',
|
||||||
|
'neighbor': 'nearby-dwelling-friend',
|
||||||
|
'stranger': 'unknown path-crosser',
|
||||||
|
'teacher': 'wisdom-sharing-elder',
|
||||||
|
'student': 'knowledge-seeking-sprout',
|
||||||
|
'doctor': 'healing-arts-practitioner',
|
||||||
|
'worker': 'labor-providing-being',
|
||||||
|
'boss': 'work-directing-leader',
|
||||||
|
'leader': 'group-guiding-chief',
|
||||||
|
'team': 'cooperating-group-unit',
|
||||||
|
'group': 'gathered-together-collection',
|
||||||
|
'community': 'shared-dwelling-collective',
|
||||||
|
|
||||||
|
// Places and locations
|
||||||
|
'place': 'woodland-location',
|
||||||
|
'home': 'cozy burrow-dwelling',
|
||||||
|
'house': 'family nest-structure',
|
||||||
|
'building': 'tall human-construction',
|
||||||
|
'room': 'enclosed dwelling-space',
|
||||||
|
'kitchen': 'food-preparation-chamber',
|
||||||
|
'bedroom': 'sleeping-rest-sanctuary',
|
||||||
|
'bathroom': 'cleansing-water-room',
|
||||||
|
'office': 'work-task-chamber',
|
||||||
|
'school': 'learning-wisdom-hall',
|
||||||
|
'hospital': 'healing-treatment-center',
|
||||||
|
'store': 'goods-trading-establishment',
|
||||||
|
'restaurant': 'food-serving-hall',
|
||||||
|
'park': 'public green-space',
|
||||||
|
'street': 'paved pathway-for-travel',
|
||||||
|
'road': 'long travel-route',
|
||||||
|
'city': 'large human-settlement',
|
||||||
|
'town': 'medium human-gathering',
|
||||||
|
'village': 'small community-cluster',
|
||||||
|
'country': 'large territorial-region',
|
||||||
|
'state': 'governmental-territory-division',
|
||||||
|
'beach': 'sandy water-meeting-shore',
|
||||||
|
'island': 'water-surrounded-land',
|
||||||
|
'desert': 'dry sandy-wasteland',
|
||||||
|
'farm': 'food-growing-sanctuary',
|
||||||
|
'field': 'open earth-expanse',
|
||||||
|
'meadow': 'flower-filled-clearing',
|
||||||
|
|
||||||
|
// Objects and things
|
||||||
|
'thing': 'woodland-object',
|
||||||
|
'object': 'physical forest-item',
|
||||||
|
'item': 'individual possession-piece',
|
||||||
|
'stuff': 'various collected-objects',
|
||||||
|
'book': 'knowledge-filled-pages',
|
||||||
|
'paper': 'tree-pulp-writing-surface',
|
||||||
|
'pen': 'ink-flowing-writing-stick',
|
||||||
|
'pencil': 'graphite-marking-tool',
|
||||||
|
'car': 'metal traveling-box',
|
||||||
|
'bike': 'two-wheeled-pedal-machine',
|
||||||
|
'train': 'long track-riding-transport',
|
||||||
|
'plane': 'sky-flying-metal-bird',
|
||||||
|
'boat': 'water-floating-vessel',
|
||||||
|
'ship': 'large ocean-crossing-craft',
|
||||||
|
'chair': 'sitting-support-furniture',
|
||||||
|
'table': 'flat surface-for-placing',
|
||||||
|
'bed': 'sleeping-comfort-platform',
|
||||||
|
'door': 'entrance-barrier-portal',
|
||||||
|
'window': 'transparent wall-opening',
|
||||||
|
'wall': 'vertical room-boundary',
|
||||||
|
'floor': 'horizontal walking-surface',
|
||||||
|
'roof': 'overhead shelter-covering',
|
||||||
|
'box': 'storage-container-cube',
|
||||||
|
'bag': 'flexible carrying-container',
|
||||||
|
'bottle': 'liquid-holding-vessel',
|
||||||
|
'cup': 'small drinking-container',
|
||||||
|
'plate': 'flat food-serving-disk',
|
||||||
|
'knife': 'sharp cutting-blade',
|
||||||
|
'fork': 'pronged eating-tool',
|
||||||
|
'spoon': 'curved scooping-utensil',
|
||||||
|
'clothes': 'body-covering-garments',
|
||||||
|
'shirt': 'upper-body-covering',
|
||||||
|
'pants': 'leg-covering-garment',
|
||||||
|
'shoes': 'foot-protecting-coverings',
|
||||||
|
'hat': 'head-covering-accessory',
|
||||||
|
'ring': 'finger-circling-jewelry',
|
||||||
|
'key': 'lock-opening-metal-tool',
|
||||||
|
'money': 'trade-value-tokens',
|
||||||
|
'coin': 'small metal-currency-disk',
|
||||||
|
'card': 'flat rectangular-object',
|
||||||
|
'gift': 'present-offering-surprise',
|
||||||
|
'toy': 'play-entertainment-object',
|
||||||
|
'game': 'rule-based-fun-activity',
|
||||||
|
'ball': 'round bouncing-sphere',
|
||||||
|
'tool': 'work-assisting-implement',
|
||||||
|
'machine': 'mechanical working-device',
|
||||||
|
'camera': 'image-capturing-box',
|
||||||
|
'picture': 'visual-image-representation',
|
||||||
|
'photo': 'light-captured-moment',
|
||||||
|
'mirror': 'reflection-showing-surface',
|
||||||
|
'lamp': 'artificial light-provider',
|
||||||
|
'candle': 'wax flame-holder',
|
||||||
|
'ice': 'frozen solid-water',
|
||||||
|
'glass': 'transparent brittle-material',
|
||||||
|
'metal': 'hard shiny-material',
|
||||||
|
'plastic': 'synthetic flexible-material',
|
||||||
|
'rubber': 'bouncy stretchy-material',
|
||||||
|
'fabric': 'woven thread-material',
|
||||||
|
'leather': 'animal-hide-material',
|
||||||
|
'string': 'thin flexible-cord',
|
||||||
|
'rope': 'thick strong-cord',
|
||||||
|
'chain': 'linked metal-connections',
|
||||||
|
'wire': 'thin metal-strand',
|
||||||
|
'nail': 'sharp fastening-spike',
|
||||||
|
'screw': 'threaded fastening-rod',
|
||||||
|
'hammer': 'striking-force-tool',
|
||||||
|
'saw': 'cutting-teeth-tool',
|
||||||
|
'brush': 'bristled cleaning-tool',
|
||||||
|
'paint': 'color-coating-liquid',
|
||||||
|
'soap': 'cleaning-foam-substance',
|
||||||
|
'towel': 'drying-absorption-cloth',
|
||||||
|
'blanket': 'warmth-providing-cover',
|
||||||
|
'pillow': 'head-supporting-cushion',
|
||||||
|
'clock': 'time-displaying-device',
|
||||||
|
'calendar': 'date-organizing-chart',
|
||||||
|
'map': 'location-showing-guide',
|
||||||
|
'flag': 'symbolic cloth-banner',
|
||||||
|
'seed': 'plant\'s future-potential',
|
||||||
|
'stick': 'small wood-piece',
|
||||||
|
'shell': 'sea-creature\'s protective-home',
|
||||||
|
'feather': 'bird\'s flight-enabling-plume',
|
||||||
|
'bone': 'skeleton\'s structural-piece',
|
||||||
|
'fur': 'animal\'s warm-covering',
|
||||||
|
'scale': 'fish\'s protective-armor',
|
||||||
|
'horn': 'animal\'s pointed-growth',
|
||||||
|
'tail': 'animal\'s rear-appendage',
|
||||||
|
'wing': 'flight-enabling-appendage',
|
||||||
|
'claw': 'sharp grasping-nail',
|
||||||
|
'tooth': 'biting-chewing-bone',
|
||||||
|
'eye': 'vision-sensing-orb',
|
||||||
|
'ear': 'sound-detecting-organ',
|
||||||
|
'nose': 'smell-sensing-protrusion',
|
||||||
|
'mouth': 'eating-speaking-opening',
|
||||||
|
'hand': 'grasping-manipulation-appendage',
|
||||||
|
'finger': 'hand\'s flexible-digit',
|
||||||
|
'foot': 'walking-support-appendage',
|
||||||
|
'toe': 'foot\'s small-digit',
|
||||||
|
'head': 'thinking-sensing-sphere',
|
||||||
|
'hair': 'head\'s growing-strands',
|
||||||
|
'face': 'front-expression-surface',
|
||||||
|
'neck': 'head-connecting-column',
|
||||||
|
'shoulder': 'arm-connecting-joint',
|
||||||
|
'arm': 'reaching-grasping-limb',
|
||||||
|
'leg': 'walking-supporting-limb',
|
||||||
|
'knee': 'leg-bending-joint',
|
||||||
|
'chest': 'front-torso-area',
|
||||||
|
'stomach': 'food-digesting-organ',
|
||||||
|
'heart': 'blood-pumping-organ',
|
||||||
|
'brain': 'thinking-control-organ',
|
||||||
|
'blood': 'life-flowing-red-liquid',
|
||||||
|
'skin': 'body\'s protective-covering',
|
||||||
|
'muscle': 'movement-creating-tissue',
|
||||||
|
'breath': 'life-sustaining-air-flow',
|
||||||
|
'voice': 'sound-producing-expression',
|
||||||
|
'word': 'meaning-carrying-sound-unit',
|
||||||
|
'language': 'communication-sound-system',
|
||||||
|
'name': 'identity-labeling-word',
|
||||||
|
'story': 'event-narrative-tale',
|
||||||
|
'joke': 'humor-creating-tale',
|
||||||
|
'song': 'melodic-sound-creation',
|
||||||
|
'music': 'organized-sound-art',
|
||||||
|
'sound': 'air-vibration-sensation',
|
||||||
|
'noise': 'unwanted-sound-disturbance',
|
||||||
|
'silence': 'absence-of-sound',
|
||||||
|
'color': 'light-wavelength-perception',
|
||||||
|
'red': 'blood-fire-color',
|
||||||
|
'blue': 'sky-water-color',
|
||||||
|
'green': 'grass-leaf-color',
|
||||||
|
'yellow': 'sun-gold-color',
|
||||||
|
'purple': 'royal-flower-color',
|
||||||
|
'pink': 'blossom-blush-color',
|
||||||
|
'brown': 'earth-wood-color',
|
||||||
|
'black': 'night-shadow-color',
|
||||||
|
'white': 'snow-cloud-color',
|
||||||
|
'gray': 'storm-stone-color',
|
||||||
|
'silver': 'moon-metal-color',
|
||||||
|
'gold': 'treasure-sun-color',
|
||||||
|
};
|
||||||
|
|
||||||
|
// Gnome exclamations and interjections
|
||||||
|
const gnomeExclamations = [
|
||||||
|
'By my pointy hat!',
|
||||||
|
'Great toadstools!',
|
||||||
|
'Mushroom caps!',
|
||||||
|
'Sacred acorns!',
|
||||||
|
'Blessed berries!',
|
||||||
|
'Garden spirits preserve us!',
|
||||||
|
'Forest magic!',
|
||||||
|
'Woodland wonders!',
|
||||||
|
'Gnome\'s beard!',
|
||||||
|
'Tiny treasures!',
|
||||||
|
'Earth\'s bounty!',
|
||||||
|
'Root and branch!',
|
||||||
|
'Moss and mushrooms!',
|
||||||
|
'Fern and flower!',
|
||||||
|
'Bark and berry!',
|
||||||
|
'Stone and stream!'
|
||||||
|
];
|
||||||
|
|
||||||
|
// Gnome sentence starters
|
||||||
|
const gnomeSentenceStarters = [
|
||||||
|
'In the sacred grove, ',
|
||||||
|
'By the ancient oak, ',
|
||||||
|
'Beneath the mushroom ring, ',
|
||||||
|
'Among the forest folk, ',
|
||||||
|
'In the woodland realm, ',
|
||||||
|
'By the babbling brook, ',
|
||||||
|
'Under the starlit sky, ',
|
||||||
|
'Within the garden walls, ',
|
||||||
|
'Beside the fairy ring, ',
|
||||||
|
'Through the morning mist, ',
|
||||||
|
'As the seasons turn, ',
|
||||||
|
'When the moon is full, ',
|
||||||
|
'In the depths of the forest, ',
|
||||||
|
'Where the wild things grow, ',
|
||||||
|
'Beyond the garden gate, '
|
||||||
|
];
|
||||||
|
|
||||||
|
// Gnome sentence endings
|
||||||
|
const gnomeSentenceEndings = [
|
||||||
|
', as the ancients foretold.',
|
||||||
|
', blessed by the forest spirits.',
|
||||||
|
', in harmony with nature.',
|
||||||
|
', according to gnome wisdom.',
|
||||||
|
', as written in the bark of the elder tree.',
|
||||||
|
', by the light of the fireflies.',
|
||||||
|
', under the watchful eyes of the owls.',
|
||||||
|
', with the blessing of the earth mother.',
|
||||||
|
', as sure as mushrooms grow.',
|
||||||
|
', in the way of our people.',
|
||||||
|
', following the old traditions.',
|
||||||
|
', as the seasons decree.',
|
||||||
|
', by the sacred laws of the woodland.',
|
||||||
|
', in the manner of the wise ones.',
|
||||||
|
', as nature intended.'
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Translates regular text into gnome speak
|
||||||
|
*/
|
||||||
|
export function translateToGnomeSpeak(text: string): string {
|
||||||
|
if (!text || typeof text !== 'string') {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
let gnomeText = text.toLowerCase();
|
||||||
|
|
||||||
|
// Preserve URLs
|
||||||
|
const urlRegex = /(https?:\/\/[^\s]+)/g;
|
||||||
|
const urlMatches: string[] = [];
|
||||||
|
gnomeText = gnomeText.replace(urlRegex, (match) => {
|
||||||
|
urlMatches.push(match);
|
||||||
|
return `__URL_${urlMatches.length - 1}__`;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Preserve nostr: references
|
||||||
|
const nostrRegex = /(nostr:(npub1|note1|nprofile1|nevent1|naddr1)([023456789acdefghjklmnpqrstuvwxyz]+))/g;
|
||||||
|
const nostrMatches: string[] = [];
|
||||||
|
gnomeText = gnomeText.replace(nostrRegex, (match) => {
|
||||||
|
nostrMatches.push(match);
|
||||||
|
return `__NOSTR_${nostrMatches.length - 1}__`;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Preserve hashtags
|
||||||
|
const hashtagRegex = /(#\w+)/g;
|
||||||
|
const hashtagMatches: string[] = [];
|
||||||
|
gnomeText = gnomeText.replace(hashtagRegex, (match) => {
|
||||||
|
hashtagMatches.push(match);
|
||||||
|
return `__HASHTAG_${hashtagMatches.length - 1}__`;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Replace words with gnome equivalents
|
||||||
|
Object.entries(gnomeVocabulary).forEach(([english, gnome]) => {
|
||||||
|
const escapedEnglish = english.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
|
const regex = new RegExp(`\\b${escapedEnglish}\\b`, 'gi');
|
||||||
|
gnomeText = gnomeText.replace(regex, gnome);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add gnome exclamations for emphasis
|
||||||
|
gnomeText = gnomeText.replace(/!/g, () => {
|
||||||
|
const exclamation = gnomeExclamations[Math.floor(Math.random() * gnomeExclamations.length)];
|
||||||
|
return `! ${exclamation}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add gnome sentence starters occasionally
|
||||||
|
const sentences = gnomeText.split(/[.!?]+/).filter(s => s.trim());
|
||||||
|
const gnomeSentences = sentences.map((sentence, index) => {
|
||||||
|
const trimmed = sentence.trim();
|
||||||
|
if (!trimmed) return sentence;
|
||||||
|
|
||||||
|
// Add starter to some sentences (not all, to avoid repetition)
|
||||||
|
if (Math.random() < 0.3 && index > 0) {
|
||||||
|
const starter = gnomeSentenceStarters[Math.floor(Math.random() * gnomeSentenceStarters.length)];
|
||||||
|
return starter + trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
return trimmed;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Rejoin sentences
|
||||||
|
gnomeText = gnomeSentences.join('. ');
|
||||||
|
|
||||||
|
// Add gnome endings occasionally
|
||||||
|
if (Math.random() < 0.4) {
|
||||||
|
const ending = gnomeSentenceEndings[Math.floor(Math.random() * gnomeSentenceEndings.length)];
|
||||||
|
gnomeText += ending;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capitalize first letter of sentences
|
||||||
|
gnomeText = gnomeText.replace(/(^|[.!?]\s+)([a-z])/g, (match, prefix, letter) => {
|
||||||
|
return prefix + letter.toUpperCase();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add some gnome-specific formatting
|
||||||
|
gnomeText = gnomeText.replace(/\b(bitcoin|btc)\b/gi, '✨golden acorns of the digital realm✨');
|
||||||
|
gnomeText = gnomeText.replace(/\b(gm|good morning)\b/gi, '🌅when dew kisses the earth🌅');
|
||||||
|
gnomeText = gnomeText.replace(/\b(gn|good night)\b/gi, '🌙when the moon watches over🌙');
|
||||||
|
|
||||||
|
// Restore preserved patterns
|
||||||
|
gnomeText = gnomeText.replace(/__URL_(\d+)__/g, (_, index) => urlMatches[parseInt(index)]);
|
||||||
|
gnomeText = gnomeText.replace(/__NOSTR_(\d+)__/g, (_, index) => nostrMatches[parseInt(index)]);
|
||||||
|
gnomeText = gnomeText.replace(/__HASHTAG_(\d+)__/g, (_, index) => hashtagMatches[parseInt(index)]);
|
||||||
|
|
||||||
|
return gnomeText;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if text should be translated (only kind 1 events)
|
||||||
|
*/
|
||||||
|
export function shouldTranslateToGnomeSpeak(eventKind: number): boolean {
|
||||||
|
return eventKind === 1;
|
||||||
|
}
|
||||||
@@ -1,15 +1,3 @@
|
|||||||
import Buffer from 'buffer';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Polyfill for Buffer in browser environment
|
|
||||||
*
|
|
||||||
* Many Node.js libraries like isomorphic-git and bitcoinjs-lib expect Buffer to be globally available.
|
|
||||||
* This polyfill makes the buffer package's Buffer available globally.
|
|
||||||
*/
|
|
||||||
if (!globalThis.Buffer) {
|
|
||||||
globalThis.Buffer = Buffer.Buffer;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Polyfill for AbortSignal.any()
|
* Polyfill for AbortSignal.any()
|
||||||
*
|
*
|
||||||
|
|||||||
+3
-8
@@ -3,15 +3,10 @@ import { createRoot } from 'react-dom/client';
|
|||||||
// Import polyfills first
|
// Import polyfills first
|
||||||
import './lib/polyfills.ts';
|
import './lib/polyfills.ts';
|
||||||
|
|
||||||
import { ErrorBoundary } from '@/components/ErrorBoundary';
|
|
||||||
import App from './App.tsx';
|
import App from './App.tsx';
|
||||||
import './index.css';
|
import './index.css';
|
||||||
|
|
||||||
// FIXME: a custom font should be used. Eg:
|
// Import gnome-themed font
|
||||||
// import '@fontsource-variable/<font-name>';
|
import '@fontsource-variable/comfortaa';
|
||||||
|
|
||||||
createRoot(document.getElementById("root")!).render(
|
createRoot(document.getElementById("root")!).render(<App />);
|
||||||
<ErrorBoundary>
|
|
||||||
<App />
|
|
||||||
</ErrorBoundary>
|
|
||||||
);
|
|
||||||
+26
-12
@@ -1,22 +1,36 @@
|
|||||||
import { useSeoMeta } from '@unhead/react';
|
import { useSeoMeta } from '@unhead/react';
|
||||||
|
import { GnomeHeader } from '@/components/GnomeHeader';
|
||||||
// FIXME: Update this page (the content is just a fallback if you fail to update the page)
|
import { GnomeComposer } from '@/components/GnomeComposer';
|
||||||
|
import { GnomeFeed } from '@/components/GnomeFeed';
|
||||||
|
|
||||||
const Index = () => {
|
const Index = () => {
|
||||||
useSeoMeta({
|
useSeoMeta({
|
||||||
title: 'Welcome to Your Blank App',
|
title: 'Gnome Nostr - The Sacred Network of Woodland Folk',
|
||||||
description: 'A modern Nostr client application built with React, TailwindCSS, and Nostrify.',
|
description: 'A magical Nostr client where all messages are translated into the ancient gnome tongue. Connect with fellow earth-dwellers across the message-mushroom network!',
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-900">
|
<div className="min-h-screen bg-background">
|
||||||
<div className="text-center">
|
<div className="container max-w-2xl mx-auto px-4 py-6">
|
||||||
<h1 className="text-4xl font-bold mb-4 text-gray-900 dark:text-gray-100">
|
<GnomeHeader />
|
||||||
Welcome to Your Blank App
|
<GnomeComposer />
|
||||||
</h1>
|
<GnomeFeed />
|
||||||
<p className="text-xl text-gray-600 dark:text-gray-400">
|
|
||||||
Start building your amazing project here!
|
{/* Footer with MKStack attribution */}
|
||||||
</p>
|
<div className="mt-12 pt-6 border-t border-border/30 text-center">
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Vibed with{' '}
|
||||||
|
<a
|
||||||
|
href="https://soapbox.pub/mkstack"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="text-primary hover:text-accent transition-colors underline"
|
||||||
|
>
|
||||||
|
MKStack
|
||||||
|
</a>
|
||||||
|
{' '}• Blessed by the forest spirits 🍄✨
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
import { useSeoMeta } from '@unhead/react';
|
|
||||||
import { DMMessagingInterface } from '@/components/dm/DMMessagingInterface';
|
|
||||||
|
|
||||||
const Messages = () => {
|
|
||||||
useSeoMeta({
|
|
||||||
title: 'Messages',
|
|
||||||
description: 'Private encrypted messaging on Nostr',
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-background">
|
|
||||||
<div className="container mx-auto p-4 h-screen flex flex-col">
|
|
||||||
{/* Header */}
|
|
||||||
<div className="flex items-center justify-between mb-4">
|
|
||||||
<h1 className="text-2xl font-semibold">Messages</h1>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<DMMessagingInterface className="flex-1" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default Messages;
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
import { nip19 } from 'nostr-tools';
|
|
||||||
import { useParams } from 'react-router-dom';
|
|
||||||
import NotFound from './NotFound';
|
|
||||||
|
|
||||||
export function NIP19Page() {
|
|
||||||
const { nip19: identifier } = useParams<{ nip19: string }>();
|
|
||||||
|
|
||||||
if (!identifier) {
|
|
||||||
return <NotFound />;
|
|
||||||
}
|
|
||||||
|
|
||||||
let decoded;
|
|
||||||
try {
|
|
||||||
decoded = nip19.decode(identifier);
|
|
||||||
} catch {
|
|
||||||
return <NotFound />;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { type } = decoded;
|
|
||||||
|
|
||||||
switch (type) {
|
|
||||||
case 'npub':
|
|
||||||
case 'nprofile':
|
|
||||||
// AI agent should implement profile view here
|
|
||||||
return <div>Profile placeholder</div>;
|
|
||||||
|
|
||||||
case 'note':
|
|
||||||
// AI agent should implement note view here
|
|
||||||
return <div>Note placeholder</div>;
|
|
||||||
|
|
||||||
case 'nevent':
|
|
||||||
// AI agent should implement event view here
|
|
||||||
return <div>Event placeholder</div>;
|
|
||||||
|
|
||||||
case 'naddr':
|
|
||||||
// AI agent should implement addressable event view here
|
|
||||||
return <div>Addressable event placeholder</div>;
|
|
||||||
|
|
||||||
default:
|
|
||||||
return <NotFound />;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
import { render, screen } from '@testing-library/react';
|
|
||||||
import { describe, it, expect, vi } from 'vitest';
|
|
||||||
import { ErrorBoundary } from '@/components/ErrorBoundary';
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Test component that throws an error
|
|
||||||
const ThrowError = ({ shouldThrow }: { shouldThrow: boolean }) => {
|
|
||||||
if (shouldThrow) {
|
|
||||||
throw new Error('Test error');
|
|
||||||
}
|
|
||||||
return <div>No error</div>;
|
|
||||||
};
|
|
||||||
|
|
||||||
describe('ErrorBoundary', () => {
|
|
||||||
it('renders children when no error occurs', () => {
|
|
||||||
render(
|
|
||||||
<ErrorBoundary>
|
|
||||||
<div>Test content</div>
|
|
||||||
</ErrorBoundary>
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(screen.getByText('Test content')).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('catches and displays error when child throws', () => {
|
|
||||||
// Suppress console.error for this test
|
|
||||||
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
||||||
|
|
||||||
render(
|
|
||||||
<ErrorBoundary>
|
|
||||||
<ThrowError shouldThrow={true} />
|
|
||||||
</ErrorBoundary>
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
|
|
||||||
expect(screen.getByText('An unexpected error occurred. The error has been reported.')).toBeInTheDocument();
|
|
||||||
|
|
||||||
consoleSpy.mockRestore();
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
it('uses custom fallback when provided', () => {
|
|
||||||
const customFallback = <div>Custom error message</div>;
|
|
||||||
|
|
||||||
// Suppress console.error for this test
|
|
||||||
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
||||||
|
|
||||||
render(
|
|
||||||
<ErrorBoundary fallback={customFallback}>
|
|
||||||
<ThrowError shouldThrow={true} />
|
|
||||||
</ErrorBoundary>
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(screen.getByText('Custom error message')).toBeInTheDocument();
|
|
||||||
|
|
||||||
consoleSpy.mockRestore();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
+4
-12
@@ -4,7 +4,6 @@ import { BrowserRouter } from 'react-router-dom';
|
|||||||
import { NostrLoginProvider } from '@nostrify/react/login';
|
import { NostrLoginProvider } from '@nostrify/react/login';
|
||||||
import NostrProvider from '@/components/NostrProvider';
|
import NostrProvider from '@/components/NostrProvider';
|
||||||
import { AppProvider } from '@/components/AppProvider';
|
import { AppProvider } from '@/components/AppProvider';
|
||||||
import { NWCProvider } from '@/contexts/NWCContext';
|
|
||||||
import { AppConfig } from '@/contexts/AppContext';
|
import { AppConfig } from '@/contexts/AppContext';
|
||||||
|
|
||||||
interface TestAppProps {
|
interface TestAppProps {
|
||||||
@@ -23,12 +22,7 @@ export function TestApp({ children }: TestAppProps) {
|
|||||||
|
|
||||||
const defaultConfig: AppConfig = {
|
const defaultConfig: AppConfig = {
|
||||||
theme: 'light',
|
theme: 'light',
|
||||||
relayMetadata: {
|
relayUrl: 'wss://relay.nostr.band',
|
||||||
relays: [
|
|
||||||
{ url: 'wss://relay.nostr.band', read: true, write: true },
|
|
||||||
],
|
|
||||||
updatedAt: 0,
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -37,11 +31,9 @@ export function TestApp({ children }: TestAppProps) {
|
|||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<NostrLoginProvider storageKey='test-login'>
|
<NostrLoginProvider storageKey='test-login'>
|
||||||
<NostrProvider>
|
<NostrProvider>
|
||||||
<NWCProvider>
|
<BrowserRouter>
|
||||||
<BrowserRouter>
|
{children}
|
||||||
{children}
|
</BrowserRouter>
|
||||||
</BrowserRouter>
|
|
||||||
</NWCProvider>
|
|
||||||
</NostrProvider>
|
</NostrProvider>
|
||||||
</NostrLoginProvider>
|
</NostrLoginProvider>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
|
|||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "mkstack",
|
||||||
|
"title": "MKStack",
|
||||||
|
"description": "Build Nostr apps in minutes with this React framework",
|
||||||
|
"uri": "git+https://gitlab.com/soapbox-pub/mkstack.git",
|
||||||
|
"image": "https://gitlab.com/-/project/69048882/uploads/0a9e3a19f2901d5c772952c1de10ce4f/image.png",
|
||||||
|
"commands": [
|
||||||
|
"npm",
|
||||||
|
"npx"
|
||||||
|
],
|
||||||
|
"tech": [
|
||||||
|
"react",
|
||||||
|
"typescript",
|
||||||
|
"tailwind",
|
||||||
|
"shadcn-ui",
|
||||||
|
"nostrify",
|
||||||
|
"vite"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -19,6 +19,9 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
extend: {
|
extend: {
|
||||||
|
fontFamily: {
|
||||||
|
sans: ['Comfortaa Variable', 'Comfortaa', 'system-ui', 'sans-serif'],
|
||||||
|
},
|
||||||
colors: {
|
colors: {
|
||||||
border: 'hsl(var(--border))',
|
border: 'hsl(var(--border))',
|
||||||
input: 'hsl(var(--input))',
|
input: 'hsl(var(--input))',
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": false,
|
||||||
|
"strictNullChecks": true,
|
||||||
|
"noUnusedLocals": false,
|
||||||
|
"noUnusedParameters": false,
|
||||||
|
"noImplicitAny": false,
|
||||||
|
"noFallthroughCasesInSwitch": false,
|
||||||
|
|
||||||
|
"baseUrl": ".",
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./src/*"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
+13
-25
@@ -1,31 +1,19 @@
|
|||||||
{
|
{
|
||||||
|
"files": [],
|
||||||
|
"references": [
|
||||||
|
{ "path": "./tsconfig.app.json" },
|
||||||
|
{ "path": "./tsconfig.node.json" }
|
||||||
|
],
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"target": "ES2020",
|
|
||||||
"useDefineForClassFields": true,
|
|
||||||
"lib": ["ESNext", "DOM", "DOM.Iterable"],
|
|
||||||
"module": "ESNext",
|
|
||||||
"skipLibCheck": true,
|
|
||||||
|
|
||||||
/* Bundler mode */
|
|
||||||
"moduleResolution": "bundler",
|
|
||||||
"allowImportingTsExtensions": true,
|
|
||||||
"isolatedModules": true,
|
|
||||||
"moduleDetection": "force",
|
|
||||||
"noEmit": true,
|
|
||||||
"jsx": "react-jsx",
|
|
||||||
|
|
||||||
/* Linting */
|
|
||||||
"strict": false,
|
|
||||||
"strictNullChecks": true,
|
|
||||||
"noUnusedLocals": false,
|
|
||||||
"noUnusedParameters": false,
|
|
||||||
"noImplicitAny": false,
|
|
||||||
"noFallthroughCasesInSwitch": false,
|
|
||||||
|
|
||||||
"baseUrl": ".",
|
"baseUrl": ".",
|
||||||
"paths": {
|
"paths": {
|
||||||
"@/*": ["./src/*"]
|
"@/*": ["./src/*"]
|
||||||
}
|
},
|
||||||
},
|
"noImplicitAny": false,
|
||||||
"include": ["src"]
|
"noUnusedParameters": false,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"allowJs": true,
|
||||||
|
"noUnusedLocals": false,
|
||||||
|
"strictNullChecks": true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"lib": ["ES2023"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": false,
|
||||||
|
"noUnusedParameters": false,
|
||||||
|
"noFallthroughCasesInSwitch": true
|
||||||
|
},
|
||||||
|
"include": ["vite.config.ts"]
|
||||||
|
}
|
||||||
@@ -19,9 +19,6 @@ export default defineConfig(() => ({
|
|||||||
onConsoleLog(log) {
|
onConsoleLog(log) {
|
||||||
return !log.includes("React Router Future Flag Warning");
|
return !log.includes("React Router Future Flag Warning");
|
||||||
},
|
},
|
||||||
env: {
|
|
||||||
DEBUG_PRINT_LIMIT: '0', // Suppress DOM output that exceeds AI context windows
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
resolve: {
|
resolve: {
|
||||||
alias: {
|
alias: {
|
||||||
|
|||||||
Reference in new issue
Block a user