mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
84
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b64692833 | ||
|
|
d3e5402dbe | ||
|
|
1dc0cf4529 | ||
|
|
509a088b84 | ||
|
|
8c95f7c0b5 | ||
|
|
944fee7256 | ||
|
|
0f17aa8c7c | ||
|
|
f8ff2583aa | ||
|
|
7d374037ee | ||
|
|
c88408ef5d | ||
|
|
0645e513dd | ||
|
|
a7b854aa6e | ||
|
|
ce0c1406eb | ||
|
|
cb00d12900 | ||
|
|
679772e979 | ||
|
|
a3fdf5f4bd | ||
|
|
f6488523f3 | ||
|
|
21425019a1 | ||
|
|
056446c343 | ||
|
|
797fe770a7 | ||
|
|
ffccfdc54e | ||
|
|
19fa5f4f50 | ||
|
|
ce30a31bb1 | ||
|
|
ac5a014d99 | ||
|
|
3dc0da9e0e | ||
|
|
0ccf2204d9 | ||
|
|
f24b82a832 | ||
|
|
0b2aab0527 | ||
|
|
ad8844d8c4 | ||
|
|
4c33d2ca02 | ||
|
|
bae0ece813 | ||
|
|
cda2d0326b | ||
|
|
c703e517ca | ||
|
|
155415c7d2 | ||
|
|
47c2d7298e | ||
|
|
5a3f282817 | ||
|
|
99723f1d43 | ||
|
|
16d41d5428 | ||
|
|
39620a7339 | ||
|
|
53adc58592 | ||
|
|
13ff6c5a65 | ||
|
|
a811bf61c9 | ||
|
|
895653fae3 | ||
|
|
acde35632a | ||
|
|
7e74eaa2cd | ||
|
|
53eebe3e73 | ||
|
|
a65b88a90b | ||
|
|
9128c53192 | ||
|
|
f0ae6bbc62 | ||
|
|
9dc856d46e | ||
|
|
93a57b2560 | ||
|
|
78398bcd7d | ||
|
|
0986dd4e9d | ||
|
|
17162b3af0 | ||
|
|
1135821195 | ||
|
|
fcf779fe35 | ||
|
|
b832c5c6fd | ||
|
|
4c7c35dc0e | ||
|
|
4837f32ade | ||
|
|
abe700cbc0 | ||
|
|
02b4da72a9 | ||
|
|
940d89a1b5 | ||
|
|
4b5ecff2ea | ||
|
|
5011ddb1bd | ||
|
|
4df7e8b27e | ||
|
|
f7a92627ff | ||
|
|
0494ccef61 | ||
|
|
9eb459e594 | ||
|
|
9a9e0619fb | ||
|
|
724e4880a6 | ||
|
|
fd7ac39a74 | ||
|
|
cdae754341 | ||
|
|
1718478f27 | ||
|
|
634a822214 | ||
|
|
f27d7c8676 | ||
|
|
e52c669144 | ||
|
|
367eed5667 | ||
|
|
d3d852771c | ||
|
|
8c06318bc6 | ||
|
|
187bfd649b | ||
|
|
c222a13901 | ||
|
|
caa4dce6f0 | ||
|
|
2cb5199179 | ||
|
|
87eee5938a |
No files matched your search
+22
-294
@@ -1,150 +1,3 @@
|
||||
# Shakespeare - AI-Powered Nostr Website Builder
|
||||
|
||||
Shakespeare is a browser-based AI chat application that allows users to build custom Nostr websites through natural language conversation. All operations including AI chat and Git operations are executed in client-side JavaScript, with API keys stored in browser storage. Simply describe what you want to build, and AI will help you create it.
|
||||
|
||||
### Virtual Filesystem Layout
|
||||
|
||||
Shakespeare uses LightningFS to provide a browser-based virtual filesystem (VFS) that persists project files in IndexedDB. This is the VFS within the browser that Shakespeare agents act upon. Each project is stored in its own isolated directory structure within the virtual filesystem.
|
||||
|
||||
#### Virtual Filesystem Architecture
|
||||
|
||||
```
|
||||
/
|
||||
├── projects/
|
||||
│ └── {projectId}/ # Individual project directory
|
||||
│ └── ... # Project files (package.json, src/, public/, etc.)
|
||||
├── config/ # Configuration files
|
||||
│ ├── ai.json # AI provider settings and API keys
|
||||
│ └── git.json # Git credentials and repository settings
|
||||
└── tmp/ # Temporary files and scratch space
|
||||
└── ... # Various temporary files and directories
|
||||
```
|
||||
|
||||
#### Key Features
|
||||
|
||||
- **IndexedDB Backend**: All project files are stored in the browser's IndexedDB for persistence across sessions
|
||||
- **Project Isolation**: Each project has its own directory namespace to prevent conflicts
|
||||
- **File Operations**: Full POSIX-like filesystem operations (read, write, mkdir, rm, etc.)
|
||||
- **Git Integration**: Projects can be initialized as Git repositories for template cloning
|
||||
|
||||
This architecture allows Shakespeare to provide a full development environment entirely within the browser, with no server-side storage requirements.
|
||||
|
||||
#### AI Tools Available in Shakespeare
|
||||
|
||||
Shakespeare provides AI agents with specialized tools for project development (note: these are different from the tools available during Shakespeare's own development). These tools are defined in `src/lib/tools/`:
|
||||
|
||||
- **ShellTool**: Execute shell commands in the virtual filesystem environment
|
||||
- **TextEditorViewTool**: Read file contents and view directory structures
|
||||
- **TextEditorWriteTool**: Create or overwrite files with new content
|
||||
- **TextEditorStrReplaceTool**: Replace strings in files
|
||||
- **BuildProjectTool**: Build and compile projects
|
||||
- **TypecheckTool**: Run TypeScript type checking
|
||||
- **NpmAddPackageTool**: Add npm packages to projects
|
||||
- **NpmRemovePackageTool**: Remove npm packages from projects
|
||||
- **GitCommitTool**: Commit changes to Git repositories
|
||||
- **DeployProjectTool**: Deploy projects to hosting platforms
|
||||
- **ReadWebpageTool**: Fetch and read web pages
|
||||
- **NostrReadNipTool**: Read Nostr protocol NIP documents
|
||||
- **NostrReadKindTool**: Read Nostr event kind documentation
|
||||
- **NostrReadTagTool**: Read Nostr tag documentation
|
||||
- **NostrReadProtocolTool**: Read Nostr protocol basics
|
||||
- **NostrReadNipsIndexTool**: Read the full list of NIPs, kinds, and tags
|
||||
- **NostrFetchEventTool**: Fetch Nostr events using NIP-19 identifiers
|
||||
- **NostrGenerateKindTool**: Generate unused Nostr event kind numbers
|
||||
|
||||
#### Shell Commands
|
||||
|
||||
Shakespeare provides a comprehensive set of shell commands that are JavaScript reimplementations of common Unix commands. These commands operate on the virtual filesystem (VFS) and are accessible through the ShellTool. The shell commands are implemented in `src/lib/commands/` and provide familiar Unix-like functionality for file and directory operations.
|
||||
|
||||
**Available Commands:**
|
||||
- **File Operations**: `cat`, `cp`, `mv`, `rm`, `touch`, `find`, `grep`
|
||||
- **Directory Operations**: `cd`, `ls`, `mkdir`, `pwd`, `tree`
|
||||
- **System Commands**: `echo`, `which`, `wc`, `head`, `tail`
|
||||
- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, etc.
|
||||
|
||||
#### Security
|
||||
|
||||
AI filesystem access through tools (including shell commands via ShellTool) has path restrictions to ensure safe operation:
|
||||
|
||||
- **Read operations**: Can access any file in the VFS, including absolute paths
|
||||
- **Write operations**: Restricted to current project directory and `/tmp/` directory (including subdirectories)
|
||||
- **Copy operations**: Can copy from any absolute path to relative paths or `/tmp/`, but cannot copy from relative to absolute paths outside allowed areas
|
||||
|
||||
### Git Integration with isomorphic-git
|
||||
|
||||
Shakespeare provides full Git functionality in the browser using `isomorphic-git` and `@isomorphic-git/lightning-fs`, with all data persisted in IndexedDB.
|
||||
|
||||
#### Key Components
|
||||
|
||||
- **LightningFSAdapter**: Adapts LightningFS to the unified JSRuntimeFS interface
|
||||
- **GitCommitTool**: AI tool for automated commits with staging and validation
|
||||
- **useGitStatus Hook**: Real-time Git status monitoring (updates every 5 seconds)
|
||||
- **ProjectsManager**: Handles project creation, Git initialization, and template cloning
|
||||
|
||||
#### Core Features
|
||||
|
||||
**Project Creation:**
|
||||
1. Clone template from GitLab repository (shallow clone, depth: 1)
|
||||
2. Remove original Git history
|
||||
3. Initialize fresh repository with `main` branch
|
||||
4. Stage all files and create initial commit
|
||||
|
||||
**Version Control:**
|
||||
- Automatic staging of all changed files before commits
|
||||
- Real-time status tracking (modified, added, deleted, untracked, staged files)
|
||||
- Full commit history with author info and SHA hashes
|
||||
- Branch management and remote repository support
|
||||
|
||||
**AI Integration:**
|
||||
- GitCommitTool allows AI assistants to commit changes automatically
|
||||
- Validates repository status and handles edge cases
|
||||
- Generates descriptive commit messages with file change statistics
|
||||
|
||||
**Browser Compatibility:**
|
||||
- CORS proxy for GitHub/GitLab repositories (`https://cors.isomorphic-git.org`)
|
||||
- IndexedDB persistence across browser sessions
|
||||
- Gitignore support using the `ignore` library
|
||||
|
||||
Git operations happen transparently in the background, providing professional version control without requiring Git knowledge from users.
|
||||
|
||||
## AI Message Format
|
||||
|
||||
Shakespeare uses OpenAI-compatible messages for communication between users and AI assistants. The message format follows these conventions:
|
||||
|
||||
### User Messages
|
||||
|
||||
**String Content**: When the user message `content` is a string, it represents the actual user's message directly.
|
||||
|
||||
```json
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Please help me build a todo app"
|
||||
}
|
||||
```
|
||||
|
||||
**Array Content**: When the user message `content` is an array of parts, the structure follows this pattern:
|
||||
|
||||
- **First text part**: Represents the user's actual message
|
||||
- **Subsequent text parts**: Represent user actions, such as adding files to the VFS
|
||||
|
||||
```json
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Can you add this logo to my site?"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Added file: /tmp/logo.svg"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
This format allows the Shakespeare UI to parse and display user actions appropriately while maintaining compatibility with OpenAI's message format standard.
|
||||
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
@@ -165,10 +18,6 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/components/ai/`: AI-related components (GitCommit, GitHistoryDialog)
|
||||
- `/src/components/comments/`: Comment system components (Comment, CommentForm, CommentsSection)
|
||||
- `/src/components/Shakespeare/`: Core Shakespeare editor components (ChatPane, FileEditor, FileTree, PreviewPane)
|
||||
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
@@ -176,44 +25,15 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useFS`: Access virtual filesystem for project file operations
|
||||
- `useAISettings`: Manage AI provider configurations and API keys
|
||||
- `useGitSettings`: Manage Git credentials and repository settings
|
||||
- `useSessionManager`: Access session management for AI chat sessions
|
||||
- `useGitStatus`: Real-time Git repository status monitoring
|
||||
- `useProjects`: Project management and CRUD operations
|
||||
- `useProjectsManager`: Advanced project operations (creation, cloning, building)
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `useZaps`: Lightning zap functionality with payment processing
|
||||
- `useWallet`: Unified wallet detection (WebLN + NWC)
|
||||
- `useNWC`: Nostr Wallet Connect connection management
|
||||
- `useNWCContext`: Access NWC context provider
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound, ProjectView, Settings pages)
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/lib/build/`: Project build system with esbuild integration (esmPlugin, fsPlugin)
|
||||
- `/src/lib/commands/`: Shell command implementations for virtual filesystem
|
||||
- `/src/lib/commands/git/`: Git command implementations (add, commit, push, pull, etc.)
|
||||
- Unix-style commands: `cat`, `cd`, `cp`, `find`, `grep`, `ls`, `mkdir`, `mv`, `rm`, etc.
|
||||
- `/src/lib/tools/`: AI tool implementations for project development
|
||||
- File operations: `TextEditorViewTool`, `TextEditorWriteTool`, `TextEditorStrReplaceTool`
|
||||
- Project tools: `BuildProjectTool`, `TypecheckTool`, `DeployProjectTool`
|
||||
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
|
||||
- Git integration: `GitCommitTool`
|
||||
- Shell access: `ShellTool`
|
||||
- Web access: `ReadWebpageTool`
|
||||
- Nostr tools: `NostrReadNipTool`, `NostrFetchEventTool`, `NostrGenerateKindTool`, etc.
|
||||
- `/src/contexts/`: React context providers
|
||||
- `AppContext`: Global app configuration and theme
|
||||
- `FSContext`: Virtual filesystem access
|
||||
- `AISettingsContext`: AI provider settings and API key management
|
||||
- `GitSettingsContext`: Git credentials and repository configuration
|
||||
- `SessionManagerContext`: AI chat session management
|
||||
- `NWCContext`: Nostr Wallet Connect integration
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
@@ -261,6 +81,7 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
@@ -274,9 +95,9 @@ These components follow a consistent pattern using React's `forwardRef` and use
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit AGENTS.md directly
|
||||
1. Edit CONTEXT.md directly
|
||||
2. The changes take effect in the next session
|
||||
|
||||
## "Vibed with MKStack"
|
||||
@@ -289,9 +110,9 @@ This project comes with custom hooks for querying and publishing events on the N
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always check the full list of existing NIPs before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -299,7 +120,7 @@ Knowing when to create a new kind versus reusing an existing kind requires caref
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Get an overview of all NIPs, and then read specific NIPs and kind documentation to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
@@ -317,7 +138,7 @@ When implementing features that could use existing NIPs, follow this decision fr
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
@@ -478,70 +299,6 @@ function usePosts() {
|
||||
}
|
||||
```
|
||||
|
||||
### 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
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
@@ -737,14 +494,12 @@ The `LoginArea` component handles all the login-related UI and interactions, inc
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
**Important**: Social applications should include a profile menu button in the main interface (typically in headers/navigation) to provide access to account settings, profile editing, and logout functionality. Don't only show `LoginArea` in logged-out states.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
@@ -798,7 +553,7 @@ This project includes a boilerplate `NIP19Page` component that provides the foun
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
@@ -1113,14 +868,14 @@ import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using npm:
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- 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`
|
||||
- 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" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
@@ -1173,11 +928,8 @@ When users specify color schemes:
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests vs Running Tests
|
||||
## Writing 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
|
||||
@@ -1190,14 +942,6 @@ There is an important distinction between **writing new tests** and **running ex
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Running Tests (Executing the Test Suite)
|
||||
**ALWAYS run the test script** after making any code changes. This is mandatory regardless of whether you wrote new tests or not.
|
||||
|
||||
- **You must run the test script** to validate your changes
|
||||
- **Your task is not complete** until the test script passes without errors
|
||||
- **This applies to all changes** - bug fixes, new features, refactoring, or any code modifications
|
||||
- **The test script includes** TypeScript compilation, ESLint checks, and existing test validation
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
@@ -1227,24 +971,8 @@ describe('MyComponent', () => {
|
||||
});
|
||||
```
|
||||
|
||||
## Validating Your Changes
|
||||
## Testing Your Changes
|
||||
|
||||
**CRITICAL**: After making any code changes, you must validate your work by running available validation tools.
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until the code successfully type-checks and builds without errors.**
|
||||
|
||||
### 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
|
||||
|
||||
**Minimum Requirements:**
|
||||
- Code must type-check without errors
|
||||
- Code must build/compile successfully
|
||||
- Fix any critical linting errors that would break functionality
|
||||
|
||||
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -1,2 +0,0 @@
|
||||
VITE_GITHUB_OAUTH_CLIENT_ID="********************"
|
||||
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"nostr": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "xjsr", "@nostrbook/mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,978 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React 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**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/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/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## 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:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.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.
|
||||
|
||||
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.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
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.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- 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)
|
||||
|
||||
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.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
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.
|
||||
|
||||
### 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.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
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 });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```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 }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
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 });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 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:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```tsx
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **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
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**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" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -11,7 +11,6 @@ node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
.ai-history/
|
||||
|
||||
# Editor directories and files
|
||||
.idea
|
||||
@@ -29,4 +28,3 @@ dist-ssr
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.ai/
|
||||
+978
@@ -0,0 +1,978 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React 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**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/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/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## 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:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.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.
|
||||
|
||||
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.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
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.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- 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)
|
||||
|
||||
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.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
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.
|
||||
|
||||
### 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.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
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 });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```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 }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
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 });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 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:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```tsx
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **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
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**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" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -0,0 +1,16 @@
|
||||
# jsr registry should not be edited or removed
|
||||
.npmrc
|
||||
|
||||
# vite client types are needed
|
||||
src/vite-env.d.ts
|
||||
|
||||
# tsconfig is stable and working correctly, so should not be edited
|
||||
tsconfig.json
|
||||
tsconfig.app.json
|
||||
tsconfig.node.json
|
||||
|
||||
# postcss config for Tailwind is stable and working correctly, so should not be edited unless upgrading Tailwind to v4
|
||||
postcss.config.js
|
||||
|
||||
# vite config is stable and usually should not need to be edited
|
||||
vite.config.ts
|
||||
@@ -1,19 +1,9 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"js-dev": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
|
||||
},
|
||||
"nostr": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@nostrbook/mcp@latest"]
|
||||
},
|
||||
"fetch": {
|
||||
"type":"stdio",
|
||||
"command": "uvx",
|
||||
"args": ["mcp-server-fetch", "--ignore-robots-txt"]
|
||||
"args": ["-y", "xjsr", "@nostrbook/mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,978 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React 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**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/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/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## 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:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.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.
|
||||
|
||||
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.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
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.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- 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)
|
||||
|
||||
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.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
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.
|
||||
|
||||
### 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.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
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 });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```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 }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
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 });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 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:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```tsx
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **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
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**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" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
+978
@@ -0,0 +1,978 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React 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**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/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/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## 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:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.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.
|
||||
|
||||
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.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
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.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- 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)
|
||||
|
||||
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.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
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.
|
||||
|
||||
### 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.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
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 });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```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 }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
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 });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 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:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```tsx
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **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
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**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" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -0,0 +1,978 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React 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**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/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/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## 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:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.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.
|
||||
|
||||
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.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
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.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- 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)
|
||||
|
||||
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.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
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.
|
||||
|
||||
### 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.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
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 });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```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 }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
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 });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 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:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```tsx
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **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
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**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" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -5,8 +5,7 @@ Shakespeare is an AI chat application that allows users to build custom Nostr we
|
||||
## Features
|
||||
|
||||
- **AI-Powered Development**: Chat with an AI assistant to build your Nostr website
|
||||
- **File Attachments**: Attach files directly to chat messages with structured text parts, visual badges, and deduplication. Supports both file selection and clipboard image pasting
|
||||
- **Project Management**: Create and manage multiple projects with sidebar navigation
|
||||
- **Project Management**: Create and manage multiple projects in a Google Drive-like interface
|
||||
- **Real-time Editing**: Edit files directly in the browser with syntax highlighting
|
||||
- **File Explorer**: Browse and manage your project files
|
||||
- **Project Preview**: Preview your website as you build it
|
||||
@@ -16,9 +15,8 @@ Shakespeare is an AI chat application that allows users to build custom Nostr we
|
||||
|
||||
1. **Create a Project**: Enter a description of what you want to build in the prompt textarea
|
||||
2. **Chat with AI**: Use the AI assistant to add features, edit files, and build your website
|
||||
3. **Attach Files**: Click the paperclip icon to attach files or paste images directly from your clipboard - they'll show as "Added file: /path/filename"
|
||||
4. **Edit Code**: Switch to the code view to manually edit files if needed
|
||||
5. **Preview**: View your website in the preview pane
|
||||
3. **Edit Code**: Switch to the code view to manually edit files if needed
|
||||
4. **Preview**: View your website in the preview pane
|
||||
|
||||
## Project Structure
|
||||
|
||||
@@ -43,36 +41,11 @@ The AI assistant can:
|
||||
|
||||
## Usage
|
||||
|
||||
1. **Homepage**: Enter a project description in the textarea to create new projects, with existing projects listed in the sidebar
|
||||
1. **Homepage**: Create new projects and view existing ones
|
||||
2. **Project View**: Split-pane interface with AI chat on the left and preview/code on the right
|
||||
3. **File Explorer**: Navigate your project files in the code view
|
||||
4. **File Editor**: Edit files with syntax highlighting and save changes
|
||||
|
||||
## Git Integration
|
||||
|
||||
Shakespeare includes full Git functionality with credential management:
|
||||
|
||||
### Features
|
||||
- **Version Control**: Full Git repository support with commit history and branch management
|
||||
- **Global Credentials**: Configure Git credentials once and use them across all projects
|
||||
- **Automatic Matching**: Credentials are automatically matched to repository origins
|
||||
- **Popular Providers**: Built-in support for GitHub, GitLab, and custom Git providers
|
||||
- **Secure Storage**: Credentials are stored locally in your browser using IndexedDB
|
||||
|
||||
### Setting Up Git Credentials
|
||||
|
||||
1. **Access Git Settings**: Click the gear icon in any Git dialog or use the Git Settings option
|
||||
2. **Add Provider**: Choose from GitHub, GitLab, or add a custom Git provider
|
||||
3. **Enter Token**: Use your username and personal access token for authentication
|
||||
4. **Automatic Usage**: Credentials are automatically used for push/pull operations in matching repositories
|
||||
|
||||
### Repository Operations
|
||||
|
||||
- **Push/Pull**: Sync changes with remote repositories using configured credentials
|
||||
- **Status Monitoring**: Real-time Git status with file changes and sync information
|
||||
- **Commit History**: View commit history and repository information
|
||||
- **Branch Management**: Work with different branches and track remote changes
|
||||
|
||||
## Development
|
||||
|
||||
Built with:
|
||||
@@ -81,5 +54,6 @@ Built with:
|
||||
- Vite
|
||||
- TailwindCSS
|
||||
- shadcn/ui
|
||||
- Vercel AI SDK
|
||||
- LightningFS for filesystem
|
||||
- isomorphic-git for template cloning
|
||||
@@ -0,0 +1,11 @@
|
||||
Please create Shakespeare, an AI chat application that allows users to build custom Nostr websites. On the landing page would be a prompt textarea. Upon entering a prompt, a template would be cloned with `isomorphic-git`. That template's clone URL is hardcoded to `https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/mkstack.git`. A unique directory name would also be generated from the prompt since the user would be able to work on multiple projects within this app.
|
||||
|
||||
For the filesystem, use LightningFS (`@isomorphic-git/lightning-fs` on npm). Note that `isomorphic-git` requires a `Buffer` polyfill to work. isomorphic-git's http client should be added by using `import http from "isomorphic-git/http/web"` (not `fetch`).
|
||||
|
||||
After projects have been created, they'll show up in a grid on the homepage, below the prompt textarea, in a grid design similar to Google Drive. Clicking them navigates to the project view. Creating a project through the homepage prompt also redirects to its project view.
|
||||
|
||||
In the project view, there is a chat in the left pane, and a project preview in the right. Initially the project preview will be empty, because the site won't have been built yet. The project needs to be built with Vite (directly in the browser) and displayed in an iframe, but we'll figure that out later. Just include a placeholder for it in the UI for now.
|
||||
|
||||
In the project chat pane, the user is able to chat with an AI assistant. The assistant will have tools that allow it to work on the project, including editing files and running the Vite build (again, just a stub). In the right preview pane, the user would also be able to switch to a "Code" view, which would display the list of files in the project.
|
||||
|
||||
For the AI implementation, use Vercel's ai-sdk (`ai` on npm). It should use the openai provider (`@ai-sdk/openai` on npm) and include a tool set for working on the project.
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"model": "claude-sonnet-4",
|
||||
"temperature": 0.2,
|
||||
"mcpServers": {
|
||||
"js-dev": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
|
||||
},
|
||||
"nostr": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@nostrbook/mcp@latest"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,978 @@
|
||||
# Project Overview
|
||||
|
||||
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version of React 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**: Unstyled, accessible UI components built with Radix UI and Tailwind
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/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/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
- `useAuthor`: Fetch user profile data by pubkey
|
||||
- `useCurrentUser`: Get currently logged-in user
|
||||
- `useNostrPublish`: Publish events to Nostr
|
||||
- `useUploadFile`: Upload files via Blossom servers
|
||||
- `useAppContext`: Access global app configuration
|
||||
- `useTheme`: Theme management
|
||||
- `useToast`: Toast notifications
|
||||
- `useLocalStorage`: Persistent local storage
|
||||
- `useLoggedInAccounts`: Manage multiple accounts
|
||||
- `useLoginActions`: Authentication actions
|
||||
- `useIsMobile`: Responsive design helper
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
- `AppRouter.tsx`: React Router configuration
|
||||
|
||||
## 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:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel (using vaul)
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## System Prompt Management
|
||||
|
||||
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||
|
||||
1. Edit CONTEXT.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.
|
||||
|
||||
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.
|
||||
|
||||
#### Choosing Between Existing NIPs and Custom Kinds
|
||||
|
||||
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.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
|
||||
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
|
||||
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
|
||||
|
||||
4. **Extension Strategy**: When existing NIPs are close but not perfect:
|
||||
- Use the existing kind as the base
|
||||
- Add domain-specific tags for additional metadata
|
||||
- Document the extensions in `NIP.md`
|
||||
|
||||
5. **When to Generate Custom Kinds**:
|
||||
- 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)
|
||||
|
||||
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.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
Need: Equipment marketplace for farmers
|
||||
Options:
|
||||
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
|
||||
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
|
||||
3. Custom kind - Perfect fit but no interoperability
|
||||
|
||||
Decision: Use NIP-99 + farming-specific tags for best balance
|
||||
```
|
||||
|
||||
#### Tag Design Principles
|
||||
|
||||
When designing tags for Nostr events, follow these principles:
|
||||
|
||||
1. **Kind vs Tags Separation**:
|
||||
- **Kind** = Schema/structure (how the data is organized)
|
||||
- **Tags** = Semantics/categories (what the data represents)
|
||||
- Don't create different kinds for the same data structure
|
||||
|
||||
2. **Use Single-Letter Tags for Categories**:
|
||||
- **Relays only index single-letter tags** for efficient querying
|
||||
- Use `t` tags for categorization, not custom multi-letter tags
|
||||
- Multiple `t` tags allow items to belong to multiple categories
|
||||
|
||||
3. **Relay-Level Filtering**:
|
||||
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
|
||||
- Avoid client-side filtering when relay-level filtering is possible
|
||||
- Consider query patterns when designing tag structure
|
||||
|
||||
4. **Tag Examples**:
|
||||
```json
|
||||
// ❌ Wrong: Multi-letter tag, not queryable at relay level
|
||||
["product_type", "electronics"]
|
||||
|
||||
// ✅ Correct: Single-letter tag, relay-indexed and queryable
|
||||
["t", "electronics"]
|
||||
["t", "smartphone"]
|
||||
["t", "android"]
|
||||
```
|
||||
|
||||
5. **Querying Best Practices**:
|
||||
```typescript
|
||||
// ❌ Inefficient: Get all events, filter in JavaScript
|
||||
const events = await nostr.query([{ kinds: [30402] }]);
|
||||
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
|
||||
|
||||
// ✅ Efficient: Filter at relay level
|
||||
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
|
||||
```
|
||||
|
||||
#### `t` Tag Filtering for Community-Specific Content
|
||||
|
||||
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
|
||||
|
||||
**When to Use:**
|
||||
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
|
||||
- ❌ Generic platforms: Twitter clones, general Nostr clients
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Publishing with community tag
|
||||
createEvent({
|
||||
kind: 1,
|
||||
content: data.content,
|
||||
tags: [['t', 'farming']]
|
||||
});
|
||||
|
||||
// Querying community content
|
||||
const events = await nostr.query([{
|
||||
kinds: [1],
|
||||
'#t': ['farming'],
|
||||
limit: 20
|
||||
}], { signal });
|
||||
```
|
||||
|
||||
### Kind Ranges
|
||||
|
||||
An event's kind number determines the event's behavior and storage characteristics:
|
||||
|
||||
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
|
||||
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
|
||||
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
|
||||
|
||||
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
|
||||
|
||||
### Content Field Design Principles
|
||||
|
||||
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
|
||||
|
||||
#### Guidelines
|
||||
|
||||
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
|
||||
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
|
||||
- **Empty content is valid**: Many events need only tags with `content: ""`
|
||||
- **Relays only index tags**: If you need to filter by a field, it must be a tag
|
||||
|
||||
#### Example
|
||||
|
||||
**✅ Good - queryable data in tags:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "",
|
||||
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
|
||||
}
|
||||
```
|
||||
|
||||
**❌ Bad - structured data in content:**
|
||||
```json
|
||||
{
|
||||
"kind": 30402,
|
||||
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
|
||||
"tags": [["d", "product-123"]]
|
||||
}
|
||||
```
|
||||
|
||||
### NIP.md
|
||||
|
||||
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
|
||||
|
||||
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.
|
||||
|
||||
### 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.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
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 });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
**✅ Efficient - Single query with multiple kinds:**
|
||||
```typescript
|
||||
// Query multiple event types in one request
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1, 6, 16], // All repost kinds in one query
|
||||
'#e': [eventId],
|
||||
limit: 150,
|
||||
}
|
||||
], { signal });
|
||||
|
||||
// Separate by type in JavaScript
|
||||
const notes = events.filter((e) => e.kind === 1);
|
||||
const reposts = events.filter((e) => e.kind === 6);
|
||||
const genericReposts = events.filter((e) => e.kind === 16);
|
||||
```
|
||||
|
||||
**❌ Inefficient - Multiple separate queries:**
|
||||
```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 }),
|
||||
]);
|
||||
```
|
||||
|
||||
**Query Optimization Guidelines:**
|
||||
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
|
||||
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
|
||||
3. **Adjust limits**: When combining queries, increase the limit appropriately
|
||||
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
|
||||
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
```typescript
|
||||
// Example validator function for NIP-52 calendar events
|
||||
function validateCalendarEvent(event: NostrEvent): boolean {
|
||||
// Check if it's a calendar event kind
|
||||
if (![31922, 31923].includes(event.kind)) return false;
|
||||
|
||||
// Check for required tags according to NIP-52
|
||||
const d = event.tags.find(([name]) => name === 'd')?.[1];
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
const start = event.tags.find(([name]) => name === 'start')?.[1];
|
||||
|
||||
// All calendar events require 'd', 'title', and 'start' tags
|
||||
if (!d || !title || !start) return false;
|
||||
|
||||
// Additional validation for date-based events (kind 31922)
|
||||
if (event.kind === 31922) {
|
||||
// start tag should be in YYYY-MM-DD format for date-based events
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!dateRegex.test(start)) return false;
|
||||
}
|
||||
|
||||
// Additional validation for time-based events (kind 31923)
|
||||
if (event.kind === 31923) {
|
||||
// start tag should be a unix timestamp for time-based events
|
||||
const timestamp = parseInt(start);
|
||||
if (isNaN(timestamp) || timestamp <= 0) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function useCalendarEvents() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
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 });
|
||||
|
||||
// Filter events through validator to ensure they meet NIP-52 requirements
|
||||
return events.filter(validateCalendarEvent);
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### The `useAuthor` Hook
|
||||
|
||||
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
|
||||
|
||||
```tsx
|
||||
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
function Post({ event }: { event: NostrEvent }) {
|
||||
const author = useAuthor(event.pubkey);
|
||||
const metadata: NostrMetadata | undefined = author.data?.metadata;
|
||||
|
||||
const displayName = metadata?.name ?? genUserName(event.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
|
||||
// ...render elements with this data
|
||||
}
|
||||
```
|
||||
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
interface NostrMetadata {
|
||||
/** A short description of the user. */
|
||||
about?: string;
|
||||
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
|
||||
banner?: string;
|
||||
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
|
||||
bot?: boolean;
|
||||
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
|
||||
display_name?: string;
|
||||
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud06?: string;
|
||||
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
|
||||
lud16?: string;
|
||||
/** A short name to be displayed for the user. */
|
||||
name?: string;
|
||||
/** An email-like Nostr address according to NIP-05. */
|
||||
nip05?: string;
|
||||
/** A URL to the user's avatar. */
|
||||
picture?: string;
|
||||
/** A web URL related in any way to the event author. */
|
||||
website?: string;
|
||||
}
|
||||
```
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea className="max-w-60" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs, sign up functionality, and switching between accounts. It should not be wrapped in any conditional logic.
|
||||
|
||||
`LoginArea` displays both "Log in" and "Sign Up" buttons when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
|
||||
|
||||
### `npub`, `naddr`, and other Nostr addresses
|
||||
|
||||
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
|
||||
|
||||
- `npub1`: **public keys** - Just the 32-byte public key, no additional metadata
|
||||
- `nsec1`: **private keys** - Secret keys (should never be displayed publicly)
|
||||
- `note1`: **event IDs** - Just the 32-byte event ID (hex), no additional metadata
|
||||
- `nevent1`: **event pointers** - Event ID plus optional relay hints and author pubkey
|
||||
- `nprofile1`: **profile pointers** - Public key plus optional relay hints and petname
|
||||
- `naddr1`: **addressable event coordinates** - For parameterized replaceable events (kind 30000-39999)
|
||||
- `nrelay1`: **relay references** - Relay URLs (deprecated)
|
||||
|
||||
#### Key Differences Between Similar Identifiers
|
||||
|
||||
**`note1` vs `nevent1`:**
|
||||
- `note1`: Contains only the event ID (32 bytes) - specifically for kind:1 events (Short Text Notes) as defined in NIP-10
|
||||
- `nevent1`: Contains event ID plus optional relay hints and author pubkey - for any event kind
|
||||
- Use `note1` for simple references to text notes and threads
|
||||
- Use `nevent1` when you need to include relay hints or author context for any event type
|
||||
|
||||
**`npub1` vs `nprofile1`:**
|
||||
- `npub1`: Contains only the public key (32 bytes)
|
||||
- `nprofile1`: Contains public key plus optional relay hints and petname
|
||||
- Use `npub1` for simple user references
|
||||
- Use `nprofile1` when you need to include relay hints or display name context
|
||||
|
||||
#### NIP-19 Routing Implementation
|
||||
|
||||
**Critical**: NIP-19 identifiers should be handled at the **root level** of URLs (e.g., `/note1...`, `/npub1...`, `/naddr1...`), NOT nested under paths like `/note/note1...` or `/profile/npub1...`.
|
||||
|
||||
This project includes a boilerplate `NIP19Page` component that provides the foundation for handling all NIP-19 identifier types at the root level. The component is configured in the routing system and ready for AI agents to populate with specific functionality.
|
||||
|
||||
**How it works:**
|
||||
|
||||
1. **Root-Level Route**: The route `/:nip19` in `AppRouter.tsx` catches all NIP-19 identifiers
|
||||
2. **Automatic Decoding**: The `NIP19Page` component automatically decodes the identifier using `nip19.decode()`
|
||||
3. **Type-Specific Sections**: Different sections are rendered based on the identifier type:
|
||||
- `npub1`/`nprofile1`: Profile section with placeholder for profile view
|
||||
- `note1`: Note section with placeholder for kind:1 text note view
|
||||
- `nevent1`: Event section with placeholder for any event type view
|
||||
- `naddr1`: Addressable event section with placeholder for articles, marketplace items, etc.
|
||||
4. **Error Handling**: Invalid, vacant, or unsupported identifiers show 404 NotFound page
|
||||
5. **Ready for Population**: Each section includes comments indicating where AI agents should implement specific functionality
|
||||
|
||||
**Example URLs that work automatically:**
|
||||
- `/npub1abc123...` - User profile (needs implementation)
|
||||
- `/note1def456...` - Kind:1 text note (needs implementation)
|
||||
- `/nevent1ghi789...` - Any event with relay hints (needs implementation)
|
||||
- `/naddr1jkl012...` - Addressable event (needs implementation)
|
||||
|
||||
**Features included:**
|
||||
- Basic NIP-19 identifier decoding and routing
|
||||
- Type-specific sections for different identifier types
|
||||
- Error handling for invalid identifiers
|
||||
- Responsive container structure
|
||||
- Comments indicating where to implement specific views
|
||||
|
||||
**Error handling:**
|
||||
- Invalid NIP-19 format → 404 NotFound
|
||||
- Unsupported identifier types (like `nsec1`) → 404 NotFound
|
||||
- Empty or missing identifiers → 404 NotFound
|
||||
|
||||
To implement NIP-19 routing in your Nostr application:
|
||||
|
||||
1. **The NIP19Page boilerplate is already created** - populate sections with specific functionality
|
||||
2. **The route is already configured** in `AppRouter.tsx`
|
||||
3. **Error handling is built-in** - all edge cases show appropriate 404 responses
|
||||
4. **Add specific components** for profile views, event displays, etc. as needed
|
||||
|
||||
#### Event Type Distinctions
|
||||
|
||||
**`note1` identifiers** are specifically for **kind:1 events** (Short Text Notes) as defined in NIP-10: "Text Notes and Threads". These are the basic social media posts in Nostr.
|
||||
|
||||
**`nevent1` identifiers** can reference any event kind and include additional metadata like relay hints and author pubkey. Use `nevent1` when:
|
||||
- The event is not a kind:1 text note
|
||||
- You need to include relay hints for better discoverability
|
||||
- You want to include author context
|
||||
|
||||
#### Use in Filters
|
||||
|
||||
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
|
||||
|
||||
```ts
|
||||
// ❌ Wrong: naddr is not decoded
|
||||
const events = await nostr.query(
|
||||
[{ ids: [naddr] }],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
Corrected example:
|
||||
|
||||
```ts
|
||||
// Import nip19 from nostr-tools
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Decode a NIP-19 identifier
|
||||
const decoded = nip19.decode(value);
|
||||
|
||||
// Optional: guard certain types (depending on the use-case)
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Unsupported Nostr identifier');
|
||||
}
|
||||
|
||||
// Get the addr object
|
||||
const naddr = decoded.data;
|
||||
|
||||
// ✅ Correct: naddr is expanded into the correct filter
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [naddr.kind],
|
||||
authors: [naddr.pubkey],
|
||||
'#d': [naddr.identifier],
|
||||
}],
|
||||
{ signal }
|
||||
);
|
||||
```
|
||||
|
||||
#### Implementation Guidelines
|
||||
|
||||
1. **Always decode NIP-19 identifiers** before using them in queries
|
||||
2. **Use the appropriate identifier type** based on your needs:
|
||||
- Use `note1` for kind:1 text notes specifically
|
||||
- Use `nevent1` when including relay hints or for non-kind:1 events
|
||||
- Use `naddr1` for addressable events (always includes author pubkey for security)
|
||||
3. **Handle different identifier types** appropriately:
|
||||
- `npub1`/`nprofile1`: Display user profiles
|
||||
- `note1`: Display kind:1 text notes specifically
|
||||
- `nevent1`: Display any event with optional relay context
|
||||
- `naddr1`: Display addressable events (articles, marketplace items, etc.)
|
||||
4. **Security considerations**: Always use `naddr1` for addressable events instead of just the `d` tag value, as `naddr1` contains the author pubkey needed to create secure filters
|
||||
5. **Error handling**: Gracefully handle invalid or unsupported NIP-19 identifiers with 404 responses
|
||||
|
||||
### Nostr Edit Profile
|
||||
|
||||
To include an Edit Profile form, place the `EditProfileForm` component in the project:
|
||||
|
||||
```tsx
|
||||
import { EditProfileForm } from "@/components/EditProfileForm";
|
||||
|
||||
function EditProfilePage() {
|
||||
return (
|
||||
<div>
|
||||
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
|
||||
|
||||
<EditProfileForm />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||
|
||||
### Uploading Files on Nostr
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
|
||||
```tsx
|
||||
import { useUploadFile } from "@/hooks/useUploadFile";
|
||||
|
||||
function MyComponent() {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
|
||||
const handleUpload = async (file: File) => {
|
||||
try {
|
||||
// Provides an array of NIP-94 compatible tags
|
||||
// The first tag in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
// ...use the url
|
||||
} catch (error) {
|
||||
// ...handle errors
|
||||
}
|
||||
};
|
||||
|
||||
// ...rest of component
|
||||
}
|
||||
```
|
||||
|
||||
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
|
||||
|
||||
### Nostr Encryption and Decryption
|
||||
|
||||
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
|
||||
|
||||
```ts
|
||||
// Get the current user
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Optional guard to check that nip44 is available
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
|
||||
}
|
||||
|
||||
// Encrypt message to self
|
||||
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
// Decrypt message to self
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
|
||||
```tsx
|
||||
import { NoteContent } from "@/components/NoteContent";
|
||||
|
||||
export function Post(/* ...props */) {
|
||||
// ...
|
||||
|
||||
return (
|
||||
<CardContent className="pb-2">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<NoteContent event={post} className="text-sm" />
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 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:
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.nostr.band",
|
||||
};
|
||||
```
|
||||
|
||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
||||
|
||||
## Routing
|
||||
|
||||
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
|
||||
|
||||
1. Create your page component in `/src/pages/`
|
||||
2. Import it in `AppRouter.tsx`
|
||||
3. Add the route above the catch-all `*` route:
|
||||
|
||||
```tsx
|
||||
<Route path="/your-path" element={<YourComponent />} />
|
||||
```
|
||||
|
||||
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to one Nostr relay for best performance
|
||||
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
|
||||
- **Never use the `any` type**: Always use proper TypeScript types for type safety
|
||||
|
||||
## Loading States
|
||||
|
||||
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
|
||||
|
||||
```tsx
|
||||
// Skeleton example matching component structure
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```tsx
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
// Empty state example
|
||||
<div className="col-span-full">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No results found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Design Customization
|
||||
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
- **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
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
|
||||
**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" })`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
2. **Import the font** in `src/main.tsx`:
|
||||
```typescript
|
||||
import '@fontsource-variable/<font-name>';
|
||||
```
|
||||
|
||||
3. **Update Tailwind configuration** in `tailwind.config.ts`:
|
||||
```typescript
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Recommended Font Choices by Use Case
|
||||
|
||||
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
|
||||
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
|
||||
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
|
||||
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
|
||||
|
||||
### Theme System
|
||||
|
||||
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
|
||||
|
||||
- `useTheme` hook for programmatic theme switching
|
||||
- CSS custom properties defined in `src/index.css`
|
||||
- Automatic dark mode support with `.dark` class
|
||||
|
||||
### Color Scheme Implementation
|
||||
|
||||
When users specify color schemes:
|
||||
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
|
||||
- Use Tailwind's color palette or define custom colors
|
||||
- Ensure proper contrast ratios for accessibility
|
||||
- Apply colors consistently across components (buttons, links, accents)
|
||||
- Test both light and dark mode variants
|
||||
|
||||
### Component Styling Patterns
|
||||
|
||||
- Use `cn()` utility for conditional class merging
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
|
||||
## Writing Tests
|
||||
|
||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||
|
||||
1. **The user explicitly asks for tests** to be written in their message
|
||||
2. **The user describes a specific bug in plain language** and requests tests to help diagnose it
|
||||
3. **The user says they are still experiencing a problem** that you have already attempted to solve (tests can help verify the fix)
|
||||
|
||||
**Never write tests because:**
|
||||
- Tool results show test failures (these are not user requests)
|
||||
- You think tests would be helpful
|
||||
- New features or components are created
|
||||
- Existing functionality needs verification
|
||||
|
||||
### Test Setup
|
||||
|
||||
The project uses Vitest with jsdom environment and includes comprehensive test setup:
|
||||
|
||||
- **Testing Library**: React Testing Library with jest-dom matchers
|
||||
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
- **Test App**: `TestApp` component provides all necessary context providers for testing
|
||||
|
||||
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { MyComponent } from './MyComponent';
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('renders correctly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<MyComponent />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Expected text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
@@ -1,5 +1,5 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export default {
|
||||
meta: {
|
||||
@@ -19,7 +19,7 @@ export default {
|
||||
|
||||
create(context) {
|
||||
const filename = context.getFilename();
|
||||
|
||||
|
||||
// Only run this rule on HTML files
|
||||
if (!filename.endsWith('.html')) {
|
||||
return {};
|
||||
@@ -29,11 +29,11 @@ export default {
|
||||
Program(node) {
|
||||
const sourceCode = context.getSourceCode();
|
||||
const htmlContent = sourceCode.getText();
|
||||
|
||||
|
||||
// Check for manifest link tag in HTML
|
||||
const manifestLinkRegex = /<link[^>]*rel=["']manifest["'][^>]*>/i;
|
||||
const manifestMatch = htmlContent.match(manifestLinkRegex);
|
||||
|
||||
|
||||
if (!manifestMatch) {
|
||||
context.report({
|
||||
node,
|
||||
@@ -53,11 +53,11 @@ export default {
|
||||
}
|
||||
|
||||
const manifestPath = hrefMatch[1];
|
||||
|
||||
|
||||
// Resolve the manifest file path relative to the project root
|
||||
const htmlDir = path.dirname(filename);
|
||||
let resolvedManifestPath;
|
||||
|
||||
|
||||
if (manifestPath.startsWith('/')) {
|
||||
// Absolute path - check in public directory first, then project root
|
||||
const publicPath = path.resolve(htmlDir, 'public' + manifestPath);
|
||||
@@ -67,7 +67,7 @@ export default {
|
||||
// Relative path
|
||||
resolvedManifestPath = path.resolve(htmlDir, manifestPath);
|
||||
}
|
||||
|
||||
|
||||
// Check if the manifest file exists
|
||||
if (!fs.existsSync(resolvedManifestPath)) {
|
||||
context.report({
|
||||
|
||||
@@ -41,7 +41,7 @@ All messages follow JSON-RPC 2.0 specification:
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "fetch",
|
||||
"params": {
|
||||
"params": {
|
||||
"request": {
|
||||
"url": "https://app123.example.com/assets/main.js",
|
||||
"method": "GET",
|
||||
@@ -54,23 +54,6 @@ All messages follow JSON-RPC 2.0 specification:
|
||||
"id": 123
|
||||
}
|
||||
|
||||
// POST Request with JSON body
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "fetch",
|
||||
"params": {
|
||||
"request": {
|
||||
"url": "https://app123.example.com/api/data",
|
||||
"method": "POST",
|
||||
"headers": {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
"body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 of: {"name":"John","age":30}
|
||||
}
|
||||
},
|
||||
"id": 124
|
||||
}
|
||||
|
||||
// Success Response
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
@@ -81,7 +64,7 @@ All messages follow JSON-RPC 2.0 specification:
|
||||
"Content-Type": "application/javascript",
|
||||
"Cache-Control": "no-cache"
|
||||
},
|
||||
"body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7"
|
||||
"body": "console.log('hello');"
|
||||
},
|
||||
"id": 123
|
||||
}
|
||||
@@ -111,14 +94,14 @@ full request body support
|
||||
- `url` (string): Full URL of the request
|
||||
- `method` (string): HTTP method (GET, POST, etc.)
|
||||
- `headers` (object): Request headers as key-value pairs
|
||||
- `body` (string|null): Request body as base64 encoded string, or null if no body
|
||||
- `body` (string|null): Request body as string, or null if no body
|
||||
|
||||
**Result:**
|
||||
|
||||
- `status` (number): HTTP status code (200, 404, etc.)
|
||||
- `statusText` (string): HTTP status text ("OK", "Not Found", etc.)
|
||||
- `headers` (object): Response headers as key-value pairs
|
||||
- `body` (string|null): Response body content as base64 encoded string (null if status is 204)
|
||||
- `body` (string|null): Response body content (null if status is 204)
|
||||
|
||||
**Error Codes:**
|
||||
|
||||
@@ -134,8 +117,8 @@ full request body support
|
||||
- File uploads (as base64 strings)
|
||||
- Any HTTP method with body content
|
||||
|
||||
Request bodies must be base64-encoded strings when not null. This ensures
|
||||
consistent handling of both text and binary data across the messaging protocol.
|
||||
Request bodies are serialized as strings, so binary data should be
|
||||
base64-encoded.
|
||||
|
||||
## Implementation
|
||||
|
||||
@@ -170,9 +153,6 @@ class FetchClientParent {
|
||||
const url = new URL(fetchRequest.url);
|
||||
const path = url.pathname;
|
||||
|
||||
// Decode request body if present
|
||||
const requestBody = fetchRequest.body ? atob(fetchRequest.body) : null;
|
||||
|
||||
const file = this.files.get(path);
|
||||
|
||||
if (file) {
|
||||
@@ -186,7 +166,7 @@ class FetchClientParent {
|
||||
"Content-Type": file.contentType,
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
body: btoa(file.content), // base64 encode the response body
|
||||
body: file.content,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
@@ -200,7 +180,7 @@ class FetchClientParent {
|
||||
headers: {
|
||||
"Content-Type": "text/plain",
|
||||
},
|
||||
body: btoa(`File not found: ${path}`), // base64 encode the error message
|
||||
body: `File not found: ${path}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -284,23 +264,6 @@ class JSONRPCClient {
|
||||
}
|
||||
```
|
||||
|
||||
## Base64 Encoding
|
||||
|
||||
All request and response bodies must be base64 encoded when not null. This ensures:
|
||||
|
||||
- **Consistent Data Handling:** Both text and binary data are handled uniformly
|
||||
- **JSON Compatibility:** Avoids issues with special characters in JSON messages
|
||||
- **Binary Data Support:** Enables transmission of images, files, and other binary content
|
||||
|
||||
**Encoding/Decoding:**
|
||||
```javascript
|
||||
// Encoding (before sending)
|
||||
const encodedBody = btoa(originalBody);
|
||||
|
||||
// Decoding (after receiving)
|
||||
const decodedBody = atob(encodedBody);
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
- **Origin Validation:** Always verify message origin
|
||||
|
||||
@@ -180,18 +180,8 @@ class FetchClient {
|
||||
|
||||
const response = await this.rpcClient.fetch(serializedRequest);
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new Error(`Failed to fetch site index: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
if (response.headers["Content-Type"] !== "text/html") {
|
||||
throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`);
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
|
||||
const text = new TextDecoder().decode(bytes);
|
||||
|
||||
// Replace current document with the site index content
|
||||
this.replaceDocument(text);
|
||||
this.replaceDocument(response.body);
|
||||
} catch (error) {
|
||||
this.showError("Failed to load site index", error);
|
||||
}
|
||||
|
||||
@@ -48,14 +48,7 @@ function handleJSONRPCResponse(message) {
|
||||
|
||||
// Create response from serialized response
|
||||
const { status, statusText, headers, body } = result;
|
||||
|
||||
// Decode base64 body if present
|
||||
let decoded = null;
|
||||
if (typeof body === "string") {
|
||||
decoded = new Uint8Array(atob(body).split('').map(c => c.charCodeAt(0)));
|
||||
}
|
||||
|
||||
const response = new Response(decoded, {
|
||||
const response = new Response(body, {
|
||||
status: status || 200,
|
||||
statusText: statusText || "OK",
|
||||
headers: headers || {},
|
||||
@@ -72,9 +65,8 @@ async function requestViaJSONRPC(request) {
|
||||
let body = null;
|
||||
if (request.body) {
|
||||
try {
|
||||
// Convert body to Uint8Array then base64 encode
|
||||
const bytes = await request.bytes();
|
||||
body = btoa(String.fromCharCode(...bytes));
|
||||
// Convert body to string (JSON-serializable)
|
||||
body = await request.text();
|
||||
} catch (error) {
|
||||
reject(new Error(`Failed to serialize request body: ${error.message}`));
|
||||
return;
|
||||
|
||||
Generated
+463
-1355
File diff suppressed because it is too large.
Load diff
+12
-23
@@ -4,19 +4,18 @@
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"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!'",
|
||||
"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"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/openai": "^1.3.23",
|
||||
"@fontsource-variable/inter": "^5.2.6",
|
||||
"@getalby/sdk": "^6.0.1",
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.5",
|
||||
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.9",
|
||||
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
|
||||
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
||||
@@ -44,28 +43,24 @@
|
||||
"@radix-ui/react-toggle": "^1.1.0",
|
||||
"@radix-ui/react-toggle-group": "^1.1.0",
|
||||
"@radix-ui/react-tooltip": "^1.1.4",
|
||||
"@soapbox.pub/streamdown": "^1.0.11",
|
||||
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
|
||||
"@std/path": "npm:@jsr/std__path@^1.1.1",
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@unhead/addons": "^2.0.10",
|
||||
"@unhead/react": "^2.0.10",
|
||||
"@webcontainer/api": "^1.6.1",
|
||||
"ai": "^4.3.19",
|
||||
"buffer": "^6.0.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.0.0",
|
||||
"decimal.js": "^10.6.0",
|
||||
"date-fns": "^3.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"esbuild-wasm": "^0.25.8",
|
||||
"ignore": "^7.0.5",
|
||||
"input-otp": "^1.2.4",
|
||||
"isomorphic-git": "^1.32.1",
|
||||
"jszip": "^3.10.1",
|
||||
"lucide-react": "^0.525.0",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"openai": "^5.15.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"qrcode": "^1.5.4",
|
||||
"next-themes": "^0.3.0",
|
||||
"nostr-tools": "^2.15.1",
|
||||
"react": "^18.3.1",
|
||||
"react-day-picker": "^8.10.1",
|
||||
"react-dom": "^18.3.1",
|
||||
@@ -76,13 +71,10 @@
|
||||
"react-syntax-highlighter": "^15.6.1",
|
||||
"recharts": "^2.12.7",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"streamdown": "^1.0.12",
|
||||
"sonner": "^1.5.0",
|
||||
"tailwind-merge": "^2.5.2",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"turndown": "^7.2.1",
|
||||
"use-stick-to-bottom": "^1.1.1",
|
||||
"vaul": "^0.9.3",
|
||||
"webln": "^0.3.2",
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -92,14 +84,11 @@
|
||||
"@tailwindcss/typography": "^0.5.15",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/jszip": "^3.4.0",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/path-browserify": "^1.0.3",
|
||||
"@types/react": "^18.3.1",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@types/react-syntax-highlighter": "^15.5.13",
|
||||
"@types/turndown": "^5.0.5",
|
||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"eslint": "^9.9.0",
|
||||
|
||||
@@ -8,12 +8,12 @@
|
||||
"theme_color": "#000000",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/favicon.png",
|
||||
"src": "/icon-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/favicon.png",
|
||||
"src": "/icon-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
}
|
||||
|
||||
+21
-34
@@ -4,21 +4,20 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { createHead, UnheadProvider } from '@unhead/react/client';
|
||||
import { InferSeoMetaPlugin } from '@unhead/addons';
|
||||
import { Suspense, useEffect } from 'react';
|
||||
import { Suspense } from 'react';
|
||||
import LightningFS from '@isomorphic-git/lightning-fs';
|
||||
import NostrProvider from '@/components/NostrProvider';
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
import { Toaster as Sonner } from "@/components/ui/sonner";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { NostrLoginProvider } from '@nostrify/react/login';
|
||||
import { AppProvider } from '@/components/AppProvider';
|
||||
import { AppConfig } from '@/contexts/AppContext';
|
||||
import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { JSRuntimeProvider } from '@/components/JSRuntimeProvider';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
|
||||
|
||||
import { WebContainerAdapter } from '@/lib/WebContainerAdapter';
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
const head = createHead({
|
||||
@@ -40,7 +39,6 @@ const queryClient = new QueryClient({
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.primal.net",
|
||||
deployServer: "shakespeare.wtf",
|
||||
};
|
||||
|
||||
const presetRelays = [
|
||||
@@ -54,44 +52,33 @@ const presetRelays = [
|
||||
const lightningFS = new LightningFS('shakespeare-fs');
|
||||
const fs = new LightningFSAdapter(lightningFS.promises);
|
||||
|
||||
// Component to handle filesystem cleanup on startup
|
||||
// Automatically removes files older than 1 hour from /tmp directory
|
||||
function FSCleanupHandler() {
|
||||
useEffect(() => {
|
||||
// Run cleanup on application startup to remove stale temporary files
|
||||
// This helps prevent the VFS from accumulating old files over time
|
||||
cleanupTmpDirectory(fs).catch(console.error);
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
// Initialize JSRuntime with WebContainer adapter
|
||||
const jsRuntime = new WebContainerAdapter();
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<UnheadProvider head={head}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||
<FSProvider fs={fs}>
|
||||
<FSCleanupHandler />
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||
<FSProvider fs={fs}>
|
||||
<JSRuntimeProvider runtime={jsRuntime}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Sonner />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</QueryClientProvider>
|
||||
</JSRuntimeProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</UnheadProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,32 +1,17 @@
|
||||
import { BrowserRouter, Route, Routes } from "react-router-dom";
|
||||
import { ScrollToTop } from "./components/ScrollToTop";
|
||||
import { SessionMonitor } from "./components/SessionMonitor";
|
||||
|
||||
import Index from "./pages/Index";
|
||||
import Clone from "./pages/Clone";
|
||||
import Settings from "./pages/Settings";
|
||||
import AISettings from "./pages/AISettings";
|
||||
import GitSettings from "./pages/GitSettings";
|
||||
import DataSettings from "./pages/DataSettings";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { ProjectView } from "./pages/ProjectView";
|
||||
import { SettingsLayout } from "./components/SettingsLayout";
|
||||
|
||||
export function AppRouter() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<ScrollToTop />
|
||||
<SessionMonitor />
|
||||
<Routes>
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/clone" element={<Clone />} />
|
||||
<Route path="/settings" element={<SettingsLayout />}>
|
||||
<Route index element={<Settings />} />
|
||||
<Route path="ai" element={<AISettings />} />
|
||||
<Route path="git" element={<GitSettings />} />
|
||||
<Route path="data" element={<DataSettings />} />
|
||||
</Route>
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
||||
<Route path="/:nip19" element={<NIP19Page />} />
|
||||
|
||||
@@ -1,247 +0,0 @@
|
||||
import { memo, useState } from 'react';
|
||||
import { Streamdown } from 'streamdown';
|
||||
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle } from 'lucide-react';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { UserMessage } from '@/components/UserMessage';
|
||||
import OpenAI from 'openai';
|
||||
|
||||
interface AIMessageItemProps {
|
||||
message: AIMessage;
|
||||
isCurrentlyLoading?: boolean;
|
||||
toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message
|
||||
}
|
||||
|
||||
export const AIMessageItem = memo(({
|
||||
message,
|
||||
isCurrentlyLoading = false,
|
||||
toolCall
|
||||
}: AIMessageItemProps) => {
|
||||
const [isToolExpanded, setIsToolExpanded] = useState(false);
|
||||
|
||||
// Get content to display
|
||||
const getContent = () => {
|
||||
if (typeof message.content === 'string') {
|
||||
return message.content;
|
||||
}
|
||||
if (Array.isArray(message.content)) {
|
||||
// Handle array content (like images, text blocks)
|
||||
return message.content
|
||||
.map(item => {
|
||||
if (typeof item === 'string') return item;
|
||||
if (item.type === 'text') return item.text;
|
||||
if (item.type === 'image_url') return `[Image: ${item.image_url.url}]`;
|
||||
return '[Unknown content]';
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
// Get tool info including icon and title
|
||||
const getToolInfo = () => {
|
||||
if (message.role === 'tool' && toolCall) {
|
||||
if (toolCall.type === 'function') {
|
||||
const toolName = toolCall.function.name;
|
||||
let args;
|
||||
|
||||
try {
|
||||
args = JSON.parse(toolCall.function.arguments);
|
||||
} catch {
|
||||
args = {};
|
||||
}
|
||||
|
||||
// Generate icons and titles based on tool name and arguments
|
||||
switch (toolName) {
|
||||
case 'shell':
|
||||
return {
|
||||
icon: Terminal,
|
||||
title: args.command ? args.command : 'Shell Command'
|
||||
};
|
||||
case 'text_editor_view': {
|
||||
const title = args.path
|
||||
? (args.start_line || args.end_line
|
||||
? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})`
|
||||
: `Viewed ${args.path}`)
|
||||
: 'Viewed File';
|
||||
return { icon: Eye, title };
|
||||
}
|
||||
case 'text_editor_write':
|
||||
return {
|
||||
icon: FileText,
|
||||
title: args.path ? `Wrote ${args.path}` : 'Wrote File'
|
||||
};
|
||||
case 'text_editor_str_replace':
|
||||
return {
|
||||
icon: Edit,
|
||||
title: args.path ? `Edited ${args.path}` : 'Edited File'
|
||||
};
|
||||
case 'npm_add_package': {
|
||||
const installTitle = args.name
|
||||
? (args.dev ? `Installed ${args.name} (dev)` : `Installed ${args.name}`)
|
||||
: 'Installed Package';
|
||||
return { icon: Package, title: installTitle };
|
||||
}
|
||||
case 'npm_remove_package':
|
||||
return {
|
||||
icon: PackageMinus,
|
||||
title: args.name ? `Removed ${args.name}` : 'Removed Package'
|
||||
};
|
||||
case 'git_commit':
|
||||
return {
|
||||
icon: GitCommit,
|
||||
title: args.message ? `Committed: ${args.message}` : 'Committed Changes'
|
||||
};
|
||||
case 'build_project':
|
||||
return {
|
||||
icon: Package,
|
||||
title: 'Built Project'
|
||||
};
|
||||
case 'nostr_read_nip':
|
||||
return {
|
||||
icon: BookOpen,
|
||||
title: args.nip ? `Read NIP-${args.nip}` : 'Read NIP'
|
||||
};
|
||||
case 'nostr_fetch_event':
|
||||
return {
|
||||
icon: Download,
|
||||
title: args.identifier ? `Fetched ${args.identifier.slice(0, 16)}...` : 'Fetched Event'
|
||||
};
|
||||
case 'nostr_read_kind':
|
||||
return {
|
||||
icon: Hash,
|
||||
title: args.kind !== undefined ? `Read Kind ${args.kind}` : 'Read Kind'
|
||||
};
|
||||
case 'nostr_read_tag':
|
||||
return {
|
||||
icon: Tag,
|
||||
title: args.tag ? `Read Tag "${args.tag}"` : 'Read Tag'
|
||||
};
|
||||
case 'nostr_read_protocol':
|
||||
return {
|
||||
icon: Network,
|
||||
title: args.doc ? `Read Protocol: ${args.doc}` : 'Read Protocol'
|
||||
};
|
||||
case 'nostr_read_nips_index':
|
||||
return {
|
||||
icon: List,
|
||||
title: 'Read NIPs Index'
|
||||
};
|
||||
case 'nostr_generate_kind':
|
||||
return {
|
||||
icon: Plus,
|
||||
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind'
|
||||
};
|
||||
case 'deploy_project':
|
||||
return {
|
||||
icon: Globe,
|
||||
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed Project'
|
||||
};
|
||||
case 'typecheck':
|
||||
return {
|
||||
icon: CheckCircle,
|
||||
title: 'TypeScript'
|
||||
};
|
||||
default:
|
||||
return {
|
||||
icon: Wrench,
|
||||
title: toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to extracting from content
|
||||
if (message.role === 'tool') {
|
||||
const content = getContent();
|
||||
const lines = content.split('\n');
|
||||
const firstLine = lines[0];
|
||||
|
||||
if (firstLine && firstLine.length < 100) {
|
||||
return {
|
||||
icon: Wrench,
|
||||
title: firstLine.replace(/^(Error |Tool |Executing |Result: )/i, '').trim()
|
||||
};
|
||||
}
|
||||
|
||||
return { icon: Wrench, title: 'Tool Result' };
|
||||
}
|
||||
|
||||
return { icon: Wrench, title: 'Tool' };
|
||||
};
|
||||
|
||||
// Special rendering for tool messages
|
||||
if (message.role === 'tool') {
|
||||
const content = getContent();
|
||||
const toolInfo = getToolInfo();
|
||||
const IconComponent = toolInfo.icon;
|
||||
|
||||
// Regular tool message rendering
|
||||
return (
|
||||
<div className="-mt-2"> {/* -mt-2 to make it snug with the previous assistant message */}
|
||||
<button
|
||||
onClick={() => setIsToolExpanded(!isToolExpanded)}
|
||||
className={cn(
|
||||
"w-full flex items-center gap-2 px-2 py-1 text-xs",
|
||||
"hover:bg-muted/30 rounded transition-colors duration-200"
|
||||
)}
|
||||
>
|
||||
<IconComponent className="h-3 w-3 text-muted-foreground flex-shrink-0" />
|
||||
<span className="text-muted-foreground font-medium truncate flex-1 text-left">
|
||||
{toolInfo.title}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{isToolExpanded && (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words font-mono">
|
||||
{content}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Regular rendering for non-tool messages
|
||||
if (message.role === 'user') {
|
||||
// User messages: right-aligned bubble without avatar/name
|
||||
const userContent = typeof message.content === 'string'
|
||||
? message.content
|
||||
: Array.isArray(message.content)
|
||||
? message.content.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
|
||||
: '';
|
||||
|
||||
return (
|
||||
<div className="flex justify-end py-6">
|
||||
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
|
||||
<div className="text-sm break-words">
|
||||
<UserMessage content={userContent} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Assistant messages: left-aligned without avatar/name
|
||||
return (
|
||||
<div className="flex">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm">
|
||||
<div className="break-words">
|
||||
<Streamdown
|
||||
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
|
||||
parseIncompleteMarkdown={isCurrentlyLoading}
|
||||
>
|
||||
{getContent()}
|
||||
</Streamdown>
|
||||
</div>
|
||||
|
||||
{/* Tool calls are now hidden from assistant messages */}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
AIMessageItem.displayName = 'AIMessageItem';
|
||||
@@ -1,215 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { renderHook, act, waitFor } from '@testing-library/react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import React from 'react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Mock localStorage
|
||||
const localStorageMock = {
|
||||
getItem: vi.fn(),
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
};
|
||||
|
||||
Object.defineProperty(window, 'localStorage', {
|
||||
value: localStorageMock,
|
||||
});
|
||||
|
||||
// Mock the config utils
|
||||
vi.mock('@/lib/configUtils', () => ({
|
||||
readAISettings: vi.fn(),
|
||||
writeAISettings: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('AISettingsProvider', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
localStorageMock.getItem.mockReturnValue(null);
|
||||
|
||||
// Mock the read function to return default settings
|
||||
const { readAISettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readAISettings).mockResolvedValue({
|
||||
providers: {},
|
||||
recentlyUsedModels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('should initialize with empty recentlyUsedModels array', async () => {
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it('should add recently used models correctly', async () => {
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet');
|
||||
});
|
||||
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([
|
||||
'openrouter/anthropic/claude-3.5-sonnet'
|
||||
]);
|
||||
});
|
||||
|
||||
it('should move existing model to front when used again', async () => {
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
|
||||
// Add multiple models
|
||||
act(() => {
|
||||
result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet');
|
||||
result.current.addRecentlyUsedModel('openrouter/openai/gpt-4');
|
||||
result.current.addRecentlyUsedModel('openrouter/google/gemini-pro');
|
||||
});
|
||||
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([
|
||||
'openrouter/google/gemini-pro',
|
||||
'openrouter/openai/gpt-4',
|
||||
'openrouter/anthropic/claude-3.5-sonnet'
|
||||
]);
|
||||
|
||||
// Use the first model again - it should move to front
|
||||
act(() => {
|
||||
result.current.addRecentlyUsedModel('openrouter/anthropic/claude-3.5-sonnet');
|
||||
});
|
||||
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([
|
||||
'openrouter/anthropic/claude-3.5-sonnet',
|
||||
'openrouter/google/gemini-pro',
|
||||
'openrouter/openai/gpt-4'
|
||||
]);
|
||||
});
|
||||
|
||||
it('should limit recently used models to 10 items', async () => {
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
|
||||
// Add 12 models
|
||||
act(() => {
|
||||
for (let i = 1; i <= 12; i++) {
|
||||
result.current.addRecentlyUsedModel(`provider/model-${i}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Should only keep the last 10
|
||||
expect(result.current.settings.recentlyUsedModels).toHaveLength(10);
|
||||
expect(result.current.settings.recentlyUsedModels[0]).toBe('provider/model-12');
|
||||
expect(result.current.settings.recentlyUsedModels[9]).toBe('provider/model-3');
|
||||
});
|
||||
|
||||
it('should migrate old settings without recentlyUsedModels', async () => {
|
||||
const oldSettings = {
|
||||
providers: {
|
||||
openrouter: {
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'test-key'
|
||||
}
|
||||
},
|
||||
recentlyUsedModels: []
|
||||
};
|
||||
|
||||
const { readAISettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readAISettings).mockResolvedValue(oldSettings);
|
||||
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
expect(result.current.settings.providers).toEqual(oldSettings.providers);
|
||||
});
|
||||
});
|
||||
|
||||
it('should invalidate provider-models query when updateSettings is called with providers', async () => {
|
||||
// Mock the QueryClient.invalidateQueries method
|
||||
const mockInvalidateQueries = vi.fn();
|
||||
|
||||
// Create a custom TestApp that mocks the query client
|
||||
const MockedTestApp = ({ children }: { children: React.ReactNode }) => {
|
||||
const queryClient = useQueryClient();
|
||||
vi.spyOn(queryClient, 'invalidateQueries').mockImplementation(mockInvalidateQueries);
|
||||
return <>{children}</>;
|
||||
};
|
||||
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => (
|
||||
<TestApp>
|
||||
<MockedTestApp>{children}</MockedTestApp>
|
||||
</TestApp>
|
||||
),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.updateSettings({
|
||||
providers: {
|
||||
'test-provider': {
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key'
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-models'] });
|
||||
});
|
||||
|
||||
it('should not invalidate provider-models query when updateSettings is called without providers', async () => {
|
||||
// Mock the QueryClient.invalidateQueries method
|
||||
const mockInvalidateQueries = vi.fn();
|
||||
|
||||
// Create a custom TestApp that mocks the query client
|
||||
const MockedTestApp = ({ children }: { children: React.ReactNode }) => {
|
||||
const queryClient = useQueryClient();
|
||||
vi.spyOn(queryClient, 'invalidateQueries').mockImplementation(mockInvalidateQueries);
|
||||
return <>{children}</>;
|
||||
};
|
||||
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => (
|
||||
<TestApp>
|
||||
<MockedTestApp>{children}</MockedTestApp>
|
||||
</TestApp>
|
||||
),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.updateSettings({
|
||||
recentlyUsedModels: ['test-model']
|
||||
});
|
||||
});
|
||||
|
||||
expect(mockInvalidateQueries).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,134 +1,44 @@
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { ReactNode, useState, useEffect } from 'react';
|
||||
import { AISettingsContext, type AISettings, type AIConnection, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { readAISettings, writeAISettings } from '@/lib/configUtils';
|
||||
import { AISettingsContext, type AISettings, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface AISettingsProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: AISettings = {
|
||||
providers: {},
|
||||
recentlyUsedModels: [],
|
||||
apiKey: '',
|
||||
baseUrl: 'https://openrouter.ai/api/v1',
|
||||
model: 'anthropic/claude-sonnet-4',
|
||||
};
|
||||
|
||||
const STORAGE_KEY = 'ai-settings';
|
||||
|
||||
export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { fs } = useFS();
|
||||
const [settings, setSettings] = useState<AISettings>(DEFAULT_SETTINGS);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
// Initialize settings from VFS on mount
|
||||
useEffect(() => {
|
||||
const initializeSettings = async () => {
|
||||
const [settings, setSettings] = useState<AISettings>(() => {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (stored) {
|
||||
try {
|
||||
const settings = await readAISettings(fs);
|
||||
setSettings(settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize AI settings:', error);
|
||||
setSettings(DEFAULT_SETTINGS);
|
||||
} finally {
|
||||
setIsInitialized(true);
|
||||
return { ...DEFAULT_SETTINGS, ...JSON.parse(stored) };
|
||||
} catch {
|
||||
return DEFAULT_SETTINGS;
|
||||
}
|
||||
};
|
||||
}
|
||||
return DEFAULT_SETTINGS;
|
||||
});
|
||||
|
||||
initializeSettings();
|
||||
}, [fs]);
|
||||
|
||||
// Save settings to VFS whenever they change (but not during initialization)
|
||||
useEffect(() => {
|
||||
if (!isInitialized) return;
|
||||
|
||||
const saveSettings = async () => {
|
||||
try {
|
||||
await writeAISettings(fs, settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to save AI settings:', error);
|
||||
}
|
||||
};
|
||||
|
||||
saveSettings();
|
||||
}, [fs, settings, isInitialized]);
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
|
||||
}, [settings]);
|
||||
|
||||
const updateSettings = (newSettings: Partial<AISettings>) => {
|
||||
setSettings(prev => ({ ...prev, ...newSettings }));
|
||||
|
||||
// If providers are being updated, invalidate the provider-models query
|
||||
if ('providers' in newSettings) {
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
}
|
||||
};
|
||||
|
||||
const addProvider = (name: string, connection: AIConnection) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
providers: {
|
||||
...prev.providers,
|
||||
[name]: connection,
|
||||
},
|
||||
}));
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
};
|
||||
|
||||
const removeProvider = (name: string) => {
|
||||
setSettings(prev => {
|
||||
const { [name]: removed, ...rest } = prev.providers;
|
||||
return {
|
||||
...prev,
|
||||
providers: rest,
|
||||
};
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
};
|
||||
|
||||
const updateProvider = (name: string, connection: Partial<AIConnection>) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
providers: {
|
||||
...prev.providers,
|
||||
[name]: {
|
||||
...prev.providers[name],
|
||||
...connection,
|
||||
},
|
||||
},
|
||||
}));
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
|
||||
};
|
||||
|
||||
const addRecentlyUsedModel = (modelId: string) => {
|
||||
setSettings(prev => {
|
||||
const existingIndex = prev.recentlyUsedModels.indexOf(modelId);
|
||||
if (existingIndex === 0) {
|
||||
return prev;
|
||||
} else if (existingIndex === -1) {
|
||||
// Add new model to front, keep only last 10
|
||||
return {
|
||||
...prev,
|
||||
recentlyUsedModels: [modelId, ...prev.recentlyUsedModels].slice(0, 10),
|
||||
}
|
||||
} else {
|
||||
// Move existing model to front
|
||||
return {
|
||||
...prev,
|
||||
recentlyUsedModels: [
|
||||
modelId,
|
||||
...prev.recentlyUsedModels.filter((_, index) => index !== existingIndex)
|
||||
]
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const isConfigured = Object.entries(settings.providers).length > 0;
|
||||
const isConfigured = Boolean(settings.apiKey);
|
||||
|
||||
const contextValue: AISettingsContextType = {
|
||||
settings,
|
||||
updateSettings,
|
||||
addProvider,
|
||||
removeProvider,
|
||||
updateProvider,
|
||||
addRecentlyUsedModel,
|
||||
isConfigured,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,348 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import {
|
||||
MoreHorizontal,
|
||||
MessageSquarePlus,
|
||||
Play,
|
||||
CloudUpload,
|
||||
Loader2,
|
||||
GitBranch,
|
||||
Download,
|
||||
Trash2,
|
||||
Settings,
|
||||
GitMerge,
|
||||
} from 'lucide-react';
|
||||
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
|
||||
import { GitDialog } from '@/components/GitDialog';
|
||||
import { AppSettingsDialog } from '@/components/AppSettingsDialog';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
interface ActionsMenuProps {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
onNewChat: () => void;
|
||||
onBuild: () => void;
|
||||
onDeploy: () => void;
|
||||
isLoading?: boolean;
|
||||
isBuildLoading?: boolean;
|
||||
isDeployLoading?: boolean;
|
||||
disabled?: boolean;
|
||||
onFirstInteraction?: () => void;
|
||||
onProjectDeleted?: () => void;
|
||||
}
|
||||
|
||||
export function ActionsMenu({
|
||||
projectId,
|
||||
projectName,
|
||||
onNewChat,
|
||||
onBuild,
|
||||
onDeploy,
|
||||
isLoading = false,
|
||||
isBuildLoading = false,
|
||||
isDeployLoading = false,
|
||||
disabled = false,
|
||||
onFirstInteraction,
|
||||
onProjectDeleted
|
||||
}: ActionsMenuProps) {
|
||||
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
|
||||
const [gitDialogOpen, setGitDialogOpen] = useState(false);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
|
||||
const navigate = useNavigate();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { toast } = useToast();
|
||||
const git = useGit();
|
||||
const { fs } = useFS();
|
||||
|
||||
const isAnyLoading = isLoading || isBuildLoading || isDeployLoading || isDeleting || isExporting;
|
||||
|
||||
const handleDeleteProject = async () => {
|
||||
setIsDeleting(true);
|
||||
try {
|
||||
await projectsManager.deleteProject(projectId);
|
||||
|
||||
toast({
|
||||
title: "Project deleted",
|
||||
description: `"${projectName}" has been permanently deleted.`,
|
||||
});
|
||||
|
||||
// Navigate back to home and notify parent
|
||||
navigate('/');
|
||||
if (onProjectDeleted) {
|
||||
onProjectDeleted();
|
||||
}
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Failed to delete project",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExportProject = async () => {
|
||||
setIsExporting(true);
|
||||
try {
|
||||
const zip = new JSZip();
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
// Recursive function to add files and directories to zip from a specific project
|
||||
const addProjectToZip = async (dirPath: string, zipFolder: JSZip) => {
|
||||
try {
|
||||
const entries = await fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = `${dirPath}/${entry.name}`;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
// Create folder in zip and recursively add its contents
|
||||
const folder = zipFolder.folder(entry.name);
|
||||
if (folder) {
|
||||
await addProjectToZip(fullPath, folder);
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
// Add file to zip
|
||||
try {
|
||||
const fileContent = await fs.readFile(fullPath);
|
||||
zipFolder.file(entry.name, fileContent);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to read file ${fullPath}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to read directory ${dirPath}:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
// Start from the project directory
|
||||
await addProjectToZip(projectPath, zip);
|
||||
|
||||
// Generate zip file
|
||||
const content = await zip.generateAsync({ type: 'blob' });
|
||||
|
||||
// Create download link
|
||||
const url = URL.createObjectURL(content);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
|
||||
// Generate filename with commit hash
|
||||
let filename = `${projectName}.zip`;
|
||||
try {
|
||||
// Get the current commit hash
|
||||
const commits = await git.log({
|
||||
dir: projectPath,
|
||||
depth: 1,
|
||||
});
|
||||
|
||||
if (commits.length > 0) {
|
||||
const commitHash = commits[0].oid.substring(0, 7); // Truncate to 7 characters
|
||||
filename = `${projectName}-${commitHash}.zip`;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to get commit hash, using project name only:', error);
|
||||
}
|
||||
|
||||
link.download = filename;
|
||||
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
toast({
|
||||
title: "Project exported successfully",
|
||||
description: `"${projectName}" has been downloaded as a zip file.`,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to export project:', error);
|
||||
toast({
|
||||
title: "Failed to export project",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0"
|
||||
disabled={disabled}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
<span className="sr-only">Open menu</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={onNewChat}
|
||||
disabled={isLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<MessageSquarePlus className="h-4 w-4" />
|
||||
New Chat
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setGitDialogOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<GitMerge className="h-4 w-4" />
|
||||
Git Status
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setGitHistoryOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<GitBranch className="h-4 w-4" />
|
||||
Git History
|
||||
</DropdownMenuItem>
|
||||
|
||||
<AppSettingsDialog>
|
||||
<DropdownMenuItem
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
onSelect={(e) => e.preventDefault()}
|
||||
>
|
||||
<Settings className="h-4 w-4" />
|
||||
Settings
|
||||
</DropdownMenuItem>
|
||||
</AppSettingsDialog>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={handleExportProject}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
{isExporting ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Download className="h-4 w-4" />
|
||||
)}
|
||||
{isExporting ? 'Exporting...' : 'Export Project'}
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
if (onFirstInteraction) onFirstInteraction();
|
||||
onBuild();
|
||||
}}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
{isBuildLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Play className="h-4 w-4" />
|
||||
)}
|
||||
{isBuildLoading ? 'Building...' : 'Build'}
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
if (onFirstInteraction) onFirstInteraction();
|
||||
onDeploy();
|
||||
}}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
{isDeployLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<CloudUpload className="h-4 w-4" />
|
||||
)}
|
||||
{isDeployLoading ? 'Deploying...' : 'Deploy'}
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive cursor-pointer gap-2"
|
||||
onSelect={(e) => e.preventDefault()}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
Delete Project
|
||||
</DropdownMenuItem>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Project</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete "{projectName}"? This action cannot be undone and will permanently delete all project data including files.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDeleteProject}
|
||||
disabled={isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{isDeleting ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Deleting...
|
||||
</>
|
||||
) : (
|
||||
'Delete Project'
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Dialogs */}
|
||||
<GitDialog
|
||||
projectId={projectId}
|
||||
open={gitDialogOpen}
|
||||
onOpenChange={setGitDialogOpen}
|
||||
/>
|
||||
|
||||
<GitHistoryDialog
|
||||
projectId={projectId}
|
||||
open={gitHistoryOpen}
|
||||
onOpenChange={setGitHistoryOpen}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { type Project } from '@/lib/ProjectsManager';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Menu, Columns2 } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
|
||||
interface AppLayoutProps {
|
||||
children: React.ReactNode;
|
||||
selectedProject?: Project | null;
|
||||
title?: string;
|
||||
showSidebar?: boolean;
|
||||
headerContent?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function AppLayout({
|
||||
children,
|
||||
selectedProject = null,
|
||||
title = "Shakespeare",
|
||||
showSidebar = true,
|
||||
headerContent
|
||||
}: AppLayoutProps) {
|
||||
const [_projects, setProjects] = useState<Project[]>([]);
|
||||
const projectsManager = useProjectsManager();
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile);
|
||||
|
||||
// Track if we've set the initial state based on projects
|
||||
const [hasSetInitialState, setHasSetInitialState] = useState(false);
|
||||
|
||||
const loadProjects = useCallback(async () => {
|
||||
try {
|
||||
await projectsManager.init();
|
||||
const projectList = await projectsManager.getProjects();
|
||||
setProjects(projectList);
|
||||
|
||||
// Set initial sidebar state based on projects and device type
|
||||
if (!hasSetInitialState && !isMobile) {
|
||||
// On desktop, show sidebar if there are projects
|
||||
setIsSidebarVisible(projectList.length > 0);
|
||||
setHasSetInitialState(true);
|
||||
} else if (!hasSetInitialState && isMobile) {
|
||||
// On mobile, always start hidden
|
||||
setIsSidebarVisible(false);
|
||||
setHasSetInitialState(true);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load projects:', error);
|
||||
if (!hasSetInitialState) {
|
||||
setHasSetInitialState(true);
|
||||
}
|
||||
}
|
||||
}, [projectsManager, hasSetInitialState, isMobile]);
|
||||
|
||||
useEffect(() => {
|
||||
loadProjects();
|
||||
}, [loadProjects]);
|
||||
|
||||
const handleProjectSelect = (project: Project | null) => {
|
||||
if (project) {
|
||||
setIsSidebarVisible(false); // Collapse sidebar on mobile navigation
|
||||
navigate(`/project/${project.id}`);
|
||||
} else {
|
||||
navigate('/');
|
||||
}
|
||||
};
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<div className="min-h-dvh bg-gradient-to-br from-primary/5 to-accent/5">
|
||||
{/* Mobile Header */}
|
||||
<header className="h-12 border-b bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur px-4 py-3 flex items-center justify-between">
|
||||
<div className="flex items-center space-x-2">
|
||||
{showSidebar && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
|
||||
aria-label="Toggle sidebar"
|
||||
>
|
||||
<Menu className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<h1 className="text-lg font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{title}
|
||||
</h1>
|
||||
</div>
|
||||
{headerContent}
|
||||
</header>
|
||||
|
||||
{/* Mobile Sidebar Overlay - show if showSidebar is true and sidebar is visible */}
|
||||
{showSidebar && isSidebarVisible && (
|
||||
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm">
|
||||
{/* Backdrop - only covers the area not occupied by the sidebar */}
|
||||
<div
|
||||
className="absolute inset-0"
|
||||
onClick={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
{/* Sidebar - positioned above the backdrop */}
|
||||
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
|
||||
<ProjectSidebar
|
||||
selectedProject={selectedProject}
|
||||
onSelectProject={(project) => {
|
||||
setIsSidebarVisible(false); // Always collapse sidebar on mobile navigation
|
||||
handleProjectSelect(project);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="container mx-auto px-4 py-6 md:py-8">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex bg-background">
|
||||
{/* Fixed Sidebar - show if showSidebar is true and sidebar is visible */}
|
||||
{showSidebar && isSidebarVisible && (
|
||||
<div className="w-80 border-r bg-sidebar transition-all duration-300">
|
||||
<ProjectSidebar
|
||||
selectedProject={selectedProject}
|
||||
onSelectProject={handleProjectSelect}
|
||||
className="h-screen sticky top-0"
|
||||
showCollapseButton={true}
|
||||
onCollapse={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 flex flex-col bg-background">
|
||||
<div className="min-h-screen bg-gradient-to-br from-primary/5 to-accent/5 relative">
|
||||
{/* Toggle Button - only show when sidebar is collapsed */}
|
||||
{showSidebar && !isSidebarVisible && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(true)}
|
||||
className="absolute top-2 left-4 h-8 w-8 p-0 z-10 bg-transparent backdrop-blur-sm hover:bg-transparent text-foreground/70 hover:text-foreground"
|
||||
aria-label="Toggle sidebar"
|
||||
>
|
||||
<Columns2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<div className="container mx-auto px-4 py-6 md:py-8">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -17,7 +17,6 @@ interface AppProviderProps {
|
||||
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
|
||||
theme: z.enum(['dark', 'light', 'system']),
|
||||
relayUrl: z.string().url(),
|
||||
deployServer: z.string().min(1),
|
||||
});
|
||||
|
||||
export function AppProvider(props: AppProviderProps) {
|
||||
@@ -89,11 +88,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);
|
||||
};
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { Settings, Save } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
|
||||
interface AppSettingsDialogProps {
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function AppSettingsDialog({ children }: AppSettingsDialogProps) {
|
||||
const { config, updateConfig } = useAppContext();
|
||||
const { toast } = useToast();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [deployServer, setDeployServer] = useState(config.deployServer);
|
||||
|
||||
const handleSave = () => {
|
||||
// Validate deploy server
|
||||
if (!deployServer.trim()) {
|
||||
toast({
|
||||
title: "Invalid deploy server",
|
||||
description: "Deploy server cannot be empty.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Remove protocol if present
|
||||
const cleanDeployServer = deployServer.replace(/^https?:\/\//, '');
|
||||
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
deployServer: cleanDeployServer,
|
||||
}));
|
||||
|
||||
toast({
|
||||
title: "Settings saved",
|
||||
description: "Your deployment settings have been updated.",
|
||||
});
|
||||
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
// Reset to current config
|
||||
setDeployServer(config.deployServer);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{children || (
|
||||
<Button variant="outline" size="sm">
|
||||
<Settings className="h-4 w-4 mr-2" />
|
||||
Settings
|
||||
</Button>
|
||||
)}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>App Settings</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure your application preferences and deployment settings.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Deployment</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="deployServer">Deploy Server</Label>
|
||||
<Input
|
||||
id="deployServer"
|
||||
value={deployServer}
|
||||
onChange={(e) => setDeployServer(e.target.value)}
|
||||
placeholder="shakespeare.wtf"
|
||||
className="font-mono"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Your projects will be deployed to subdomains of this server.
|
||||
Example: yourproject.{deployServer || 'shakespeare.wtf'}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-2">
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
Save Settings
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { GitDialog } from './GitDialog';
|
||||
|
||||
// Mock the hooks
|
||||
const mockRefetch = vi.fn();
|
||||
const mockUseGitStatus = vi.fn();
|
||||
|
||||
const baseGitStatus = {
|
||||
isGitRepo: true,
|
||||
currentBranch: 'main',
|
||||
hasUncommittedChanges: false,
|
||||
changedFiles: [],
|
||||
totalCommits: 5,
|
||||
remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }],
|
||||
latestCommit: {
|
||||
oid: 'abc123def456',
|
||||
message: 'Initial commit',
|
||||
author: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: Date.now() / 1000,
|
||||
},
|
||||
},
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
};
|
||||
|
||||
vi.mock('@/hooks/useGitStatus', () => ({
|
||||
useGitStatus: () => mockUseGitStatus(),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useFS', () => ({
|
||||
useFS: vi.fn(() => ({
|
||||
fs: {},
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useToast', () => ({
|
||||
useToast: vi.fn(() => ({
|
||||
toast: vi.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useGitSettings', () => ({
|
||||
useGitSettings: vi.fn(() => ({
|
||||
settings: {
|
||||
credentials: {
|
||||
'https://github.com': {
|
||||
username: 'git',
|
||||
password: 'github-token',
|
||||
},
|
||||
},
|
||||
},
|
||||
})),
|
||||
}));
|
||||
|
||||
describe('GitDialog', () => {
|
||||
beforeEach(() => {
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: baseGitStatus,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
});
|
||||
|
||||
it('renders git repository information', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Git Repository Status')).toBeInTheDocument();
|
||||
expect(screen.getByText('Repository Information')).toBeInTheDocument();
|
||||
expect(screen.getByText('main')).toBeInTheDocument();
|
||||
expect(screen.getByText('5')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('origin')).toHaveLength(2); // Appears in remotes and credentials sections
|
||||
});
|
||||
|
||||
it('shows sync status', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Sync Status')).toBeInTheDocument();
|
||||
expect(screen.getByText('Up to date')).toBeInTheDocument();
|
||||
expect(screen.getByText('Pull')).toBeInTheDocument();
|
||||
expect(screen.getByText('Push')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows clean working directory when no changes', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Working directory is clean')).toBeInTheDocument();
|
||||
expect(screen.getByText('No uncommitted changes')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('enables push button when there are commits ahead', () => {
|
||||
// Mock git status with commits ahead
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
ahead: 2,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const pushButton = screen.getByText('Push');
|
||||
expect(pushButton).toBeInTheDocument();
|
||||
expect(pushButton.closest('button')).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('disables push button when no commits ahead', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const pushButton = screen.getByText('Push');
|
||||
expect(pushButton).toBeInTheDocument();
|
||||
expect(pushButton.closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows configured credentials status', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Authentication')).toBeInTheDocument();
|
||||
expect(screen.getByText('github.com')).toBeInTheDocument();
|
||||
expect(screen.getByText('Configured')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,554 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import {
|
||||
GitBranch,
|
||||
Upload,
|
||||
Download,
|
||||
Loader2,
|
||||
CheckCircle,
|
||||
AlertCircle,
|
||||
Clock,
|
||||
FileIcon,
|
||||
Plus,
|
||||
Minus,
|
||||
Edit,
|
||||
RefreshCw,
|
||||
Settings,
|
||||
AlertTriangle,
|
||||
} from 'lucide-react';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { findCredentialsForRepo, getOriginDisplayName } from '@/lib/gitCredentials';
|
||||
|
||||
interface GitDialogProps {
|
||||
projectId: string;
|
||||
children?: React.ReactNode;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function GitDialog({ projectId, children, open, onOpenChange }: GitDialogProps) {
|
||||
const [isPushing, setIsPushing] = useState(false);
|
||||
const [isPulling, setIsPulling] = useState(false);
|
||||
const [pushResult, setPushResult] = useState<string | null>(null);
|
||||
const [pullResult, setPullResult] = useState<string | null>(null);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
|
||||
const { settings } = useGitSettings();
|
||||
const git = useGit();
|
||||
const { toast } = useToast();
|
||||
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
// Get credentials for the current repository
|
||||
const getCredentialsForCurrentRepo = () => {
|
||||
if (!gitStatus?.remotes.length) return null;
|
||||
const remoteUrl = gitStatus.remotes[0].url; // Use first remote (usually 'origin')
|
||||
return findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
};
|
||||
|
||||
const currentCredentials = getCredentialsForCurrentRepo();
|
||||
|
||||
const handlePush = async () => {
|
||||
if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) {
|
||||
toast({
|
||||
title: "Cannot push",
|
||||
description: "Not a git repository or no current branch",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (gitStatus.remotes.length === 0) {
|
||||
toast({
|
||||
title: "Cannot push",
|
||||
description: "No remote repositories configured",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (gitStatus.ahead === 0) {
|
||||
toast({
|
||||
title: "Nothing to push",
|
||||
description: "No commits ahead of remote. Commit your changes first.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsPushing(true);
|
||||
setPushResult(null);
|
||||
|
||||
try {
|
||||
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
|
||||
|
||||
// Prepare authentication if credentials are available
|
||||
const authOptions = currentCredentials ? {
|
||||
onAuth: () => ({
|
||||
username: currentCredentials.username,
|
||||
password: currentCredentials.password
|
||||
}),
|
||||
} : {};
|
||||
|
||||
await git.push({
|
||||
dir: projectPath,
|
||||
remote: remote.name,
|
||||
ref: gitStatus.currentBranch,
|
||||
...authOptions,
|
||||
});
|
||||
|
||||
setPushResult(`✅ Successfully pushed ${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} to ${remote.name}/${gitStatus.currentBranch}`);
|
||||
toast({
|
||||
title: "Push successful",
|
||||
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
|
||||
// Refresh git status after push
|
||||
await refetchGitStatus();
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
setPushResult(`❌ Push failed: ${errorMessage}`);
|
||||
toast({
|
||||
title: "Push failed",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsPushing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePull = async () => {
|
||||
if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) {
|
||||
toast({
|
||||
title: "Cannot pull",
|
||||
description: "Not a git repository or no current branch",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (gitStatus.remotes.length === 0) {
|
||||
toast({
|
||||
title: "Cannot pull",
|
||||
description: "No remote repositories configured",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsPulling(true);
|
||||
setPullResult(null);
|
||||
|
||||
try {
|
||||
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
|
||||
|
||||
// Prepare authentication if credentials are available
|
||||
const authOptions = currentCredentials ? {
|
||||
onAuth: () => ({
|
||||
username: currentCredentials.username,
|
||||
password: currentCredentials.password
|
||||
}),
|
||||
} : {};
|
||||
|
||||
await git.pull({
|
||||
dir: projectPath,
|
||||
ref: gitStatus.currentBranch,
|
||||
singleBranch: true,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
...authOptions,
|
||||
});
|
||||
|
||||
setPullResult(`✅ Successfully pulled from ${remote.name}/${gitStatus.currentBranch}`);
|
||||
toast({
|
||||
title: "Pull successful",
|
||||
description: `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
|
||||
// Refresh git status after pull
|
||||
await refetchGitStatus();
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
setPullResult(`❌ Pull failed: ${errorMessage}`);
|
||||
toast({
|
||||
title: "Pull failed",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsPulling(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRefresh = async () => {
|
||||
await refetchGitStatus();
|
||||
setPushResult(null);
|
||||
setPullResult(null);
|
||||
};
|
||||
|
||||
const getFileStatusIcon = (status: string) => {
|
||||
switch (status) {
|
||||
case 'added':
|
||||
return <Plus className="h-3 w-3 text-green-500" />;
|
||||
case 'deleted':
|
||||
return <Minus className="h-3 w-3 text-red-500" />;
|
||||
case 'modified':
|
||||
return <Edit className="h-3 w-3 text-blue-500" />;
|
||||
case 'staged':
|
||||
return <CheckCircle className="h-3 w-3 text-green-600" />;
|
||||
case 'untracked':
|
||||
return <FileIcon className="h-3 w-3 text-gray-500" />;
|
||||
default:
|
||||
return <FileIcon className="h-3 w-3" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getFileStatusColor = (status: string) => {
|
||||
switch (status) {
|
||||
case 'added':
|
||||
return 'bg-green-100 text-green-800 border-green-200';
|
||||
case 'deleted':
|
||||
return 'bg-red-100 text-red-800 border-red-200';
|
||||
case 'modified':
|
||||
return 'bg-blue-100 text-blue-800 border-blue-200';
|
||||
case 'staged':
|
||||
return 'bg-green-100 text-green-800 border-green-200';
|
||||
case 'untracked':
|
||||
return 'bg-gray-100 text-gray-800 border-gray-200';
|
||||
default:
|
||||
return 'bg-gray-100 text-gray-800 border-gray-200';
|
||||
}
|
||||
};
|
||||
|
||||
const getSyncStatus = () => {
|
||||
if (!gitStatus?.isGitRepo) {
|
||||
return { status: 'not-repo', text: 'Not a Git repository', icon: AlertCircle, color: 'text-gray-500' };
|
||||
}
|
||||
|
||||
if (gitStatus.remotes.length === 0) {
|
||||
return { status: 'no-remote', text: 'No remote configured', icon: AlertCircle, color: 'text-yellow-600' };
|
||||
}
|
||||
|
||||
if (gitStatus.ahead > 0 && gitStatus.behind > 0) {
|
||||
return { status: 'diverged', text: `${gitStatus.ahead} ahead, ${gitStatus.behind} behind`, icon: AlertCircle, color: 'text-red-600' };
|
||||
}
|
||||
|
||||
if (gitStatus.ahead > 0) {
|
||||
return { status: 'ahead', text: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} ahead`, icon: Upload, color: 'text-blue-600' };
|
||||
}
|
||||
|
||||
// Show uncommitted changes but with different styling since they can't be pushed directly
|
||||
if (gitStatus.hasUncommittedChanges) {
|
||||
return { status: 'uncommitted', text: `${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}`, icon: Clock, color: 'text-yellow-600' };
|
||||
}
|
||||
|
||||
if (gitStatus.behind > 0) {
|
||||
return { status: 'behind', text: `${gitStatus.behind} commit${gitStatus.behind !== 1 ? 's' : ''} behind`, icon: Download, color: 'text-orange-600' };
|
||||
}
|
||||
|
||||
return { status: 'synced', text: 'Up to date', icon: CheckCircle, color: 'text-green-600' };
|
||||
};
|
||||
|
||||
const syncStatus = getSyncStatus();
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
{children && <DialogTrigger asChild>{children}</DialogTrigger>}
|
||||
<DialogContent className="max-w-2xl max-h-[80vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<GitBranch className="h-5 w-5" />
|
||||
Git Repository Status
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
View repository status and sync with remote repositories
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<ScrollArea className="max-h-[60vh]">
|
||||
<div className="space-y-4">
|
||||
{/* Repository Info */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm flex items-center justify-between">
|
||||
Repository Information
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleRefresh}
|
||||
className="h-7 w-7 p-0"
|
||||
>
|
||||
<RefreshCw className="h-3 w-3" />
|
||||
</Button>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{gitStatus?.isGitRepo ? (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">Current Branch:</span>
|
||||
<Badge variant="outline" className="font-mono">
|
||||
{gitStatus.currentBranch || 'unknown'}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">Total Commits:</span>
|
||||
<Badge variant="secondary">{gitStatus.totalCommits}</Badge>
|
||||
</div>
|
||||
|
||||
{gitStatus.latestCommit && (
|
||||
<div className="space-y-2">
|
||||
<span className="text-sm text-muted-foreground">Latest Commit:</span>
|
||||
<div className="bg-muted/50 rounded-md p-2 space-y-1">
|
||||
<div className="font-mono text-xs text-muted-foreground">
|
||||
{gitStatus.latestCommit.oid.substring(0, 7)}
|
||||
</div>
|
||||
<div className="text-sm">{gitStatus.latestCommit.message}</div>
|
||||
<div className="text-xs text-muted-foreground flex items-center gap-1">
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(gitStatus.latestCommit.author.timestamp * 1000).toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<span className="text-sm text-muted-foreground">Remotes:</span>
|
||||
{gitStatus.remotes.map((remote) => (
|
||||
<div key={remote.name} className="bg-muted/50 rounded-md p-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Badge variant="outline">{remote.name}</Badge>
|
||||
<span className="font-mono text-xs text-muted-foreground truncate ml-2">
|
||||
{remote.url}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="text-center py-4 text-muted-foreground">
|
||||
<AlertCircle className="h-8 w-8 mx-auto mb-2" />
|
||||
<p>Not a Git repository</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Credentials Status */}
|
||||
{gitStatus?.isGitRepo && gitStatus.remotes.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm flex items-center justify-between">
|
||||
Authentication
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate('/settings/git')}
|
||||
className="h-7 gap-1 text-xs"
|
||||
>
|
||||
<Settings className="h-3 w-3" />
|
||||
Settings
|
||||
</Button>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Credentials for push/pull operations
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{gitStatus.remotes.map((remote) => {
|
||||
const credentials = findCredentialsForRepo(remote.url, settings.credentials);
|
||||
const originDisplayName = getOriginDisplayName(remote.url);
|
||||
|
||||
return (
|
||||
<div key={remote.name} className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline">{remote.name}</Badge>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{originDisplayName}
|
||||
</span>
|
||||
</div>
|
||||
{credentials ? (
|
||||
<div className="flex items-center gap-1 text-green-600">
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
<span className="text-xs">Configured</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-1 text-amber-600">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
<span className="text-xs">No credentials</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!credentials && (
|
||||
<Alert className="border-amber-200 bg-amber-50">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
No credentials configured for {originDisplayName}.
|
||||
Push/pull operations may fail for private repositories.{' '}
|
||||
<button
|
||||
onClick={() => navigate('/settings/git')}
|
||||
className="underline hover:no-underline font-medium"
|
||||
>
|
||||
Configure credentials
|
||||
</button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Sync Status */}
|
||||
{gitStatus?.isGitRepo && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm">Sync Status</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<syncStatus.icon className={cn("h-4 w-4", syncStatus.color)} />
|
||||
<span className={cn("text-sm font-medium", syncStatus.color)}>
|
||||
{syncStatus.text}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handlePull}
|
||||
disabled={isPulling || isPushing}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
>
|
||||
{isPulling ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isPulling ? 'Pulling...' : 'Pull'}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={handlePush}
|
||||
disabled={isPushing || isPulling || gitStatus.ahead === 0}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
>
|
||||
{isPushing ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Upload className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isPushing ? 'Pushing...' : 'Push'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Operation Results */}
|
||||
{(pushResult || pullResult) && (
|
||||
<div className="mt-3 space-y-2">
|
||||
{pushResult && (
|
||||
<div className="text-xs font-mono bg-muted/50 rounded p-2">
|
||||
{pushResult}
|
||||
</div>
|
||||
)}
|
||||
{pullResult && (
|
||||
<div className="text-xs font-mono bg-muted/50 rounded p-2">
|
||||
{pullResult}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Working Directory Changes */}
|
||||
{gitStatus?.isGitRepo && gitStatus.changedFiles.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm">Working Directory Changes</CardTitle>
|
||||
<CardDescription>
|
||||
{gitStatus.changedFiles.length} file{gitStatus.changedFiles.length !== 1 ? 's' : ''} with changes
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{gitStatus.changedFiles.map((file, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center gap-2 p-2 rounded-md border bg-muted/20"
|
||||
>
|
||||
{getFileStatusIcon(file.status)}
|
||||
<span className="font-mono text-sm flex-1 truncate">
|
||||
{file.filepath}
|
||||
</span>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn("text-xs", getFileStatusColor(file.status))}
|
||||
>
|
||||
{file.status}
|
||||
</Badge>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Clean Working Directory */}
|
||||
{gitStatus?.isGitRepo && gitStatus.changedFiles.length === 0 && (
|
||||
<Card>
|
||||
<CardContent className="py-6">
|
||||
<div className="text-center text-muted-foreground">
|
||||
<CheckCircle className="h-8 w-8 mx-auto mb-2 text-green-500" />
|
||||
<p>Working directory is clean</p>
|
||||
<p className="text-xs">No uncommitted changes</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { ReactNode } from 'react';
|
||||
import { GitSettingsProvider } from './GitSettingsProvider';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import type { GitCredential } from '@/contexts/GitSettingsContext';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Mock the config utils
|
||||
vi.mock('@/lib/configUtils', () => ({
|
||||
readGitSettings: vi.fn(),
|
||||
writeGitSettings: vi.fn(),
|
||||
}));
|
||||
|
||||
// Test component that uses the hook
|
||||
function TestComponent() {
|
||||
const { settings, updateSettings, addCredential, removeCredential, updateCredential, isConfigured } = useGitSettings();
|
||||
|
||||
const handleAdd = () => {
|
||||
const credential: GitCredential = {
|
||||
username: 'git',
|
||||
password: 'test-token',
|
||||
};
|
||||
addCredential('https://github.com', credential);
|
||||
};
|
||||
|
||||
const handleUpdate = () => {
|
||||
updateCredential('https://github.com', { password: 'updated-token' });
|
||||
};
|
||||
|
||||
const handleRemove = () => {
|
||||
removeCredential('https://github.com');
|
||||
};
|
||||
|
||||
const handleUpdateCorsProxy = () => {
|
||||
updateSettings({ corsProxy: 'https://custom-cors.example.com' });
|
||||
};
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div data-testid="configured">{isConfigured ? 'configured' : 'not-configured'}</div>
|
||||
<div data-testid="count">{Object.keys(settings.credentials).length}</div>
|
||||
<div data-testid="cors-proxy">{settings.corsProxy}</div>
|
||||
<button onClick={handleAdd}>Add GitHub</button>
|
||||
<button onClick={handleUpdate}>Update GitHub</button>
|
||||
<button onClick={handleRemove}>Remove GitHub</button>
|
||||
<button onClick={handleUpdateCorsProxy}>Update CORS Proxy</button>
|
||||
{settings.credentials['https://github.com'] && (
|
||||
<div data-testid="github-creds">
|
||||
{settings.credentials['https://github.com'].username}:
|
||||
{settings.credentials['https://github.com'].password}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TestWrapper({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<TestApp>
|
||||
<GitSettingsProvider>
|
||||
{children}
|
||||
</GitSettingsProvider>
|
||||
</TestApp>
|
||||
);
|
||||
}
|
||||
|
||||
describe('GitSettingsProvider', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
localStorage.clear();
|
||||
|
||||
// Mock the read function to return default settings
|
||||
const { readGitSettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readGitSettings).mockResolvedValue({
|
||||
credentials: {},
|
||||
corsProxy: 'https://cors.isomorphic-git.org',
|
||||
});
|
||||
});
|
||||
|
||||
it('provides initial empty state', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('0');
|
||||
});
|
||||
});
|
||||
|
||||
it('can add credentials', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText('Add GitHub'));
|
||||
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('1');
|
||||
expect(screen.getByTestId('github-creds')).toHaveTextContent('git:test-token');
|
||||
});
|
||||
|
||||
it('can update credentials', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
});
|
||||
|
||||
// First add a credential
|
||||
fireEvent.click(screen.getByText('Add GitHub'));
|
||||
expect(screen.getByTestId('github-creds')).toHaveTextContent('git:test-token');
|
||||
|
||||
// Then update it
|
||||
fireEvent.click(screen.getByText('Update GitHub'));
|
||||
expect(screen.getByTestId('github-creds')).toHaveTextContent('git:updated-token');
|
||||
});
|
||||
|
||||
it('can remove credentials', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
});
|
||||
|
||||
// First add a credential
|
||||
fireEvent.click(screen.getByText('Add GitHub'));
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('1');
|
||||
|
||||
// Then remove it
|
||||
fireEvent.click(screen.getByText('Remove GitHub'));
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('0');
|
||||
});
|
||||
|
||||
it('persists settings to VFS', async () => {
|
||||
const { writeGitSettings } = await import('@/lib/configUtils');
|
||||
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('not-configured');
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText('Add GitHub'));
|
||||
|
||||
// Check that settings were saved to VFS
|
||||
await waitFor(() => {
|
||||
expect(writeGitSettings).toHaveBeenCalledWith(
|
||||
expect.anything(), // fs instance
|
||||
expect.objectContaining({
|
||||
credentials: {
|
||||
'https://github.com': {
|
||||
username: 'git',
|
||||
password: 'test-token',
|
||||
}
|
||||
},
|
||||
corsProxy: 'https://cors.isomorphic-git.org'
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('loads settings from VFS', async () => {
|
||||
const settings = {
|
||||
credentials: {
|
||||
'https://gitlab.com': {
|
||||
username: 'git',
|
||||
password: 'gitlab-token',
|
||||
},
|
||||
},
|
||||
corsProxy: 'https://custom-cors.example.com',
|
||||
};
|
||||
|
||||
const { readGitSettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readGitSettings).mockResolvedValue(settings);
|
||||
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('1');
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://custom-cors.example.com');
|
||||
});
|
||||
});
|
||||
|
||||
it('provides default CORS proxy', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://cors.isomorphic-git.org');
|
||||
});
|
||||
});
|
||||
|
||||
it('can update CORS proxy', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://cors.isomorphic-git.org');
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText('Update CORS Proxy'));
|
||||
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://custom-cors.example.com');
|
||||
});
|
||||
|
||||
|
||||
});
|
||||
@@ -1,105 +0,0 @@
|
||||
import { ReactNode, useState, useEffect } from 'react';
|
||||
import { GitSettingsContext, type GitSettings, type GitCredential, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { readGitSettings, writeGitSettings } from '@/lib/configUtils';
|
||||
|
||||
interface GitSettingsProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: GitSettings = {
|
||||
credentials: {},
|
||||
corsProxy: 'https://cors.isomorphic-git.org',
|
||||
};
|
||||
|
||||
export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
const { fs } = useFS();
|
||||
const [settings, setSettings] = useState<GitSettings>(DEFAULT_SETTINGS);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
// Initialize settings from VFS on mount
|
||||
useEffect(() => {
|
||||
const initializeSettings = async () => {
|
||||
try {
|
||||
const settings = await readGitSettings(fs);
|
||||
setSettings(settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize Git settings:', error);
|
||||
setSettings(DEFAULT_SETTINGS);
|
||||
} finally {
|
||||
setIsInitialized(true);
|
||||
}
|
||||
};
|
||||
|
||||
initializeSettings();
|
||||
}, [fs]);
|
||||
|
||||
// Save settings to VFS whenever they change (but not during initialization)
|
||||
useEffect(() => {
|
||||
if (!isInitialized) return;
|
||||
|
||||
const saveSettings = async () => {
|
||||
try {
|
||||
await writeGitSettings(fs, settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to save Git settings:', error);
|
||||
}
|
||||
};
|
||||
|
||||
saveSettings();
|
||||
}, [fs, settings, isInitialized]);
|
||||
|
||||
const updateSettings = (newSettings: Partial<GitSettings>) => {
|
||||
setSettings(prev => ({ ...prev, ...newSettings }));
|
||||
};
|
||||
|
||||
const addCredential = (origin: string, credential: GitCredential) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
credentials: {
|
||||
...prev.credentials,
|
||||
[origin]: credential,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const removeCredential = (origin: string) => {
|
||||
setSettings(prev => {
|
||||
const { [origin]: removed, ...rest } = prev.credentials;
|
||||
return {
|
||||
...prev,
|
||||
credentials: rest,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const updateCredential = (origin: string, credential: Partial<GitCredential>) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
credentials: {
|
||||
...prev.credentials,
|
||||
[origin]: {
|
||||
...prev.credentials[origin],
|
||||
...credential,
|
||||
},
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const isConfigured = Object.entries(settings.credentials).length > 0;
|
||||
|
||||
const contextValue: GitSettingsContextType = {
|
||||
settings,
|
||||
updateSettings,
|
||||
addCredential,
|
||||
removeCredential,
|
||||
updateCredential,
|
||||
isConfigured,
|
||||
};
|
||||
|
||||
return (
|
||||
<GitSettingsContext.Provider value={contextValue}>
|
||||
{children}
|
||||
</GitSettingsContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { GitStatusIndicator } from './GitStatusIndicator';
|
||||
|
||||
// Mock the useGitStatus hook
|
||||
vi.mock('@/hooks/useGitStatus', () => ({
|
||||
useGitStatus: vi.fn(),
|
||||
}));
|
||||
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
|
||||
describe('GitStatusIndicator', () => {
|
||||
it('should not render when not in a git repo', () => {
|
||||
vi.mocked(useGitStatus).mockReturnValue({
|
||||
data: {
|
||||
hasUncommittedChanges: false,
|
||||
changedFiles: [],
|
||||
isGitRepo: false,
|
||||
},
|
||||
} as unknown as ReturnType<typeof useGitStatus>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<GitStatusIndicator projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('should not render when no uncommitted changes', () => {
|
||||
vi.mocked(useGitStatus).mockReturnValue({
|
||||
data: {
|
||||
hasUncommittedChanges: false,
|
||||
changedFiles: [],
|
||||
isGitRepo: true,
|
||||
},
|
||||
} as unknown as ReturnType<typeof useGitStatus>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<GitStatusIndicator projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('should render yellow dot when there are uncommitted changes', () => {
|
||||
vi.mocked(useGitStatus).mockReturnValue({
|
||||
data: {
|
||||
hasUncommittedChanges: true,
|
||||
changedFiles: ['file1.txt', 'file2.txt'],
|
||||
isGitRepo: true,
|
||||
},
|
||||
} as unknown as ReturnType<typeof useGitStatus>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<GitStatusIndicator projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const indicator = container.firstChild as HTMLElement;
|
||||
expect(indicator).toBeTruthy();
|
||||
expect(indicator.className).toContain('bg-yellow-500');
|
||||
expect(indicator.className).toContain('rounded-full');
|
||||
expect(indicator.title).toBe('2 uncommitted changes');
|
||||
});
|
||||
|
||||
it('should handle singular file count in tooltip', () => {
|
||||
vi.mocked(useGitStatus).mockReturnValue({
|
||||
data: {
|
||||
hasUncommittedChanges: true,
|
||||
changedFiles: ['file1.txt'],
|
||||
isGitRepo: true,
|
||||
},
|
||||
} as unknown as ReturnType<typeof useGitStatus>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<GitStatusIndicator projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const indicator = container.firstChild as HTMLElement;
|
||||
expect(indicator.title).toBe('1 uncommitted change');
|
||||
});
|
||||
});
|
||||
@@ -1,27 +0,0 @@
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface GitStatusIndicatorProps {
|
||||
projectId: string | null;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function GitStatusIndicator({ projectId, className }: GitStatusIndicatorProps) {
|
||||
const { data: gitStatus } = useGitStatus(projectId);
|
||||
|
||||
// Only show the indicator if we're in a git repo and have uncommitted changes
|
||||
if (!gitStatus?.isGitRepo || !gitStatus?.hasUncommittedChanges) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"w-2 h-2 bg-yellow-500 rounded-full animate-pulse",
|
||||
"shadow-sm shadow-yellow-500/50",
|
||||
className
|
||||
)}
|
||||
title={`${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { JSRuntimeContext, type JSRuntimeContextType } from '@/contexts/JSRuntimeContext';
|
||||
import type { JSRuntime } from '@/lib/JSRuntime';
|
||||
|
||||
interface JSRuntimeProviderProps {
|
||||
children: ReactNode;
|
||||
runtime: JSRuntime;
|
||||
}
|
||||
|
||||
export function JSRuntimeProvider({ children, runtime }: JSRuntimeProviderProps) {
|
||||
const contextValue: JSRuntimeContextType = { runtime };
|
||||
|
||||
return (
|
||||
<JSRuntimeContext.Provider value={contextValue}>
|
||||
{children}
|
||||
</JSRuntimeContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,256 +0,0 @@
|
||||
import { useState, useMemo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ModelSelectorProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export function ModelSelector({
|
||||
value,
|
||||
onChange,
|
||||
className,
|
||||
disabled = false,
|
||||
placeholder = "Select or enter a model...",
|
||||
}: ModelSelectorProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [isCustomInput, setIsCustomInput] = useState(false);
|
||||
const [customValue, setCustomValue] = useState('');
|
||||
const { settings, addRecentlyUsedModel, isConfigured } = useAISettings();
|
||||
const { models, isLoading, error, refetch } = useProviderModels();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]);
|
||||
|
||||
// Group models by provider
|
||||
const modelsByProvider = useMemo(() => {
|
||||
const groups: Record<string, typeof models> = {};
|
||||
for (const model of models) {
|
||||
if (!groups[model.provider]) {
|
||||
groups[model.provider] = [];
|
||||
}
|
||||
groups[model.provider].push(model);
|
||||
}
|
||||
return groups;
|
||||
}, [models]);
|
||||
|
||||
// Don't auto-initialize with recently used models
|
||||
// Let the parent component handle initialization
|
||||
|
||||
const handleSelect = (selectedValue: string) => {
|
||||
if (selectedValue === '__custom__') {
|
||||
setIsCustomInput(true);
|
||||
setCustomValue(value);
|
||||
setOpen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedValue === '__manage_providers__') {
|
||||
navigate('/settings/ai');
|
||||
setOpen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
onChange(selectedValue);
|
||||
addRecentlyUsedModel(selectedValue);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleCustomSubmit = () => {
|
||||
if (customValue.trim()) {
|
||||
onChange(customValue.trim());
|
||||
addRecentlyUsedModel(customValue.trim());
|
||||
setIsCustomInput(false);
|
||||
setCustomValue('');
|
||||
}
|
||||
};
|
||||
|
||||
const handleCustomKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleCustomSubmit();
|
||||
} else if (e.key === 'Escape') {
|
||||
setIsCustomInput(false);
|
||||
setCustomValue('');
|
||||
}
|
||||
};
|
||||
|
||||
if (isCustomInput) {
|
||||
return (
|
||||
<div className={cn("flex items-center gap-1", className)}>
|
||||
<Input
|
||||
value={customValue}
|
||||
onChange={(e) => setCustomValue(e.target.value)}
|
||||
onKeyDown={handleCustomKeyDown}
|
||||
onBlur={handleCustomSubmit}
|
||||
placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)"
|
||||
className="h-8 text-xs"
|
||||
autoFocus
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 w-8 p-0"
|
||||
onClick={handleCustomSubmit}
|
||||
>
|
||||
<Check className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
className={cn(
|
||||
"h-8 p-0 gap-0.5 justify-between text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right",
|
||||
className
|
||||
)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<span className="w-full truncate">
|
||||
{value || placeholder}
|
||||
</span>
|
||||
<ChevronDown className="size-3 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-96 p-0" align="end">
|
||||
<Command>
|
||||
{isConfigured && <CommandInput placeholder="Search models..." className="h-9" />}
|
||||
<CommandList className="max-h-[300px]">
|
||||
{/* Custom model option and manage providers */}
|
||||
<CommandGroup>
|
||||
{isConfigured && (
|
||||
<CommandItem
|
||||
value="__custom_model_option__"
|
||||
onSelect={() => handleSelect('__custom__')}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Edit3 className="mr-2 h-4 w-4" />
|
||||
Enter custom model...
|
||||
</CommandItem>
|
||||
)}
|
||||
<CommandItem
|
||||
value="__manage_providers_option__"
|
||||
onSelect={() => handleSelect('__manage_providers__')}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
Manage providers...
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
|
||||
<CommandSeparator />
|
||||
|
||||
<CommandEmpty>
|
||||
<div className="py-6 text-center text-sm text-muted-foreground">
|
||||
<p>No models found.</p>
|
||||
<p className="mt-2 text-xs">Try using a custom model instead.</p>
|
||||
</div>
|
||||
</CommandEmpty>
|
||||
|
||||
{recentlyUsedModels.length > 0 && (
|
||||
<CommandGroup heading="Recently Used">
|
||||
{recentlyUsedModels.map((model) => (
|
||||
<CommandItem
|
||||
key={model}
|
||||
value={model}
|
||||
onSelect={() => handleSelect(model)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
value === model ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
<span className="truncate">{model}</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
)}
|
||||
|
||||
{recentlyUsedModels.length > 0 && <CommandSeparator />}
|
||||
|
||||
{/* Loading state */}
|
||||
{isLoading && (
|
||||
<CommandGroup heading="Loading Models...">
|
||||
<div className="px-2 py-1.5">
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4 w-1/2" />
|
||||
</div>
|
||||
</div>
|
||||
</CommandGroup>
|
||||
)}
|
||||
|
||||
{/* Error state */}
|
||||
{error && !isLoading && (
|
||||
<CommandGroup heading="Error Loading Models">
|
||||
<div className="px-2 py-1.5 text-sm text-muted-foreground">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
|
||||
<div className="space-y-2">
|
||||
<p className="text-destructive">{error}</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={refetch}
|
||||
className="h-7 text-xs"
|
||||
>
|
||||
<RefreshCw className="h-3 w-3 mr-1" />
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CommandGroup>
|
||||
)}
|
||||
|
||||
{/* Provider models */}
|
||||
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
|
||||
<div key={provider}>
|
||||
<CommandSeparator />
|
||||
<CommandGroup heading={provider}>
|
||||
{providerModels.map((model) => (
|
||||
<CommandItem
|
||||
key={model.fullId}
|
||||
value={model.fullId}
|
||||
onSelect={() => handleSelect(model.fullId)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
value === model.fullId ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
<span className="truncate">{model.fullId}</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</div>
|
||||
))}
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -1,359 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { type Project } from '@/lib/ProjectsManager';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import {
|
||||
Calendar,
|
||||
Folder,
|
||||
GitBranch,
|
||||
Package,
|
||||
FileText,
|
||||
GitCommit,
|
||||
GitMerge,
|
||||
Globe,
|
||||
Clock,
|
||||
User,
|
||||
Hash,
|
||||
AlertCircle,
|
||||
CheckCircle,
|
||||
Plus,
|
||||
Minus,
|
||||
Edit,
|
||||
Eye
|
||||
} from 'lucide-react';
|
||||
|
||||
interface ProjectInfoDialogProps {
|
||||
project: Project;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
interface ProjectMetadata {
|
||||
description?: string;
|
||||
version?: string;
|
||||
nostrRepoAddress?: string;
|
||||
fileCount?: number;
|
||||
}
|
||||
|
||||
export function ProjectInfoDialog({ project, open, onOpenChange }: ProjectInfoDialogProps) {
|
||||
const [metadata, setMetadata] = useState<ProjectMetadata>({});
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const projectsManager = useProjectsManager();
|
||||
const gitStatus = useGitStatus(project.id);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
const loadProjectMetadata = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const meta: ProjectMetadata = {};
|
||||
|
||||
// Try to read package.json
|
||||
try {
|
||||
const packageJsonContent = await projectsManager.readFile(project.id, 'package.json');
|
||||
const packageJson = JSON.parse(packageJsonContent);
|
||||
meta.description = packageJson.description;
|
||||
meta.version = packageJson.version;
|
||||
} catch {
|
||||
// package.json doesn't exist or is invalid
|
||||
}
|
||||
|
||||
// Get Nostr repo address
|
||||
try {
|
||||
const repoAddress = await projectsManager.getNostrRepoAddress(project.id);
|
||||
if (repoAddress) {
|
||||
meta.nostrRepoAddress = repoAddress;
|
||||
}
|
||||
} catch {
|
||||
// No Nostr repo configured
|
||||
}
|
||||
|
||||
// Calculate file count and size (simplified)
|
||||
try {
|
||||
const files = await projectsManager.listFiles(project.id);
|
||||
meta.fileCount = files.length;
|
||||
} catch {
|
||||
// Can't read directory
|
||||
}
|
||||
|
||||
setMetadata(meta);
|
||||
} catch (error) {
|
||||
console.error('Failed to load project metadata:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadProjectMetadata();
|
||||
}, [open, project.id, projectsManager]);
|
||||
|
||||
const formatDate = (date: Date) => {
|
||||
return new Intl.DateTimeFormat('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(date);
|
||||
};
|
||||
|
||||
const formatDistanceToNow = (date: Date) => {
|
||||
const now = new Date();
|
||||
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
|
||||
|
||||
if (diffInSeconds < 60) return 'just now';
|
||||
if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} minutes ago`;
|
||||
if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} hours ago`;
|
||||
if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)} days ago`;
|
||||
if (diffInSeconds < 31536000) return `${Math.floor(diffInSeconds / 2592000)} months ago`;
|
||||
return `${Math.floor(diffInSeconds / 31536000)} years ago`;
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Folder className="h-5 w-5" />
|
||||
{project.name}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Project information and metadata
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="space-y-4">
|
||||
<div className="animate-pulse">
|
||||
<div className="h-4 bg-muted rounded w-3/4 mb-2"></div>
|
||||
<div className="h-4 bg-muted rounded w-1/2"></div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
{/* Basic Information */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
Basic Information
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Folder className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Project ID:</span>
|
||||
<code className="bg-muted px-1.5 py-0.5 rounded text-xs">{project.id}</code>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Last Modified:</span>
|
||||
<span>{formatDistanceToNow(project.lastModified)}</span>
|
||||
</div>
|
||||
{metadata.version && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Package className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Version:</span>
|
||||
<Badge variant="secondary">{metadata.version}</Badge>
|
||||
</div>
|
||||
)}
|
||||
{metadata.fileCount !== undefined && (
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Files:</span>
|
||||
<span>{metadata.fileCount}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-sm">
|
||||
<span className="text-muted-foreground">Created:</span>
|
||||
<span className="ml-2">{formatDate(project.lastModified)}</span>
|
||||
</div>
|
||||
{metadata.description && (
|
||||
<div className="text-sm">
|
||||
<span className="text-muted-foreground">Description:</span>
|
||||
<p className="mt-1 text-foreground">{metadata.description}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Nostr Information */}
|
||||
{metadata.nostrRepoAddress && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-2">
|
||||
<GitBranch className="h-4 w-4" />
|
||||
Nostr Repository
|
||||
</h3>
|
||||
<div className="text-sm">
|
||||
<span className="text-muted-foreground">Repository Address:</span>
|
||||
<code className="ml-2 bg-muted px-1.5 py-0.5 rounded text-xs break-all">
|
||||
{metadata.nostrRepoAddress}
|
||||
</code>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Git Status Information */}
|
||||
<Separator />
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-2">
|
||||
<GitCommit className="h-4 w-4" />
|
||||
Git Repository
|
||||
</h3>
|
||||
|
||||
{gitStatus.isLoading ? (
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4 w-1/2" />
|
||||
<Skeleton className="h-4 w-2/3" />
|
||||
</div>
|
||||
) : !gitStatus.data?.isGitRepo ? (
|
||||
<div className="text-sm text-muted-foreground flex items-center gap-2">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
This project is not a Git repository
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{/* Repository Status */}
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
{/* Current Branch */}
|
||||
<div className="flex items-center gap-2">
|
||||
<GitBranch className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Branch:</span>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{gitStatus.data?.currentBranch || 'unknown'}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{/* Uncommitted Changes */}
|
||||
<div className="flex items-center gap-2">
|
||||
{gitStatus.data?.hasUncommittedChanges ? (
|
||||
<>
|
||||
<AlertCircle className="h-4 w-4 text-orange-500" />
|
||||
<span className="text-muted-foreground">Status:</span>
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
{gitStatus.data.changedFiles.length} uncommitted changes
|
||||
</Badge>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle className="h-4 w-4 text-green-500" />
|
||||
<span className="text-muted-foreground">Status:</span>
|
||||
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
|
||||
Clean working tree
|
||||
</Badge>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Total Commits */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Hash className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Commits:</span>
|
||||
<span>{gitStatus.data?.totalCommits || 0}</span>
|
||||
</div>
|
||||
|
||||
{/* All Branches */}
|
||||
<div className="flex items-center gap-2">
|
||||
<GitMerge className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Branches:</span>
|
||||
<span>{gitStatus.data?.branches.length || 0}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Latest Commit */}
|
||||
{gitStatus.data?.latestCommit && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
Latest Commit
|
||||
</h4>
|
||||
<div className="bg-muted/30 rounded-md p-3 space-y-2">
|
||||
<div className="flex items-start gap-2">
|
||||
<GitCommit className="h-4 w-4 text-muted-foreground mt-0.5" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium break-words">
|
||||
{gitStatus.data.latestCommit.message.split('\n')[0]}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground font-mono">
|
||||
{gitStatus.data.latestCommit.oid.substring(0, 7)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-xs text-muted-foreground">
|
||||
<div className="flex items-center gap-1">
|
||||
<User className="h-3 w-3" />
|
||||
{gitStatus.data.latestCommit.author.name}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(gitStatus.data.latestCommit.author.timestamp * 1000).toLocaleDateString()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Changed Files */}
|
||||
{gitStatus.data?.hasUncommittedChanges && gitStatus.data.changedFiles.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
Uncommitted Changes
|
||||
</h4>
|
||||
<div className="space-y-1 max-h-32 overflow-y-auto">
|
||||
{gitStatus.data.changedFiles.map((file, index) => (
|
||||
<div key={index} className="flex items-center gap-2 text-sm">
|
||||
{file.status === 'added' && <Plus className="h-3 w-3 text-green-500" />}
|
||||
{file.status === 'modified' && <Edit className="h-3 w-3 text-blue-500" />}
|
||||
{file.status === 'deleted' && <Minus className="h-3 w-3 text-red-500" />}
|
||||
{file.status === 'untracked' && <Eye className="h-3 w-3 text-orange-500" />}
|
||||
{file.status === 'staged' && <CheckCircle className="h-3 w-3 text-purple-500" />}
|
||||
<span className="text-muted-foreground capitalize">{file.status}:</span>
|
||||
<code className="text-xs bg-muted px-1 py-0.5 rounded font-mono">
|
||||
{file.filepath}
|
||||
</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Remotes */}
|
||||
{gitStatus.data?.remotes && gitStatus.data.remotes.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
Remote Repositories
|
||||
</h4>
|
||||
<div className="space-y-1">
|
||||
{gitStatus.data.remotes.map((remote, index) => (
|
||||
<div key={index} className="flex items-center gap-2 text-sm">
|
||||
<Globe className="h-3 w-3 text-muted-foreground" />
|
||||
<span className="text-muted-foreground font-medium">{remote.name}:</span>
|
||||
<code className="text-xs bg-muted px-1 py-0.5 rounded font-mono break-all">
|
||||
{remote.url}
|
||||
</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
+420
-149
@@ -1,146 +1,336 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Plus, Folder, GitBranch, Settings, Loader2, ChevronDown, Star, Columns2 } from 'lucide-react';
|
||||
import { Plus, Loader2, Info, MoreVertical, Trash2, Eye, Star, Bug, Folder, Download } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Label } from '@/components/ui/label';
|
||||
|
||||
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { LoginArea } from '@/components/auth/LoginArea';
|
||||
import { useProjects } from '@/hooks/useProjects';
|
||||
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import type { Project } from '@/lib/ProjectsManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
interface ProjectItemProps {
|
||||
project: Project;
|
||||
isSelected: boolean;
|
||||
onSelect: (project: Project) => void;
|
||||
isFavorite?: boolean;
|
||||
}
|
||||
|
||||
const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect, isFavorite }) => {
|
||||
const navigate = useNavigate();
|
||||
const { hasRunningSessions } = useProjectSessionStatus(project.id);
|
||||
|
||||
const handleClick = () => {
|
||||
onSelect(project);
|
||||
navigate(`/project/${project.id}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"group relative rounded-lg transition-all duration-200 hover:bg-gradient-to-r hover:from-primary/10 hover:to-accent/10",
|
||||
isSelected && "bg-gradient-to-r from-primary/15 to-accent/15 shadow-sm"
|
||||
)}
|
||||
>
|
||||
<div className="w-full px-3 py-2 text-left text-sidebar-foreground">
|
||||
<button
|
||||
onClick={handleClick}
|
||||
className="absolute inset-0"
|
||||
/>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex-shrink-0">
|
||||
{hasRunningSessions ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-blue-600 dark:text-blue-400" />
|
||||
) : (
|
||||
<Folder className="h-4 w-4 text-primary" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex justify-between gap-2 flex-1 min-w-0">
|
||||
<div className="min-w-0 flex-1 flex items-center">
|
||||
<h3 className="font-medium text-sm truncate">
|
||||
{project.name}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
{/* Star indicator - only shown when favorited */}
|
||||
{isFavorite && (
|
||||
<div className="flex-shrink-0 relative -mr-1 pointer-events-none">
|
||||
<div className="flex items-center justify-center">
|
||||
<Star className="h-4 w-4 text-yellow-500 fill-current" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
ProjectItem.displayName = 'ProjectItem';
|
||||
import JSZip from 'jszip';
|
||||
import git from 'isomorphic-git';
|
||||
|
||||
interface ProjectSidebarProps {
|
||||
selectedProject: Project | null;
|
||||
onSelectProject: (project: Project | null) => void;
|
||||
className?: string;
|
||||
showCollapseButton?: boolean;
|
||||
onCollapse?: () => void;
|
||||
}
|
||||
|
||||
export function ProjectSidebar({
|
||||
selectedProject,
|
||||
onSelectProject,
|
||||
className,
|
||||
showCollapseButton = false,
|
||||
onCollapse
|
||||
className
|
||||
}: ProjectSidebarProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { data: projects = [], isLoading, error } = useProjects();
|
||||
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
const [favorites, setFavorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||
const projectsManager = useProjectsManager();
|
||||
const navigate = useNavigate();
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
|
||||
// Load projects on mount
|
||||
React.useEffect(() => {
|
||||
const loadProjects = async () => {
|
||||
try {
|
||||
await projectsManager.init();
|
||||
const projectList = await projectsManager.getProjects();
|
||||
setProjects(projectList);
|
||||
} catch (error) {
|
||||
console.error('Failed to load projects:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadProjects();
|
||||
}, [projectsManager]);
|
||||
|
||||
const handleNewProject = () => {
|
||||
onSelectProject(null);
|
||||
navigate('/');
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
}, [favorites, queryClient]);
|
||||
const handleDeleteProject = async (project: Project) => {
|
||||
setIsDeleting(true);
|
||||
try {
|
||||
await projectsManager.deleteProject(project.id);
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to load projects:', error);
|
||||
}
|
||||
// Remove from local state
|
||||
setProjects(prev => prev.filter(p => p.id !== project.id));
|
||||
|
||||
// If the deleted project was selected, deselect it
|
||||
if (selectedProject?.id === project.id) {
|
||||
onSelectProject(null);
|
||||
navigate('/');
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Project deleted",
|
||||
description: `"${project.name}" has been permanently deleted.`,
|
||||
});
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Failed to delete project",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleFavorite = (project: Project) => {
|
||||
const wasFavorite = favorites.includes(project.id);
|
||||
const newFavorites = wasFavorite
|
||||
? favorites.filter(id => id !== project.id)
|
||||
: [...favorites, project.id];
|
||||
|
||||
setFavorites(newFavorites);
|
||||
|
||||
toast({
|
||||
title: wasFavorite ? "Project Unfavorited" : "Project Favorited",
|
||||
description: `"${project.name}" has been ${wasFavorite ? 'removed from' : 'added to'} your favorites.`,
|
||||
});
|
||||
};
|
||||
|
||||
const isFavorite = (projectId: string) => favorites.includes(projectId);
|
||||
|
||||
const exportFilesAsZip = async (projectName: string) => {
|
||||
const zip = new JSZip();
|
||||
|
||||
// Recursive function to add files and directories to zip
|
||||
const addToZip = async (dirPath: string, zipFolder: JSZip) => {
|
||||
try {
|
||||
const entries = await fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = dirPath === '/' ? `/${entry.name}` : `${dirPath}/${entry.name}`;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
// Create folder in zip and recursively add its contents
|
||||
const folder = zipFolder.folder(entry.name);
|
||||
if (folder) {
|
||||
await addToZip(fullPath, folder);
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
// Add file to zip
|
||||
try {
|
||||
const fileContent = await fs.readFile(fullPath);
|
||||
zipFolder.file(entry.name, fileContent);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to read file ${fullPath}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to read directory ${dirPath}:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
// Start from root directory
|
||||
await addToZip('/', zip);
|
||||
|
||||
// Generate zip file
|
||||
const content = await zip.generateAsync({ type: 'blob' });
|
||||
|
||||
// Create download link
|
||||
const url = URL.createObjectURL(content);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
|
||||
// Generate filename with date
|
||||
const now = new Date();
|
||||
const dateStr = now.toISOString().split('T')[0]; // YYYY-MM-DD format
|
||||
link.download = `${projectName}-${dateStr}.zip`;
|
||||
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
const handleExportFiles = async () => {
|
||||
setIsExporting(true);
|
||||
try {
|
||||
const projectName = selectedProject?.name || 'shakespeare';
|
||||
await exportFilesAsZip(projectName);
|
||||
|
||||
toast({
|
||||
title: "Files exported successfully",
|
||||
description: "Your project files have been downloaded as a zip file.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to export files:', error);
|
||||
toast({
|
||||
title: "Failed to export files",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExportProject = async (project: Project) => {
|
||||
setIsExporting(true);
|
||||
try {
|
||||
const zip = new JSZip();
|
||||
const projectPath = `/projects/${project.id}`;
|
||||
|
||||
// Recursive function to add files and directories to zip from a specific project
|
||||
const addProjectToZip = async (dirPath: string, zipFolder: JSZip) => {
|
||||
try {
|
||||
const entries = await fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = `${dirPath}/${entry.name}`;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
// Create folder in zip and recursively add its contents
|
||||
const folder = zipFolder.folder(entry.name);
|
||||
if (folder) {
|
||||
await addProjectToZip(fullPath, folder);
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
// Add file to zip
|
||||
try {
|
||||
const fileContent = await fs.readFile(fullPath);
|
||||
zipFolder.file(entry.name, fileContent);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to read file ${fullPath}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to read directory ${dirPath}:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
// Start from the project directory
|
||||
await addProjectToZip(projectPath, zip);
|
||||
|
||||
// Generate zip file
|
||||
const content = await zip.generateAsync({ type: 'blob' });
|
||||
|
||||
// Create download link
|
||||
const url = URL.createObjectURL(content);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
|
||||
// Generate filename with commit hash
|
||||
let filename = `${project.name}.zip`;
|
||||
try {
|
||||
// Get the current commit hash
|
||||
const commits = await git.log({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
depth: 1,
|
||||
});
|
||||
|
||||
if (commits.length > 0) {
|
||||
const commitHash = commits[0].oid.substring(0, 7); // Truncate to 7 characters
|
||||
filename = `${project.name}-${commitHash}.zip`;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to get commit hash, using project name only:', error);
|
||||
}
|
||||
|
||||
link.download = filename;
|
||||
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
toast({
|
||||
title: "Project exported successfully",
|
||||
description: `"${project.name}" has been downloaded as a zip file.`,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to export project:', error);
|
||||
toast({
|
||||
title: "Failed to export project",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Sort projects: favorites first, then by lastModified (newest first)
|
||||
const sortedProjects = projects.sort((a, b) => {
|
||||
const aIsFavorite = isFavorite(a.id);
|
||||
const bIsFavorite = isFavorite(b.id);
|
||||
|
||||
if (aIsFavorite && !bIsFavorite) return -1;
|
||||
if (!aIsFavorite && bIsFavorite) return 1;
|
||||
|
||||
return b.lastModified.getTime() - a.lastModified.getTime();
|
||||
});
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-col h-full bg-gradient-to-b from-sidebar to-sidebar/95", className)}>
|
||||
{/* Header with Logo */}
|
||||
<div className="flex px-4 h-12 border-b border-sidebar-border bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<button
|
||||
onClick={() => navigate('/')}
|
||||
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
|
||||
>
|
||||
<span className="text-2xl">🎭</span>
|
||||
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
Shakespeare
|
||||
</h1>
|
||||
</button>
|
||||
<div className="flex items-center gap-1">
|
||||
{/* Collapse button - shown when showCollapseButton is true */}
|
||||
{showCollapseButton && onCollapse && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 hover:bg-primary/10"
|
||||
onClick={onCollapse}
|
||||
aria-label="Collapse sidebar"
|
||||
>
|
||||
<Columns2 className="h-4 w-4 text-primary/60 hover:text-primary" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
|
||||
onClick={() => navigate('/settings')}
|
||||
>
|
||||
<Settings className="h-4 w-4 text-primary/60 hover:text-primary" />
|
||||
</Button>
|
||||
<div className="p-4 border-b border-sidebar-border bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
|
||||
<button
|
||||
onClick={() => navigate('/')}
|
||||
className="flex items-center gap-3 hover:opacity-80 transition-opacity w-full text-left"
|
||||
>
|
||||
<span className="text-2xl">🎭</span>
|
||||
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
Shakespeare
|
||||
</h1>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Info Section */}
|
||||
<div className="p-4 border-b border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-xs font-medium text-primary/80 uppercase tracking-wide">
|
||||
Projects
|
||||
</Label>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-4 w-4 p-0 hover:bg-primary/10">
|
||||
<MoreVertical className="h-3 w-3 text-primary/60 hover:text-primary" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={handleExportFiles}
|
||||
disabled={isExporting}
|
||||
className="flex items-center gap-2 w-full"
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
{isExporting ? 'Exporting...' : 'Export Files'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="https://soapbox.pub/mkstack" target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 w-full">
|
||||
<Info className="h-4 w-4" />
|
||||
About MKStack
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="https://github.com/soapbox-pub/mkstack/issues" target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 w-full">
|
||||
<Bug className="h-4 w-4" />
|
||||
Report an Issue
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -148,34 +338,14 @@ export function ProjectSidebar({
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="p-2">
|
||||
<div className="mb-2">
|
||||
<div className="relative rounded-md bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90 transition-all duration-200">
|
||||
<div className="flex">
|
||||
<button
|
||||
onClick={handleNewProject}
|
||||
className="flex-1 flex items-center justify-center px-3 py-2 text-sm font-medium text-primary-foreground rounded-l-md hover:bg-white/10 transition-colors"
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Project
|
||||
</button>
|
||||
<div className="w-px bg-white/20" />
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="px-2 py-2 text-primary-foreground hover:bg-white/10 rounded-r-md transition-colors">
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={() => navigate('/clone')}
|
||||
className="flex items-center gap-2 w-full"
|
||||
>
|
||||
<GitBranch className="h-4 w-4" />
|
||||
Import Repository
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
className="w-full bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90"
|
||||
onClick={handleNewProject}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Project
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
@@ -197,15 +367,116 @@ export function ProjectSidebar({
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{projects.map((project) => (
|
||||
<ProjectItem
|
||||
key={project.id}
|
||||
project={project}
|
||||
isSelected={selectedProject?.id === project.id}
|
||||
onSelect={onSelectProject}
|
||||
isFavorite={favorites.includes(project.id)}
|
||||
/>
|
||||
))}
|
||||
{sortedProjects.map((project) => (
|
||||
<div
|
||||
key={project.id}
|
||||
className={cn(
|
||||
"group relative rounded-lg transition-all duration-200 hover:bg-gradient-to-r hover:from-primary/10 hover:to-accent/10",
|
||||
selectedProject?.id === project.id && "bg-gradient-to-r from-primary/15 to-accent/15 shadow-sm"
|
||||
)}
|
||||
>
|
||||
<button
|
||||
onClick={() => {
|
||||
onSelectProject(project);
|
||||
navigate(`/project/${project.id}`);
|
||||
}}
|
||||
className="w-full p-3 text-left text-sidebar-foreground"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-start justify-between gap-2 flex-1 min-w-0">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<h3 className="font-medium text-sm truncate">
|
||||
{project.name}
|
||||
</h3>
|
||||
<div className="flex items-center gap-1 ml-auto">
|
||||
{isFavorite(project.id) && (
|
||||
<Star className="h-3 w-3 text-yellow-500 fill-current" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Dropdown Menu */}
|
||||
<div className="flex-shrink-0 -mt-1 -mr-1">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 hover:bg-primary/20"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<MoreVertical className="h-3 w-3" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleToggleFavorite(project)}
|
||||
>
|
||||
<Star className={cn(
|
||||
"h-4 w-4 mr-2",
|
||||
isFavorite(project.id) ? "text-yellow-500 fill-current" : "text-muted-foreground"
|
||||
)} />
|
||||
{isFavorite(project.id) ? "Unfavorite" : "Favorite"}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => navigate(`/project/${project.id}`)}
|
||||
>
|
||||
<Eye className="h-4 w-4 mr-2" />
|
||||
Open Project
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleExportProject(project)}
|
||||
disabled={isExporting}
|
||||
>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
{isExporting ? 'Exporting...' : 'Export Project'}
|
||||
</DropdownMenuItem>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive cursor-pointer"
|
||||
onSelect={(e) => e.preventDefault()}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
Delete Project
|
||||
</DropdownMenuItem>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Project</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete "{project.name}"? This action cannot be undone and will permanently delete all project data including files.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => handleDeleteProject(project)}
|
||||
disabled={isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{isDeleting ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Deleting...
|
||||
</>
|
||||
) : (
|
||||
'Delete Project'
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
import { ReactNode, useMemo, useEffect } from 'react';
|
||||
import { SessionManagerContext } from '@/contexts/SessionManagerContext';
|
||||
import { SessionManager } from '@/lib/SessionManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
|
||||
interface SessionManagerProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider that creates and manages the global session manager instance
|
||||
*/
|
||||
export function SessionManagerProvider({ children }: SessionManagerProviderProps) {
|
||||
const { fs } = useFS();
|
||||
const { settings } = useAISettings();
|
||||
const { models } = useProviderModels();
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
const sessionManager = useMemo(() => {
|
||||
const getProviderModels = () => models;
|
||||
const getCurrentUser = () => user;
|
||||
return new SessionManager(fs, settings, getProviderModels, getCurrentUser);
|
||||
}, [fs, settings, models, user]);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
// Fire and forget cleanup - we don't need to await in useEffect cleanup
|
||||
sessionManager.cleanup().catch(error => {
|
||||
console.warn('Failed to cleanup session manager:', error);
|
||||
});
|
||||
};
|
||||
}, [sessionManager]);
|
||||
|
||||
return (
|
||||
<SessionManagerContext.Provider value={sessionManager}>
|
||||
{children}
|
||||
</SessionManagerContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useNavigate, useLocation } from 'react-router-dom';
|
||||
|
||||
/**
|
||||
* Global component that monitors AI sessions and shows notifications
|
||||
* when sessions complete in the background
|
||||
*/
|
||||
export function SessionMonitor() {
|
||||
const sessionManager = useSessionManager();
|
||||
const { toast } = useToast();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const previousLoadingStates = useRef<Map<string, boolean>>(new Map());
|
||||
|
||||
useEffect(() => {
|
||||
const handleLoadingChanged = (projectId: string, isLoading: boolean) => {
|
||||
const wasLoading = previousLoadingStates.current.get(projectId);
|
||||
previousLoadingStates.current.set(projectId, isLoading);
|
||||
|
||||
// If session just finished loading (was loading, now not loading)
|
||||
if (wasLoading && !isLoading) {
|
||||
const session = sessionManager.getSession(projectId);
|
||||
if (!session) return;
|
||||
|
||||
// Check if user is currently viewing this project
|
||||
const currentProjectId = location.pathname.split('/')[2]; // /project/{projectId}
|
||||
const isCurrentProject = session.projectId === currentProjectId;
|
||||
|
||||
// Only show notification if user is not currently viewing this project
|
||||
if (!isCurrentProject) {
|
||||
toast({
|
||||
title: "AI Session Complete",
|
||||
description: `Finished working on ${session.projectId}`,
|
||||
action: (
|
||||
<button
|
||||
onClick={() => navigate(`/project/${session.projectId}`)}
|
||||
className="inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus-visible:ring-destructive"
|
||||
>
|
||||
View
|
||||
</button>
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleSessionCreated = (projectId: string) => {
|
||||
const session = sessionManager.getSession(projectId);
|
||||
if (session) {
|
||||
previousLoadingStates.current.set(projectId, session.isLoading);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSessionDeleted = (projectId: string) => {
|
||||
previousLoadingStates.current.delete(projectId);
|
||||
};
|
||||
|
||||
// Initialize with current sessions
|
||||
sessionManager.getAllSessions().forEach(session => {
|
||||
previousLoadingStates.current.set(session.projectId, session.isLoading);
|
||||
});
|
||||
|
||||
// Subscribe to events
|
||||
sessionManager.on('loadingChanged', handleLoadingChanged);
|
||||
sessionManager.on('sessionCreated', handleSessionCreated);
|
||||
sessionManager.on('sessionDeleted', handleSessionDeleted);
|
||||
|
||||
return () => {
|
||||
sessionManager.off('loadingChanged', handleLoadingChanged);
|
||||
sessionManager.off('sessionCreated', handleSessionCreated);
|
||||
sessionManager.off('sessionDeleted', handleSessionDeleted);
|
||||
};
|
||||
}, [sessionManager, toast, navigate, location.pathname]);
|
||||
|
||||
// This component doesn't render anything
|
||||
return null;
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Menu, Columns2, Bot, GitBranch, Database } from 'lucide-react';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { type Project } from '@/lib/ProjectsManager';
|
||||
import { useCallback } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface SettingsItem {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
href: string;
|
||||
}
|
||||
|
||||
const settingsItems: SettingsItem[] = [
|
||||
{
|
||||
id: 'ai',
|
||||
title: 'AI Settings',
|
||||
description: 'Configure AI providers and API keys',
|
||||
icon: Bot,
|
||||
href: '/settings/ai',
|
||||
},
|
||||
{
|
||||
id: 'git',
|
||||
title: 'Git Settings',
|
||||
description: 'Configure Git credentials for HTTP authentication',
|
||||
icon: GitBranch,
|
||||
href: '/settings/git',
|
||||
},
|
||||
{
|
||||
id: 'data',
|
||||
title: 'Data',
|
||||
description: 'Export files and manage local data',
|
||||
icon: Database,
|
||||
href: '/settings/data',
|
||||
},
|
||||
];
|
||||
|
||||
export function SettingsLayout() {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const isMobile = useIsMobile();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
const [_projects, setProjects] = useState<Project[]>([]);
|
||||
const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile);
|
||||
const [hasSetInitialState, setHasSetInitialState] = useState(false);
|
||||
|
||||
const loadProjects = useCallback(async () => {
|
||||
try {
|
||||
await projectsManager.init();
|
||||
const projectList = await projectsManager.getProjects();
|
||||
setProjects(projectList);
|
||||
|
||||
// Set initial sidebar state based on projects and device type
|
||||
if (!hasSetInitialState && !isMobile) {
|
||||
// On desktop, show sidebar if there are projects
|
||||
setIsSidebarVisible(projectList.length > 0);
|
||||
setHasSetInitialState(true);
|
||||
} else if (!hasSetInitialState && isMobile) {
|
||||
// On mobile, always start hidden
|
||||
setIsSidebarVisible(false);
|
||||
setHasSetInitialState(true);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load projects:', error);
|
||||
if (!hasSetInitialState) {
|
||||
setHasSetInitialState(true);
|
||||
}
|
||||
}
|
||||
}, [projectsManager, hasSetInitialState, isMobile]);
|
||||
|
||||
useEffect(() => {
|
||||
loadProjects();
|
||||
}, [loadProjects]);
|
||||
|
||||
const handleProjectSelect = (project: Project | null) => {
|
||||
if (project) {
|
||||
setIsSidebarVisible(false); // Collapse sidebar on mobile navigation
|
||||
navigate(`/project/${project.id}`);
|
||||
} else {
|
||||
navigate('/');
|
||||
}
|
||||
};
|
||||
|
||||
// Get current settings page
|
||||
const currentPath = location.pathname;
|
||||
const currentSettingsId = settingsItems.find(item => item.href === currentPath)?.id;
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<div className="min-h-dvh bg-white">
|
||||
{/* Mobile Header */}
|
||||
<header className="h-12 border-b bg-white px-4 py-3 flex items-center justify-between">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
|
||||
aria-label="Toggle sidebar"
|
||||
>
|
||||
<Menu className="h-4 w-4" />
|
||||
</Button>
|
||||
<h1 className="text-lg font-semibold">Settings</h1>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Mobile Sidebar Overlay */}
|
||||
{isSidebarVisible && (
|
||||
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm">
|
||||
<div
|
||||
className="absolute inset-0"
|
||||
onClick={() => setIsSidebarVisible(false)}
|
||||
/>
|
||||
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={(project) => {
|
||||
setIsSidebarVisible(false);
|
||||
handleProjectSelect(project);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Outlet />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Desktop 3-column layout
|
||||
return (
|
||||
<div className="h-screen flex bg-white overflow-hidden">
|
||||
{/* Left Column - Projects Sidebar (optionally hidden) */}
|
||||
{isSidebarVisible && (
|
||||
<div className="w-80 border-r bg-sidebar flex-shrink-0">
|
||||
<ProjectSidebar
|
||||
selectedProject={null}
|
||||
onSelectProject={handleProjectSelect}
|
||||
className="h-full"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Middle Column - Settings Navigation */}
|
||||
<div className="w-96 border-r bg-white flex flex-col flex-shrink-0">
|
||||
{/* Header with toggle button */}
|
||||
<div className="h-12 px-4 py-2 border-b flex-shrink-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
|
||||
className="h-8 w-8 p-0"
|
||||
aria-label="Toggle sidebar"
|
||||
>
|
||||
{isSidebarVisible ? <Columns2 className="h-4 w-4" /> : <Menu className="h-4 w-4" />}
|
||||
</Button>
|
||||
<h1 className="text-xl font-bold flex items-center gap-2">
|
||||
Settings
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Settings Navigation - Scrollable */}
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-4">
|
||||
<div className="space-y-2">
|
||||
{settingsItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = currentSettingsId === item.id;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
onClick={() => navigate(item.href)}
|
||||
className={cn('w-full text-left p-3 rounded-lg transition-colors border border-transparent', {
|
||||
'bg-primary/10 border border-primary/20': isActive,
|
||||
'hover:bg-muted/50': !isActive,
|
||||
})}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<Icon className={`h-5 w-5 mt-0.5 ${isActive ? 'text-primary' : 'text-muted-foreground'}`} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className={`font-medium ${isActive ? 'text-primary' : 'text-foreground'}`}>
|
||||
{item.title}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-0.5">
|
||||
{item.description}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
{/* Right Column - Settings Content - Scrollable */}
|
||||
<ScrollArea className="flex-1 bg-white">
|
||||
<div className="max-w-4xl">
|
||||
<Outlet />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { ChatPane } from './ChatPane';
|
||||
|
||||
// Mock the AI settings hook to return configured state
|
||||
vi.mock('@/hooks/useAISettings', () => ({
|
||||
useAISettings: () => ({
|
||||
isConfigured: true,
|
||||
settings: {
|
||||
recentlyUsedModels: ['gpt-4'],
|
||||
},
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock other hooks
|
||||
vi.mock('@/hooks/useFS', () => ({
|
||||
useFS: () => ({
|
||||
fs: {},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useCurrentUser', () => ({
|
||||
useCurrentUser: () => ({
|
||||
user: null,
|
||||
metadata: null,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useKeepAlive', () => ({
|
||||
useKeepAlive: () => ({
|
||||
updateMetadata: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useAIChat', () => ({
|
||||
useAIChat: () => ({
|
||||
messages: [],
|
||||
streamingMessage: null,
|
||||
isLoading: false,
|
||||
totalCost: 0,
|
||||
lastInputTokens: 0,
|
||||
sendMessage: vi.fn(),
|
||||
startGeneration: vi.fn(),
|
||||
stopGeneration: vi.fn(),
|
||||
startNewSession: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useProviderModels', () => ({
|
||||
useProviderModels: () => ({
|
||||
models: [
|
||||
{
|
||||
fullId: 'gpt-4',
|
||||
contextLength: 8192,
|
||||
},
|
||||
],
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('ChatPane', () => {
|
||||
it('handles image paste from clipboard', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const textarea = screen.getByPlaceholderText(/Ask me to add features/);
|
||||
expect(textarea).toBeInTheDocument();
|
||||
|
||||
// Create a mock image file
|
||||
const imageFile = new File(['fake-image-data'], 'test.png', {
|
||||
type: 'image/png',
|
||||
});
|
||||
|
||||
// Create mock clipboard data
|
||||
const mockClipboardItem = {
|
||||
type: 'image/png',
|
||||
getAsFile: () => imageFile,
|
||||
} as DataTransferItem;
|
||||
|
||||
const mockClipboardData = {
|
||||
items: [mockClipboardItem],
|
||||
length: 1,
|
||||
} as unknown as DataTransfer;
|
||||
|
||||
// Fire the paste event on the textarea using fireEvent
|
||||
fireEvent.paste(textarea, {
|
||||
clipboardData: mockClipboardData,
|
||||
});
|
||||
|
||||
// The file should be added to the attached files
|
||||
// We can't easily test the internal state, but we can verify the event was handled
|
||||
// without throwing an error
|
||||
expect(textarea).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders welcome message when no messages exist', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ChatPane projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Welcome to Shakespeare')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -4,21 +4,18 @@ import { Textarea } from '@/components/ui/textarea';
|
||||
import { CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Save, Loader2 } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
|
||||
interface FileEditorProps {
|
||||
filePath: string;
|
||||
content: string;
|
||||
onSave: (content: string) => void;
|
||||
isLoading: boolean;
|
||||
projectId?: string;
|
||||
}
|
||||
|
||||
export function FileEditor({ filePath, content, onSave, isLoading, projectId }: FileEditorProps) {
|
||||
export function FileEditor({ filePath, content, onSave, isLoading }: FileEditorProps) {
|
||||
const [editedContent, setEditedContent] = useState(content);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [hasChanges, setHasChanges] = useState(false);
|
||||
const { data: gitStatus } = useGitStatus(projectId || null);
|
||||
|
||||
useEffect(() => {
|
||||
setEditedContent(content);
|
||||
@@ -67,36 +64,11 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
|
||||
return 'font-mono text-sm';
|
||||
};
|
||||
|
||||
// Helper function to get git status for the current file
|
||||
const getFileGitStatus = (filePath: string) => {
|
||||
if (!gitStatus?.changedFiles) return null;
|
||||
const fileChange = gitStatus.changedFiles.find(change => change.filepath === filePath);
|
||||
return fileChange?.status || null;
|
||||
};
|
||||
|
||||
// Helper function to get styling classes based on git status
|
||||
const getGitStatusClasses = (status: string | null) => {
|
||||
switch (status) {
|
||||
case 'added':
|
||||
case 'untracked':
|
||||
return 'text-green-600 dark:text-green-400';
|
||||
case 'modified':
|
||||
case 'staged':
|
||||
return 'text-yellow-600 dark:text-yellow-400';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
// Get git status for the current file
|
||||
const currentFileGitStatus = getFileGitStatus(filePath);
|
||||
const gitStatusClasses = getGitStatusClasses(currentFileGitStatus);
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
<CardHeader className="border-b py-2 sm:py-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className={cn("text-sm sm:text-base truncate flex-1 mr-2", gitStatusClasses)}>{filePath}</CardTitle>
|
||||
<CardTitle className="text-sm sm:text-base truncate flex-1 mr-2">{filePath}</CardTitle>
|
||||
<div className="flex items-center space-x-1 sm:space-x-2">
|
||||
{hasChanges && (
|
||||
<span className="text-xs sm:text-sm text-muted-foreground hidden sm:inline">Unsaved changes</span>
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { ChevronRight, ChevronDown, File, Folder, Search } from 'lucide-react';
|
||||
import { ChevronRight, ChevronDown, File, Folder } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { createGitignoreFilter, normalizePathForGitignore } from '@/lib/gitignore';
|
||||
import { Input } from '@/components/ui/input';
|
||||
|
||||
interface FileTreeProps {
|
||||
projectId: string;
|
||||
@@ -23,63 +20,9 @@ interface FileNode {
|
||||
|
||||
export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProps) {
|
||||
const [tree, setTree] = useState<FileNode[]>([]);
|
||||
const [filteredTree, setFilteredTree] = useState<FileNode[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [gitignoreFilter, setGitignoreFilter] = useState<{
|
||||
isIgnored: (path: string) => boolean;
|
||||
shouldShow: (path: string) => boolean;
|
||||
} | null>(null);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [isSearching, setIsSearching] = useState(false);
|
||||
const { fs } = useFS();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { data: gitStatus } = useGitStatus(projectId);
|
||||
|
||||
// Helper function to get git status for a file
|
||||
const getFileGitStatus = (filePath: string) => {
|
||||
if (!gitStatus?.changedFiles) return null;
|
||||
const fileChange = gitStatus.changedFiles.find(change => change.filepath === filePath);
|
||||
return fileChange?.status || null;
|
||||
};
|
||||
|
||||
// Helper function to get git status for a directory
|
||||
const getDirectoryGitStatus = (dirPath: string, _children: FileNode[]): 'modified' | 'added' | null => {
|
||||
if (!gitStatus?.changedFiles) return null;
|
||||
|
||||
// Check if any files in this directory or subdirectories have changes
|
||||
const hasChanges = gitStatus.changedFiles.some(change =>
|
||||
change.filepath.startsWith(dirPath + '/') ||
|
||||
(dirPath === '' && !change.filepath.includes('/'))
|
||||
);
|
||||
|
||||
if (!hasChanges) return null;
|
||||
|
||||
// Check if all changes are new files (added/untracked)
|
||||
const relevantChanges = gitStatus.changedFiles.filter(change =>
|
||||
change.filepath.startsWith(dirPath + '/') ||
|
||||
(dirPath === '' && !change.filepath.includes('/'))
|
||||
);
|
||||
|
||||
const allAdded = relevantChanges.every(change =>
|
||||
change.status === 'added' || change.status === 'untracked'
|
||||
);
|
||||
|
||||
return allAdded ? 'added' : 'modified';
|
||||
};
|
||||
|
||||
// Helper function to get styling classes based on git status
|
||||
const getGitStatusClasses = (status: string | null) => {
|
||||
switch (status) {
|
||||
case 'added':
|
||||
case 'untracked':
|
||||
return 'text-green-600 dark:text-green-400';
|
||||
case 'modified':
|
||||
case 'staged':
|
||||
return 'text-yellow-600 dark:text-yellow-400';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
const buildFileTree = useCallback(async (projectId: string, dirPath: string): Promise<FileNode[]> => {
|
||||
const items = await projectsManager.listFiles(projectId, dirPath);
|
||||
@@ -124,20 +67,14 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
const loadFileTree = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
// Load gitignore filter
|
||||
const projectPath = `${projectsManager['dir']}/${projectId}`;
|
||||
const filter = await createGitignoreFilter(fs, projectPath);
|
||||
setGitignoreFilter(filter);
|
||||
|
||||
const structure = await buildFileTree(projectId, '');
|
||||
setTree(structure);
|
||||
setFilteredTree(structure);
|
||||
} catch (_error) {
|
||||
console.error('Failed to load file tree:', _error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [projectId, buildFileTree, fs, projectsManager]);
|
||||
}, [projectId, buildFileTree]);
|
||||
|
||||
useEffect(() => {
|
||||
loadFileTree();
|
||||
@@ -156,9 +93,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
});
|
||||
};
|
||||
|
||||
// Update both the original tree and filtered tree
|
||||
setTree(prev => toggleNode(prev));
|
||||
setFilteredTree(prev => toggleNode(prev));
|
||||
};
|
||||
|
||||
const handleFileClick = (filePath: string, type: 'file' | 'directory') => {
|
||||
@@ -169,76 +104,9 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
}
|
||||
};
|
||||
|
||||
// Search functions
|
||||
const searchInFiles = useCallback(async (nodes: FileNode[], term: string): Promise<FileNode[]> => {
|
||||
if (!term.trim()) return nodes;
|
||||
|
||||
const results: FileNode[] = [];
|
||||
const searchTermLower = term.toLowerCase();
|
||||
|
||||
for (const node of nodes) {
|
||||
if (node.type === 'file') {
|
||||
const fileNameMatch = node.name.toLowerCase().includes(searchTermLower);
|
||||
|
||||
if (fileNameMatch) {
|
||||
results.push(node);
|
||||
}
|
||||
} else if (node.type === 'directory' && node.children) {
|
||||
const childResults = await searchInFiles(node.children, term);
|
||||
if (childResults.length > 0) {
|
||||
// Create a filtered directory node with matching children
|
||||
results.push({
|
||||
...node,
|
||||
children: childResults,
|
||||
isOpen: true, // Auto-expand directories with matches
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results }, []);
|
||||
|
||||
// Perform search when search term changes
|
||||
useEffect(() => {
|
||||
const performSearch = async () => {
|
||||
if (!searchTerm.trim()) {
|
||||
setFilteredTree(tree);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSearching(true);
|
||||
try {
|
||||
const results = await searchInFiles(tree, searchTerm);
|
||||
setFilteredTree(results);
|
||||
} catch (error) {
|
||||
console.error('Search failed:', error);
|
||||
setFilteredTree([]);
|
||||
} finally {
|
||||
setIsSearching(false);
|
||||
}
|
||||
};
|
||||
|
||||
performSearch();
|
||||
}, [searchTerm, tree, searchInFiles]);
|
||||
|
||||
const renderNode = (node: FileNode, depth: number = 0) => {
|
||||
const isSelected = selectedFile === node.path;
|
||||
|
||||
// Get git status for this node
|
||||
const gitFileStatus = node.type === 'file' ? getFileGitStatus(node.path) : null;
|
||||
const gitDirStatus = node.type === 'directory' ? getDirectoryGitStatus(node.path, node.children || []) : null;
|
||||
const gitStatus = gitFileStatus || gitDirStatus;
|
||||
|
||||
// Check if this file/directory is gitignored
|
||||
const normalizedPath = normalizePathForGitignore(node.path);
|
||||
const isGitignored = gitignoreFilter?.isIgnored(normalizedPath) ?? false;
|
||||
|
||||
// Get styling classes for git status
|
||||
const gitStatusClasses = getGitStatusClasses(gitStatus);
|
||||
|
||||
// Apply muted styling for gitignored files
|
||||
const gitignoreClasses = isGitignored ? 'text-muted-foreground' : '';
|
||||
|
||||
return (
|
||||
<div key={node.path}>
|
||||
<div
|
||||
@@ -253,19 +121,19 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
{node.type === 'directory' ? (
|
||||
<>
|
||||
{node.isOpen ? (
|
||||
<ChevronDown className={cn("h-4 w-4 flex-shrink-0", gitignoreClasses)} />
|
||||
<ChevronDown className="h-4 w-4 flex-shrink-0" />
|
||||
) : (
|
||||
<ChevronRight className={cn("h-4 w-4 flex-shrink-0", gitignoreClasses)} />
|
||||
<ChevronRight className="h-4 w-4 flex-shrink-0" />
|
||||
)}
|
||||
<Folder className={cn("h-4 w-4 text-blue-500 flex-shrink-0", gitignoreClasses)} />
|
||||
<Folder className="h-4 w-4 text-blue-500 flex-shrink-0" />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="w-4" /> {/* Spacer for alignment */}
|
||||
<File className={cn("h-4 w-4 text-gray-500 flex-shrink-0", gitignoreClasses)} />
|
||||
<File className="h-4 w-4 text-gray-500 flex-shrink-0" />
|
||||
</>
|
||||
)}
|
||||
<span className={cn("text-sm whitespace-nowrap", gitStatusClasses, gitignoreClasses)}>{node.name}</span>
|
||||
<span className="text-sm truncate">{node.name}</span>
|
||||
</div>
|
||||
|
||||
{node.type === 'directory' && node.isOpen && node.children && (
|
||||
@@ -291,32 +159,12 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
|
||||
return (
|
||||
<div className="p-2">
|
||||
{/* Search Section */}
|
||||
<div className="mb-3">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search files..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* File Tree */}
|
||||
{isSearching ? (
|
||||
<div className="space-y-2">
|
||||
{[...Array(3)].map((_, i) => (
|
||||
<div key={i} className="h-6 bg-muted rounded animate-pulse"></div>
|
||||
))}
|
||||
</div>
|
||||
) : filteredTree.length === 0 ? (
|
||||
<div className="text-center text-sm text-muted-foreground py-4">
|
||||
{searchTerm ? 'No files found matching your search' : 'No files found'}
|
||||
{tree.length === 0 ? (
|
||||
<div className="text-center text-sm text-muted-foreground py-8">
|
||||
No files found
|
||||
</div>
|
||||
) : (
|
||||
filteredTree.map(node => renderNode(node))
|
||||
tree.map(node => renderNode(node))
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { encodeBase64 } from '@std/encoding/base64';
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FolderOpen, ArrowLeft } from 'lucide-react';
|
||||
import { RefreshCw, FolderOpen, ArrowLeft } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
||||
|
||||
import { FileTree } from './FileTree';
|
||||
import { FileEditor } from './FileEditor';
|
||||
@@ -55,9 +52,6 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor'>('explorer');
|
||||
const isMobile = useIsMobile();
|
||||
const [hasBuiltProject, setHasBuiltProject] = useState(false);
|
||||
const [currentPath, setCurrentPath] = useState('/');
|
||||
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
|
||||
const [historyIndex, setHistoryIndex] = useState(0);
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
const { fs } = useFS();
|
||||
const projectsManager = useProjectsManager();
|
||||
@@ -125,51 +119,6 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
}
|
||||
}, []);
|
||||
|
||||
const navigateToPath = useCallback((path: string) => {
|
||||
if (iframeRef.current) {
|
||||
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
|
||||
const newUrl = `${baseUrl}${path}`;
|
||||
iframeRef.current.src = newUrl;
|
||||
setCurrentPath(path);
|
||||
|
||||
// Update navigation history
|
||||
const newHistory = navigationHistory.slice(0, historyIndex + 1);
|
||||
newHistory.push(path);
|
||||
setNavigationHistory(newHistory);
|
||||
setHistoryIndex(newHistory.length - 1);
|
||||
}
|
||||
}, [projectId, navigationHistory, historyIndex]);
|
||||
|
||||
const goBack = useCallback(() => {
|
||||
if (historyIndex > 0) {
|
||||
const newIndex = historyIndex - 1;
|
||||
const path = navigationHistory[newIndex];
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentPath(path);
|
||||
|
||||
if (iframeRef.current) {
|
||||
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
|
||||
const newUrl = `${baseUrl}${path}`;
|
||||
iframeRef.current.src = newUrl;
|
||||
}
|
||||
}
|
||||
}, [historyIndex, navigationHistory, projectId]);
|
||||
|
||||
const goForward = useCallback(() => {
|
||||
if (historyIndex < navigationHistory.length - 1) {
|
||||
const newIndex = historyIndex + 1;
|
||||
const path = navigationHistory[newIndex];
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentPath(path);
|
||||
|
||||
if (iframeRef.current) {
|
||||
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
|
||||
const newUrl = `${baseUrl}${path}`;
|
||||
iframeRef.current.src = newUrl;
|
||||
}
|
||||
}
|
||||
}, [historyIndex, navigationHistory, projectId]);
|
||||
|
||||
const sendResponse = useCallback((message: JSONRPCResponse) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
console.log(`Sending response to iframe:`, message);
|
||||
@@ -215,9 +164,8 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
|
||||
// SPA routing: try to serve the exact file first
|
||||
try {
|
||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
|
||||
const file = await projectsManager.readFile(projectId, 'dist' + filePath);
|
||||
console.log(`Serving file: ${filePath}`);
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
@@ -227,7 +175,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
'Content-Type': getContentType(filePath),
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
body: encodeBase64(bytes),
|
||||
body: file,
|
||||
},
|
||||
id
|
||||
});
|
||||
@@ -239,9 +187,8 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
|
||||
// SPA fallback: serve index.html for non-file requests
|
||||
try {
|
||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
|
||||
const indexFile = await projectsManager.readFile(projectId, 'dist/index.html');
|
||||
console.log(`Serving index.html fallback for: ${path}`);
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
@@ -251,14 +198,13 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
'Content-Type': 'text/html',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
body: encodeBase64(bytes),
|
||||
body: indexFile,
|
||||
},
|
||||
id
|
||||
});
|
||||
} catch {
|
||||
// Even index.html doesn't exist
|
||||
console.log(`No files found, returning 404 for: ${path}`);
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
@@ -267,7 +213,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
headers: {
|
||||
'Content-Type': 'text/plain',
|
||||
},
|
||||
body: encodeBase64(`File not found: ${path}`),
|
||||
body: `File not found: ${path}`,
|
||||
},
|
||||
id
|
||||
});
|
||||
@@ -356,18 +302,20 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
<TabsContent value="preview" className="h-full mt-0">
|
||||
{hasBuiltProject ? (
|
||||
<div className="h-full w-full flex flex-col">
|
||||
<BrowserAddressBar
|
||||
currentPath={currentPath}
|
||||
onNavigate={navigateToPath}
|
||||
onRefresh={refreshIframe}
|
||||
onBack={goBack}
|
||||
onForward={goForward}
|
||||
canGoBack={historyIndex > 0}
|
||||
canGoForward={historyIndex < navigationHistory.length - 1}
|
||||
/>
|
||||
<div className="flex items-center justify-between p-2 border-b bg-gradient-to-r from-primary/5 to-accent/5">
|
||||
<span className="text-sm font-medium bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">Project Preview</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={refreshIframe}
|
||||
className="h-8 w-8 p-0 hover:bg-primary/10"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.local-shakespeare.dev${currentPath}`}
|
||||
src={`https://${projectId}.local-shakespeare.dev/`}
|
||||
className="w-full flex-1 border-0"
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin"
|
||||
@@ -380,6 +328,20 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
<p className="text-muted-foreground mb-4">
|
||||
Build your project to see the preview here
|
||||
</p>
|
||||
<div className="bg-background border rounded-lg p-8 max-w-md">
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Run the build command to generate <code className="bg-muted px-1 rounded">dist/index.html</code>
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={checkForBuiltProject}
|
||||
className="gap-2"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
Check for Build
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -391,20 +353,14 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
{mobileCodeView === 'explorer' ? (
|
||||
<>
|
||||
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
</div>
|
||||
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
|
||||
</div>
|
||||
<ScrollArea className="flex-1">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</>
|
||||
) : (
|
||||
@@ -421,7 +377,6 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
<h3 className="font-semibold flex-1 truncate bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
{selectedFile ? selectedFile.split('/').pop() : 'File Editor'}
|
||||
</h3>
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
{selectedFile ? (
|
||||
@@ -430,7 +385,6 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
content={fileContent}
|
||||
onSave={handleFileSave}
|
||||
isLoading={isLoading}
|
||||
projectId={projectId}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center">
|
||||
@@ -458,20 +412,14 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
<div className="h-full flex">
|
||||
<div className="w-1/3 border-r">
|
||||
<div className="p-4 border-b bg-gradient-to-r from-primary/5 to-accent/5">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
</div>
|
||||
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
|
||||
</div>
|
||||
<ScrollArea className="h-[calc(100%-60px)]">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
@@ -482,7 +430,6 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
content={fileContent}
|
||||
onSave={handleFileSave}
|
||||
isLoading={isLoading}
|
||||
projectId={projectId}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center">
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Star } from 'lucide-react';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface StarButtonProps {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
className?: string;
|
||||
size?: 'sm' | 'default' | 'lg';
|
||||
variant?: 'ghost' | 'outline' | 'default';
|
||||
showToast?: boolean;
|
||||
}
|
||||
|
||||
export function StarButton({
|
||||
projectId,
|
||||
projectName,
|
||||
className,
|
||||
size = 'sm',
|
||||
variant = 'ghost',
|
||||
showToast = true
|
||||
}: StarButtonProps) {
|
||||
const [favorites, setFavorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const isFavorite = favorites.includes(projectId);
|
||||
|
||||
const handleToggleFavorite = (e: React.MouseEvent) => {
|
||||
e.stopPropagation(); // Prevent triggering parent click events
|
||||
|
||||
const newFavorites = isFavorite
|
||||
? favorites.filter(id => id !== projectId)
|
||||
: [...favorites, projectId];
|
||||
|
||||
setFavorites(newFavorites);
|
||||
|
||||
// Invalidate the projects query to trigger a refetch with new sorting
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
|
||||
if (showToast) {
|
||||
toast({
|
||||
title: isFavorite ? "Project Unfavorited" : "Project Favorited",
|
||||
description: `"${projectName}" has been ${isFavorite ? 'removed from' : 'added to'} your favorites.`,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant={variant}
|
||||
size={size}
|
||||
onClick={handleToggleFavorite}
|
||||
className={cn(
|
||||
"h-8 w-8 p-0",
|
||||
className
|
||||
)}
|
||||
aria-label={isFavorite ? "Remove from favorites" : "Add to favorites"}
|
||||
>
|
||||
<Star
|
||||
className={cn(
|
||||
"h-4 w-4",
|
||||
isFavorite ? "text-yellow-500 fill-current" : "text-muted-foreground hover:text-yellow-500"
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { UserMessage } from './UserMessage';
|
||||
|
||||
describe('UserMessage Integration', () => {
|
||||
it('renders text parts with file attachments correctly', () => {
|
||||
// Simulate the new text parts structure that ChatPane would create
|
||||
const content = [
|
||||
{ type: 'text' as const, text: 'Please analyze this file:' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/data.csv' },
|
||||
{ type: 'text' as const, text: 'Let me know what you find!' }
|
||||
];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
// Check that regular text is displayed
|
||||
expect(screen.getByText('Please analyze this file:')).toBeInTheDocument();
|
||||
expect(screen.getByText('Let me know what you find!')).toBeInTheDocument();
|
||||
|
||||
// Check that file attachment is rendered as a badge
|
||||
expect(screen.getByText('data.csv')).toBeInTheDocument();
|
||||
// Full path should not be displayed
|
||||
expect(screen.queryByText('/tmp/data.csv')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles single text part with file attachment', () => {
|
||||
const content = [
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/script.js' }
|
||||
];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('script.js')).toBeInTheDocument();
|
||||
// Full path should not be displayed
|
||||
expect(screen.queryByText('/tmp/script.js')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles multiple file attachments in separate parts', () => {
|
||||
const content = [
|
||||
{ type: 'text' as const, text: 'Here are my files:' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/config.json' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/styles.css' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/main.js' }
|
||||
];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('Here are my files:')).toBeInTheDocument();
|
||||
expect(screen.getByText('config.json')).toBeInTheDocument();
|
||||
expect(screen.getByText('styles.css')).toBeInTheDocument();
|
||||
expect(screen.getByText('main.js')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles empty content gracefully', () => {
|
||||
const content: Array<{ type: 'text'; text: string }> = [];
|
||||
|
||||
const { container } = render(<UserMessage content={content} />);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,110 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { UserMessage } from './UserMessage';
|
||||
|
||||
describe('UserMessage', () => {
|
||||
it('renders regular text without file attachments', () => {
|
||||
const content = 'This is a regular message without any file attachments.';
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText(content)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles backward compatibility with string content containing file attachments', () => {
|
||||
const content = 'Here is my file: Added file: /tmp/test.txt';
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
// When using string content, it should still work but won't separate file attachments
|
||||
expect(screen.getByText(content)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders file attachment badges for single file with text parts', () => {
|
||||
const content = [
|
||||
{ type: 'text' as const, text: 'Here is my file:' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/test.txt' }
|
||||
];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('Here is my file:')).toBeInTheDocument();
|
||||
expect(screen.getByText('test.txt')).toBeInTheDocument();
|
||||
// Full path should not be displayed
|
||||
expect(screen.queryByText('/tmp/test.txt')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders multiple file attachments with text parts', () => {
|
||||
const content = [
|
||||
{ type: 'text' as const, text: 'Files uploaded:' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/document.pdf' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/image.jpg' },
|
||||
{ type: 'text' as const, text: 'All done!' }
|
||||
];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('Files uploaded:')).toBeInTheDocument();
|
||||
expect(screen.getByText('document.pdf')).toBeInTheDocument();
|
||||
expect(screen.getByText('image.jpg')).toBeInTheDocument();
|
||||
expect(screen.getByText('All done!')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders text files with FileText icon', () => {
|
||||
const content = [{ type: 'text' as const, text: 'Added file: /tmp/script.js' }];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('script.js')).toBeInTheDocument();
|
||||
// FileText icon should be rendered (we can't easily test the icon itself, but we can test the component renders)
|
||||
});
|
||||
|
||||
it('handles files without extensions', () => {
|
||||
const content = [{ type: 'text' as const, text: 'Added file: /tmp/README' }];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('README')).toBeInTheDocument();
|
||||
// Full path should not be displayed
|
||||
expect(screen.queryByText('/tmp/README')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles complex filenames with underscores and numbers', () => {
|
||||
const content = [{ type: 'text' as const, text: 'Added file: /tmp/my_file_1.txt' }];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('my_file_1.txt')).toBeInTheDocument();
|
||||
// Full path should not be displayed
|
||||
expect(screen.queryByText('/tmp/my_file_1.txt')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('preserves whitespace in text content', () => {
|
||||
const content = [
|
||||
{ type: 'text' as const, text: 'Line 1\n\nLine 3 with spaces \n\nFinal line' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/test.txt' }
|
||||
];
|
||||
|
||||
const { container } = render(<UserMessage content={content} />);
|
||||
|
||||
// Check that the component renders and contains the expected text content
|
||||
expect(container.textContent).toContain('Line 1');
|
||||
expect(container.textContent).toContain('Line 3 with spaces');
|
||||
expect(container.textContent).toContain('Final line');
|
||||
expect(screen.getByText('test.txt')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('handles mixed content with file attachments in the middle', () => {
|
||||
const content = [
|
||||
{ type: 'text' as const, text: 'Starting text' },
|
||||
{ type: 'text' as const, text: 'Added file: /tmp/middle.txt' },
|
||||
{ type: 'text' as const, text: 'ending text' }
|
||||
];
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
expect(screen.getByText('Starting text')).toBeInTheDocument();
|
||||
expect(screen.getByText('middle.txt')).toBeInTheDocument();
|
||||
expect(screen.getByText('ending text')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,85 +0,0 @@
|
||||
import { FileText, File } from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import type OpenAI from 'openai';
|
||||
|
||||
interface UserMessageProps {
|
||||
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Component to render user messages nicely
|
||||
* Handles both string content and array content (text parts)
|
||||
* Detects "Added file: /tmp/<filename>" patterns and renders them as badges
|
||||
*/
|
||||
export function UserMessage({ content }: UserMessageProps) {
|
||||
// Convert content to array format for uniform processing
|
||||
const contentParts = typeof content === 'string'
|
||||
? [{ type: 'text' as const, text: content }]
|
||||
: content.filter(part => part.type === 'text') as Array<{ type: 'text'; text: string }>;
|
||||
|
||||
// Regular expression to match "Added file: /tmp/<filename>" patterns
|
||||
const filePattern = /^Added file: (\/tmp\/[^\s\n]+)$/;
|
||||
|
||||
// Process each content part and categorize as text or file
|
||||
const processedParts: Array<{ type: 'text' | 'file'; content: string; filepath?: string }> = [];
|
||||
|
||||
contentParts.forEach(part => {
|
||||
const text = part.text.trim();
|
||||
const match = text.match(filePattern);
|
||||
|
||||
if (match) {
|
||||
// This is a file attachment
|
||||
const filepath = match[1]; // "/tmp/filename.txt"
|
||||
processedParts.push({ type: 'file', content: text, filepath });
|
||||
} else if (text) {
|
||||
// This is regular text content
|
||||
processedParts.push({ type: 'text', content: text });
|
||||
}
|
||||
});
|
||||
|
||||
// If no content, return empty
|
||||
if (processedParts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const getFileIcon = (filename: string) => {
|
||||
const extension = filename.split('.').pop()?.toLowerCase();
|
||||
|
||||
// Return FileText icon for text-like files, File icon for others
|
||||
const textExtensions = ['txt', 'md', 'json', 'js', 'ts', 'jsx', 'tsx', 'css', 'html', 'xml', 'yml', 'yaml'];
|
||||
|
||||
if (extension && textExtensions.includes(extension)) {
|
||||
return <FileText className="h-3 w-3" />;
|
||||
}
|
||||
|
||||
return <File className="h-3 w-3" />;
|
||||
};
|
||||
|
||||
const getFileName = (filepath: string) => {
|
||||
return filepath.split('/').pop() || filepath;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{processedParts.map((part, index) => {
|
||||
if (part.type === 'text') {
|
||||
return (
|
||||
<div key={index} className="whitespace-pre-wrap">
|
||||
{part.content}
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
const filename = getFileName(part.filepath!);
|
||||
return (
|
||||
<div key={index} className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="flex items-center gap-1.5 px-2 py-1">
|
||||
{getFileIcon(filename)}
|
||||
<span className="text-xs font-medium">{filename}</span>
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,395 +0,0 @@
|
||||
import { useState, forwardRef } from 'react';
|
||||
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
DrawerTrigger,
|
||||
DrawerClose,
|
||||
} from '@/components/ui/drawer';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
|
||||
|
||||
interface WalletModalProps {
|
||||
children?: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
// Extracted AddWalletContent to prevent re-renders
|
||||
const AddWalletContent = forwardRef<HTMLDivElement, {
|
||||
alias: string;
|
||||
setAlias: (value: string) => void;
|
||||
connectionUri: string;
|
||||
setConnectionUri: (value: string) => void;
|
||||
}>(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (
|
||||
<div className="space-y-4 px-4" ref={ref}>
|
||||
<div>
|
||||
<Label htmlFor="alias">Wallet Name (optional)</Label>
|
||||
<Input
|
||||
id="alias"
|
||||
placeholder="My Lightning Wallet"
|
||||
value={alias}
|
||||
onChange={(e) => setAlias(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="connection-uri">Connection URI</Label>
|
||||
<Textarea
|
||||
id="connection-uri"
|
||||
placeholder="nostr+walletconnect://..."
|
||||
value={connectionUri}
|
||||
onChange={(e) => setConnectionUri(e.target.value)}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
));
|
||||
AddWalletContent.displayName = 'AddWalletContent';
|
||||
|
||||
// Extracted WalletContent to prevent re-renders
|
||||
const WalletContent = forwardRef<HTMLDivElement, {
|
||||
hasWebLN: boolean;
|
||||
isDetecting: boolean;
|
||||
hasNWC: boolean;
|
||||
connections: NWCConnection[];
|
||||
connectionInfo: Record<string, NWCInfo>;
|
||||
activeConnection: string | null;
|
||||
handleSetActive: (cs: string) => void;
|
||||
handleRemoveConnection: (cs: string) => void;
|
||||
setAddDialogOpen: (open: boolean) => void;
|
||||
}>(({
|
||||
hasWebLN,
|
||||
isDetecting,
|
||||
hasNWC,
|
||||
connections,
|
||||
connectionInfo,
|
||||
activeConnection,
|
||||
handleSetActive,
|
||||
handleRemoveConnection,
|
||||
setAddDialogOpen
|
||||
}, ref) => (
|
||||
<div className="space-y-6 px-4 pb-4" ref={ref}>
|
||||
{/* Current Status */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="font-medium">Current Status</h3>
|
||||
<div className="grid gap-3">
|
||||
{/* WebLN */}
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<Globe className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">WebLN</p>
|
||||
<p className="text-xs text-muted-foreground">Browser extension</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
|
||||
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
{/* NWC */}
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">Nostr Wallet Connect</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{connections.length > 0
|
||||
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
|
||||
: "Remote wallet connection"
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{hasNWC && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={hasNWC ? "default" : "secondary"} className="text-xs">
|
||||
{hasNWC ? "Ready" : "None"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Separator />
|
||||
{/* NWC Management */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-medium">Nostr Wallet Connect</h3>
|
||||
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
{/* Connected Wallets List */}
|
||||
{connections.length === 0 ? (
|
||||
<div className="text-center py-6 text-muted-foreground">
|
||||
<p className="text-sm">No wallets connected</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{connections.map((connection) => {
|
||||
const info = connectionInfo[connection.connectionString];
|
||||
const isActive = activeConnection === connection.connectionString;
|
||||
return (
|
||||
<div key={connection.connectionString} className={`flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`}>
|
||||
<div className="flex items-center gap-3">
|
||||
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
{connection.alias || info?.alias || 'Lightning Wallet'}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
NWC Connection
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{isActive && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
{!isActive && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleSetActive(connection.connectionString)}
|
||||
>
|
||||
<Zap className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleRemoveConnection(connection.connectionString)}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* Help */}
|
||||
{!hasWebLN && connections.length === 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="text-center py-4 space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Install a WebLN extension or connect a NWC wallet for zaps.
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
));
|
||||
WalletContent.displayName = 'WalletContent';
|
||||
|
||||
export function WalletModal({ children, className }: WalletModalProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
||||
const [connectionUri, setConnectionUri] = useState('');
|
||||
const [alias, setAlias] = useState('');
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
const {
|
||||
connections,
|
||||
activeConnection,
|
||||
connectionInfo,
|
||||
addConnection,
|
||||
removeConnection,
|
||||
setActiveConnection
|
||||
} = useNWC();
|
||||
|
||||
const { hasWebLN, isDetecting } = useWallet();
|
||||
|
||||
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
|
||||
const { toast } = useToast();
|
||||
|
||||
const handleAddConnection = async () => {
|
||||
if (!connectionUri.trim()) {
|
||||
toast({
|
||||
title: 'Connection URI required',
|
||||
description: 'Please enter a valid NWC connection URI.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsConnecting(true);
|
||||
try {
|
||||
const success = await addConnection(connectionUri.trim(), alias.trim() || undefined);
|
||||
if (success) {
|
||||
setConnectionUri('');
|
||||
setAlias('');
|
||||
setAddDialogOpen(false);
|
||||
}
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveConnection = (connectionString: string) => {
|
||||
removeConnection(connectionString);
|
||||
};
|
||||
|
||||
const handleSetActive = (connectionString: string) => {
|
||||
setActiveConnection(connectionString);
|
||||
toast({
|
||||
title: 'Active wallet changed',
|
||||
description: 'The selected wallet is now active for zaps.',
|
||||
});
|
||||
};
|
||||
|
||||
const walletContentProps = {
|
||||
hasWebLN,
|
||||
isDetecting,
|
||||
hasNWC,
|
||||
connections,
|
||||
connectionInfo,
|
||||
activeConnection,
|
||||
handleSetActive,
|
||||
handleRemoveConnection,
|
||||
setAddDialogOpen,
|
||||
};
|
||||
|
||||
const addWalletDialog = (
|
||||
<Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Connect NWC Wallet</DialogTitle>
|
||||
<DialogDescription>
|
||||
Enter your connection string from a compatible wallet.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<AddWalletContent
|
||||
alias={alias}
|
||||
setAlias={setAlias}
|
||||
connectionUri={connectionUri}
|
||||
setConnectionUri={setConnectionUri}
|
||||
/>
|
||||
<DialogFooter className="px-4">
|
||||
<Button
|
||||
onClick={handleAddConnection}
|
||||
disabled={isConnecting || !connectionUri.trim()}
|
||||
className="w-full"
|
||||
>
|
||||
{isConnecting ? 'Connecting...' : 'Connect'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<>
|
||||
<Drawer open={open} onOpenChange={setOpen}>
|
||||
<DrawerTrigger asChild>
|
||||
{children || (
|
||||
<Button variant="outline" size="sm" className={className}>
|
||||
<Wallet className="h-4 w-4 mr-2" />
|
||||
Wallet Settings
|
||||
</Button>
|
||||
)}
|
||||
</DrawerTrigger>
|
||||
<DrawerContent className="h-full">
|
||||
<DrawerHeader className="text-center relative">
|
||||
<DrawerClose asChild>
|
||||
<Button variant="ghost" size="sm" className="absolute right-4 top-4">
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</Button>
|
||||
</DrawerClose>
|
||||
<DrawerTitle className="flex items-center justify-center gap-2 pt-2">
|
||||
<Wallet className="h-5 w-5" />
|
||||
Lightning Wallet
|
||||
</DrawerTitle>
|
||||
<DrawerDescription>
|
||||
Connect your lightning wallet to send zaps instantly.
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
<div className="overflow-y-auto">
|
||||
<WalletContent {...walletContentProps} />
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
{/* Render Add Wallet as a separate Drawer for mobile */}
|
||||
<Drawer open={addDialogOpen} onOpenChange={setAddDialogOpen}>
|
||||
<DrawerContent>
|
||||
<DrawerHeader>
|
||||
<DrawerTitle>Connect NWC Wallet</DrawerTitle>
|
||||
<DrawerDescription>
|
||||
Enter your connection string from a compatible wallet.
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
<AddWalletContent
|
||||
alias={alias}
|
||||
setAlias={setAlias}
|
||||
connectionUri={connectionUri}
|
||||
setConnectionUri={setConnectionUri}
|
||||
/>
|
||||
<div className="p-4">
|
||||
<Button
|
||||
onClick={handleAddConnection}
|
||||
disabled={isConnecting || !connectionUri.trim()}
|
||||
className="w-full"
|
||||
>
|
||||
{isConnecting ? 'Connecting...' : 'Connect'}
|
||||
</Button>
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{children || (
|
||||
<Button variant="outline" size="sm" className={className}>
|
||||
<Wallet className="h-4 w-4 mr-2" />
|
||||
Wallet Settings
|
||||
</Button>
|
||||
)}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[500px] max-h-[80vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Wallet className="h-5 w-5" />
|
||||
Lightning Wallet
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Connect your lightning wallet to send zaps instantly.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<WalletContent {...walletContentProps} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
{addWalletDialog}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import { ZapDialog } from '@/components/ZapDialog';
|
||||
import { useZaps } from '@/hooks/useZaps';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { Zap } from 'lucide-react';
|
||||
import type { Event } from 'nostr-tools';
|
||||
|
||||
interface ZapButtonProps {
|
||||
target: Event;
|
||||
className?: string;
|
||||
showCount?: boolean;
|
||||
zapData?: { count: number; totalSats: number; isLoading?: boolean };
|
||||
}
|
||||
|
||||
export function ZapButton({
|
||||
target,
|
||||
className = "text-xs ml-1",
|
||||
showCount = true,
|
||||
zapData: externalZapData
|
||||
}: ZapButtonProps) {
|
||||
const { user } = useCurrentUser();
|
||||
const { data: author } = useAuthor(target?.pubkey || '');
|
||||
const { webln, activeNWC } = useWallet();
|
||||
|
||||
// Only fetch data if not provided externally
|
||||
const { totalSats: fetchedTotalSats, isLoading } = useZaps(
|
||||
externalZapData ? [] : target ?? [], // Empty array prevents fetching if external data provided
|
||||
webln,
|
||||
activeNWC
|
||||
);
|
||||
|
||||
// Don't show zap button if user is not logged in, is the author, or author has no lightning address
|
||||
if (!user || !target || user.pubkey === target.pubkey || (!author?.metadata?.lud16 && !author?.metadata?.lud06)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Use external data if provided, otherwise use fetched data
|
||||
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
|
||||
const showLoading = externalZapData?.isLoading || isLoading;
|
||||
|
||||
return (
|
||||
<ZapDialog target={target}>
|
||||
<div className={`flex items-center gap-1 ${className}`}>
|
||||
<Zap className="h-4 w-4" />
|
||||
<span className="text-xs">
|
||||
{showLoading ? (
|
||||
'...'
|
||||
) : showCount && totalSats > 0 ? (
|
||||
`${totalSats.toLocaleString()}`
|
||||
) : (
|
||||
'Zap'
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</ZapDialog>
|
||||
);
|
||||
}
|
||||
@@ -1,470 +0,0 @@
|
||||
import { useState, useEffect, useRef, forwardRef } from 'react';
|
||||
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
DrawerTrigger,
|
||||
DrawerClose,
|
||||
} from '@/components/ui/drawer';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useZaps } from '@/hooks/useZaps';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import QRCode from 'qrcode';
|
||||
|
||||
interface ZapDialogProps {
|
||||
target: Event;
|
||||
children?: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const presetAmounts = [
|
||||
{ amount: 1, icon: Sparkle },
|
||||
{ amount: 50, icon: Sparkles },
|
||||
{ amount: 100, icon: Zap },
|
||||
{ amount: 250, icon: Star },
|
||||
{ amount: 1000, icon: Rocket },
|
||||
];
|
||||
|
||||
interface ZapContentProps {
|
||||
invoice: string | null;
|
||||
amount: number | string;
|
||||
comment: string;
|
||||
isZapping: boolean;
|
||||
qrCodeUrl: string;
|
||||
copied: boolean;
|
||||
hasWebLN: boolean;
|
||||
handleZap: () => void;
|
||||
handleCopy: () => void;
|
||||
openInWallet: () => void;
|
||||
setAmount: (amount: number | string) => void;
|
||||
setComment: (comment: string) => void;
|
||||
inputRef: React.RefObject<HTMLInputElement>;
|
||||
zap: (amount: number, comment: string) => void;
|
||||
}
|
||||
|
||||
// Moved ZapContent outside of ZapDialog to prevent re-renders causing focus loss
|
||||
const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
||||
invoice,
|
||||
amount,
|
||||
comment,
|
||||
isZapping,
|
||||
qrCodeUrl,
|
||||
copied,
|
||||
hasWebLN,
|
||||
handleZap,
|
||||
handleCopy,
|
||||
openInWallet,
|
||||
setAmount,
|
||||
setComment,
|
||||
inputRef,
|
||||
zap,
|
||||
}, ref) => (
|
||||
<div ref={ref}>
|
||||
{invoice ? (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
{/* Payment amount display */}
|
||||
<div className="text-center pt-4">
|
||||
<div className="text-2xl font-bold">{amount} sats</div>
|
||||
</div>
|
||||
|
||||
<Separator className="my-4" />
|
||||
|
||||
<div className="flex flex-col justify-center min-h-0 flex-1 px-2">
|
||||
{/* QR Code */}
|
||||
<div className="flex justify-center">
|
||||
<Card className="p-3 [@media(max-height:680px)]:max-w-[65vw] max-w-[95vw] mx-auto">
|
||||
<CardContent className="p-0 flex justify-center">
|
||||
{qrCodeUrl ? (
|
||||
<img
|
||||
src={qrCodeUrl}
|
||||
alt="Lightning Invoice QR Code"
|
||||
className="w-full h-auto aspect-square max-w-full object-contain"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full aspect-square bg-muted animate-pulse rounded" />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Invoice input */}
|
||||
<div className="space-y-2 mt-4">
|
||||
<Label htmlFor="invoice">Lightning Invoice</Label>
|
||||
<div className="flex gap-2 min-w-0">
|
||||
<Input
|
||||
id="invoice"
|
||||
value={invoice}
|
||||
readOnly
|
||||
className="font-mono text-xs min-w-0 flex-1 overflow-hidden text-ellipsis"
|
||||
onClick={(e) => e.currentTarget.select()}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleCopy}
|
||||
className="shrink-0"
|
||||
>
|
||||
{copied ? (
|
||||
<Check className="h-4 w-4 text-green-600" />
|
||||
) : (
|
||||
<Copy className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Payment buttons */}
|
||||
<div className="space-y-3 mt-4">
|
||||
{hasWebLN && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||
zap(finalAmount, comment);
|
||||
}}
|
||||
disabled={isZapping}
|
||||
className="w-full"
|
||||
size="lg"
|
||||
>
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
{isZapping ? "Processing..." : "Pay with WebLN"}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={openInWallet}
|
||||
className="w-full"
|
||||
size="lg"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
Open in Lightning Wallet
|
||||
</Button>
|
||||
|
||||
<div className="text-xs sm:text-[.65rem] text-muted-foreground text-center">
|
||||
Scan the QR code or copy the invoice to pay with any Lightning wallet.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid gap-3 px-4 py-4 w-full overflow-hidden">
|
||||
<ToggleGroup
|
||||
type="single"
|
||||
value={String(amount)}
|
||||
onValueChange={(value) => {
|
||||
if (value) {
|
||||
setAmount(parseInt(value, 10));
|
||||
}
|
||||
}}
|
||||
className="grid grid-cols-5 gap-1 w-full"
|
||||
>
|
||||
{presetAmounts.map(({ amount: presetAmount, icon: Icon }) => (
|
||||
<ToggleGroupItem
|
||||
key={presetAmount}
|
||||
value={String(presetAmount)}
|
||||
className="flex flex-col h-auto min-w-0 text-xs px-1 py-2"
|
||||
>
|
||||
<Icon className="h-4 w-4 mb-1" />
|
||||
<span className="truncate">{presetAmount}</span>
|
||||
</ToggleGroupItem>
|
||||
))}
|
||||
</ToggleGroup>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="h-px flex-1 bg-muted" />
|
||||
<span className="text-xs text-muted-foreground">OR</span>
|
||||
<div className="h-px flex-1 bg-muted" />
|
||||
</div>
|
||||
<Input
|
||||
ref={inputRef}
|
||||
id="custom-amount"
|
||||
type="number"
|
||||
placeholder="Custom amount"
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(e.target.value)}
|
||||
className="w-full text-sm"
|
||||
/>
|
||||
<Textarea
|
||||
id="custom-comment"
|
||||
placeholder="Add a comment (optional)"
|
||||
value={comment}
|
||||
onChange={(e) => setComment(e.target.value)}
|
||||
className="w-full resize-none text-sm"
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
<div className="px-4 pb-4">
|
||||
<Button onClick={handleZap} className="w-full" disabled={isZapping} size="default">
|
||||
{isZapping ? (
|
||||
'Creating invoice...'
|
||||
) : (
|
||||
<>
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
Zap {amount} sats
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
));
|
||||
ZapContent.displayName = 'ZapContent';
|
||||
|
||||
|
||||
export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { user } = useCurrentUser();
|
||||
const { data: author } = useAuthor(target.pubkey);
|
||||
const { toast } = useToast();
|
||||
const { webln, activeNWC, hasWebLN, detectWebLN } = useWallet();
|
||||
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
|
||||
const [amount, setAmount] = useState<number | string>(100);
|
||||
const [comment, setComment] = useState<string>('');
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
useEffect(() => {
|
||||
if (target) {
|
||||
setComment('Zapped with MKStack!');
|
||||
}
|
||||
}, [target]);
|
||||
|
||||
// Detect WebLN when dialog opens
|
||||
useEffect(() => {
|
||||
if (open && !hasWebLN) {
|
||||
detectWebLN();
|
||||
}
|
||||
}, [open, hasWebLN, detectWebLN]);
|
||||
|
||||
// Generate QR code
|
||||
useEffect(() => {
|
||||
let isCancelled = false;
|
||||
|
||||
const generateQR = async () => {
|
||||
if (!invoice) {
|
||||
setQrCodeUrl('');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const url = await QRCode.toDataURL(invoice.toUpperCase(), {
|
||||
width: 512,
|
||||
margin: 2,
|
||||
color: {
|
||||
dark: '#000000',
|
||||
light: '#FFFFFF',
|
||||
},
|
||||
});
|
||||
|
||||
if (!isCancelled) {
|
||||
setQrCodeUrl(url);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!isCancelled) {
|
||||
console.error('Failed to generate QR code:', err);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
generateQR();
|
||||
|
||||
return () => {
|
||||
isCancelled = true;
|
||||
};
|
||||
}, [invoice]);
|
||||
|
||||
const handleCopy = async () => {
|
||||
if (invoice) {
|
||||
await navigator.clipboard.writeText(invoice);
|
||||
setCopied(true);
|
||||
toast({
|
||||
title: 'Invoice copied',
|
||||
description: 'Lightning invoice copied to clipboard',
|
||||
});
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}
|
||||
};
|
||||
|
||||
const openInWallet = () => {
|
||||
if (invoice) {
|
||||
const lightningUrl = `lightning:${invoice}`;
|
||||
window.open(lightningUrl, '_blank');
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setAmount(100);
|
||||
setInvoice(null);
|
||||
setCopied(false);
|
||||
setQrCodeUrl('');
|
||||
} else {
|
||||
// Clean up state when dialog closes
|
||||
setAmount(100);
|
||||
setInvoice(null);
|
||||
setCopied(false);
|
||||
setQrCodeUrl('');
|
||||
}
|
||||
}, [open, setInvoice]);
|
||||
|
||||
const handleZap = () => {
|
||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||
zap(finalAmount, comment);
|
||||
};
|
||||
|
||||
const contentProps = {
|
||||
invoice,
|
||||
amount,
|
||||
comment,
|
||||
isZapping,
|
||||
qrCodeUrl,
|
||||
copied,
|
||||
hasWebLN,
|
||||
handleZap,
|
||||
handleCopy,
|
||||
openInWallet,
|
||||
setAmount,
|
||||
setComment,
|
||||
inputRef,
|
||||
zap,
|
||||
};
|
||||
|
||||
if (!user || user.pubkey === target.pubkey || !author?.metadata?.lud06 && !author?.metadata?.lud16) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
// Use drawer for entire mobile flow, make it full-screen when showing invoice
|
||||
return (
|
||||
<Drawer
|
||||
open={open}
|
||||
onOpenChange={(newOpen) => {
|
||||
// Reset invoice when closing
|
||||
if (!newOpen) {
|
||||
setInvoice(null);
|
||||
setQrCodeUrl('');
|
||||
}
|
||||
setOpen(newOpen);
|
||||
}}
|
||||
dismissible={true} // Always allow dismissal via drag
|
||||
snapPoints={invoice ? [0.5, 0.75, 0.98] : [0.98]}
|
||||
activeSnapPoint={invoice ? 0.98 : 0.98}
|
||||
modal={true}
|
||||
shouldScaleBackground={false}
|
||||
fadeFromIndex={0}
|
||||
>
|
||||
<DrawerTrigger asChild>
|
||||
<div className={`cursor-pointer ${className || ''}`}>
|
||||
{children}
|
||||
</div>
|
||||
</DrawerTrigger>
|
||||
<DrawerContent
|
||||
key={invoice ? 'payment' : 'form'}
|
||||
className={cn(
|
||||
"transition-all duration-300",
|
||||
invoice ? "h-full max-h-screen" : "max-h-[98vh]"
|
||||
)}
|
||||
data-testid="zap-modal"
|
||||
>
|
||||
<DrawerHeader className="text-center relative">
|
||||
{/* Back button when showing invoice */}
|
||||
{invoice && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setInvoice(null);
|
||||
setQrCodeUrl('');
|
||||
}}
|
||||
className="absolute left-4 top-4 flex items-center gap-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Close button */}
|
||||
<DrawerClose asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-4 top-4"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</Button>
|
||||
</DrawerClose>
|
||||
|
||||
<DrawerTitle className="text-lg break-words pt-2">
|
||||
{invoice ? 'Lightning Payment' : 'Send a Zap'}
|
||||
</DrawerTitle>
|
||||
<DrawerDescription className="text-sm break-words text-center">
|
||||
{invoice ? (
|
||||
'Pay with Bitcoin Lightning Network'
|
||||
) : (
|
||||
'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
|
||||
)}
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
<div className="flex-1 overflow-y-auto px-4 pb-4">
|
||||
<ZapContent {...contentProps} />
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<div className={`cursor-pointer ${className || ''}`}>
|
||||
{children}
|
||||
</div>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[425px] max-h-[95vh] overflow-hidden" data-testid="zap-modal">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-lg break-words">
|
||||
{invoice ? 'Lightning Payment' : 'Send a Zap'}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-sm text-center break-words">
|
||||
{invoice ? (
|
||||
'Pay with Bitcoin Lightning Network'
|
||||
) : (
|
||||
<>
|
||||
Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!
|
||||
</>
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="overflow-y-auto">
|
||||
<ZapContent {...contentProps} />
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useState } from 'react';
|
||||
import { Settings } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
|
||||
export function AISettingsDialog() {
|
||||
const { settings, updateSettings, isConfigured } = useAISettings();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [localSettings, setLocalSettings] = useState(settings);
|
||||
|
||||
const handleSave = () => {
|
||||
updateSettings(localSettings);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
setLocalSettings(settings);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="gap-2">
|
||||
<Settings className="h-4 w-4" />
|
||||
AI Settings
|
||||
{!isConfigured && (
|
||||
<span className="ml-1 h-2 w-2 rounded-full bg-red-500" />
|
||||
)}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>AI Settings</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure your AI provider settings. These settings are stored locally in your browser.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="apiKey">API Key</Label>
|
||||
<Input
|
||||
id="apiKey"
|
||||
type="password"
|
||||
placeholder="Enter your API key"
|
||||
value={localSettings.apiKey}
|
||||
onChange={(e) => setLocalSettings({ ...localSettings, apiKey: e.target.value })}
|
||||
/>
|
||||
{!localSettings.apiKey && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Required for AI functionality
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="baseUrl">Base URL</Label>
|
||||
<Input
|
||||
id="baseUrl"
|
||||
placeholder="https://openrouter.ai/api/v1"
|
||||
value={localSettings.baseUrl}
|
||||
onChange={(e) => setLocalSettings({ ...localSettings, baseUrl: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="model">Model</Label>
|
||||
<Input
|
||||
id="model"
|
||||
placeholder="anthropic/claude-sonnet-4"
|
||||
value={localSettings.model}
|
||||
onChange={(e) => setLocalSettings({ ...localSettings, model: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
Save Settings
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
import { memo } from 'react';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import { Code } from 'lucide-react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { DiffRenderer } from '@/components/ai/DiffRenderer';
|
||||
import { ScriptRunner } from '@/components/ai/ScriptRunner';
|
||||
import { FileViewer } from '@/components/ai/FileViewer';
|
||||
import { FileWriter } from '@/components/ai/FileWriter';
|
||||
import { ShellCommand } from '@/components/ai/ShellCommand';
|
||||
import { PackageManager } from '@/components/ai/PackageManager';
|
||||
import { GitCommit } from '@/components/ai/GitCommit';
|
||||
import type { CoreAssistantMessage, CoreToolMessage } from 'ai';
|
||||
|
||||
interface AssistantContentProps {
|
||||
content: CoreAssistantMessage['content'];
|
||||
toolResults?: CoreToolMessage[];
|
||||
}
|
||||
|
||||
export const AssistantContent = memo(({ content, toolResults = [] }: AssistantContentProps) => {
|
||||
// Helper function to find tool result by call ID
|
||||
const findToolResult = (toolCallId: string) => {
|
||||
for (const toolMessage of toolResults) {
|
||||
if (toolMessage.content) {
|
||||
for (const resultPart of toolMessage.content) {
|
||||
if (resultPart.toolCallId === toolCallId) {
|
||||
return resultPart;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// Helper function to extract result text and error status
|
||||
const extractToolResult = (toolCallId: string): { result?: string; isError: boolean } => {
|
||||
const toolResult = findToolResult(toolCallId);
|
||||
|
||||
if (!toolResult) {
|
||||
return { isError: false };
|
||||
}
|
||||
|
||||
// Handle direct string results
|
||||
if (typeof toolResult.result === 'string') {
|
||||
return {
|
||||
result: toolResult.result,
|
||||
isError: toolResult.isError || false
|
||||
};
|
||||
}
|
||||
|
||||
// Handle CallToolResult structure
|
||||
if (toolResult.result && typeof toolResult.result === 'object') {
|
||||
const callResult = toolResult.result as {
|
||||
content?: Array<{ type: string; text: string }>;
|
||||
isError?: boolean;
|
||||
};
|
||||
if (callResult.content && Array.isArray(callResult.content) && callResult.content[0]?.text) {
|
||||
return {
|
||||
result: callResult.content[0].text,
|
||||
isError: callResult.isError || false
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { isError: toolResult.isError || false };
|
||||
};
|
||||
// Handle string content (simple text messages)
|
||||
if (typeof content === 'string') {
|
||||
return (
|
||||
<div className="prose prose-sm max-w-none dark:prose-invert">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
components={{
|
||||
// Customize code blocks to match the existing tool styling
|
||||
pre: ({ children }) => (
|
||||
<pre className="bg-muted/50 rounded p-3 overflow-x-auto text-sm">
|
||||
{children}
|
||||
</pre>
|
||||
),
|
||||
code: ({ children, className }) => {
|
||||
const isInline = !className;
|
||||
if (isInline) {
|
||||
return (
|
||||
<code className="bg-muted px-1.5 py-0.5 rounded text-sm font-mono">
|
||||
{children}
|
||||
</code>
|
||||
);
|
||||
}
|
||||
return <code className={className}>{children}</code>;
|
||||
},
|
||||
// Style links
|
||||
a: ({ href, children }) => (
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
// Style blockquotes
|
||||
blockquote: ({ children }) => (
|
||||
<blockquote className="border-l-4 border-muted-foreground/20 pl-4 italic text-muted-foreground">
|
||||
{children}
|
||||
</blockquote>
|
||||
),
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{content.map((item, index) => {
|
||||
if (item.type === 'text') {
|
||||
return (
|
||||
<div key={index} className="prose prose-sm max-w-none dark:prose-invert">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
components={{
|
||||
// Customize code blocks to match the existing tool styling
|
||||
pre: ({ children }) => (
|
||||
<pre className="bg-muted/50 rounded p-3 overflow-x-auto text-sm">
|
||||
{children}
|
||||
</pre>
|
||||
),
|
||||
code: ({ children, className }) => {
|
||||
const isInline = !className;
|
||||
if (isInline) {
|
||||
return (
|
||||
<code className="bg-muted px-1.5 py-0.5 rounded text-sm font-mono">
|
||||
{children}
|
||||
</code>
|
||||
);
|
||||
}
|
||||
return <code className={className}>{children}</code>;
|
||||
},
|
||||
// Style links
|
||||
a: ({ href, children }) => (
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
// Style blockquotes
|
||||
blockquote: ({ children }) => (
|
||||
<blockquote className="border-l-4 border-muted-foreground/20 pl-4 italic text-muted-foreground">
|
||||
{children}
|
||||
</blockquote>
|
||||
),
|
||||
}}
|
||||
>
|
||||
{item.text}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
} else if (item.type === 'tool-call') {
|
||||
// Special rendering for text_editor_str_replace tool
|
||||
if (item.toolName === 'text_editor_str_replace' && item.args) {
|
||||
const { path, old_str, new_str } = item.args as { path: string; old_str: string; new_str: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<DiffRenderer
|
||||
key={index}
|
||||
path={path}
|
||||
oldStr={old_str}
|
||||
newStr={new_str}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for run_script tool
|
||||
if (item.toolName === 'run_script' && item.args) {
|
||||
const { script } = item.args as { script: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<ScriptRunner
|
||||
key={index}
|
||||
script={script}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for text_editor_view tool
|
||||
if (item.toolName === 'text_editor_view' && item.args) {
|
||||
const { path } = item.args as { path: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<FileViewer
|
||||
key={index}
|
||||
path={path}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for text_editor_write tool
|
||||
if (item.toolName === 'text_editor_write' && item.args) {
|
||||
const { path, file_text } = item.args as { path: string; file_text: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<FileWriter
|
||||
key={index}
|
||||
path={path}
|
||||
fileText={file_text}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for shell tool
|
||||
if (item.toolName === 'shell' && item.args) {
|
||||
const { command } = item.args as { command: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<ShellCommand
|
||||
key={index}
|
||||
command={command}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for npm_add_package tool
|
||||
if (item.toolName === 'npm_add_package' && item.args) {
|
||||
const { name, version, dev } = item.args as { name: string; version?: string; dev?: boolean };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<PackageManager
|
||||
key={index}
|
||||
action="add"
|
||||
registry="npm"
|
||||
packageName={name}
|
||||
version={version}
|
||||
dev={dev}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for npm_remove_package tool
|
||||
if (item.toolName === 'npm_remove_package' && item.args) {
|
||||
const { name } = item.args as { name: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<PackageManager
|
||||
key={index}
|
||||
action="remove"
|
||||
registry="npm"
|
||||
packageName={name}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for jsr_add_package tool
|
||||
if (item.toolName === 'jsr_add_package' && item.args) {
|
||||
const { name, version, dev } = item.args as { name: string; version?: string; dev?: boolean };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<PackageManager
|
||||
key={index}
|
||||
action="add"
|
||||
registry="jsr"
|
||||
packageName={name}
|
||||
version={version}
|
||||
dev={dev}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for jsr_remove_package tool
|
||||
if (item.toolName === 'jsr_remove_package' && item.args) {
|
||||
const { name } = item.args as { name: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<PackageManager
|
||||
key={index}
|
||||
action="remove"
|
||||
registry="jsr"
|
||||
packageName={name}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Special rendering for git_commit tool
|
||||
if (item.toolName === 'git_commit' && item.args) {
|
||||
const { message } = item.args as { message: string };
|
||||
const { result, isError } = extractToolResult(item.toolCallId);
|
||||
|
||||
return (
|
||||
<GitCommit
|
||||
key={index}
|
||||
message={message}
|
||||
result={result}
|
||||
isError={isError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Default tool rendering for other tools
|
||||
return (
|
||||
<Card key={index} className="mt-2 bg-muted/50">
|
||||
<CardContent className="p-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Code className="h-4 w-4 flex-shrink-0" />
|
||||
<span className="font-mono text-sm break-all">{String(item.toolName)}</span>
|
||||
</div>
|
||||
{item.args && typeof item.args === 'object' && item.args !== null && Object.keys(item.args).length > 0 ? (
|
||||
<div className="text-xs text-muted-foreground mb-2">
|
||||
<pre className="overflow-hidden text-ellipsis">
|
||||
{JSON.stringify(item.args, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
})}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
AssistantContent.displayName = 'AssistantContent';
|
||||
@@ -0,0 +1,164 @@
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { FileText, CheckCircle, XCircle } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface DiffRendererProps {
|
||||
path: string;
|
||||
oldStr: string;
|
||||
newStr: string;
|
||||
result?: string;
|
||||
isError?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function DiffRenderer({ path, oldStr, newStr, result, isError = false, className }: DiffRendererProps) {
|
||||
// Split strings into lines for diff rendering
|
||||
const oldLines = oldStr.split('\n');
|
||||
const newLines = newStr.split('\n');
|
||||
|
||||
// Simple diff algorithm - find common prefix and suffix
|
||||
const findCommonPrefix = (a: string[], b: string[]) => {
|
||||
let i = 0;
|
||||
while (i < Math.min(a.length, b.length) && a[i] === b[i]) {
|
||||
i++;
|
||||
}
|
||||
return i;
|
||||
};
|
||||
|
||||
const findCommonSuffix = (a: string[], b: string[], prefixLength: number) => {
|
||||
let i = 0;
|
||||
const maxLength = Math.min(a.length - prefixLength, b.length - prefixLength);
|
||||
while (i < maxLength && a[a.length - 1 - i] === b[b.length - 1 - i]) {
|
||||
i++;
|
||||
}
|
||||
return i;
|
||||
};
|
||||
|
||||
const prefixLength = findCommonPrefix(oldLines, newLines);
|
||||
const suffixLength = findCommonSuffix(oldLines, newLines, prefixLength);
|
||||
|
||||
const commonPrefix = oldLines.slice(0, prefixLength);
|
||||
const commonSuffix = oldLines.slice(oldLines.length - suffixLength);
|
||||
|
||||
const removedLines = oldLines.slice(prefixLength, oldLines.length - suffixLength);
|
||||
const addedLines = newLines.slice(prefixLength, newLines.length - suffixLength);
|
||||
|
||||
return (
|
||||
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-mono text-sm font-medium">{path}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{isError ? (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
<XCircle className="h-3 w-3 mr-1" />
|
||||
Failed
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
|
||||
<CheckCircle className="h-3 w-3 mr-1" />
|
||||
Success
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<div className="bg-muted/30 rounded-md overflow-x-auto overflow-y-hidden">
|
||||
<div className="font-mono text-xs min-w-max">
|
||||
{/* Context before changes */}
|
||||
{commonPrefix.length > 0 && (
|
||||
<div className="border-b border-muted/50">
|
||||
{commonPrefix.slice(-3).map((line, index) => (
|
||||
<div key={`prefix-${index}`} className="px-3 py-1 text-muted-foreground">
|
||||
<span className="inline-block w-8 text-right mr-3 select-none">
|
||||
{prefixLength - 3 + index + 1}
|
||||
</span>
|
||||
<span className="whitespace-pre whitespace-nowrap">{line || ' '}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Removed lines */}
|
||||
{removedLines.map((line, index) => (
|
||||
<div key={`removed-${index}`} className="px-3 py-1 bg-red-50 text-red-800 dark:bg-red-900/20 dark:text-red-300">
|
||||
<span className="inline-block w-8 text-right mr-3 select-none text-red-600 dark:text-red-400">
|
||||
-{prefixLength + index + 1}
|
||||
</span>
|
||||
<span className="whitespace-pre whitespace-nowrap">
|
||||
<span className="bg-red-200 dark:bg-red-800/50">-</span>
|
||||
{line || ' '}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Added lines */}
|
||||
{addedLines.map((line, index) => (
|
||||
<div key={`added-${index}`} className="px-3 py-1 bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-300">
|
||||
<span className="inline-block w-8 text-right mr-3 select-none text-green-600 dark:text-green-400">
|
||||
+{prefixLength + index + 1}
|
||||
</span>
|
||||
<span className="whitespace-pre whitespace-nowrap">
|
||||
<span className="bg-green-200 dark:bg-green-800/50">+</span>
|
||||
{line || ' '}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Context after changes */}
|
||||
{commonSuffix.length > 0 && (
|
||||
<div className="border-t border-muted/50">
|
||||
{commonSuffix.slice(0, 3).map((line, index) => (
|
||||
<div key={`suffix-${index}`} className="px-3 py-1 text-muted-foreground">
|
||||
<span className="inline-block w-8 text-right mr-3 select-none">
|
||||
{prefixLength + Math.max(removedLines.length, addedLines.length) + index + 1}
|
||||
</span>
|
||||
<span className="whitespace-pre whitespace-nowrap">{line || ' '}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Handle case where there are no changes */}
|
||||
{removedLines.length === 0 && addedLines.length === 0 && (
|
||||
<div className="px-3 py-4 text-center text-muted-foreground">
|
||||
No changes detected
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Summary */}
|
||||
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
|
||||
{removedLines.length > 0 && (
|
||||
<span className="text-red-600 dark:text-red-400">
|
||||
-{removedLines.length} line{removedLines.length !== 1 ? 's' : ''}
|
||||
</span>
|
||||
)}
|
||||
{addedLines.length > 0 && (
|
||||
<span className="text-green-600 dark:text-green-400">
|
||||
+{addedLines.length} line{addedLines.length !== 1 ? 's' : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tool Result */}
|
||||
{result && (
|
||||
<div className={cn(
|
||||
"mt-3 p-3 rounded-md text-sm",
|
||||
isError
|
||||
? "bg-destructive/10 text-destructive border border-destructive/20"
|
||||
: "bg-muted/30 text-muted-foreground"
|
||||
)}>
|
||||
<pre className="whitespace-pre-wrap break-words">{result}</pre>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
|
||||
import { oneDark, oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism';
|
||||
import { useTheme } from '@/hooks/useTheme';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface FileContentsProps {
|
||||
content: string;
|
||||
filePath: string;
|
||||
className?: string;
|
||||
showLineNumbers?: boolean;
|
||||
maxHeight?: string;
|
||||
showHeader?: boolean;
|
||||
headerContent?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function FileContents({
|
||||
content,
|
||||
filePath,
|
||||
className,
|
||||
showLineNumbers,
|
||||
maxHeight = 'max-h-80',
|
||||
showHeader = true,
|
||||
headerContent
|
||||
}: FileContentsProps) {
|
||||
const { theme } = useTheme();
|
||||
|
||||
// Get file extension for syntax highlighting hints
|
||||
const getFileExtension = (path: string) => {
|
||||
const parts = path.split('.');
|
||||
return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
|
||||
};
|
||||
|
||||
// Map file extensions to syntax highlighter languages
|
||||
const getLanguageFromExtension = (ext: string): string => {
|
||||
const languageMap: Record<string, string> = {
|
||||
'ts': 'typescript',
|
||||
'tsx': 'tsx',
|
||||
'js': 'javascript',
|
||||
'jsx': 'jsx',
|
||||
'json': 'json',
|
||||
'md': 'markdown',
|
||||
'css': 'css',
|
||||
'scss': 'scss',
|
||||
'sass': 'sass',
|
||||
'less': 'less',
|
||||
'html': 'html',
|
||||
'xml': 'xml',
|
||||
'svg': 'xml',
|
||||
'yml': 'yaml',
|
||||
'yaml': 'yaml',
|
||||
'toml': 'toml',
|
||||
'py': 'python',
|
||||
'rb': 'ruby',
|
||||
'php': 'php',
|
||||
'java': 'java',
|
||||
'c': 'c',
|
||||
'cpp': 'cpp',
|
||||
'cs': 'csharp',
|
||||
'go': 'go',
|
||||
'rs': 'rust',
|
||||
'sh': 'bash',
|
||||
'bash': 'bash',
|
||||
'zsh': 'bash',
|
||||
'fish': 'bash',
|
||||
'sql': 'sql',
|
||||
'dockerfile': 'dockerfile',
|
||||
'gitignore': 'gitignore',
|
||||
'env': 'bash',
|
||||
'ini': 'ini',
|
||||
'conf': 'nginx',
|
||||
'nginx': 'nginx',
|
||||
'apache': 'apache',
|
||||
'htaccess': 'apache',
|
||||
'vim': 'vim',
|
||||
'lua': 'lua',
|
||||
'r': 'r',
|
||||
'matlab': 'matlab',
|
||||
'swift': 'swift',
|
||||
'kotlin': 'kotlin',
|
||||
'dart': 'dart',
|
||||
'elm': 'elm',
|
||||
'haskell': 'haskell',
|
||||
'clojure': 'clojure',
|
||||
'scala': 'scala',
|
||||
'perl': 'perl',
|
||||
'powershell': 'powershell',
|
||||
'makefile': 'makefile',
|
||||
'cmake': 'cmake',
|
||||
'gradle': 'gradle',
|
||||
'properties': 'properties',
|
||||
'diff': 'diff',
|
||||
'patch': 'diff',
|
||||
'log': 'log'
|
||||
};
|
||||
|
||||
return languageMap[ext] || 'text';
|
||||
};
|
||||
|
||||
// Check if content should be syntax highlighted
|
||||
const shouldHighlight = (ext: string, text: string): boolean => {
|
||||
// Don't highlight very large files (over 50KB) for performance
|
||||
if (text.length > 50000) return false;
|
||||
|
||||
// Don't highlight binary-looking content (check for null bytes and other binary indicators)
|
||||
if (text.includes('\0') || text.includes('\uFFFD')) return false;
|
||||
|
||||
// Always highlight known code file extensions
|
||||
const codeExtensions = ['ts', 'tsx', 'js', 'jsx', 'json', 'css', 'scss', 'html', 'xml', 'py', 'rb', 'php', 'java', 'c', 'cpp', 'cs', 'go', 'rs', 'sh', 'bash', 'sql', 'yml', 'yaml', 'toml', 'md'];
|
||||
return codeExtensions.includes(ext);
|
||||
};
|
||||
|
||||
const fileExtension = getFileExtension(filePath);
|
||||
const shouldUseHighlighting = shouldHighlight(fileExtension, content);
|
||||
|
||||
// Determine if we should show line numbers
|
||||
const shouldShowLineNumbers = showLineNumbers ?? (content.split('\n').length > 10);
|
||||
|
||||
return (
|
||||
<div className={cn("bg-muted/30 rounded-md overflow-hidden", className)}>
|
||||
{showHeader && (
|
||||
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50 flex items-center justify-between">
|
||||
<span>File Contents</span>
|
||||
{headerContent || (fileExtension && (
|
||||
<span className="text-xs bg-muted px-2 py-1 rounded">
|
||||
{fileExtension.toUpperCase()}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className={cn("p-0 overflow-auto", maxHeight)}>
|
||||
{shouldUseHighlighting ? (
|
||||
<SyntaxHighlighter
|
||||
language={getLanguageFromExtension(fileExtension)}
|
||||
style={theme === 'dark' ? oneDark : oneLight}
|
||||
customStyle={{
|
||||
margin: 0,
|
||||
padding: '12px',
|
||||
fontSize: '12px',
|
||||
lineHeight: '1.4',
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
borderRadius: 0,
|
||||
}}
|
||||
codeTagProps={{
|
||||
style: {
|
||||
fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace',
|
||||
}
|
||||
}}
|
||||
showLineNumbers={shouldShowLineNumbers}
|
||||
lineNumberStyle={{
|
||||
minWidth: '2.5em',
|
||||
paddingRight: '1em',
|
||||
color: theme === 'dark' ? '#6b7280' : '#9ca3af',
|
||||
fontSize: '11px',
|
||||
}}
|
||||
wrapLines={false}
|
||||
wrapLongLines={false}
|
||||
>
|
||||
{content}
|
||||
</SyntaxHighlighter>
|
||||
) : (
|
||||
<div className="p-3">
|
||||
<pre className="text-xs font-mono whitespace-pre text-foreground">
|
||||
{content}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { CheckCircle, XCircle, Eye } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { FileContents } from '@/components/ai/FileContents';
|
||||
|
||||
interface FileViewerProps {
|
||||
path: string;
|
||||
result?: string;
|
||||
isError?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function FileViewer({ path, result, isError = false, className }: FileViewerProps) {
|
||||
// Determine if it's a directory or file based on the result
|
||||
const isDirectory = result?.includes('├──') || result?.includes('└──') || result?.includes('│');
|
||||
|
||||
// Get file extension for syntax highlighting hints
|
||||
const getFileExtension = (filePath: string) => {
|
||||
const parts = filePath.split('.');
|
||||
return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
|
||||
};
|
||||
|
||||
const getFileIcon = (filePath: string, isDir: boolean) => {
|
||||
if (isDir) return '📁';
|
||||
|
||||
const ext = getFileExtension(filePath);
|
||||
switch (ext) {
|
||||
case 'ts':
|
||||
case 'tsx': return '🔷';
|
||||
case 'js':
|
||||
case 'jsx': return '🟨';
|
||||
case 'json': return '📋';
|
||||
case 'md': return '📝';
|
||||
case 'css': return '🎨';
|
||||
case 'html': return '🌐';
|
||||
case 'svg': return '🖼️';
|
||||
case 'png':
|
||||
case 'jpg':
|
||||
case 'jpeg':
|
||||
case 'gif': return '🖼️';
|
||||
case 'yml':
|
||||
case 'yaml': return '⚙️';
|
||||
case 'toml': return '⚙️';
|
||||
case 'lock': return '🔒';
|
||||
default: return '📄';
|
||||
}
|
||||
};
|
||||
|
||||
const fileIcon = getFileIcon(path, isDirectory || false);
|
||||
const fileExtension = getFileExtension(path);
|
||||
|
||||
// Parse directory structure for better display
|
||||
const parseDirectoryStructure = (content: string) => {
|
||||
if (!isDirectory) return content;
|
||||
|
||||
const lines = content.split('\n').filter(line => line.trim());
|
||||
return lines.map((line) => {
|
||||
// Extract the file/folder name from tree structure
|
||||
const match = line.match(/[├└]──\s*(.+)$/);
|
||||
if (match) {
|
||||
const name = match[1];
|
||||
const isFolder = !name.includes('.');
|
||||
const icon = isFolder ? '📁' : getFileIcon(name, false);
|
||||
return { line, name, icon, isFolder };
|
||||
}
|
||||
return { line, name: line.trim(), icon: '📄', isFolder: false };
|
||||
});
|
||||
};
|
||||
|
||||
const directoryItems = isDirectory ? parseDirectoryStructure(result || '') : [];
|
||||
const directoryItemsArray = Array.isArray(directoryItems) ? directoryItems : [];
|
||||
|
||||
return (
|
||||
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Eye className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-lg">{fileIcon}</span>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-mono text-sm font-medium">{path}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{isDirectory ? 'Directory listing' : `${fileExtension ? fileExtension.toUpperCase() + ' file' : 'File'} contents`}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{result ? (
|
||||
isError ? (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
<XCircle className="h-3 w-3 mr-1" />
|
||||
Error
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
|
||||
<CheckCircle className="h-3 w-3 mr-1" />
|
||||
Viewed
|
||||
</Badge>
|
||||
)
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-400">
|
||||
<Eye className="h-3 w-3 mr-1" />
|
||||
Loading
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
{result && (
|
||||
<CardContent className="pt-0">
|
||||
{isError ? (
|
||||
<div className="bg-destructive/10 text-destructive border border-destructive/20 rounded-md p-3 text-sm">
|
||||
{result}
|
||||
</div>
|
||||
) : isDirectory ? (
|
||||
<div className="bg-muted/30 rounded-md overflow-hidden">
|
||||
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50">
|
||||
Directory Structure
|
||||
</div>
|
||||
<div className="p-3 max-h-80 overflow-y-auto">
|
||||
<div className="space-y-1">
|
||||
{directoryItemsArray.map((item, index) => (
|
||||
<div key={index} className="flex items-center gap-2 text-sm font-mono">
|
||||
<span className="text-muted-foreground">{item.line.replace(/[├└]──\s*(.+)$/, '')}</span>
|
||||
<span className="text-xs">{item.icon}</span>
|
||||
<span className={cn(
|
||||
item.isFolder ? "text-blue-600 dark:text-blue-400 font-medium" : "text-foreground"
|
||||
)}>
|
||||
{item.name}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<FileContents
|
||||
content={result}
|
||||
filePath={path}
|
||||
headerContent={fileExtension && (
|
||||
<span className="text-xs bg-muted px-2 py-1 rounded">
|
||||
{fileExtension.toUpperCase()}
|
||||
</span>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* File stats */}
|
||||
{!isError && result && (
|
||||
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
|
||||
{isDirectory ? (
|
||||
<span>
|
||||
{directoryItemsArray.length} item{directoryItemsArray.length !== 1 ? 's' : ''}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<span>
|
||||
{result.split('\n').length} line{result.split('\n').length !== 1 ? 's' : ''}
|
||||
</span>
|
||||
<span>
|
||||
{result.length} character{result.length !== 1 ? 's' : ''}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { CheckCircle, XCircle, Edit3 } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { FileContents } from '@/components/ai/FileContents';
|
||||
|
||||
interface FileWriterProps {
|
||||
path: string;
|
||||
fileText: string;
|
||||
result?: string;
|
||||
isError?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function FileWriter({ path, fileText, result, isError = false, className }: FileWriterProps) {
|
||||
// Get file extension for syntax highlighting hints
|
||||
const getFileExtension = (filePath: string) => {
|
||||
const parts = filePath.split('.');
|
||||
return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
|
||||
};
|
||||
|
||||
const getFileIcon = (filePath: string) => {
|
||||
const ext = getFileExtension(filePath);
|
||||
switch (ext) {
|
||||
case 'ts':
|
||||
case 'tsx': return '🔷';
|
||||
case 'js':
|
||||
case 'jsx': return '🟨';
|
||||
case 'json': return '📋';
|
||||
case 'md': return '📝';
|
||||
case 'css': return '🎨';
|
||||
case 'html': return '🌐';
|
||||
case 'svg': return '🖼️';
|
||||
case 'png':
|
||||
case 'jpg':
|
||||
case 'jpeg':
|
||||
case 'gif': return '🖼️';
|
||||
case 'yml':
|
||||
case 'yaml': return '⚙️';
|
||||
case 'toml': return '⚙️';
|
||||
case 'lock': return '🔒';
|
||||
default: return '📄';
|
||||
}
|
||||
};
|
||||
|
||||
const fileIcon = getFileIcon(path);
|
||||
const fileExtension = getFileExtension(path);
|
||||
const isNewFile = path.includes('new') || result?.includes('created') || result?.includes('Created');
|
||||
|
||||
// Calculate file stats
|
||||
const lineCount = fileText.split('\n').length;
|
||||
const charCount = fileText.length;
|
||||
const wordCount = fileText.split(/\s+/).filter(word => word.length > 0).length;
|
||||
|
||||
// Preview first few lines for collapsed view
|
||||
const previewLines = fileText.split('\n').slice(0, 5);
|
||||
const hasMoreLines = lineCount > 5;
|
||||
const previewContent = previewLines.join('\n') + (hasMoreLines ? `\n... (${lineCount - 5} more lines)` : '');
|
||||
|
||||
return (
|
||||
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Edit3 className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-lg">{fileIcon}</span>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-mono text-sm font-medium">{path}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{isNewFile ? 'Created new file' : 'Updated file contents'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{result !== undefined ? (
|
||||
isError ? (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
<XCircle className="h-3 w-3 mr-1" />
|
||||
Failed
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
|
||||
<CheckCircle className="h-3 w-3 mr-1" />
|
||||
{isNewFile ? 'Created' : 'Updated'}
|
||||
</Badge>
|
||||
)
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
|
||||
<Edit3 className="h-3 w-3 mr-1" />
|
||||
Writing
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="pt-0">
|
||||
{/* Error display */}
|
||||
{isError && result && (
|
||||
<div className="mb-3 bg-destructive/10 text-destructive border border-destructive/20 rounded-md p-3 text-sm">
|
||||
{result}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* File stats */}
|
||||
<div className="mb-3 flex items-center gap-4 text-xs">
|
||||
<span className="text-muted-foreground">
|
||||
{lineCount} line{lineCount !== 1 ? 's' : ''}
|
||||
</span>
|
||||
<span className="text-muted-foreground">
|
||||
{wordCount} word{wordCount !== 1 ? 's' : ''}
|
||||
</span>
|
||||
<span className="text-muted-foreground">
|
||||
{charCount} character{charCount !== 1 ? 's' : ''}
|
||||
</span>
|
||||
{fileExtension && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{fileExtension.toUpperCase()}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* File preview */}
|
||||
<details className="group">
|
||||
<summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground transition-colors mb-2 flex items-center gap-1">
|
||||
<span className="group-open:rotate-90 transition-transform">▶</span>
|
||||
Preview file contents
|
||||
</summary>
|
||||
<FileContents
|
||||
content={hasMoreLines ? previewContent : fileText}
|
||||
filePath={path}
|
||||
showLineNumbers={false}
|
||||
headerContent={fileExtension && (
|
||||
<span className="text-xs bg-muted px-2 py-1 rounded">
|
||||
{fileExtension.toUpperCase()}
|
||||
</span>
|
||||
)}
|
||||
/>
|
||||
</details>
|
||||
|
||||
{/* Success message */}
|
||||
{!isError && result && (
|
||||
<div className="mt-3 text-xs text-green-600 dark:text-green-400">
|
||||
✓ File {isNewFile ? 'created' : 'updated'} successfully
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { GitHistoryDialog } from './GitHistoryDialog';
|
||||
|
||||
// Mock isomorphic-git
|
||||
vi.mock('isomorphic-git', () => ({
|
||||
default: {
|
||||
log: vi.fn(),
|
||||
resolveRef: vi.fn(),
|
||||
readCommit: vi.fn(),
|
||||
listFiles: vi.fn(),
|
||||
readBlob: vi.fn(),
|
||||
add: vi.fn(),
|
||||
remove: vi.fn(),
|
||||
commit: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock the useFS hook
|
||||
vi.mock('@/hooks/useFS', () => ({
|
||||
useFS: () => ({
|
||||
fs: {
|
||||
stat: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock the useToast hook
|
||||
vi.mock('@/hooks/useToast', () => ({
|
||||
useToast: () => ({
|
||||
toast: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('GitHistoryDialog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the history button', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitHistoryDialog projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button', { name: /history/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens dialog when history button is clicked', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitHistoryDialog projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const historyButton = screen.getByRole('button', { name: /history/i });
|
||||
fireEvent.click(historyButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Git History')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows loading state when dialog opens', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitHistoryDialog projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const historyButton = screen.getByRole('button', { name: /history/i });
|
||||
fireEvent.click(historyButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Loading git history...')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('renders rollback buttons for commits (except the first one)', async () => {
|
||||
const mockCommits = [
|
||||
{
|
||||
oid: 'commit1',
|
||||
commit: {
|
||||
message: 'Latest commit',
|
||||
author: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000), timezoneOffset: 0 },
|
||||
committer: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000), timezoneOffset: 0 },
|
||||
parent: [],
|
||||
tree: 'tree1',
|
||||
},
|
||||
payload: '',
|
||||
},
|
||||
{
|
||||
oid: 'commit2',
|
||||
commit: {
|
||||
message: 'Previous commit',
|
||||
author: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000) - 3600, timezoneOffset: 0 },
|
||||
committer: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000) - 3600, timezoneOffset: 0 },
|
||||
parent: [],
|
||||
tree: 'tree2',
|
||||
},
|
||||
payload: '',
|
||||
},
|
||||
];
|
||||
|
||||
const git = await import('isomorphic-git');
|
||||
vi.mocked(git.default.log).mockResolvedValue(mockCommits);
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitHistoryDialog projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const historyButton = screen.getByRole('button', { name: /history/i });
|
||||
fireEvent.click(historyButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Latest commit')).toBeInTheDocument();
|
||||
expect(screen.getByText('Previous commit')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Should have one rollback button (not for the latest commit)
|
||||
const rollbackButtons = screen.getAllByText('Rollback');
|
||||
expect(rollbackButtons).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('handles multi-line commit messages with expand/collapse', async () => {
|
||||
const mockCommits = [
|
||||
{
|
||||
oid: 'commit1',
|
||||
commit: {
|
||||
message: 'Add new feature\n\nThis commit adds a new feature with the following changes:\n- Added component A\n- Updated component B\n- Fixed bug in component C',
|
||||
author: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000), timezoneOffset: 0 },
|
||||
committer: { name: 'User', email: '[email protected]', timestamp: Math.floor(Date.now() / 1000), timezoneOffset: 0 },
|
||||
parent: [],
|
||||
tree: 'tree1',
|
||||
},
|
||||
payload: '',
|
||||
},
|
||||
];
|
||||
|
||||
const git = await import('isomorphic-git');
|
||||
vi.mocked(git.default.log).mockResolvedValue(mockCommits);
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitHistoryDialog projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const historyButton = screen.getByRole('button', { name: /history/i });
|
||||
fireEvent.click(historyButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Add new feature')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Should show expand button for multi-line commit
|
||||
const expandButton = screen.getByRole('button', { name: '' }); // ChevronDown button
|
||||
expect(expandButton).toBeInTheDocument();
|
||||
|
||||
// Click to expand
|
||||
fireEvent.click(expandButton);
|
||||
|
||||
// Should show the expanded content
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/This commit adds a new feature/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -5,9 +5,9 @@ import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { History, GitCommit, RotateCcw, AlertTriangle, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import git from 'isomorphic-git';
|
||||
|
||||
interface GitCommit {
|
||||
oid: string;
|
||||
@@ -28,26 +28,21 @@ interface GitCommit {
|
||||
|
||||
interface GitHistoryDialogProps {
|
||||
projectId: string;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange }: GitHistoryDialogProps) {
|
||||
export function GitHistoryDialog({ projectId }: GitHistoryDialogProps) {
|
||||
const [commits, setCommits] = useState<GitCommit[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [internalOpen, setInternalOpen] = useState(false);
|
||||
|
||||
// Use controlled or internal state
|
||||
const isOpen = controlledOpen !== undefined ? controlledOpen : internalOpen;
|
||||
const setIsOpen = onOpenChange || setInternalOpen;
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isRollingBack, setIsRollingBack] = useState<string | null>(null);
|
||||
const [expandedCommits, setExpandedCommits] = useState<Set<string>>(new Set());
|
||||
const git = useGit();
|
||||
const { fs } = useFS();
|
||||
const { toast } = useToast();
|
||||
|
||||
const loadGitHistory = useCallback(async () => {
|
||||
if (!fs) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
@@ -56,7 +51,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
|
||||
// Check if git repository exists
|
||||
try {
|
||||
await git.findRoot({ filepath: projectPath });
|
||||
await fs.stat(`${projectPath}/.git`);
|
||||
} catch {
|
||||
setError('No git repository found in this project');
|
||||
return;
|
||||
@@ -64,6 +59,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
|
||||
// Get git log
|
||||
const gitLog = await git.log({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
depth: 50, // Limit to last 50 commits
|
||||
});
|
||||
@@ -75,7 +71,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [git, projectId]);
|
||||
}, [fs, projectId]);
|
||||
|
||||
const rollbackToCommit = useCallback(async (targetCommit: GitCommit) => {
|
||||
if (!fs) return;
|
||||
@@ -87,6 +83,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
|
||||
// Get the current HEAD commit
|
||||
const currentCommit = await git.resolveRef({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
@@ -102,6 +99,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
|
||||
// Get all commits between the target commit and HEAD
|
||||
const allCommits = await git.log({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
depth: 1000,
|
||||
});
|
||||
@@ -134,12 +132,14 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
|
||||
// Get all files from the target commit
|
||||
const targetFiles = await git.listFiles({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
ref: targetCommit.oid,
|
||||
});
|
||||
|
||||
// Get current files to know what to remove
|
||||
const currentFiles = await git.listFiles({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
@@ -150,6 +150,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
try {
|
||||
await fs.unlink(`${projectPath}/${filepath}`);
|
||||
await git.remove({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
filepath,
|
||||
});
|
||||
@@ -164,6 +165,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
for (const filepath of targetFiles) {
|
||||
try {
|
||||
const { blob } = await git.readBlob({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
oid: targetCommit.oid,
|
||||
filepath,
|
||||
@@ -180,6 +182,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
|
||||
// Stage the file
|
||||
await git.add({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
filepath,
|
||||
});
|
||||
@@ -201,6 +204,7 @@ ${commitsToRevert.map(c => {
|
||||
}).join('\n')}`;
|
||||
|
||||
await git.commit({
|
||||
fs,
|
||||
dir: projectPath,
|
||||
message: revertMessage,
|
||||
author: {
|
||||
@@ -227,7 +231,7 @@ ${commitsToRevert.map(c => {
|
||||
} finally {
|
||||
setIsRollingBack(null);
|
||||
}
|
||||
}, [git, fs, projectId, toast, loadGitHistory]);
|
||||
}, [fs, projectId, toast, loadGitHistory]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
@@ -276,19 +280,16 @@ ${commitsToRevert.map(c => {
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
{/* Only show trigger if not controlled externally */}
|
||||
{controlledOpen === undefined && (
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-1 sm:gap-2 hover:bg-secondary/10 hover:border-secondary/20"
|
||||
>
|
||||
<History className="h-4 w-4" />
|
||||
<span className="hidden sm:inline">History</span>
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
)}
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-1 sm:gap-2 hover:bg-secondary/10 hover:border-secondary/20"
|
||||
>
|
||||
<History className="h-4 w-4" />
|
||||
<span className="hidden sm:inline">History</span>
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-4xl max-h-[80vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { memo } from 'react';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { AssistantContent } from '@/components/ai/AssistantContent';
|
||||
import { Bot, User } from 'lucide-react';
|
||||
import type { CoreUserMessage, CoreAssistantMessage, CoreToolMessage } from 'ai';
|
||||
|
||||
interface MessageItemProps {
|
||||
message: (CoreUserMessage | CoreAssistantMessage | CoreToolMessage) & { id: string };
|
||||
userDisplayName?: string;
|
||||
userProfileImage?: string;
|
||||
toolResults?: CoreToolMessage[];
|
||||
}
|
||||
|
||||
export const MessageItem = memo(({
|
||||
message,
|
||||
userDisplayName = 'You',
|
||||
userProfileImage,
|
||||
toolResults = []
|
||||
}: MessageItemProps) => {
|
||||
// Don't render tool messages as separate items - they're integrated into assistant messages
|
||||
if (message.role === 'tool') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex gap-3">
|
||||
<Avatar className="h-8 w-8 flex-shrink-0">
|
||||
{message.role === 'user' ? (
|
||||
<>
|
||||
<AvatarImage src={userProfileImage} alt={userDisplayName} />
|
||||
<AvatarFallback>
|
||||
<User className="h-4 w-4" />
|
||||
</AvatarFallback>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<AvatarFallback>
|
||||
<Bot className="h-4 w-4" />
|
||||
</AvatarFallback>
|
||||
</>
|
||||
)}
|
||||
</Avatar>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="font-medium text-sm">
|
||||
{message.role === 'user' ? userDisplayName : 'Assistant'}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{message.role === 'user' ? 'User' : 'AI'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-sm">
|
||||
{message.role === 'user' ? (
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
{typeof message.content === 'string' ? message.content :
|
||||
message.content.map((part, _i) => {
|
||||
if (part.type === 'text') return part.text;
|
||||
return null;
|
||||
}).join('')
|
||||
}
|
||||
</div>
|
||||
) : message.role === 'assistant' ? (
|
||||
<AssistantContent
|
||||
content={(message as CoreAssistantMessage).content}
|
||||
toolResults={toolResults}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
MessageItem.displayName = 'MessageItem';
|
||||
@@ -0,0 +1,243 @@
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Package, Plus, Minus, CheckCircle, XCircle } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface PackageManagerProps {
|
||||
action: 'add' | 'remove';
|
||||
registry: 'npm' | 'jsr';
|
||||
packageName: string;
|
||||
version?: string;
|
||||
dev?: boolean;
|
||||
result?: string;
|
||||
isError?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function PackageManager({
|
||||
action,
|
||||
registry,
|
||||
packageName,
|
||||
version,
|
||||
dev,
|
||||
result,
|
||||
isError = false,
|
||||
className
|
||||
}: PackageManagerProps) {
|
||||
// Get package info
|
||||
const getPackageInfo = (name: string) => {
|
||||
// Common package icons
|
||||
if (name.includes('react')) return '⚛️';
|
||||
if (name.includes('vue')) return '💚';
|
||||
if (name.includes('angular')) return '🅰️';
|
||||
if (name.includes('typescript') || name.includes('@types/')) return '🔷';
|
||||
if (name.includes('eslint')) return '🔍';
|
||||
if (name.includes('prettier')) return '✨';
|
||||
if (name.includes('vite')) return '⚡';
|
||||
if (name.includes('webpack')) return '📦';
|
||||
if (name.includes('babel')) return '🐠';
|
||||
if (name.includes('jest') || name.includes('vitest')) return '🧪';
|
||||
if (name.includes('tailwind')) return '🎨';
|
||||
if (name.includes('sass') || name.includes('scss')) return '🎨';
|
||||
if (name.includes('lodash')) return '🔧';
|
||||
if (name.includes('axios')) return '🌐';
|
||||
if (name.includes('express')) return '🚀';
|
||||
if (name.includes('next')) return '▲';
|
||||
if (name.includes('nuxt')) return '💚';
|
||||
if (name.includes('svelte')) return '🧡';
|
||||
if (name.includes('prisma')) return '🔺';
|
||||
if (name.includes('graphql')) return '🔗';
|
||||
if (name.includes('socket')) return '🔌';
|
||||
if (name.includes('redis')) return '🔴';
|
||||
if (name.includes('mongo')) return '🍃';
|
||||
if (name.includes('postgres')) return '🐘';
|
||||
if (name.includes('mysql')) return '🐬';
|
||||
if (name.includes('docker')) return '🐳';
|
||||
if (name.includes('kubernetes')) return '☸️';
|
||||
if (name.includes('aws')) return '☁️';
|
||||
if (name.includes('firebase')) return '🔥';
|
||||
if (name.includes('stripe')) return '💳';
|
||||
if (name.includes('auth')) return '🔐';
|
||||
if (name.includes('crypto')) return '🔒';
|
||||
if (name.includes('date') || name.includes('moment')) return '📅';
|
||||
if (name.includes('uuid')) return '🆔';
|
||||
if (name.includes('validator')) return '✅';
|
||||
if (name.includes('helmet')) return '⛑️';
|
||||
if (name.includes('cors')) return '🌐';
|
||||
if (name.includes('dotenv')) return '🔧';
|
||||
if (name.includes('nodemon')) return '👀';
|
||||
if (name.includes('concurrently')) return '🔄';
|
||||
if (name.includes('husky')) return '🐶';
|
||||
if (name.includes('lint-staged')) return '🎭';
|
||||
if (name.includes('commitizen')) return '📝';
|
||||
if (name.includes('semantic-release')) return '🚀';
|
||||
if (name.includes('storybook')) return '📚';
|
||||
if (name.includes('cypress')) return '🌲';
|
||||
if (name.includes('playwright')) return '🎭';
|
||||
if (name.includes('puppeteer')) return '🎪';
|
||||
return '📦';
|
||||
};
|
||||
|
||||
const packageIcon = getPackageInfo(packageName);
|
||||
const registryIcon = registry === 'jsr' ? '🦕' : '📦';
|
||||
|
||||
// Parse output for useful information
|
||||
const parseOutput = (output: string) => {
|
||||
if (!output) return { summary: '', details: output };
|
||||
|
||||
if (action === 'add') {
|
||||
if (output.includes('added') || output.includes('installed')) {
|
||||
return {
|
||||
summary: `Successfully added ${packageName}${version ? `@${version}` : ''}`,
|
||||
details: output
|
||||
};
|
||||
}
|
||||
if (output.includes('already exists') || output.includes('up to date')) {
|
||||
return {
|
||||
summary: `${packageName} is already installed`,
|
||||
details: output
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (action === 'remove') {
|
||||
if (output.includes('removed') || output.includes('uninstalled')) {
|
||||
return {
|
||||
summary: `Successfully removed ${packageName}`,
|
||||
details: output
|
||||
};
|
||||
}
|
||||
if (output.includes('not found') || output.includes('not installed')) {
|
||||
return {
|
||||
summary: `${packageName} was not installed`,
|
||||
details: output
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
summary: `Package ${action} completed`,
|
||||
details: output
|
||||
};
|
||||
};
|
||||
|
||||
const { summary, details } = parseOutput(result || '');
|
||||
|
||||
return (
|
||||
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Package className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-lg">{packageIcon}</span>
|
||||
<span className="text-sm">{registryIcon}</span>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-mono text-sm font-medium">
|
||||
{action === 'add' ? (
|
||||
<span className="flex items-center gap-1">
|
||||
<Plus className="h-3 w-3 text-green-600" />
|
||||
{packageName}{version && `@${version}`}
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-1">
|
||||
<Minus className="h-3 w-3 text-red-600" />
|
||||
{packageName}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{action === 'add' ? 'Install' : 'Remove'} {registry.toUpperCase()} package
|
||||
{dev && ' (dev dependency)'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{result !== undefined ? (
|
||||
isError ? (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
<XCircle className="h-3 w-3 mr-1" />
|
||||
Failed
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
|
||||
<CheckCircle className="h-3 w-3 mr-1" />
|
||||
Success
|
||||
</Badge>
|
||||
)
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
|
||||
<Package className="h-3 w-3 mr-1" />
|
||||
{action === 'add' ? 'Installing' : 'Removing'}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
{result && (
|
||||
<CardContent className="pt-0">
|
||||
{/* Summary */}
|
||||
{summary && (
|
||||
<div className={cn(
|
||||
"mb-3 p-3 rounded-md text-sm font-medium",
|
||||
isError
|
||||
? "bg-destructive/10 text-destructive border border-destructive/20"
|
||||
: "bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-400 border border-green-200 dark:border-green-800/30"
|
||||
)}>
|
||||
{summary}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Full output */}
|
||||
{details && details.trim() && (
|
||||
<details className="group">
|
||||
<summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground transition-colors mb-2 flex items-center gap-1">
|
||||
<span className="group-open:rotate-90 transition-transform">▶</span>
|
||||
View package manager output
|
||||
</summary>
|
||||
<div className="bg-muted/30 rounded-md overflow-hidden">
|
||||
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50">
|
||||
Package Manager Output
|
||||
</div>
|
||||
<div className="p-3 max-h-80 overflow-auto">
|
||||
<pre className="text-xs font-mono whitespace-pre text-muted-foreground">
|
||||
{details}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
|
||||
{/* Package info */}
|
||||
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
|
||||
<span className="flex items-center gap-1">
|
||||
{registryIcon} {registry.toUpperCase()} registry
|
||||
</span>
|
||||
{version && (
|
||||
<span>
|
||||
Version: {version}
|
||||
</span>
|
||||
)}
|
||||
{dev && (
|
||||
<span className="text-orange-600 dark:text-orange-400">
|
||||
Development dependency
|
||||
</span>
|
||||
)}
|
||||
{action === 'add' && (
|
||||
<span className="text-green-600 dark:text-green-400">
|
||||
Added to project
|
||||
</span>
|
||||
)}
|
||||
{action === 'remove' && (
|
||||
<span className="text-red-600 dark:text-red-400">
|
||||
Removed from project
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Play, CheckCircle, XCircle } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ScriptRunnerProps {
|
||||
script: string;
|
||||
result?: string;
|
||||
isError?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ScriptRunner({ script, result, isError = false, className }: ScriptRunnerProps) {
|
||||
// Get script info
|
||||
const getScriptInfo = (scriptName: string) => {
|
||||
switch (scriptName) {
|
||||
case 'build': return { icon: '🔨', description: 'Build the project for production' };
|
||||
case 'test': return { icon: '🧪', description: 'Run tests and linting' };
|
||||
case 'dev': return { icon: '🚀', description: 'Start development server' };
|
||||
case 'start': return { icon: '▶️', description: 'Start the application' };
|
||||
case 'lint': return { icon: '🔍', description: 'Check code quality' };
|
||||
case 'format': return { icon: '✨', description: 'Format code' };
|
||||
case 'preview': return { icon: '👀', description: 'Preview production build' };
|
||||
case 'deploy': return { icon: '🚀', description: 'Deploy to production' };
|
||||
default: return { icon: '⚡', description: 'Run script' };
|
||||
}
|
||||
};
|
||||
|
||||
const scriptInfo = getScriptInfo(script);
|
||||
|
||||
// Parse output for useful information
|
||||
const parseOutput = (output: string) => {
|
||||
if (!output) return { summary: '', details: output };
|
||||
|
||||
const lines = output.split('\n').filter(line => line.trim());
|
||||
|
||||
// Look for common patterns
|
||||
if (script === 'build') {
|
||||
if (output.includes('built in') || output.includes('Build completed')) {
|
||||
return {
|
||||
summary: 'Build completed successfully',
|
||||
details: output
|
||||
};
|
||||
}
|
||||
if (output.includes('error') || output.includes('Error')) {
|
||||
return {
|
||||
summary: 'Build failed with errors',
|
||||
details: output
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (script === 'test') {
|
||||
const passMatch = output.match(/(\d+) passing/);
|
||||
const failMatch = output.match(/(\d+) failing/);
|
||||
if (passMatch || failMatch) {
|
||||
const passing = passMatch ? passMatch[1] : '0';
|
||||
const failing = failMatch ? failMatch[1] : '0';
|
||||
return {
|
||||
summary: `Tests completed: ${passing} passing, ${failing} failing`,
|
||||
details: output
|
||||
};
|
||||
}
|
||||
if (output.includes('All tests passed') || output.includes('✓')) {
|
||||
return {
|
||||
summary: 'All tests passed',
|
||||
details: output
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (script === 'lint') {
|
||||
if (output.includes('No linting errors found') || output.includes('✓')) {
|
||||
return {
|
||||
summary: 'No linting errors found',
|
||||
details: output
|
||||
};
|
||||
}
|
||||
const errorMatch = output.match(/(\d+) error/);
|
||||
const warningMatch = output.match(/(\d+) warning/);
|
||||
if (errorMatch || warningMatch) {
|
||||
const errors = errorMatch ? errorMatch[1] : '0';
|
||||
const warnings = warningMatch ? warningMatch[1] : '0';
|
||||
return {
|
||||
summary: `Linting completed: ${errors} errors, ${warnings} warnings`,
|
||||
details: output
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Default: use last meaningful line
|
||||
const meaningfulLines = lines.filter(line =>
|
||||
!line.startsWith('#') &&
|
||||
!line.startsWith('//') &&
|
||||
line.length > 0
|
||||
);
|
||||
|
||||
return {
|
||||
summary: meaningfulLines[meaningfulLines.length - 1] || 'Script executed',
|
||||
details: output
|
||||
};
|
||||
};
|
||||
|
||||
const { summary, details } = parseOutput(result || '');
|
||||
|
||||
return (
|
||||
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Play className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-lg">{scriptInfo.icon}</span>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-mono text-sm font-medium">npm run {script}</div>
|
||||
<div className="text-xs text-muted-foreground">{scriptInfo.description}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{result !== undefined ? (
|
||||
isError ? (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
<XCircle className="h-3 w-3 mr-1" />
|
||||
Failed
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
|
||||
<CheckCircle className="h-3 w-3 mr-1" />
|
||||
Success
|
||||
</Badge>
|
||||
)
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
|
||||
<Play className="h-3 w-3 mr-1" />
|
||||
Running
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
{result && (
|
||||
<CardContent className="pt-0">
|
||||
{/* Summary */}
|
||||
{summary && (
|
||||
<div className={cn(
|
||||
"mb-3 p-3 rounded-md text-sm font-medium",
|
||||
isError
|
||||
? "bg-destructive/10 text-destructive border border-destructive/20"
|
||||
: "bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-400 border border-green-200 dark:border-green-800/30"
|
||||
)}>
|
||||
{summary}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Full output */}
|
||||
{details && details.trim() && (
|
||||
<details className="group">
|
||||
<summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground transition-colors mb-2 flex items-center gap-1">
|
||||
<span className="group-open:rotate-90 transition-transform">▶</span>
|
||||
View script output
|
||||
</summary>
|
||||
<div className="bg-muted/30 rounded-md overflow-hidden">
|
||||
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50">
|
||||
Script Output
|
||||
</div>
|
||||
<div className="p-3 max-h-80 overflow-auto">
|
||||
<pre className="text-xs font-mono whitespace-pre text-muted-foreground">
|
||||
{details}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
|
||||
{/* Script stats */}
|
||||
{!isError && details && (
|
||||
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
|
||||
<span>
|
||||
{details.split('\n').length} line{details.split('\n').length !== 1 ? 's' : ''} output
|
||||
</span>
|
||||
{script === 'build' && details.includes('built in') && (
|
||||
<span>
|
||||
Build time: {details.match(/built in (\d+\.?\d*[a-z]+)/)?.[1] || 'unknown'}
|
||||
</span>
|
||||
)}
|
||||
{script === 'test' && (
|
||||
<>
|
||||
{details.match(/(\d+) passing/) && (
|
||||
<span className="text-green-600 dark:text-green-400">
|
||||
{details.match(/(\d+) passing/)?.[1]} passing
|
||||
</span>
|
||||
)}
|
||||
{details.match(/(\d+) failing/) && (
|
||||
<span className="text-red-600 dark:text-red-400">
|
||||
{details.match(/(\d+) failing/)?.[1]} failing
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Terminal, CheckCircle, XCircle, Play } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ShellCommandProps {
|
||||
command: string;
|
||||
result?: string;
|
||||
isError?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ShellCommand({ command, result, isError = false, className }: ShellCommandProps) {
|
||||
// Parse command to get useful information
|
||||
const parseCommand = (cmd: string) => {
|
||||
const parts = cmd.trim().split(' ');
|
||||
const baseCommand = parts[0];
|
||||
|
||||
// Get command info
|
||||
const getCommandInfo = (baseCmd: string) => {
|
||||
switch (baseCmd) {
|
||||
case 'ls':
|
||||
case 'dir': return { icon: '📁', description: 'List directory contents' };
|
||||
case 'cd': return { icon: '📂', description: 'Change directory' };
|
||||
case 'mkdir': return { icon: '📁', description: 'Create directory' };
|
||||
case 'rm':
|
||||
case 'rmdir':
|
||||
case 'del': return { icon: '🗑️', description: 'Remove files/directories' };
|
||||
case 'cp':
|
||||
case 'copy': return { icon: '📋', description: 'Copy files' };
|
||||
case 'mv':
|
||||
case 'move': return { icon: '📦', description: 'Move/rename files' };
|
||||
case 'cat':
|
||||
case 'type': return { icon: '📄', description: 'Display file contents' };
|
||||
case 'grep':
|
||||
case 'findstr': return { icon: '🔍', description: 'Search text patterns' };
|
||||
case 'find': return { icon: '🔍', description: 'Find files and directories' };
|
||||
case 'chmod': return { icon: '🔐', description: 'Change file permissions' };
|
||||
case 'git': return { icon: '🌿', description: 'Git version control' };
|
||||
case 'npm':
|
||||
case 'yarn':
|
||||
case 'pnpm': return { icon: '📦', description: 'Package manager' };
|
||||
case 'node': return { icon: '🟢', description: 'Run Node.js' };
|
||||
case 'python':
|
||||
case 'python3': return { icon: '🐍', description: 'Run Python' };
|
||||
case 'curl':
|
||||
case 'wget': return { icon: '🌐', description: 'Download from web' };
|
||||
case 'ps': return { icon: '⚙️', description: 'List running processes' };
|
||||
case 'kill': return { icon: '⚡', description: 'Terminate processes' };
|
||||
case 'echo': return { icon: '💬', description: 'Display text' };
|
||||
case 'pwd': return { icon: '📍', description: 'Show current directory' };
|
||||
case 'whoami': return { icon: '👤', description: 'Show current user' };
|
||||
case 'which':
|
||||
case 'where': return { icon: '🔍', description: 'Locate command' };
|
||||
default: return { icon: '⚡', description: 'Execute command' };
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
baseCommand,
|
||||
fullCommand: cmd,
|
||||
...getCommandInfo(baseCommand)
|
||||
};
|
||||
};
|
||||
|
||||
const commandInfo = parseCommand(command);
|
||||
|
||||
// Parse output for useful information
|
||||
const parseOutput = (output: string) => {
|
||||
if (!output) return { summary: '', details: output };
|
||||
|
||||
const lines = output.split('\n').filter(line => line.trim());
|
||||
|
||||
// Look for common patterns
|
||||
if (commandInfo.baseCommand === 'ls' || commandInfo.baseCommand === 'dir') {
|
||||
const fileCount = lines.length;
|
||||
return {
|
||||
summary: `Found ${fileCount} item${fileCount !== 1 ? 's' : ''}`,
|
||||
details: output
|
||||
};
|
||||
}
|
||||
|
||||
if (commandInfo.baseCommand === 'git') {
|
||||
const gitSubcommand = command.split(' ')[1];
|
||||
if (gitSubcommand === 'status') {
|
||||
return {
|
||||
summary: lines.find(line => line.includes('nothing to commit') || line.includes('Changes') || line.includes('Untracked')) || 'Git status checked',
|
||||
details: output
|
||||
};
|
||||
}
|
||||
if (gitSubcommand === 'log') {
|
||||
const commitCount = (output.match(/commit /g) || []).length;
|
||||
return {
|
||||
summary: `Showing ${commitCount} commit${commitCount !== 1 ? 's' : ''}`,
|
||||
details: output
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (commandInfo.baseCommand === 'npm' || commandInfo.baseCommand === 'yarn') {
|
||||
if (output.includes('added') || output.includes('installed')) {
|
||||
return {
|
||||
summary: 'Package installation completed',
|
||||
details: output
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Default: use first meaningful line or last line
|
||||
const meaningfulLines = lines.filter(line =>
|
||||
!line.startsWith('#') &&
|
||||
!line.startsWith('//') &&
|
||||
line.length > 0
|
||||
);
|
||||
|
||||
return {
|
||||
summary: meaningfulLines[meaningfulLines.length - 1] || 'Command executed',
|
||||
details: output
|
||||
};
|
||||
};
|
||||
|
||||
const { summary, details } = parseOutput(result || '');
|
||||
|
||||
return (
|
||||
<Card className={cn("mt-2", isError ? "border-destructive/50" : "border-muted", className)}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Terminal className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-lg">{commandInfo.icon}</span>
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-mono text-sm font-medium">$ {commandInfo.fullCommand}</div>
|
||||
<div className="text-xs text-muted-foreground">{commandInfo.description}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{result !== undefined ? (
|
||||
isError ? (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
<XCircle className="h-3 w-3 mr-1" />
|
||||
Failed
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
|
||||
<CheckCircle className="h-3 w-3 mr-1" />
|
||||
Success
|
||||
</Badge>
|
||||
)
|
||||
) : (
|
||||
<Badge variant="secondary" className="text-xs bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-400">
|
||||
<Play className="h-3 w-3 mr-1" />
|
||||
Running
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
{result && (
|
||||
<CardContent className="pt-0">
|
||||
{/* Summary */}
|
||||
{summary && (
|
||||
<div className={cn(
|
||||
"mb-3 p-3 rounded-md text-sm font-medium",
|
||||
isError
|
||||
? "bg-destructive/10 text-destructive border border-destructive/20"
|
||||
: "bg-green-50 text-green-800 dark:bg-green-900/20 dark:text-green-400 border border-green-200 dark:border-green-800/30"
|
||||
)}>
|
||||
{summary}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Full output */}
|
||||
{details && details.trim() && (
|
||||
<details className="group">
|
||||
<summary className="cursor-pointer text-xs text-muted-foreground hover:text-foreground transition-colors mb-2 flex items-center gap-1">
|
||||
<span className="group-open:rotate-90 transition-transform">▶</span>
|
||||
View command output
|
||||
</summary>
|
||||
<div className="bg-muted/30 rounded-md overflow-hidden">
|
||||
<div className="bg-muted/50 px-3 py-2 text-xs font-mono text-muted-foreground border-b border-muted/50">
|
||||
Terminal Output
|
||||
</div>
|
||||
<div className="p-3 max-h-80 overflow-auto">
|
||||
<pre className="text-xs font-mono whitespace-pre text-muted-foreground">
|
||||
{details}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
|
||||
{/* Command stats */}
|
||||
{!isError && details && (
|
||||
<div className="mt-3 flex items-center gap-4 text-xs text-muted-foreground">
|
||||
<span>
|
||||
{details.split('\n').length} line{details.split('\n').length !== 1 ? 's' : ''} output
|
||||
</span>
|
||||
{commandInfo.baseCommand === 'ls' && (
|
||||
<span>
|
||||
{details.split('\n').filter(line => line.trim()).length} items listed
|
||||
</span>
|
||||
)}
|
||||
{(commandInfo.baseCommand === 'git' && command.includes('log')) && (
|
||||
<span>
|
||||
{(details.match(/commit /g) || []).length} commits shown
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { memo } from 'react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { CheckCircle, XCircle, Wrench } from 'lucide-react';
|
||||
import type { CoreToolMessage } from 'ai';
|
||||
|
||||
interface ToolResultContentProps {
|
||||
content: CoreToolMessage['content'];
|
||||
}
|
||||
|
||||
export const ToolResultContent = memo(({ content }: ToolResultContentProps) => {
|
||||
if (typeof content === 'string') {
|
||||
return (
|
||||
<Card className="mt-2 bg-muted/50">
|
||||
<CardContent className="p-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Wrench className="h-4 w-4 flex-shrink-0" />
|
||||
<span className="font-mono text-sm">Tool Result</span>
|
||||
</div>
|
||||
<div className="text-xs rounded p-2 border bg-background">
|
||||
<pre className="whitespace-pre-wrap break-words overflow-x-auto">{content}</pre>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{content.map((item, index) => {
|
||||
if (item.type === 'tool-result') {
|
||||
const isError = item.isError || false;
|
||||
const result = typeof item.result === 'string' ? item.result : JSON.stringify(item.result);
|
||||
|
||||
return (
|
||||
<Card key={index} className="mt-2 bg-muted/50">
|
||||
<CardContent className="p-3">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Wrench className="h-4 w-4 flex-shrink-0" />
|
||||
<span className="font-mono text-sm">{item.toolName}</span>
|
||||
</div>
|
||||
<Badge variant={isError ? "destructive" : "secondary"} className="text-xs">
|
||||
{isError ? (
|
||||
<>
|
||||
<XCircle className="h-3 w-3 mr-1" />
|
||||
Error
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle className="h-3 w-3 mr-1" />
|
||||
Success
|
||||
</>
|
||||
)}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className={`text-xs rounded p-2 border max-h-40 overflow-scroll ${
|
||||
isError ? 'bg-destructive/10 border-destructive/20' : 'bg-background'
|
||||
}`}>
|
||||
<pre className="whitespace-pre-wrap break-words overflow-x-auto">{result}</pre>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
})}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
ToolResultContent.displayName = 'ToolResultContent';
|
||||
@@ -35,7 +35,7 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
|
||||
<AvatarImage src={currentUser.metadata.picture} alt={getDisplayName(currentUser)} />
|
||||
<AvatarFallback>{getDisplayName(currentUser).charAt(0)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className='flex-1 text-left truncate'>
|
||||
<div className='flex-1 text-left hidden md:block truncate'>
|
||||
<p className='font-medium text-sm truncate'>{getDisplayName(currentUser)}</p>
|
||||
</div>
|
||||
<ChevronDown className='w-4 h-4 text-muted-foreground' />
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { ArrowLeft, ArrowRight, Settings, Bot } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
|
||||
interface AISettingsStepProps {
|
||||
onNext: () => void;
|
||||
onPrevious: () => void;
|
||||
onSkip: () => void;
|
||||
}
|
||||
|
||||
export function AISettingsStep({ onNext, onPrevious, onSkip }: AISettingsStepProps) {
|
||||
const { settings, updateSettings } = useAISettings();
|
||||
const [localSettings, setLocalSettings] = useState(settings);
|
||||
|
||||
const handleSave = () => {
|
||||
updateSettings(localSettings);
|
||||
onNext();
|
||||
};
|
||||
|
||||
const isValid = localSettings.apiKey.trim() && localSettings.baseUrl.trim() && localSettings.model.trim();
|
||||
|
||||
return (
|
||||
<div className="space-y-2 sm:space-y-4 mb-3 sm:mb-0">
|
||||
<div className="text-center space-y-1 sm:space-y-1.5">
|
||||
<div className="flex justify-center mb-0.5 sm:mb-1">
|
||||
<Bot className="h-5 w-5 sm:h-6 sm:w-6 text-primary" />
|
||||
</div>
|
||||
<h1 className="text-base sm:text-lg md:text-xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent leading-tight">
|
||||
Configure AI Settings
|
||||
</h1>
|
||||
<p className="text-xs sm:text-sm text-muted-foreground max-w-md mx-auto px-2">
|
||||
Set up your AI provider to start building with AI assistance.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="max-w-md sm:max-w-lg md:max-w-lg mx-auto">
|
||||
<CardHeader className="pb-2 sm:pb-3">
|
||||
<div className="flex items-center gap-1.5 sm:gap-2">
|
||||
<Settings className="h-3.5 w-3.5 sm:h-4 sm:w-4 text-primary" />
|
||||
<CardTitle className="text-base sm:text-lg">AI Provider</CardTitle>
|
||||
</div>
|
||||
<CardDescription className="text-[10px] sm:text-xs">
|
||||
We recommend OpenRouter for easy setup
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 sm:space-y-3">
|
||||
<div className="space-y-2 sm:space-y-3">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="apiKey" className="text-xs sm:text-sm">API Key *</Label>
|
||||
<Input
|
||||
id="apiKey"
|
||||
type="password"
|
||||
placeholder="sk-... or your-api-key"
|
||||
value={localSettings.apiKey}
|
||||
onChange={(e) => setLocalSettings({ ...localSettings, apiKey: e.target.value })}
|
||||
className="font-mono text-xs sm:text-sm h-8 sm:h-9"
|
||||
/>
|
||||
<p className="text-[10px] sm:text-xs text-muted-foreground">
|
||||
Stored locally, never shared
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="baseUrl" className="text-xs sm:text-sm">Base URL *</Label>
|
||||
<Input
|
||||
id="baseUrl"
|
||||
placeholder="https://openrouter.ai/api/v1"
|
||||
value={localSettings.baseUrl}
|
||||
onChange={(e) => setLocalSettings({ ...localSettings, baseUrl: e.target.value })}
|
||||
className="text-xs sm:text-sm h-8 sm:h-9"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="model" className="text-xs sm:text-sm">Model *</Label>
|
||||
<Input
|
||||
id="model"
|
||||
placeholder="anthropic/claude-sonnet-4"
|
||||
value={localSettings.model}
|
||||
onChange={(e) => setLocalSettings({ ...localSettings, model: e.target.value })}
|
||||
className="text-xs sm:text-sm h-8 sm:h-9"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex justify-center gap-2 sm:gap-3 pt-1 sm:pt-2">
|
||||
<Button
|
||||
onClick={onPrevious}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-1 h-8 text-sm"
|
||||
>
|
||||
<ArrowLeft className="h-3 w-3" />
|
||||
Back
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={!isValid}
|
||||
size="sm"
|
||||
className="gap-1 h-8 text-sm bg-gradient-to-r from-primary to-primary/90"
|
||||
>
|
||||
Continue
|
||||
<ArrowRight className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="text-center">
|
||||
<Button
|
||||
onClick={onSkip}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-muted-foreground text-[10px] sm:text-xs h-6 sm:h-7"
|
||||
>
|
||||
Skip for now
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { WelcomeStep } from './WelcomeStep';
|
||||
import { AISettingsStep } from './AISettingsStep';
|
||||
import { ProjectStep } from './ProjectStep';
|
||||
|
||||
interface OnboardingDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onProjectCreated?: (projectId: string) => void;
|
||||
onComplete: () => void;
|
||||
currentStep: number;
|
||||
onNextStep: () => void;
|
||||
onPreviousStep: () => void;
|
||||
initialPrompt?: string;
|
||||
}
|
||||
|
||||
const STEPS = [
|
||||
{ id: 'welcome', title: 'Welcome' },
|
||||
{ id: 'ai-settings', title: 'AI Settings' },
|
||||
{ id: 'project', title: 'Create Project' },
|
||||
];
|
||||
|
||||
export function OnboardingDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onProjectCreated,
|
||||
onComplete,
|
||||
currentStep: propCurrentStep,
|
||||
onNextStep,
|
||||
onPreviousStep,
|
||||
initialPrompt = ''
|
||||
}: OnboardingDialogProps) {
|
||||
const [localStep, setLocalStep] = useState(propCurrentStep);
|
||||
|
||||
// Sync local step with prop when it changes
|
||||
useEffect(() => {
|
||||
setLocalStep(propCurrentStep);
|
||||
}, [propCurrentStep]);
|
||||
|
||||
const currentStep = Math.min(localStep, STEPS.length - 1);
|
||||
const progress = ((currentStep + 1) / STEPS.length) * 100;
|
||||
|
||||
const handleNext = () => {
|
||||
if (currentStep < STEPS.length - 1) {
|
||||
setLocalStep(prev => prev + 1);
|
||||
onNextStep();
|
||||
}
|
||||
};
|
||||
|
||||
const handlePrevious = () => {
|
||||
if (currentStep > 0) {
|
||||
setLocalStep(prev => prev - 1);
|
||||
onPreviousStep();
|
||||
}
|
||||
};
|
||||
|
||||
const handleSkip = () => {
|
||||
onComplete();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const handleComplete = () => {
|
||||
onComplete();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const renderStep = () => {
|
||||
switch (STEPS[currentStep]?.id) {
|
||||
case 'welcome':
|
||||
return (
|
||||
<WelcomeStep
|
||||
onNext={handleNext}
|
||||
onSkip={handleSkip}
|
||||
/>
|
||||
);
|
||||
case 'ai-settings':
|
||||
return (
|
||||
<AISettingsStep
|
||||
onNext={handleNext}
|
||||
onPrevious={handlePrevious}
|
||||
onSkip={handleSkip}
|
||||
/>
|
||||
);
|
||||
case 'project':
|
||||
return (
|
||||
<ProjectStep
|
||||
onNext={handleSkip} // Skip to complete
|
||||
onPrevious={handlePrevious}
|
||||
onComplete={handleComplete}
|
||||
onProjectCreated={onProjectCreated}
|
||||
initialPrompt={initialPrompt}
|
||||
/>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg w-[95vw] max-h-[90vh] overflow-y-auto p-0 sm:max-w-xl md:max-w-4xl">
|
||||
<div className="sticky top-0 bg-background border-b p-4 sm:p-5 pb-3 z-10">
|
||||
<DialogTitle className="sr-only">Getting Started Onboarding</DialogTitle>
|
||||
<DialogDescription className="sr-only">Complete the onboarding process to get started with Shakespeare</DialogDescription>
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-base sm:text-lg font-semibold">Getting Started</h2>
|
||||
<span className="text-xs sm:text-sm text-muted-foreground">
|
||||
{currentStep + 1} / {STEPS.length}
|
||||
</span>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<Progress value={progress} className="h-1.5" />
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 text-[10px] sm:text-xs text-muted-foreground">
|
||||
{STEPS.map((step, index) => (
|
||||
<span
|
||||
key={step.id}
|
||||
className={`text-center ${index <= currentStep ? 'text-primary font-medium' : ''} truncate`}
|
||||
>
|
||||
{step.title}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="px-2 sm:p-6">
|
||||
{renderStep()}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { ArrowLeft, Plus, Sparkles } from 'lucide-react';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
interface ProjectStepProps {
|
||||
onNext: () => void;
|
||||
onPrevious: () => void;
|
||||
onComplete: () => void;
|
||||
onProjectCreated?: (projectId: string) => void;
|
||||
initialPrompt?: string;
|
||||
}
|
||||
|
||||
export function ProjectStep({ onPrevious, onComplete, onProjectCreated, initialPrompt = '' }: ProjectStepProps) {
|
||||
const [prompt, setPrompt] = useState(initialPrompt);
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const projectsManager = useProjectsManager();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleCreateProject = async () => {
|
||||
if (!prompt.trim()) return;
|
||||
|
||||
setIsCreating(true);
|
||||
try {
|
||||
const project = await projectsManager.createProject(prompt.trim());
|
||||
onProjectCreated?.(project.id);
|
||||
onComplete();
|
||||
navigate(`/project/${project.id}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to create project:', error);
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3 sm:space-y-6 pb-4">
|
||||
<div className="text-center space-y-1 sm:space-y-4">
|
||||
<div className="flex justify-center mb-0.5 sm:mb-2">
|
||||
<Sparkles className="h-5 w-5 sm:h-8 sm:w-8 text-primary" />
|
||||
</div>
|
||||
<h1 className="text-base sm:text-2xl md:text-3xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent leading-tight">
|
||||
Create Your First Project
|
||||
</h1>
|
||||
<p className="text-xs sm:text-base text-muted-foreground max-w-md sm:max-w-2xl mx-auto px-2">
|
||||
Our AI will help you create it step by step.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="max-w-md sm:max-w-2xl md:max-w-2xl mx-auto">
|
||||
<CardHeader className="pb-3 sm:pb-4">
|
||||
<div className="flex items-center gap-1.5 sm:gap-2">
|
||||
<Sparkles className="h-4 w-4 sm:h-5 sm:w-5 text-primary" />
|
||||
<CardTitle className="text-base sm:text-lg">Project Description</CardTitle>
|
||||
</div>
|
||||
<CardDescription className="text-xs sm:text-sm">
|
||||
Be as detailed as possible about what you want to build
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3 sm:space-y-4">
|
||||
<Textarea
|
||||
placeholder="e.g., Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies. Include user profiles, product listings with images, search functionality, and direct messaging between buyers and sellers..."
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
className="min-h-[175px] sm:min-h-[100px] sm:min-h-[125px] text-xs sm:text-sm leading-relaxed"
|
||||
disabled={isCreating}
|
||||
/>
|
||||
|
||||
<div className="hidden sm:block space-y-1.5 sm:space-y-2">
|
||||
<h3 className="font-medium text-xs sm:text-sm">Example prompts:</h3>
|
||||
<ul className="text-[10px] sm:text-xs text-muted-foreground space-y-0.5 sm:space-y-1">
|
||||
<li>• "Build a social media platform for photographers"</li>
|
||||
<li>• "Create a blog with markdown and Nostr comments"</li>
|
||||
<li>• "Design a marketplace with categories and ratings"</li>
|
||||
</ul>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex flex-col items-center gap-2 pt-2 sm:pt-4">
|
||||
<Button
|
||||
onClick={handleCreateProject}
|
||||
disabled={!prompt.trim() || isCreating}
|
||||
size="lg"
|
||||
className="gap-2 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80"
|
||||
>
|
||||
{isCreating ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-1"></div>
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Plus className="h-4 w-4" />
|
||||
Create Project
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={onPrevious}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-muted-foreground text-xs h-7"
|
||||
>
|
||||
<ArrowLeft className="h-3 w-3" />
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { ArrowRight, Zap, GlobeLock, Palette } from 'lucide-react';
|
||||
|
||||
interface WelcomeStepProps {
|
||||
onNext: () => void;
|
||||
onSkip: () => void;
|
||||
}
|
||||
|
||||
export function WelcomeStep({ onNext, onSkip }: WelcomeStepProps) {
|
||||
return (
|
||||
<div className="space-y-6 p-4">
|
||||
<div className="text-center space-y-4">
|
||||
<div className="text-6xl mb-4">🎭</div>
|
||||
<h1 className="text-3xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
Welcome to Shakespeare
|
||||
</h1>
|
||||
<p className="text-base text-muted-foreground max-w-2xl mx-auto">
|
||||
Build custom Nostr websites with AI assistance. Let's get you set up in just a few steps.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="hidden md:grid md:grid-cols-3 gap-4 max-w-4xl mx-auto">
|
||||
<Card className="text-center">
|
||||
<CardHeader>
|
||||
<div className="flex justify-center mb-2">
|
||||
<Zap className="h-8 w-8 text-primary" />
|
||||
</div>
|
||||
<CardTitle className="text-lg">AI-Powered</CardTitle>
|
||||
<CardDescription>
|
||||
Describe your vision and let AI build your Nostr website
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
<Card className="text-center">
|
||||
<CardHeader>
|
||||
<div className="flex justify-center mb-2">
|
||||
<GlobeLock className="h-8 w-8 text-primary" />
|
||||
</div>
|
||||
<CardTitle className="text-lg">Decentralized</CardTitle>
|
||||
<CardDescription>
|
||||
Built with the Nostr protocol for censorship resistance
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
<Card className="text-center">
|
||||
<CardHeader>
|
||||
<div className="flex justify-center mb-2">
|
||||
<Palette className="h-8 w-8 text-primary" />
|
||||
</div>
|
||||
<CardTitle className="text-lg">Customizable</CardTitle>
|
||||
<CardDescription>
|
||||
Edit code directly or let AI make changes based on your feedback
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-center gap-2 pt-4">
|
||||
<Button
|
||||
onClick={onNext}
|
||||
size="lg"
|
||||
className="gap-2 bg-gradient-to-r from-primary to-primary/90 hover:from-primary/90 hover:to-primary/80"
|
||||
>
|
||||
Get Started
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
onClick={onSkip}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-muted-foreground text-xs h-7"
|
||||
>
|
||||
Skip for now
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export { OnboardingDialog } from './OnboardingDialog';
|
||||
export { WelcomeStep } from './WelcomeStep';
|
||||
export { AISettingsStep } from './AISettingsStep';
|
||||
export { ProjectStep } from './ProjectStep';
|
||||
@@ -1,61 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { BrowserAddressBar } from './browser-address-bar';
|
||||
|
||||
describe('BrowserAddressBar', () => {
|
||||
it('renders navigation buttons and address input', () => {
|
||||
render(<BrowserAddressBar />);
|
||||
|
||||
expect(screen.getByTitle('Go back')).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Go forward')).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Refresh')).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('Enter path (e.g., /, /about)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onNavigate with proper path when form is submitted', () => {
|
||||
const onNavigate = vi.fn();
|
||||
render(<BrowserAddressBar onNavigate={onNavigate} />);
|
||||
|
||||
const input = screen.getByPlaceholderText('Enter path (e.g., /, /about)');
|
||||
fireEvent.change(input, { target: { value: 'about' } });
|
||||
fireEvent.submit(input.closest('form')!);
|
||||
|
||||
expect(onNavigate).toHaveBeenCalledWith('/about');
|
||||
});
|
||||
|
||||
it('disables back/forward buttons based on canGoBack/canGoForward props', () => {
|
||||
render(
|
||||
<BrowserAddressBar
|
||||
canGoBack={false}
|
||||
canGoForward={true}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTitle('Go back')).toBeDisabled();
|
||||
expect(screen.getByTitle('Go forward')).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('calls navigation handlers when buttons are clicked', () => {
|
||||
const onBack = vi.fn();
|
||||
const onForward = vi.fn();
|
||||
const onRefresh = vi.fn();
|
||||
|
||||
render(
|
||||
<BrowserAddressBar
|
||||
onBack={onBack}
|
||||
onForward={onForward}
|
||||
onRefresh={onRefresh}
|
||||
canGoBack={true}
|
||||
canGoForward={true}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByTitle('Go back'));
|
||||
fireEvent.click(screen.getByTitle('Go forward'));
|
||||
fireEvent.click(screen.getByTitle('Refresh'));
|
||||
|
||||
expect(onBack).toHaveBeenCalled();
|
||||
expect(onForward).toHaveBeenCalled();
|
||||
expect(onRefresh).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,96 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface BrowserAddressBarProps {
|
||||
currentPath?: string;
|
||||
onNavigate?: (path: string) => void;
|
||||
onRefresh?: () => void;
|
||||
onBack?: () => void;
|
||||
onForward?: () => void;
|
||||
canGoBack?: boolean;
|
||||
canGoForward?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function BrowserAddressBar({
|
||||
currentPath = '/',
|
||||
onNavigate,
|
||||
onRefresh,
|
||||
onBack,
|
||||
onForward,
|
||||
canGoBack = false,
|
||||
canGoForward = false,
|
||||
className,
|
||||
}: BrowserAddressBarProps) {
|
||||
const [inputValue, setInputValue] = useState(currentPath);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
let path = inputValue.trim();
|
||||
|
||||
// Ensure path starts with /
|
||||
if (!path.startsWith('/')) {
|
||||
path = '/' + path;
|
||||
}
|
||||
|
||||
onNavigate?.(path);
|
||||
};
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setInputValue(e.target.value);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn(
|
||||
"flex items-center gap-1 p-2 border-b bg-background",
|
||||
className
|
||||
)}>
|
||||
{/* Navigation buttons */}
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onBack}
|
||||
disabled={!canGoBack}
|
||||
className="h-8 w-8 p-0"
|
||||
title="Go back"
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onForward}
|
||||
disabled={!canGoForward}
|
||||
className="h-8 w-8 p-0"
|
||||
title="Go forward"
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onRefresh}
|
||||
className="h-8 w-8 p-0"
|
||||
title="Refresh"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Address bar */}
|
||||
<form onSubmit={handleSubmit} className="flex-1 mx-2">
|
||||
<Input
|
||||
type="text"
|
||||
value={inputValue}
|
||||
onChange={handleInputChange}
|
||||
placeholder="Enter path (e.g., /, /about)"
|
||||
className="h-8 bg-muted/50 border-muted-foreground/20 focus:bg-background"
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
interface CircularProgressProps {
|
||||
value?: number;
|
||||
size?: number;
|
||||
strokeWidth?: number;
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
const CircularProgress = React.forwardRef<
|
||||
SVGSVGElement,
|
||||
CircularProgressProps
|
||||
>(({ value = 0, size = 24, strokeWidth = 2, className, children }, ref) => {
|
||||
const radius = (size - strokeWidth) / 2;
|
||||
const circumference = 2 * Math.PI * radius;
|
||||
const strokeDasharray = circumference;
|
||||
const strokeDashoffset = circumference - (value / 100) * circumference;
|
||||
|
||||
return (
|
||||
<div className={cn("relative inline-flex items-center justify-center", className)}>
|
||||
<svg
|
||||
ref={ref}
|
||||
width={size}
|
||||
height={size}
|
||||
className="transform -rotate-90"
|
||||
viewBox={`0 0 ${size} ${size}`}
|
||||
>
|
||||
{/* Background circle */}
|
||||
<circle
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={radius}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={strokeWidth}
|
||||
className="text-muted/30"
|
||||
/>
|
||||
{/* Progress circle */}
|
||||
<circle
|
||||
cx={size / 2}
|
||||
cy={size / 2}
|
||||
r={radius}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinecap="round"
|
||||
strokeDasharray={strokeDasharray}
|
||||
strokeDashoffset={strokeDashoffset}
|
||||
className="text-primary transition-all duration-300 ease-in-out"
|
||||
/>
|
||||
</svg>
|
||||
{children && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
{children}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
CircularProgress.displayName = "CircularProgress";
|
||||
|
||||
export { CircularProgress };
|
||||
@@ -1,102 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { FileAttachment } from './file-attachment';
|
||||
|
||||
describe('FileAttachment', () => {
|
||||
it('renders the attachment button', () => {
|
||||
const onFileSelect = vi.fn();
|
||||
|
||||
render(
|
||||
<FileAttachment onFileSelect={onFileSelect} />
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onFileSelect when file is selected', async () => {
|
||||
const onFileSelect = vi.fn();
|
||||
|
||||
render(
|
||||
<FileAttachment onFileSelect={onFileSelect} />
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
fireEvent.click(button);
|
||||
|
||||
// Get the hidden file input
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
expect(fileInput).toBeInTheDocument();
|
||||
|
||||
// Create a mock file
|
||||
const file = new File(['test content'], 'test.txt', { type: 'text/plain' });
|
||||
|
||||
// Mock the file input change event
|
||||
Object.defineProperty(fileInput, 'files', {
|
||||
value: [file],
|
||||
writable: false,
|
||||
});
|
||||
|
||||
fireEvent.change(fileInput);
|
||||
|
||||
expect(onFileSelect).toHaveBeenCalledWith(file);
|
||||
});
|
||||
|
||||
it('displays selected files', () => {
|
||||
const onFileSelect = vi.fn();
|
||||
const onFileRemove = vi.fn();
|
||||
const selectedFiles = [
|
||||
new File(['content1'], 'file1.txt', { type: 'text/plain' }),
|
||||
new File(['content2'], 'file2.txt', { type: 'text/plain' }),
|
||||
];
|
||||
|
||||
render(
|
||||
<FileAttachment
|
||||
onFileSelect={onFileSelect}
|
||||
onFileRemove={onFileRemove}
|
||||
selectedFiles={selectedFiles}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('file1.txt')).toBeInTheDocument();
|
||||
expect(screen.getByText('file2.txt')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onFileRemove when remove button is clicked', () => {
|
||||
const onFileSelect = vi.fn();
|
||||
const onFileRemove = vi.fn();
|
||||
const selectedFiles = [
|
||||
new File(['content'], 'test.txt', { type: 'text/plain' }),
|
||||
];
|
||||
|
||||
render(
|
||||
<FileAttachment
|
||||
onFileSelect={onFileSelect}
|
||||
onFileRemove={onFileRemove}
|
||||
selectedFiles={selectedFiles}
|
||||
/>
|
||||
);
|
||||
|
||||
const removeButtons = screen.getAllByRole('button');
|
||||
// First button is the attachment button, second is the remove button
|
||||
const removeButton = removeButtons[1];
|
||||
|
||||
fireEvent.click(removeButton);
|
||||
|
||||
expect(onFileRemove).toHaveBeenCalledWith(selectedFiles[0]);
|
||||
});
|
||||
|
||||
it('disables interaction when disabled prop is true', () => {
|
||||
const onFileSelect = vi.fn();
|
||||
|
||||
render(
|
||||
<FileAttachment onFileSelect={onFileSelect} disabled={true} />
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toBeDisabled();
|
||||
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
expect(fileInput).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -1,100 +0,0 @@
|
||||
import React, { useRef } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Paperclip, X } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface FileAttachmentProps {
|
||||
onFileSelect: (file: File) => void;
|
||||
onFileRemove?: (file: File) => void;
|
||||
selectedFiles?: File[];
|
||||
disabled?: boolean;
|
||||
accept?: string;
|
||||
multiple?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function FileAttachment({
|
||||
onFileSelect,
|
||||
onFileRemove,
|
||||
selectedFiles = [],
|
||||
disabled = false,
|
||||
accept,
|
||||
multiple = false,
|
||||
className
|
||||
}: FileAttachmentProps) {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleButtonClick = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = event.target.files;
|
||||
if (files) {
|
||||
Array.from(files).forEach(file => {
|
||||
onFileSelect(file);
|
||||
});
|
||||
}
|
||||
// Reset input so the same file can be selected again
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveFile = (file: File) => {
|
||||
if (onFileRemove) {
|
||||
onFileRemove(file);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn("flex items-center gap-2", className)}>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
onChange={handleFileChange}
|
||||
accept={accept}
|
||||
multiple={multiple}
|
||||
className="hidden"
|
||||
disabled={disabled}
|
||||
/>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleButtonClick}
|
||||
disabled={disabled}
|
||||
className="h-8 w-8 p-0 rounded-full hover:bg-muted/50"
|
||||
>
|
||||
<Paperclip className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
{selectedFiles.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 max-w-48">
|
||||
{selectedFiles.map((file, index) => (
|
||||
<div
|
||||
key={`${file.name}-${index}`}
|
||||
className="flex items-center gap-1 px-2 py-1 bg-muted/50 rounded-md text-xs"
|
||||
>
|
||||
<span className="truncate max-w-24" title={file.name}>
|
||||
{file.name}
|
||||
</span>
|
||||
{onFileRemove && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleRemoveFile(file)}
|
||||
className="h-3 w-3 p-0 hover:bg-muted/70"
|
||||
>
|
||||
<X className="h-2 w-2" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useTheme } from "next-themes"
|
||||
import { Toaster as Sonner } from "sonner"
|
||||
|
||||
type ToasterProps = React.ComponentProps<typeof Sonner>
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
toastOptions={{
|
||||
classNames: {
|
||||
toast:
|
||||
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
|
||||
description: "group-[.toast]:text-muted-foreground",
|
||||
actionButton:
|
||||
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
|
||||
cancelButton:
|
||||
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
|
||||
},
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
@@ -1,23 +1,14 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export interface AIConnection {
|
||||
baseURL: string;
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
}
|
||||
|
||||
export interface AISettings {
|
||||
providers: Record<string, AIConnection>;
|
||||
recentlyUsedModels: string[];
|
||||
apiKey: string;
|
||||
baseUrl: string;
|
||||
model: string;
|
||||
}
|
||||
|
||||
export interface AISettingsContextType {
|
||||
settings: AISettings;
|
||||
updateSettings: (settings: Partial<AISettings>) => void;
|
||||
addProvider: (name: string, connection: AIConnection) => void;
|
||||
removeProvider: (name: string) => void;
|
||||
updateProvider: (name: string, connection: Partial<AIConnection>) => void;
|
||||
addRecentlyUsedModel: (modelId: string) => void;
|
||||
isConfigured: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,8 +7,6 @@ export interface AppConfig {
|
||||
theme: Theme;
|
||||
/** Selected relay URL */
|
||||
relayUrl: string;
|
||||
/** Deploy server domain (e.g., "shakespeare.wtf") */
|
||||
deployServer: string;
|
||||
}
|
||||
|
||||
export interface AppContextType {
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export interface GitCredential {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface GitSettings {
|
||||
credentials: Record<string, GitCredential>; // keyed by origin
|
||||
corsProxy: string;
|
||||
}
|
||||
|
||||
export interface GitSettingsContextType {
|
||||
settings: GitSettings;
|
||||
updateSettings: (settings: Partial<GitSettings>) => void;
|
||||
addCredential: (origin: string, credential: GitCredential) => void;
|
||||
removeCredential: (origin: string) => void;
|
||||
updateCredential: (origin: string, credential: Partial<GitCredential>) => void;
|
||||
isConfigured: boolean;
|
||||
}
|
||||
|
||||
export const GitSettingsContext = createContext<GitSettingsContextType | undefined>(undefined);
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createContext } from 'react';
|
||||
import type { JSRuntime } from '@/lib/JSRuntime';
|
||||
|
||||
export interface JSRuntimeContextType {
|
||||
runtime: JSRuntime;
|
||||
}
|
||||
|
||||
export const JSRuntimeContext = createContext<JSRuntimeContextType | undefined>(undefined);
|
||||
@@ -1,8 +0,0 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { useNWCInternal as useNWCHook } from '@/hooks/useNWC';
|
||||
import { NWCContext } from '@/hooks/useNWCContext';
|
||||
|
||||
export function NWCProvider({ children }: { children: ReactNode }) {
|
||||
const nwc = useNWCHook();
|
||||
return <NWCContext.Provider value={nwc}>{children}</NWCContext.Provider>;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
import { createContext } from 'react';
|
||||
import type { SessionManager } from '@/lib/SessionManager';
|
||||
|
||||
export const SessionManagerContext = createContext<SessionManager | null>(null);
|
||||
@@ -1,162 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||
import { useSessionSubscription } from '@/hooks/useSessionSubscription';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import type OpenAI from 'openai';
|
||||
import type { Tool } from '@/lib/tools/Tool';
|
||||
|
||||
interface UseAIChatSessionOptions {
|
||||
projectId: string;
|
||||
tools?: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
customTools?: Record<string, Tool<unknown>>;
|
||||
systemPrompt?: string;
|
||||
maxSteps?: number;
|
||||
onUpdateMetadata?: (title: string, description: string) => void;
|
||||
}
|
||||
|
||||
interface StreamingMessage {
|
||||
role: 'assistant';
|
||||
content: string;
|
||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook that provides AI chat functionality using the global session manager.
|
||||
* Sessions persist and can run in the background when switching between projects.
|
||||
*/
|
||||
export function useAIChat({
|
||||
projectId,
|
||||
tools = {},
|
||||
customTools = {},
|
||||
systemPrompt,
|
||||
maxSteps = 50,
|
||||
onUpdateMetadata
|
||||
}: UseAIChatSessionOptions) {
|
||||
const sessionManager = useSessionManager();
|
||||
const { isConfigured } = useAISettings();
|
||||
|
||||
// Split session state into individual variables for efficient updates
|
||||
const [messages, setMessages] = useState<AIMessage[]>([]);
|
||||
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
const [totalCost, setTotalCost] = useState<number>(0);
|
||||
const [lastInputTokens, setLastInputTokens] = useState<number>(0);
|
||||
|
||||
const initSession = useCallback(async () => {
|
||||
// Load or update session
|
||||
const session = await sessionManager.loadSession(projectId, tools, customTools, systemPrompt, maxSteps);
|
||||
// Initialize individual state variables from existing session
|
||||
setMessages([...session.messages]);
|
||||
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
|
||||
setIsLoading(session.isLoading);
|
||||
setTotalCost(session.totalCost || 0);
|
||||
setLastInputTokens(session.lastInputTokens || 0);
|
||||
}, [sessionManager, projectId, tools, customTools, systemPrompt, maxSteps]);
|
||||
|
||||
// Initialize session
|
||||
useEffect(() => {
|
||||
initSession();
|
||||
}, [initSession]);
|
||||
|
||||
// Subscribe to atomic session events for efficient updates
|
||||
useSessionSubscription('messageAdded', (updatedProjectId: string, message: AIMessage) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setMessages(prev => [...prev, message]);
|
||||
// Whenever an assistant message is added, it means streaming is done (until we get another streamingUpdate)
|
||||
if (message.role === 'assistant') {
|
||||
setStreamingMessage({
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
useSessionSubscription('streamingUpdate', (updatedProjectId: string, content: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setStreamingMessage({
|
||||
role: 'assistant',
|
||||
content,
|
||||
tool_calls: toolCalls
|
||||
});
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
useSessionSubscription('loadingChanged', (updatedProjectId: string, loading: boolean) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setIsLoading(loading);
|
||||
|
||||
// Clear streaming message when loading stops
|
||||
if (!loading) {
|
||||
setStreamingMessage(undefined);
|
||||
}
|
||||
|
||||
if (onUpdateMetadata && loading) {
|
||||
onUpdateMetadata('Shakespeare', `Working on ${projectId}...`);
|
||||
}
|
||||
}
|
||||
}, [projectId, onUpdateMetadata]);
|
||||
|
||||
useSessionSubscription('costUpdated', (updatedProjectId: string, cost: number) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setTotalCost(cost);
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
useSessionSubscription('contextUsageUpdated', (updatedProjectId: string, inputTokens: number) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setLastInputTokens(inputTokens);
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
// Actions
|
||||
const sendMessage = useCallback(async (content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string) => {
|
||||
await initSession();
|
||||
await sessionManager.sendMessage(projectId, content, providerModel);
|
||||
}, [projectId, sessionManager, initSession]);
|
||||
|
||||
const startGeneration = useCallback(async (providerModel: string) => {
|
||||
await initSession();
|
||||
await sessionManager.startGeneration(projectId, providerModel);
|
||||
}, [projectId, sessionManager, initSession]);
|
||||
|
||||
const stopGeneration = useCallback(() => {
|
||||
sessionManager.stopGeneration(projectId);
|
||||
}, [projectId, sessionManager]);
|
||||
|
||||
const addMessage = useCallback(async (message: AIMessage) => {
|
||||
await sessionManager.addMessage(projectId, message);
|
||||
}, [projectId, sessionManager]);
|
||||
|
||||
const startNewSession = useCallback(async () => {
|
||||
await sessionManager.startNewSession(projectId);
|
||||
|
||||
// Reset individual state variables
|
||||
setMessages([]);
|
||||
setStreamingMessage(undefined);
|
||||
setTotalCost(0);
|
||||
setLastInputTokens(0);
|
||||
}, [projectId, sessionManager]);
|
||||
|
||||
const clearMessages = useCallback(async () => {
|
||||
// Alias for startNewSession for backward compatibility
|
||||
await startNewSession();
|
||||
}, [startNewSession]);
|
||||
|
||||
return {
|
||||
messages,
|
||||
streamingMessage,
|
||||
isLoading,
|
||||
totalCost,
|
||||
lastInputTokens,
|
||||
sendMessage,
|
||||
startGeneration,
|
||||
stopGeneration,
|
||||
clearMessages,
|
||||
startNewSession,
|
||||
addMessage,
|
||||
isConfigured,
|
||||
projectId
|
||||
};
|
||||
}
|
||||
@@ -1,316 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { useAIProjectId } from './useAIProjectId';
|
||||
import { useAISettings } from './useAISettings';
|
||||
import { useCurrentUser } from './useCurrentUser';
|
||||
import { useProjectsManager } from './useProjectsManager';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import type { ProjectsManager } from '@/lib/ProjectsManager';
|
||||
|
||||
// Mock the hooks and dependencies
|
||||
vi.mock('./useAISettings');
|
||||
vi.mock('./useCurrentUser');
|
||||
vi.mock('./useProjectsManager');
|
||||
vi.mock('@/lib/ai-client');
|
||||
vi.mock('@/lib/parseProviderModel');
|
||||
|
||||
describe('useAIProjectId', () => {
|
||||
const mockUseAISettings = vi.mocked(useAISettings);
|
||||
const mockUseCurrentUser = vi.mocked(useCurrentUser);
|
||||
const mockUseProjectsManager = vi.mocked(useProjectsManager);
|
||||
const mockCreateAIClient = vi.mocked(createAIClient);
|
||||
const mockParseProviderModel = vi.mocked(parseProviderModel);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Mock fetch globally
|
||||
global.fetch = vi.fn();
|
||||
|
||||
// Mock useCurrentUser to return undefined user by default
|
||||
mockUseCurrentUser.mockReturnValue({
|
||||
user: undefined,
|
||||
users: [],
|
||||
});
|
||||
|
||||
// Mock useProjectsManager
|
||||
const mockProjectsManager = {
|
||||
getProject: vi.fn().mockResolvedValue(null),
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
// Mock parseProviderModel
|
||||
mockParseProviderModel.mockReturnValue({
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
connection: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
});
|
||||
|
||||
// Mock createAIClient
|
||||
const mockCompletion = {
|
||||
choices: [{ message: { content: 'test-project-name' } }]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn().mockResolvedValue(mockCompletion)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
});
|
||||
|
||||
it('should return not configured when AI settings are not configured', () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: {}, recentlyUsedModels: [] },
|
||||
isConfigured: false,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
expect(result.current.isConfigured).toBe(false);
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
it('should throw error when trying to generate ID without configuration', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: {}, recentlyUsedModels: [] },
|
||||
isConfigured: false,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
await expect(result.current.generateProjectId('openai/gpt-4', 'test prompt')).rejects.toThrow(
|
||||
'AI settings not configured'
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw error when prompt is empty', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
await expect(result.current.generateProjectId('openai/gpt-4', '')).rejects.toThrow(
|
||||
'Prompt cannot be empty'
|
||||
);
|
||||
});
|
||||
|
||||
it('should have configured status when providers are available', () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
expect(result.current.isConfigured).toBe(true);
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
it('should successfully generate project ID', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
|
||||
|
||||
expect(projectId).toBe('test-project-name');
|
||||
expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
});
|
||||
expect(mockCreateAIClient).toHaveBeenCalledWith(
|
||||
{ apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
|
||||
undefined
|
||||
);
|
||||
});
|
||||
|
||||
it('should retry with new names when project exists', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock multiple responses - first one exists, second one is unique
|
||||
const mockCompletion1 = {
|
||||
choices: [{ message: { content: 'existing-project' } }]
|
||||
};
|
||||
const mockCompletion2 = {
|
||||
choices: [{ message: { content: 'unique-project' } }]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn()
|
||||
.mockResolvedValueOnce(mockCompletion1)
|
||||
.mockResolvedValueOnce(mockCompletion2)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
|
||||
// Mock getProject - first call returns project (exists), second returns null (unique)
|
||||
const mockGetProject = vi.fn()
|
||||
.mockResolvedValueOnce({ id: 'existing-project', name: 'Existing Project', path: '/projects/existing-project', lastModified: new Date() })
|
||||
.mockResolvedValueOnce(null);
|
||||
|
||||
const mockProjectsManager = {
|
||||
getProject: mockGetProject,
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
|
||||
|
||||
expect(projectId).toBe('unique-project');
|
||||
expect(mockGetProject).toHaveBeenCalledTimes(2);
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'existing-project');
|
||||
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'unique-project');
|
||||
|
||||
// Should have called AI twice - once for initial name, once for retry
|
||||
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Second call should include the "already taken" message
|
||||
const mockCreate = mockOpenAI.chat.completions.create as ReturnType<typeof vi.fn>;
|
||||
const secondCallArgs = mockCreate.mock.calls[1][0];
|
||||
expect(secondCallArgs.messages).toHaveLength(3);
|
||||
expect(secondCallArgs.messages[2].content).toContain('already taken');
|
||||
});
|
||||
|
||||
it('should throw error after maximum iterations', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock AI to always return the same name
|
||||
const mockCompletion = {
|
||||
choices: [{ message: { content: 'taken-project' } }]
|
||||
};
|
||||
const mockOpenAI = {
|
||||
chat: {
|
||||
completions: {
|
||||
create: vi.fn().mockResolvedValue(mockCompletion)
|
||||
}
|
||||
}
|
||||
} as unknown as ReturnType<typeof createAIClient>;
|
||||
mockCreateAIClient.mockReturnValue(mockOpenAI);
|
||||
|
||||
// Mock getProject to always return a project (project always exists)
|
||||
const mockGetProject = vi.fn().mockResolvedValue({
|
||||
id: 'taken-project',
|
||||
name: 'Taken Project',
|
||||
path: '/projects/taken-project',
|
||||
lastModified: new Date()
|
||||
});
|
||||
|
||||
const mockProjectsManager = {
|
||||
getProject: mockGetProject,
|
||||
} as unknown as ProjectsManager;
|
||||
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
await expect(result.current.generateProjectId('openai/gpt-4', 'A social media app for developers'))
|
||||
.rejects.toThrow('Failed to generate a unique project name after 3 attempts');
|
||||
|
||||
expect(mockGetProject).toHaveBeenCalledTimes(3);
|
||||
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('should handle loading state correctly', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: {
|
||||
providers: {
|
||||
openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
},
|
||||
recentlyUsedModels: []
|
||||
},
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
addProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
updateProvider: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
|
||||
const promise = result.current.generateProjectId('openai/gpt-4', 'Test prompt');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false); // Should be false after completion
|
||||
});
|
||||
|
||||
await promise;
|
||||
});
|
||||
});
|
||||
@@ -1,107 +0,0 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
|
||||
interface UseAIProjectIdOptions {
|
||||
onError?: (error: string) => void;
|
||||
}
|
||||
|
||||
export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const { settings, isConfigured } = useAISettings();
|
||||
const { user } = useCurrentUser();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
const generateProjectId = useCallback(async (providerModel: string, prompt: string): Promise<string> => {
|
||||
if (!isConfigured) {
|
||||
throw new Error('AI settings not configured');
|
||||
}
|
||||
|
||||
if (!prompt.trim()) {
|
||||
throw new Error('Prompt cannot be empty');
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
// Initialize OpenAI client
|
||||
const { model, connection } = parseProviderModel(providerModel, settings.providers);
|
||||
const openai = createAIClient(connection, user);
|
||||
|
||||
const systemPrompt = `You are a product expert. Given the user's project description, come up with a short, unique, and memorable name for their product or brand. Generate only the name without any additional text or punctuation. The name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens. Avoid using special characters or underscores.`;
|
||||
|
||||
const messages = [
|
||||
{ role: 'system' as const, content: systemPrompt },
|
||||
{ role: 'user' as const, content: prompt }
|
||||
];
|
||||
|
||||
let iterations = 0;
|
||||
const maxIterations = 3;
|
||||
|
||||
while (iterations < maxIterations) {
|
||||
iterations++;
|
||||
|
||||
const completion = await openai.chat.completions.create({
|
||||
model,
|
||||
messages,
|
||||
temperature: 1,
|
||||
});
|
||||
|
||||
const projectName = completion.choices[0]?.message?.content?.trim();
|
||||
if (!projectName) {
|
||||
throw new Error('Failed to generate project name');
|
||||
}
|
||||
|
||||
// Convert the name into kebab-case
|
||||
const projectId = projectName
|
||||
.toLowerCase()
|
||||
.replace(/\s+/g, '-') // Replace spaces with hyphens
|
||||
.replace(/[^a-z0-9-]/g, '') // Remove invalid characters
|
||||
.replace(/-+/g, '-') // Replace multiple hyphens with a single hyphen
|
||||
.replace(/^-+|-+$/g, ''); // Trim hyphens from start and end
|
||||
|
||||
if (!projectId) {
|
||||
throw new Error('Generated project ID is empty after formatting');
|
||||
}
|
||||
|
||||
// Validate the generated ID
|
||||
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
||||
if (!validIdRegex.test(projectId)) {
|
||||
throw new Error('Generated project ID is invalid');
|
||||
}
|
||||
|
||||
// Check if project exists
|
||||
const existingProject = await projectsManager.getProject(projectId);
|
||||
if (existingProject !== null) {
|
||||
// Add user message indicating the name is already taken
|
||||
messages.push({
|
||||
role: 'user',
|
||||
content: `The name "${projectName}" (project ID: ${projectId}) is already taken. Please generate another unique name.`
|
||||
});
|
||||
continue; // Try again with updated conversation
|
||||
}
|
||||
|
||||
// If we reach here, the project ID is valid and unique
|
||||
return projectId;
|
||||
}
|
||||
|
||||
// If we've exceeded max iterations, throw an error
|
||||
throw new Error(`Failed to generate a unique project name after ${maxIterations} attempts`);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
|
||||
onError?.(errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [isConfigured, settings, onError, user, projectsManager]);
|
||||
|
||||
return {
|
||||
generateProjectId,
|
||||
isLoading,
|
||||
isConfigured
|
||||
};
|
||||
}
|
||||
@@ -25,11 +25,6 @@ export function useCurrentUser() {
|
||||
const users = useMemo(() => {
|
||||
const users: NUser[] = [];
|
||||
|
||||
// Safeguard against undefined or null logins
|
||||
if (!logins || !Array.isArray(logins)) {
|
||||
return users;
|
||||
}
|
||||
|
||||
for (const login of logins) {
|
||||
try {
|
||||
const user = loginToUser(login);
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { useGit } from './useGit';
|
||||
import { useFS } from './useFS';
|
||||
import { useGitSettings } from './useGitSettings';
|
||||
import { Git } from '@/lib/git';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
|
||||
// Mock the dependencies
|
||||
vi.mock('./useFS');
|
||||
vi.mock('./useGitSettings');
|
||||
vi.mock('@/lib/git');
|
||||
|
||||
const mockUseFS = vi.mocked(useFS);
|
||||
const mockUseGitSettings = vi.mocked(useGitSettings);
|
||||
const MockGit = vi.mocked(Git);
|
||||
|
||||
describe('useGit', () => {
|
||||
const mockFS = {} as JSRuntimeFS;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockUseFS.mockReturnValue({ fs: mockFS });
|
||||
});
|
||||
|
||||
it('creates Git instance with default CORS proxy', () => {
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {},
|
||||
corsProxy: 'https://cors.isomorphic-git.org',
|
||||
},
|
||||
updateSettings: vi.fn(),
|
||||
addCredential: vi.fn(),
|
||||
removeCredential: vi.fn(),
|
||||
updateCredential: vi.fn(),
|
||||
isConfigured: false,
|
||||
});
|
||||
|
||||
renderHook(() => useGit());
|
||||
|
||||
expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://cors.isomorphic-git.org');
|
||||
});
|
||||
|
||||
it('creates Git instance with custom CORS proxy', () => {
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {},
|
||||
corsProxy: 'https://custom-cors.example.com',
|
||||
},
|
||||
updateSettings: vi.fn(),
|
||||
addCredential: vi.fn(),
|
||||
removeCredential: vi.fn(),
|
||||
updateCredential: vi.fn(),
|
||||
isConfigured: false,
|
||||
});
|
||||
|
||||
renderHook(() => useGit());
|
||||
|
||||
expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://custom-cors.example.com');
|
||||
});
|
||||
|
||||
it('recreates Git instance when CORS proxy changes', () => {
|
||||
const { rerender } = renderHook(() => useGit());
|
||||
|
||||
// First render with default proxy
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {},
|
||||
corsProxy: 'https://cors.isomorphic-git.org',
|
||||
},
|
||||
updateSettings: vi.fn(),
|
||||
addCredential: vi.fn(),
|
||||
removeCredential: vi.fn(),
|
||||
updateCredential: vi.fn(),
|
||||
isConfigured: false,
|
||||
});
|
||||
|
||||
rerender();
|
||||
expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://cors.isomorphic-git.org');
|
||||
|
||||
// Second render with custom proxy
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {},
|
||||
corsProxy: 'https://custom-cors.example.com',
|
||||
},
|
||||
updateSettings: vi.fn(),
|
||||
addCredential: vi.fn(),
|
||||
removeCredential: vi.fn(),
|
||||
updateCredential: vi.fn(),
|
||||
isConfigured: false,
|
||||
});
|
||||
|
||||
rerender();
|
||||
expect(MockGit).toHaveBeenLastCalledWith(mockFS, 'https://custom-cors.example.com');
|
||||
});
|
||||
});
|
||||
@@ -1,19 +0,0 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Git } from '@/lib/git';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
|
||||
/**
|
||||
* Hook that provides a Git instance configured with the virtual filesystem
|
||||
* and configurable CORS proxy for GitHub/GitLab repositories.
|
||||
*/
|
||||
export function useGit() {
|
||||
const { fs } = useFS();
|
||||
const { settings } = useGitSettings();
|
||||
|
||||
const git = useMemo(() => {
|
||||
return new Git(fs, settings.corsProxy);
|
||||
}, [fs, settings.corsProxy]);
|
||||
|
||||
return git;
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useGitSettings } from './useGitSettings';
|
||||
|
||||
interface GitHubOAuthState {
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
interface GitHubTokenResponse {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
scope: string;
|
||||
}
|
||||
|
||||
export function useGitHubOAuth() {
|
||||
const [state, setState] = useState<GitHubOAuthState>({
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
const { addCredential } = useGitSettings();
|
||||
|
||||
// Check if OAuth is configured
|
||||
const isOAuthConfigured = !!(
|
||||
import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID &&
|
||||
import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET
|
||||
);
|
||||
|
||||
const initiateOAuth = useCallback(() => {
|
||||
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
|
||||
|
||||
if (!clientId) {
|
||||
setState(prev => ({ ...prev, error: 'GitHub OAuth client ID not configured' }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Generate a random state parameter for security
|
||||
const state = crypto.randomUUID();
|
||||
localStorage.setItem('github_oauth_state', state);
|
||||
|
||||
// Redirect to GitHub OAuth
|
||||
const params = new URLSearchParams({
|
||||
client_id: clientId,
|
||||
redirect_uri: window.location.origin + '/',
|
||||
scope: 'repo',
|
||||
state: state,
|
||||
});
|
||||
|
||||
window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`;
|
||||
}, []);
|
||||
|
||||
const handleCallback = useCallback(async (code: string, state: string) => {
|
||||
setState(prev => ({ ...prev, isLoading: true, error: null }));
|
||||
|
||||
try {
|
||||
// Verify state parameter
|
||||
const storedState = localStorage.getItem('github_oauth_state');
|
||||
if (!storedState || storedState !== state) {
|
||||
throw new Error('Invalid OAuth state parameter');
|
||||
}
|
||||
|
||||
// Clean up stored state
|
||||
localStorage.removeItem('github_oauth_state');
|
||||
|
||||
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
|
||||
const clientSecret = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET;
|
||||
|
||||
if (!clientId || !clientSecret) {
|
||||
throw new Error('GitHub OAuth credentials not configured');
|
||||
}
|
||||
|
||||
// Exchange code for access token
|
||||
const tokenResponse = await fetch('https://corsproxy.io/?url=https://github.com/login/oauth/access_token', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
client_id: clientId,
|
||||
client_secret: clientSecret,
|
||||
code: code,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!tokenResponse.ok) {
|
||||
throw new Error(`GitHub OAuth token exchange failed: ${tokenResponse.statusText}`);
|
||||
}
|
||||
|
||||
const tokenData: GitHubTokenResponse = await tokenResponse.json();
|
||||
|
||||
if (!tokenData.access_token) {
|
||||
throw new Error('No access token received from GitHub');
|
||||
}
|
||||
|
||||
// Get user info to verify the token works
|
||||
const userResponse = await fetch('https://corsproxy.io/?url=https://api.github.com/user', {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${tokenData.access_token}`,
|
||||
'Accept': 'application/vnd.github.v3+json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!userResponse.ok) {
|
||||
throw new Error(`Failed to verify GitHub token: ${userResponse.statusText}`);
|
||||
}
|
||||
|
||||
const userData = await userResponse.json();
|
||||
|
||||
// Store the credentials
|
||||
addCredential('https://github.com', {
|
||||
username: userData.login || 'git',
|
||||
password: tokenData.access_token,
|
||||
});
|
||||
|
||||
setState(prev => ({ ...prev, isLoading: false }));
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('GitHub OAuth error:', error);
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
isLoading: false,
|
||||
error: error instanceof Error ? error.message : 'OAuth authentication failed'
|
||||
}));
|
||||
return false;
|
||||
}
|
||||
}, [addCredential]);
|
||||
|
||||
return {
|
||||
...state,
|
||||
isOAuthConfigured,
|
||||
initiateOAuth,
|
||||
handleCallback,
|
||||
};
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import { useContext } from 'react';
|
||||
import { GitSettingsContext, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
|
||||
|
||||
/**
|
||||
* Hook to access and update Git settings
|
||||
* @returns Git settings context with settings and update methods
|
||||
*/
|
||||
export function useGitSettings(): GitSettingsContextType {
|
||||
const context = useContext(GitSettingsContext);
|
||||
if (!context) {
|
||||
throw new Error('useGitSettings must be used within GitSettingsProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -1,278 +0,0 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useGit } from './useGit';
|
||||
|
||||
interface GitFileChange {
|
||||
filepath: string;
|
||||
status: 'modified' | 'added' | 'deleted' | 'untracked' | 'staged';
|
||||
}
|
||||
|
||||
interface GitCommit {
|
||||
oid: string;
|
||||
message: string;
|
||||
author: {
|
||||
name: string;
|
||||
email: string;
|
||||
timestamp: number;
|
||||
};
|
||||
committer: {
|
||||
name: string;
|
||||
email: string;
|
||||
timestamp: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface GitRemote {
|
||||
name: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface GitStatus {
|
||||
hasUncommittedChanges: boolean;
|
||||
changedFiles: GitFileChange[];
|
||||
isGitRepo: boolean;
|
||||
currentBranch: string | null;
|
||||
latestCommit: GitCommit | null;
|
||||
remotes: GitRemote[];
|
||||
totalCommits: number;
|
||||
branches: string[];
|
||||
ahead: number;
|
||||
behind: number;
|
||||
}
|
||||
|
||||
export function useGitStatus(projectId: string | null) {
|
||||
const git = useGit();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['git-status', projectId],
|
||||
queryFn: async (): Promise<GitStatus> => {
|
||||
if (!projectId) {
|
||||
return {
|
||||
hasUncommittedChanges: false,
|
||||
changedFiles: [],
|
||||
isGitRepo: false,
|
||||
currentBranch: null,
|
||||
latestCommit: null,
|
||||
remotes: [],
|
||||
totalCommits: 0,
|
||||
branches: [],
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const cwd = `/projects/${projectId}`;
|
||||
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await git.findRoot({ filepath: cwd });
|
||||
} catch {
|
||||
return {
|
||||
hasUncommittedChanges: false,
|
||||
changedFiles: [],
|
||||
isGitRepo: false,
|
||||
currentBranch: null,
|
||||
latestCommit: null,
|
||||
remotes: [],
|
||||
totalCommits: 0,
|
||||
branches: [],
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Get current branch
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
const branch = await git.currentBranch({
|
||||
dir: cwd,
|
||||
fullname: false,
|
||||
});
|
||||
currentBranch = branch || null;
|
||||
} catch (error) {
|
||||
console.warn('Could not get current branch:', error);
|
||||
}
|
||||
|
||||
// Get all branches
|
||||
const branches: string[] = [];
|
||||
try {
|
||||
const allBranches = await git.listBranches({
|
||||
dir: cwd,
|
||||
});
|
||||
branches.push(...allBranches);
|
||||
} catch (error) {
|
||||
console.warn('Could not list branches:', error);
|
||||
}
|
||||
|
||||
// Get latest commit
|
||||
let latestCommit: GitCommit | null = null;
|
||||
let totalCommits = 0;
|
||||
try {
|
||||
const commits = await git.log({
|
||||
dir: cwd,
|
||||
depth: 1,
|
||||
});
|
||||
|
||||
if (commits.length > 0) {
|
||||
const commit = commits[0];
|
||||
latestCommit = {
|
||||
oid: commit.oid,
|
||||
message: commit.commit.message,
|
||||
author: {
|
||||
name: commit.commit.author.name,
|
||||
email: commit.commit.author.email,
|
||||
timestamp: commit.commit.author.timestamp,
|
||||
},
|
||||
committer: {
|
||||
name: commit.commit.committer.name,
|
||||
email: commit.commit.committer.email,
|
||||
timestamp: commit.commit.committer.timestamp,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Get total commit count
|
||||
const allCommits = await git.log({
|
||||
dir: cwd,
|
||||
});
|
||||
totalCommits = allCommits.length;
|
||||
} catch (error) {
|
||||
console.warn('Could not get commit history:', error);
|
||||
}
|
||||
|
||||
// Get remotes
|
||||
const remotes: GitRemote[] = [];
|
||||
try {
|
||||
const remoteNames = await git.listRemotes({
|
||||
dir: cwd,
|
||||
});
|
||||
|
||||
for (const remote of remoteNames) {
|
||||
remotes.push({
|
||||
name: remote.remote,
|
||||
url: remote.url,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Could not get remotes:', error);
|
||||
}
|
||||
|
||||
// Get git status to see what files have changed
|
||||
const statusMatrix = await git.statusMatrix({
|
||||
dir: cwd,
|
||||
});
|
||||
|
||||
// Parse file changes with more detailed status
|
||||
const changedFiles: GitFileChange[] = [];
|
||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||
let status: GitFileChange['status'];
|
||||
|
||||
if (headStatus === 0 && workdirStatus === 2 && stageStatus === 0) {
|
||||
status = 'untracked';
|
||||
} else if (headStatus === 0 && workdirStatus === 2 && stageStatus === 2) {
|
||||
status = 'added';
|
||||
} else if (headStatus === 1 && workdirStatus === 2 && stageStatus === 2) {
|
||||
status = 'staged';
|
||||
} else if (headStatus === 1 && workdirStatus === 2 && stageStatus === 1) {
|
||||
status = 'modified';
|
||||
} else if (headStatus === 1 && workdirStatus === 0 && stageStatus === 0) {
|
||||
status = 'deleted';
|
||||
} else if (headStatus !== workdirStatus || workdirStatus !== stageStatus) {
|
||||
status = 'modified';
|
||||
} else {
|
||||
continue; // No changes
|
||||
}
|
||||
|
||||
changedFiles.push({
|
||||
filepath,
|
||||
status,
|
||||
});
|
||||
}
|
||||
|
||||
// Calculate ahead/behind
|
||||
let ahead = 0;
|
||||
let behind = 0;
|
||||
try {
|
||||
if (currentBranch && remotes.length > 0) {
|
||||
const remote = remotes[0]; // Use first remote (usually 'origin')
|
||||
const remoteBranchName = `${remote.name}/${currentBranch}`;
|
||||
|
||||
try {
|
||||
// Try to get the remote branch reference
|
||||
const remoteRef = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: remoteBranchName,
|
||||
});
|
||||
|
||||
const localRef = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: currentBranch,
|
||||
});
|
||||
|
||||
if (remoteRef && localRef && remoteRef !== localRef) {
|
||||
// Get commits between local and remote
|
||||
const localCommits = await git.log({
|
||||
dir: cwd,
|
||||
ref: currentBranch,
|
||||
});
|
||||
|
||||
const remoteCommits = await git.log({
|
||||
dir: cwd,
|
||||
ref: remoteBranchName,
|
||||
});
|
||||
|
||||
// Find commits that are in local but not in remote (ahead)
|
||||
const remoteCommitOids = new Set(remoteCommits.map(c => c.oid));
|
||||
const localOnlyCommits = localCommits.filter(c => !remoteCommitOids.has(c.oid));
|
||||
ahead = localOnlyCommits.length;
|
||||
|
||||
// Find commits that are in remote but not in local (behind)
|
||||
const localCommitOids = new Set(localCommits.map(c => c.oid));
|
||||
const remoteOnlyCommits = remoteCommits.filter(c => !localCommitOids.has(c.oid));
|
||||
behind = remoteOnlyCommits.length;
|
||||
}
|
||||
} catch {
|
||||
// Remote branch might not exist or other issues
|
||||
// If we can't find remote branch, assume we're ahead if we have commits
|
||||
if (totalCommits > 0) {
|
||||
ahead = totalCommits;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Could not calculate ahead/behind:', err);
|
||||
}
|
||||
|
||||
return {
|
||||
hasUncommittedChanges: changedFiles.length > 0,
|
||||
changedFiles,
|
||||
isGitRepo: true,
|
||||
currentBranch,
|
||||
latestCommit,
|
||||
remotes,
|
||||
totalCommits,
|
||||
branches,
|
||||
ahead,
|
||||
behind,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking git status:', error);
|
||||
return {
|
||||
hasUncommittedChanges: false,
|
||||
changedFiles: [],
|
||||
isGitRepo: false,
|
||||
currentBranch: null,
|
||||
latestCommit: null,
|
||||
remotes: [],
|
||||
totalCommits: 0,
|
||||
branches: [],
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
};
|
||||
}
|
||||
},
|
||||
enabled: !!projectId,
|
||||
refetchInterval: 5000, // Check every 5 seconds
|
||||
staleTime: 2000, // Consider data stale after 2 seconds
|
||||
});
|
||||
}
|
||||
+12
-12
@@ -1,19 +1,19 @@
|
||||
import { useEffect, useState } from "react"
|
||||
import * as React from "react"
|
||||
|
||||
const MOBILE_BREAKPOINT = 768;
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
|
||||
export function useIsMobile(): boolean {
|
||||
const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
export function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||
|
||||
useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
||||
React.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
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useContext } from 'react';
|
||||
import { JSRuntimeContext, type JSRuntimeContextType } from '@/contexts/JSRuntimeContext';
|
||||
|
||||
/**
|
||||
* Hook to access the JavaScript runtime
|
||||
* @returns JSRuntime context with runtime instance
|
||||
*/
|
||||
export function useJSRuntime(): JSRuntimeContextType {
|
||||
const context = useContext(JSRuntimeContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useJSRuntime must be used within a JSRuntimeProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
/**
|
||||
* Generic hook for managing localStorage state using React Query
|
||||
* Generic hook for managing localStorage state
|
||||
*/
|
||||
export function useLocalStorage<T>(
|
||||
key: string,
|
||||
@@ -11,13 +10,11 @@ export function useLocalStorage<T>(
|
||||
serialize: (value: T) => string;
|
||||
deserialize: (value: string) => T;
|
||||
}
|
||||
): readonly [T, (value: T | ((prev: T) => T)) => void] {
|
||||
) {
|
||||
const serialize = serializer?.serialize || JSON.stringify;
|
||||
const deserialize = serializer?.deserialize || JSON.parse;
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const queryFn = () => {
|
||||
const [state, setState] = useState<T>(() => {
|
||||
try {
|
||||
const item = localStorage.getItem(key);
|
||||
return item ? deserialize(item) : defaultValue;
|
||||
@@ -25,22 +22,13 @@ export function useLocalStorage<T>(
|
||||
console.warn(`Failed to load ${key} from localStorage:`, error);
|
||||
return defaultValue;
|
||||
}
|
||||
};
|
||||
|
||||
const { data: state } = useQuery({
|
||||
queryKey: ['localStorage', key],
|
||||
queryFn,
|
||||
initialData: queryFn,
|
||||
staleTime: Infinity, // localStorage data doesn't become stale
|
||||
gcTime: Infinity, // Keep in cache indefinitely
|
||||
});
|
||||
|
||||
const setValue = (value: T | ((prev: T) => T)) => {
|
||||
try {
|
||||
const currentValue = state ?? defaultValue;
|
||||
const valueToStore = value instanceof Function ? value(currentValue) : value;
|
||||
const valueToStore = value instanceof Function ? value(state) : value;
|
||||
setState(valueToStore);
|
||||
localStorage.setItem(key, serialize(valueToStore));
|
||||
queryClient.setQueryData(['localStorage', key], valueToStore);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to save ${key} to localStorage:`, error);
|
||||
}
|
||||
@@ -51,8 +39,7 @@ export function useLocalStorage<T>(
|
||||
const handleStorageChange = (e: StorageEvent) => {
|
||||
if (e.key === key && e.newValue !== null) {
|
||||
try {
|
||||
const newValue = deserialize(e.newValue);
|
||||
queryClient.setQueryData(['localStorage', key], newValue);
|
||||
setState(deserialize(e.newValue));
|
||||
} catch (error) {
|
||||
console.warn(`Failed to sync ${key} from localStorage:`, error);
|
||||
}
|
||||
@@ -61,7 +48,7 @@ export function useLocalStorage<T>(
|
||||
|
||||
window.addEventListener('storage', handleStorageChange);
|
||||
return () => window.removeEventListener('storage', handleStorageChange);
|
||||
}, [key, deserialize, queryClient]);
|
||||
}, [key, deserialize]);
|
||||
|
||||
return [state, setValue] as const;
|
||||
}
|
||||
@@ -1,221 +0,0 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { LN } from '@getalby/sdk';
|
||||
|
||||
export interface NWCConnection {
|
||||
connectionString: string;
|
||||
alias?: string;
|
||||
isConnected: boolean;
|
||||
client?: LN;
|
||||
}
|
||||
|
||||
export interface NWCInfo {
|
||||
alias?: string;
|
||||
color?: string;
|
||||
pubkey?: string;
|
||||
network?: string;
|
||||
methods?: string[];
|
||||
notifications?: string[];
|
||||
}
|
||||
|
||||
export function useNWCInternal() {
|
||||
const { toast } = useToast();
|
||||
const [connections, setConnections] = useLocalStorage<NWCConnection[]>('nwc-connections', []);
|
||||
const [activeConnection, setActiveConnection] = useLocalStorage<string | null>('nwc-active-connection', null);
|
||||
const [connectionInfo, setConnectionInfo] = useState<Record<string, NWCInfo>>({});
|
||||
|
||||
// Add new connection
|
||||
const addConnection = async (uri: string, alias?: string): Promise<boolean> => {
|
||||
const parseNWCUri = (uri: string): { connectionString: string } | null => {
|
||||
try {
|
||||
if (!uri.startsWith('nostr+walletconnect://') && !uri.startsWith('nostrwalletconnect://')) {
|
||||
console.error('Invalid NWC URI protocol:', { protocol: uri.split('://')[0] });
|
||||
return null;
|
||||
}
|
||||
return { connectionString: uri };
|
||||
} catch (error) {
|
||||
console.error('Failed to parse NWC URI:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const parsed = parseNWCUri(uri);
|
||||
if (!parsed) {
|
||||
toast({
|
||||
title: 'Invalid NWC URI',
|
||||
description: 'Please check the connection string and try again.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
const existingConnection = connections.find(c => c.connectionString === parsed.connectionString);
|
||||
if (existingConnection) {
|
||||
toast({
|
||||
title: 'Connection already exists',
|
||||
description: 'This wallet is already connected.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
let timeoutId: NodeJS.Timeout | undefined;
|
||||
const testPromise = new Promise((resolve, reject) => {
|
||||
try {
|
||||
const client = new LN(parsed.connectionString);
|
||||
resolve(client);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
timeoutId = setTimeout(() => reject(new Error('Connection test timeout')), 10000);
|
||||
});
|
||||
|
||||
try {
|
||||
await Promise.race([testPromise, timeoutPromise]) as LN;
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
} catch (error) {
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const connection: NWCConnection = {
|
||||
connectionString: parsed.connectionString,
|
||||
alias: alias || 'NWC Wallet',
|
||||
isConnected: true,
|
||||
};
|
||||
|
||||
setConnectionInfo(prev => ({
|
||||
...prev,
|
||||
[parsed.connectionString]: {
|
||||
alias: connection.alias,
|
||||
methods: ['pay_invoice'],
|
||||
},
|
||||
}));
|
||||
|
||||
const newConnections = [...connections, connection];
|
||||
setConnections(newConnections);
|
||||
|
||||
if (connections.length === 0 || !activeConnection)
|
||||
setActiveConnection(parsed.connectionString);
|
||||
|
||||
toast({
|
||||
title: 'Wallet connected',
|
||||
description: `Successfully connected to ${connection.alias}.`,
|
||||
});
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('NWC connection failed:', error);
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
|
||||
toast({
|
||||
title: 'Connection failed',
|
||||
description: `Could not connect to the wallet: ${errorMessage}`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Remove connection
|
||||
const removeConnection = (connectionString: string) => {
|
||||
const filtered = connections.filter(c => c.connectionString !== connectionString);
|
||||
setConnections(filtered);
|
||||
|
||||
if (activeConnection === connectionString) {
|
||||
const newActive = filtered.length > 0 ? filtered[0].connectionString : null;
|
||||
setActiveConnection(newActive);
|
||||
}
|
||||
|
||||
setConnectionInfo(prev => {
|
||||
const newInfo = { ...prev };
|
||||
delete newInfo[connectionString];
|
||||
return newInfo;
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Wallet disconnected',
|
||||
description: 'The wallet connection has been removed.',
|
||||
});
|
||||
};
|
||||
|
||||
// Get active connection
|
||||
const getActiveConnection = useCallback((): NWCConnection | null => {
|
||||
if (!activeConnection && connections.length > 0) {
|
||||
setActiveConnection(connections[0].connectionString);
|
||||
return connections[0];
|
||||
}
|
||||
|
||||
if (!activeConnection) return null;
|
||||
|
||||
const found = connections.find(c => c.connectionString === activeConnection);
|
||||
return found || null;
|
||||
}, [activeConnection, connections, setActiveConnection]);
|
||||
|
||||
// Send payment using the SDK
|
||||
const sendPayment = useCallback(async (
|
||||
connection: NWCConnection,
|
||||
invoice: string
|
||||
): Promise<{ preimage: string }> => {
|
||||
if (!connection.connectionString) {
|
||||
throw new Error('Invalid connection: missing connection string');
|
||||
}
|
||||
|
||||
let client: LN;
|
||||
try {
|
||||
client = new LN(connection.connectionString);
|
||||
} catch (error) {
|
||||
console.error('Failed to create NWC client:', error);
|
||||
throw new Error(`Failed to create NWC client: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
|
||||
try {
|
||||
let timeoutId: NodeJS.Timeout | undefined;
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
timeoutId = setTimeout(() => reject(new Error('Payment timeout after 15 seconds')), 15000);
|
||||
});
|
||||
|
||||
const paymentPromise = client.pay(invoice);
|
||||
|
||||
try {
|
||||
const response = await Promise.race([paymentPromise, timeoutPromise]) as { preimage: string };
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
return response;
|
||||
} catch (error) {
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('NWC payment failed:', error);
|
||||
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('timeout')) {
|
||||
throw new Error('Payment timed out. Please try again.');
|
||||
} else if (error.message.includes('insufficient')) {
|
||||
throw new Error('Insufficient balance in connected wallet.');
|
||||
} else if (error.message.includes('invalid')) {
|
||||
throw new Error('Invalid invoice or connection. Please check your wallet.');
|
||||
} else {
|
||||
throw new Error(`Payment failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('Payment failed with unknown error');
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
connections,
|
||||
activeConnection,
|
||||
connectionInfo,
|
||||
addConnection,
|
||||
removeConnection,
|
||||
setActiveConnection,
|
||||
getActiveConnection,
|
||||
sendPayment,
|
||||
};
|
||||
}
|
||||
Loaded 100 of 274 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user