147 Commits
Author SHA1 Message Date
lemonknowsall 315989fc87 Update nostr-tools to ^2.21.0 and @getalby/sdk to ^7.0.0 2026-01-28 23:28:11 -08:00
Alex Gleason c1bd55108c Remove stray docs mentions from AGENTS.md 2026-01-24 21:21:09 -06:00
Alex Gleason 266e2c92d8 Replace docs with skills 2026-01-24 21:20:22 -06:00
Alex Gleason 8163f30011 You don't actually have to pass signal now 2026-01-24 00:02:15 -06:00
Alex Gleason b97db2ca77 Upgrade zod to v4 2026-01-23 23:59:13 -06:00
Alex Gleason cda1b903a9 Merge branch 'main' of gitlab.com:soapbox-pub/mkstack 2026-01-21 16:52:45 -06:00
Alex Gleason ead11c31fe Remove stack.json 2026-01-21 16:52:23 -06:00
Alex Gleason a9bbb5ab84 Merge branch 'remove-nostr-band-relay' into 'main'
Replace dead relay.nostr.band with relay.primal.net

See merge request soapbox-pub/mkstack!29
2026-01-21 20:32:10 +00:00
Derek Ross f87510bc3a Replace dead relay.nostr.band with relay.primal.net 2026-01-21 15:29:02 -05:00
Alex Gleason fc010f9b91 Add Nostr Security Model to AGENTS.md 2026-01-21 12:14:24 -06:00
Alex Gleason 20f9ea9069 npm audit fix 2026-01-17 19:19:05 -06:00
Alex Gleason fc4c4deded Upgrade Nostrify 2026-01-17 19:18:43 -06:00
Alex Gleason b3dac352a4 Remove deploy script 2026-01-11 22:21:47 -06:00
Alex Gleason e94f53f0e2 Add -z-10 isolate hint 2026-01-10 11:37:12 -06:00
Alex Gleason 74449cf0d7 Add opencode.json with Nostr MCP server 2026-01-09 16:27:49 -06:00
Alex Gleason e26ab6a433 Fix URL wrapping in NoteContent 2025-12-30 18:19:20 -06:00
Alex Gleason 816051f5ea Greatly simplify the login and signup dialogs 2025-12-30 17:53:32 -06:00
Alex Gleason 413aa93e4f Generate custom images liberally 2025-12-23 05:54:11 -06:00
Alex Gleason 6941aad2f5 Upgrade Nostrify 2025-12-22 13:28:39 -06:00
Alex Gleason 28aba4b3a4 Revert "Fix happy-dom vuln"
This reverts commit e5b3f249f8.
2025-12-21 04:11:11 -06:00
Alex Gleason e5b3f249f8 Fix happy-dom vuln 2025-12-21 02:28:15 -06:00
Alex Gleason 12e6465912 npm audit fix 2025-12-21 02:02:24 -06:00
Alex Gleason 722d138f35 Remove "Vibed with MKStack" 2025-12-02 20:26:37 -06:00
Alex Gleason 84a15aa077 Revert "Try adding cashu deps"
This reverts commit 6534c5fcea.
2025-11-20 11:14:14 -06:00
Alex Gleason 8c7b595d22 Revert "Use nutstack package.json and package-lock.json"
This reverts commit 0bf1e0e85e.
2025-11-20 11:14:07 -06:00
Alex Gleason 0bf1e0e85e Use nutstack package.json and package-lock.json 2025-11-19 18:47:04 -06:00
Alex Gleason 6534c5fcea Try adding cashu deps 2025-11-19 18:42:35 -06:00
Alex Gleason e4ee998500 Fix posting a comment not invalidating comment cache 2025-11-17 19:44:34 -06:00
Alex Gleason 000be63075 Don't redirect /assets/* in Netlify redirects file 2025-11-13 22:11:57 -06:00
Alex Gleason 5f14ac11fc Remove DM stuff from App.tsx, add instructions on how to add it in docs 2025-11-11 17:36:32 -06:00
Alex Gleason 0b7d86a16f Remove DMProvider from App.tsx and update DM documentation
- Removed DMProvider, DMConfig imports and configuration from App.tsx
- Updated docs/NOSTR_DIRECT_MESSAGES.md with setup instructions
- DM functionality now requires manual setup as documented
- Preserved all existing intentional test errors
2025-11-11 17:34:45 -06:00
Alex Gleason 8496cb99e5 Disable DM functionality by default 2025-11-11 17:31:46 -06:00
Alex Gleason 386d664a33 Merge branch 'main' of gitlab.com:soapbox-pub/mkstack 2025-11-10 17:49:28 -06:00
Alex Gleason 0a5e8fc9e0 Bully the robot to utilize git if it's available, and to always read files before writing to them 2025-11-10 17:45:42 -06:00
Alex Gleason 2ba510c54f Merge branch 'removeMessageRoute' into 'main'
Remove "/messages" route

See merge request soapbox-pub/mkstack!27
2025-11-07 12:19:29 +00:00
lemonknowsall eb0fd14e33 remove /messages route 2025-11-06 19:43:20 -08:00
Alex Gleason 0532d23b57 RelayListManager improved mobile support 2025-11-05 00:23:40 -06:00
Alex Gleason 8eddf49e61 Implement NIP-65 relay management
- Replace single relayUrl with NIP-65 compatible relayMetadata structure
- Add RelayListManager component for managing multiple relays with read/write permissions
- Add NostrSync component to automatically sync user's NIP-65 relay list on login
- Update NostrProvider to use relay list instead of single relay
- Remove RelaySelector component and update empty states
- Update AGENTS.md documentation to reflect relay management changes
- Automatically publish relay list changes as NIP-65 events when user is logged in
2025-11-04 23:58:32 -06:00
Alex Gleason d7dee81b1c Split DM context up into multiple files 2025-11-04 23:33:58 -06:00
Alex Gleason fbafc52992 Stronger guidance to call the generate_kind tool 2025-11-03 22:33:18 -06:00
Alex Gleason 6d9e1816ee Fix some lint/test issues 2025-10-23 12:08:27 -05:00
Alex Gleason 44b264e4b4 Merge branch 'feat/messaging' into 'main'
feat/messaging

See merge request soapbox-pub/mkstack!26
2025-10-23 17:08:13 +00:00
sam cc393a266c refactor docs into the appropriate dm doc file 2025-10-23 18:17:51 +02:00
sam 7eca8f850b ++ 2025-10-23 00:07:50 +07:00
sam f37b97630f leave out yarn trace 2025-10-23 00:05:39 +07:00
sam 14db9f59d0 Merge branch 'main' into feat/messaging-example 2025-10-22 23:59:41 +07:00
sam 701067fa8f remove one invalid dep, and calmed other lint warns 2025-10-22 23:11:02 +07:00
sam ea791d405e lint fix 2025-10-22 23:06:29 +07:00
sam 35ad8cfa1b log edge case nip17 processesing errors 2025-10-22 22:48:08 +07:00
sam 0fd52feabb fix some nip17 issues; fuzzed signers and times 2025-10-22 22:05:38 +07:00
sam 440e02ff0e remove debug statemnts 2025-10-22 18:27:56 +07:00
sam 6380b1980c handle kind 14/15s via contained event instead 2025-10-22 16:55:37 +07:00
sam 79980ded70 redo encryption to enc individual messages content, not the whole blob, to circumvent nip44 signer limits 2025-10-22 16:44:27 +07:00
Alex Gleason 0562cb8ee2 Remove some cruft 2025-10-21 20:14:50 -05:00
Alex Gleason 1b4c27d17d Use nostrify from npm 2025-10-21 20:11:41 -05:00
sam 9d7f5e48df fix caching messages insecurely if signer nip44 failed 2025-10-21 22:06:29 +07:00
sam dbacdbc8ac update docs regarding default enabled state, and with info on all messaging components so that there's a better base for custom UIs 2025-10-21 21:46:22 +07:00
sam 1c23b6bafc enable a custom messaging db file per mkstacks app made 2025-10-21 21:45:20 +07:00
sam 1dc91bd978 disable message unless explicitly added 2025-10-21 21:45:04 +07:00
sam 69b314c831 wip - document DMs to the LLM 2025-10-21 21:28:57 +07:00
sam 50ed58730c expose attachments param 2025-10-21 20:42:38 +07:00
sam 69252a7526 port dms hook to provider to unify source of truth 2025-10-21 20:26:04 +07:00
sam d1ef321e38 cahce profile data 2025-10-21 17:37:52 +07:00
sam 8d14062d14 skeleton on avatar and resolved display name to avoid glitchy looking rewrites 2025-10-21 17:35:26 +07:00
sam 61763d04c8 avoid unnecessary render 2025-10-21 17:23:31 +07:00
sam 211d303301 idb package 2025-10-21 08:58:24 +07:00
sam 5ad2d7fabc add relay selector to debug/test messaging page 2025-10-21 08:58:12 +07:00
sam 76cb50f2da comvey message type in ui 2025-10-21 06:58:59 +07:00
sam 7e24b0c347 use same date formatting funcs on messages as chat list 2025-10-20 21:44:17 +07:00
sam 6c48e7c684 better loading feedback in the ui 2025-10-20 21:33:38 +07:00
sam d8b195e624 theres only one format, no need for versioning 2025-10-20 21:03:04 +07:00
sam e6acf05e8d tooltip for any decryption errors for the curious minded 2025-10-20 19:34:44 +07:00
sam e8ef8f02ab query relays for nip4 and nip17s in parallel 2025-10-20 19:07:16 +07:00
sam e218305799 encrypt the whole message cache instaed of individual messages, for faster decryption on load 2025-10-20 18:36:16 +07:00
sam 8bbb247ba8 intercept hard refresh to clear cache 2025-10-20 15:16:51 +07:00
sam ed80d74824 use a config object for DM provider 2025-10-20 14:04:58 +07:00
sam 92eb50f8d2 handle edge case cache reset when user changes relay while logged out then logs in again 2025-10-20 12:53:58 +07:00
sam f379a95548 clear message cache on relay change 2025-10-20 12:47:18 +07:00
sam 9bafd29ec9 fix updating latest message date when new messages from another nip are added 2025-10-20 12:00:05 +07:00
sam d7d6f8d6d5 change formatting for recent convo 2025-10-20 11:52:56 +07:00
sam 381fdaf977 ensure unique ids for dom 2025-10-19 22:34:26 +07:00
sam 15ec6c69e7 fix issue with decrypting stored encrypted messages 2025-10-19 21:42:09 +07:00
sam 7a52562926 wip kind 14/15 within nip17 seal for attachments 2025-10-19 19:57:40 +07:00
sam 5d8a4d4ace since nip17s can be fuzzed +- 2 days, query/subscribe from -2days as an offset 2025-10-19 19:02:33 +07:00
sam cb50cbe137 give 1059s a fuzzed time 2025-10-19 18:58:13 +07:00
sam 79b03dee38 random signers for 1059s 2025-10-19 18:16:09 +07:00
sam 04ae3d89c0 pagination 2025-10-19 14:37:43 +07:00
sam 1ffe78c80c let messaging be optional 2025-10-19 14:28:23 +07:00
sam 04c5a84ca9 memoize a bunch of things 2025-10-19 14:18:55 +07:00
sam 71b9c9d380 rename dm components for concistency 2025-10-19 14:12:29 +07:00
sam cb231c7770 put the split responsive messaging ui in a component of its own 2025-10-19 13:57:15 +07:00
sam d72b28cf77 loading state copy 2025-10-19 13:24:12 +07:00
Alex Gleason 19ecfee4bf Add Buffer polyfill 2025-10-18 12:11:32 -05:00
sam 67658eb446 optionality around what messaging nips can be used 2025-10-18 21:37:09 +07:00
sam d8e2e62736 add warn to all nip4 messages 2025-10-18 21:04:36 +07:00
sam f37d86b8d3 fix sending nip4 2025-10-18 20:53:53 +07:00
sam d3866ae0af fix use latest message in sidebar 2025-10-18 20:49:09 +07:00
sam f6e149893b fix surfacing decrypt error for nip17s once already cached 2025-10-18 20:43:17 +07:00
sam dcffee03af rearrange header 2025-10-18 20:33:17 +07:00
sam 9d3ead4428 fix scroll and use a warn for nip4 messages 2025-10-18 20:18:35 +07:00
sam 9e222850ce fix sixing of conversation list items 2025-10-18 19:39:51 +07:00
sam 114eb13ce6 clear cache properly and without hacky window reload 2025-10-18 18:54:48 +07:00
sam d72fc80cc5 use a lower subscription overlap 2025-10-18 18:51:08 +07:00
sam 68031244a5 fix: always update sync time even if no messages 2025-10-18 18:44:18 +07:00
sam 53ac562d10 ++ 2025-10-18 18:26:15 +07:00
sam 51be437219 change var names, remove unused, change component to pure style 2025-10-18 18:25:46 +07:00
sam b132e4847d wip chat ui 2025-10-18 18:19:47 +07:00
sam 1d42551b36 wip initial dump of DM stuff from universes 2025-10-18 15:34:36 +07:00
Alex Gleason 49abb22471 Fix inefficient queryClient update when relay URL changes 2025-10-16 18:42:35 -05:00
Alex Gleason a974da9f88 Make Ditto relay the default 2025-10-16 18:33:30 -05:00
Alex Gleason 16837284fb Only set app config that's actually changed 2025-10-16 18:33:24 -05:00
Alex Gleason 3f21df473b Try copying in some of bolt.diy's system prompt 2025-10-12 19:17:32 -05:00
Alex Gleason cec3b7f7d2 Merge branch 'main' of gitlab.com:soapbox-pub/mkstack 2025-10-11 18:26:25 -05:00
Alex Gleason df0cc7c6aa Add robots.txt 2025-10-11 17:13:33 -05:00
Alex Gleason 629c350300 Merge branch 'aiChatModelSelector' into 'main'
Remove Hardcoded Shakespeare Models

See merge request soapbox-pub/mkstack!25
2025-10-08 06:29:10 +00:00
lemonknowsall 998bf4fc47 remove hardcoded model names 2025-10-07 22:56:30 -07:00
Alex Gleason c69e440c04 Merge branch 'weblnQuiet' into 'main'
Make webln check less intrusive

See merge request soapbox-pub/mkstack!24
2025-10-05 23:59:37 +00:00
Chad Curtis aac77d05bd Move type import to line. v2 2025-10-05 21:11:47 +00:00
Chad Curtis c3c41ca4b3 Move type import to line. 2025-10-05 21:10:57 +00:00
Chad Curtis bd675e090e Remove unrelated lint fix attempt. 2025-10-05 21:09:12 +00:00
Chad Curtis b77885093c Remove webln from state, simplify webln detection. 2025-10-05 20:59:27 +00:00
Chad Curtis 45cdcecf9e Review fixes 2025-10-05 20:05:33 +00:00
Chad Curtis d462a8d679 Remove unneeded webln npm package
This change removes the webln package as it serves no specific function that isn't
already provided via native browser capability as it relates to WebLN.
2025-10-05 19:33:04 +00:00
Alex Gleason 1fbd0cdcc2 Merge branch 'infiniteDedup' into 'main'
Add deduplication to infinite feed scroll example

See merge request soapbox-pub/mkstack!23
2025-10-05 18:54:44 +00:00
Chad Curtis 23b9ca58c0 Add deduplication to infinite feed scroll example
This change introduces a simple deduplication mechanicsm for the example infinite
scroll feed code we provide for the agent. I have also added a 'isFetchingNextPage'
check to avoid the potential scenario of aggressively overfetching via quick scrolling.

If a post exists in the feed already (it has been 'seen'), the it and all duplicate
post events will be filtered out from the returned content.
2025-10-04 17:46:17 +00:00
Alex Gleason 1f2fa9d03e Add docs section to AGENTS.md 2025-10-01 00:32:03 -05:00
Alex Gleason 5c8e74b484 Move some more info out of AGENTS.md into docs/ 2025-10-01 00:23:52 -05:00
Alex Gleason b00b19a4bd Add docs/ dir, move AI chat lingo to docs/AI_CHAT.md 2025-10-01 00:13:44 -05:00
Alex Gleason aa9a0d8f93 Merge branch 'shakespeare-ai-hook' into 'main'
Shakespeare AI Hook

See merge request soapbox-pub/mkstack!21
2025-10-01 05:09:09 +00:00
lemonknowsall 6ffa656680 agent instructions to assist with AI 1-shot 2025-09-28 11:18:27 -07:00
lemonknowsall c669dd3604 added error handling and more instruction 2025-09-27 21:29:00 -07:00
lemonknowsall 6980497532 Add Shakespeare AI hook and agent instruction 2025-09-27 21:29:00 -07:00
Alex Gleason 57c646f919 Revert tailwindcss changes, @apply is fine actually
Revert "Remove all @apply usage from index.css"

This reverts commit 81fae13219.

Revert "Add TailwindCSS @apply guidelines"

This reverts commit 3aedc574d7.
2025-09-27 22:23:38 -05:00
Alex Gleason 81fae13219 Remove all @apply usage from index.css
- Convert @apply border-border to pure CSS: border-color: hsl(var(--border))
- Convert @apply bg-background text-foreground to pure CSS equivalents
- Update comment to reflect complete @apply removal
- Update AGENTS.md to strengthen prohibition language
- Maintain all theming functionality with pure CSS custom properties
2025-09-26 21:15:31 -05:00
Alex Gleason 3aedc574d7 Add TailwindCSS @apply guidelines
- Document prohibition of @apply at-rule in AGENTS.md
- Add explanatory comment in index.css about @apply policy
- Promote component-driven styling approach over @apply usage
- Note exceptions for shadcn/ui base layer styles
2025-09-26 20:59:43 -05:00
Alex Gleason be71f350fc Remove bg-background from "outline" button variant 2025-09-20 11:20:44 -05:00
Alex Gleason 03578ab05d Add information about connecting to multiple relays 2025-09-15 20:27:51 -05:00
Alex Gleason a26a755505 Give useIsMobile an initial state 2025-09-13 18:35:08 -05:00
Alex Gleason 849693416a Add git commit requirement to validation process
- Include creating a git commit as step 5 in validation priority order
- Add git commit to minimum requirements for completing changes
- Ensures work is properly saved after validation
2025-09-11 22:12:20 -05:00
Alex Gleason 58322d237e vitest dot reporter 2025-09-08 15:24:51 -05:00
Alex Gleason 976164b480 Minimize build and test output 2025-09-08 14:49:10 -05:00
Alex Gleason 36756f56a9 Remove non-standard context files 2025-09-08 13:46:10 -05:00
Alex Gleason 3701c14c37 AGENTS.md: make "validating your changes" more flexible to different environments 2025-09-08 13:44:59 -05:00
Alex Gleason 33614b1ddd Add improved README 2025-09-08 12:15:01 -05:00
Alex Gleason ca9c88b5ea AGENTS.md: generalize tool names 2025-09-08 03:22:35 -05:00
Alex Gleason 95881bb09f Merge branch 'simplify-tsconfig' into 'main'
Simplify tsconfig

See merge request soapbox-pub/mkstack!18
2025-09-03 01:37:50 +00:00
Alex Gleason ba1a7871a0 Simplify tsconfig 2025-09-02 20:17:44 -05:00
62 changed files with 6006 additions and 1386 deletions

No files matched your search

+337
View File
@@ -0,0 +1,337 @@
---
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 };
}
```
+59
View File
@@ -0,0 +1,59 @@
---
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"
/>
```
@@ -0,0 +1,478 @@
---
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>
);
}
```
@@ -0,0 +1,77 @@
---
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>
);
}
```
-1
View File
@@ -1 +0,0 @@
../.mcp.json
+2
View File
@@ -7,11 +7,13 @@ yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
.ai/
yarn.lock
# Editor directories and files
.idea
-1
View File
@@ -1 +0,0 @@
@jsr:registry=https://npm.jsr.io
+317 -169
View File
@@ -18,6 +18,7 @@ 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/`: shadcn/ui components (48+ components available)
- `/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:
- `useNostr`: Core Nostr protocol integration
@@ -36,14 +37,19 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `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/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext, NWCContext)
- `/src/contexts/`: React context providers (AppContext, NWCContext, DMContext)
- `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
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
- `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)
- `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
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:
@@ -104,19 +110,15 @@ The AI assistant's behavior and knowledge is defined by the AGENTS.md file, whic
1. Edit AGENTS.md directly
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
This project comes with custom hooks for querying and publishing events on the Nostr network.
### Nostr Implementation Guidelines
- 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, 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 with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
- Always check the full list of existing NIPs 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.
- Only generate new kind numbers 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.
@@ -124,7 +126,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:
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.
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.
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
@@ -141,8 +143,9 @@ When implementing features that could use existing NIPs, follow this decision fr
- No existing NIP covers the core functionality
- The data structure is fundamentally different from existing patterns
- 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 kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
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**:
```
@@ -217,7 +220,7 @@ const events = await nostr.query([{
kinds: [1],
'#t': ['farming'],
limit: 20
}], { signal });
}]);
```
### Kind Ranges
@@ -267,6 +270,104 @@ 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.
### 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 returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
@@ -281,6 +382,85 @@ 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
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
@@ -295,79 +475,14 @@ function usePosts() {
return useQuery({
queryKey: ['posts'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
const events = await nostr.query([{ kinds: [1], limit: 20 }]);
return events; // these events could be transformed into another format
},
});
}
```
### Infinite Scroll for 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';
function GlobalFeed() {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
const { ref, inView } = useInView();
useEffect(() => {
if (inView && hasNextPage) {
fetchNextPage();
}
}, [inView, hasNextPage, fetchNextPage]);
const posts = data?.pages.flat() || [];
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>
);
}
```
#### 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.
@@ -380,7 +495,7 @@ const events = await nostr.query([
'#e': [eventId],
limit: 150,
}
], { signal });
]);
// Separate by type in JavaScript
const notes = events.filter((e) => e.kind === 1);
@@ -392,9 +507,9 @@ const genericReposts = events.filter((e) => e.kind === 16);
```typescript
// This creates unnecessary load and can trigger rate limiting
const [notes, reposts, genericReposts] = await Promise.all([
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [1], '#e': [eventId] }]),
nostr.query([{ kinds: [6], '#e': [eventId] }]),
nostr.query([{ kinds: [16], '#e': [eventId] }]),
]);
```
@@ -407,7 +522,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.
#### 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.
@@ -448,8 +563,7 @@ function useCalendarEvents() {
return useQuery({
queryKey: ['calendar-events'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }]);
// Filter events through validator to ensure they meet NIP-52 requirements
return events.filter(validateCalendarEvent);
@@ -478,7 +592,7 @@ function Post({ event }: { event: NostrEvent }) {
}
```
#### `NostrMetadata` type
### `NostrMetadata` type
```ts
/** Kind 0 metadata. */
@@ -650,7 +764,6 @@ The base Nostr protocol uses hex string identifiers when filtering by event IDs
// ❌ Wrong: naddr is not decoded
const events = await nostr.query(
[{ ids: [naddr] }],
{ signal }
);
```
@@ -678,7 +791,6 @@ const events = await nostr.query(
authors: [naddr.pubkey],
'#d': [naddr.identifier],
}],
{ signal }
);
```
@@ -783,73 +895,48 @@ export function Post(/* ...props */) {
}
```
### Adding 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"
/>
```
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
The project includes an `AppProvider` that manages global application state including theme and NIP-65 relay configuration. The default configuration includes:
```typescript
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.nostr.band",
relayMetadata: {
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,
},
};
```
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
The app uses NIP-65 compatible relay management with automatic sync when users log in. Local storage persists user preferences and relay configurations.
### 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
@@ -903,10 +990,9 @@ The router includes automatic scroll-to-top functionality and a 404 NotFound pag
### Empty States and No Content Found
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.
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.
```tsx
import { RelaySelector } from '@/components/RelaySelector';
import { Card, CardContent } from '@/components/ui/card';
// Empty state example
@@ -915,37 +1001,74 @@ import { Card, CardContent } from '@/components/ui/card';
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<p className="text-muted-foreground">
No results found. Try another relay?
No results found. Try checking your relay connections or wait a moment for content to load.
</p>
<RelaySelector className="w-full" />
</div>
</CardContent>
</Card>
</div>
```
## Design Customization
## CRITICAL Design Standards
**Tailor the site's look and feel based on the user's specific request.** This includes:
- Create breathtaking, immersive designs that feel like bespoke masterpieces, rivaling the polish of Apple, Stripe, or luxury brands
- 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
- **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.)
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
### Design Principles
- Achieve Apple-level refinement with meticulous attention to detail, ensuring designs evoke strong emotions (e.g., wonder, inspiration, energy) through color, motion, and composition
- Deliver fully functional interactive components with intuitive feedback states, ensuring every element has a clear purpose and enhances user engagement
- **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
- 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
To add custom fonts, follow these steps:
1. **Install a font package** using the `js-dev__npm_add_package` tool:
1. **Install a font package** using npm:
**Any Google Font can be installed** using the @fontsource packages. Examples:
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
- For Inter Variable: `@fontsource-variable/inter`
- For Roboto: `@fontsource/roboto`
- For Outfit Variable: `@fontsource-variable/outfit`
- For Poppins: `@fontsource/poppins`
- For Open Sans: `@fontsource/open-sans`
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
@@ -997,12 +1120,14 @@ When users specify color schemes:
- Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints
- 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
There is an important distinction between **writing new tests** and **running existing tests**:
### 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
@@ -1016,9 +1141,10 @@ There is an important distinction between **writing new tests** and **running ex
- 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** using `js-dev__run_script` tool with the "test" parameter
- **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
@@ -1052,10 +1178,32 @@ describe('MyComponent', () => {
});
```
## Testing Your Changes
## Validating Your Changes
**CRITICAL**: Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
**CRITICAL**: After making any code changes, you must validate your work by running available validation tools.
**Your task is not considered finished until this test passes without errors.**
**Your task is not considered finished until the code successfully type-checks and builds without errors.**
**This requirement applies regardless of whether you wrote new tests or not.** The test script validates the entire codebase, including TypeScript compilation, ESLint rules, and existing test suite.
### 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.
-1
View File
@@ -1 +0,0 @@
AGENTS.md
-1
View File
@@ -1 +0,0 @@
AGENTS.md
-1
View File
@@ -1 +0,0 @@
AGENTS.md
+236 -1
View File
@@ -1,3 +1,238 @@
# MKStack
Template for building Nostr client application with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
**The Complete Framework for Building Nostr Clients with AI**
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.
## 🚀 Quick Start
Build your Nostr app in 3 simple steps:
### 1. Install & Create
```bash
npm install -g @getstacks/stacks
stacks mkstack
```
### 2. Build with AI
```bash
stacks agent
# Tell Dork AI what you want: "Build a group chat application"
```
### 3. Deploy Instantly
```bash
npm run deploy
# ✅ App deployed to NostrDeploy.com!
```
## ✨ What Makes MKStack Special
- **🤖 AI-First Development**: Build complete Nostr apps with just one prompt using Dork AI agent
- **⚡ 8 Minutes Average**: From idea to deployed application in minutes, not months
- **🔗 50+ NIPs Supported**: Comprehensive Nostr protocol implementation
- **🎨 Beautiful UI**: 48+ shadcn/ui components with light/dark theme support
- **🔐 Built-in Security**: NIP-07 browser signing, NIP-44 encryption, event validation
- **💰 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
- **React 18.x**: Stable version with hooks, concurrent rendering, and improved performance
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
- **Vite**: Fast build tool and development server
- **shadcn/ui**: 48+ unstyled, accessible UI components built with Radix UI
- **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: Client-side routing with BrowserRouter
- **TanStack Query**: Data fetching, caching, and state management
- **TypeScript**: Type-safe JavaScript development
## 🎯 Real-World Examples
### Built with One Prompt
Each of these applications was created with just a single prompt to Dork AI:
- **Group Chat Application**: `"Build me a group chat application"`
- [Live Demo](https://groupchat-74z9j26wq-mks-projects-1f1254c4.vercel.app/)
- **Decentralized Goodreads**: `"Build a decentralized goodreads alternative. Use OpenLibrary API for book data."`
- [Live Demo](https://bookstr123-87phkwjcy-mks-projects-1f1254c4.vercel.app/)
- **Chess Game**: `"Build a chess game with NIP 64"`
- [Live Demo](https://chess-l0d7ms7m3-mks-projects-1f1254c4.vercel.app/chess)
### Production Apps
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
MKStack is open source and welcomes contributions. The framework is designed to be:
- **Extensible**: Easy to add new NIPs and features
- **Maintainable**: Clean architecture with TypeScript
- **Testable**: Comprehensive testing setup included
- **Documented**: Clear patterns and examples
## 📄 License
Open source - build amazing Nostr applications and help grow the decentralized web!
---
**"Vibed with MKStack"** - [Learn more about MKStack](https://soapbox.pub/mkstack)
*Build your Nostr app in minutes, not months. Start with AI, deploy instantly.*
-1
View File
@@ -17,7 +17,6 @@ export default tseslint.config(
globals: globals.browser,
},
linterOptions: {
noInlineConfig: true, // Prevents all eslint-disable comments
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
},
plugins: {
+9
View File
@@ -0,0 +1,9 @@
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"nostr": {
"type": "local",
"command": ["npx", "-y", "@nostrbook/mcp@latest"]
}
}
}
+246 -140
View File
@@ -10,9 +10,9 @@
"dependencies": {
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
"@hookform/resolvers": "^5.2.2",
"@nostrify/nostrify": "^0.49.2",
"@nostrify/react": "^0.2.24",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -43,11 +43,13 @@
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"buffer": "^6.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"date-fns": "^3.6.0",
"embla-carousel-react": "^8.3.0",
"idb": "^8.0.3",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"nostr-tools": "^2.13.0",
@@ -55,7 +57,7 @@
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.0",
"react-hook-form": "^7.71.1",
"react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.3",
"react-router-dom": "^6.26.2",
@@ -63,8 +65,7 @@
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3",
"webln": "^0.3.2",
"zod": "^3.25.71"
"zod": "^4.3.6"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
@@ -78,6 +79,7 @@
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react-swc": "^3.5.0",
"@webbtc/webln-types": "^3.0.0",
"autoprefixer": "^10.4.20",
"eslint": "^9.9.0",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
@@ -984,12 +986,15 @@
}
},
"node_modules/@hookform/resolvers": {
"version": "3.10.0",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-3.10.0.tgz",
"integrity": "sha512-79Dv+3mDF7i+2ajj7SkypSKHhl1cbln1OGavqrsF7p6mbUv11xpqpacPsGDCTRvCSjEEIez2ef1NveSVL3b0Ag==",
"version": "5.2.2",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-5.2.2.tgz",
"integrity": "sha512-A/IxlMLShx3KjV/HeTcTfaMxdwy690+L/ZADoeaTltLx+CVuzkeVIPuybK3jrRfw7YZnmdKsVVHAlEPIAEUNlA==",
"license": "MIT",
"dependencies": {
"@standard-schema/utils": "^0.3.0"
},
"peerDependencies": {
"react-hook-form": "^7.0.0"
"react-hook-form": "^7.55.0"
}
},
"node_modules/@html-eslint/eslint-plugin": {
@@ -1170,35 +1175,6 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@jsr/nostrify__nostrify": {
"version": "0.46.4",
"resolved": "https://npm.jsr.io/~/11/@jsr/nostrify__nostrify/0.46.4.tgz",
"integrity": "sha512-bYuYkw9+jnHIDEJD6i+w0p8xV1oBLr1RF5rS3qF2yTz1b8i50dXKMO2cLObjalAAO3RYbnib3l85t1ZgWLCzAA==",
"dependencies": {
"@jsr/nostrify__types": "^0.36.0",
"@jsr/scure__base": "^1.2.4",
"@jsr/std__encoding": "^0.224.1",
"lru-cache": "^10.2.0",
"nostr-tools": "^2.13.0",
"websocket-ts": "^2.2.1",
"zod": "^3.23.8"
}
},
"node_modules/@jsr/nostrify__types": {
"version": "0.36.0",
"resolved": "https://npm.jsr.io/~/11/@jsr/nostrify__types/0.36.0.tgz",
"integrity": "sha512-kDjFf1nJMhZafULtH2GW+TWjs85J0aDxYYLpwBDQugDVsFqG2kLbxnoE2NtMJCIMNk1vUaipUHeil//4fY/d2w=="
},
"node_modules/@jsr/scure__base": {
"version": "1.2.5",
"resolved": "https://npm.jsr.io/~/11/@jsr/scure__base/1.2.5.tgz",
"integrity": "sha512-ino21k5s2kamz+uhAL/N3iI5vJ7x3zTtrzhM52iXBth41KxkFSIDiOlQNbMj4/jTih27jmS6Mi4Xke5vKTdNIA=="
},
"node_modules/@jsr/std__encoding": {
"version": "0.224.3",
"resolved": "https://npm.jsr.io/~/11/@jsr/std__encoding/0.224.3.tgz",
"integrity": "sha512-zAuX2QV1zwJ5RSmrnDGVerAtN3pBXpYYNlGzhERW9AiQ1UJd2/xruyB3i5NdTWy2OK2pjETswOj+0+prYTPlxQ=="
},
"node_modules/@noble/ciphers": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-0.5.3.tgz",
@@ -1280,31 +1256,64 @@
}
},
"node_modules/@nostrify/nostrify": {
"name": "@jsr/nostrify__nostrify",
"version": "0.46.4",
"resolved": "https://npm.jsr.io/~/11/@jsr/nostrify__nostrify/0.46.4.tgz",
"integrity": "sha512-bYuYkw9+jnHIDEJD6i+w0p8xV1oBLr1RF5rS3qF2yTz1b8i50dXKMO2cLObjalAAO3RYbnib3l85t1ZgWLCzAA==",
"version": "0.49.2",
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.49.2.tgz",
"integrity": "sha512-JMiGifc/XX4QhzFnmJVw00UjcOS295w/NYth9mJH0cbS0EqPQ/4HBn33P0DGW3iE5EAkk+n98cnwzYeIPtn9pQ==",
"dependencies": {
"@jsr/nostrify__types": "^0.36.0",
"@jsr/scure__base": "^1.2.4",
"@jsr/std__encoding": "^0.224.1",
"@nostrify/types": "0.36.9",
"@scure/base": "^2.0.0",
"@smithy/util-base64": "^4.3.0",
"@smithy/util-hex-encoding": "^4.2.0",
"@types/node": "^24.1.0",
"lru-cache": "^10.2.0",
"nostr-tools": "^2.13.0",
"websocket-ts": "^2.2.1",
"zod": "^3.23.8"
"ws": "^8.18.3",
"zod": "^4.3.6"
}
},
"node_modules/@nostrify/react": {
"name": "@jsr/nostrify__react",
"version": "0.2.8",
"resolved": "https://npm.jsr.io/~/11/@jsr/nostrify__react/0.2.8.tgz",
"integrity": "sha512-9sCsMm1uwuGWU+NhgFf6LS/4JzeRXnGOz+ocA5X3/ncvxZhidPOEAU39QyygRLFo/JYG8OC5wlyH8w0Uejq+VQ==",
"dependencies": {
"@jsr/nostrify__nostrify": "^0.46.4",
"nostr-tools": "^2.13.0",
"react": "^18.0.0"
"node_modules/@nostrify/nostrify/node_modules/@scure/base": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@scure/base/-/base-2.0.0.tgz",
"integrity": "sha512-3E1kpuZginKkek01ovG8krQ0Z44E3DHPjc5S2rjJw9lZn3KSQOs8S7wqikF/AH7iRanHypj85uGyxk0XAyC37w==",
"license": "MIT",
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@nostrify/nostrify/node_modules/@types/node": {
"version": "24.10.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.4.tgz",
"integrity": "sha512-vnDVpYPMzs4wunl27jHrfmwojOGKya0xyM3sH+UE5iv5uPS6vX7UIoh6m+vQc5LGBq52HBKPIn/zcSZVzeDEZg==",
"license": "MIT",
"dependencies": {
"undici-types": "~7.16.0"
}
},
"node_modules/@nostrify/nostrify/node_modules/undici-types": {
"version": "7.16.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",
"integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",
"license": "MIT"
},
"node_modules/@nostrify/react": {
"version": "0.2.24",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.24.tgz",
"integrity": "sha512-LdB6UjNKZ/Xhz+jj8CRCcudHt4WNNVZMgJsiO+XAloqWE8oPRf1G2i1k6I/eF6buCJokKE1PFUTMlyieOpIXNQ==",
"dependencies": {
"@nostrify/nostrify": "0.49.2",
"@nostrify/types": "0.36.9",
"@tanstack/react-query": "^5.69.0",
"nostr-tools": "^2.13.0",
"react": "^18.0.0",
"react-dom": "^18.0.0"
}
},
"node_modules/@nostrify/types": {
"version": "0.36.9",
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.9.tgz",
"integrity": "sha512-tMx/r0W+QoVRRgs8d6ltaSgrftasOXuFsi33kW8WirswCy2b3UR1tqRgc0iBU9zRa9XR0nlej/wJZW+6wUFi+Q=="
},
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
@@ -2670,9 +2679,9 @@
"license": "MIT"
},
"node_modules/@remix-run/router": {
"version": "1.23.0",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.0.tgz",
"integrity": "sha512-O3rHJzAQKamUz1fvE0Qaw0xSFqsA/yafi2iqeE0pvdFtCO1viYx8QL6f3Ln/aCCTLxs68SLf0KPM9eSeM8yBnA==",
"version": "1.23.2",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz",
"integrity": "sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w==",
"license": "MIT",
"engines": {
"node": ">=14.0.0"
@@ -2725,7 +2734,6 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2739,7 +2747,6 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2753,7 +2760,6 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2767,7 +2773,6 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2781,7 +2786,6 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2795,7 +2799,6 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2809,7 +2812,6 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2823,7 +2825,6 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2837,7 +2838,6 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2851,7 +2851,6 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2865,7 +2864,6 @@
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2879,7 +2877,6 @@
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2893,7 +2890,6 @@
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2907,7 +2903,6 @@
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2921,7 +2916,6 @@
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2935,7 +2929,6 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2949,7 +2942,6 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2963,7 +2955,6 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2977,7 +2968,6 @@
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2991,7 +2981,6 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -3049,6 +3038,76 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@smithy/is-array-buffer": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.0.tgz",
"integrity": "sha512-DZZZBvC7sjcYh4MazJSGiWMI2L7E0oCiRHREDzIxi/M2LY79/21iXt6aPLHge82wi5LsuRF5A06Ds3+0mlh6CQ==",
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/util-base64": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.3.0.tgz",
"integrity": "sha512-GkXZ59JfyxsIwNTWFnjmFEI8kZpRNIBfxKjv09+nkAWPt/4aGaEWMM04m4sxgNVWkbt2MdSvE3KF/PfX4nFedQ==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/util-buffer-from": "^4.2.0",
"@smithy/util-utf8": "^4.2.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/util-buffer-from": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.2.0.tgz",
"integrity": "sha512-kAY9hTKulTNevM2nlRtxAG2FQ3B2OR6QIrPY3zE5LqJy1oxzmgBGsHLWTcNhWXKchgA0WHW+mZkQrng/pgcCew==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/is-array-buffer": "^4.2.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/util-hex-encoding": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.2.0.tgz",
"integrity": "sha512-CCQBwJIvXMLKxVbO88IukazJD9a4kQ9ZN7/UMGBjBcJYvatpWk+9g870El4cB8/EJxfe+k+y0GmR9CAzkF+Nbw==",
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/util-utf8": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.2.0.tgz",
"integrity": "sha512-zBPfuzoI8xyBtR2P6WQj63Rz8i3AmfAaJLuNG8dWsfvPe8lO4aCPYLn879mEgHndZH1zQ2oXmG8O1GGzzaoZiw==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/util-buffer-from": "^4.2.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@standard-schema/utils": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
"license": "MIT"
},
"node_modules/@swc/core": {
"version": "1.11.24",
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz",
@@ -3416,15 +3475,6 @@
"license": "MIT",
"peer": true
},
"node_modules/@types/chrome": {
"version": "0.0.74",
"resolved": "https://registry.npmjs.org/@types/chrome/-/chrome-0.0.74.tgz",
"integrity": "sha512-hzosS5CkQcIKCgxcsV2AzbJ36KNxG/Db2YEN/erEu7Boprg+KpMDLBQqKFmSo+JkQMGqRcicUyqCowJpuT+C6A==",
"license": "MIT",
"dependencies": {
"@types/filesystem": "*"
}
},
"node_modules/@types/d3-array": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.1.tgz",
@@ -3494,21 +3544,6 @@
"integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==",
"license": "MIT"
},
"node_modules/@types/filesystem": {
"version": "0.0.36",
"resolved": "https://registry.npmjs.org/@types/filesystem/-/filesystem-0.0.36.tgz",
"integrity": "sha512-vPDXOZuannb9FZdxgHnqSwAG/jvdGM8Wq+6N4D/d80z+D4HWH+bItqsZaVRQykAn6WEVeEkLm2oQigyHtgb0RA==",
"license": "MIT",
"dependencies": {
"@types/filewriter": "*"
}
},
"node_modules/@types/filewriter": {
"version": "0.0.33",
"resolved": "https://registry.npmjs.org/@types/filewriter/-/filewriter-0.0.33.tgz",
"integrity": "sha512-xFU8ZXTw4gd358lb2jw25nxY9QAgqn2+bKKjKOYfNCzN4DKCFetK7sPtrlpg66Ywe3vWY9FNxprZawAh9wfJ3g==",
"license": "MIT"
},
"node_modules/@types/json-schema": {
"version": "7.0.15",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
@@ -3929,6 +3964,17 @@
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@webbtc/webln-types": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@webbtc/webln-types/-/webln-types-3.0.0.tgz",
"integrity": "sha512-aXfTHLKz5lysd+6xTeWl+qHNh/p3qVYbeLo+yDN5cUDmhie2ZoGvkppfWxzbGkcFBzb6dJyQ2/i2cbmDHas+zQ==",
"dev": true,
"license": "MIT",
"funding": {
"type": "lightning",
"url": "lightning:[email protected]"
}
},
"node_modules/acorn": {
"version": "8.15.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
@@ -4129,6 +4175,26 @@
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"license": "MIT"
},
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/binary-extensions": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
@@ -4197,6 +4263,30 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
"node_modules/buffer": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.1",
"ieee754": "^1.2.1"
}
},
"node_modules/cac": {
"version": "6.7.14",
"resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
@@ -5329,9 +5419,9 @@
}
},
"node_modules/glob": {
"version": "10.4.5",
"resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz",
"integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==",
"version": "10.5.0",
"resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
"integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
"license": "ISC",
"dependencies": {
"foreground-child": "^3.1.0",
@@ -5486,6 +5576,32 @@
"node": ">=0.10.0"
}
},
"node_modules/idb": {
"version": "8.0.3",
"resolved": "https://registry.npmjs.org/idb/-/idb-8.0.3.tgz",
"integrity": "sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg==",
"license": "ISC"
},
"node_modules/ieee754": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "BSD-3-Clause"
},
"node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
@@ -5662,9 +5778,9 @@
"license": "MIT"
},
"node_modules/js-yaml": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz",
"integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==",
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -6613,9 +6729,9 @@
}
},
"node_modules/react-hook-form": {
"version": "7.56.1",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz",
"integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==",
"version": "7.71.1",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.71.1.tgz",
"integrity": "sha512-9SUJKCGKo8HUSsCO+y0CtqkqI5nNuaDqTxyqPsZPqIwudpj4rCrAz/jZV+jn57bx5gtZKOh3neQu94DXMc+w5w==",
"license": "MIT",
"engines": {
"node": ">=18.0.0"
@@ -6707,12 +6823,12 @@
}
},
"node_modules/react-router": {
"version": "6.30.0",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.0.tgz",
"integrity": "sha512-D3X8FyH9nBcTSHGdEKurK7r8OYE1kKFn3d/CF+CoxbSHkxU7o37+Uh7eAHRXr6k2tSExXYO++07PeXJtA/dEhQ==",
"version": "6.30.3",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.3.tgz",
"integrity": "sha512-XRnlbKMTmktBkjCLE8/XcZFlnHvr2Ltdr1eJX4idL55/9BbORzyZEaIkBFDhFGCEWBBItsVrDxwx3gnisMitdw==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.0"
"@remix-run/router": "1.23.2"
},
"engines": {
"node": ">=14.0.0"
@@ -6722,13 +6838,13 @@
}
},
"node_modules/react-router-dom": {
"version": "6.30.0",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.0.tgz",
"integrity": "sha512-x30B78HV5tFk8ex0ITwzC9TTZMua4jGyA9IUlH1JLQYQTFyxr/ZxwOJq7evg1JX1qGVUcvhsmQSKdPncQrjTgA==",
"version": "6.30.3",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.3.tgz",
"integrity": "sha512-pxPcv1AczD4vso7G4Z3TKcvlxK7g7TNt3/FNGMhfqyntocvYKj+GCatfigGDjbLozC4baguJ0ReCigoDJXb0ag==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.0",
"react-router": "6.30.0"
"@remix-run/router": "1.23.2",
"react-router": "6.30.3"
},
"engines": {
"node": ">=14.0.0"
@@ -7792,9 +7908,9 @@
}
},
"node_modules/vite": {
"version": "6.3.5",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz",
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
"version": "6.4.1",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz",
"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -8011,15 +8127,6 @@
"node": ">=12"
}
},
"node_modules/webln": {
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/webln/-/webln-0.3.2.tgz",
"integrity": "sha512-YYT83aOCLup2AmqvJdKtdeBTaZpjC6/JDMe8o6x1kbTYWwiwrtWHyO//PAsPixF3jwFsAkj5DmiceB6w/QSe7Q==",
"license": "MIT",
"dependencies": {
"@types/chrome": "^0.0.74"
}
},
"node_modules/webpack-virtual-modules": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz",
@@ -8206,10 +8313,9 @@
}
},
"node_modules/ws": {
"version": "8.18.2",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.2.tgz",
"integrity": "sha512-DMricUmwGZUVr++AEAe2uiVM7UoO9MAVZMDu05UQOaUII0lp+zOzLLU4Xqh/JvTqklB1T4uELaaPBKyjE1r4fQ==",
"dev": true,
"version": "8.18.3",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
@@ -8404,9 +8510,9 @@
}
},
"node_modules/zod": {
"version": "3.25.71",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.71.tgz",
"integrity": "sha512-BsBc/NPk7h8WsUWYWYL+BajcJPY8YhjelaWu2NMLuzgraKAz4Lb4/6K11g9jpuDetjMiqhZ6YaexFLOC0Ogi3Q==",
"version": "4.3.6",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
+13 -12
View File
@@ -4,17 +4,16 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "npm i && vite",
"build": "npm i && vite build && cp dist/index.html dist/404.html",
"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"
"dev": "npm i --silent && vite",
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"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!'"
},
"dependencies": {
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
"@getalby/sdk": "^7.0.0",
"@hookform/resolvers": "^5.2.2",
"@nostrify/nostrify": "^0.49.2",
"@nostrify/react": "^0.2.24",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -45,19 +44,21 @@
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"buffer": "^6.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"date-fns": "^3.6.0",
"embla-carousel-react": "^8.3.0",
"idb": "^8.0.3",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"nostr-tools": "^2.13.0",
"nostr-tools": "^2.21.0",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.0",
"react-hook-form": "^7.71.1",
"react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.3",
"react-router-dom": "^6.26.2",
@@ -65,8 +66,7 @@
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3",
"webln": "^0.3.2",
"zod": "^3.25.71"
"zod": "^4.3.6"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
@@ -80,6 +80,7 @@
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react-swc": "^3.5.0",
"@webbtc/webln-types": "^3.0.0",
"autoprefixer": "^10.4.20",
"eslint": "^9.9.0",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
+2 -1
View File
@@ -1 +1,2 @@
/* /index.html 200
/assets/* /assets/:splat 200
/* /index.html 200
+2
View File
@@ -0,0 +1,2 @@
User-agent: *
Allow: /
+11 -9
View File
@@ -6,6 +6,7 @@ import { createHead, UnheadProvider } from '@unhead/react/client';
import { InferSeoMetaPlugin } from '@unhead/addons';
import { Suspense } from 'react';
import NostrProvider from '@/components/NostrProvider';
import { NostrSync } from '@/components/NostrSync';
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { NostrLoginProvider } from '@nostrify/react/login';
@@ -32,23 +33,24 @@ const queryClient = new QueryClient({
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.primal.net",
relayMetadata: {
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() {
return (
<UnheadProvider head={head}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NostrSync />
<NWCProvider>
<TooltipProvider>
<Toaster />
+22 -14
View File
@@ -1,7 +1,7 @@
import { ReactNode, useEffect } from 'react';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext';
interface AppProviderProps {
children: ReactNode;
@@ -9,46 +9,54 @@ interface AppProviderProps {
storageKey: string;
/** Default app configuration */
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
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
const AppConfigSchema = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
});
relayMetadata: RelayMetadataSchema,
}) satisfies z.ZodType<AppConfig>;
export function AppProvider(props: AppProviderProps) {
const {
children,
storageKey,
defaultConfig,
presetRelays,
} = props;
// App configuration state with localStorage persistence
const [config, setConfig] = useLocalStorage<AppConfig>(
const [rawConfig, setConfig] = useLocalStorage<Partial<AppConfig>>(
storageKey,
defaultConfig,
{},
{
serialize: JSON.stringify,
deserialize: (value: string) => {
const parsed = JSON.parse(value);
return AppConfigSchema.parse(parsed);
return AppConfigSchema.partial().parse(parsed);
}
}
);
// Generic config updater with callback pattern
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
const updateConfig = (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => {
setConfig(updater);
};
const config = { ...defaultConfig, ...rawConfig };
const appContextValue: AppContextType = {
config,
updateConfig,
presetRelays,
};
// Apply theme effects to document
@@ -88,11 +96,11 @@ function useApplyTheme(theme: Theme) {
if (theme !== 'system') return;
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
root.classList.add(systemTheme);
};
File diff suppressed because it is too large. Load diff
+25 -19
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useRef } from 'react';
import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrEvent, NostrFilter, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrContext } from '@nostrify/react';
import { useQueryClient } from '@tanstack/react-query';
import { useAppContext } from '@/hooks/useAppContext';
@@ -10,7 +10,7 @@ interface NostrProviderProps {
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const { children } = props;
const { config, presetRelays } = useAppContext();
const { config } = useAppContext();
const queryClient = useQueryClient();
@@ -18,13 +18,13 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const pool = useRef<NPool | undefined>(undefined);
// Use refs so the pool always has the latest data
const relayUrl = useRef<string>(config.relayUrl);
const relayMetadata = useRef(config.relayMetadata);
// Update refs when config changes
// Invalidate Nostr queries when relay metadata changes
useEffect(() => {
relayUrl.current = config.relayUrl;
queryClient.resetQueries();
}, [config.relayUrl, queryClient]);
relayMetadata.current = config.relayMetadata;
queryClient.invalidateQueries({ queryKey: ['nostr'] });
}, [config.relayMetadata, queryClient]);
// Initialize NPool only once
if (!pool.current) {
@@ -32,21 +32,27 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
open(url: string) {
return new NRelay1(url);
},
reqRouter(filters) {
return new Map([[relayUrl.current, filters]]);
reqRouter(filters: NostrFilter[]) {
const routes = new Map<string, NostrFilter[]>();
// 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) {
// Publish to the selected relay
const allRelays = new Set<string>([relayUrl.current]);
// Get write relays from metadata
const writeRelays = relayMetadata.current.relays
.filter(r => r.write)
.map(r => r.url);
// Also publish to the preset relays, capped to 5
for (const { url } of (presetRelays ?? [])) {
allRelays.add(url);
if (allRelays.size >= 5) {
break;
}
}
const allRelays = new Set<string>(writeRelays);
return [...allRelays];
},
+62
View File
@@ -0,0 +1,62 @@
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;
}
+7 -2
View File
@@ -45,7 +45,7 @@ export function NoteContent({
href={url}
target="_blank"
rel="noopener noreferrer"
className="text-blue-500 hover:underline"
className="text-blue-500 hover:underline break-all"
>
{url}
</a>
@@ -61,13 +61,18 @@ export function NoteContent({
parts.push(
<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 {
// For other types, just show as a link
parts.push(
<Link
key={`nostr-${keyCounter++}`}
to={`/${nostrId}`}
className="text-blue-500 hover:underline"
className="text-blue-500 hover:underline break-all"
>
{fullMatch}
</Link>
+286
View File
@@ -0,0 +1,286 @@
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>
);
}
-174
View File
@@ -1,174 +0,0 @@
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>
);
}
+9 -11
View File
@@ -29,6 +29,7 @@ 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;
@@ -68,8 +69,7 @@ AddWalletContent.displayName = 'AddWalletContent';
// Extracted WalletContent to prevent re-renders
const WalletContent = forwardRef<HTMLDivElement, {
hasWebLN: boolean;
isDetecting: boolean;
webln: WebLNProvider | null;
hasNWC: boolean;
connections: NWCConnection[];
connectionInfo: Record<string, NWCInfo>;
@@ -78,8 +78,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
handleRemoveConnection: (cs: string) => void;
setAddDialogOpen: (open: boolean) => void;
}>(({
hasWebLN,
isDetecting,
webln,
hasNWC,
connections,
connectionInfo,
@@ -103,9 +102,9 @@ const WalletContent = forwardRef<HTMLDivElement, {
</div>
</div>
<div className="flex items-center gap-2">
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
{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>
@@ -191,7 +190,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
)}
</div>
{/* Help */}
{!hasWebLN && connections.length === 0 && (
{!webln && connections.length === 0 && (
<>
<Separator />
<div className="text-center py-4 space-y-2">
@@ -222,7 +221,7 @@ export function WalletModal({ children, className }: WalletModalProps) {
setActiveConnection
} = useNWC();
const { hasWebLN, isDetecting } = useWallet();
const { webln } = useWallet();
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
const { toast } = useToast();
@@ -263,8 +262,7 @@ export function WalletModal({ children, className }: WalletModalProps) {
};
const walletContentProps = {
hasWebLN,
isDetecting,
webln,
hasNWC,
connections,
connectionInfo,
+6 -13
View File
@@ -33,6 +33,7 @@ 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;
@@ -55,7 +56,7 @@ interface ZapContentProps {
isZapping: boolean;
qrCodeUrl: string;
copied: boolean;
hasWebLN: boolean;
webln: WebLNProvider | null;
handleZap: () => void;
handleCopy: () => void;
openInWallet: () => void;
@@ -73,7 +74,7 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
isZapping,
qrCodeUrl,
copied,
hasWebLN,
webln,
handleZap,
handleCopy,
openInWallet,
@@ -138,7 +139,7 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
{/* Payment buttons */}
<div className="space-y-3 mt-4">
{hasWebLN && (
{webln && (
<Button
onClick={() => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
@@ -234,13 +235,12 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
));
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, hasWebLN, detectWebLN } = useWallet();
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>('');
@@ -255,13 +255,6 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
}
}, [target]);
// Detect WebLN when dialog opens
useEffect(() => {
if (open && !hasWebLN) {
detectWebLN();
}
}, [open, hasWebLN, detectWebLN]);
// Generate QR code
useEffect(() => {
let isCancelled = false;
@@ -345,7 +338,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
isZapping,
qrCodeUrl,
copied,
hasWebLN,
webln,
handleZap,
handleCopy,
openInWallet,
+1 -15
View File
@@ -1,7 +1,7 @@
// 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.
import { ChevronDown, LogOut, UserIcon, UserPlus, Wallet } from 'lucide-react';
import { ChevronDown, LogOut, UserIcon, UserPlus } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
@@ -10,8 +10,6 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { RelaySelector } from '@/components/RelaySelector';
import { WalletModal } from '@/components/WalletModal';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName';
@@ -43,9 +41,6 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</button>
</DropdownMenuTrigger>
<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>
{otherUsers.map((user) => (
<DropdownMenuItem
@@ -64,15 +59,6 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<WalletModal>
<DropdownMenuItem
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
onSelect={(e) => e.preventDefault()}
>
<Wallet className='w-4 h-4' />
<span>Wallet Settings</span>
</DropdownMenuItem>
</WalletModal>
<DropdownMenuItem
onClick={onAddAccountClick}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
+1 -5
View File
@@ -2,7 +2,6 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { useState } from 'react';
import { User, UserPlus } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
@@ -34,15 +33,13 @@ export function LoginArea({ className }: LoginAreaProps) {
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'
>
<User className='w-4 h-4' />
<span className='truncate'>Log in</span>
</Button><Button
onClick={() => setSignupDialogOpen(true)}
variant="outline"
className="flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all"
>
<UserPlus className="w-4 h-4" />
<span>Sign Up</span>
<span>Sign up</span>
</Button>
</div>
)}
@@ -51,7 +48,6 @@ export function LoginArea({ className }: LoginAreaProps) {
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/>
<SignupDialog
+151 -187
View File
@@ -2,20 +2,20 @@
// 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 { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react';
import { Upload, AlertTriangle, ChevronDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
import { Dialog, DialogContent, DialogHeader } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { useLoginActions } from '@/hooks/useLoginActions';
import { cn } from '@/lib/utils';
import { DialogTitle } from '@radix-ui/react-dialog';
interface LoginDialogProps {
isOpen: boolean;
onClose: () => void;
onLogin: () => void;
onSignup?: () => void;
}
const validateNsec = (nsec: string) => {
@@ -26,7 +26,7 @@ const validateBunkerUri = (uri: string) => {
return uri.startsWith('bunker://');
};
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) => {
const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState('');
@@ -170,203 +170,167 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
reader.readAsText(file);
};
const handleSignupClick = () => {
onClose();
if (onSignup) {
onSignup();
}
};
const hasExtension = 'nostr' in window;
const [isMoreOptionsOpen, setIsMoreOptionsOpen] = useState(false);
const defaultTab = 'nostr' in window ? 'extension' : 'key';
const renderTabs = () => (
<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 (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl overflow-y-scroll")}
>
<DialogHeader className={cn('px-6 pt-6 pb-1 relative')}>
<DialogDescription className="text-center">
Sign up or log in to continue
</DialogDescription>
<DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-6 overflow-hidden rounded-2xl overflow-y-auto">
<DialogHeader className="px-6 pt-6">
<DialogTitle className="text-lg font-semibold leading-none tracking-tight text-center">
Log in
</DialogTitle>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1'>
{/* Prominent Sign Up Section */}
<div className='relative p-4 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 border border-blue-200 dark:border-blue-800 overflow-hidden'>
<div className='relative z-10 text-center space-y-3'>
<div className='flex justify-center items-center gap-2 mb-2'>
<Sparkles className='w-5 h-5 text-blue-600' />
<span className='font-semibold text-blue-800 dark:text-blue-200'>
New to Nostr?
</span>
</div>
<p className='text-sm text-blue-700 dark:text-blue-300'>
Create a new account to get started. It's free and open.
</p>
<Button
onClick={handleSignupClick}
className='w-full rounded-full py-3 text-base font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg border-0'
>
<UserPlus className='w-4 h-4 mr-2' />
<span>Sign Up</span>
</Button>
</div>
</div>
{/* Divider */}
<div className='relative'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-gray-300 dark:border-gray-600'></div>
</div>
<div className='relative flex justify-center text-sm'>
<span className='px-3 bg-background text-muted-foreground'>
<span>Or log in</span>
</span>
</div>
</div>
<div className="flex size-40 text-8xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
🔑
</div>
{/* Login Methods */}
<Tabs defaultValue={defaultTab} className="w-full">
<TabsList className="grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4">
<TabsTrigger value="extension" className="flex items-center gap-2">
<Shield className="w-4 h-4" />
<span>Extension</span>
</TabsTrigger>
<TabsTrigger value="key" className="flex items-center gap-2">
<KeyRound className="w-4 h-4" />
<span>Key</span>
</TabsTrigger>
<TabsTrigger value="bunker" className="flex items-center gap-2">
<Cloud className="w-4 h-4" />
<span>Bunker</span>
</TabsTrigger>
</TabsList>
<TabsContent value='extension' className='space-y-3 bg-muted'>
<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>
)}
<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>
<div className="flex justify-center">
<Button
className='w-full rounded-full py-4'
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
</div>
</div>
</TabsContent>
<Button
className="w-full h-12 px-9"
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Log in with Extension'}
</Button>
</div>
)}
<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'>
Secret Key (nsec)
</label>
<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>
{/* Tabs - wrapped in collapsible if extension is available, otherwise shown directly */}
{hasExtension ? (
<Collapsible className="space-y-4" open={isMoreOptionsOpen} onOpenChange={setIsMoreOptionsOpen}>
<CollapsibleTrigger asChild>
<button className="w-full flex items-center justify-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors">
<span>More Options</span>
<ChevronDown className={`w-4 h-4 transition-transform ${isMoreOptionsOpen ? 'rotate-180' : ''}`} />
</button>
</CollapsibleTrigger>
<Button
className='w-full rounded-full py-3'
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
>
{isLoading ? 'Verifying...' : 'Log In'}
</Button>
<div className='relative'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-muted'></div>
</div>
<div className='relative flex justify-center text-xs'>
<span className='px-2 bg-background text-muted-foreground'>
or
</span>
</div>
</div>
<div className='text-center'>
<input
type='file'
accept='.txt'
className='hidden'
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
variant='outline'
className='w-full'
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
>
<Upload className='w-4 h-4 mr-2' />
{isFileLoading ? 'Reading File...' : 'Upload Your Key File'}
</Button>
{errors.file && (
<p className="text-sm text-red-500 mt-2">{errors.file}</p>
)}
</div>
</div>
</TabsContent>
<TabsContent value='bunker' className='space-y-3 bg-muted'>
<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);
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>
<div className="flex justify-center">
<Button
className='w-full rounded-full py-4'
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim()}
>
{isLoading ? 'Connecting...' : 'Login with Bunker'}
</Button>
</div>
</TabsContent>
</Tabs>
<CollapsibleContent>
{renderTabs()}
</CollapsibleContent>
</Collapsible>
) : (
renderTabs()
)}
</div>
</DialogContent>
</Dialog>
+88 -435
View File
@@ -2,35 +2,26 @@
// 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 { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, CheckCircle, Upload, Globe } from 'lucide-react';
import { Download, Upload, Eye, EyeOff } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Card, CardContent } from '@/components/ui/card';
import { toast } from '@/hooks/useToast';
import { useLoginActions } from '@/hooks/useLoginActions';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useUploadFile } from '@/hooks/useUploadFile';
import { generateSecretKey, nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils';
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
interface SignupDialogProps {
isOpen: boolean;
onClose: () => void;
onComplete?: () => void;
}
const sanitizeFilename = (filename: string) => {
return filename.replace(/[^a-z0-9_.-]/gi, '_');
}
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete }) => {
const [step, setStep] = useState<'welcome' | 'generate' | 'download' | 'profile' | 'done'>('welcome');
const [isLoading, setIsLoading] = useState(false);
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const [step, setStep] = useState<'generate' | 'download' | 'profile'>('generate');
const [nsec, setNsec] = useState('');
const [showSparkles, setShowSparkles] = useState(false);
const [keySecured, setKeySecured] = useState<'none' | 'downloaded'>('none');
const [showKey, setShowKey] = useState(false);
const [profileData, setProfileData] = useState({
name: '',
about: '',
@@ -43,34 +34,9 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
// Generate a proper nsec key using nostr-tools
const generateKey = () => {
setIsLoading(true);
setShowSparkles(true);
// Add a dramatic pause for the key generation effect
setTimeout(() => {
try {
// Generate a new secret key
const sk = generateSecretKey();
// Convert to nsec format
setNsec(nip19.nsecEncode(sk));
setStep('download');
toast({
title: 'Your Secret Key is Ready!',
description: 'A new secret key has been generated for you.',
});
} catch {
toast({
title: 'Error',
description: 'Failed to generate key. Please try again.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
setShowSparkles(false);
}
}, 2000);
const sk = generateSecretKey();
setNsec(nip19.nsecEncode(sk));
setStep('download');
};
const downloadKey = () => {
@@ -79,8 +45,14 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob);
// Sanitize filename
const filename = sanitizeFilename('nostr-nsec-key.txt');
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');
@@ -94,32 +66,13 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
// Mark as secured
setKeySecured('downloaded');
toast({
title: 'Secret Key Saved!',
description: 'Your key has been safely stored.',
});
} catch {
toast({
title: 'Download failed',
description: 'Could not download the key file. Please copy it manually.',
variant: 'destructive',
});
}
};
const finishKeySetup = () => {
try {
// Continue to profile step
login.nsec(nsec);
setStep('profile');
} catch {
toast({
title: 'Login Failed',
description: 'Failed to login with the generated key. Please try again.',
title: 'Download failed',
description: 'Could not download the key file. Please copy it manually.',
variant: 'destructive',
});
}
@@ -158,10 +111,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
const url = tags[0]?.[1];
if (url) {
setProfileData(prev => ({ ...prev, picture: url }));
toast({
title: 'Avatar uploaded!',
description: 'Your avatar has been uploaded successfully.',
});
}
} catch {
toast({
@@ -173,9 +122,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
};
const finishSignup = async (skipProfile = false) => {
// Mark signup completion time for fallback welcome modal
localStorage.setItem('signup_completed', Date.now().toString());
try {
// Publish profile if user provided information
if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) {
@@ -188,30 +134,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
kind: 0,
content: JSON.stringify(metadata),
});
toast({
title: 'Profile Created!',
description: 'Your profile has been set up.',
});
}
// Close signup and show welcome modal
onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
} else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
}
} catch {
toast({
@@ -219,372 +141,111 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
description: 'Your account was created but profile setup failed. You can update it later.',
variant: 'destructive',
});
// Still proceed to completion even if profile failed
} finally {
onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
} else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
}
}
};
const getTitle = () => {
if (step === 'welcome') return (
<span className="flex items-center justify-center gap-2">
Create Your Account
</span>
);
if (step === 'generate') return (
<span className="flex items-center justify-center gap-2">
Generating Your Key
</span>
);
if (step === 'download') return (
<span className="flex items-center justify-center gap-2">
Secret Key
</span>
);
if (step === 'profile') return (
<span className="flex items-center justify-center gap-2">
Create Your Profile
</span>
);
return (
<span className="flex items-center justify-center gap-2">
Welcome!
</span>
);
if (step === 'generate') return 'Sign up';
if (step === 'download') return 'Secret Key';
if (step === 'profile') return 'Create Your Profile';
};
// Reset state when dialog opens
useEffect(() => {
if (isOpen) {
setStep('welcome');
setIsLoading(false);
setStep('generate');
setNsec('');
setShowSparkles(false);
setKeySecured('none');
setShowKey(false);
setProfileData({ name: '', about: '', picture: '' });
}
}, [isOpen]);
// Add sparkle animation effect
useEffect(() => {
if (showSparkles) {
const interval = setInterval(() => {
// This will trigger re-renders for sparkle animation
}, 100);
return () => clearInterval(interval);
}
}, [showSparkles]);
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl flex flex-col")}
>
<DialogHeader className={cn('px-6 pt-6 pb-1 relative flex-shrink-0')}>
<DialogTitle className={cn('font-semibold text-center text-lg')}>
<DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-6 overflow-hidden rounded-2xl overflow-y-auto">
<DialogHeader className="px-6 pt-6">
<DialogTitle className="text-lg font-semibold leading-none tracking-tight text-center">
{getTitle()}
</DialogTitle>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-scroll flex-1'>
{/* Welcome Step - New engaging introduction */}
{step === 'welcome' && (
<div className='text-center space-y-4'>
{/* Hero illustration */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50'>
<div className='flex justify-center items-center space-x-4 mb-3'>
<div className='relative'>
<UserPlus className='w-12 h-12 text-blue-600' />
<Sparkles className='w-4 h-4 text-yellow-500 absolute -top-1 -right-1 animate-pulse' />
</div>
<Globe className='w-16 h-16 text-blue-700 animate-spin-slow' />
<div className='relative'>
<FileText className='w-12 h-12 text-blue-600' />
<Sparkles className='w-4 h-4 text-yellow-500 absolute -top-1 -left-1 animate-pulse' style={{animationDelay: '0.3s'}} />
</div>
</div>
{/* Benefits */}
<div className='grid grid-cols-1 gap-2 text-sm'>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<Shield className='w-4 h-4' />
Decentralized and censorship-resistant
</div>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<User className='w-4 h-4' />
You are in control of your data
</div>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<Globe className='w-4 h-4' />
Join a global network
</div>
</div>
</div>
<div className='space-y-3'>
<Button
className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg'
onClick={() => setStep('generate')}
>
<LogIn className='w-5 h-5 mr-2' />
Get Started
</Button>
</div>
</div>
)}
{/* Generate Step - Enhanced with animations */}
<div className='px-6 pb-6 space-y-4 overflow-y-auto flex-1'>
{/* Generate Step */}
{step === 'generate' && (
<div className='text-center space-y-4'>
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-purple-100 dark:from-blue-950/50 dark:to-purple-950/50 overflow-hidden'>
{/* Animated background elements */}
{showSparkles && (
<div className='absolute inset-0'>
{[...Array(12)].map((_, i) => (
<Sparkles
key={i}
className={`absolute w-4 h-4 text-yellow-400 animate-ping`}
style={{
left: `${Math.random() * 80 + 10}%`,
top: `${Math.random() * 80 + 10}%`,
animationDelay: `${Math.random() * 2}s`
}}
/>
))}
</div>
)}
<div className='relative z-10'>
{isLoading ? (
<div className='space-y-3'>
<div className='relative'>
<Key className='w-20 h-20 text-primary mx-auto animate-pulse' />
<div className='absolute inset-0 flex items-center justify-center'>
<div className='w-24 h-24 border-4 border-yellow-400 border-t-transparent rounded-full animate-spin'></div>
</div>
</div>
<div className='space-y-2'>
<p className='text-lg font-semibold text-primary flex items-center justify-center gap-2'>
<Sparkles className='w-5 h-5' />
Generating your secret key...
</p>
<p className='text-sm text-muted-foreground'>
Creating your secure key
</p>
</div>
</div>
) : (
<div className='space-y-3'>
<Key className='w-20 h-20 text-primary mx-auto' />
<div className='space-y-2'>
<p className='text-lg font-semibold'>
Ready to generate your secret key?
</p>
<p className='text-sm text-muted-foreground px-5'>
This key will be your password to access applications within the Nostr network.
</p>
</div>
</div>
)}
</div>
<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>
{!isLoading && (
<Button
className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 transform transition-all duration-200 hover:scale-105 shadow-lg'
onClick={generateKey}
disabled={isLoading}
>
<Sparkles className='w-5 h-5 mr-2' />
Generate My Secret Key
</Button>
)}
<Button className="w-full h-12 px-9" onClick={generateKey}>
Generate key
</Button>
</div>
)}
{/* Download Step - Whimsical and magical */}
{/* Download Step */}
{step === 'download' && (
<div className='text-center space-y-4'>
{/* Key reveal */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden'>
{/* Sparkles */}
<div className='absolute inset-0 pointer-events-none'>
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
<Sparkles className='absolute bottom-3 right-4 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '1.5s'}} />
</div>
<div className='relative z-10 flex justify-center items-center mb-3'>
<div className='relative'>
<div className='w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg animate-pulse'>
<Key className='w-8 h-8 text-indigo-800' />
</div>
<div className='absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce'>
<Sparkles className='w-3 h-3 text-white' />
</div>
</div>
</div>
<div className='relative z-10 space-y-2'>
<p className='text-base font-semibold'>
Your secret key has been generated!
</p>
{/* Warning */}
<div className='relative mx-auto max-w-sm'>
<div className='p-3 bg-gradient-to-r from-amber-100 via-yellow-50 to-amber-100 dark:from-amber-950/40 dark:via-yellow-950/20 dark:to-amber-950/40 rounded-lg border-2 border-amber-300 dark:border-amber-700 shadow-md'>
<div className='flex items-center gap-2 mb-1'>
<FileText className='w-3 h-3 text-amber-700' />
<span className='text-xs font-bold text-amber-800 dark:text-amber-200'>
Important Warning
</span>
</div>
<p className='text-xs text-red-700 dark:text-amber-300 italic'>
This key is your primary and only means of accessing your account. Store it safely and securely.
</p>
</div>
</div>
</div>
<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>
{/* Key vault */}
{/* Security options */}
<div className='space-y-3'>
<div className='grid grid-cols-1 gap-2'>
{/* Download Option */}
<Card className={`cursor-pointer transition-all duration-200 ${
keySecured === 'downloaded'
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
: 'hover:bg-primary/5 hover:border-primary/20'
}`}>
<CardContent className='p-3'>
<Button
variant="ghost"
className='w-full h-auto p-0 justify-start hover:bg-transparent'
onClick={downloadKey}
>
<div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${
keySecured === 'downloaded'
? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10'
}`}>
{keySecured === 'downloaded' ? (
<CheckCircle className='w-4 h-4 text-green-600' />
) : (
<Download className='w-4 h-4 text-primary' />
)}
</div>
<div className='flex-1 text-left'>
<div className='font-medium text-sm'>
Download as File
</div>
<div className='text-xs text-muted-foreground'>
Save as nostr-nsec-key.txt file
</div>
</div>
{keySecured === 'downloaded' && (
<div className='text-xs font-medium text-green-600'>
✓ Downloaded
</div>
)}
</div>
</Button>
</CardContent>
</Card>
</div>
{/* Continue button */}
<div className="relative">
<Input
type={showKey ? "text" : "password"}
value={nsec}
readOnly
className="pr-10 font-mono text-sm"
/>
<Button
className={`w-full rounded-full py-4 text-base font-semibold transform transition-all duration-200 shadow-lg ${
keySecured === 'downloaded'
? 'bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 dark:from-blue-950/50 dark:to-purple-950/50 hover:scale-105'
: 'bg-gradient-to-r from-blue-600/60 to-indigo-600/60 text-muted cursor-not-allowed'
}`}
onClick={finishKeySetup}
disabled={keySecured !== 'downloaded'}
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
onClick={() => setShowKey(!showKey)}
>
<LogIn className='w-4 h-4 mr-2 flex-shrink-0' />
<span className="text-center leading-tight">
{keySecured === 'none' ? (
<>
Please download your key first
</>
) : (
<>
<span className="hidden sm:inline">My Key is Safe - Continue</span>
<span className="sm:hidden">Key Secured - Continue</span>
</>
)}
</span>
{showKey ? (
<EyeOff className="h-4 w-4 text-muted-foreground" />
) : (
<Eye className="h-4 w-4 text-muted-foreground" />
)}
</Button>
</div>
<Button
className="w-full h-12 px-9"
onClick={downloadKey}
>
<Download className="size-4" />
Download key
</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>
)}
{/* Profile Step - Optional profile setup */}
{/* Profile Step */}
{step === 'profile' && (
<div className='text-center space-y-4'>
{/* Profile setup illustration */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden'>
{/* Sparkles */}
<div className='absolute inset-0 pointer-events-none'>
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
</div>
<div className='relative z-10 flex justify-center items-center mb-3'>
<div className='relative'>
<div className='w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg'>
<User className='w-8 h-8 text-blue-800' />
</div>
<div className='absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce'>
<Sparkles className='w-3 h-3 text-white' />
</div>
</div>
</div>
<div className='relative z-10 space-y-2'>
<p className='text-base font-semibold'>
Almost there! Let's set up your profile
</p>
<p className='text-sm text-muted-foreground'>
Your profile is your identity on Nostr.
</p>
</div>
</div>
{/* Publishing status indicator */}
{isPublishing && (
<div className='relative p-4 rounded-xl bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-950/30 dark:to-indigo-950/30 border border-blue-200 dark:border-blue-800'>
<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-blue-600 border-t-transparent rounded-full animate-spin' />
<span className='text-sm font-medium text-blue-700 dark:text-blue-300'>
<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>
@@ -602,7 +263,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
value={profileData.name}
onChange={(e) => setProfileData(prev => ({ ...prev, name: e.target.value }))}
placeholder='Your name'
className='rounded-lg'
disabled={isPublishing}
/>
</div>
@@ -616,7 +276,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
value={profileData.about}
onChange={(e) => setProfileData(prev => ({ ...prev, about: e.target.value }))}
placeholder='Tell others about yourself...'
className='rounded-lg resize-none'
className='resize-none'
rows={3}
disabled={isPublishing}
/>
@@ -632,7 +292,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
value={profileData.picture}
onChange={(e) => setProfileData(prev => ({ ...prev, picture: e.target.value }))}
placeholder='https://example.com/your-avatar.jpg'
className='rounded-lg flex-1'
className='flex-1'
disabled={isPublishing}
/>
<input
@@ -648,7 +308,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
size='icon'
onClick={() => avatarFileInputRef.current?.click()}
disabled={isUploading || isPublishing}
className='rounded-lg shrink-0'
title='Upload avatar image'
>
{isUploading ? (
@@ -664,7 +323,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
{/* Action buttons */}
<div className='space-y-3'>
<Button
className='w-full rounded-full py-4 text-base font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none'
className='w-full'
onClick={() => finishSignup(false)}
disabled={isPublishing || isUploading}
>
@@ -674,24 +333,18 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
Creating Profile...
</>
) : (
<>
<User className='w-4 h-4 mr-2' />
Create Profile & Finish
</>
'Create profile'
)}
</Button>
<Button
variant='outline'
className='w-full rounded-full py-3 disabled:opacity-50 disabled:cursor-not-allowed'
className='w-full'
onClick={() => finishSignup(true)}
disabled={isPublishing || isUploading}
>
{isPublishing ? (
<>
<div className='w-4 h-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin' />
Setting up account...
</>
'Setting up account...'
) : (
'Skip for now'
)}
+409
View File
@@ -0,0 +1,409 @@
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>
);
};
+266
View File
@@ -0,0 +1,266 @@
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>
);
};
@@ -0,0 +1,84 @@
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>
</>
);
};
+214
View File
@@ -0,0 +1,214 @@
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>
);
};
+1 -1
View File
@@ -9,7 +9,7 @@ export const buttonVariants = cva(
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
"border border-input hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
+1 -1
View File
@@ -43,7 +43,7 @@ const DialogContent = React.forwardRef<
>
{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">
<X className="h-4 w-4" />
<X className="size-5" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
+1 -1
View File
@@ -12,7 +12,7 @@ const ScrollArea = React.forwardRef<
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit] [&>div]:!block [&>div]:!w-full">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
+10 -5
View File
@@ -2,20 +2,25 @@ import { createContext } from "react";
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 {
/** Current theme */
theme: Theme;
/** Selected relay URL */
relayUrl: string;
/** NIP-65 relay list metadata */
relayMetadata: RelayMetadata;
}
export interface AppContextType {
/** Current application configuration */
config: AppConfig;
/** Update configuration using a callback that receives current config and returns new config */
updateConfig: (updater: (currentConfig: AppConfig) => AppConfig) => void;
/** Optional list of preset relays to display in the RelaySelector */
presetRelays?: { name: string; url: string }[];
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
}
export const AppContext = createContext<AppContextType | undefined>(undefined);
+138
View File
@@ -0,0 +1,138 @@
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
View File
@@ -28,6 +28,7 @@ export function useAuthor(pubkey: string | undefined) {
return { event };
}
},
staleTime: 5 * 60 * 1000, // Keep cached data fresh for 5 minutes
retry: 3,
});
}
+1 -1
View File
@@ -6,7 +6,7 @@ export function useComments(root: NostrEvent | URL, limit?: number) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['comments', root instanceof URL ? root.toString() : root.id, limit],
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id, limit],
queryFn: async (c) => {
const filter: NostrFilter = { kinds: [1111] };
+87
View File
@@ -0,0 +1,87 @@
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,
};
}
+45
View File
@@ -0,0 +1,45 @@
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
View File
@@ -1,19 +1,19 @@
import * as React from "react"
import { useEffect, useState } from "react"
const MOBILE_BREAKPOINT = 768
const MOBILE_BREAKPOINT = 768;
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
export function useIsMobile(): boolean {
const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT);
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
}
mql.addEventListener("change", onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener("change", onChange)
}, [])
mql.addEventListener("change", onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener("change", onChange);
}, []);
return !!isMobile
return !!isMobile;
}
+1 -1
View File
@@ -15,7 +15,7 @@ export function useLoggedInAccounts() {
const { logins, setLogin, removeLogin } = useNostrLogin();
const { data: authors = [] } = useQuery({
queryKey: ['logins', logins.map((l) => l.id).join(';')],
queryKey: ['nostr', 'logins', logins.map((l) => l.id).join(';')],
queryFn: async ({ signal }) => {
const events = await nostr.query(
[{ kinds: [0], authors: logins.map((l) => l.pubkey) }],
+1 -1
View File
@@ -85,7 +85,7 @@ export function usePostComment() {
onSuccess: (_, { root }) => {
// Invalidate and refetch comments
queryClient.invalidateQueries({
queryKey: ['comments', root instanceof URL ? root.toString() : root.id]
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id]
});
},
});
+372
View File
@@ -0,0 +1,372 @@
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,
};
}
+5 -58
View File
@@ -1,68 +1,22 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
import { useMemo } from 'react';
import { useNWC } from '@/hooks/useNWCContext';
import type { WebLNProvider } from 'webln';
import { requestProvider } from 'webln';
import type { WebLNProvider } from '@webbtc/webln-types';
export interface WalletStatus {
hasWebLN: boolean;
hasNWC: boolean;
webln: WebLNProvider | null;
activeNWC: ReturnType<typeof useNWC>['getActiveConnection'] extends () => infer T ? T : null;
isDetecting: boolean;
preferredMethod: 'nwc' | 'webln' | 'manual';
}
export function useWallet() {
const [webln, setWebln] = useState<WebLNProvider | null>(null);
const [isDetecting, setIsDetecting] = useState(false);
const [hasAttemptedDetection, setHasAttemptedDetection] = useState(false);
const { connections, getActiveConnection } = useNWC();
// Get the active connection directly - no memoization to avoid stale state
const activeNWC = getActiveConnection();
// Detect WebLN
const detectWebLN = useCallback(async () => {
if (webln || isDetecting) return webln;
setIsDetecting(true);
try {
const provider = await requestProvider();
setWebln(provider);
setHasAttemptedDetection(true);
return provider;
} catch (error) {
// Only log the error if it's not the common "no provider" error
if (error instanceof Error && !error.message.includes('no WebLN provider')) {
console.warn('WebLN detection error:', error);
}
setWebln(null);
setHasAttemptedDetection(true);
return null;
} finally {
setIsDetecting(false);
}
}, [webln, isDetecting]);
// Only auto-detect once on mount
useEffect(() => {
if (!hasAttemptedDetection) {
detectWebLN();
}
}, [detectWebLN, hasAttemptedDetection]);
// Test WebLN connection
const testWebLN = useCallback(async (): Promise<boolean> => {
if (!webln) return false;
try {
await webln.enable();
return true;
} catch (error) {
console.error('WebLN test failed:', error);
return false;
}
}, [webln]);
// Access WebLN directly from browser global scope
const webln = (globalThis as { webln?: WebLNProvider }).webln || null;
// Calculate status values reactively
const hasNWC = useMemo(() => {
@@ -77,18 +31,11 @@ export function useWallet() {
: 'manual';
const status: WalletStatus = {
hasWebLN: !!webln,
hasNWC,
webln,
activeNWC,
isDetecting,
preferredMethod,
};
return {
...status,
hasAttemptedDetection,
detectWebLN,
testWebLN,
};
return status;
}
+17 -5
View File
@@ -7,7 +7,7 @@ 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 'webln';
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';
@@ -205,7 +205,7 @@ export function useZaps(
profile: actualTarget.pubkey,
event: event,
amount: zapAmount,
relays: [config.relayUrl],
relays: config.relayMetadata.relays.map(r => r.url),
comment
});
@@ -263,10 +263,22 @@ export function useZaps(
});
}
}
if (webln) { // Try WebLN next
try {
await webln.sendPayment(newInvoice);
// 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);
@@ -283,7 +295,7 @@ export function useZaps(
// Close dialog last to ensure clean state
onZapSuccess?.();
} catch (weblnError) {
console.error('webln payment failed, falling back:', 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';
+1 -1
View File
@@ -32,7 +32,7 @@
--input: 214.3 31.8% 91.4%;
--ring: 222.2 84% 4.9%;
--radius: 0.5rem;
--radius: 0.75rem;
--sidebar-background: 0 0% 98%;
+86
View File
@@ -0,0 +1,86 @@
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;
}
+117
View File
@@ -0,0 +1,117 @@
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;
}
}
+98
View File
@@ -0,0 +1,98 @@
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'
});
}
+12
View File
@@ -1,3 +1,15 @@
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()
*
+24
View File
@@ -0,0 +1,24 @@
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;
+6 -1
View File
@@ -23,7 +23,12 @@ export function TestApp({ children }: TestAppProps) {
const defaultConfig: AppConfig = {
theme: 'light',
relayUrl: 'wss://relay.nostr.band',
relayMetadata: {
relays: [
{ url: 'wss://relay.nostr.band', read: true, write: true },
],
updatedAt: 0,
},
};
return (
-19
View File
@@ -1,19 +0,0 @@
{
"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"
]
}
-31
View File
@@ -1,31 +0,0 @@
{
"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"]
}
+25 -13
View File
@@ -1,19 +1,31 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
],
"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": ".",
"paths": {
"@/*": ["./src/*"]
},
"noImplicitAny": false,
"noUnusedParameters": false,
"skipLibCheck": true,
"allowJs": true,
"noUnusedLocals": false,
"strictNullChecks": true
}
}
},
"include": ["src"]
}
-22
View File
@@ -1,22 +0,0 @@
{
"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"]
}