mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
296
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f1b3e6b7e | ||
|
|
749d173cf4 | ||
|
|
a7b45b5068 | ||
|
|
d26d1051f1 | ||
|
|
d99a9e1c46 | ||
|
|
8be2ef7b22 | ||
|
|
75a0d637ce | ||
|
|
a84ba7385b | ||
|
|
2fdd9e6a49 | ||
|
|
67a77419df | ||
|
|
4676738a14 | ||
|
|
444dfbc5dd | ||
|
|
5d075e02ab | ||
|
|
6edc623c13 | ||
|
|
027cd819f8 | ||
|
|
ef55e80c35 | ||
|
|
3666aac2a1 | ||
|
|
f58f75ae8b | ||
|
|
22885e0978 | ||
|
|
a988238bb4 | ||
|
|
11197139f9 | ||
|
|
9ccad00888 | ||
|
|
32ff6570cf | ||
|
|
80bb72ef79 | ||
|
|
e45f167d2b | ||
|
|
7e755916c0 | ||
|
|
5915b96d98 | ||
|
|
b327607be3 | ||
|
|
e23b5031ee | ||
|
|
104a08c75a | ||
|
|
ddc23e3800 | ||
|
|
a1959369c5 | ||
|
|
6c4c1dab3b | ||
|
|
45edc6a777 | ||
|
|
2cde8b5105 | ||
|
|
d2a84fa00d | ||
|
|
1915e6044f | ||
|
|
4f7525bf0a | ||
|
|
cb3fb88a75 | ||
|
|
7d0cd03da9 | ||
|
|
dd3946d6de | ||
|
|
24e70712d8 | ||
|
|
6a11b5ea05 | ||
|
|
85ac92db96 | ||
|
|
4cbce6be63 | ||
|
|
87de7c79ff | ||
|
|
a96e028bb5 | ||
|
|
b9e5a2f3c2 | ||
|
|
f6b3b3a5ea | ||
|
|
88ba38d21a | ||
|
|
f8b7ad4689 | ||
|
|
f4a3953d4d | ||
|
|
16cb47832e | ||
|
|
6839f50a48 | ||
|
|
638b2dd1b8 | ||
|
|
93c23cb2b6 | ||
|
|
a69d96533e | ||
|
|
87db8d7101 | ||
|
|
47820048dc | ||
|
|
26945e3b84 | ||
|
|
38ffe02185 | ||
|
|
0192d307c5 | ||
|
|
fa495f876e | ||
|
|
c6caeed31d | ||
|
|
9941078da1 | ||
|
|
ef67b9b166 | ||
|
|
a0d3c4fbd0 | ||
|
|
55cc3c61d5 | ||
|
|
2acc0191ad | ||
|
|
5a43a1ea61 | ||
|
|
48d357549a | ||
|
|
4cbff7c8dd | ||
|
|
fa1a8781dc | ||
|
|
fefa97cb21 | ||
|
|
55ea749c31 | ||
|
|
1120d6e574 | ||
|
|
8fe872e015 | ||
|
|
88def1264d | ||
|
|
e0241a3250 | ||
|
|
fc9bd3ef02 | ||
|
|
69a49af983 | ||
|
|
0a17b575d0 | ||
|
|
dff3497ba6 | ||
|
|
02cc069ff8 | ||
|
|
b7081ea64a | ||
|
|
eb7071789c | ||
|
|
e4e37c01f4 | ||
|
|
6c5ac6adee | ||
|
|
a752b22138 | ||
|
|
db64cb3047 | ||
|
|
f9d398091b | ||
|
|
ffa65212bc | ||
|
|
f9febcce1e | ||
|
|
71f3a08325 | ||
|
|
1e13ed8f36 | ||
|
|
758e3ab261 | ||
|
|
0ee88f5968 | ||
|
|
d8e46732b3 | ||
|
|
5691954dc8 | ||
|
|
03e867c33a | ||
|
|
e5087e5ad6 | ||
|
|
74c0be9d5d | ||
|
|
1c54a889ce | ||
|
|
41f4a53b1f | ||
|
|
44dfd25a84 | ||
|
|
dc0144a477 | ||
|
|
b60d11186b | ||
|
|
f5036b8b56 | ||
|
|
243853b6c8 | ||
|
|
d314655a7b | ||
|
|
b3f5219062 | ||
|
|
4216d9864c | ||
|
|
85ee7c40f5 | ||
|
|
b863009c47 | ||
|
|
2743d42b55 | ||
|
|
6542b55823 | ||
|
|
d1b5a26839 | ||
|
|
393eef282b | ||
|
|
118fb6cf2f | ||
|
|
adcd87cb64 | ||
|
|
54c89f03c7 | ||
|
|
dd726c1766 | ||
|
|
3b332c6ade | ||
|
|
4e68ee57d6 | ||
|
|
9987cfca6d | ||
|
|
84cf0ff23a | ||
|
|
0138c3a17f | ||
|
|
a606c1237d | ||
|
|
6d001daf8a | ||
|
|
e2c4da5300 | ||
|
|
b2afa2bc3e | ||
|
|
739b0d50e0 | ||
|
|
0139d7c2dd | ||
|
|
6407523df4 | ||
|
|
932db9107d | ||
|
|
1d5b3b1ca7 | ||
|
|
598447b89f | ||
|
|
e13c3c0077 | ||
|
|
6a74120ddd | ||
|
|
5ef848b45e | ||
|
|
83fec3f6d6 | ||
|
|
0fa4d3a199 | ||
|
|
39652a85ca | ||
|
|
2f2957435a | ||
|
|
1804436565 | ||
|
|
2cc61bd6df | ||
|
|
4546098df7 | ||
|
|
e288660d3e | ||
|
|
e599f76787 | ||
|
|
a9c1922e51 | ||
|
|
1f87c68c4f | ||
|
|
cfb7242e2b | ||
|
|
6a12e1f4f4 | ||
|
|
9eb068c2ad | ||
|
|
977c40f85b | ||
|
|
f8ed988042 | ||
|
|
ad92e655cc | ||
|
|
53c8f16dec | ||
|
|
a74db2cdd0 | ||
|
|
7428a23c8d | ||
|
|
f2e34ed9af | ||
|
|
12433320b6 | ||
|
|
d2fd29ed86 | ||
|
|
bc0eec3839 | ||
|
|
ddc59a74ff | ||
|
|
5f054a9a4a | ||
|
|
21df7fe3dd | ||
|
|
99764670ef | ||
|
|
2948a3b4d4 | ||
|
|
46affcbdcc | ||
|
|
dcdee5b875 | ||
|
|
c1427d45dc | ||
|
|
fba7d680f2 | ||
|
|
fe72549e2d | ||
|
|
5c8d9b3aaa | ||
|
|
2dc22cc40b | ||
|
|
1fadd80adc | ||
|
|
49f535827c | ||
|
|
2df6887591 | ||
|
|
1c28587bdf | ||
|
|
56f2715f79 | ||
|
|
1424663b43 | ||
|
|
91ae86bbde | ||
|
|
0dbe51fd88 | ||
|
|
1ffd2d06cf | ||
|
|
db807d52d8 | ||
|
|
95eea4230d | ||
|
|
80400ef159 | ||
|
|
a8796e6197 | ||
|
|
028d22c7c9 | ||
|
|
9fe97c0b61 | ||
|
|
f7fc018ae2 | ||
|
|
8174db459f | ||
|
|
45dd2507fa | ||
|
|
0b19ac4f09 | ||
|
|
5460a2e766 | ||
|
|
9d32a13971 | ||
|
|
706ec3642e | ||
|
|
3465b97c13 | ||
|
|
c9d1509481 | ||
|
|
31fc4d61c5 | ||
|
|
956dfb5099 | ||
|
|
8b8958f7c8 | ||
|
|
b99c20c7f7 | ||
|
|
b82b4539d9 | ||
|
|
43190b7a35 | ||
|
|
e98fc617a1 | ||
|
|
46a89a67d9 | ||
|
|
c84acfdcaa | ||
|
|
b79b7f04db | ||
|
|
6739fea580 | ||
|
|
34db584772 | ||
|
|
05d18ae788 | ||
|
|
ac8fe4108a | ||
|
|
3eae1bda4a | ||
|
|
4fdb881075 | ||
|
|
3eb156e983 | ||
|
|
a915b9121f | ||
|
|
91313764aa | ||
|
|
6a7ec8413a | ||
|
|
4f49c8efb4 | ||
|
|
bd97dda7ab | ||
|
|
ab879c9023 | ||
|
|
062e2e41bc | ||
|
|
a415a7c5bc | ||
|
|
f5010518e2 | ||
|
|
aa1f456a36 | ||
|
|
117cc2ee1e | ||
|
|
50c9645e3a | ||
|
|
8224589dbe | ||
|
|
11f670871c | ||
|
|
581f6406dc | ||
|
|
ba02d7bf33 | ||
|
|
d72729f379 | ||
|
|
8eeea7b188 | ||
|
|
95dead2c79 | ||
|
|
afa21c7507 | ||
|
|
d82df433de | ||
|
|
5a55c09a67 | ||
|
|
c14419640a | ||
|
|
94cdf2c9a4 | ||
|
|
1405d0a760 | ||
|
|
a957338afd | ||
|
|
d1cdcb0fd9 | ||
|
|
94d62b254d | ||
|
|
112a042bc5 | ||
|
|
c53233d5d8 | ||
|
|
5d7ae56e2d | ||
|
|
0689f1cbf7 | ||
|
|
91130cbd89 | ||
|
|
8b9d87b5d5 | ||
|
|
ead95a4d03 | ||
|
|
fcc305788d | ||
|
|
9c2f4f9eb6 | ||
|
|
6dfedaa97e | ||
|
|
8ed98a9d73 | ||
|
|
0377761fc6 | ||
|
|
fbdcd01b38 | ||
|
|
07807ea1bf | ||
|
|
31b26e40a8 | ||
|
|
42b697643f | ||
|
|
97038ec809 | ||
|
|
e644d7127c | ||
|
|
3d3d35be40 | ||
|
|
d4dc0d54c4 | ||
|
|
246b23167b | ||
|
|
88c6b80484 | ||
|
|
8fc7c0bb60 | ||
|
|
155707436c | ||
|
|
b59dbc9ba8 | ||
|
|
2f8055abfa | ||
|
|
763cf87749 | ||
|
|
97b334da8e | ||
|
|
8af3618793 | ||
|
|
8c7c2694c4 | ||
|
|
f3d2f40c13 | ||
|
|
2347770d46 | ||
|
|
a5f89d20ae | ||
|
|
eb17feadea | ||
|
|
7a252e0037 | ||
|
|
7b9310c6ac | ||
|
|
e012c74b41 | ||
|
|
6cccf6e2d9 | ||
|
|
45038c9b96 | ||
|
|
b74259f5f7 | ||
|
|
7322b0ff41 | ||
|
|
af09c9aa79 | ||
|
|
179a59c58c | ||
|
|
5a456c9957 | ||
|
|
7478be317c | ||
|
|
54a2b807d8 | ||
|
|
a8e6d51f9f | ||
|
|
27dec36a3f | ||
|
|
6e03767f62 | ||
|
|
421c3f2b2b | ||
|
|
77a1a17c06 |
No files matched your search
@@ -33,7 +33,7 @@ This architecture allows Shakespeare to provide a full development environment e
|
||||
|
||||
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 (virtual in browser, real OS shell in Electron)
|
||||
- **ShellTool**: Execute shell commands in the virtual browser environment
|
||||
- **TextEditorViewTool**: Read file contents and view directory structures
|
||||
- **TextEditorWriteTool**: Create or overwrite files with new content
|
||||
- **TextEditorStrReplaceTool**: Replace strings in files
|
||||
@@ -41,7 +41,6 @@ Shakespeare provides AI agents with specialized tools for project development (n
|
||||
- **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
|
||||
@@ -54,7 +53,6 @@ Shakespeare provides AI agents with specialized tools for project development (n
|
||||
|
||||
#### Shell Commands
|
||||
|
||||
**In Browser Mode:**
|
||||
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:**
|
||||
@@ -63,16 +61,6 @@ Shakespeare provides a comprehensive set of shell commands that are JavaScript r
|
||||
- **System Commands**: `echo`, `which`, `wc`, `head`, `tail`
|
||||
- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, etc.
|
||||
|
||||
**In Electron Mode:**
|
||||
When running in Electron, the ShellTool automatically uses the **real OS terminal** instead of the virtual terminal. This means:
|
||||
- **All OS commands available**: Not limited to built-in commands
|
||||
- **Native shell features**: Pipes, redirection, environment variables work natively
|
||||
- **Package managers**: `npm`, `yarn`, `pnpm` work directly
|
||||
- **Build tools**: `vite`, `webpack`, `tsc`, etc. available
|
||||
- **System utilities**: Full access to OS commands
|
||||
|
||||
The ShellTool detects the environment automatically and uses the appropriate execution method.
|
||||
|
||||
#### Security
|
||||
|
||||
AI filesystem access through tools (including shell commands via ShellTool) has path restrictions to ensure safe operation:
|
||||
@@ -90,7 +78,7 @@ Shakespeare provides full Git functionality in the browser using `isomorphic-git
|
||||
- **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)
|
||||
- **useGitFetch Hook**: Automatic remote fetch with change detection (updates every 60 seconds, shows toast notifications)
|
||||
- **useGitFetch Hook**: Automatic remote fetch
|
||||
- **ProjectsManager**: Handles project creation, Git initialization, and template cloning
|
||||
|
||||
#### Core Features
|
||||
@@ -219,7 +207,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `useGitSettings`: Manage Git credentials and repository settings
|
||||
- `useSessionManager`: Access session management for AI chat sessions
|
||||
- `useGitStatus`: Real-time Git repository status monitoring
|
||||
- `useGitFetch`: Automatic remote fetch with change detection and toast notifications
|
||||
- `useGitFetch`: Automatic remote fetch
|
||||
- `useProjects`: Project management and CRUD operations
|
||||
- `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import)
|
||||
- `useTheme`: Theme management
|
||||
@@ -240,7 +228,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- 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`, `DeployProjectTool`
|
||||
- Project tools: `BuildProjectTool`
|
||||
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
|
||||
- Git integration: `GitCommitTool`
|
||||
- Shell access: `ShellTool`
|
||||
@@ -1300,6 +1288,7 @@ When users specify color schemes:
|
||||
- Follow shadcn/ui patterns for component variants
|
||||
- Implement responsive design with Tailwind breakpoints
|
||||
- Add hover and focus states for interactive elements
|
||||
- **Use `hover:bg-muted` for hover states on clickable cards/buttons** - provides subtle, accessible feedback without overpowering the design (avoid `hover:bg-accent` or `hover:bg-secondary` which can be too strong)
|
||||
|
||||
## Writing Tests vs Running Tests
|
||||
|
||||
|
||||
+42
-2
@@ -15,6 +15,7 @@ The OAuth system consists of three main components:
|
||||
- **GitHub** - Git repository hosting (with PKCE support)
|
||||
- **Netlify** - Static site deployment
|
||||
- **Vercel** - Static site deployment
|
||||
- **OpenRouter** - AI model routing (with PKCE support)
|
||||
|
||||
## File Structure
|
||||
|
||||
@@ -24,11 +25,13 @@ src/
|
||||
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
|
||||
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
|
||||
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
|
||||
│ └── useVercelOAuth.ts # Vercel-specific configuration
|
||||
│ ├── useVercelOAuth.ts # Vercel-specific configuration
|
||||
│ └── useOpenRouterOAuth.ts # OpenRouter-specific configuration
|
||||
├── pages/
|
||||
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
|
||||
│ ├── NetlifyOAuth.tsx # Netlify OAuth callback page
|
||||
│ └── VercelOAuth.tsx # Vercel OAuth callback page
|
||||
│ ├── VercelOAuth.tsx # Vercel OAuth callback page
|
||||
│ └── OpenRouterOAuth.tsx # OpenRouter OAuth callback page
|
||||
└── AppRouter.tsx # Routes for OAuth callbacks
|
||||
```
|
||||
|
||||
@@ -190,6 +193,7 @@ const config: OAuthConfig = {
|
||||
- ✅ GitHub - Supports PKCE (enabled)
|
||||
- ❌ Netlify - Doesn't support PKCE (disabled)
|
||||
- ❌ Vercel - Doesn't support PKCE (disabled)
|
||||
- ✅ OpenRouter - Requires PKCE (enabled)
|
||||
|
||||
### Scope Parameter
|
||||
|
||||
@@ -199,6 +203,42 @@ The `scope` parameter is optional in the OAuth configuration. Some providers (li
|
||||
- ✅ GitHub - Uses scopes (e.g., `repo workflow`)
|
||||
- ❌ Netlify - No scope parameter (permissions set in app settings)
|
||||
- ✅ Vercel - Uses scopes (e.g., `deployments:write projects:read`)
|
||||
- ❌ OpenRouter - No scope parameter (uses PKCE for authorization)
|
||||
|
||||
### OpenRouter Custom OAuth Implementation
|
||||
|
||||
OpenRouter uses a custom OAuth flow that differs from the standard OAuth 2.0 specification. Instead of using the generic `useOAuth` hook, it has a dedicated `useOpenRouterOAuth` hook with the following key differences:
|
||||
|
||||
1. **No Client Credentials**: OpenRouter doesn't require client ID or client secret - it uses PKCE only
|
||||
2. **Authorization URL**: Uses `callback_url` parameter instead of `redirect_uri`
|
||||
3. **Token Exchange**: Posts to `/api/v1/auth/keys` with a simplified request body
|
||||
4. **Response Format**: Returns `{ key }` instead of standard `{ access_token }`
|
||||
5. **PKCE Required**: Must use PKCE with S256 code challenge method
|
||||
6. **No User Info**: Doesn't provide a user info endpoint after authentication
|
||||
7. **No Environment Variables**: No configuration needed - works out of the box
|
||||
|
||||
**Authorization URL Format:**
|
||||
```
|
||||
https://openrouter.ai/auth?callback_url=<REDIRECT_URI>&code_challenge=<CHALLENGE>&code_challenge_method=S256
|
||||
```
|
||||
|
||||
**Token Exchange Request:**
|
||||
```json
|
||||
{
|
||||
"code": "<CODE_FROM_QUERY_PARAM>",
|
||||
"code_verifier": "<CODE_VERIFIER>",
|
||||
"code_challenge_method": "S256"
|
||||
}
|
||||
```
|
||||
|
||||
**Token Exchange Response:**
|
||||
```json
|
||||
{
|
||||
"key": "sk-or-v1-..."
|
||||
}
|
||||
```
|
||||
|
||||
This custom implementation is fully contained in `useOpenRouterOAuth.ts` and doesn't rely on the generic OAuth hook. Unlike other providers, OpenRouter's OAuth doesn't require any environment variables or application registration - it works immediately without configuration.
|
||||
|
||||
## Adding a New OAuth Provider
|
||||
|
||||
|
||||
+1
-5
@@ -174,9 +174,6 @@ When called, it:
|
||||
Plugins are stored in the configured plugins directory:
|
||||
|
||||
- **Browser**: `/plugins` (IndexedDB via LightningFS)
|
||||
- **Electron (Windows)**: `~/AppData/Local/shakespeare/plugins`
|
||||
- **Electron (macOS)**: `~/Library/Application Support/shakespeare/plugins`
|
||||
- **Electron (Linux)**: `~/.config/shakespeare/plugins`
|
||||
|
||||
## System Prompt Integration
|
||||
|
||||
@@ -250,8 +247,7 @@ When designing web interfaces, follow these principles:
|
||||
|
||||
Configure in **Settings > System > Filesystem Paths**:
|
||||
|
||||
- Default browser: `/plugins`
|
||||
- Default Electron: OS-specific (see Storage section)
|
||||
- Default: `/plugins`
|
||||
- Custom: Any absolute path
|
||||
|
||||
Changes take effect immediately.
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
package.json
|
||||
package-lock.json
|
||||
README.md
|
||||
node_modules/
|
||||
dist/
|
||||
@@ -1,582 +0,0 @@
|
||||
# Shakespeare Electron - Complete Guide
|
||||
|
||||
This guide provides comprehensive documentation for developing, building, and troubleshooting the Shakespeare Electron desktop application.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Filesystem Architecture](#filesystem-architecture)
|
||||
2. [Terminal Integration](#terminal-integration)
|
||||
3. [Development Workflow](#development-workflow)
|
||||
4. [Building for Distribution](#building-for-distribution)
|
||||
5. [Troubleshooting](#troubleshooting)
|
||||
|
||||
---
|
||||
|
||||
## Filesystem Architecture
|
||||
|
||||
### Overview
|
||||
|
||||
The Electron version uses your local OS filesystem at `~/shakespeare` instead of IndexedDB, providing direct file access and unlimited storage.
|
||||
|
||||
### Path Resolution
|
||||
|
||||
All paths are relative to `~/shakespeare`:
|
||||
- `/projects/my-app/` → `~/shakespeare/projects/my-app/`
|
||||
- `/tmp/upload.txt` → `~/shakespeare/tmp/upload.txt`
|
||||
- `/config/ai.json` → `~/shakespeare/config/ai.json`
|
||||
|
||||
### Implementation
|
||||
|
||||
**Automatic Adapter Selection** (`src/App.tsx`):
|
||||
```typescript
|
||||
const fs = window.electron?.isElectron
|
||||
? new NodeFSAdapter() // Real filesystem
|
||||
: new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
|
||||
```
|
||||
|
||||
**IPC Communication Flow:**
|
||||
1. **Renderer** (`NodeFSAdapter.ts`) - Calls `window.electron.fs.*` methods
|
||||
2. **Preload** (`preload.js`) - Exposes API via `contextBridge`
|
||||
3. **Main** (`main.js`) - Handles IPC with `ipcMain.handle()`, performs filesystem operations
|
||||
|
||||
### Supported Operations
|
||||
|
||||
All standard filesystem operations are supported:
|
||||
- **Files**: `readFile`, `writeFile`, `unlink`, `rename`
|
||||
- **Directories**: `readdir`, `mkdir`, `rmdir`
|
||||
- **Metadata**: `stat`, `lstat`
|
||||
- **Symlinks**: `readlink`, `symlink`
|
||||
|
||||
### Benefits
|
||||
|
||||
✅ **No storage limits** - Only limited by disk space
|
||||
✅ **Direct access** - Use any editor, file manager, or Git client
|
||||
✅ **Easy backup** - Standard backup tools work
|
||||
✅ **Better performance** - Faster for large projects
|
||||
✅ **Data portability** - Copy projects between machines
|
||||
|
||||
### Data Migration
|
||||
|
||||
**Browser to Electron:**
|
||||
1. Export project as ZIP from browser
|
||||
2. Import ZIP in Electron version
|
||||
|
||||
**Electron to Browser:**
|
||||
1. Export project as ZIP from Electron
|
||||
2. Import ZIP in browser version
|
||||
|
||||
---
|
||||
|
||||
## Terminal Integration
|
||||
|
||||
### Overview
|
||||
|
||||
The Electron version uses the **real OS terminal** instead of the virtual terminal, providing access to all system commands.
|
||||
|
||||
### Architecture
|
||||
|
||||
**ShellTool Detection** (`src/lib/tools/ShellTool.ts`):
|
||||
```typescript
|
||||
if (window.electron?.shell) {
|
||||
// Use real OS shell
|
||||
const result = await window.electron.shell.exec(command, workingDir);
|
||||
} else {
|
||||
// Use virtual command system
|
||||
const result = await executeCommand(command, workingDir, fs);
|
||||
}
|
||||
```
|
||||
|
||||
**Shell Execution** (`electron/main.js`):
|
||||
- Uses `child_process.spawn()` to execute commands
|
||||
- Windows: Uses `cmd.exe`
|
||||
- macOS/Linux: Uses `/bin/sh`
|
||||
- Executes in project directory: `~/shakespeare/projects/{projectId}`
|
||||
|
||||
### Features
|
||||
|
||||
**All OS Commands Available:**
|
||||
```bash
|
||||
# Package managers
|
||||
$ npm install
|
||||
$ yarn add lodash
|
||||
$ pnpm update
|
||||
|
||||
# Build tools
|
||||
$ vite build
|
||||
$ webpack --config webpack.config.js
|
||||
$ tsc --noEmit
|
||||
|
||||
# Git operations
|
||||
$ git commit -m "Update"
|
||||
$ git push origin main
|
||||
|
||||
# System utilities
|
||||
$ grep -r "TODO" src/
|
||||
$ curl https://api.example.com
|
||||
$ python script.py
|
||||
```
|
||||
|
||||
**Native Shell Features:**
|
||||
- Pipes: `ls | grep ".ts$"`
|
||||
- Redirection: `echo "test" > file.txt`
|
||||
- Environment variables: `$PATH`, `$HOME`
|
||||
- Command chaining: `npm install && npm run build`
|
||||
|
||||
### ANSI Code Stripping
|
||||
|
||||
Output from shell commands is cleaned for AI consumption:
|
||||
- Color codes removed (e.g., `\u001b[31m`)
|
||||
- Cursor control sequences stripped
|
||||
- Text formatting removed (bold, italic)
|
||||
- Newlines preserved
|
||||
|
||||
**Example:**
|
||||
```
|
||||
Input: \u001b[1m\u001b[32madded 142 packages\u001b[39m\u001b[22m in 3s
|
||||
Output: added 142 packages in 3s
|
||||
```
|
||||
|
||||
Terminal UI still shows colored output for users.
|
||||
|
||||
### Platform Support
|
||||
|
||||
| Platform | Shell | Notes |
|
||||
|----------|-------|-------|
|
||||
| macOS | `/bin/sh` | All Unix commands available |
|
||||
| Linux | `/bin/sh` | Standard Linux utilities |
|
||||
| Windows | `cmd.exe` | Windows commands, consider Git Bash for Unix tools |
|
||||
|
||||
### Security
|
||||
|
||||
- Commands run with user permissions (no sudo/elevation)
|
||||
- Working directory sandboxed to `~/shakespeare`
|
||||
- Environment variables inherited from Electron process
|
||||
|
||||
---
|
||||
|
||||
## Development Workflow
|
||||
|
||||
### Running in Development Mode
|
||||
|
||||
```bash
|
||||
npm run electron:dev
|
||||
```
|
||||
|
||||
This will:
|
||||
1. Start Vite dev server on http://localhost:5173
|
||||
2. Wait for server to be ready
|
||||
3. Launch Electron with hot reload
|
||||
4. Open DevTools automatically
|
||||
|
||||
### Testing Shell Execution
|
||||
|
||||
Use the provided test script to verify shell functionality:
|
||||
|
||||
```bash
|
||||
# Start Electron in dev mode
|
||||
npm run electron:dev
|
||||
|
||||
# Open DevTools (View > Toggle Developer Tools)
|
||||
# Paste contents of electron/test-terminal.js into console
|
||||
```
|
||||
|
||||
The test script verifies:
|
||||
- Basic command execution
|
||||
- File listing
|
||||
- Node.js version check
|
||||
- Error handling
|
||||
- Working directory
|
||||
|
||||
### Debugging
|
||||
|
||||
**Renderer Process:**
|
||||
- DevTools open automatically in dev mode
|
||||
- Or press `Cmd+Option+I` (macOS) / `Ctrl+Shift+I` (Windows/Linux)
|
||||
|
||||
**Main Process:**
|
||||
```bash
|
||||
# Enable verbose logging
|
||||
ELECTRON_ENABLE_LOGGING=1 npm run electron:dev
|
||||
```
|
||||
|
||||
**Check Configuration:**
|
||||
```bash
|
||||
node electron/test-config.js
|
||||
```
|
||||
|
||||
### File Watching
|
||||
|
||||
In development mode:
|
||||
- Vite provides hot module replacement
|
||||
- Changes to React components reload instantly
|
||||
- Electron process restarts on main.js changes (via `nodemon` in the script)
|
||||
|
||||
---
|
||||
|
||||
## Building for Distribution
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 18+ installed
|
||||
- All dependencies installed: `npm install`
|
||||
- Web build completed: `npm run build`
|
||||
|
||||
### Build Commands
|
||||
|
||||
**Current Platform:**
|
||||
```bash
|
||||
npm run electron:build
|
||||
```
|
||||
|
||||
**Specific Platforms:**
|
||||
```bash
|
||||
npm run electron:build:mac # macOS (DMG + ZIP)
|
||||
npm run electron:build:win # Windows (NSIS + Portable)
|
||||
npm run electron:build:linux # Linux (AppImage, DEB, RPM)
|
||||
npm run electron:build:all # All platforms
|
||||
```
|
||||
|
||||
### Build Output
|
||||
|
||||
```
|
||||
electron-dist/
|
||||
├── mac/
|
||||
│ ├── Shakespeare.app # macOS application bundle
|
||||
│ ├── Shakespeare.dmg # DMG installer
|
||||
│ └── Shakespeare-mac.zip # ZIP archive
|
||||
├── win-unpacked/
|
||||
│ └── Shakespeare.exe # Windows executable
|
||||
├── Shakespeare Setup.exe # NSIS installer
|
||||
├── Shakespeare Portable.exe # Portable executable
|
||||
├── shakespeare-*.AppImage # Linux AppImage
|
||||
├── shakespeare_*.deb # Debian package
|
||||
└── shakespeare-*.rpm # RPM package
|
||||
```
|
||||
|
||||
### Platform-Specific Notes
|
||||
|
||||
**macOS:**
|
||||
- Builds for Intel (x64) and Apple Silicon (arm64)
|
||||
- Code signing optional for development
|
||||
- For distribution: Requires Apple Developer account
|
||||
|
||||
**Windows:**
|
||||
- Builds for x64 and ARM64
|
||||
- No code signing required for development
|
||||
- For distribution: EV certificate recommended for SmartScreen
|
||||
|
||||
**Linux:**
|
||||
- Builds for x64 and ARM64
|
||||
- AppImage requires FUSE: `sudo apt-get install fuse`
|
||||
- DEB/RPM packages can be installed with package managers
|
||||
|
||||
### Cross-Platform Limitations
|
||||
|
||||
- **macOS builds require macOS** (for code signing)
|
||||
- Windows/Linux can be built from any platform
|
||||
- Use GitHub Actions or CI/CD for multi-platform builds
|
||||
|
||||
### Code Signing
|
||||
|
||||
**Development (Disable Signing):**
|
||||
|
||||
Edit `electron/builder.config.js`:
|
||||
```javascript
|
||||
mac: {
|
||||
identity: null, // Disable code signing
|
||||
}
|
||||
```
|
||||
|
||||
**Production (macOS):**
|
||||
1. Obtain Apple Developer account
|
||||
2. Create certificates in Xcode
|
||||
3. Configure signing in builder.config.js
|
||||
4. See: https://www.electron.build/code-signing
|
||||
|
||||
**Production (Windows):**
|
||||
1. Obtain EV code signing certificate
|
||||
2. Configure in builder.config.js
|
||||
3. Builds reputation with SmartScreen over time
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Development Issues
|
||||
|
||||
#### Port 5173 Already in Use
|
||||
|
||||
**Solution:**
|
||||
```bash
|
||||
# Find and kill the process
|
||||
lsof -i :5173 # macOS/Linux
|
||||
netstat -ano | findstr :5173 # Windows
|
||||
|
||||
# Or change the port in vite.config.ts
|
||||
export default defineConfig({
|
||||
server: { port: 5174 },
|
||||
});
|
||||
```
|
||||
|
||||
#### Blank Screen on Launch
|
||||
|
||||
**Browser Mode:**
|
||||
1. Check Vite server is running: http://localhost:5173
|
||||
2. Check Electron console for errors
|
||||
3. Verify URL in `electron/main.js` matches Vite server
|
||||
4. Clear cache: Delete `node_modules/.vite`
|
||||
|
||||
**Production Build:**
|
||||
1. Ensure `base: './'` is set in `vite.config.ts`
|
||||
2. Check `dist/` directory contains all files
|
||||
3. Look for "Failed to load resource" errors in console
|
||||
4. Verify file:// protocol is used in loadURL
|
||||
|
||||
#### Assets Fail to Load: "net::ERR_FILE_NOT_FOUND"
|
||||
|
||||
**Problem:** CSS/JS fail to load with `file:///assets/npm/...` errors
|
||||
|
||||
**Solution:** Add to `vite.config.ts`:
|
||||
```typescript
|
||||
export default defineConfig(() => ({
|
||||
base: './', // Required for Electron
|
||||
// ... rest of config
|
||||
}))
|
||||
```
|
||||
|
||||
Then rebuild: `npm run build`
|
||||
|
||||
#### 404 Error: Page Not Found
|
||||
|
||||
**Problem:** App shows "404: Oops! Page not found" on launch
|
||||
|
||||
**Solution:** Verify `HashRouter` is used in Electron.
|
||||
|
||||
Check `src/AppRouter.tsx`:
|
||||
```typescript
|
||||
const Router = window.electron?.isElectron ? HashRouter : BrowserRouter;
|
||||
```
|
||||
|
||||
Rebuild: `npm run build && npm run electron:build`
|
||||
|
||||
#### Service Worker Errors
|
||||
|
||||
**Solution:** Service workers don't work with `file://` protocol.
|
||||
|
||||
Check `src/main.tsx`:
|
||||
```typescript
|
||||
if ('serviceWorker' in navigator && !window.electron?.isElectron) {
|
||||
// Only register in web environment
|
||||
}
|
||||
```
|
||||
|
||||
#### CSP Font Errors
|
||||
|
||||
**Solution:** Update CSP in `index.html`:
|
||||
```html
|
||||
<meta http-equiv="content-security-policy"
|
||||
content="... font-src 'self' data:; ...">
|
||||
```
|
||||
|
||||
#### Broken SVG Images
|
||||
|
||||
**Problem:** Logo/SVG files show as broken
|
||||
|
||||
**Solution:** Import SVG files properly:
|
||||
```typescript
|
||||
// ❌ Wrong
|
||||
<img src="/shakespeare.svg" alt="Logo" />
|
||||
|
||||
// ✅ Correct
|
||||
import logo from '/shakespeare.svg?url';
|
||||
<img src={logo} alt="Logo" />
|
||||
```
|
||||
|
||||
#### Preload Script ESM Errors
|
||||
|
||||
**Solution:** Requires `sandbox: false` in webPreferences.
|
||||
|
||||
Check `electron/main.js`:
|
||||
```javascript
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.js'),
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true, // Still enabled
|
||||
sandbox: false, // Disabled for ESM
|
||||
webSecurity: true,
|
||||
}
|
||||
```
|
||||
|
||||
### Build Issues
|
||||
|
||||
#### Build Fails with "Cannot find module"
|
||||
|
||||
**Solutions:**
|
||||
1. Install dependencies: `npm install`
|
||||
2. Clear and reinstall: `rm -rf node_modules package-lock.json && npm install`
|
||||
3. Build web first: `npm run build`
|
||||
4. Verify `dist/` exists
|
||||
5. Check config: `node electron/test-config.js`
|
||||
|
||||
#### Icons Not Appearing
|
||||
|
||||
**Solution:** Should work automatically with `public/shakespeare-512x512.png`.
|
||||
|
||||
If not:
|
||||
1. Verify PNG exists
|
||||
2. Check build output for icon errors
|
||||
3. Try: `npm run electron:icons` (requires ImageMagick)
|
||||
4. Check paths in `electron/builder.config.js`
|
||||
|
||||
#### Code Signing Errors (macOS)
|
||||
|
||||
**Development:** Disable signing:
|
||||
```javascript
|
||||
mac: {
|
||||
identity: null,
|
||||
}
|
||||
```
|
||||
|
||||
**Production:** Requires Apple Developer account and certificates.
|
||||
|
||||
#### App Won't Launch After Build
|
||||
|
||||
**Solutions:**
|
||||
1. Check console/terminal for errors
|
||||
2. Try unpacked version first
|
||||
3. macOS: Check Security & Privacy settings
|
||||
4. Windows: Check Windows Defender logs
|
||||
5. Verify `dist/` contains valid files
|
||||
|
||||
### Runtime Issues
|
||||
|
||||
#### App Crashes on Startup
|
||||
|
||||
**Solutions:**
|
||||
1. Check crash logs:
|
||||
- macOS: `~/Library/Logs/Shakespeare/`
|
||||
- Windows: `%APPDATA%\Shakespeare\logs\`
|
||||
- Linux: `~/.config/Shakespeare/logs/`
|
||||
2. Run from terminal to see errors
|
||||
3. Test web build in browser first
|
||||
|
||||
#### Shell Execution Error: "spawn /bin/sh ENOENT"
|
||||
|
||||
**Problem:** Terminal commands fail with spawn error
|
||||
|
||||
**Root Cause:** Working directory doesn't exist
|
||||
|
||||
**Solution:** Should be fixed - main.js creates directories automatically.
|
||||
|
||||
**Debug:**
|
||||
1. Open DevTools
|
||||
2. Check console for "Shell exec in directory: ..."
|
||||
3. Verify directory exists: `ls -la ~/shakespeare/projects/`
|
||||
4. Manually create if needed: `mkdir -p ~/shakespeare/projects`
|
||||
|
||||
#### External Links Not Opening
|
||||
|
||||
**Solution:** Should open in default browser automatically.
|
||||
|
||||
Check `electron/main.js` has:
|
||||
```javascript
|
||||
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
|
||||
shell.openExternal(url);
|
||||
return { action: 'deny' };
|
||||
});
|
||||
```
|
||||
|
||||
### Platform-Specific Issues
|
||||
|
||||
#### macOS: "App is damaged and can't be opened"
|
||||
|
||||
**Solutions:**
|
||||
1. Development: `xattr -cr /path/to/Shakespeare.app`
|
||||
2. Distribution: Requires code signing
|
||||
3. Users: Right-click → Open (instead of double-click)
|
||||
|
||||
#### Windows: "Windows protected your PC"
|
||||
|
||||
**Solutions:**
|
||||
1. Testing: Click "More info" → "Run anyway"
|
||||
2. Distribution: Requires EV code signing
|
||||
3. Build reputation over time
|
||||
|
||||
#### Linux: "Permission denied"
|
||||
|
||||
**Solutions:**
|
||||
1. Make executable: `chmod +x Shakespeare*.AppImage`
|
||||
2. Install FUSE: `sudo apt-get install fuse`
|
||||
3. Try DEB/RPM package instead
|
||||
|
||||
### Performance Issues
|
||||
|
||||
#### App Feels Slow
|
||||
|
||||
**Solutions:**
|
||||
1. Close DevTools
|
||||
2. Check system resources
|
||||
3. Use production build
|
||||
4. Disable hardware acceleration in `main.js`:
|
||||
```javascript
|
||||
app.disableHardwareAcceleration();
|
||||
```
|
||||
|
||||
#### High Memory Usage
|
||||
|
||||
**Solutions:**
|
||||
1. Normal for Chromium-based apps
|
||||
2. Close unused projects
|
||||
3. Restart app periodically
|
||||
4. Check for memory leaks in web code
|
||||
|
||||
---
|
||||
|
||||
## Getting Help
|
||||
|
||||
If issues persist:
|
||||
|
||||
1. **Check existing issues:** https://gitlab.com/soapbox-pub/shakespeare/-/issues
|
||||
2. **Create new issue** with:
|
||||
- OS and version
|
||||
- Electron version: `npm list electron`
|
||||
- Steps to reproduce
|
||||
- Error messages/logs
|
||||
- Screenshots
|
||||
3. **Community support:** Check project README for links
|
||||
|
||||
## Useful Commands
|
||||
|
||||
**Complete rebuild:**
|
||||
```bash
|
||||
rm -rf node_modules dist electron-dist package-lock.json
|
||||
npm install
|
||||
npm run build
|
||||
npm run electron:build
|
||||
```
|
||||
|
||||
**Check versions:**
|
||||
```bash
|
||||
npm list electron
|
||||
node --version
|
||||
npm --version
|
||||
```
|
||||
|
||||
**Verbose logging:**
|
||||
```bash
|
||||
ELECTRON_ENABLE_LOGGING=1 npm run electron:dev
|
||||
```
|
||||
|
||||
**Check build contents:**
|
||||
```bash
|
||||
npm run electron:build -- --dir
|
||||
ls -la electron-dist/[platform]-unpacked/
|
||||
```
|
||||
|
||||
## Additional Resources
|
||||
|
||||
- [Electron Documentation](https://www.electronjs.org/docs)
|
||||
- [electron-builder Documentation](https://www.electron.build/)
|
||||
- [Electron Security](https://www.electronjs.org/docs/latest/tutorial/security)
|
||||
- [Debugging Electron](https://www.electronjs.org/docs/latest/tutorial/debugging-main-process)
|
||||
- [Shakespeare Main Docs](../README.md)
|
||||
@@ -1,22 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
import { spawn } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
import electron from 'electron';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const appPath = join(__dirname, '..');
|
||||
|
||||
const child = spawn(electron, [appPath], {
|
||||
stdio: 'inherit',
|
||||
windowsHide: false,
|
||||
});
|
||||
|
||||
child.on('close', code => process.exit(code ?? 0));
|
||||
child.on('error', err => {
|
||||
console.error('Failed to launch Electron:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
process.on('SIGINT', () => child.kill('SIGINT'));
|
||||
process.on('SIGTERM', () => child.kill('SIGTERM'));
|
||||
Vendored
-99
@@ -1,99 +0,0 @@
|
||||
/**
|
||||
* TypeScript definitions for the Electron API exposed to the renderer process.
|
||||
*
|
||||
* Add this to your tsconfig.json include array to use these types:
|
||||
* "include": ["src", "electron/electron.d.ts"]
|
||||
*/
|
||||
|
||||
interface DirectoryEntry {
|
||||
name: string;
|
||||
isDirectory: boolean;
|
||||
isFile: boolean;
|
||||
}
|
||||
|
||||
interface StatResult {
|
||||
isDirectory: boolean;
|
||||
isFile: boolean;
|
||||
isBlockDevice: boolean;
|
||||
isCharacterDevice: boolean;
|
||||
isSymbolicLink: boolean;
|
||||
isFIFO: boolean;
|
||||
isSocket: boolean;
|
||||
size: number;
|
||||
mtimeMs: number;
|
||||
ctimeMs: number;
|
||||
atimeMs: number;
|
||||
// Timestamps (serialized as numbers for IPC)
|
||||
mtime: number;
|
||||
ctime: number;
|
||||
atime: number;
|
||||
}
|
||||
|
||||
interface ElectronFSAPI {
|
||||
readFile(path: string, encoding?: string): Promise<string | number[]>;
|
||||
writeFile(path: string, data: string | number[], encoding?: string): Promise<void>;
|
||||
readdir(path: string, withFileTypes?: boolean): Promise<string[] | DirectoryEntry[]>;
|
||||
mkdir(path: string, recursive?: boolean): Promise<void>;
|
||||
stat(path: string): Promise<StatResult>;
|
||||
lstat(path: string): Promise<StatResult>;
|
||||
unlink(path: string): Promise<void>;
|
||||
rmdir(path: string): Promise<void>;
|
||||
rename(oldPath: string, newPath: string): Promise<void>;
|
||||
readlink(path: string): Promise<string>;
|
||||
symlink(target: string, path: string): Promise<void>;
|
||||
}
|
||||
|
||||
interface ShellExecResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
exitCode: number;
|
||||
}
|
||||
|
||||
interface ElectronShellAPI {
|
||||
/**
|
||||
* Execute a shell command on the host OS.
|
||||
* @param command - The command to execute
|
||||
* @param cwd - Working directory (relative to ~/shakespeare)
|
||||
* @returns Promise with stdout, stderr, and exit code
|
||||
*/
|
||||
exec(command: string, cwd?: string): Promise<ShellExecResult>;
|
||||
}
|
||||
|
||||
interface ElectronAPI {
|
||||
/**
|
||||
* Get the user's home directory path.
|
||||
*/
|
||||
homedir: string;
|
||||
|
||||
/**
|
||||
* Get the current platform.
|
||||
* @returns 'darwin' | 'win32' | 'linux'
|
||||
*/
|
||||
platform(): Promise<string>;
|
||||
|
||||
/**
|
||||
* Get the application version from package.json.
|
||||
* @returns Version string (e.g., "1.0.0")
|
||||
*/
|
||||
version(): Promise<string>;
|
||||
|
||||
/**
|
||||
* Filesystem API for accessing the local OS filesystem.
|
||||
* All paths are relative to ~/shakespeare directory.
|
||||
*/
|
||||
fs: ElectronFSAPI;
|
||||
|
||||
/**
|
||||
* Shell API for executing real shell commands on the host OS.
|
||||
* All paths in commands are relative to ~/shakespeare directory.
|
||||
*/
|
||||
shell: ElectronShellAPI;
|
||||
}
|
||||
|
||||
interface Window {
|
||||
/**
|
||||
* Electron API exposed via preload script.
|
||||
* Only available when running in Electron.
|
||||
*/
|
||||
electron?: ElectronAPI;
|
||||
}
|
||||
@@ -1,532 +0,0 @@
|
||||
import { app, BrowserWindow, ipcMain, shell, Menu, protocol } from 'electron';
|
||||
import { spawn } from 'child_process';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import fs from 'fs/promises';
|
||||
import os from 'os';
|
||||
|
||||
// ESM equivalent of __dirname
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
let mainWindow;
|
||||
|
||||
function createWindow() {
|
||||
// Remove the default menu (File, Edit, View, etc.)
|
||||
Menu.setApplicationMenu(null);
|
||||
|
||||
// Create the browser window.
|
||||
mainWindow = new BrowserWindow({
|
||||
width: 1400,
|
||||
height: 900,
|
||||
minWidth: 800,
|
||||
minHeight: 600,
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.js'),
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true,
|
||||
sandbox: false, // Disabled to support ESM in preload
|
||||
webSecurity: true,
|
||||
},
|
||||
icon: path.join(__dirname, 'dist/shakespeare-512x512.png'),
|
||||
title: 'Shakespeare',
|
||||
backgroundColor: '#ffffff',
|
||||
});
|
||||
|
||||
// Enable DevTools keyboard shortcut (Ctrl+Shift+I / Cmd+Option+I)
|
||||
mainWindow.webContents.on('before-input-event', (event, input) => {
|
||||
// Check for Ctrl+Shift+I (Windows/Linux) or Cmd+Option+I (Mac)
|
||||
if (input.control && input.shift && input.key.toLowerCase() === 'i') {
|
||||
mainWindow.webContents.toggleDevTools();
|
||||
event.preventDefault();
|
||||
}
|
||||
// Also support F12
|
||||
if (input.key === 'F12') {
|
||||
mainWindow.webContents.toggleDevTools();
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
// Load the app
|
||||
if (process.env.ELECTRON_DEV) {
|
||||
// Development mode - load from Vite dev server
|
||||
console.log('Loading from Vite dev server: http://localhost:5173');
|
||||
mainWindow.loadURL('http://localhost:5173');
|
||||
mainWindow.webContents.openDevTools();
|
||||
} else {
|
||||
// Production mode - load from custom protocol
|
||||
// This allows absolute paths like /shakespeare.svg to work naturally
|
||||
console.log('Loading from app:// protocol: app://./index.html');
|
||||
mainWindow.loadURL('app://./index.html');
|
||||
}
|
||||
|
||||
// Log any load errors
|
||||
mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
|
||||
console.error('Failed to load:', validatedURL, errorCode, errorDescription);
|
||||
});
|
||||
|
||||
// Log successful load
|
||||
mainWindow.webContents.on('did-finish-load', () => {
|
||||
console.log('Successfully loaded app');
|
||||
});
|
||||
|
||||
// Handle window close
|
||||
mainWindow.on('closed', () => {
|
||||
mainWindow = null;
|
||||
});
|
||||
}
|
||||
|
||||
// Register custom protocol scheme before app is ready (required for privileges)
|
||||
if (!process.env.ELECTRON_DEV) {
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: 'app',
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: false,
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
// This method will be called when Electron has finished
|
||||
// initialization and is ready to create browser windows.
|
||||
app.whenReady().then(async () => {
|
||||
// Register the app:// protocol to serve files from dist/
|
||||
// This allows absolute paths (/) to work naturally without base: './'
|
||||
if (!process.env.ELECTRON_DEV) {
|
||||
protocol.registerFileProtocol('app', (request, callback) => {
|
||||
// Remove 'app://' prefix and normalize path
|
||||
let filePath = request.url.replace('app://', '');
|
||||
|
||||
// Remove trailing slashes
|
||||
filePath = filePath.replace(/\/+$/, '');
|
||||
|
||||
// Handle root path
|
||||
if (filePath === '' || filePath === '/') {
|
||||
filePath = 'index.html';
|
||||
}
|
||||
|
||||
// Remove leading slash if present
|
||||
if (filePath.startsWith('/')) {
|
||||
filePath = filePath.substring(1);
|
||||
}
|
||||
|
||||
// Resolve to dist directory
|
||||
const fullPath = path.join(__dirname, 'dist', filePath);
|
||||
|
||||
console.log('Protocol handler:', request.url, '->', fullPath);
|
||||
callback({ path: fullPath });
|
||||
});
|
||||
}
|
||||
|
||||
createWindow();
|
||||
|
||||
app.on('activate', () => {
|
||||
// On macOS it's common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Quit when all windows are closed, except on macOS.
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
// Handle app-level events
|
||||
app.on('web-contents-created', (event, contents) => {
|
||||
// Security: Prevent navigation to external sites
|
||||
contents.on('will-navigate', (event, navigationUrl) => {
|
||||
const parsedUrl = new URL(navigationUrl);
|
||||
|
||||
// Allow navigation within the app
|
||||
if (parsedUrl.origin === 'http://localhost:5173' ||
|
||||
parsedUrl.protocol === 'file:') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Block all other navigation
|
||||
event.preventDefault();
|
||||
});
|
||||
|
||||
// Security: Prevent opening new windows
|
||||
contents.setWindowOpenHandler(({ url }) => {
|
||||
// Open external links in the default browser
|
||||
shell.openExternal(url);
|
||||
return { action: 'deny' };
|
||||
});
|
||||
});
|
||||
|
||||
// IPC handlers can be added here if needed for future Electron-specific features
|
||||
// For example: file system access, native dialogs, etc.
|
||||
|
||||
// Example: Handle getting app version
|
||||
ipcMain.handle('get-app-version', () => {
|
||||
return app.getVersion();
|
||||
});
|
||||
|
||||
// Example: Handle getting platform
|
||||
ipcMain.handle('get-platform', () => {
|
||||
return process.platform;
|
||||
});
|
||||
|
||||
// Helper function to expand tilde (~) in paths
|
||||
function expandTilde(filepath) {
|
||||
if (filepath.startsWith('~/') || filepath === '~') {
|
||||
return path.join(os.homedir(), filepath.slice(1));
|
||||
}
|
||||
return filepath;
|
||||
}
|
||||
|
||||
// Filesystem IPC handlers
|
||||
ipcMain.handle('fs:readFile', async (event, filePath, encoding) => {
|
||||
if (!filePath) {
|
||||
const err = new Error('Failed to read file: path is required');
|
||||
err.code = 'EINVAL';
|
||||
// Don't log - empty paths are expected from isomorphic-git's ref resolution
|
||||
throw err;
|
||||
}
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
const data = await fs.readFile(fullPath, encoding ? { encoding } : undefined);
|
||||
// If no encoding, convert Buffer to array for IPC serialization
|
||||
return encoding ? data : Array.from(data);
|
||||
} catch (error) {
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
// Serialize the error code as a regular property so it survives IPC
|
||||
const err = new Error(`Failed to read file ${filePath}: ${error.message}`);
|
||||
// Copy enumerable properties including code
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
// Don't log ENOENT errors - these are expected for git packed objects and missing refs
|
||||
// Only log unexpected errors
|
||||
if (error.code !== 'ENOENT' && error.code !== 'EINVAL') {
|
||||
console.error(err);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:writeFile', async (event, filePath, data, encoding) => {
|
||||
if (!filePath) {
|
||||
const err = new Error('Failed to write file: path is required');
|
||||
err.code = 'EINVAL';
|
||||
throw err;
|
||||
}
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
// Ensure parent directory exists
|
||||
await fs.mkdir(path.dirname(fullPath), { recursive: true });
|
||||
// Convert array back to Buffer if needed
|
||||
const dataToWrite = Array.isArray(data) ? Buffer.from(data) : data;
|
||||
await fs.writeFile(fullPath, dataToWrite, encoding ? { encoding } : undefined);
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to write file ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:readdir', async (event, dirPath, withFileTypes) => {
|
||||
try {
|
||||
const fullPath = expandTilde(dirPath);
|
||||
const entries = await fs.readdir(fullPath, { withFileTypes: !!withFileTypes });
|
||||
|
||||
if (withFileTypes) {
|
||||
// Convert Dirent objects to plain objects for IPC
|
||||
return entries.map(entry => ({
|
||||
name: entry.name,
|
||||
isDirectory: entry.isDirectory(),
|
||||
isFile: entry.isFile(),
|
||||
}));
|
||||
}
|
||||
|
||||
return entries;
|
||||
} catch (error) {
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
const err = new Error(`Failed to read directory ${dirPath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
// Only log non-ENOTDIR errors (ENOTDIR is expected when checking if a file is a directory)
|
||||
if (error.code !== 'ENOTDIR') {
|
||||
console.error(err);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:mkdir', async (event, dirPath, recursive) => {
|
||||
try {
|
||||
const fullPath = expandTilde(dirPath);
|
||||
await fs.mkdir(fullPath, { recursive: !!recursive });
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to create directory ${dirPath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:stat', async (event, filePath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
const stats = await fs.stat(fullPath);
|
||||
const now = Date.now();
|
||||
return {
|
||||
isDirectory: stats.isDirectory(),
|
||||
isFile: stats.isFile(),
|
||||
isBlockDevice: stats.isBlockDevice(),
|
||||
isCharacterDevice: stats.isCharacterDevice(),
|
||||
isSymbolicLink: stats.isSymbolicLink(),
|
||||
isFIFO: stats.isFIFO(),
|
||||
isSocket: stats.isSocket(),
|
||||
size: stats.size,
|
||||
mtimeMs: stats.mtimeMs ?? now,
|
||||
ctimeMs: stats.ctimeMs ?? now,
|
||||
atimeMs: stats.atimeMs ?? now,
|
||||
// Date objects need to be serialized as timestamps for IPC
|
||||
// Use optional chaining and fallback to now to prevent valueOf errors
|
||||
mtime: stats.mtime?.getTime() ?? now,
|
||||
ctime: stats.ctime?.getTime() ?? now,
|
||||
atime: stats.atime?.getTime() ?? now,
|
||||
};
|
||||
} catch (error) {
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
const err = new Error(`Failed to stat ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:lstat', async (event, filePath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
const stats = await fs.lstat(fullPath);
|
||||
const now = Date.now();
|
||||
return {
|
||||
isDirectory: stats.isDirectory(),
|
||||
isFile: stats.isFile(),
|
||||
isBlockDevice: stats.isBlockDevice(),
|
||||
isCharacterDevice: stats.isCharacterDevice(),
|
||||
isSymbolicLink: stats.isSymbolicLink(),
|
||||
isFIFO: stats.isFIFO(),
|
||||
isSocket: stats.isSocket(),
|
||||
size: stats.size,
|
||||
mtimeMs: stats.mtimeMs ?? now,
|
||||
ctimeMs: stats.ctimeMs ?? now,
|
||||
atimeMs: stats.atimeMs ?? now,
|
||||
// Date objects need to be serialized as timestamps for IPC
|
||||
// Use optional chaining and fallback to now to prevent valueOf errors
|
||||
mtime: stats.mtime?.getTime() ?? now,
|
||||
ctime: stats.ctime?.getTime() ?? now,
|
||||
atime: stats.atime?.getTime() ?? now,
|
||||
};
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to lstat ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:unlink', async (event, filePath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
await fs.unlink(fullPath);
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to unlink ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:rmdir', async (event, dirPath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(dirPath);
|
||||
await fs.rmdir(fullPath);
|
||||
} catch (error) {
|
||||
// Re-throw with original error code preserved for ENOENT handling
|
||||
const err = new Error(`Failed to remove directory ${dirPath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:rename', async (event, oldPath, newPath) => {
|
||||
try {
|
||||
const fullOldPath = expandTilde(oldPath);
|
||||
const fullNewPath = expandTilde(newPath);
|
||||
// Ensure parent directory of new path exists
|
||||
await fs.mkdir(path.dirname(fullNewPath), { recursive: true });
|
||||
await fs.rename(fullOldPath, fullNewPath);
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to rename ${oldPath} to ${newPath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:readlink', async (event, filePath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
return await fs.readlink(fullPath);
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to read link ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('fs:symlink', async (event, target, filePath) => {
|
||||
try {
|
||||
const fullPath = expandTilde(filePath);
|
||||
// Ensure parent directory exists
|
||||
await fs.mkdir(path.dirname(fullPath), { recursive: true });
|
||||
await fs.symlink(target, fullPath);
|
||||
} catch (error) {
|
||||
const err = new Error(`Failed to create symlink ${filePath}: ${error.message}`);
|
||||
if (error.code) {
|
||||
Object.defineProperty(err, 'code', {
|
||||
value: error.code,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
// Shell execution handler
|
||||
ipcMain.handle('shell:exec', async (event, command, cwd) => {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
// Determine the shell and command execution method based on platform
|
||||
const isWindows = process.platform === 'win32';
|
||||
const shellCmd = isWindows ? 'cmd.exe' : '/bin/sh';
|
||||
const shellArgs = isWindows ? ['/c', command] : ['-c', command];
|
||||
|
||||
// Expand tilde in working directory if provided, otherwise use home directory
|
||||
const workingDir = cwd ? expandTilde(cwd) : os.homedir();
|
||||
|
||||
// Ensure the working directory exists before spawning
|
||||
try {
|
||||
await fs.mkdir(workingDir, { recursive: true });
|
||||
console.log(`Shell exec in directory: ${workingDir}`);
|
||||
console.log(`Command: ${command}`);
|
||||
} catch (mkdirError) {
|
||||
console.warn(`Failed to create directory ${workingDir}:`, mkdirError.message);
|
||||
// Continue anyway - directory might already exist
|
||||
}
|
||||
|
||||
const child = spawn(shellCmd, shellArgs, {
|
||||
cwd: workingDir,
|
||||
env: { ...process.env },
|
||||
shell: false, // We're already using the shell
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
child.stdout?.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
child.stderr?.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
child.on('error', (error) => {
|
||||
console.error('Shell execution error:', error);
|
||||
console.error('Working directory:', workingDir);
|
||||
console.error('Shell command:', shellCmd);
|
||||
console.error('Shell args:', shellArgs);
|
||||
reject(new Error(`Failed to execute command: ${error.message} (cwd: ${workingDir})`));
|
||||
});
|
||||
|
||||
child.on('close', (code) => {
|
||||
resolve({
|
||||
stdout,
|
||||
stderr,
|
||||
exitCode: code ?? 0,
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Shell setup error:', error);
|
||||
reject(new Error(`Failed to setup shell execution: ${error.message}`));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron';
|
||||
import os from 'node:os';
|
||||
|
||||
// Expose protected methods that allow the renderer process to use
|
||||
// ipcRenderer without exposing the entire object
|
||||
contextBridge.exposeInMainWorld('electron', {
|
||||
// Get the home directory
|
||||
homedir: os.homedir(),
|
||||
|
||||
// Platform information
|
||||
platform: () => ipcRenderer.invoke('get-platform'),
|
||||
|
||||
// App version
|
||||
version: () => ipcRenderer.invoke('get-app-version'),
|
||||
|
||||
// Filesystem API - paths support tilde (~) expansion for home directory
|
||||
fs: {
|
||||
readFile: (path, encoding) => ipcRenderer.invoke('fs:readFile', path, encoding),
|
||||
writeFile: (path, data, encoding) => ipcRenderer.invoke('fs:writeFile', path, data, encoding),
|
||||
readdir: (path, withFileTypes) => ipcRenderer.invoke('fs:readdir', path, withFileTypes),
|
||||
mkdir: (path, recursive) => ipcRenderer.invoke('fs:mkdir', path, recursive),
|
||||
stat: (path) => ipcRenderer.invoke('fs:stat', path),
|
||||
lstat: (path) => ipcRenderer.invoke('fs:lstat', path),
|
||||
unlink: (path) => ipcRenderer.invoke('fs:unlink', path),
|
||||
rmdir: (path) => ipcRenderer.invoke('fs:rmdir', path),
|
||||
rename: (oldPath, newPath) => ipcRenderer.invoke('fs:rename', oldPath, newPath),
|
||||
readlink: (path) => ipcRenderer.invoke('fs:readlink', path),
|
||||
symlink: (target, path) => ipcRenderer.invoke('fs:symlink', target, path),
|
||||
},
|
||||
|
||||
// Shell API - execute real shell commands
|
||||
shell: {
|
||||
exec: (command, cwd) => ipcRenderer.invoke('shell:exec', command, cwd),
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"mcp": {
|
||||
"nostr": {
|
||||
"type": "local",
|
||||
"command": ["npx", "-y", "@nostrbook/mcp@latest"]
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+238
-714
File diff suppressed because it is too large.
Load diff
+4
-7
@@ -17,9 +17,7 @@
|
||||
"dev": "npm i --silent && vite",
|
||||
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
|
||||
"typecheck": "npm i --silent && tsc --noEmit",
|
||||
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'",
|
||||
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && node scripts/prepare-electron-publish.js && electron electron",
|
||||
"electron:publish": "npm run build && node scripts/prepare-electron-publish.js && cd electron && npm publish"
|
||||
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
@@ -31,8 +29,8 @@
|
||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||
"@modelcontextprotocol/sdk": "^1.22.0",
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
"@nostrify/nostrify": "^0.47.1",
|
||||
"@nostrify/react": "^0.2.17",
|
||||
"@nostrify/nostrify": "^0.48.2",
|
||||
"@nostrify/react": "^0.2.20",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
||||
@@ -79,7 +77,7 @@
|
||||
"isomorphic-git": "^1.32.1",
|
||||
"jsonc-parser": "^3.3.1",
|
||||
"jszip": "^3.10.1",
|
||||
"lucide-react": "^0.525.0",
|
||||
"lucide-react": "^0.562.0",
|
||||
"mime": "^4.1.0",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"nunjucks": "^3.2.4",
|
||||
@@ -130,7 +128,6 @@
|
||||
"@types/uri-templates": "^0.1.34",
|
||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"electron": "^39.0.0",
|
||||
"eslint": "^9.9.0",
|
||||
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.9",
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { readFileSync, writeFileSync, copyFileSync, rmSync, cpSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const rootDir = join(__dirname, '..');
|
||||
const electronDir = join(rootDir, 'electron');
|
||||
const distDir = join(rootDir, 'dist');
|
||||
const electronDistDir = join(electronDir, 'dist');
|
||||
|
||||
// Read root package.json
|
||||
const rootPackage = JSON.parse(readFileSync(join(rootDir, 'package.json'), 'utf-8'));
|
||||
|
||||
// Generate CalVer version (YYYY.MM.DDHHMM) in UTC
|
||||
const now = new Date();
|
||||
const year = now.getUTCFullYear();
|
||||
const month = String(now.getUTCMonth() + 1).padStart(2, '0');
|
||||
const day = String(now.getUTCDate()).padStart(2, '0');
|
||||
const hour = String(now.getUTCHours()).padStart(2, '0');
|
||||
const minute = String(now.getUTCMinutes()).padStart(2, '0');
|
||||
const version = `${year}.${month}.${day}${hour}${minute}`;
|
||||
|
||||
// Get electron version from root devDependencies
|
||||
const electronVersion = rootPackage.devDependencies.electron;
|
||||
|
||||
// Remove old electron/dist and copy new one
|
||||
console.log('Removing old electron/dist...');
|
||||
rmSync(electronDistDir, { recursive: true, force: true });
|
||||
|
||||
console.log('Copying dist to electron/dist...');
|
||||
cpSync(distDir, electronDistDir, { recursive: true });
|
||||
|
||||
// Create electron package.json
|
||||
const electronPackage = {
|
||||
name: rootPackage.name,
|
||||
description: rootPackage.description,
|
||||
homepage: rootPackage.homepage,
|
||||
license: rootPackage.license,
|
||||
version: version,
|
||||
type: "module",
|
||||
main: "main.js",
|
||||
bin: {
|
||||
shakespeare: "./bin/shakespeare.js"
|
||||
},
|
||||
files: [
|
||||
"bin/",
|
||||
"dist/",
|
||||
"main.js",
|
||||
"package.json",
|
||||
"preload.js",
|
||||
"LICENSE",
|
||||
"README.md"
|
||||
],
|
||||
author: rootPackage.author,
|
||||
repository: rootPackage.repository,
|
||||
dependencies: {
|
||||
electron: electronVersion
|
||||
}
|
||||
};
|
||||
|
||||
// Write electron package.json
|
||||
writeFileSync(
|
||||
join(electronDir, 'package.json'),
|
||||
JSON.stringify(electronPackage, null, 2) + '\n',
|
||||
'utf-8'
|
||||
);
|
||||
|
||||
// Copy README.md to electron directory
|
||||
copyFileSync(
|
||||
join(rootDir, 'README.md'),
|
||||
join(electronDir, 'README.md')
|
||||
);
|
||||
|
||||
console.log(`✓ Generated electron/package.json with version ${version}`);
|
||||
console.log('✓ Copied README.md to electron/');
|
||||
+23
-15
@@ -23,24 +23,32 @@ export default {
|
||||
} catch {
|
||||
return new Response('Invalid url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
// AI-provider-specific hacks
|
||||
|
||||
let hostname = url.hostname;
|
||||
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
|
||||
hostname = 'ollama.com';
|
||||
} else if (url.host === 'generativelanguage.googleapis.com') {
|
||||
hostname = 'gemini.google.com';
|
||||
} else if (url.host === 'api.z.ai') {
|
||||
hostname = 'docs.z.ai';
|
||||
}
|
||||
|
||||
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
|
||||
hostname = hostname.replace(/^(ai\.|api\.)/, '');
|
||||
|
||||
return fetchFavicon(hostname);
|
||||
},
|
||||
};
|
||||
// GitHub hack: neutral color for light/dark mode
|
||||
if (hostname === 'github.com') {
|
||||
const svg = await (await fetch('https://github.githubassets.com/favicons/favicon.svg')).text();
|
||||
return new Response(svg.replaceAll('#24292E', '#808080'), {
|
||||
headers: { 'Content-Type': 'image/svg+xml' },
|
||||
});
|
||||
}
|
||||
|
||||
// AI-provider-specific hacks
|
||||
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
|
||||
hostname = 'ollama.com';
|
||||
} else if (url.host === 'localhost:45554' || url.origin === '127.0.0.1:45554') {
|
||||
hostname = 'claude.ai';
|
||||
} else if (url.host === 'generativelanguage.googleapis.com') {
|
||||
hostname = 'gemini.google.com';
|
||||
} else if (url.host === 'z.ai') {
|
||||
hostname = 'docs.z.ai';
|
||||
}
|
||||
|
||||
function fetchFavicon(hostname: string): Promise<Response> {
|
||||
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
|
||||
}
|
||||
// Fetch the favicon from DuckDuckGo's service
|
||||
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
|
||||
},
|
||||
};
|
||||
@@ -160,16 +160,6 @@ consistent handling of both text and binary data across the messaging protocol.
|
||||
**Parameters:** None
|
||||
**Result:** None (notification only)
|
||||
|
||||
#### `goBack`
|
||||
**Purpose:** Navigate back in the iframe's history
|
||||
**Parameters:** None
|
||||
**Result:** None (notification only)
|
||||
|
||||
#### `goForward`
|
||||
**Purpose:** Navigate forward in the iframe's history
|
||||
**Parameters:** None
|
||||
**Result:** None (notification only)
|
||||
|
||||
#### `updateNavigationState`
|
||||
**Purpose:** Update parent about iframe's current navigation state
|
||||
**Parameters:**
|
||||
|
||||
@@ -193,12 +193,6 @@ class NavigationHandler {
|
||||
case "refresh":
|
||||
this.handleRefresh();
|
||||
break;
|
||||
case "goBack":
|
||||
this.handleGoBack();
|
||||
break;
|
||||
case "goForward":
|
||||
this.handleGoForward();
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -286,14 +280,6 @@ class NavigationHandler {
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
handleGoBack() {
|
||||
window.history.back();
|
||||
}
|
||||
|
||||
handleGoForward() {
|
||||
window.history.forward();
|
||||
}
|
||||
|
||||
updateNavigationState() {
|
||||
// Use tracked semantic path, fallback to current location if needed
|
||||
const semanticPath = this.currentSemanticPath || this.extractSemanticPath(window.location);
|
||||
|
||||
+9
-8
@@ -12,16 +12,17 @@ export default {
|
||||
return new Response(null, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
|
||||
"Access-Control-Allow-Headers": "*", // Or specify specific headers
|
||||
"Access-Control-Max-Age": "86400", // Cache preflight for 24 hours
|
||||
"access-control-allow-origin": "*",
|
||||
"access-control-allow-methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
|
||||
"access-control-allow-headers": "*", // Or specify specific headers
|
||||
"access-control-max-age": "86400", // Cache preflight for 24 hours
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set('User-Agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
|
||||
headers.set('user-agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
|
||||
headers.delete('origin');
|
||||
|
||||
const targetResponse = await fetch(target, {
|
||||
method: request.method,
|
||||
@@ -31,9 +32,9 @@ export default {
|
||||
|
||||
const response = new Response(targetResponse.body, targetResponse);
|
||||
|
||||
response.headers.set("Access-Control-Allow-Origin", "*");
|
||||
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
|
||||
response.headers.set("Access-Control-Allow-Headers", "*");
|
||||
response.headers.set("access-control-allow-origin", "*");
|
||||
response.headers.set("access-control-allow-methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
|
||||
response.headers.set("access-control-allow-headers", "*");
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
+34
-78
@@ -21,13 +21,14 @@ import { DeploySettingsProvider } from '@/components/DeploySettingsProvider';
|
||||
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
|
||||
import { GitSyncProvider } from '@/components/GitSyncProvider';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { ElectronFSAdapter } from '@/lib/ElectronFSAdapter';
|
||||
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
|
||||
import { DynamicFavicon } from '@/components/DynamicFavicon';
|
||||
import { OfflineIndicator } from '@/components/OfflineIndicator';
|
||||
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
|
||||
import { ErrorBoundary } from '@/components/ErrorBoundary';
|
||||
import { NWCProvider } from '@/contexts/NWCContext';
|
||||
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
@@ -47,55 +48,6 @@ const queryClient = new QueryClient({
|
||||
},
|
||||
});
|
||||
|
||||
// Get OS-specific default paths for Electron
|
||||
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string; fsPathTemplates: string } {
|
||||
if (!globalThis.electron) {
|
||||
// Browser defaults - use virtual filesystem paths
|
||||
return {
|
||||
fsPathProjects: "/projects",
|
||||
fsPathConfig: "/config",
|
||||
fsPathTmp: "/tmp",
|
||||
fsPathPlugins: "/plugins",
|
||||
fsPathTemplates: "/templates",
|
||||
};
|
||||
}
|
||||
|
||||
// Electron defaults - use OS-specific paths
|
||||
// Note: The ~ will be expanded by the Electron main process
|
||||
const platform = navigator.platform.toLowerCase();
|
||||
|
||||
if (platform.includes('win')) {
|
||||
// Windows
|
||||
return {
|
||||
fsPathProjects: "~/Documents/Projects",
|
||||
fsPathConfig: "~/AppData/Local/shakespeare",
|
||||
fsPathTmp: "~/AppData/Local/Temp/shakespeare",
|
||||
fsPathPlugins: "~/AppData/Local/shakespeare/plugins",
|
||||
fsPathTemplates: "~/AppData/Local/shakespeare/templates",
|
||||
};
|
||||
} else if (platform.includes('mac')) {
|
||||
// macOS
|
||||
return {
|
||||
fsPathProjects: "~/Projects",
|
||||
fsPathConfig: "~/Library/Application Support/shakespeare",
|
||||
fsPathTmp: "/tmp/shakespeare",
|
||||
fsPathPlugins: "~/Library/Application Support/shakespeare/plugins",
|
||||
fsPathTemplates: "~/Library/Application Support/shakespeare/templates",
|
||||
};
|
||||
} else {
|
||||
// Linux and other Unix-like systems
|
||||
return {
|
||||
fsPathProjects: "~/Projects",
|
||||
fsPathConfig: "~/.config/shakespeare",
|
||||
fsPathTmp: "/tmp/shakespeare",
|
||||
fsPathPlugins: "~/.config/shakespeare/plugins",
|
||||
fsPathTemplates: "~/.config/shakespeare/templates",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const electronPaths = getElectronDefaultPaths();
|
||||
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "system",
|
||||
relayMetadata: {
|
||||
@@ -106,6 +58,13 @@ const defaultConfig: AppConfig = {
|
||||
],
|
||||
updatedAt: 0,
|
||||
},
|
||||
graspMetadata: {
|
||||
relays: [
|
||||
{ url: 'wss://git.shakespeare.diy/' },
|
||||
{ url: 'wss://relay.ngit.dev/' },
|
||||
],
|
||||
updatedAt: 0,
|
||||
},
|
||||
templates: [
|
||||
{
|
||||
name: "MKStack",
|
||||
@@ -117,34 +76,27 @@ const defaultConfig: AppConfig = {
|
||||
description: "This is a variant of MKStack extended to support Cashu integration. Choose this template only if the user has indicated they require Cashu integration.",
|
||||
url: "https://gitlab.com/lemonknowsall/nutstack.git",
|
||||
},
|
||||
{
|
||||
name: "Luvstack",
|
||||
description: "Barebones React template. Choose this to build mockups or demo sites that don't require Nostr functionality. Only choose this if the user has indicated they want to create a demo or mockup site, as it cannot support any sort of backend functionality or remote storage. It might also work for simple PWAs.",
|
||||
url: "https://gitlab.com/soapbox-pub/luvstack.git",
|
||||
}
|
||||
],
|
||||
esmUrl: "https://esm.sh",
|
||||
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
|
||||
gitProxyOrigins: ["https://github.com", "https://gitlab.com"],
|
||||
faviconUrl: "https://favicon.shakespeare.diy/?url={href}",
|
||||
ngitWebUrl: "https://nostrhub.io/{naddr}",
|
||||
previewDomain: "local-shakespeare.dev",
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
|
||||
ngitServers: ["git.shakespeare.diy", "relay.ngit.dev"],
|
||||
fsPathProjects: electronPaths.fsPathProjects,
|
||||
fsPathConfig: electronPaths.fsPathConfig,
|
||||
fsPathTmp: electronPaths.fsPathTmp,
|
||||
fsPathPlugins: electronPaths.fsPathPlugins,
|
||||
fsPathTemplates: electronPaths.fsPathTemplates,
|
||||
fsPathProjects: "/projects",
|
||||
fsPathConfig: "/config",
|
||||
fsPathTmp: "/tmp",
|
||||
fsPathPlugins: "/plugins",
|
||||
fsPathTemplates: "/templates",
|
||||
sentryDsn: import.meta.env.VITE_SENTRY_DSN || "",
|
||||
sentryEnabled: true,
|
||||
};
|
||||
|
||||
// Initialize filesystem adapter based on environment
|
||||
// In Electron, use Electron filesystem at ~/shakespeare
|
||||
// In browser, use LightningFS (IndexedDB-backed virtual filesystem)
|
||||
const fs = globalThis.electron
|
||||
? new ElectronFSAdapter()
|
||||
: new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
|
||||
// Initialize filesystem adapter
|
||||
// Use LightningFS (IndexedDB-backed virtual filesystem)
|
||||
const fs = new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
|
||||
|
||||
// Component to handle filesystem initialization and cleanup on startup
|
||||
// Ensures tmp directory exists and removes files older than 1 hour
|
||||
@@ -191,23 +143,27 @@ export function App() {
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<NostrSync />
|
||||
<NWCProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<DeploySettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<DynamicFavicon />
|
||||
<OfflineIndicator />
|
||||
<PWAUpdatePrompt />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
<GitSyncProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<DynamicFavicon />
|
||||
<OfflineIndicator />
|
||||
<PWAUpdatePrompt />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSyncProvider>
|
||||
</DeploySettingsProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NWCProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</ConsoleErrorProvider>
|
||||
|
||||
@@ -5,12 +5,14 @@ import { URLFragmentHandler } from "./components/URLFragmentHandler";
|
||||
|
||||
import Index from "./pages/Index";
|
||||
import Clone from "./pages/Clone";
|
||||
import Explore from "./pages/Explore";
|
||||
import Settings from "./pages/Settings";
|
||||
import Preferences from "./pages/Preferences";
|
||||
import NostrSettings from "./pages/NostrSettings";
|
||||
import AISettings from "./pages/AISettings";
|
||||
import GitSettings from "./pages/GitSettings";
|
||||
import DeploySettings from "./pages/DeploySettings";
|
||||
import WalletSettings from "./pages/WalletSettings";
|
||||
import SystemSettings from "./pages/SystemSettings";
|
||||
import StorageSettings from "./pages/StorageSettings";
|
||||
import AboutSettings from "./pages/AboutSettings";
|
||||
@@ -18,6 +20,7 @@ import AboutSettings from "./pages/AboutSettings";
|
||||
import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import NetlifyOAuth from "./pages/NetlifyOAuth";
|
||||
import VercelOAuth from "./pages/VercelOAuth";
|
||||
import OpenRouterOAuth from "./pages/OpenRouterOAuth";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { ProjectView } from "./pages/ProjectView";
|
||||
@@ -36,9 +39,11 @@ export function AppRouter() {
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/giftcard" element={<Index />} />
|
||||
<Route path="/clone" element={<Clone />} />
|
||||
<Route path="/explore" element={<Explore />} />
|
||||
<Route path="/oauth/github" element={<GitHubOAuth />} />
|
||||
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
||||
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
||||
<Route path="/oauth/openrouter" element={<OpenRouterOAuth />} />
|
||||
<Route path="/settings" element={<SettingsLayout />}>
|
||||
<Route index element={<Settings />} />
|
||||
<Route path="preferences" element={<Preferences />} />
|
||||
@@ -46,6 +51,7 @@ export function AppRouter() {
|
||||
<Route path="ai" element={<AISettings />} />
|
||||
<Route path="git" element={<GitSettings />} />
|
||||
<Route path="deploy" element={<DeploySettings />} />
|
||||
<Route path="wallet" element={<WalletSettings />} />
|
||||
<Route path="system" element={<SystemSettings />} />
|
||||
<Route path="storage" element={<StorageSettings />} />
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
|
||||
@@ -80,14 +80,6 @@ export const AIMessageItem = memo(({
|
||||
// User messages: right-aligned bubble without avatar/name
|
||||
// Extract text and image parts from message content
|
||||
const contentArray = Array.isArray(message.content) ? message.content : null;
|
||||
const textParts = contentArray
|
||||
? contentArray.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
|
||||
: [];
|
||||
const userContent = typeof message.content === 'string'
|
||||
? message.content
|
||||
: textParts.length > 0
|
||||
? textParts.map(part => part.text).join('\n')
|
||||
: '';
|
||||
|
||||
// Extract image URLs from content array
|
||||
const imageUrls = contentArray
|
||||
@@ -102,7 +94,7 @@ export const AIMessageItem = memo(({
|
||||
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
|
||||
<div className="text-sm break-words space-y-2">
|
||||
{/* Render text content and attachments first */}
|
||||
{userContent && <UserMessage content={userContent} />}
|
||||
<UserMessage content={message.content} />
|
||||
{/* Render images after text and attachments */}
|
||||
{imageUrls.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -151,6 +151,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
};
|
||||
|
||||
const isConfigured = settings.providers.length > 0;
|
||||
const isLoading = !isInitialized;
|
||||
|
||||
const contextValue: AISettingsContextType = {
|
||||
settings,
|
||||
@@ -162,6 +163,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
setMCPServer,
|
||||
removeMCPServer,
|
||||
isConfigured,
|
||||
isLoading,
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
GitBranch,
|
||||
MoreHorizontal,
|
||||
MessageSquarePlus,
|
||||
History,
|
||||
Folder,
|
||||
Rocket,
|
||||
Copy,
|
||||
} from 'lucide-react';
|
||||
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
|
||||
import { GitDialog } from '@/components/GitDialog';
|
||||
import { DeployDialog } from '@/components/DeployDialog';
|
||||
import { DuplicateProjectDialog } from '@/components/DuplicateProjectDialog';
|
||||
|
||||
interface ActionsMenuProps {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
onNewChat: () => void;
|
||||
onProjectDetails?: () => void;
|
||||
isLoading?: boolean;
|
||||
isBuildLoading?: boolean;
|
||||
disabled?: boolean;
|
||||
onFirstInteraction?: () => void;
|
||||
}
|
||||
|
||||
export function ActionsMenu({
|
||||
projectId,
|
||||
projectName,
|
||||
onNewChat,
|
||||
onProjectDetails,
|
||||
isLoading = false,
|
||||
isBuildLoading = false,
|
||||
disabled = false,
|
||||
onFirstInteraction: _onFirstInteraction,
|
||||
}: ActionsMenuProps) {
|
||||
const { t } = useTranslation();
|
||||
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
|
||||
const [gitDialogOpen, setGitDialogOpen] = useState(false);
|
||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||
const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false);
|
||||
|
||||
const isAnyLoading = isLoading || isBuildLoading;
|
||||
|
||||
|
||||
|
||||
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={() => setGitHistoryOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<History className="h-4 w-4" />
|
||||
Rollback
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setGitDialogOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<GitBranch className="h-4 w-4" />
|
||||
Repository
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setDeployDialogOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<Rocket className="h-4 w-4" />
|
||||
Deploy
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setDuplicateDialogOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<Copy className="h-4 w-4" />
|
||||
{t('duplicateProject')}
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onProjectDetails}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<Folder className="h-4 w-4" />
|
||||
Project Details
|
||||
</DropdownMenuItem>
|
||||
|
||||
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Dialogs */}
|
||||
<GitDialog
|
||||
projectId={projectId}
|
||||
open={gitDialogOpen}
|
||||
onOpenChange={setGitDialogOpen}
|
||||
/>
|
||||
|
||||
<GitHistoryDialog
|
||||
projectId={projectId}
|
||||
open={gitHistoryOpen}
|
||||
onOpenChange={setGitHistoryOpen}
|
||||
/>
|
||||
|
||||
<DeployDialog
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
open={deployDialogOpen}
|
||||
onOpenChange={setDeployDialogOpen}
|
||||
/>
|
||||
|
||||
<DuplicateProjectDialog
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
open={duplicateDialogOpen}
|
||||
onOpenChange={setDuplicateDialogOpen}
|
||||
/>
|
||||
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Bot, ChevronDown } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { ExternalInput } from '@/components/ui/external-input';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { PresetProvider } from '@/lib/aiProviderPresets';
|
||||
|
||||
interface OAuthHook {
|
||||
isOAuthConfigured: boolean;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
initiateOAuth: () => void;
|
||||
}
|
||||
|
||||
interface AddAIProviderDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
preset: PresetProvider;
|
||||
isLoggedIntoNostr: boolean;
|
||||
oauthHook?: OAuthHook | null;
|
||||
forceManualEntry?: boolean;
|
||||
onSetForceManualEntry?: (force: boolean) => void;
|
||||
onAdd: (apiKey: string) => void;
|
||||
}
|
||||
|
||||
export function AddAIProviderDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
preset,
|
||||
isLoggedIntoNostr,
|
||||
oauthHook,
|
||||
forceManualEntry = false,
|
||||
onSetForceManualEntry,
|
||||
onAdd,
|
||||
}: AddAIProviderDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [apiKey, setApiKey] = useState('');
|
||||
const [termsAgreed, setTermsAgreed] = useState(false);
|
||||
|
||||
const showNostrLoginRequired = preset.nostr && !isLoggedIntoNostr;
|
||||
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
|
||||
const isOAuthLoading = oauthHook?.isLoading ?? false;
|
||||
const oauthError = oauthHook?.error ?? null;
|
||||
|
||||
const handleAdd = () => {
|
||||
onAdd(apiKey);
|
||||
setApiKey('');
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
// Reset state when dialog closes
|
||||
const handleOpenChange = (open: boolean) => {
|
||||
if (!open) {
|
||||
setApiKey('');
|
||||
setTermsAgreed(false);
|
||||
}
|
||||
onOpenChange(open);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalFavicon
|
||||
url={preset.baseURL}
|
||||
size={20}
|
||||
fallback={<Bot size={20} />}
|
||||
/>
|
||||
<DialogTitle>{preset.name}</DialogTitle>
|
||||
</div>
|
||||
<DialogDescription>
|
||||
Add {preset.name} as your AI provider
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
{showNostrLoginRequired ? (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('loginToNostrRequired')}
|
||||
</p>
|
||||
<Button asChild className="w-full">
|
||||
<Link to="/settings/nostr">
|
||||
{t('goToNostrSettings')}
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : isOAuthConfigured && !forceManualEntry ? (
|
||||
// Show OAuth button if OAuth is configured and not forced to manual
|
||||
<div className="space-y-3">
|
||||
<div className="flex gap-0">
|
||||
<Button
|
||||
onClick={() => oauthHook?.initiateOAuth()}
|
||||
disabled={isOAuthLoading}
|
||||
className="flex-1 rounded-r-none gap-2"
|
||||
variant="default"
|
||||
>
|
||||
{isOAuthLoading ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to {preset.name}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="default"
|
||||
className="rounded-l-none border-l border-primary-foreground/20 px-2"
|
||||
disabled={isOAuthLoading}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => onSetForceManualEntry?.(true)}>
|
||||
Enter API key
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
{oauthError && (
|
||||
<p className="text-sm text-destructive">
|
||||
{oauthError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{!preset.nostr && preset.apiKeysURL && (
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={preset.id === "routstr" ? t('enterCashuToken') : t('enterApiKey')}
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() && termsAgreed) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
url={preset.apiKeysURL}
|
||||
urlTitle="Get Key"
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Terms of Service Agreement */}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Checkbox
|
||||
id="agree-terms"
|
||||
checked={termsAgreed}
|
||||
onCheckedChange={(checked) => setTermsAgreed(checked === true)}
|
||||
className="size-3 [&_svg]:size-3"
|
||||
/>
|
||||
<label
|
||||
htmlFor="agree-terms"
|
||||
className="text-xs text-muted-foreground leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||
>
|
||||
{t('agreeToTermsOfService', { providerName: preset.name })}{' '}
|
||||
{preset.tosURL ? (
|
||||
<a
|
||||
href={preset.tosURL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-muted-foreground underline hover:text-foreground hover:no-underline"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{t('termsOfService')}
|
||||
</a>
|
||||
) : (
|
||||
t('termsOfService')
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!showNostrLoginRequired && !(isOAuthConfigured && !forceManualEntry) && (
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleAdd}
|
||||
disabled={
|
||||
!termsAgreed ||
|
||||
(!!preset.apiKeysURL && !apiKey.trim())
|
||||
}
|
||||
>
|
||||
{t('add')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Check } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface AddCustomAIProviderDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onAdd: (provider: AIProvider) => void;
|
||||
existingIds: string[];
|
||||
}
|
||||
|
||||
// Helper function to generate ID from name
|
||||
function generateIdFromName(name: string): string {
|
||||
return name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-') // Replace non-alphanumeric chars with hyphens
|
||||
.replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
|
||||
}
|
||||
|
||||
export function AddCustomAIProviderDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onAdd,
|
||||
existingIds,
|
||||
}: AddCustomAIProviderDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [customProviderName, setCustomProviderName] = useState('');
|
||||
const [customProviderId, setCustomProviderId] = useState('');
|
||||
const [customIdManuallyEdited, setCustomIdManuallyEdited] = useState(false);
|
||||
const [customBaseURL, setCustomBaseURL] = useState('');
|
||||
const [customApiKey, setCustomApiKey] = useState('');
|
||||
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr'>('api-key');
|
||||
const [customProxy, setCustomProxy] = useState(false);
|
||||
|
||||
const handleAdd = () => {
|
||||
if (!customProviderName.trim() || !customProviderId.trim() || !customBaseURL.trim()) return;
|
||||
|
||||
const provider: AIProvider = {
|
||||
id: customProviderId.trim(),
|
||||
name: customProviderName.trim(),
|
||||
baseURL: customBaseURL.trim(),
|
||||
};
|
||||
|
||||
if (customAuthMethod === 'api-key' && customApiKey.trim()) {
|
||||
provider.apiKey = customApiKey.trim();
|
||||
} else if (customAuthMethod === 'nostr') {
|
||||
provider.nostr = true;
|
||||
}
|
||||
|
||||
if (customProxy) {
|
||||
provider.proxy = true;
|
||||
}
|
||||
|
||||
onAdd(provider);
|
||||
|
||||
// Reset form
|
||||
setCustomProviderName('');
|
||||
setCustomProviderId('');
|
||||
setCustomIdManuallyEdited(false);
|
||||
setCustomBaseURL('');
|
||||
setCustomApiKey('');
|
||||
setCustomAuthMethod('api-key');
|
||||
setCustomProxy(false);
|
||||
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const isValid = customProviderName.trim() &&
|
||||
customProviderId.trim() &&
|
||||
customBaseURL.trim() &&
|
||||
!existingIds.includes(customProviderId.trim());
|
||||
|
||||
const idExists = existingIds.includes(customProviderId.trim());
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('addCustomProvider')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure a custom AI provider with your own settings
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-name">
|
||||
{t('name')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-name"
|
||||
placeholder="e.g., My Custom API"
|
||||
value={customProviderName}
|
||||
onChange={(e) => {
|
||||
const newName = e.target.value;
|
||||
setCustomProviderName(newName);
|
||||
|
||||
// Auto-generate ID from name if ID hasn't been manually edited
|
||||
if (!customIdManuallyEdited) {
|
||||
setCustomProviderId(generateIdFromName(newName));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-id">
|
||||
{t('id')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-id"
|
||||
placeholder="e.g., my-custom-api"
|
||||
value={customProviderId}
|
||||
onChange={(e) => {
|
||||
setCustomProviderId(e.target.value);
|
||||
setCustomIdManuallyEdited(true);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-baseurl">
|
||||
{t('baseUrl')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-baseurl"
|
||||
placeholder="https://api.example.com/v1"
|
||||
value={customBaseURL}
|
||||
onChange={(e) => setCustomBaseURL(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-auth">{t('authentication')}</Label>
|
||||
<Select
|
||||
value={customAuthMethod}
|
||||
onValueChange={(value: 'api-key' | 'nostr') => {
|
||||
setCustomAuthMethod(value);
|
||||
if (value === 'nostr') {
|
||||
setCustomApiKey(''); // Clear API key when switching to Nostr auth
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
|
||||
<SelectItem value="nostr">Nostr</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{customAuthMethod === 'api-key' && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-apikey">{t('apiKey')}</Label>
|
||||
<PasswordInput
|
||||
id="custom-apikey"
|
||||
placeholder={t('enterApiKey') + ' (optional)'}
|
||||
value={customApiKey}
|
||||
onChange={(e) => setCustomApiKey(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
id="custom-proxy"
|
||||
checked={customProxy}
|
||||
onCheckedChange={(checked) => setCustomProxy(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="custom-proxy" className="cursor-pointer">
|
||||
{t('useCorsProxy')}
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{idExists && (
|
||||
<p className="text-sm text-destructive">
|
||||
{t('providerExists')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleAdd} disabled={!isValid}>
|
||||
<Check className="h-4 w-4 mr-2" />
|
||||
{t('addCustomProviderButton')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Check } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
interface AddCustomGitCredentialDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onAdd: (credential: {
|
||||
name: string;
|
||||
origin: string;
|
||||
username: string;
|
||||
password: string;
|
||||
}) => void;
|
||||
existingOrigins: string[];
|
||||
}
|
||||
|
||||
export function AddCustomGitCredentialDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onAdd,
|
||||
existingOrigins,
|
||||
}: AddCustomGitCredentialDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [customName, setCustomName] = useState('');
|
||||
const [customOrigin, setCustomOrigin] = useState('');
|
||||
const [customUsername, setCustomUsername] = useState('');
|
||||
const [customPassword, setCustomPassword] = useState('');
|
||||
|
||||
const handleAdd = () => {
|
||||
if (!customName.trim() || !customOrigin.trim() || !customUsername.trim() || !customPassword.trim()) return;
|
||||
|
||||
onAdd({
|
||||
name: customName.trim(),
|
||||
origin: customOrigin.trim(),
|
||||
username: customUsername.trim(),
|
||||
password: customPassword.trim(),
|
||||
});
|
||||
|
||||
// Reset form
|
||||
setCustomName('');
|
||||
setCustomOrigin('');
|
||||
setCustomUsername('');
|
||||
setCustomPassword('');
|
||||
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const isValid = customName.trim() &&
|
||||
customOrigin.trim() &&
|
||||
customUsername.trim() &&
|
||||
customPassword.trim() &&
|
||||
!existingOrigins.includes(customOrigin.trim());
|
||||
|
||||
const originExists = existingOrigins.includes(customOrigin.trim());
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('addCustomProvider')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure a custom Git server with your credentials
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-name">
|
||||
{t('name')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-name"
|
||||
placeholder="My Git Server"
|
||||
value={customName}
|
||||
onChange={(e) => setCustomName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-origin">
|
||||
{t('origin')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-origin"
|
||||
placeholder="https://git.example.com"
|
||||
value={customOrigin}
|
||||
onChange={(e) => setCustomOrigin(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-username">
|
||||
{t('username')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-username"
|
||||
placeholder="git"
|
||||
value={customUsername}
|
||||
onChange={(e) => setCustomUsername(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-password">
|
||||
{t('password')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<PasswordInput
|
||||
id="custom-password"
|
||||
placeholder={t('enterPassword')}
|
||||
value={customPassword}
|
||||
onChange={(e) => setCustomPassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{originExists && (
|
||||
<p className="text-sm text-destructive">
|
||||
{t('credentialsExist')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleAdd} disabled={!isValid}>
|
||||
<Check className="h-4 w-4 mr-2" />
|
||||
{t('addCustomProviderButton')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Check } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type {
|
||||
ShakespeareDeployProvider,
|
||||
NetlifyProvider,
|
||||
VercelProvider,
|
||||
NsiteProvider,
|
||||
CloudflareProvider,
|
||||
DenoDeployProvider,
|
||||
} from '@/contexts/DeploySettingsContext';
|
||||
|
||||
// Type for provider without the 'id' field (will be generated)
|
||||
type DeployProviderInput =
|
||||
| Omit<ShakespeareDeployProvider, 'id'>
|
||||
| Omit<NetlifyProvider, 'id'>
|
||||
| Omit<VercelProvider, 'id'>
|
||||
| Omit<NsiteProvider, 'id'>
|
||||
| Omit<CloudflareProvider, 'id'>
|
||||
| Omit<DenoDeployProvider, 'id'>;
|
||||
|
||||
interface AddCustomProviderDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onAdd: (provider: DeployProviderInput) => void;
|
||||
}
|
||||
|
||||
export function AddCustomProviderDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onAdd,
|
||||
}: AddCustomProviderDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | ''>('');
|
||||
const [customName, setCustomName] = useState('');
|
||||
const [customApiKey, setCustomApiKey] = useState('');
|
||||
const [customAccountId, setCustomAccountId] = useState('');
|
||||
const [customOrganizationId, setCustomOrganizationId] = useState('');
|
||||
const [customBaseURL, setCustomBaseURL] = useState('');
|
||||
const [customBaseDomain, setCustomBaseDomain] = useState('');
|
||||
const [customHost, setCustomHost] = useState('');
|
||||
const [customProxy, setCustomProxy] = useState(false);
|
||||
const [customGateway, setCustomGateway] = useState('');
|
||||
const [customRelayUrls, setCustomRelayUrls] = useState('');
|
||||
const [customBlossomServers, setCustomBlossomServers] = useState('');
|
||||
|
||||
const handleAdd = () => {
|
||||
if (!customProviderType || !customName.trim()) return;
|
||||
|
||||
// Build provider object based on type
|
||||
let provider: DeployProviderInput;
|
||||
|
||||
if (customProviderType === 'shakespeare') {
|
||||
provider = {
|
||||
type: 'shakespeare',
|
||||
name: customName.trim(),
|
||||
...(customHost?.trim() && { host: customHost.trim() }),
|
||||
...(customProxy && { proxy: true }),
|
||||
};
|
||||
} else if (customProviderType === 'nsite') {
|
||||
provider = {
|
||||
type: 'nsite',
|
||||
name: customName.trim(),
|
||||
gateway: customGateway.trim() || 'nsite.lol',
|
||||
relayUrls: customRelayUrls.trim()
|
||||
? customRelayUrls.split(',').map(s => s.trim()).filter(Boolean)
|
||||
: ['wss://relay.nostr.band'],
|
||||
blossomServers: customBlossomServers.trim()
|
||||
? customBlossomServers.split(',').map(s => s.trim()).filter(Boolean)
|
||||
: ['https://blossom.primal.net/'],
|
||||
};
|
||||
} else if (customProviderType === 'netlify') {
|
||||
if (!customApiKey.trim()) return;
|
||||
provider = {
|
||||
type: 'netlify',
|
||||
name: customName.trim(),
|
||||
apiKey: customApiKey.trim(),
|
||||
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
|
||||
...(customProxy && { proxy: true }),
|
||||
};
|
||||
} else if (customProviderType === 'vercel') {
|
||||
if (!customApiKey.trim()) return;
|
||||
provider = {
|
||||
type: 'vercel',
|
||||
name: customName.trim(),
|
||||
apiKey: customApiKey.trim(),
|
||||
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
|
||||
...(customProxy && { proxy: true }),
|
||||
};
|
||||
} else if (customProviderType === 'cloudflare') {
|
||||
if (!customApiKey.trim() || !customAccountId.trim()) return;
|
||||
provider = {
|
||||
type: 'cloudflare',
|
||||
name: customName.trim(),
|
||||
apiKey: customApiKey.trim(),
|
||||
accountId: customAccountId.trim(),
|
||||
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
|
||||
...(customBaseDomain?.trim() && { baseDomain: customBaseDomain.trim() }),
|
||||
...(customProxy && { proxy: true }),
|
||||
};
|
||||
} else if (customProviderType === 'deno') {
|
||||
if (!customApiKey.trim() || !customOrganizationId.trim()) return;
|
||||
provider = {
|
||||
type: 'deno',
|
||||
name: customName.trim(),
|
||||
apiKey: customApiKey.trim(),
|
||||
organizationId: customOrganizationId.trim(),
|
||||
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
|
||||
...(customBaseDomain?.trim() && { baseDomain: customBaseDomain.trim() }),
|
||||
...(customProxy && { proxy: true }),
|
||||
};
|
||||
} else {
|
||||
return; // Unknown type
|
||||
}
|
||||
|
||||
onAdd(provider);
|
||||
|
||||
// Reset form
|
||||
setCustomProviderType('');
|
||||
setCustomName('');
|
||||
setCustomApiKey('');
|
||||
setCustomAccountId('');
|
||||
setCustomOrganizationId('');
|
||||
setCustomBaseURL('');
|
||||
setCustomBaseDomain('');
|
||||
setCustomHost('');
|
||||
setCustomProxy(false);
|
||||
setCustomGateway('');
|
||||
setCustomRelayUrls('');
|
||||
setCustomBlossomServers('');
|
||||
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const isValid = customProviderType && customName.trim() &&
|
||||
(customProviderType === 'shakespeare' || customProviderType === 'nsite' ||
|
||||
(customApiKey.trim() &&
|
||||
(customProviderType !== 'cloudflare' || customAccountId.trim()) &&
|
||||
(customProviderType !== 'deno' || customOrganizationId.trim())));
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('addCustomProvider')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure a custom deployment provider with your own settings
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-provider-type">
|
||||
{t('providerType')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Select
|
||||
value={customProviderType}
|
||||
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno') => {
|
||||
setCustomProviderType(value);
|
||||
// Reset form when provider type changes
|
||||
setCustomApiKey('');
|
||||
setCustomAccountId('');
|
||||
setCustomOrganizationId('');
|
||||
setCustomBaseURL('');
|
||||
setCustomBaseDomain('');
|
||||
setCustomHost('');
|
||||
setCustomProxy(false);
|
||||
setCustomGateway('');
|
||||
setCustomRelayUrls('');
|
||||
setCustomBlossomServers('');
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('selectProviderType')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="shakespeare">Shakespeare Deploy</SelectItem>
|
||||
<SelectItem value="nsite">nsite</SelectItem>
|
||||
<SelectItem value="netlify">Netlify</SelectItem>
|
||||
<SelectItem value="vercel">Vercel</SelectItem>
|
||||
<SelectItem value="cloudflare">Cloudflare</SelectItem>
|
||||
<SelectItem value="deno">Deno Deploy</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{customProviderType && (
|
||||
<>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-name">
|
||||
{t('providerName')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-name"
|
||||
placeholder="e.g., My Production Deploy"
|
||||
value={customName}
|
||||
onChange={(e) => setCustomName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{customProviderType === 'shakespeare' ? (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('shakespeareDeployNostrAuth')}
|
||||
</p>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-host">Host (Optional)</Label>
|
||||
<Input
|
||||
id="custom-host"
|
||||
placeholder="shakespeare.wtf"
|
||||
value={customHost}
|
||||
onChange={(e) => setCustomHost(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : customProviderType === 'nsite' ? (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Deploy to Nostr as a static website. Uses kind 34128 events and Blossom file storage.
|
||||
</p>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-gateway">Gateway</Label>
|
||||
<Input
|
||||
id="custom-gateway"
|
||||
placeholder="nsite.lol"
|
||||
value={customGateway}
|
||||
onChange={(e) => setCustomGateway(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-relays">Relay URLs (comma-separated)</Label>
|
||||
<Input
|
||||
id="custom-relays"
|
||||
placeholder="wss://relay.nostr.band, wss://relay.damus.io"
|
||||
value={customRelayUrls}
|
||||
onChange={(e) => setCustomRelayUrls(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-blossom">Blossom Servers (comma-separated)</Label>
|
||||
<Input
|
||||
id="custom-blossom"
|
||||
placeholder="https://blossom.primal.net/"
|
||||
value={customBlossomServers}
|
||||
onChange={(e) => setCustomBlossomServers(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{customProviderType === 'cloudflare' && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-accountid">
|
||||
Account ID <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-accountid"
|
||||
placeholder="Enter Account ID"
|
||||
value={customAccountId}
|
||||
onChange={(e) => setCustomAccountId(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{customProviderType === 'deno' && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-organizationid">
|
||||
Organization ID <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-organizationid"
|
||||
placeholder="Enter Organization ID"
|
||||
value={customOrganizationId}
|
||||
onChange={(e) => setCustomOrganizationId(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-apikey">
|
||||
{customProviderType === 'netlify' ? 'Personal Access Token' :
|
||||
customProviderType === 'cloudflare' ? 'API Token' :
|
||||
customProviderType === 'deno' ? 'Access Token' :
|
||||
'Access Token'} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<PasswordInput
|
||||
id="custom-apikey"
|
||||
placeholder={t('enterApiKey')}
|
||||
value={customApiKey}
|
||||
onChange={(e) => setCustomApiKey(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-baseurl">Base URL (Optional)</Label>
|
||||
<Input
|
||||
id="custom-baseurl"
|
||||
placeholder={
|
||||
customProviderType === 'netlify'
|
||||
? 'https://api.netlify.com/api/v1'
|
||||
: customProviderType === 'vercel'
|
||||
? 'https://api.vercel.com'
|
||||
: customProviderType === 'deno'
|
||||
? 'https://api.deno.com/v1'
|
||||
: 'https://api.cloudflare.com/client/v4'
|
||||
}
|
||||
value={customBaseURL}
|
||||
onChange={(e) => setCustomBaseURL(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{(customProviderType === 'cloudflare' || customProviderType === 'deno') && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-basedomain">Base Domain (Optional)</Label>
|
||||
<Input
|
||||
id="custom-basedomain"
|
||||
placeholder={customProviderType === 'cloudflare' ? 'workers.dev' : 'deno.dev'}
|
||||
value={customBaseDomain}
|
||||
onChange={(e) => setCustomBaseDomain(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{customProviderType === 'cloudflare'
|
||||
? 'The domain suffix for deployed workers (e.g., workers.dev)'
|
||||
: 'The domain suffix for deployed projects (e.g., deno.dev)'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="custom-proxy"
|
||||
checked={customProxy}
|
||||
onCheckedChange={(checked) => setCustomProxy(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="custom-proxy" className="text-sm font-normal cursor-pointer">
|
||||
Use CORS Proxy
|
||||
</Label>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleAdd} disabled={!isValid}>
|
||||
<Check className="h-4 w-4 mr-2" />
|
||||
{t('add')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Rocket, ChevronDown } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ExternalInput } from '@/components/ui/external-input';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
|
||||
interface OAuthHook {
|
||||
isOAuthConfigured: boolean;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
initiateOAuth: () => void;
|
||||
}
|
||||
|
||||
interface AddDeployProviderDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
preset: PresetDeployProvider;
|
||||
isLoggedIntoNostr: boolean;
|
||||
oauthHook: OAuthHook | null;
|
||||
forceManualEntry: boolean;
|
||||
onSetForceManualEntry: (force: boolean) => void;
|
||||
onAdd: (apiKey: string, accountId?: string, organizationId?: string) => void;
|
||||
}
|
||||
|
||||
export function AddDeployProviderDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
preset,
|
||||
isLoggedIntoNostr,
|
||||
oauthHook,
|
||||
forceManualEntry,
|
||||
onSetForceManualEntry,
|
||||
onAdd,
|
||||
}: AddDeployProviderDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [apiKey, setApiKey] = useState('');
|
||||
const [accountId, setAccountId] = useState('');
|
||||
const [organizationId, setOrganizationId] = useState('');
|
||||
|
||||
const showNostrLoginRequired = preset.requiresNostr && !isLoggedIntoNostr;
|
||||
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
|
||||
const isOAuthLoading = oauthHook?.isLoading ?? false;
|
||||
const oauthError = oauthHook?.error ?? null;
|
||||
|
||||
const handleAdd = () => {
|
||||
onAdd(apiKey, accountId, organizationId);
|
||||
setApiKey('');
|
||||
setAccountId('');
|
||||
setOrganizationId('');
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalFavicon
|
||||
url={preset.baseURL}
|
||||
size={20}
|
||||
fallback={<Rocket size={20} />}
|
||||
/>
|
||||
<DialogTitle>{preset.name}</DialogTitle>
|
||||
</div>
|
||||
<DialogDescription>
|
||||
{preset.description}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
{showNostrLoginRequired ? (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('loginToNostrRequired')}
|
||||
</p>
|
||||
<Button asChild className="w-full">
|
||||
<Link to="/settings/nostr">
|
||||
{t('goToNostrSettings')}
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : isOAuthConfigured && !forceManualEntry ? (
|
||||
// Show OAuth button if OAuth is configured and not forced to manual
|
||||
<div className="space-y-3">
|
||||
<div className="flex gap-0">
|
||||
<Button
|
||||
onClick={() => oauthHook?.initiateOAuth()}
|
||||
disabled={isOAuthLoading}
|
||||
className="flex-1 rounded-r-none gap-2"
|
||||
variant="default"
|
||||
>
|
||||
{isOAuthLoading ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to {preset.name}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="default"
|
||||
className="rounded-l-none border-l border-primary-foreground/20 px-2"
|
||||
disabled={isOAuthLoading}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => onSetForceManualEntry(true)}>
|
||||
Enter API key
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
{oauthError && (
|
||||
<p className="text-sm text-destructive">
|
||||
{oauthError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
// Show manual token input
|
||||
<div className="space-y-3">
|
||||
{!preset.requiresNostr && preset.type !== 'nsite' && (
|
||||
<>
|
||||
{preset.type === 'cloudflare' && (
|
||||
<ExternalInput
|
||||
type="text"
|
||||
placeholder={preset.accountIdLabel || 'Account ID'}
|
||||
value={accountId}
|
||||
onChange={(e) => setAccountId(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() && accountId.trim()) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
url={preset.accountIdURL}
|
||||
urlTitle="Find ID"
|
||||
/>
|
||||
)}
|
||||
{preset.type === 'deno' && (
|
||||
<ExternalInput
|
||||
type="text"
|
||||
placeholder={preset.organizationIdLabel || 'Organization ID'}
|
||||
value={organizationId}
|
||||
onChange={(e) => setOrganizationId(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() && organizationId.trim()) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
url={preset.organizationIdURL}
|
||||
urlTitle="Find ID"
|
||||
/>
|
||||
)}
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={preset.apiKeyLabel || t('enterApiKey')}
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() &&
|
||||
(preset.type !== 'cloudflare' || accountId.trim()) &&
|
||||
(preset.type !== 'deno' || organizationId.trim())) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
url={preset.apiKeyURL}
|
||||
urlTitle="Get Key"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!showNostrLoginRequired && !(isOAuthConfigured && !forceManualEntry) && (
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleAdd}
|
||||
disabled={
|
||||
(preset.requiresNostr && !isLoggedIntoNostr) ||
|
||||
(!preset.requiresNostr && preset.type !== 'nsite' && !apiKey.trim()) ||
|
||||
(preset.type === 'cloudflare' && !accountId.trim()) ||
|
||||
(preset.type === 'deno' && !organizationId.trim())
|
||||
}
|
||||
>
|
||||
{t('add')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { GitBranch, ChevronDown } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ExternalInput } from '@/components/ui/external-input';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
|
||||
interface PresetProvider {
|
||||
id: string;
|
||||
name: string;
|
||||
origin: string;
|
||||
username: string;
|
||||
tokenURL?: string;
|
||||
}
|
||||
|
||||
interface OAuthHook {
|
||||
initiateOAuth: () => void;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
isOAuthConfigured: boolean;
|
||||
}
|
||||
|
||||
interface AddGitCredentialDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
preset: PresetProvider;
|
||||
oauthHook: OAuthHook | null;
|
||||
forceManualEntry: boolean;
|
||||
onSetForceManualEntry: (force: boolean) => void;
|
||||
onAdd: (token: string) => void;
|
||||
}
|
||||
|
||||
export function AddGitCredentialDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
preset,
|
||||
oauthHook,
|
||||
forceManualEntry,
|
||||
onSetForceManualEntry,
|
||||
onAdd,
|
||||
}: AddGitCredentialDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [token, setToken] = useState('');
|
||||
|
||||
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
|
||||
const isOAuthLoading = oauthHook?.isLoading ?? false;
|
||||
const oauthError = oauthHook?.error ?? null;
|
||||
|
||||
const handleAdd = () => {
|
||||
onAdd(token);
|
||||
setToken('');
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalFavicon
|
||||
url={preset.origin}
|
||||
size={20}
|
||||
fallback={<GitBranch size={20} />}
|
||||
/>
|
||||
<DialogTitle>{preset.name}</DialogTitle>
|
||||
</div>
|
||||
<DialogDescription>
|
||||
Add {preset.name} credentials for Git operations
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
{isOAuthConfigured && !forceManualEntry ? (
|
||||
// Show OAuth button if OAuth is configured and not forced to manual
|
||||
<div className="space-y-3">
|
||||
<div className="flex gap-0">
|
||||
<Button
|
||||
onClick={() => oauthHook?.initiateOAuth()}
|
||||
disabled={isOAuthLoading}
|
||||
className="flex-1 rounded-r-none gap-2"
|
||||
variant="default"
|
||||
>
|
||||
{isOAuthLoading ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to {preset.name}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="default"
|
||||
className="rounded-l-none border-l border-primary-foreground/20 px-2"
|
||||
disabled={isOAuthLoading}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => onSetForceManualEntry(true)}>
|
||||
Enter token manually
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
{oauthError && (
|
||||
<p className="text-sm text-destructive">
|
||||
{oauthError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
// Show manual token input
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={t('enterToken')}
|
||||
value={token}
|
||||
onChange={(e) => setToken(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && token.trim()) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
url={preset.tokenURL}
|
||||
urlTitle="Get Token"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!(isOAuthConfigured && !forceManualEntry) && (
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleAdd} disabled={!token.trim()}>
|
||||
{t('add')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Plus } from 'lucide-react';
|
||||
|
||||
interface AddProviderTileProps {
|
||||
onClick: () => void;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export function AddProviderTile({ onClick, label = 'Add Custom' }: AddProviderTileProps) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className="flex flex-col items-center justify-center gap-2 p-4 rounded-lg border border-dashed bg-card hover:bg-muted transition-colors text-center min-h-[100px]"
|
||||
>
|
||||
<Plus size={32} className="text-muted-foreground" />
|
||||
<span className="text-sm font-medium text-muted-foreground overflow-hidden max-w-full text-ellipsis">
|
||||
{label}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
+14
-14
@@ -2,10 +2,10 @@ import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { AddProviderDialog } from './AddProviderDialog';
|
||||
import { AddSharedProviderDialog } from './AddSharedProviderDialog';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
describe('AddProviderDialog', () => {
|
||||
describe('AddSharedProviderDialog', () => {
|
||||
const mockProvider: AIProvider = {
|
||||
id: 'test-provider',
|
||||
name: 'Test Provider',
|
||||
@@ -18,7 +18,7 @@ describe('AddProviderDialog', () => {
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
<AddSharedProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={mockProvider}
|
||||
@@ -26,9 +26,9 @@ describe('AddProviderDialog', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Provider name is used as the heading (fallback to id since it's not in presets)
|
||||
expect(screen.getByRole('heading', { name: 'test-provider' })).toBeInTheDocument();
|
||||
expect(screen.getByText(/Add test-provider to your configuration/i)).toBeInTheDocument();
|
||||
// Provider name is displayed in the heading
|
||||
expect(screen.getByRole('heading', { name: 'Test Provider' })).toBeInTheDocument();
|
||||
expect(screen.getByText(/Add Test Provider to your configuration/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows add provider button for new provider', () => {
|
||||
@@ -36,7 +36,7 @@ describe('AddProviderDialog', () => {
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
<AddSharedProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={mockProvider}
|
||||
@@ -55,7 +55,7 @@ describe('AddProviderDialog', () => {
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
<AddSharedProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={mockProvider}
|
||||
@@ -74,7 +74,7 @@ describe('AddProviderDialog', () => {
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
<AddSharedProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={mockProvider}
|
||||
@@ -100,7 +100,7 @@ describe('AddProviderDialog', () => {
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
<AddSharedProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={openrouterProvider}
|
||||
@@ -112,7 +112,7 @@ describe('AddProviderDialog', () => {
|
||||
expect(screen.getByText(/Add OpenRouter to your configuration/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses provider id as fallback name when not in presets', () => {
|
||||
it('uses provider name when not in presets', () => {
|
||||
const onOpenChange = vi.fn();
|
||||
const customProvider: AIProvider = {
|
||||
id: 'my-custom-provider',
|
||||
@@ -122,7 +122,7 @@ describe('AddProviderDialog', () => {
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
<AddSharedProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={customProvider}
|
||||
@@ -130,7 +130,7 @@ describe('AddProviderDialog', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should use the id as the name since it's not in presets
|
||||
expect(screen.getByText(/Add my-custom-provider to your configuration/i)).toBeInTheDocument();
|
||||
// Should use the provider name even when not in presets
|
||||
expect(screen.getByText(/Add My Custom Provider to your configuration/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -8,13 +8,13 @@ import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface AddProviderDialogProps {
|
||||
interface AddSharedProviderDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
provider: AIProvider;
|
||||
}
|
||||
|
||||
export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderDialogProps) {
|
||||
export function AddSharedProviderDialog({ open, onOpenChange, provider }: AddSharedProviderDialogProps) {
|
||||
const scrollableContentRef = useRef<HTMLDivElement>(null);
|
||||
const [agreedToTerms, setAgreedToTerms] = useState(false);
|
||||
|
||||
@@ -32,7 +32,6 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
|
||||
const preset = AI_PROVIDER_PRESETS.find(
|
||||
p => p.id === provider.id && p.baseURL === provider.baseURL
|
||||
);
|
||||
const providerName = preset?.name || provider.id;
|
||||
|
||||
const handleAddProvider = () => {
|
||||
setProvider(provider);
|
||||
@@ -69,7 +68,7 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-2xl font-bold">Already Configured</h2>
|
||||
<p className="text-muted-foreground max-w-md mx-auto">
|
||||
You already have {providerName} configured with the same settings.
|
||||
You already have {provider.name} configured with the same settings.
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => onOpenChange(false)} className="gap-2">
|
||||
@@ -164,9 +163,9 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
|
||||
/>
|
||||
</div>
|
||||
<div className="text-center space-y-2">
|
||||
<h2 className="text-2xl font-bold">{providerName}</h2>
|
||||
<h2 className="text-2xl font-bold">{provider.name}</h2>
|
||||
<p className="text-muted-foreground max-w-md mx-auto">
|
||||
Add {providerName} to your configuration?
|
||||
Add {provider.name} to your configuration?
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -183,7 +182,7 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
|
||||
htmlFor="agree-provider-terms"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||
>
|
||||
I agree to {providerName}'s{' '}
|
||||
I agree to {provider.name}'s{' '}
|
||||
<a
|
||||
href={preset.tosURL}
|
||||
target="_blank"
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ReactNode, useEffect } from 'react';
|
||||
import { z } from 'zod';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext';
|
||||
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata, type GraspMetadata } from '@/contexts/AppContext';
|
||||
import i18n from '@/lib/i18n';
|
||||
|
||||
interface AppProviderProps {
|
||||
@@ -22,6 +22,14 @@ const RelayMetadataSchema = z.object({
|
||||
updatedAt: z.number(),
|
||||
}) satisfies z.ZodType<RelayMetadata>;
|
||||
|
||||
// Zod schema for GraspMetadata
|
||||
const GraspMetadataSchema = z.object({
|
||||
relays: z.array(z.object({
|
||||
url: z.string().url(),
|
||||
})),
|
||||
updatedAt: z.number(),
|
||||
}) satisfies z.ZodType<GraspMetadata>;
|
||||
|
||||
// Zod schema for ProjectTemplate
|
||||
const ProjectTemplateSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
@@ -33,15 +41,17 @@ const ProjectTemplateSchema = z.object({
|
||||
const AppConfigSchema = z.object({
|
||||
theme: z.enum(['dark', 'light', 'system']),
|
||||
relayMetadata: RelayMetadataSchema,
|
||||
graspMetadata: GraspMetadataSchema,
|
||||
templates: z.array(ProjectTemplateSchema),
|
||||
esmUrl: z.string().url(),
|
||||
corsProxy: z.string().url(),
|
||||
gitProxyOrigins: z.array(z.string()),
|
||||
faviconUrl: z.string().url(),
|
||||
ngitWebUrl: z.string().url(),
|
||||
previewDomain: z.string().min(1),
|
||||
language: z.string(),
|
||||
showcaseEnabled: z.boolean(),
|
||||
showcaseModerator: z.string(),
|
||||
ngitServers: z.array(z.string()),
|
||||
fsPathProjects: z.string().min(1),
|
||||
fsPathConfig: z.string().min(1),
|
||||
fsPathTmp: z.string().min(1),
|
||||
@@ -80,13 +90,6 @@ export function AppProvider(props: AppProviderProps) {
|
||||
// Merge default config with stored config
|
||||
const config = { ...defaultConfig, ...rawConfig };
|
||||
|
||||
// Expand filesystem paths
|
||||
config.fsPathConfig = expandPath(config.fsPathConfig);
|
||||
config.fsPathProjects = expandPath(config.fsPathProjects);
|
||||
config.fsPathTmp = expandPath(config.fsPathTmp);
|
||||
config.fsPathPlugins = expandPath(config.fsPathPlugins);
|
||||
config.fsPathTemplates = expandPath(config.fsPathTemplates);
|
||||
|
||||
const appContextValue: AppContextType = {
|
||||
config,
|
||||
defaultConfig,
|
||||
@@ -154,18 +157,4 @@ function useApplyLanguage(language?: string): void {
|
||||
useEffect(() => {
|
||||
i18n.changeLanguage(language ?? navigator.language);
|
||||
}, [language]);
|
||||
}
|
||||
|
||||
/** Expand FS paths with the user's home directory, if available. */
|
||||
function expandPath(path: string): string {
|
||||
const homedir = window.electron?.homedir;
|
||||
if (!homedir) {
|
||||
return path;
|
||||
} else if (path.startsWith('~/')) {
|
||||
return homedir + path.slice(1);
|
||||
} else if (path === '~') {
|
||||
return homedir;
|
||||
} else {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
@@ -35,25 +35,51 @@ export function AppShowcase() {
|
||||
}, [config.showcaseModerator]);
|
||||
const isModerator = user?.pubkey === MODERATOR_HEX;
|
||||
|
||||
// Filter and shuffle submissions - memoized with stable dependency
|
||||
const { templateApps, featuredApps, approvedApps } = useMemo(() => {
|
||||
// Filter visible submissions
|
||||
const visibleSubmissions = submissions.filter(app => !app.isHidden);
|
||||
|
||||
// Separate template apps from other apps
|
||||
const templates = shuffleArray(visibleSubmissions.filter(app => app.appTags.includes('Template')));
|
||||
const nonTemplateSubmissions = visibleSubmissions.filter(app => !app.appTags.includes('Template'));
|
||||
|
||||
// Shuffle featured and approved apps for random display order
|
||||
const featured = shuffleArray(nonTemplateSubmissions.filter(app => app.isFeatured));
|
||||
const approved = shuffleArray(nonTemplateSubmissions.filter(app => app.isApproved && !app.isFeatured));
|
||||
|
||||
// Categorize and organize submissions - single pass for efficiency
|
||||
const {
|
||||
displayedFeaturedApps,
|
||||
displayedTemplateApps,
|
||||
moreApps
|
||||
} = useMemo(() => {
|
||||
const DISPLAY_LIMIT = 6;
|
||||
|
||||
// Single pass categorization
|
||||
const templates: typeof submissions = [];
|
||||
const featured: typeof submissions = [];
|
||||
const approved: typeof submissions = [];
|
||||
|
||||
for (const app of submissions) {
|
||||
if (app.isHidden) continue;
|
||||
|
||||
const isTemplate = app.appTags.includes('Template');
|
||||
const isFeatured = app.isFeatured;
|
||||
const isApproved = app.isApproved;
|
||||
|
||||
if (isTemplate) {
|
||||
templates.push(app);
|
||||
} else if (isFeatured) {
|
||||
featured.push(app);
|
||||
} else if (isApproved) {
|
||||
approved.push(app);
|
||||
}
|
||||
}
|
||||
|
||||
// Shuffle each category once
|
||||
const shuffledTemplates = shuffleArray(templates);
|
||||
const shuffledFeatured = shuffleArray(featured);
|
||||
const shuffledApproved = shuffleArray(approved);
|
||||
|
||||
// Split into display and more sections
|
||||
return {
|
||||
templateApps: templates,
|
||||
featuredApps: featured,
|
||||
approvedApps: approved,
|
||||
displayedFeaturedApps: shuffledFeatured.slice(0, DISPLAY_LIMIT),
|
||||
displayedTemplateApps: shuffledTemplates.slice(0, DISPLAY_LIMIT),
|
||||
moreApps: [
|
||||
...shuffledFeatured.slice(DISPLAY_LIMIT),
|
||||
...shuffledTemplates.slice(DISPLAY_LIMIT),
|
||||
...shuffledApproved,
|
||||
],
|
||||
};
|
||||
}, [submissions]); // Only depend on submissions, not intermediate filtered arrays
|
||||
}, [submissions]);
|
||||
|
||||
// Don't show showcase if disabled in settings
|
||||
if (!config.showcaseEnabled) {
|
||||
@@ -124,7 +150,7 @@ export function AppShowcase() {
|
||||
{/* Apps Grid */}
|
||||
<div className="space-y-12">
|
||||
{/* Featured Apps */}
|
||||
{featuredApps.length > 0 && (
|
||||
{displayedFeaturedApps.length > 0 && (
|
||||
<div>
|
||||
<div className="flex items-start gap-3 mb-6">
|
||||
<div className="flex-none w-8 h-8 bg-yellow-100 dark:bg-yellow-900/30 rounded-lg flex items-center justify-center">
|
||||
@@ -136,7 +162,7 @@ export function AppShowcase() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{featuredApps.slice(0, 6).map((app) => (
|
||||
{displayedFeaturedApps.map((app) => (
|
||||
<AppShowcaseCard
|
||||
key={app.id}
|
||||
app={app}
|
||||
@@ -149,7 +175,7 @@ export function AppShowcase() {
|
||||
)}
|
||||
|
||||
{/* Templates Section */}
|
||||
{templateApps.length > 0 && (
|
||||
{displayedTemplateApps.length > 0 && (
|
||||
<div>
|
||||
<div className="flex items-start gap-3 mb-6">
|
||||
<div className="flex-none w-8 h-8 bg-purple-100 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
|
||||
@@ -161,7 +187,7 @@ export function AppShowcase() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{templateApps.slice(0, 6).map((app) => (
|
||||
{displayedTemplateApps.map((app) => (
|
||||
<AppShowcaseCard
|
||||
key={app.id}
|
||||
app={app}
|
||||
@@ -173,8 +199,8 @@ export function AppShowcase() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* More Apps (Approved) - Collapsible */}
|
||||
{approvedApps.length > 0 && (
|
||||
{/* More Apps (Remaining Featured, Templates, and Approved) - Collapsible */}
|
||||
{moreApps.length > 0 && (
|
||||
<div>
|
||||
<Collapsible open={showAllApps} onOpenChange={setShowAllApps}>
|
||||
<CollapsibleTrigger asChild>
|
||||
@@ -185,7 +211,7 @@ export function AppShowcase() {
|
||||
</div>
|
||||
<div className="text-left">
|
||||
<h3 className="text-xl font-bold text-foreground">
|
||||
{t('moreAppsCount', { count: approvedApps.length })}
|
||||
{t('moreAppsCount', { count: moreApps.length })}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{showAllApps ? t('clickToCollapse') : t('clickToViewMore')}
|
||||
@@ -196,7 +222,7 @@ export function AppShowcase() {
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{approvedApps.map((app) => (
|
||||
{moreApps.map((app) => (
|
||||
<AppShowcaseCard
|
||||
key={app.id}
|
||||
app={app}
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { BranchSwitcher } from './BranchSwitcher';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Mock hooks
|
||||
vi.mock('@/hooks/useGitStatus', () => ({
|
||||
useGitStatus: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useGit', () => ({
|
||||
useGit: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useFSPaths', () => ({
|
||||
useFSPaths: vi.fn(() => ({
|
||||
projectsPath: '/projects',
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useToast', () => ({
|
||||
useToast: vi.fn(() => ({
|
||||
toast: vi.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
|
||||
describe('BranchSwitcher', () => {
|
||||
const mockGit = {
|
||||
checkout: vi.fn(),
|
||||
branch: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(useGit as ReturnType<typeof vi.fn>).mockReturnValue({ git: mockGit });
|
||||
});
|
||||
|
||||
it('should not render when not in a git repository', () => {
|
||||
(useGitStatus as ReturnType<typeof vi.fn>).mockReturnValue({
|
||||
data: {
|
||||
isGitRepo: false,
|
||||
currentBranch: null,
|
||||
branches: [],
|
||||
},
|
||||
});
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<BranchSwitcher projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('should render branch switcher button when in a git repository', () => {
|
||||
(useGitStatus as ReturnType<typeof vi.fn>).mockReturnValue({
|
||||
data: {
|
||||
isGitRepo: true,
|
||||
currentBranch: 'main',
|
||||
branches: ['main', 'develop'],
|
||||
hasUncommittedChanges: false,
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<BranchSwitcher projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button')).toBeInTheDocument();
|
||||
expect(screen.getByText('main')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show dropdown menu when clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
(useGitStatus as ReturnType<typeof vi.fn>).mockReturnValue({
|
||||
data: {
|
||||
isGitRepo: true,
|
||||
currentBranch: 'main',
|
||||
branches: ['main', 'develop', 'feature/test'],
|
||||
hasUncommittedChanges: false,
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<BranchSwitcher projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
await user.click(button);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Switch Branch')).toBeInTheDocument();
|
||||
expect(screen.getByText('develop')).toBeInTheDocument();
|
||||
expect(screen.getByText('feature/test')).toBeInTheDocument();
|
||||
expect(screen.getByText('Create new branch')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should show current branch with checkmark', async () => {
|
||||
const user = userEvent.setup();
|
||||
(useGitStatus as ReturnType<typeof vi.fn>).mockReturnValue({
|
||||
data: {
|
||||
isGitRepo: true,
|
||||
currentBranch: 'main',
|
||||
branches: ['main', 'develop'],
|
||||
hasUncommittedChanges: false,
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<BranchSwitcher projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
await user.click(button);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Switch Branch')).toBeInTheDocument();
|
||||
expect(screen.getByText('develop')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should open create branch dialog when clicking create new branch', async () => {
|
||||
const user = userEvent.setup();
|
||||
(useGitStatus as ReturnType<typeof vi.fn>).mockReturnValue({
|
||||
data: {
|
||||
isGitRepo: true,
|
||||
currentBranch: 'main',
|
||||
branches: ['main'],
|
||||
hasUncommittedChanges: false,
|
||||
},
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<BranchSwitcher projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
await user.click(button);
|
||||
|
||||
const createButton = await screen.findByText('Create new branch');
|
||||
await user.click(createButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Create New Branch')).toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText('feature/my-new-feature')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle branch creation', async () => {
|
||||
const user = userEvent.setup();
|
||||
(useGitStatus as ReturnType<typeof vi.fn>).mockReturnValue({
|
||||
data: {
|
||||
isGitRepo: true,
|
||||
currentBranch: 'main',
|
||||
branches: ['main'],
|
||||
hasUncommittedChanges: false,
|
||||
},
|
||||
});
|
||||
|
||||
mockGit.branch.mockResolvedValue(undefined);
|
||||
mockGit.checkout.mockResolvedValue(undefined);
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<BranchSwitcher projectId="test-project" />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dropdown
|
||||
const button = screen.getByRole('button');
|
||||
await user.click(button);
|
||||
|
||||
// Click create new branch
|
||||
const createButton = await screen.findByText('Create new branch');
|
||||
await user.click(createButton);
|
||||
|
||||
// Enter branch name
|
||||
const input = await screen.findByPlaceholderText('feature/my-new-feature');
|
||||
await user.type(input, 'feature/new-branch');
|
||||
|
||||
// Click create button
|
||||
const createBranchButton = screen.getByRole('button', { name: /Create Branch/i });
|
||||
await user.click(createBranchButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockGit.branch).toHaveBeenCalledWith({
|
||||
dir: '/projects/test-project',
|
||||
ref: 'feature/new-branch',
|
||||
});
|
||||
expect(mockGit.checkout).toHaveBeenCalledWith({
|
||||
dir: '/projects/test-project',
|
||||
ref: 'feature/new-branch',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { GitBranch, Check, Plus, Loader2 } from 'lucide-react';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface BranchSwitcherProps {
|
||||
projectId: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function BranchSwitcher({ projectId, className }: BranchSwitcherProps) {
|
||||
const [isCreatingBranch, setIsCreatingBranch] = useState(false);
|
||||
const [newBranchName, setNewBranchName] = useState('');
|
||||
const [isSwitching, setIsSwitching] = useState(false);
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
|
||||
const { data: gitStatus } = useGitStatus(projectId);
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const handleSwitchBranch = async (branchName: string) => {
|
||||
if (!gitStatus?.currentBranch || branchName === gitStatus.currentBranch) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for uncommitted changes
|
||||
if (gitStatus.hasUncommittedChanges) {
|
||||
toast({
|
||||
title: "Uncommitted changes",
|
||||
description: "Please commit or discard your changes before switching branches.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSwitching(true);
|
||||
|
||||
try {
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: branchName,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: "Branch switched",
|
||||
description: `Switched to branch "${branchName}"`,
|
||||
});
|
||||
|
||||
// Invalidate git status to refresh the UI
|
||||
await queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
|
||||
} catch (error) {
|
||||
console.error('Failed to switch branch:', error);
|
||||
toast({
|
||||
title: "Failed to switch branch",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSwitching(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateBranch = async () => {
|
||||
if (!newBranchName.trim()) {
|
||||
toast({
|
||||
title: "Invalid branch name",
|
||||
description: "Branch name cannot be empty",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate branch name (basic validation)
|
||||
if (!/^[a-zA-Z0-9_\-/.]+$/.test(newBranchName)) {
|
||||
toast({
|
||||
title: "Invalid branch name",
|
||||
description: "Branch name can only contain letters, numbers, hyphens, underscores, slashes, and dots",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if branch already exists
|
||||
if (gitStatus?.branches.includes(newBranchName)) {
|
||||
toast({
|
||||
title: "Branch already exists",
|
||||
description: `A branch named "${newBranchName}" already exists`,
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCreating(true);
|
||||
|
||||
try {
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
// Create new branch
|
||||
await git.branch({
|
||||
dir: projectPath,
|
||||
ref: newBranchName,
|
||||
});
|
||||
|
||||
// Switch to the new branch
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: newBranchName,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: "Branch created",
|
||||
description: `Created and switched to branch "${newBranchName}"`,
|
||||
});
|
||||
|
||||
// Close dialog and reset state
|
||||
setIsCreatingBranch(false);
|
||||
setNewBranchName('');
|
||||
|
||||
// Invalidate git status to refresh the UI
|
||||
await queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
|
||||
} catch (error) {
|
||||
console.error('Failed to create branch:', error);
|
||||
toast({
|
||||
title: "Failed to create branch",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Don't show if not a git repo
|
||||
if (!gitStatus?.isGitRepo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentBranch = gitStatus.currentBranch || 'main';
|
||||
const branches = gitStatus.branches || [];
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className={cn("gap-1 sm:gap-2 hover:bg-secondary/10 hover:border-secondary/20", className)}
|
||||
disabled={isSwitching}
|
||||
>
|
||||
{isSwitching ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<GitBranch className="h-4 w-4" />
|
||||
)}
|
||||
<span className=" max-w-[120px] truncate">{currentBranch}</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
<DropdownMenuLabel>Switch Branch</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{branches.length > 0 ? (
|
||||
branches.map((branch) => (
|
||||
<DropdownMenuItem
|
||||
key={branch}
|
||||
onClick={() => handleSwitchBranch(branch)}
|
||||
disabled={branch === currentBranch || isSwitching}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<span className="truncate">{branch}</span>
|
||||
{branch === currentBranch && (
|
||||
<Check className="h-4 w-4 ml-2 shrink-0 text-primary" />
|
||||
)}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
))
|
||||
) : (
|
||||
<DropdownMenuItem disabled>No branches found</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => setIsCreatingBranch(true)}
|
||||
disabled={isSwitching}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Create new branch
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<Dialog open={isCreatingBranch} onOpenChange={setIsCreatingBranch}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create New Branch</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create a new branch from the current branch "{currentBranch}".
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="branch-name">Branch name</Label>
|
||||
<Input
|
||||
id="branch-name"
|
||||
placeholder="feature/my-new-feature"
|
||||
value={newBranchName}
|
||||
onChange={(e) => setNewBranchName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleCreateBranch();
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setIsCreatingBranch(false);
|
||||
setNewBranchName('');
|
||||
}}
|
||||
disabled={isCreating}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleCreateBranch} disabled={isCreating}>
|
||||
{isCreating ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GitBranch className="h-4 w-4 mr-2" />
|
||||
Create Branch
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -30,7 +30,8 @@ describe('CreditsBadge', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('$10.50')).toBeInTheDocument();
|
||||
// Credits are formatted as whole dollars (10.50 rounds to $11)
|
||||
expect(screen.getByText('$11')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onOpenDialog when badge is clicked', () => {
|
||||
@@ -45,7 +46,7 @@ describe('CreditsBadge', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const badge = screen.getByText('$10.50');
|
||||
const badge = screen.getByText('$11');
|
||||
fireEvent.click(badge);
|
||||
|
||||
expect(mockCallback).toHaveBeenCalled();
|
||||
@@ -58,7 +59,7 @@ describe('CreditsBadge', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const badge = screen.getByText('$10.50');
|
||||
const badge = screen.getByText('$11');
|
||||
expect(badge).toHaveClass('cursor-pointer');
|
||||
expect(badge).toHaveClass('hover:bg-secondary/80');
|
||||
});
|
||||
|
||||
@@ -28,8 +28,8 @@ export function CreditsBadge({ provider, className, onOpenDialog }: CreditsBadge
|
||||
const formattedAmount = new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 0,
|
||||
}).format(credits.amount);
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { CreditsDialog } from './CreditsDialog';
|
||||
import { AIProviderConfigDialog } from './AIProviderConfigDialog';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
// Mock useAICredits to return credits data
|
||||
vi.mock('@/hooks/useAICredits', () => ({
|
||||
useAICredits: () => ({
|
||||
data: { amount: 10.50 },
|
||||
error: null,
|
||||
isLoading: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock the fetch function
|
||||
global.fetch = vi.fn();
|
||||
|
||||
@@ -15,30 +24,42 @@ const mockProvider: AIProvider = {
|
||||
nostr: false,
|
||||
};
|
||||
|
||||
describe('CreditsDialog', () => {
|
||||
it('renders dialog when open', () => {
|
||||
describe('AIProviderConfigDialog - Credits Tab', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders dialog when open with credits tab', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
<AIProviderConfigDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
provider={mockProvider}
|
||||
onUpdate={() => {}}
|
||||
onRemove={() => {}}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Credits')).toBeInTheDocument();
|
||||
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
|
||||
// Wait for the dialog to render with tabs
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('tab', { name: /credits/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText('Buy Credits')).toBeInTheDocument();
|
||||
expect(screen.getByText('Recent Transactions')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render when closed', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
<AIProviderConfigDialog
|
||||
open={false}
|
||||
onOpenChange={() => {}}
|
||||
provider={mockProvider}
|
||||
onUpdate={() => {}}
|
||||
onRemove={() => {}}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
@@ -46,49 +67,71 @@ describe('CreditsDialog', () => {
|
||||
expect(screen.queryByText('Credits')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows payment method options', () => {
|
||||
it('shows payment method options', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
<AIProviderConfigDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
provider={mockProvider}
|
||||
onUpdate={() => {}}
|
||||
onRemove={() => {}}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Payment Method')).toBeInTheDocument();
|
||||
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
|
||||
// Wait for accordion to be available and click to expand
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Buy Credits')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// The content is in an accordion that needs to be expanded
|
||||
// Check for accordion trigger text instead
|
||||
expect(screen.getByText('Buy Credits')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows preset amount buttons', () => {
|
||||
it('shows preset amount buttons', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
<AIProviderConfigDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
provider={mockProvider}
|
||||
onUpdate={() => {}}
|
||||
onRemove={() => {}}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('$5')).toBeInTheDocument();
|
||||
expect(screen.getByText('$10')).toBeInTheDocument();
|
||||
expect(screen.getByText('$25')).toBeInTheDocument();
|
||||
expect(screen.getByText('$50')).toBeInTheDocument();
|
||||
expect(screen.getByText('$100')).toBeInTheDocument();
|
||||
// Wait for the Buy Credits accordion to be visible
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Buy Credits')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click the accordion to expand it (accordions default to closed)
|
||||
const buyCreditsButton = screen.getByText('Buy Credits');
|
||||
buyCreditsButton.click();
|
||||
|
||||
// Now the preset buttons should be visible
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('$5')).toBeInTheDocument();
|
||||
expect(screen.getByText('$10')).toBeInTheDocument();
|
||||
expect(screen.getByText('$25')).toBeInTheDocument();
|
||||
expect(screen.getByText('$50')).toBeInTheDocument();
|
||||
expect(screen.getByText('$100')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
it('calls onDialogStateChange callback when dialog state changes', () => {
|
||||
it('calls onDialogStateChange callback when dialog state changes', async () => {
|
||||
const mockCallback = vi.fn();
|
||||
const { rerender } = render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
<AIProviderConfigDialog
|
||||
open={false}
|
||||
onOpenChange={mockCallback}
|
||||
provider={mockProvider}
|
||||
onUpdate={() => {}}
|
||||
onRemove={() => {}}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
@@ -96,14 +139,19 @@ describe('CreditsDialog', () => {
|
||||
// Simulate opening the dialog
|
||||
rerender(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
<AIProviderConfigDialog
|
||||
open={true}
|
||||
onOpenChange={mockCallback}
|
||||
provider={mockProvider}
|
||||
onUpdate={() => {}}
|
||||
onRemove={() => {}}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Credits')).toBeInTheDocument();
|
||||
// Wait for the Credits tab to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('tab', { name: /credits/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
interface DeleteProjectDialogProps {
|
||||
projectName: string;
|
||||
onDelete: () => void | Promise<void>;
|
||||
isDeleting: boolean;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
trigger?: ReactNode;
|
||||
}
|
||||
|
||||
export function DeleteProjectDialog({
|
||||
projectName,
|
||||
onDelete,
|
||||
isDeleting,
|
||||
open,
|
||||
onOpenChange,
|
||||
trigger,
|
||||
}: DeleteProjectDialogProps) {
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={onOpenChange}>
|
||||
{trigger && <AlertDialogTrigger asChild>{trigger}</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={onDelete}
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Bot, GripVertical } from 'lucide-react';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { ReactNode } from 'react';
|
||||
import { useSortable } from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
|
||||
interface DraggableProviderTileProps {
|
||||
id: string;
|
||||
icon?: ReactNode;
|
||||
iconUrl?: string | null;
|
||||
name: string;
|
||||
onClick: () => void;
|
||||
badge?: ReactNode;
|
||||
}
|
||||
|
||||
export function DraggableProviderTile({ id, icon, iconUrl, name, onClick, badge }: DraggableProviderTileProps) {
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
setNodeRef,
|
||||
transform,
|
||||
transition,
|
||||
isDragging,
|
||||
} = useSortable({ id });
|
||||
|
||||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
opacity: isDragging ? 0.5 : 1,
|
||||
};
|
||||
|
||||
return (
|
||||
<div ref={setNodeRef} style={style} className="relative group">
|
||||
<button
|
||||
onClick={onClick}
|
||||
className="flex flex-col items-center justify-center gap-2 p-4 rounded-lg border bg-card hover:bg-muted transition-colors text-center h-[120px] w-full relative"
|
||||
>
|
||||
{iconUrl ? (
|
||||
<ExternalFavicon
|
||||
url={iconUrl}
|
||||
size={32}
|
||||
fallback={icon || <Bot size={32} />}
|
||||
/>
|
||||
) : (
|
||||
icon || <Bot size={32} />
|
||||
)}
|
||||
<span className="text-sm font-medium line-clamp-2 overflow-hidden max-w-full text-ellipsis">
|
||||
{name}
|
||||
</span>
|
||||
{badge && (
|
||||
<div className="absolute top-0 right-0">
|
||||
{badge}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
<div
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
className="absolute top-1 right-1 p-1 cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 transition-opacity bg-background/80 rounded hover:bg-muted"
|
||||
title="Drag to reorder"
|
||||
>
|
||||
<GripVertical size={16} className="text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { faviconUrl, normalizeUrl } from '@/lib/faviconUrl';
|
||||
import { faviconUrl } from '@/lib/faviconUrl';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ReactNode, useMemo } from 'react';
|
||||
|
||||
interface ExternalFaviconProps {
|
||||
/** The URL to fetch the favicon for */
|
||||
url: string;
|
||||
url: string | URL | undefined;
|
||||
/** Size of the favicon in pixels */
|
||||
size?: number;
|
||||
/** Fallback element to display if favicon fails to load */
|
||||
@@ -28,10 +28,15 @@ export function ExternalFavicon({
|
||||
|
||||
// Generate the favicon URL using the configured template
|
||||
const faviconSrc = useMemo(() => {
|
||||
if (!url) return;
|
||||
try {
|
||||
const parsedUrl = new URL(url);
|
||||
|
||||
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
|
||||
parsedUrl.hostname = parsedUrl.hostname.replace(/^(ai\.|api\.)/, '');
|
||||
|
||||
// Normalize the URL to ensure it has a protocol
|
||||
const normalizedUrl = normalizeUrl(url);
|
||||
return faviconUrl(config.faviconUrl, normalizedUrl);
|
||||
return faviconUrl(config.faviconUrl, parsedUrl);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Trash2, GitBranch } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import type { GitCredential } from '@/contexts/GitSettingsContext';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
|
||||
interface GitCredentialConfigDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
credential: GitCredential;
|
||||
onUpdate: (credential: GitCredential) => void;
|
||||
onRemove: () => void;
|
||||
isCustom?: boolean;
|
||||
}
|
||||
|
||||
export function GitCredentialConfigDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
credential,
|
||||
onUpdate,
|
||||
onRemove,
|
||||
isCustom = false,
|
||||
}: GitCredentialConfigDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [localCredential, setLocalCredential] = useState(credential);
|
||||
|
||||
// Reset local state when credential changes or dialog opens
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setLocalCredential(credential);
|
||||
}
|
||||
}, [credential, open]);
|
||||
|
||||
const handleSave = () => {
|
||||
onUpdate(localCredential);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const handleDelete = () => {
|
||||
onRemove();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalFavicon
|
||||
url={localCredential.origin}
|
||||
size={20}
|
||||
fallback={<GitBranch size={20} />}
|
||||
/>
|
||||
<DialogTitle>{localCredential.name}</DialogTitle>
|
||||
{isCustom && <Badge variant="outline">{t('custom')}</Badge>}
|
||||
</div>
|
||||
<DialogDescription>
|
||||
Configure your Git credentials
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="credential-name">
|
||||
{t('name')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="credential-name"
|
||||
placeholder="GitHub"
|
||||
value={localCredential.name}
|
||||
onChange={(e) => setLocalCredential({ ...localCredential, name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="credential-origin">
|
||||
{t('origin')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="credential-origin"
|
||||
placeholder="https://github.com"
|
||||
value={localCredential.origin}
|
||||
onChange={(e) => setLocalCredential({ ...localCredential, origin: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="credential-username">
|
||||
{t('username')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="credential-username"
|
||||
placeholder="git"
|
||||
value={localCredential.username}
|
||||
onChange={(e) => setLocalCredential({ ...localCredential, username: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="credential-password">
|
||||
{t('password')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<PasswordInput
|
||||
id="credential-password"
|
||||
placeholder={t('enterPassword')}
|
||||
value={localCredential.password}
|
||||
onChange={(e) => setLocalCredential({ ...localCredential, password: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="gap-2">
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleDelete}
|
||||
className="sm:mr-auto"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
{t('delete')}
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
{t('save')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,245 +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,
|
||||
remoteBranchExists: false,
|
||||
};
|
||||
|
||||
vi.mock('@/hooks/useGitStatus', () => ({
|
||||
useGitStatus: () => mockUseGitStatus(),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useFS', () => ({
|
||||
useFS: vi.fn(() => ({
|
||||
fs: {},
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useToast', () => ({
|
||||
useToast: vi.fn(() => ({
|
||||
toast: vi.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
const mockUseGitSettings = vi.fn();
|
||||
|
||||
vi.mock('@/hooks/useGitSettings', () => ({
|
||||
useGitSettings: () => mockUseGitSettings(),
|
||||
}));
|
||||
|
||||
describe('GitDialog', () => {
|
||||
beforeEach(() => {
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: baseGitStatus,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {
|
||||
'https://github.com': {
|
||||
username: 'git',
|
||||
password: 'github-token',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('renders git dialog without repository information section', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Repository')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Repository Information')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
|
||||
});
|
||||
|
||||
it('shows sync status when branch is published', () => {
|
||||
// Mock git status with published branch
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
remoteBranchExists: true,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
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 and branch is published', () => {
|
||||
// Mock git status with published branch and no commits ahead
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
ahead: 0,
|
||||
remoteBranchExists: true,
|
||||
},
|
||||
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')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('enables push and disables pull when branch is not published', () => {
|
||||
// Mock git status with unpublished branch (has commits but no remote branch)
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
ahead: 0,
|
||||
remoteBranchExists: false,
|
||||
totalCommits: 5,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
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('Branch not published')).toBeInTheDocument();
|
||||
|
||||
const pushButton = screen.getByText('Push');
|
||||
expect(pushButton).toBeInTheDocument();
|
||||
expect(pushButton.closest('button')).not.toBeDisabled();
|
||||
|
||||
const pullButton = screen.getByText('Pull');
|
||||
expect(pullButton).toBeInTheDocument();
|
||||
expect(pullButton.closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('does not show credentials warning when credentials are configured', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should not show warning when credentials are configured
|
||||
expect(screen.queryByText(/No credentials configured/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
|
||||
});
|
||||
|
||||
it('shows credentials warning when no credentials are configured', () => {
|
||||
// Mock git settings with no credentials and mock git status with an https remote
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {},
|
||||
},
|
||||
});
|
||||
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }],
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show warning when credentials are missing
|
||||
expect(screen.getByText(/You are not logged into github.com/)).toBeInTheDocument();
|
||||
expect(screen.getByText('log in')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -14,35 +14,49 @@ vi.mock('@/lib/configUtils', () => ({
|
||||
|
||||
// Test component that uses the hook
|
||||
function TestComponent() {
|
||||
const { settings, addCredential, removeCredential, updateCredential, isConfigured } = useGitSettings();
|
||||
const { settings, addCredential, removeCredential, setCredentials, isConfigured } = useGitSettings();
|
||||
|
||||
const handleAdd = () => {
|
||||
const credential: GitCredential = {
|
||||
id: crypto.randomUUID(),
|
||||
name: 'GitHub',
|
||||
origin: 'https://github.com',
|
||||
username: 'git',
|
||||
password: 'test-token',
|
||||
};
|
||||
addCredential('https://github.com', credential);
|
||||
addCredential(credential);
|
||||
};
|
||||
|
||||
const handleUpdate = () => {
|
||||
updateCredential('https://github.com', { password: 'updated-token' });
|
||||
const githubCred = settings.credentials.find(c => c.origin === 'https://github.com');
|
||||
if (githubCred) {
|
||||
const updatedCredentials = settings.credentials.map((cred) =>
|
||||
cred.id === githubCred.id ? { ...cred, password: 'updated-token' } : cred
|
||||
);
|
||||
setCredentials(updatedCredentials);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemove = () => {
|
||||
removeCredential('https://github.com');
|
||||
const githubCred = settings.credentials.find(c => c.origin === 'https://github.com');
|
||||
if (githubCred) {
|
||||
removeCredential(githubCred.id);
|
||||
}
|
||||
};
|
||||
|
||||
const githubCred = settings.credentials.find(c => c.origin === 'https://github.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="count">{settings.credentials.length}</div>
|
||||
<button onClick={handleAdd}>Add GitHub</button>
|
||||
<button onClick={handleUpdate}>Update GitHub</button>
|
||||
<button onClick={handleRemove}>Remove GitHub</button>
|
||||
{settings.credentials['https://github.com'] && (
|
||||
{githubCred && (
|
||||
<div data-testid="github-creds">
|
||||
{settings.credentials['https://github.com'].username}:
|
||||
{settings.credentials['https://github.com'].password}
|
||||
{githubCred.username}:
|
||||
{githubCred.password}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -67,8 +81,7 @@ describe('GitSettingsProvider', () => {
|
||||
// Mock the read function to return default settings
|
||||
const { readGitSettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readGitSettings).mockResolvedValue({
|
||||
credentials: {},
|
||||
hostTokens: {},
|
||||
credentials: [],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -165,12 +178,13 @@ describe('GitSettingsProvider', () => {
|
||||
expect(writeGitSettings).toHaveBeenCalledWith(
|
||||
expect.anything(), // fs instance
|
||||
expect.objectContaining({
|
||||
credentials: {
|
||||
'https://github.com': {
|
||||
credentials: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
origin: 'https://github.com',
|
||||
username: 'git',
|
||||
password: 'test-token',
|
||||
}
|
||||
}
|
||||
})
|
||||
])
|
||||
}),
|
||||
'/config' // configPath
|
||||
);
|
||||
@@ -179,13 +193,15 @@ describe('GitSettingsProvider', () => {
|
||||
|
||||
it('loads settings from VFS', async () => {
|
||||
const settings = {
|
||||
credentials: {
|
||||
'https://gitlab.com': {
|
||||
credentials: [
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
name: 'GitLab',
|
||||
origin: 'https://gitlab.com',
|
||||
username: 'git',
|
||||
password: 'gitlab-token',
|
||||
},
|
||||
},
|
||||
hostTokens: {},
|
||||
],
|
||||
};
|
||||
|
||||
const { readGitSettings } = await import('@/lib/configUtils');
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ReactNode, useState, useEffect } from 'react';
|
||||
import { GitSettingsContext, type GitSettings, type GitCredential, type GitHostToken, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
|
||||
import { GitSettingsContext, type GitSettings, type GitCredential, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { readGitSettings, writeGitSettings } from '@/lib/configUtils';
|
||||
@@ -9,8 +9,7 @@ interface GitSettingsProviderProps {
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: GitSettings = {
|
||||
credentials: {},
|
||||
hostTokens: {},
|
||||
credentials: [],
|
||||
};
|
||||
|
||||
export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
@@ -55,83 +54,35 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
setSettings(prev => ({ ...prev, ...newSettings }));
|
||||
};
|
||||
|
||||
const addCredential = (origin: string, credential: GitCredential) => {
|
||||
const addCredential = (credential: GitCredential) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
credentials: {
|
||||
...prev.credentials,
|
||||
[origin]: credential,
|
||||
},
|
||||
credentials: [...prev.credentials, credential],
|
||||
}));
|
||||
};
|
||||
|
||||
const removeCredential = (origin: string) => {
|
||||
setSettings(prev => {
|
||||
const { [origin]: removed, ...rest } = prev.credentials;
|
||||
return {
|
||||
...prev,
|
||||
credentials: rest,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const updateCredential = (origin: string, credential: Partial<GitCredential>) => {
|
||||
const removeCredential = (id: string) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
credentials: {
|
||||
...prev.credentials,
|
||||
[origin]: {
|
||||
...prev.credentials[origin],
|
||||
...credential,
|
||||
},
|
||||
},
|
||||
credentials: prev.credentials.filter((cred) => cred.id !== id),
|
||||
}));
|
||||
};
|
||||
|
||||
const addHostToken = (host: string, token: GitHostToken) => {
|
||||
const setCredentials = (credentials: GitCredential[]) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
hostTokens: {
|
||||
...prev.hostTokens,
|
||||
[host]: token,
|
||||
},
|
||||
credentials,
|
||||
}));
|
||||
};
|
||||
|
||||
const removeHostToken = (host: string) => {
|
||||
setSettings(prev => {
|
||||
const { [host]: removed, ...rest } = prev.hostTokens;
|
||||
return {
|
||||
...prev,
|
||||
hostTokens: rest,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const updateHostToken = (host: string, token: Partial<GitHostToken>) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
hostTokens: {
|
||||
...prev.hostTokens,
|
||||
[host]: {
|
||||
...prev.hostTokens[host],
|
||||
...token,
|
||||
},
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const isConfigured = Object.entries(settings.credentials).length > 0;
|
||||
const isConfigured = settings.credentials.length > 0;
|
||||
|
||||
const contextValue: GitSettingsContextType = {
|
||||
settings,
|
||||
updateSettings,
|
||||
addCredential,
|
||||
removeCredential,
|
||||
updateCredential,
|
||||
addHostToken,
|
||||
removeHostToken,
|
||||
updateHostToken,
|
||||
setCredentials,
|
||||
isConfigured,
|
||||
isInitialized,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
import { useState, useCallback, ReactNode, useRef } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { GitSyncContext, GitOperation, GitSyncState, FetchResult } from '@/contexts/GitSyncContext';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
|
||||
export function GitSyncProvider({ children }: { children: ReactNode }) {
|
||||
const [syncStates, setSyncStates] = useState<Map<string, GitSyncState>>(new Map());
|
||||
const queryClient = useQueryClient();
|
||||
const { git } = useGit();
|
||||
|
||||
// Track active operations to prevent concurrent operations on the same directory
|
||||
const activeOperations = useRef<Map<string, Promise<unknown>>>(new Map());
|
||||
|
||||
const startOperation = useCallback((dir: string, operation: GitOperation) => {
|
||||
setSyncStates(prev => {
|
||||
const next = new Map(prev);
|
||||
// Clear any previous error when starting a new operation
|
||||
next.set(dir, { dir, operation, isActive: true });
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const endOperation = useCallback((dir: string, error?: Error) => {
|
||||
setSyncStates(prev => {
|
||||
const next = new Map(prev);
|
||||
if (error) {
|
||||
// Keep the state with the error
|
||||
const currentState = prev.get(dir);
|
||||
if (currentState) {
|
||||
next.set(dir, { ...currentState, isActive: false, error });
|
||||
}
|
||||
} else {
|
||||
// Remove the state if no error
|
||||
next.delete(dir);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const setError = useCallback((dir: string, error: Error | null) => {
|
||||
setSyncStates(prev => {
|
||||
const next = new Map(prev);
|
||||
const currentState = prev.get(dir);
|
||||
|
||||
if (error) {
|
||||
// Set or update error
|
||||
if (currentState) {
|
||||
next.set(dir, { ...currentState, error });
|
||||
} else {
|
||||
// Create a new state with just the error (no active operation)
|
||||
next.set(dir, { dir, operation: 'fetch', isActive: false, error });
|
||||
}
|
||||
} else {
|
||||
// Clear error
|
||||
if (currentState) {
|
||||
const { error: _, ...stateWithoutError } = currentState;
|
||||
if (stateWithoutError.isActive) {
|
||||
next.set(dir, stateWithoutError);
|
||||
} else {
|
||||
// If not active and no error, remove the state entirely
|
||||
next.delete(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const getState = useCallback((dir: string) => {
|
||||
return syncStates.get(dir);
|
||||
}, [syncStates]);
|
||||
|
||||
const getError = useCallback((dir: string) => {
|
||||
return syncStates.get(dir)?.error;
|
||||
}, [syncStates]);
|
||||
|
||||
// Helper to invalidate git status queries
|
||||
const invalidateGitStatus = useCallback((dir: string) => {
|
||||
const projectId = dir.split('/').pop();
|
||||
if (projectId) {
|
||||
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
|
||||
}
|
||||
}, [queryClient]);
|
||||
|
||||
// Helper to ensure only one operation runs at a time per directory
|
||||
const withOperationLock = useCallback(async <T,>(
|
||||
dir: string,
|
||||
operation: GitOperation,
|
||||
fn: () => Promise<T>
|
||||
): Promise<T> => {
|
||||
// Check if there's already an active operation for this directory
|
||||
const existingOp = activeOperations.current.get(dir);
|
||||
if (existingOp) {
|
||||
// Wait for the existing operation to complete first
|
||||
await existingOp.catch(() => {
|
||||
// Ignore errors from previous operation
|
||||
});
|
||||
}
|
||||
|
||||
// Start the new operation
|
||||
startOperation(dir, operation);
|
||||
setError(dir, null);
|
||||
|
||||
const promise = fn()
|
||||
.then(result => {
|
||||
endOperation(dir);
|
||||
activeOperations.current.delete(dir);
|
||||
return result;
|
||||
})
|
||||
.catch(err => {
|
||||
const error = err instanceof Error ? err : new Error(`${operation} failed`);
|
||||
endOperation(dir, error);
|
||||
setError(dir, error);
|
||||
activeOperations.current.delete(dir);
|
||||
throw error;
|
||||
});
|
||||
|
||||
activeOperations.current.set(dir, promise);
|
||||
return promise;
|
||||
}, [startOperation, endOperation, setError]);
|
||||
|
||||
// Git operation: fetch
|
||||
const fetch = useCallback(async (dir: string, remote = 'origin'): Promise<FetchResult> => {
|
||||
return withOperationLock(dir, 'fetch', async () => {
|
||||
const fetchResult = await git.fetch({ dir, remote });
|
||||
invalidateGitStatus(dir);
|
||||
return fetchResult;
|
||||
});
|
||||
}, [git, withOperationLock, invalidateGitStatus]);
|
||||
|
||||
// Git operation: pull
|
||||
const pull = useCallback(async (dir: string, ref: string, _remote = 'origin'): Promise<void> => {
|
||||
return withOperationLock(dir, 'pull', async () => {
|
||||
await git.pull({ dir, ref, singleBranch: true });
|
||||
invalidateGitStatus(dir);
|
||||
});
|
||||
}, [git, withOperationLock, invalidateGitStatus]);
|
||||
|
||||
// Git operation: push
|
||||
const push = useCallback(async (dir: string, ref: string, remote = 'origin', force = false): Promise<void> => {
|
||||
return withOperationLock(dir, 'push', async () => {
|
||||
await git.push({ dir, remote, ref, force });
|
||||
invalidateGitStatus(dir);
|
||||
});
|
||||
}, [git, withOperationLock, invalidateGitStatus]);
|
||||
|
||||
// Git operation: sync (pull then push)
|
||||
const sync = useCallback(async (dir: string, ref: string, remote = 'origin'): Promise<void> => {
|
||||
return withOperationLock(dir, 'pull', async () => {
|
||||
const cache = {};
|
||||
|
||||
// Pull first
|
||||
await git.pull({ dir, ref, singleBranch: true, cache });
|
||||
|
||||
// Then push (update operation type)
|
||||
startOperation(dir, 'push');
|
||||
await git.push({ dir, remote, ref, cache });
|
||||
|
||||
invalidateGitStatus(dir);
|
||||
});
|
||||
}, [git, withOperationLock, invalidateGitStatus, startOperation]);
|
||||
|
||||
// Git operation: force pull
|
||||
const forcePull = useCallback(async (dir: string, ref: string, remote = 'origin'): Promise<void> => {
|
||||
return withOperationLock(dir, 'pull', async () => {
|
||||
const cache = {};
|
||||
|
||||
// Step 1: Fetch latest changes from remote
|
||||
await git.fetch({
|
||||
dir,
|
||||
remote,
|
||||
ref,
|
||||
singleBranch: true,
|
||||
cache,
|
||||
});
|
||||
|
||||
// Step 2: Get the remote commit SHA
|
||||
const remoteRef = `refs/remotes/${remote}/${ref}`;
|
||||
const remoteSha = await git.resolveRef({ dir, ref: remoteRef });
|
||||
|
||||
// Step 3: Force update the current branch to point to remote
|
||||
await git.writeRef({
|
||||
dir,
|
||||
ref: `refs/heads/${ref}`,
|
||||
value: remoteSha,
|
||||
force: true,
|
||||
});
|
||||
|
||||
// Step 4: Force checkout all files (overwrite local changes)
|
||||
await git.checkout({
|
||||
dir,
|
||||
ref,
|
||||
force: true,
|
||||
cache,
|
||||
});
|
||||
|
||||
invalidateGitStatus(dir);
|
||||
});
|
||||
}, [git, withOperationLock, invalidateGitStatus]);
|
||||
|
||||
// Git operation: force push
|
||||
const forcePush = useCallback(async (dir: string, ref: string, remote = 'origin'): Promise<void> => {
|
||||
return withOperationLock(dir, 'push', async () => {
|
||||
await git.push({ dir, remote, ref, force: true });
|
||||
invalidateGitStatus(dir);
|
||||
});
|
||||
}, [git, withOperationLock, invalidateGitStatus]);
|
||||
|
||||
return (
|
||||
<GitSyncContext.Provider value={{
|
||||
syncStates,
|
||||
getState,
|
||||
getError,
|
||||
fetch,
|
||||
pull,
|
||||
push,
|
||||
sync,
|
||||
forcePull,
|
||||
forcePush,
|
||||
startOperation,
|
||||
endOperation,
|
||||
setError,
|
||||
}}>
|
||||
{children}
|
||||
</GitSyncContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Plus, X, Server } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
|
||||
export function GraspListManager() {
|
||||
const { config, updateConfig } = useAppContext();
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: publishEvent } = useNostrPublish();
|
||||
|
||||
const [graspRelays, setGraspRelays] = useState<{ url: string }[]>(config.graspMetadata.relays);
|
||||
const [newRelayUrl, setNewRelayUrl] = useState('');
|
||||
|
||||
// Sync local state with config when it changes (e.g., from NostrProvider sync)
|
||||
useEffect(() => {
|
||||
setGraspRelays(config.graspMetadata.relays);
|
||||
}, [config.graspMetadata.relays]);
|
||||
|
||||
const normalizeRelayUrl = (url: string): string => {
|
||||
url = url.trim();
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
// Ensure it's a websocket URL
|
||||
if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
|
||||
parsed.protocol = 'wss:';
|
||||
}
|
||||
// Ensure trailing slash
|
||||
if (!parsed.pathname.endsWith('/')) {
|
||||
parsed.pathname += '/';
|
||||
}
|
||||
return parsed.toString();
|
||||
} catch {
|
||||
// If parsing fails, try to construct a valid URL
|
||||
try {
|
||||
const withProtocol = url.startsWith('ws://') || url.startsWith('wss://')
|
||||
? url
|
||||
: `wss://${url}`;
|
||||
const parsed = new URL(withProtocol);
|
||||
if (!parsed.pathname.endsWith('/')) {
|
||||
parsed.pathname += '/';
|
||||
}
|
||||
return parsed.toString();
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const isValidRelayUrl = (url: string): boolean => {
|
||||
const trimmed = url.trim();
|
||||
if (!trimmed) return false;
|
||||
|
||||
const normalized = normalizeRelayUrl(trimmed);
|
||||
try {
|
||||
const parsed = new URL(normalized);
|
||||
return parsed.protocol === 'ws:' || parsed.protocol === 'wss:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddRelay = () => {
|
||||
if (!isValidRelayUrl(newRelayUrl)) {
|
||||
toast({
|
||||
title: 'Invalid relay URL',
|
||||
description: 'Please enter a valid websocket URL (e.g., wss://git.shakespeare.diy/)',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const normalized = normalizeRelayUrl(newRelayUrl);
|
||||
|
||||
if (graspRelays.some(r => r.url === normalized)) {
|
||||
toast({
|
||||
title: 'Relay already exists',
|
||||
description: 'This relay is already in your list',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const newRelays = [...graspRelays, { url: normalized }];
|
||||
setGraspRelays(newRelays);
|
||||
setNewRelayUrl('');
|
||||
|
||||
saveRelays(newRelays);
|
||||
};
|
||||
|
||||
const handleRemoveRelay = (url: string) => {
|
||||
const newRelays = graspRelays.filter(r => r.url !== url);
|
||||
setGraspRelays(newRelays);
|
||||
saveRelays(newRelays);
|
||||
};
|
||||
|
||||
const saveRelays = (newRelays: { url: string }[]) => {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
// Update local config
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
graspMetadata: {
|
||||
relays: newRelays,
|
||||
updatedAt: now,
|
||||
},
|
||||
}));
|
||||
|
||||
// Publish to Nostr if user is logged in
|
||||
if (user) {
|
||||
publishNIP34GraspList(newRelays);
|
||||
}
|
||||
};
|
||||
|
||||
const publishNIP34GraspList = (relays: { url: string }[]) => {
|
||||
const tags = relays.map(relay => ['g', relay.url]);
|
||||
|
||||
publishEvent(
|
||||
{
|
||||
kind: 10317,
|
||||
content: '',
|
||||
tags,
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast({
|
||||
title: 'Grasp list published',
|
||||
description: 'Your Nostr git server list has been published to your relays',
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('Failed to publish grasp list:', error);
|
||||
toast({
|
||||
title: 'Publish failed',
|
||||
description: 'Failed to publish your grasp server list',
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
const renderRelayUrl = (url: string): string => {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
if (parsed.pathname === '/') {
|
||||
return parsed.host;
|
||||
} else {
|
||||
return parsed.host + parsed.pathname;
|
||||
}
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Relay List */}
|
||||
<div className="space-y-2">
|
||||
{graspRelays.map((relay) => (
|
||||
<div
|
||||
key={relay.url}
|
||||
className="flex items-center gap-2 p-2 rounded-md border bg-muted/20"
|
||||
>
|
||||
<Server className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
<span className="font-mono text-sm flex-1 truncate" title={relay.url}>
|
||||
{renderRelayUrl(relay.url)}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => handleRemoveRelay(relay.url)}
|
||||
className="size-5 text-muted-foreground hover:text-destructive hover:bg-transparent shrink-0"
|
||||
disabled={graspRelays.length <= 1}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Add Relay Form */}
|
||||
<div className="flex gap-2">
|
||||
<div className="flex-1">
|
||||
<Label htmlFor="new-grasp-relay" className="sr-only">
|
||||
Grasp Relay URL
|
||||
</Label>
|
||||
<Input
|
||||
id="new-grasp-relay"
|
||||
placeholder="wss://git.shakespeare.diy/"
|
||||
value={newRelayUrl}
|
||||
onChange={(e) => setNewRelayUrl(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleAddRelay();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleAddRelay}
|
||||
disabled={!newRelayUrl.trim()}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-10 shrink-0"
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{!user && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Log in to sync your grasp server list with Nostr
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,17 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
// Mock useAICredits to return credits data
|
||||
vi.mock('@/hooks/useAICredits', () => ({
|
||||
useAICredits: () => ({
|
||||
data: { amount: 10.50 },
|
||||
error: null,
|
||||
isLoading: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock QRCode
|
||||
vi.mock('qrcode', () => ({
|
||||
default: {
|
||||
@@ -17,7 +26,7 @@ const mockWebLN = {
|
||||
};
|
||||
|
||||
// We need to import the component after mocking
|
||||
const { CreditsDialog } = await import('./CreditsDialog');
|
||||
const { AIProviderConfigDialog } = await import('./AIProviderConfigDialog');
|
||||
|
||||
const mockProvider: AIProvider = {
|
||||
id: 'test-provider',
|
||||
@@ -40,16 +49,20 @@ describe('Lightning Payment', () => {
|
||||
it('shows QR code for Lightning payment', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
<AIProviderConfigDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
provider={mockProvider}
|
||||
onUpdate={() => {}}
|
||||
onRemove={() => {}}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show the normal form initially
|
||||
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
|
||||
// Should show the Credits tab with Buy Credits accordion
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Buy Credits')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows WebLN button when available', async () => {
|
||||
@@ -61,30 +74,38 @@ describe('Lightning Payment', () => {
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
<AIProviderConfigDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
provider={mockProvider}
|
||||
onUpdate={() => {}}
|
||||
onRemove={() => {}}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show the normal form initially
|
||||
expect(screen.getByText('Amount (USD)')).toBeInTheDocument();
|
||||
// Should show the Credits tab with Buy Credits accordion
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Buy Credits')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('displays copy invoice button', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsDialog
|
||||
<AIProviderConfigDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
provider={mockProvider}
|
||||
onUpdate={() => {}}
|
||||
onRemove={() => {}}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show the normal form initially
|
||||
expect(screen.getByText('Payment Method')).toBeInTheDocument();
|
||||
// Should show the Credits tab with Buy Credits accordion
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Buy Credits')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -45,6 +45,7 @@ describe('ModelSelector', () => {
|
||||
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
isLoading: false,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
@@ -91,6 +92,7 @@ describe('ModelSelector', () => {
|
||||
},
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
isLoading: false,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
@@ -154,6 +156,7 @@ describe('ModelSelector', () => {
|
||||
},
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
isLoading: false,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
@@ -213,6 +216,7 @@ describe('ModelSelector', () => {
|
||||
},
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
isLoading: false,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
@@ -266,6 +270,7 @@ describe('ModelSelector', () => {
|
||||
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} }, // No recently used models
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
isLoading: false,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
|
||||
@@ -44,7 +44,7 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
|
||||
const [isCustomInput, setIsCustomInput] = useState(false);
|
||||
const [customValue, setCustomValue] = useState('');
|
||||
const { settings, addRecentlyUsedModel, isConfigured } = useAISettings();
|
||||
const { settings, addRecentlyUsedModel, isConfigured, isLoading: isLoadingSettings } = useAISettings();
|
||||
const { models: allModels, isLoading, error, refetch } = useProviderModels();
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
@@ -314,9 +314,11 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
className={cn(
|
||||
"h-8 p-0 gap-1 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 min-w-0 max-w-[280px]"
|
||||
)}
|
||||
disabled={disabled}
|
||||
disabled={disabled || isLoading || isLoadingSettings}
|
||||
>
|
||||
{selectedModelDisplay ? (
|
||||
{(isLoading || isLoadingSettings) ? (
|
||||
<Skeleton className="h-4 w-32" />
|
||||
) : selectedModelDisplay ? (
|
||||
<>
|
||||
{selectedModelDisplay.baseURL ? (
|
||||
<ExternalFavicon
|
||||
@@ -337,7 +339,9 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
{placeholder || defaultPlaceholder}
|
||||
</span>
|
||||
)}
|
||||
<ChevronDown className="size-3 shrink-0 opacity-50" />
|
||||
{(!isLoading && !isLoadingSettings) && (
|
||||
<ChevronDown className="size-3 shrink-0 opacity-50" />
|
||||
)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="p-0 w-80" align="end">
|
||||
|
||||
@@ -19,7 +19,7 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
const { children } = props;
|
||||
const { config } = useAppContext();
|
||||
|
||||
const gitRelays = config.ngitServers.map(server => `wss://${server}/`);
|
||||
const gitRelays = config.graspMetadata.relays.map(r => r.url);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Create NPool instance only once
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useNostrRepo } from '@/hooks/useNostrRepo';
|
||||
import { createRepositoryAnnouncementEvent } from '@/lib/announceRepository';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
interface NostrRepoEditDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
repoIdentifier: string;
|
||||
onSuccess?: () => void;
|
||||
}
|
||||
|
||||
// Helper function to convert kebab-case to Title Case
|
||||
function kebabToTitleCase(str: string): string {
|
||||
return str
|
||||
.split('-')
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
export function NostrRepoEditDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
repoIdentifier,
|
||||
onSuccess,
|
||||
}: NostrRepoEditDialogProps) {
|
||||
const [repoName, setRepoName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Load existing repository data with react-query
|
||||
const { data: existingEvent, isLoading } = useNostrRepo({
|
||||
repoIdentifier,
|
||||
});
|
||||
|
||||
// Update form fields when event data loads
|
||||
useEffect(() => {
|
||||
if (existingEvent) {
|
||||
const name = existingEvent.tags.find(([tagName]) => tagName === 'name')?.[1] || kebabToTitleCase(repoIdentifier);
|
||||
const desc = existingEvent.tags.find(([tagName]) => tagName === 'description')?.[1] || '';
|
||||
|
||||
setRepoName(name);
|
||||
setDescription(desc);
|
||||
} else if (!isLoading) {
|
||||
// No existing event, use defaults
|
||||
setRepoName(kebabToTitleCase(repoIdentifier));
|
||||
setDescription('');
|
||||
}
|
||||
}, [existingEvent, isLoading, repoIdentifier]);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!user || !existingEvent) {
|
||||
setError('Repository not found');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSaving(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Extract existing data from the event
|
||||
const webTag = existingEvent.tags.find(([tagName]) => tagName === 'web');
|
||||
const webUrls = webTag ? webTag.slice(1) : undefined;
|
||||
const tTags = existingEvent.tags
|
||||
.filter(([tagName]) => tagName === 't')
|
||||
.map(([, value]) => value);
|
||||
const eucTag = existingEvent.tags.find(([tagName, , marker]) => tagName === 'r' && marker === 'euc');
|
||||
const earliestCommit = eucTag?.[1];
|
||||
|
||||
// Get clone URLs and relays from existing event
|
||||
const cloneTag = existingEvent.tags.find(([tagName]) => tagName === 'clone');
|
||||
const cloneUrls = cloneTag ? cloneTag.slice(1) : [];
|
||||
const relaysTag = existingEvent.tags.find(([tagName]) => tagName === 'relays');
|
||||
const relays = relaysTag ? relaysTag.slice(1) : [];
|
||||
|
||||
// If no clone URLs or relays, regenerate from current GRASP servers
|
||||
let finalCloneUrls = cloneUrls;
|
||||
let finalRelays = relays;
|
||||
|
||||
if (cloneUrls.length === 0 || relays.length === 0) {
|
||||
// Convert user's GRASP servers to clone URLs and relay URLs
|
||||
const npub = nip19.npubEncode(user.pubkey);
|
||||
const newCloneUrls = new Set<string>();
|
||||
const newRelays = new Set<string>();
|
||||
|
||||
for (const graspRelay of config.graspMetadata.relays) {
|
||||
try {
|
||||
const relayUrl = new URL(graspRelay.url);
|
||||
newRelays.add(relayUrl.href);
|
||||
|
||||
const cloneUrl = new URL(`/${npub}/${repoIdentifier}.git`, `https://${relayUrl.host}`);
|
||||
newCloneUrls.add(cloneUrl.href);
|
||||
} catch {
|
||||
// fallthrough
|
||||
}
|
||||
}
|
||||
|
||||
for (const relay of config.relayMetadata.relays.filter(r => r.write)) {
|
||||
try {
|
||||
const relayUrl = new URL(relay.url);
|
||||
newRelays.add(relayUrl.href);
|
||||
} catch {
|
||||
// fallthrough
|
||||
}
|
||||
}
|
||||
|
||||
finalCloneUrls = cloneUrls.length === 0 ? [...newCloneUrls] : cloneUrls;
|
||||
finalRelays = relays.length === 0 ? [...newRelays] : relays;
|
||||
}
|
||||
|
||||
// Create updated repository announcement event
|
||||
const eventTemplate = createRepositoryAnnouncementEvent({
|
||||
repoId: repoIdentifier,
|
||||
name: repoName.trim() || undefined,
|
||||
description: description.trim() || undefined,
|
||||
webUrls,
|
||||
cloneUrls: finalCloneUrls,
|
||||
relays: finalRelays,
|
||||
tTags: tTags.length > 0 ? tTags : undefined,
|
||||
earliestCommit,
|
||||
});
|
||||
|
||||
// Publish the updated event
|
||||
await publishEvent(eventTemplate);
|
||||
|
||||
// Wait a moment for relays to process
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
// Call success callback if provided
|
||||
if (onSuccess) {
|
||||
onSuccess();
|
||||
}
|
||||
|
||||
// Close dialog
|
||||
onOpenChange(false);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to update repository';
|
||||
setError(message);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRepoNameChange = (value: string) => {
|
||||
setRepoName(value);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit Repository</DialogTitle>
|
||||
<DialogDescription>
|
||||
Update your repository announcement on Nostr.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
{isLoading ? (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-20" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-24 w-full" />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="repo-name">Repo Name</Label>
|
||||
<Input
|
||||
id="repo-name"
|
||||
placeholder="My Project"
|
||||
value={repoName}
|
||||
onChange={(e) => handleRepoNameChange(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="description">Description</Label>
|
||||
<Textarea
|
||||
id="description"
|
||||
placeholder="A brief description of your project"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription className="text-sm">{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={isSaving || isLoading}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={isSaving || isLoading || !existingEvent}
|
||||
>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2" />
|
||||
Saving...
|
||||
</>
|
||||
) : (
|
||||
'Save'
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { useContacts } from '@/hooks/useContacts';
|
||||
* This component runs globally to sync various Nostr data when the user logs in.
|
||||
* Currently syncs:
|
||||
* - NIP-65 relay list (kind 10002)
|
||||
* - NIP-34 grasp server list (kind 10317)
|
||||
*/
|
||||
export function NostrSync() {
|
||||
const { nostr } = useNostr();
|
||||
@@ -62,5 +63,45 @@ export function NostrSync() {
|
||||
syncRelaysFromNostr();
|
||||
}, [user, config.relayMetadata.updatedAt, nostr, updateConfig]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
|
||||
const syncGraspServersFromNostr = async () => {
|
||||
try {
|
||||
const events = await nostr.query(
|
||||
[{ kinds: [10317], authors: [user.pubkey], limit: 1 }],
|
||||
{ signal: AbortSignal.timeout(5000) }
|
||||
);
|
||||
|
||||
if (events.length > 0) {
|
||||
const event = events[0];
|
||||
|
||||
// Only update if the event is newer than our stored data
|
||||
if (event.created_at > config.graspMetadata.updatedAt) {
|
||||
const fetchedRelays = event.tags
|
||||
.filter(([name]) => name === 'g')
|
||||
.map(([_, url]) => ({ url }))
|
||||
.filter(relay => relay.url); // Filter out empty URLs
|
||||
|
||||
if (fetchedRelays.length > 0) {
|
||||
console.log('Syncing grasp server list from Nostr:', fetchedRelays);
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
graspMetadata: {
|
||||
relays: fetchedRelays,
|
||||
updatedAt: event.created_at,
|
||||
},
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to sync grasp servers from Nostr:', error);
|
||||
}
|
||||
};
|
||||
|
||||
syncGraspServersFromNostr();
|
||||
}, [user, config.graspMetadata.updatedAt, nostr, updateConfig]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { generateSecretKey } from 'nostr-tools';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink, Search, Coins } from 'lucide-react';
|
||||
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, Search, Coins } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -9,13 +9,13 @@ import { Card, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { ExternalInput } from '@/components/ui/external-input';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
import { CreditsDialog } from '@/components/CreditsDialog';
|
||||
import { AIProviderConfigDialog } from '@/components/AIProviderConfigDialog';
|
||||
import { OnboardingCreditsBadge } from '@/components/OnboardingCreditsBadge';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
import { ModelPricing } from '@/components/ModelPricing';
|
||||
@@ -465,37 +465,28 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
{/* API Key Input Section */}
|
||||
{selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && (
|
||||
<div className="space-y-3 max-w-md mx-auto">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold">
|
||||
<h3 className="flex justify-center text-lg font-semibold gap-2">
|
||||
<ExternalFavicon
|
||||
url={selectedProvider.baseURL}
|
||||
size={16}
|
||||
fallback={<Bot size={16} />}
|
||||
/>
|
||||
<span>
|
||||
{selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{selectedProvider.id === 'routstr' ? (
|
||||
t('requiresCashuToken', { providerName: selectedProvider.name })
|
||||
) : (
|
||||
<>
|
||||
{selectedProvider.name} {t('requiresAnApiKey')}{' '}
|
||||
{selectedProvider.apiKeysURL ? (
|
||||
<a className="text-foreground underline" href={selectedProvider.apiKeysURL} target="_blank">
|
||||
{t('apiKey')}
|
||||
<ExternalLink className="inline-block h-4 w-4 ml-1" />
|
||||
</a>
|
||||
) : (
|
||||
t('apiKey')
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<PasswordInput
|
||||
</span>
|
||||
</h3>
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
||||
value={providerApiKey}
|
||||
onChange={(e) => setProviderApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && providerApiKey.trim()) {
|
||||
if (e.key === 'Enter' && providerApiKey.trim() && agreedToProviderTerms) {
|
||||
handleContinueFromProviderSelection();
|
||||
}
|
||||
}}
|
||||
url={selectedProvider.apiKeysURL}
|
||||
urlTitle="Get Key"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -726,7 +717,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
|
||||
{/* Credits Dialog */}
|
||||
{showCreditsDialog && selectedModel && selectedProvider && (
|
||||
<CreditsDialog
|
||||
<AIProviderConfigDialog
|
||||
open={showCreditsDialog}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
@@ -739,6 +730,8 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
baseURL: selectedProvider.baseURL,
|
||||
nostr: selectedProvider.nostr || undefined,
|
||||
}}
|
||||
onUpdate={() => {}}
|
||||
onRemove={() => {}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -7,17 +7,6 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
@@ -29,18 +18,21 @@ import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
Calendar,
|
||||
Folder,
|
||||
Download,
|
||||
Loader2,
|
||||
Trash2,
|
||||
Save,
|
||||
DollarSign,
|
||||
ExternalLink,
|
||||
FileCode,
|
||||
Download,
|
||||
Trash2,
|
||||
} from 'lucide-react';
|
||||
import JSZip from 'jszip';
|
||||
import { Skeleton } from './ui/skeleton';
|
||||
import { Separator } from './ui/separator';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { LabelSelector } from '@/components/labels/LabelSelector';
|
||||
import { DeleteProjectDialog } from '@/components/DeleteProjectDialog';
|
||||
import { cn } from '@/lib/utils';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
interface ProjectDetailsDialogProps {
|
||||
project: Project;
|
||||
@@ -50,11 +42,12 @@ interface ProjectDetailsDialogProps {
|
||||
}
|
||||
|
||||
export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDeleted }: ProjectDetailsDialogProps) {
|
||||
const [isRenaming, setIsRenaming] = useState(false);
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isRenaming, setIsRenaming] = useState(false);
|
||||
const [newProjectName, setNewProjectName] = useState(project.id);
|
||||
const [totalCost, setTotalCost] = useState<number | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
@@ -72,6 +65,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
// Load total project cost and template info
|
||||
useEffect(() => {
|
||||
const loadProjectData = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const dotAI = new DotAI(fs, `${projectsPath}/${project.id}`);
|
||||
|
||||
@@ -86,6 +80,8 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
console.warn('Failed to load project data:', error);
|
||||
setTotalCost(null);
|
||||
setTemplateInfo(null);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -259,30 +255,44 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
</div>
|
||||
|
||||
{/* Total Cost */}
|
||||
{totalCost !== null && totalCost > 0 && (
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<DollarSign className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Total Cost:</span>
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<DollarSign className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Total Cost:</span>
|
||||
{typeof totalCost === 'number' ? (
|
||||
<span className="font-mono">${totalCost.toFixed(2)}</span>
|
||||
</div>
|
||||
)}
|
||||
) : (
|
||||
isLoading ? (
|
||||
<Skeleton className="h-4 w-16" />
|
||||
) : (
|
||||
<span>N/A</span>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Template Info */}
|
||||
{templateInfo && (
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<FileCode className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Template:</span>
|
||||
<a
|
||||
href={templateInfo.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-1 text-primary hover:underline"
|
||||
>
|
||||
{templateInfo.name}
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<FileCode className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Template:</span>
|
||||
<a
|
||||
href={templateInfo?.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={cn("flex items-center gap-1", { "text-primary hover:underline": !!templateInfo })}
|
||||
>
|
||||
{templateInfo ? (
|
||||
<>
|
||||
<span>{templateInfo.name}</span>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</>
|
||||
) : (
|
||||
isLoading ? (
|
||||
<Skeleton className="h-4 w-24" />
|
||||
) : (
|
||||
<span>N/A</span>
|
||||
)
|
||||
)}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* Project Name */}
|
||||
<div className="space-y-2">
|
||||
@@ -339,8 +349,11 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
</Button>
|
||||
|
||||
{/* Delete Project Button */}
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<DeleteProjectDialog
|
||||
projectName={project.name}
|
||||
onDelete={handleDeleteProject}
|
||||
isDeleting={isDeleting}
|
||||
trigger={
|
||||
<Button
|
||||
variant="destructive"
|
||||
className="w-full gap-2"
|
||||
@@ -349,33 +362,8 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
<Trash2 className="h-4 w-4" />
|
||||
Delete Project
|
||||
</Button>
|
||||
</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}
|
||||
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>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders } from 'lucide-react';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders, Compass } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@@ -367,6 +367,13 @@ export function ProjectSidebar({
|
||||
<GitBranch className="h-4 w-4" />
|
||||
{t('importRepository')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => navigateAndClose('/explore')}
|
||||
className="flex items-center gap-2 w-full"
|
||||
>
|
||||
<Compass className="h-4 w-4" />
|
||||
{t('exploreApps')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setLabelsDialogOpen(true)}
|
||||
className="flex items-center gap-2 w-full"
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
MessageSquarePlus,
|
||||
History,
|
||||
Folder,
|
||||
Copy,
|
||||
ChevronDown,
|
||||
Trash2,
|
||||
Star,
|
||||
} from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
interface ProjectTitleMenuProps {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
onNewChat: () => void;
|
||||
onGitHistory: () => void;
|
||||
onDuplicate: () => void;
|
||||
onDelete: () => void;
|
||||
onProjectDetails: () => void;
|
||||
isAILoading: boolean;
|
||||
isAnyLoading: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ProjectTitleMenu({
|
||||
projectId,
|
||||
projectName,
|
||||
onNewChat,
|
||||
onGitHistory,
|
||||
onDuplicate,
|
||||
onDelete,
|
||||
onProjectDetails,
|
||||
isAILoading,
|
||||
isAnyLoading,
|
||||
className = '',
|
||||
}: ProjectTitleMenuProps) {
|
||||
const { t } = useTranslation();
|
||||
const [favorites, setFavorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const isFavorite = favorites.includes(projectId);
|
||||
|
||||
const handleToggleFavorite = (e: React.MouseEvent) => {
|
||||
e.preventDefault(); // Prevent menu from closing
|
||||
e.stopPropagation();
|
||||
|
||||
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'] });
|
||||
};
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className={cn("p-0 h-auto font-semibold truncate hover:bg-transparent hover:text-muted-foreground flex items-center gap-1", className)}
|
||||
>
|
||||
<span className="truncate">{projectName}</span>
|
||||
<ChevronDown className="h-4 w-4 flex-shrink-0 text-muted-foreground" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={handleToggleFavorite}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
onSelect={(e) => e.preventDefault()} // Prevent menu from closing
|
||||
>
|
||||
<Star
|
||||
className={cn(
|
||||
"h-4 w-4",
|
||||
{ "text-yellow-500 fill-current": isFavorite },
|
||||
)}
|
||||
/>
|
||||
{isFavorite ? 'Unfavorite' : 'Favorite'}
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onProjectDetails}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<Folder className="h-4 w-4" />
|
||||
Project Details
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onGitHistory}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<History className="h-4 w-4" />
|
||||
Rollback
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onNewChat}
|
||||
disabled={isAILoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<MessageSquarePlus className="h-4 w-4" />
|
||||
New Chat
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onDuplicate}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<Copy className="h-4 w-4" />
|
||||
{t('duplicateProject')}
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onDelete}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2 text-destructive focus:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
Delete Project
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Trash2, Rocket } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
|
||||
interface ProviderConfigDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
provider: DeployProvider;
|
||||
preset?: PresetDeployProvider;
|
||||
onUpdate: (provider: DeployProvider) => void;
|
||||
onRemove: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a URL string to ensure it has a protocol
|
||||
* @param url - The URL string to normalize
|
||||
* @returns A fully-qualified URL string
|
||||
*/
|
||||
function normalizeUrl(url: string): string {
|
||||
// If it already has a protocol, return as-is
|
||||
if (/^https?:\/\//i.test(url)) {
|
||||
return url;
|
||||
}
|
||||
|
||||
// Add https:// prefix
|
||||
return `https://${url}`;
|
||||
}
|
||||
|
||||
export function ProviderConfigDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
provider,
|
||||
preset,
|
||||
onUpdate,
|
||||
onRemove,
|
||||
}: ProviderConfigDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [localProvider, setLocalProvider] = useState(provider);
|
||||
|
||||
// Reset local state when provider changes or dialog opens
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setLocalProvider(provider);
|
||||
}
|
||||
}, [provider, open]);
|
||||
|
||||
const handleSave = () => {
|
||||
onUpdate(localProvider);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const handleDelete = () => {
|
||||
onRemove();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
// Use baseURL from configured provider, falling back to preset baseURL
|
||||
const baseURL = ('baseURL' in localProvider && localProvider.baseURL) || preset?.baseURL;
|
||||
|
||||
// For Shakespeare, special handling for host field
|
||||
const shakespeareUrl = localProvider.type === 'shakespeare' && 'host' in localProvider && localProvider.host
|
||||
? normalizeUrl(localProvider.host)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalFavicon
|
||||
url={shakespeareUrl || baseURL}
|
||||
size={20}
|
||||
fallback={<Rocket size={20} />}
|
||||
/>
|
||||
<DialogTitle>{localProvider.name}</DialogTitle>
|
||||
</div>
|
||||
<DialogDescription>
|
||||
{preset?.description || 'Configure your deployment provider'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-name">
|
||||
Name <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-name"
|
||||
placeholder="Provider name"
|
||||
value={localProvider.name}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, name: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{localProvider.type === 'shakespeare' ? (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('shakespeareDeployNostrAuth')}
|
||||
</p>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-host">
|
||||
Host (Optional)
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-host"
|
||||
placeholder="shakespeare.wtf"
|
||||
value={localProvider.host || ''}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, host: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : localProvider.type === 'nsite' ? (
|
||||
<>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-gateway">
|
||||
Gateway <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-gateway"
|
||||
placeholder="nsite.lol"
|
||||
value={localProvider.gateway || ''}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-relays">
|
||||
Relay URLs (comma-separated) <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-relays"
|
||||
placeholder="wss://relay.nostr.band, wss://relay.damus.io"
|
||||
value={localProvider.relayUrls?.join(', ') || ''}
|
||||
onChange={(e) => setLocalProvider({
|
||||
...localProvider,
|
||||
relayUrls: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-blossom">
|
||||
Blossom Servers (comma-separated) <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-blossom"
|
||||
placeholder="https://blossom.primal.net/"
|
||||
value={localProvider.blossomServers?.join(', ') || ''}
|
||||
onChange={(e) => setLocalProvider({
|
||||
...localProvider,
|
||||
blossomServers: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{localProvider.type === 'cloudflare' && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-accountId">
|
||||
{preset?.accountIdLabel || 'Account ID'} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-accountId"
|
||||
placeholder="Enter Account ID"
|
||||
value={localProvider.accountId}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, accountId: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{localProvider.type === 'deno' && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-organizationId">
|
||||
{preset?.organizationIdLabel || 'Organization ID'} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-organizationId"
|
||||
placeholder="Enter Organization ID"
|
||||
value={localProvider.organizationId}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, organizationId: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-apiKey">
|
||||
{preset?.apiKeyLabel || t('apiKey')} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<PasswordInput
|
||||
id="provider-apiKey"
|
||||
placeholder={t('enterApiKey')}
|
||||
value={localProvider.apiKey}
|
||||
onChange={(e) => {
|
||||
if (localProvider.type === 'netlify') {
|
||||
setLocalProvider({ ...localProvider, apiKey: e.target.value });
|
||||
} else if (localProvider.type === 'vercel') {
|
||||
setLocalProvider({ ...localProvider, apiKey: e.target.value });
|
||||
} else if (localProvider.type === 'cloudflare') {
|
||||
setLocalProvider({ ...localProvider, apiKey: e.target.value });
|
||||
} else if (localProvider.type === 'deno') {
|
||||
setLocalProvider({ ...localProvider, apiKey: e.target.value });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-baseURL">
|
||||
Base URL (Optional)
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-baseURL"
|
||||
placeholder={
|
||||
localProvider.type === 'netlify' ? 'https://api.netlify.com/api/v1' :
|
||||
localProvider.type === 'vercel' ? 'https://api.vercel.com' :
|
||||
localProvider.type === 'cloudflare' ? 'https://api.cloudflare.com/client/v4' :
|
||||
localProvider.type === 'deno' ? 'https://api.deno.com/v1' :
|
||||
'Base URL'
|
||||
}
|
||||
value={localProvider.baseURL || ''}
|
||||
onChange={(e) => {
|
||||
if (localProvider.type === 'netlify') {
|
||||
setLocalProvider({ ...localProvider, baseURL: e.target.value });
|
||||
} else if (localProvider.type === 'vercel') {
|
||||
setLocalProvider({ ...localProvider, baseURL: e.target.value });
|
||||
} else if (localProvider.type === 'cloudflare') {
|
||||
setLocalProvider({ ...localProvider, baseURL: e.target.value });
|
||||
} else if (localProvider.type === 'deno') {
|
||||
setLocalProvider({ ...localProvider, baseURL: e.target.value });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{(localProvider.type === 'cloudflare' || localProvider.type === 'deno') && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-baseDomain">
|
||||
Base Domain (Optional)
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-baseDomain"
|
||||
placeholder={localProvider.type === 'cloudflare' ? 'workers.dev' : 'deno.dev'}
|
||||
value={localProvider.baseDomain || ''}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, baseDomain: e.target.value })}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{localProvider.type === 'cloudflare'
|
||||
? 'The domain suffix for deployed workers (e.g., workers.dev)'
|
||||
: 'The domain suffix for deployed projects (e.g., deno.dev)'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="provider-proxy"
|
||||
checked={localProvider.proxy || false}
|
||||
onCheckedChange={(checked) => setLocalProvider({ ...localProvider, proxy: checked === true })}
|
||||
/>
|
||||
<Label
|
||||
htmlFor="provider-proxy"
|
||||
className="text-sm font-normal cursor-pointer"
|
||||
>
|
||||
Use CORS Proxy
|
||||
</Label>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="gap-2">
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleDelete}
|
||||
className="sm:mr-auto"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
{t('delete')}
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
{t('save')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Bot } from 'lucide-react';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { ReactNode } from 'react';
|
||||
|
||||
interface ProviderTileProps {
|
||||
icon?: ReactNode;
|
||||
iconUrl?: string | null;
|
||||
name: string;
|
||||
onClick: () => void;
|
||||
badge?: ReactNode;
|
||||
}
|
||||
|
||||
export function ProviderTile({ icon, iconUrl, name, onClick, badge }: ProviderTileProps) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className="flex flex-col items-center justify-center gap-2 p-4 rounded-lg border bg-card hover:bg-muted transition-colors text-center h-[120px] relative"
|
||||
>
|
||||
{iconUrl ? (
|
||||
<ExternalFavicon
|
||||
url={iconUrl}
|
||||
size={32}
|
||||
fallback={icon || <Bot size={32} />}
|
||||
/>
|
||||
) : (
|
||||
icon || <Bot size={32} />
|
||||
)}
|
||||
<span className="text-sm font-medium line-clamp-2 overflow-hidden max-w-full text-ellipsis">
|
||||
{name}
|
||||
</span>
|
||||
{badge && (
|
||||
<div className="absolute top-0 right-0">
|
||||
{badge}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -23,9 +23,9 @@ vi.mock('react-router-dom', () => ({
|
||||
useNavigate: () => vi.fn()
|
||||
}));
|
||||
|
||||
// Mock CreditsDialog to avoid NostrProvider dependency
|
||||
vi.mock('./CreditsDialog', () => ({
|
||||
CreditsDialog: () => null
|
||||
// Mock AIProviderConfigDialog to avoid NostrProvider dependency
|
||||
vi.mock('./AIProviderConfigDialog', () => ({
|
||||
AIProviderConfigDialog: () => null
|
||||
}));
|
||||
|
||||
describe('Quilly', () => {
|
||||
|
||||
@@ -6,7 +6,7 @@ import { QuillySVG } from '@/components/ui/QuillySVG';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
import { CreditsDialog } from './CreditsDialog';
|
||||
import { AIProviderConfigDialog } from './AIProviderConfigDialog';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
import { useState } from 'react';
|
||||
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
|
||||
@@ -279,10 +279,12 @@ function QuillyCreditsButton({ provider }: QuillyCreditsButtonProps) {
|
||||
<button className="text-primary underline" onClick={() => setShowCreditsDialog(true)}>
|
||||
{credits.data ? `Add credits (${credits.data.amount.toFixed(2)} remaining)` : 'Add credits'}
|
||||
</button>
|
||||
<CreditsDialog
|
||||
<AIProviderConfigDialog
|
||||
open={showCreditsDialog}
|
||||
onOpenChange={setShowCreditsDialog}
|
||||
provider={provider}
|
||||
onUpdate={() => {}}
|
||||
onRemove={() => {}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -273,7 +273,7 @@ export function RelayListManager() {
|
||||
className="h-10 shrink-0"
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
{t('addRelay')}
|
||||
{t('add')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,59 +1,276 @@
|
||||
import React from 'react';
|
||||
import React, { useState, useRef, useEffect, memo } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { GitBranch } from 'lucide-react';
|
||||
import { GitBranch, Loader2, EllipsisVertical, Edit, Code, ExternalLink } from 'lucide-react';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import type { Repository } from '@/hooks/useUserRepositories';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { detectFork } from '@/lib/detectFork';
|
||||
import { NostrRepoEditDialog } from '@/components/NostrRepoEditDialog';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useOGImage } from '@/hooks/useOGImage';
|
||||
import { ZapDialog } from '@/components/ZapDialog';
|
||||
import { Zap } from 'lucide-react';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import type { NostrMetadata } from '@nostrify/nostrify';
|
||||
import { formatRelativeTime } from '@/lib/utils';
|
||||
|
||||
interface RepositoryCardProps {
|
||||
repo: Repository;
|
||||
/** Pre-fetched author metadata to avoid individual fetches */
|
||||
authorMetadata?: NostrMetadata;
|
||||
/** Callback when a tag is clicked - receives the tag value */
|
||||
onTagClick?: (tag: string) => void;
|
||||
}
|
||||
|
||||
export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
const { data: authorData } = useAuthor(repo.pubkey);
|
||||
function RepositoryCardInner({ repo, authorMetadata: preloadedMetadata, onTagClick }: RepositoryCardProps) {
|
||||
// Only fetch author data if not preloaded
|
||||
const { data: authorData } = useAuthor(preloadedMetadata ? undefined : repo.pubkey);
|
||||
const metadata = preloadedMetadata ?? authorData?.metadata;
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { settings: gitSettings } = useGitSettings();
|
||||
const navigate = useNavigate();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { toast } = useToast();
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
const [isCloning, setIsCloning] = useState(false);
|
||||
const [editRepoOpen, setEditRepoOpen] = useState(false);
|
||||
const [imageError, setImageError] = useState(false);
|
||||
const [eventViewerOpen, setEventViewerOpen] = useState(false);
|
||||
const [isInViewport, setIsInViewport] = useState(false);
|
||||
const cardRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const displayName = authorData?.metadata?.name || genUserName(repo.pubkey);
|
||||
const profileImage = authorData?.metadata?.picture;
|
||||
// Lazy load OG images - only fetch when card is in viewport
|
||||
useEffect(() => {
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (entry.isIntersecting) {
|
||||
setIsInViewport(true);
|
||||
observer.disconnect();
|
||||
}
|
||||
},
|
||||
{ rootMargin: '100px' } // Start loading slightly before visible
|
||||
);
|
||||
|
||||
if (cardRef.current) {
|
||||
observer.observe(cardRef.current);
|
||||
}
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const displayName = metadata?.name || genUserName(repo.pubkey);
|
||||
const profileImage = metadata?.picture;
|
||||
const isOwnRepo = user?.pubkey === repo.pubkey;
|
||||
const hasLightning = !!(metadata?.lud16 || metadata?.lud06);
|
||||
const canZap = user && !isOwnRepo && hasLightning;
|
||||
|
||||
// Get OG metadata from first web URL - only when in viewport
|
||||
const firstWebUrl = repo.webUrls?.[0];
|
||||
const { data: ogMetadata } = useOGImage(isInViewport ? firstWebUrl : undefined);
|
||||
const ogImageUrl = ogMetadata?.image ?? null;
|
||||
const ogDescription = ogMetadata?.description ?? null;
|
||||
|
||||
// Construct Nostr clone URL
|
||||
const nostrCloneUrl = `nostr://${nip19.npubEncode(repo.pubkey)}/${repo.repoId}`;
|
||||
const nostrURI = new NostrURI({
|
||||
pubkey: repo.pubkey,
|
||||
identifier: repo.repoId,
|
||||
relay: repo.relays[0],
|
||||
});
|
||||
|
||||
const handleClone = () => {
|
||||
// Navigate to clone page with Nostr URL parameter
|
||||
navigate(`/clone?url=${encodeURIComponent(nostrCloneUrl)}`);
|
||||
const handleClone = async (e: React.MouseEvent) => {
|
||||
// Prevent card click from triggering
|
||||
e.stopPropagation();
|
||||
|
||||
setIsCloning(true);
|
||||
|
||||
try {
|
||||
await projectsManager.init();
|
||||
|
||||
// Determine if this is a fork
|
||||
const repoUrl = nostrURI.toString();
|
||||
const fork = await detectFork(repoUrl, user?.pubkey, gitSettings.credentials);
|
||||
|
||||
// Clone the repository using the Nostr URI
|
||||
const project = await projectsManager.cloneProject({
|
||||
name: repo.name,
|
||||
repoUrl,
|
||||
fork,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: t('nostrRepositoryImportedSuccessfully'),
|
||||
description: t('repositoryClonedFromNostr', { repoName: repo.name }),
|
||||
});
|
||||
|
||||
// Navigate to the new project with build parameter
|
||||
navigate(`/project/${project.id}?build`);
|
||||
} catch (error) {
|
||||
console.error('Failed to clone repository:', error);
|
||||
|
||||
let errorMessage = t('failedToImportRepository');
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('Repository not found on Nostr network')) {
|
||||
errorMessage = t('repositoryNotFoundOnNostr');
|
||||
} else if (error.message.includes('No clone URLs found')) {
|
||||
errorMessage = t('noCloneUrlsFound');
|
||||
} else if (error.message.includes('All clone attempts failed')) {
|
||||
errorMessage = t('allCloneAttemptsFailed');
|
||||
} else {
|
||||
errorMessage = error.message;
|
||||
}
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('failedToImportRepository'),
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsCloning(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRepoEditSuccess = () => {
|
||||
// Refresh repositories list after successful edit
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'user-repositories', user?.pubkey] });
|
||||
};
|
||||
|
||||
// Check if we have a valid OG image to show
|
||||
const hasValidImage = ogImageUrl && !imageError;
|
||||
|
||||
return (
|
||||
<Card className="h-full flex flex-col hover:shadow-lg transition-shadow cursor-pointer" onClick={handleClone}>
|
||||
<Card ref={cardRef} className="h-full flex flex-col hover:shadow-lg transition-shadow">
|
||||
{/* Preview Image or Placeholder */}
|
||||
{hasValidImage && firstWebUrl ? (
|
||||
<a
|
||||
href={firstWebUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block aspect-video bg-muted overflow-hidden rounded-t-lg cursor-pointer hover:opacity-90 transition-opacity"
|
||||
>
|
||||
<img
|
||||
src={ogImageUrl}
|
||||
alt={`${repo.name} preview`}
|
||||
className="w-full h-full object-cover"
|
||||
onError={() => setImageError(true)}
|
||||
/>
|
||||
</a>
|
||||
) : (
|
||||
<div className="aspect-video bg-gradient-to-br from-primary to-accent rounded-t-lg flex items-center justify-center">
|
||||
<Code className="h-12 w-12 text-white" />
|
||||
</div>
|
||||
)}
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
{/* Header with name and author */}
|
||||
{/* Header with name and menu */}
|
||||
<div className="mb-4 flex items-start justify-between">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-end gap-2 mb-2">
|
||||
<h3 className="font-semibold text-lg leading-tight truncate">
|
||||
{repo.name}
|
||||
</h3>
|
||||
<span className="text-sm text-muted-foreground shrink-0">
|
||||
{formatRelativeTime(repo.created_at)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center -mt-1 -mr-2 shrink-0">
|
||||
{canZap && (
|
||||
<ZapDialog target={repo as unknown as Event}>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8 text-amber-500 hover:text-amber-600 hover:bg-amber-500/10">
|
||||
<Zap className="h-4 w-4" />
|
||||
</Button>
|
||||
</ZapDialog>
|
||||
)}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<EllipsisVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{firstWebUrl && (
|
||||
<DropdownMenuItem asChild className="gap-2">
|
||||
<a href={firstWebUrl} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
Open Website
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem onClick={() => setEventViewerOpen(true)} className="gap-2">
|
||||
<Code className="h-4 w-4" />
|
||||
View Event
|
||||
</DropdownMenuItem>
|
||||
{isOwnRepo && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => setEditRepoOpen(true)} className="gap-2">
|
||||
<Edit className="h-4 w-4" />
|
||||
Edit Repository
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Author */}
|
||||
<div className="mb-4">
|
||||
<h3 className="font-semibold text-lg leading-tight mb-2 truncate">
|
||||
{repo.name}
|
||||
</h3>
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Avatar className="h-4 w-4">
|
||||
<div className="flex items-center gap-3 text-sm">
|
||||
<Avatar className="h-10 w-10">
|
||||
{profileImage && (
|
||||
<AvatarImage src={profileImage} alt={displayName} />
|
||||
)}
|
||||
<AvatarFallback className="text-[8px]">
|
||||
<AvatarFallback className="text-xs">
|
||||
{displayName.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="truncate">{displayName}</span>
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onTagClick?.(displayName);
|
||||
}}
|
||||
className="truncate font-medium text-base text-foreground hover:text-primary hover:underline transition-colors text-left"
|
||||
>
|
||||
{displayName}
|
||||
</button>
|
||||
{metadata?.nip05 && (
|
||||
<span className="text-sm text-muted-foreground shrink-0">{metadata.nip05}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
{repo.description && (
|
||||
{(repo.description || ogDescription) && (
|
||||
<p className="text-sm text-muted-foreground line-clamp-2 mb-4">
|
||||
{repo.description}
|
||||
{repo.description || ogDescription}
|
||||
</p>
|
||||
)}
|
||||
|
||||
@@ -61,14 +278,21 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
{repo.repoTags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 mb-4">
|
||||
{repo.repoTags.slice(0, 3).map((tag, index) => (
|
||||
<Badge key={index} variant="secondary" className="text-xs">
|
||||
{tag}
|
||||
</Badge>
|
||||
<button
|
||||
key={index}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onTagClick?.(tag);
|
||||
}}
|
||||
className="text-sm text-primary hover:text-primary/80 hover:underline transition-colors font-medium"
|
||||
>
|
||||
#{tag}
|
||||
</button>
|
||||
))}
|
||||
{repo.repoTags.length > 3 && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
+{repo.repoTags.length - 3}
|
||||
</Badge>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -88,12 +312,54 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={handleClone}
|
||||
disabled={isCloning}
|
||||
>
|
||||
<GitBranch className="h-4 w-4 mr-2" />
|
||||
Clone
|
||||
{isCloning ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Cloning...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GitBranch className="h-4 w-4 mr-2" />
|
||||
Clone
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<NostrRepoEditDialog
|
||||
open={editRepoOpen}
|
||||
onOpenChange={setEditRepoOpen}
|
||||
repoIdentifier={repo.repoId}
|
||||
onSuccess={handleRepoEditSuccess}
|
||||
/>
|
||||
|
||||
{/* Event Viewer Dialog */}
|
||||
<Dialog open={eventViewerOpen} onOpenChange={setEventViewerOpen}>
|
||||
<DialogContent className="max-w-2xl max-h-[80vh] flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Repository Event</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="overflow-y-auto flex-1 min-h-0">
|
||||
<pre className="text-xs p-4 rounded-lg overflow-x-auto">
|
||||
{JSON.stringify({
|
||||
id: repo.id,
|
||||
pubkey: repo.pubkey,
|
||||
created_at: repo.created_at,
|
||||
kind: repo.kind,
|
||||
tags: repo.tags,
|
||||
content: repo.content,
|
||||
sig: repo.sig,
|
||||
}, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Memoize to prevent re-renders when parent re-renders with same props
|
||||
export const RepositoryCard = memo(RepositoryCardInner);
|
||||
@@ -27,14 +27,19 @@ describe('SentryProvider', () => {
|
||||
relays: [{ url: 'wss://relay.test', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
graspMetadata: {
|
||||
relays: [],
|
||||
updatedAt: 0,
|
||||
},
|
||||
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
|
||||
esmUrl: 'https://esm.test',
|
||||
corsProxy: 'https://proxy.test/{href}',
|
||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||
faviconUrl: 'https://favicon.test/{href}',
|
||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||
previewDomain: 'test.dev',
|
||||
showcaseEnabled: false,
|
||||
showcaseModerator: '',
|
||||
ngitServers: [],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
@@ -64,14 +69,19 @@ describe('SentryProvider', () => {
|
||||
relays: [{ url: 'wss://relay.test', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
graspMetadata: {
|
||||
relays: [],
|
||||
updatedAt: 0,
|
||||
},
|
||||
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
|
||||
esmUrl: 'https://esm.test',
|
||||
corsProxy: 'https://proxy.test/{href}',
|
||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||
faviconUrl: 'https://favicon.test/{href}',
|
||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||
previewDomain: 'test.dev',
|
||||
showcaseEnabled: false,
|
||||
showcaseModerator: '',
|
||||
ngitServers: [],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
@@ -102,14 +112,19 @@ describe('SentryProvider', () => {
|
||||
relays: [{ url: 'wss://relay.test', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
graspMetadata: {
|
||||
relays: [],
|
||||
updatedAt: 0,
|
||||
},
|
||||
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
|
||||
esmUrl: 'https://esm.test',
|
||||
corsProxy: 'https://proxy.test/{href}',
|
||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||
faviconUrl: 'https://favicon.test/{href}',
|
||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||
previewDomain: 'test.dev',
|
||||
showcaseEnabled: false,
|
||||
showcaseModerator: '',
|
||||
ngitServers: [],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
@@ -143,14 +158,19 @@ describe('SentryProvider', () => {
|
||||
relays: [{ url: 'wss://relay.test', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
graspMetadata: {
|
||||
relays: [],
|
||||
updatedAt: 0,
|
||||
},
|
||||
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
|
||||
esmUrl: 'https://esm.test',
|
||||
corsProxy: 'https://proxy.test/{href}',
|
||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||
faviconUrl: 'https://favicon.test/{href}',
|
||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||
previewDomain: 'test.dev',
|
||||
showcaseEnabled: false,
|
||||
showcaseModerator: '',
|
||||
ngitServers: [],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { ArrowLeft, type LucideIcon } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import type { ReactNode } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface SettingsPageLayoutProps {
|
||||
/** The icon component to display next to the title */
|
||||
icon: LucideIcon;
|
||||
/** Translation key for the page title */
|
||||
titleKey: string;
|
||||
/** Translation key for the page description */
|
||||
descriptionKey: string;
|
||||
/** The main content of the settings page */
|
||||
children: ReactNode;
|
||||
/** Optional className for the content container */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared layout component for all settings pages.
|
||||
* Provides consistent header structure with mobile back button, icon, title, and description.
|
||||
*/
|
||||
export function SettingsPageLayout({
|
||||
icon: Icon,
|
||||
titleKey,
|
||||
descriptionKey,
|
||||
children,
|
||||
className,
|
||||
}: SettingsPageLayoutProps) {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6 pb-16">
|
||||
{isMobile && (
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate('/settings')}
|
||||
className="h-8 w-auto px-2 -ml-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
{t('backToSettings')}
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Icon className="h-6 w-6 text-primary" />
|
||||
{t(titleKey)}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t(descriptionKey)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isMobile && (
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Icon className="h-6 w-6 text-primary" />
|
||||
{t(titleKey)}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t(descriptionKey)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={cn('space-y-6 max-w-xl', className)}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import { ModelSelector } from '@/components/ModelSelector';
|
||||
interface ChatInputProps {
|
||||
isLoading: boolean;
|
||||
isConfigured: boolean;
|
||||
isLoadingSettings: boolean;
|
||||
providerModel: string;
|
||||
onProviderModelChange: (model: string) => void;
|
||||
onSend: (input: string, files: File[]) => void;
|
||||
@@ -33,6 +34,7 @@ interface ChatInputProps {
|
||||
export const ChatInput = memo(function ChatInput({
|
||||
isLoading,
|
||||
isConfigured,
|
||||
isLoadingSettings,
|
||||
providerModel,
|
||||
onProviderModelChange,
|
||||
onSend,
|
||||
@@ -83,35 +85,6 @@ export const ChatInput = memo(function ChatInput({
|
||||
}
|
||||
}, [handleSend]);
|
||||
|
||||
const handlePaste = useCallback(async (e: React.ClipboardEvent) => {
|
||||
const items = e.clipboardData?.items;
|
||||
if (!items) return;
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
|
||||
// Check if the item is an image
|
||||
if (item.type.startsWith('image/')) {
|
||||
e.preventDefault(); // Prevent default paste behavior for images
|
||||
|
||||
const file = item.getAsFile();
|
||||
if (file) {
|
||||
// Generate a filename with timestamp
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
const extension = file.type.split('/')[1] || 'png';
|
||||
const filename = `pasted-image-${timestamp}.${extension}`;
|
||||
|
||||
// Create a new File object with the generated name
|
||||
const namedFile = new File([file], filename, { type: file.type });
|
||||
|
||||
// Add to attached files
|
||||
setAttachedFiles(prev => [...prev, namedFile]);
|
||||
}
|
||||
break; // Only handle the first image found
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
setInput(e.target.value);
|
||||
}, []);
|
||||
@@ -132,7 +105,7 @@ export const ChatInput = memo(function ChatInput({
|
||||
value={input}
|
||||
onChange={handleInputChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
|
||||
onFocus={onFocus}
|
||||
placeholder={
|
||||
!isConfigured
|
||||
@@ -142,7 +115,7 @@ export const ChatInput = memo(function ChatInput({
|
||||
: t('selectModelFirst')
|
||||
}
|
||||
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
|
||||
disabled={isLoading || (isConfigured && !providerModel.trim())}
|
||||
disabled={isLoadingSettings || (isConfigured && !providerModel.trim())}
|
||||
rows={1}
|
||||
aria-label="Chat message input"
|
||||
style={{
|
||||
@@ -163,7 +136,7 @@ export const ChatInput = memo(function ChatInput({
|
||||
onFileSelect={handleFileSelect}
|
||||
onFileRemove={handleFileRemove}
|
||||
selectedFiles={attachedFiles}
|
||||
disabled={isLoading}
|
||||
disabled={isLoadingSettings}
|
||||
multiple={true}
|
||||
/>
|
||||
|
||||
@@ -212,7 +185,7 @@ export const ChatInput = memo(function ChatInput({
|
||||
<ModelSelector
|
||||
value={providerModel}
|
||||
onChange={onProviderModelChange}
|
||||
disabled={isLoading}
|
||||
disabled={isLoadingSettings}
|
||||
placeholder={t('chooseModel')}
|
||||
open={isModelSelectorOpen}
|
||||
onOpenChange={onModelSelectorOpenChange}
|
||||
@@ -234,7 +207,7 @@ export const ChatInput = memo(function ChatInput({
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
onMouseDown={onFirstInteraction}
|
||||
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
|
||||
disabled={isLoadingSettings || (!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
|
||||
size="sm"
|
||||
className="size-8 [&_svg]:size-5 rounded-full p-0"
|
||||
>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
import { ChevronDown, Play } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
@@ -15,6 +15,7 @@ import { useAIChat } from '@/hooks/useAIChat';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||
import { useMCPTools } from '@/hooks/useMCPTools';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { AIMessageItem } from '@/components/AIMessageItem';
|
||||
import { ToolCallDisplay } from '@/components/ToolCallDisplay';
|
||||
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
|
||||
@@ -24,7 +25,6 @@ import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
|
||||
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
|
||||
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
|
||||
import { BuildProjectTool } from '@/lib/tools/BuildProjectTool';
|
||||
import { DeployProjectTool } from '@/lib/tools/DeployProjectTool';
|
||||
import { NostrReadNipTool } from '@/lib/tools/NostrReadNipTool';
|
||||
import { NostrFetchEventTool } from '@/lib/tools/NostrFetchEventTool';
|
||||
import { NostrReadKindTool } from '@/lib/tools/NostrReadKindTool';
|
||||
@@ -88,6 +88,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const { models } = useProviderModels();
|
||||
const { config } = useAppContext();
|
||||
const { projectsPath, tmpPath, pluginsPath } = useFSPaths();
|
||||
const queryClient = useQueryClient();
|
||||
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const [scrolledProjects] = useState(() => new Set<string>());
|
||||
@@ -97,14 +98,15 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
|
||||
const [showTemplateInfo, setShowTemplateInfo] = useState(false);
|
||||
|
||||
// Determine which error to show - console error takes priority over AI errors
|
||||
const displayError = consoleError || aiError;
|
||||
// Determine which error to show - AI errors take priority over console errors
|
||||
// since they are more immediately relevant to the user's current action
|
||||
const displayError = aiError || consoleError;
|
||||
|
||||
// Use external state if provided, otherwise default to false
|
||||
const isBuildLoading = externalIsBuildLoading || false;
|
||||
const scrollAreaRef = useRef<HTMLDivElement>(null);
|
||||
const aiSettings = useAISettings();
|
||||
const { isConfigured, settings, addRecentlyUsedModel } = aiSettings;
|
||||
const { isConfigured, settings, addRecentlyUsedModel, isLoading: isLoadingSettings } = aiSettings;
|
||||
const [providerModel, setProviderModel] = useState(() => {
|
||||
// Initialize with first recently used model if available, otherwise empty
|
||||
return settings.recentlyUsedModels?.[0] || '';
|
||||
@@ -159,13 +161,19 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
sessionManager.emit('fileChanged', projectId, filePath);
|
||||
}, [sessionManager, projectId]);
|
||||
|
||||
// Callback to trigger sync after git commits
|
||||
const handleCommit = useCallback(() => {
|
||||
// Invalidate the git-sync query to trigger an immediate sync
|
||||
queryClient.invalidateQueries({ queryKey: ['git-sync', cwd] });
|
||||
}, [queryClient, cwd]);
|
||||
|
||||
// Fetch MCP tools
|
||||
const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools();
|
||||
|
||||
// Separate built-in tools from MCP tools for clarity
|
||||
const builtInTools = useMemo(() => {
|
||||
const tools: Record<string, Tool<unknown>> = {
|
||||
git_commit: new GitCommitTool(fs, cwd, git),
|
||||
git_commit: new GitCommitTool(fs, cwd, git, { onCommit: handleCommit }),
|
||||
text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }),
|
||||
text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
|
||||
text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
|
||||
@@ -185,11 +193,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
skill: new SkillTool(fs, pluginsPath, cwd),
|
||||
};
|
||||
|
||||
// Add deploy tool only if user is logged in
|
||||
if (user && user.signer) {
|
||||
tools.deploy_project = new DeployProjectTool(fs, cwd, user.signer, projectId);
|
||||
}
|
||||
|
||||
// Add generate_image tool if imageModel is configured
|
||||
if (settings.imageModel) {
|
||||
try {
|
||||
@@ -239,7 +242,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
|
||||
return tools;
|
||||
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged]);
|
||||
}, [fs, git, cwd, user, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit]);
|
||||
|
||||
// MCP tools wrapped for execution
|
||||
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
|
||||
@@ -293,8 +296,10 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
messages,
|
||||
streamingMessage,
|
||||
isLoading: internalIsLoading,
|
||||
isLoadingHistory,
|
||||
totalCost,
|
||||
lastInputTokens,
|
||||
lastFinishReason,
|
||||
addMessage,
|
||||
sendMessage,
|
||||
startGeneration,
|
||||
@@ -706,8 +711,53 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Loading skeleton while loading history */}
|
||||
{isLoadingHistory && (
|
||||
<div className="space-y-6">
|
||||
{/* User message skeleton */}
|
||||
<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="space-y-2">
|
||||
<Skeleton className="h-4 w-64" />
|
||||
<Skeleton className="h-4 w-48" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Assistant message skeleton */}
|
||||
<div className="flex py-6">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-5/6" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Another user message skeleton */}
|
||||
<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="space-y-2">
|
||||
<Skeleton className="h-4 w-56" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Another assistant message skeleton */}
|
||||
<div className="flex py-6">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-11/12" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Empty state when no messages and not loading */}
|
||||
{messages.length === 0 && !streamingMessage && !isLoading && (
|
||||
{!isLoadingHistory && messages.length === 0 && !streamingMessage && !isLoading && (
|
||||
<div className="flex-1 flex items-center justify-center min-h-[400px]">
|
||||
<div className="text-center space-y-4 max-w-md mx-auto">
|
||||
<div className="mb-6">
|
||||
@@ -731,7 +781,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{messages.map((message, index) => {
|
||||
{!isLoadingHistory && messages.map((message, index) => {
|
||||
// Find the corresponding tool call for tool messages
|
||||
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
|
||||
if (message.role === 'tool') {
|
||||
@@ -754,7 +804,23 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
);
|
||||
})}
|
||||
|
||||
{renderStreamingMessage()}
|
||||
{!isLoadingHistory && renderStreamingMessage()}
|
||||
|
||||
{/* Resume button - shown when not loading and finish reason is not "stop" or "length" (or no finish reason) */}
|
||||
{!isLoadingHistory && !isLoading && (!lastFinishReason || (lastFinishReason !== 'stop' && lastFinishReason !== 'length')) && messages.length > 0 && (
|
||||
<div className="flex justify-center py-4">
|
||||
<Button
|
||||
onClick={() => startGeneration(providerModel)}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={!providerModel.trim() || !isConfigured}
|
||||
className="gap-2"
|
||||
>
|
||||
<Play className="h-4 w-4" />
|
||||
{t('resume')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error Alert (Console or AI) - Don't show while assistant is loading */}
|
||||
{displayError && !isLoading && (
|
||||
@@ -788,6 +854,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
<ChatInput
|
||||
isLoading={isLoading}
|
||||
isConfigured={isConfigured}
|
||||
isLoadingSettings={isLoadingSettings}
|
||||
providerModel={providerModel}
|
||||
onProviderModelChange={handleModelChange}
|
||||
onSend={handleSend}
|
||||
|
||||
@@ -10,16 +10,12 @@ import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, Rocket, X, Terminal } from 'lucide-react';
|
||||
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Loader2, Code, X, Terminal, Expand, Shrink, Hammer } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { BranchSwitcher } from '@/components/BranchSwitcher';
|
||||
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { type DeviceMode } from '@/components/ui/device-toggle';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
@@ -28,7 +24,6 @@ import {
|
||||
import { cn } from '@/lib/utils';
|
||||
import { FileTree } from './FileTree';
|
||||
import { FileEditor } from './FileEditor';
|
||||
import { DeployDialog } from '@/components/DeployDialog';
|
||||
import { Terminal as TerminalComponent } from '@/components/Terminal';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
@@ -38,8 +33,6 @@ interface PreviewPaneProps {
|
||||
projectId: string;
|
||||
activeTab: 'preview' | 'code';
|
||||
onToggleView?: () => void;
|
||||
projectName?: string;
|
||||
onFirstInteraction?: () => void;
|
||||
isPreviewable?: boolean;
|
||||
}
|
||||
|
||||
@@ -73,7 +66,7 @@ interface JSONRPCResponse {
|
||||
id: number;
|
||||
}
|
||||
|
||||
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction: _onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
|
||||
export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable = true }: PreviewPaneProps) {
|
||||
const { t } = useTranslation();
|
||||
const { config } = useAppContext();
|
||||
const { previewDomain } = config;
|
||||
@@ -88,7 +81,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
|
||||
const [historyIndex, setHistoryIndex] = useState(0);
|
||||
|
||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||
const [isFullscreen, setIsFullscreen] = useState(false);
|
||||
const [deviceMode, setDeviceMode] = useState<DeviceMode>('laptop');
|
||||
const previewContainerRef = useRef<HTMLDivElement>(null);
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
@@ -102,14 +97,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [shouldBuild, setShouldBuild] = useState(false);
|
||||
|
||||
const handleBuildProject = useCallback(() => {
|
||||
buildProject(undefined, {
|
||||
onError: (error) => {
|
||||
console.error('Build failed:', error);
|
||||
}
|
||||
});
|
||||
}, [buildProject]);
|
||||
|
||||
// Handle "build" URL parameter on initial load
|
||||
useEffect(() => {
|
||||
if (searchParams.has('build')) {
|
||||
@@ -126,9 +113,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
useEffect(() => {
|
||||
if (shouldBuild && isPreviewable && !isBuildLoading) {
|
||||
setShouldBuild(false);
|
||||
handleBuildProject();
|
||||
buildProject(undefined, {
|
||||
onError: (error) => {
|
||||
console.error('Build failed:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [isBuildLoading, isPreviewable, handleBuildProject, shouldBuild]);
|
||||
}, [isBuildLoading, isPreviewable, buildProject, shouldBuild]);
|
||||
|
||||
const loadFileContent = useCallback(async (filePath: string) => {
|
||||
// Skip loading media files - they can't be edited as text
|
||||
@@ -291,33 +282,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
sendNavigationCommand('refresh');
|
||||
}, [sendNavigationCommand]);
|
||||
|
||||
const goBackIframe = useCallback(() => {
|
||||
if (historyIndex > 0) {
|
||||
// Move back in history
|
||||
const newIndex = historyIndex - 1;
|
||||
const targetPath = navigationHistory[newIndex];
|
||||
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentPath(targetPath);
|
||||
|
||||
// Tell iframe to navigate to this path
|
||||
sendNavigationCommand('navigate', { url: targetPath });
|
||||
}
|
||||
}, [historyIndex, navigationHistory, sendNavigationCommand]);
|
||||
|
||||
const goForwardIframe = useCallback(() => {
|
||||
if (historyIndex < navigationHistory.length - 1) {
|
||||
// Move forward in history
|
||||
const newIndex = historyIndex + 1;
|
||||
const targetPath = navigationHistory[newIndex];
|
||||
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentPath(targetPath);
|
||||
|
||||
// Tell iframe to navigate to this path
|
||||
sendNavigationCommand('navigate', { url: targetPath });
|
||||
}
|
||||
}, [historyIndex, navigationHistory, sendNavigationCommand]);
|
||||
const toggleFullscreen = useCallback(() => {
|
||||
setIsFullscreen(prev => !prev);
|
||||
}, []);
|
||||
|
||||
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
|
||||
const { params, id } = request;
|
||||
@@ -522,7 +489,11 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
// Automatically trigger a rebuild after saving a file
|
||||
if (isPreviewable) {
|
||||
console.log('File saved, triggering rebuild...');
|
||||
handleBuildProject();
|
||||
buildProject(undefined, {
|
||||
onError: (error) => {
|
||||
console.error('Build failed:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to save file:', error);
|
||||
@@ -553,9 +524,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 relative"
|
||||
className="h-8 gap-2 relative"
|
||||
>
|
||||
<Bug className="h-4 w-4" />
|
||||
<span className="hidden lg:inline">Logs</span>
|
||||
{hasConsoleErrors && (
|
||||
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
|
||||
)}
|
||||
@@ -563,7 +535,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="end"
|
||||
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0"
|
||||
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0 z-[9999]"
|
||||
sideOffset={4}
|
||||
>
|
||||
|
||||
@@ -628,118 +600,113 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
);
|
||||
};
|
||||
|
||||
const Menu = () => {
|
||||
const isAnyLoading = isBuildLoading;
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<MenuIcon className="h-4 w-4" />
|
||||
<span className="sr-only">Open menu</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48 sm:w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={handleBuildProject}
|
||||
disabled={isBuildLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
{isBuildLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Play className="h-4 w-4" />
|
||||
)}
|
||||
{isBuildLoading ? 'Building...' : 'Build'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setDeployDialogOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<Rocket className="h-4 w-4" />
|
||||
Deploy
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-full">
|
||||
<Tabs value={activeTab} className="h-full">
|
||||
{isPreviewable && (
|
||||
<TabsContent value="preview" className="h-full mt-0">
|
||||
<div className="h-full w-full flex flex-col relative">
|
||||
{/* Always show browser address bar */}
|
||||
<div className="h-12 flex items-center w-full">
|
||||
<BrowserAddressBar
|
||||
currentPath={currentPath}
|
||||
onNavigate={hasBuiltProject ? navigateIframe : undefined}
|
||||
onRefresh={hasBuiltProject ? refreshIframe : undefined}
|
||||
onBack={hasBuiltProject ? goBackIframe : undefined}
|
||||
onForward={hasBuiltProject ? goForwardIframe : undefined}
|
||||
canGoBack={hasBuiltProject && historyIndex > 0}
|
||||
canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1}
|
||||
extraContent={(
|
||||
<div className="flex items-center">
|
||||
{(!isMobile && onToggleView && isPreviewable) && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onToggleView}
|
||||
className="h-8 gap-2"
|
||||
>
|
||||
<Code className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<ConsoleDropdown />
|
||||
<Menu />
|
||||
</div>
|
||||
<div
|
||||
ref={previewContainerRef}
|
||||
className={cn(
|
||||
"h-full w-full flex flex-col relative",
|
||||
isFullscreen && "fixed inset-0 z-[100] bg-background"
|
||||
)}
|
||||
>
|
||||
{/* Top navigation bar */}
|
||||
<div className="h-12 flex items-center gap-2 p-2 border-b bg-background w-full">
|
||||
{/* Left side - fullscreen toggle */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={toggleFullscreen}
|
||||
className="h-8 w-8 p-0"
|
||||
title={isFullscreen ? 'Exit fullscreen' : 'Enter fullscreen'}
|
||||
>
|
||||
{isFullscreen ? (
|
||||
<Shrink className="h-4 w-4" />
|
||||
) : (
|
||||
<Expand className="h-4 w-4" />
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
|
||||
{/* Center - address bar with device toggle */}
|
||||
<div className="flex-1 px-6">
|
||||
<div className="relative max-w-64 mx-auto">
|
||||
<BrowserAddressBar
|
||||
currentPath={currentPath}
|
||||
onNavigate={hasBuiltProject ? navigateIframe : undefined}
|
||||
onRefresh={hasBuiltProject ? refreshIframe : undefined}
|
||||
navigationHistory={navigationHistory}
|
||||
deviceMode={deviceMode}
|
||||
onDeviceModeChange={setDeviceMode}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right side - actions */}
|
||||
<div className="flex items-center gap-1">
|
||||
{/* Build button */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => buildProject(undefined, {
|
||||
onError: (error) => {
|
||||
console.error('Build failed:', error);
|
||||
}
|
||||
})}
|
||||
disabled={isBuildLoading}
|
||||
className="h-8 gap-2"
|
||||
title="Build project"
|
||||
>
|
||||
{isBuildLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Hammer className="h-4 w-4" />
|
||||
)}
|
||||
<span className="hidden lg:inline">Build</span>
|
||||
</Button>
|
||||
{(!isMobile && onToggleView && isPreviewable) && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onToggleView}
|
||||
className="h-8 gap-2"
|
||||
>
|
||||
<Code className="h-4 w-4" />
|
||||
<span className="hidden lg:inline">Code</span>
|
||||
</Button>
|
||||
)}
|
||||
<ConsoleDropdown />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content area */}
|
||||
<div className="flex-1">
|
||||
<div className="flex-1 flex items-center justify-center bg-muted/30">
|
||||
{hasBuiltProject ? (
|
||||
<iframe
|
||||
key={projectId}
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.${previewDomain}/`}
|
||||
className="w-full h-full border-0"
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin allow-forms"
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
"h-full transition-all duration-300 ease-in-out bg-background",
|
||||
deviceMode === 'laptop' && "w-full",
|
||||
deviceMode === 'tablet' && "w-full max-w-3xl shadow-lg",
|
||||
deviceMode === 'phone' && "w-full max-w-sm shadow-lg"
|
||||
)}
|
||||
>
|
||||
<iframe
|
||||
key={projectId}
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.${previewDomain}/`}
|
||||
className="w-full h-full border-0"
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin allow-forms"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center bg-muted">
|
||||
<div className="h-full w-full flex items-center justify-center bg-muted">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
<p className="text-muted-foreground">
|
||||
{t('buildProjectToSeePreview')}
|
||||
</p>
|
||||
<Button
|
||||
onClick={handleBuildProject}
|
||||
disabled={isBuildLoading}
|
||||
variant="outline"
|
||||
className="gap-2"
|
||||
>
|
||||
{isBuildLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
Building...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="h-5 w-5" />
|
||||
Build Project
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -764,8 +731,24 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<TabsContent value="code" className="h-full mt-0">
|
||||
{isMobile ? (
|
||||
<div className="h-full flex flex-col min-h-0">
|
||||
{/* Mobile Code view header */}
|
||||
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background flex-shrink-0">
|
||||
<BranchSwitcher projectId={projectId} />
|
||||
<div className="flex-1" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setMobileCodeView(mobileCodeView === 'terminal' ? 'explorer' : 'terminal')}
|
||||
className="gap-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Terminal className="h-4 w-4" />
|
||||
<span className="hidden sm:inline">Terminal</span>
|
||||
</Button>
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
</div>
|
||||
|
||||
{mobileCodeView === 'explorer' ? (
|
||||
<div className="flex-1 relative min-h-0">
|
||||
<div className="flex-1 min-h-0">
|
||||
<ScrollArea className="h-full">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
@@ -776,35 +759,11 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
{/* Floating Terminal Button */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setMobileCodeView('terminal')}
|
||||
className="fixed right-4 bottom-14 mb-safe z-20 size-12 p-0 rounded-full shadow-lg bg-background border-2"
|
||||
>
|
||||
<Terminal className="h-6 w-6" />
|
||||
</Button>
|
||||
</div>
|
||||
) : mobileCodeView === 'terminal' ? (
|
||||
<>
|
||||
<div className="h-12 px-3 flex items-center gap-2 bg-black text-purple-400 flex-shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setMobileCodeView('explorer')}
|
||||
className="p-1 hover:bg-transparent hover:text-white"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<h3 className="font-semibold">
|
||||
Terminal
|
||||
</h3>
|
||||
</div>
|
||||
<div className="flex-1 min-h-0">
|
||||
<TerminalComponent cwd={`${projectsPath}/${projectId}`} />
|
||||
</div>
|
||||
</>
|
||||
<div className="flex-1 min-h-0">
|
||||
<TerminalComponent cwd={`${projectsPath}/${projectId}`} />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5 flex items-center gap-2">
|
||||
@@ -856,7 +815,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<div className="h-full flex flex-col">
|
||||
{/* Code view header with back button */}
|
||||
{!isMobile && onToggleView && isPreviewable && (
|
||||
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background">
|
||||
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background gap-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@@ -867,6 +826,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
{t('backToPreview')}
|
||||
</Button>
|
||||
<div className="flex-1" />
|
||||
<BranchSwitcher projectId={projectId} />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@@ -874,13 +834,16 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
className="gap-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Terminal className="h-4 w-4" />
|
||||
<span className="hidden lg:inline">Terminal</span>
|
||||
</Button>
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
</div>
|
||||
)}
|
||||
{/* Code view header without back button for non-previewable projects */}
|
||||
{!isMobile && !isPreviewable && (
|
||||
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background">
|
||||
<div className="flex-1" />
|
||||
<BranchSwitcher projectId={projectId} />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@@ -888,6 +851,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
className="gap-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Terminal className="h-4 w-4" />
|
||||
<span className="hidden lg:inline">Terminal</span>
|
||||
</Button>
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
</div>
|
||||
@@ -939,16 +903,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
{/* Deploy Dialog */}
|
||||
{projectName && (
|
||||
<DeployDialog
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
open={deployDialogOpen}
|
||||
onOpenChange={setDeployDialogOpen}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -61,7 +61,7 @@ export function StarButton({
|
||||
>
|
||||
<Star
|
||||
className={cn(
|
||||
"h-4 w-4",
|
||||
"size-5",
|
||||
isFavorite ? "text-yellow-500 fill-current" : "text-muted-foreground hover:text-yellow-500"
|
||||
)}
|
||||
/>
|
||||
|
||||
+18
-50
@@ -8,7 +8,7 @@ import { useFS } from '@/hooks/useFS';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml';
|
||||
import { stripAnsiCodes } from '@/lib/ansiToHtml';
|
||||
|
||||
interface TerminalProps {
|
||||
cwd: string;
|
||||
@@ -104,50 +104,22 @@ export function Terminal({ cwd, className }: TerminalProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if running in Electron - use real shell
|
||||
if (window.electron?.shell) {
|
||||
// Use the provided cwd (Electron will expand ~ if present)
|
||||
const result = await window.electron.shell.exec(command, cwd);
|
||||
// Use virtual shell
|
||||
if (!shellToolRef.current) return;
|
||||
|
||||
// Format output
|
||||
let output = '';
|
||||
|
||||
if (result.stdout) {
|
||||
output += result.stdout;
|
||||
}
|
||||
|
||||
if (result.stderr) {
|
||||
if (output) output += '\n';
|
||||
output += result.stderr;
|
||||
}
|
||||
|
||||
// Add exit code info for non-zero exits
|
||||
if (result.exitCode !== 0) {
|
||||
if (output) output += '\n';
|
||||
output += `Exit code: ${result.exitCode}`;
|
||||
}
|
||||
|
||||
if (output) {
|
||||
addLine('output', output);
|
||||
}
|
||||
// Handle special help command
|
||||
if (command.trim() === 'help') {
|
||||
const availableCommands = shellToolRef.current.getAvailableCommands();
|
||||
const helpText = `Available commands:\n\n${availableCommands.map(cmd =>
|
||||
`${cmd.name.padEnd(12)} - ${cmd.description}`
|
||||
).join('\n')}\n\nUse 'which <command>' for more details about a specific command.`;
|
||||
addLine('output', helpText);
|
||||
} else {
|
||||
// Use virtual shell (browser mode)
|
||||
if (!shellToolRef.current) return;
|
||||
const result = await shellToolRef.current.execute({ command });
|
||||
|
||||
// Handle special help command
|
||||
if (command.trim() === 'help') {
|
||||
const availableCommands = shellToolRef.current.getAvailableCommands();
|
||||
const helpText = `Available commands:\n\n${availableCommands.map(cmd =>
|
||||
`${cmd.name.padEnd(12)} - ${cmd.description}`
|
||||
).join('\n')}\n\nUse 'which <command>' for more details about a specific command.`;
|
||||
addLine('output', helpText);
|
||||
} else {
|
||||
const result = await shellToolRef.current.execute({ command });
|
||||
|
||||
// Add output
|
||||
if (result.content && result.content.trim()) {
|
||||
addLine('output', result.content);
|
||||
}
|
||||
// Add output
|
||||
if (result.content && result.content.trim()) {
|
||||
addLine('output', result.content);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -155,7 +127,7 @@ export function Terminal({ cwd, className }: TerminalProps) {
|
||||
} finally {
|
||||
setIsExecuting(false);
|
||||
}
|
||||
}, [addLine, commandHistory, cwd]);
|
||||
}, [addLine, commandHistory]);
|
||||
|
||||
const handleSubmit = useCallback((e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
@@ -193,9 +165,7 @@ export function Terminal({ cwd, className }: TerminalProps) {
|
||||
|
||||
const copyToClipboard = useCallback(async (content: string) => {
|
||||
try {
|
||||
// Strip ANSI codes when copying to clipboard
|
||||
const cleanContent = content.replace(/\u001b\[(?:\d+;)*\d+m/g, '');
|
||||
await navigator.clipboard.writeText(cleanContent);
|
||||
await navigator.clipboard.writeText(content);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy to clipboard:', error);
|
||||
}
|
||||
@@ -230,16 +200,14 @@ export function Terminal({ cwd, className }: TerminalProps) {
|
||||
${' '}
|
||||
</span>
|
||||
) : null}
|
||||
{containsAnsiCodes(line.content)
|
||||
? <span dangerouslySetInnerHTML={{ __html: ansiToHtml(line.content) }} />
|
||||
: line.content}
|
||||
{stripAnsiCodes(line.content)}
|
||||
</pre>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
copyToClipboard(line.content);
|
||||
copyToClipboard(stripAnsiCodes(line.content));
|
||||
}}
|
||||
className="absolute right-0 top-0 h-4 w-4 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-gray-500 hover:text-white hover:bg-gray-700"
|
||||
>
|
||||
|
||||
@@ -3,9 +3,9 @@ import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { URLFragmentHandler } from './URLFragmentHandler';
|
||||
|
||||
// Mock the AddProviderDialog component
|
||||
vi.mock('./AddProviderDialog', () => ({
|
||||
AddProviderDialog: ({ open, provider }: { open: boolean; provider: { id: string; baseURL: string; apiKey?: string; nostr?: boolean; proxy?: boolean } }) => {
|
||||
// Mock the AddSharedProviderDialog component
|
||||
vi.mock('./AddSharedProviderDialog', () => ({
|
||||
AddSharedProviderDialog: ({ open, provider }: { open: boolean; provider: { id: string; baseURL: string; apiKey?: string; nostr?: boolean; proxy?: boolean } }) => {
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div data-testid="add-provider-dialog">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import { AddProviderDialog } from '@/components/AddProviderDialog';
|
||||
import { AddSharedProviderDialog } from '@/components/AddSharedProviderDialog';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||
|
||||
@@ -78,7 +78,7 @@ export function URLFragmentHandler() {
|
||||
}
|
||||
|
||||
return (
|
||||
<AddProviderDialog
|
||||
<AddSharedProviderDialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={handleDialogClose}
|
||||
provider={providerFromURL}
|
||||
|
||||
@@ -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,113 +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 parse and separate file attachments
|
||||
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 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();
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { Badge } from '@/components/ui/badge';
|
||||
import type OpenAI from 'openai';
|
||||
|
||||
interface UserMessageProps {
|
||||
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>;
|
||||
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPart>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -13,71 +13,12 @@ interface UserMessageProps {
|
||||
*/
|
||||
export function UserMessage({ content }: UserMessageProps) {
|
||||
// Convert content to array format for uniform processing
|
||||
const contentParts = typeof content === 'string'
|
||||
const parts = 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
|
||||
// Matches the pattern anywhere in the text
|
||||
const filePattern = /Added file:\s*(\/tmp\/[^\s\n]+)/g;
|
||||
|
||||
// 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();
|
||||
|
||||
// Find all file patterns in this text part
|
||||
const fileMatches: Array<{ filepath: string; index: number; length: number }> = [];
|
||||
let match;
|
||||
filePattern.lastIndex = 0; // Reset regex
|
||||
|
||||
while ((match = filePattern.exec(text)) !== null) {
|
||||
fileMatches.push({
|
||||
filepath: match[1], // "/tmp/filename.txt"
|
||||
index: match.index,
|
||||
length: match[0].length
|
||||
});
|
||||
}
|
||||
|
||||
if (fileMatches.length > 0) {
|
||||
// Split text around file patterns and process each segment
|
||||
let lastIndex = 0;
|
||||
|
||||
fileMatches.forEach((fileMatch) => {
|
||||
// Add text before the file pattern
|
||||
if (fileMatch.index > lastIndex) {
|
||||
const textBefore = text.substring(lastIndex, fileMatch.index).trim();
|
||||
if (textBefore) {
|
||||
processedParts.push({ type: 'text', content: textBefore });
|
||||
}
|
||||
}
|
||||
|
||||
// Add the file attachment badge (without showing "Added file:" text)
|
||||
processedParts.push({
|
||||
type: 'file',
|
||||
content: '', // Empty - badge will show filename only
|
||||
filepath: fileMatch.filepath
|
||||
});
|
||||
|
||||
lastIndex = fileMatch.index + fileMatch.length;
|
||||
});
|
||||
|
||||
// Add remaining text after the last file pattern
|
||||
if (lastIndex < text.length) {
|
||||
const textAfter = text.substring(lastIndex).trim();
|
||||
if (textAfter) {
|
||||
processedParts.push({ type: 'text', content: textAfter });
|
||||
}
|
||||
}
|
||||
} else if (text) {
|
||||
// No file patterns found, treat as regular text
|
||||
processedParts.push({ type: 'text', content: text });
|
||||
}
|
||||
});
|
||||
: content.filter(part => part.type === 'text');
|
||||
|
||||
// If no content, return empty
|
||||
if (processedParts.length === 0) {
|
||||
if (parts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -87,28 +28,42 @@ export function UserMessage({ content }: UserMessageProps) {
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{processedParts.map((part, index) => {
|
||||
{parts.map((part, index) => {
|
||||
if (part.type === 'text') {
|
||||
// Only render text if it has content
|
||||
if (!part.content.trim()) return null;
|
||||
if (!part.text.trim()) return null;
|
||||
|
||||
// Detect "Added file: <filename>" pattern
|
||||
const fileAddedMatch = /^Added file: (\/[^\s\n]+$)/g.exec(part.text);
|
||||
console.log('fileAddedMatch', part, fileAddedMatch);
|
||||
if (fileAddedMatch && fileAddedMatch[1]) {
|
||||
const path = fileAddedMatch[1];
|
||||
const filename = getFileName(path);
|
||||
return (
|
||||
<div key={index} className="flex items-center gap-2 max-w-full min-w-0">
|
||||
<Badge variant="secondary" className="inline-flex items-center gap-1.5 px-2 py-1 max-w-full">
|
||||
<span className="flex-shrink-0">
|
||||
<Paperclip className="h-3 w-3" />
|
||||
</span>
|
||||
<span className="text-xs font-medium truncate min-w-0" title={filename}>
|
||||
{filename}
|
||||
</span>
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Regular text rendering
|
||||
return (
|
||||
<div key={index} className="whitespace-pre-wrap">
|
||||
{part.content}
|
||||
{part.text}
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
// Render file attachment badge (no "Added file:" text)
|
||||
const filename = getFileName(part.filepath!);
|
||||
// Unsupported content type
|
||||
return (
|
||||
<div key={index} className="flex items-center gap-2 max-w-full min-w-0">
|
||||
<Badge variant="secondary" className="inline-flex items-center gap-1.5 px-2 py-1 max-w-full">
|
||||
<span className="flex-shrink-0">
|
||||
<Paperclip className="h-3 w-3" />
|
||||
</span>
|
||||
<span className="text-xs font-medium truncate min-w-0" title={filename}>
|
||||
{filename}
|
||||
</span>
|
||||
</Badge>
|
||||
<div key={index} className="text-sm text-red-500">
|
||||
[Unsupported content type]
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -251,7 +251,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
|
||||
useEffect(() => {
|
||||
if (target) {
|
||||
setComment('Zapped with MKStack!');
|
||||
setComment('Zapped from Shakespeare!');
|
||||
}
|
||||
}, [target]);
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -11,6 +11,7 @@ import { useFS } from '@/hooks/useFS';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { formatRelativeTime } from '@/lib/utils';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
interface GitCommit {
|
||||
oid: string;
|
||||
@@ -40,6 +41,8 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [internalOpen, setInternalOpen] = useState(false);
|
||||
const gitCache = useRef<object>({});
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Use controlled or internal state
|
||||
const isOpen = controlledOpen !== undefined ? controlledOpen : internalOpen;
|
||||
@@ -72,6 +75,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
const gitLog = await git.log({
|
||||
dir: projectPath,
|
||||
depth: 50, // Limit to last 50 commits
|
||||
cache: gitCache.current,
|
||||
});
|
||||
|
||||
setCommits(gitLog);
|
||||
@@ -86,11 +90,10 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
const rollbackToCommit = useCallback(async (targetCommit: GitCommit) => {
|
||||
if (!fs) return;
|
||||
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
setIsRollingBack(targetCommit.oid);
|
||||
|
||||
try {
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
// Get the current HEAD commit
|
||||
const currentCommit = await git.resolveRef({
|
||||
dir: projectPath,
|
||||
@@ -110,6 +113,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
const allCommits = await git.log({
|
||||
dir: projectPath,
|
||||
depth: 1000,
|
||||
cache: gitCache.current,
|
||||
});
|
||||
|
||||
// Find the index of target commit and current HEAD
|
||||
@@ -142,12 +146,14 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
const targetFiles = await git.listFiles({
|
||||
dir: projectPath,
|
||||
ref: targetCommit.oid,
|
||||
cache: gitCache.current,
|
||||
});
|
||||
|
||||
// Get current files to know what to remove
|
||||
const currentFiles = await git.listFiles({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
cache: gitCache.current,
|
||||
});
|
||||
|
||||
// Remove files that don't exist in target commit
|
||||
@@ -158,6 +164,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
await git.remove({
|
||||
dir: projectPath,
|
||||
filepath,
|
||||
cache: gitCache.current,
|
||||
});
|
||||
} catch (err) {
|
||||
// File might not exist, continue
|
||||
@@ -173,6 +180,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
dir: projectPath,
|
||||
oid: targetCommit.oid,
|
||||
filepath,
|
||||
cache: gitCache.current,
|
||||
});
|
||||
|
||||
// Ensure directory exists
|
||||
@@ -188,6 +196,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
await git.add({
|
||||
dir: projectPath,
|
||||
filepath,
|
||||
cache: gitCache.current,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(`Failed to restore ${filepath}:`, err);
|
||||
@@ -209,6 +218,7 @@ ${commitsToRevert.map(c => {
|
||||
await git.commit({
|
||||
dir: projectPath,
|
||||
message: revertMessage,
|
||||
cache: gitCache.current,
|
||||
});
|
||||
|
||||
toast({
|
||||
@@ -228,18 +238,18 @@ ${commitsToRevert.map(c => {
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
queryClient.invalidateQueries({ queryKey: ['git-sync', projectPath] })
|
||||
setIsRollingBack(null);
|
||||
}
|
||||
}, [git, fs, projectId, toast, navigate, setIsOpen, projectsPath]);
|
||||
}, [fs, projectsPath, projectId, git, toast, setIsOpen, navigate, queryClient]);
|
||||
|
||||
const resetToHead = useCallback(async () => {
|
||||
if (!fs) return;
|
||||
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
setIsRollingBack('HEAD');
|
||||
|
||||
try {
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
// Get the current HEAD commit
|
||||
const headCommit = await git.resolveRef({
|
||||
dir: projectPath,
|
||||
@@ -250,11 +260,13 @@ ${commitsToRevert.map(c => {
|
||||
const headFiles = await git.listFiles({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
cache: gitCache.current,
|
||||
});
|
||||
|
||||
// Get current files in working directory
|
||||
const currentFiles = await git.listFiles({
|
||||
dir: projectPath,
|
||||
cache: gitCache.current,
|
||||
});
|
||||
|
||||
// Remove files that don't exist in HEAD (equivalent to git clean -fd for tracked files)
|
||||
@@ -275,6 +287,7 @@ ${commitsToRevert.map(c => {
|
||||
dir: projectPath,
|
||||
oid: headCommit,
|
||||
filepath,
|
||||
cache: gitCache.current,
|
||||
});
|
||||
|
||||
// Ensure directory exists
|
||||
@@ -294,6 +307,7 @@ ${commitsToRevert.map(c => {
|
||||
// Get git status to find untracked files
|
||||
const status = await git.statusMatrix({
|
||||
dir: projectPath,
|
||||
cache: gitCache.current,
|
||||
});
|
||||
|
||||
const untrackedFiles = status
|
||||
@@ -327,9 +341,10 @@ ${commitsToRevert.map(c => {
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
queryClient.invalidateQueries({ queryKey: ['git-sync', projectPath] })
|
||||
setIsRollingBack(null);
|
||||
}
|
||||
}, [git, fs, projectId, toast, navigate, setIsOpen, projectsPath]);
|
||||
}, [fs, projectsPath, projectId, git, toast, setIsOpen, navigate, queryClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useState } from 'react';
|
||||
import { Rocket } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { DeploySteps } from './DeploySteps';
|
||||
|
||||
interface DeployButtonProps {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function DeployButton({ projectId, projectName, className, disabled }: DeployButtonProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn("size-8 p-0 group", className)}
|
||||
aria-label="Deploy project"
|
||||
disabled={disabled}
|
||||
>
|
||||
<Rocket className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
className="w-96"
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
<DeploySteps
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +1,11 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Rocket, ExternalLink, AlertCircle } from 'lucide-react';
|
||||
import { Rocket, ExternalLink, AlertCircle, Settings, Cloud } from 'lucide-react';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { useDeploySettings } from '@/hooks/useDeploySettings';
|
||||
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
@@ -27,64 +13,52 @@ import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, CloudflareAdapter, DenoDeployAdapter, DeployAdapter } from '@/lib/deploy';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
import { createRepositoryAnnouncementEvent } from '@/lib/announceRepository';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider, CloudflareProvider, DenoDeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
||||
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
|
||||
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
|
||||
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
|
||||
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
|
||||
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
|
||||
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { DeployAdapter } from '@/lib/deploy/types';
|
||||
import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter';
|
||||
import { NsiteAdapter } from '@/lib/deploy/NsiteAdapter';
|
||||
import { NetlifyAdapter } from '@/lib/deploy/NetlifyAdapter';
|
||||
import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
|
||||
import { CloudflareAdapter } from '@/lib/deploy/CloudflareAdapter';
|
||||
import { DenoDeployAdapter } from '@/lib/deploy/DenoDeployAdapter';
|
||||
|
||||
/**
|
||||
* Helper function to get provider URL for favicon
|
||||
* Normalize a URL string to ensure it has a protocol
|
||||
*/
|
||||
function getProviderUrl(provider: DeployProvider): string | null {
|
||||
switch (provider.type) {
|
||||
case 'shakespeare':
|
||||
if (provider.host) {
|
||||
return `https://${provider.host}`;
|
||||
}
|
||||
return 'https://shakespeare.diy';
|
||||
|
||||
case 'netlify':
|
||||
if (provider.baseURL) {
|
||||
return provider.baseURL;
|
||||
}
|
||||
return 'https://netlify.com';
|
||||
|
||||
case 'vercel':
|
||||
if (provider.baseURL) {
|
||||
return provider.baseURL;
|
||||
}
|
||||
return 'https://vercel.com';
|
||||
|
||||
case 'cloudflare':
|
||||
if (provider.baseURL) {
|
||||
return provider.baseURL;
|
||||
}
|
||||
return 'https://cloudflare.com';
|
||||
|
||||
case 'deno':
|
||||
if (provider.baseURL) {
|
||||
return provider.baseURL;
|
||||
}
|
||||
return 'https://deno.com';
|
||||
|
||||
case 'nsite':
|
||||
return null;
|
||||
|
||||
default:
|
||||
return null;
|
||||
function normalizeUrl(url: string): string {
|
||||
if (/^https?:\/\//i.test(url)) {
|
||||
return url;
|
||||
}
|
||||
return `https://${url}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render provider icon using favicon or fallback
|
||||
*/
|
||||
function renderProviderIcon(provider: DeployProvider, size = 14) {
|
||||
const url = getProviderUrl(provider);
|
||||
function renderProviderIcon(provider: DeployProvider, preset: PresetDeployProvider | undefined, size = 14) {
|
||||
// Use baseURL from configured provider, falling back to preset baseURL
|
||||
const baseURL = ('baseURL' in provider && provider.baseURL) || preset?.baseURL;
|
||||
|
||||
// For Shakespeare, special handling for host field
|
||||
const shakespeareUrl = provider.type === 'shakespeare' && 'host' in provider && provider.host
|
||||
? normalizeUrl(provider.host)
|
||||
: undefined;
|
||||
|
||||
const url = shakespeareUrl || baseURL;
|
||||
|
||||
if (url) {
|
||||
return (
|
||||
@@ -99,11 +73,10 @@ function renderProviderIcon(provider: DeployProvider, size = 14) {
|
||||
return <Rocket size={size} />;
|
||||
}
|
||||
|
||||
interface DeployDialogProps {
|
||||
interface DeployStepsProps {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
interface ShakespeareFormData {
|
||||
@@ -132,7 +105,7 @@ interface DenoDeployFormData {
|
||||
projectName: string;
|
||||
}
|
||||
|
||||
export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) {
|
||||
export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProps) {
|
||||
const { t } = useTranslation();
|
||||
const { settings } = useDeploySettings();
|
||||
const { settings: projectSettings, updateSettings: updateProjectSettings } = useProjectDeploySettings(projectId);
|
||||
@@ -141,6 +114,8 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { config } = useAppContext();
|
||||
const { nostr } = useNostr();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const { git } = useGit();
|
||||
|
||||
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
|
||||
const [isDeploying, setIsDeploying] = useState(false);
|
||||
@@ -170,21 +145,19 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
projectName: projectName || projectId,
|
||||
});
|
||||
|
||||
// Load project settings when dialog opens
|
||||
// Load project settings when component mounts
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
// First, try to use the currentProvider from project settings
|
||||
if (projectSettings.currentProvider && settings.providers.some(p => p.id === projectSettings.currentProvider)) {
|
||||
setSelectedProviderId(projectSettings.currentProvider);
|
||||
} else {
|
||||
// Otherwise, find the first configured provider in project settings
|
||||
const providerIds = Object.keys(projectSettings.providers);
|
||||
if (providerIds.length > 0) {
|
||||
setSelectedProviderId(providerIds[0]);
|
||||
}
|
||||
// First, try to use the currentProvider from project settings
|
||||
if (projectSettings.currentProvider && settings.providers.some(p => p.id === projectSettings.currentProvider)) {
|
||||
setSelectedProviderId(projectSettings.currentProvider);
|
||||
} else {
|
||||
// Otherwise, find the first configured provider in project settings
|
||||
const providerIds = Object.keys(projectSettings.providers);
|
||||
if (providerIds.length > 0) {
|
||||
setSelectedProviderId(providerIds[0]);
|
||||
}
|
||||
}
|
||||
}, [open, projectSettings, settings.providers]);
|
||||
}, [projectSettings, settings.providers]);
|
||||
|
||||
const selectedProvider = settings.providers.find(p => p.id === selectedProviderId);
|
||||
|
||||
@@ -205,7 +178,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
throw new Error('You must be logged in with Nostr to use Shakespeare Deploy');
|
||||
}
|
||||
|
||||
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
|
||||
const shakespeareProvider = selectedProvider;
|
||||
adapter = new ShakespeareAdapter({
|
||||
fs,
|
||||
signer: user.signer,
|
||||
@@ -214,7 +187,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
corsProxy: shakespeareProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else if (selectedProvider.type === 'nsite') {
|
||||
const nsiteProvider = selectedProvider as import('@/contexts/DeploySettingsContext').NsiteProvider;
|
||||
const nsiteProvider = selectedProvider;
|
||||
|
||||
if (!nsiteForm.nsec) {
|
||||
throw new Error('Site private key (nsec) is required');
|
||||
@@ -229,7 +202,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
blossomServers: nsiteProvider.blossomServers,
|
||||
});
|
||||
} else if (selectedProvider.type === 'netlify') {
|
||||
const netlifyProvider = selectedProvider as NetlifyProvider;
|
||||
const netlifyProvider = selectedProvider;
|
||||
if (!netlifyProvider.apiKey) {
|
||||
throw new Error('Netlify API key is required');
|
||||
}
|
||||
@@ -245,7 +218,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
corsProxy: netlifyProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else if (selectedProvider.type === 'vercel') {
|
||||
const vercelProvider = selectedProvider as VercelProvider;
|
||||
const vercelProvider = selectedProvider;
|
||||
if (!vercelProvider.apiKey) {
|
||||
throw new Error('Vercel API key is required');
|
||||
}
|
||||
@@ -259,7 +232,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
corsProxy: vercelProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else if (selectedProvider.type === 'cloudflare') {
|
||||
const cloudflareProvider = selectedProvider as CloudflareProvider;
|
||||
const cloudflareProvider = selectedProvider;
|
||||
if (!cloudflareProvider.apiKey) {
|
||||
throw new Error('Cloudflare API key is required');
|
||||
}
|
||||
@@ -277,7 +250,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else if (selectedProvider.type === 'deno') {
|
||||
const denoProvider = selectedProvider as DenoDeployProvider;
|
||||
const denoProvider = selectedProvider;
|
||||
if (!denoProvider.apiKey) {
|
||||
throw new Error('Deno Deploy access token is required');
|
||||
}
|
||||
@@ -356,6 +329,65 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
}
|
||||
|
||||
setDeployResult(result);
|
||||
|
||||
// Update repository announcement with deployment URL if using Nostr git
|
||||
try {
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const remoteUrl = await git.getRemoteURL(projectPath, 'origin');
|
||||
|
||||
if (remoteUrl && remoteUrl.startsWith('nostr://') && user) {
|
||||
const nostrURI = await NostrURI.parse(remoteUrl);
|
||||
|
||||
// Query for existing repository announcement
|
||||
const existingRepos = await nostr.query(
|
||||
[{ kinds: [30617], authors: [user.pubkey], '#d': [nostrURI.identifier], limit: 1 }],
|
||||
{ signal: AbortSignal.timeout(5000) }
|
||||
);
|
||||
|
||||
if (existingRepos.length > 0) {
|
||||
const existingEvent = existingRepos[0];
|
||||
|
||||
// Extract existing data from the event
|
||||
const description = existingEvent.tags.find(([tagName]) => tagName === 'description')?.[1];
|
||||
const webTag = existingEvent.tags.find(([tagName]) => tagName === 'web');
|
||||
const existingWebUrls = webTag ? webTag.slice(1) : [];
|
||||
const cloneTag = existingEvent.tags.find(([tagName]) => tagName === 'clone');
|
||||
const cloneUrls = cloneTag ? cloneTag.slice(1) : [];
|
||||
const relaysTag = existingEvent.tags.find(([tagName]) => tagName === 'relays');
|
||||
const relays = relaysTag ? relaysTag.slice(1) : [];
|
||||
const tTags = existingEvent.tags
|
||||
.filter(([tagName]) => tagName === 't')
|
||||
.map(([, value]) => value);
|
||||
const eucTag = existingEvent.tags.find(([tagName, , marker]) => tagName === 'r' && marker === 'euc');
|
||||
const earliestCommit = eucTag?.[1];
|
||||
const name = existingEvent.tags.find(([tagName]) => tagName === 'name')?.[1];
|
||||
|
||||
// Add deployment URL if not already present
|
||||
const deploymentUrl = result.url;
|
||||
const updatedWebUrls = existingWebUrls.includes(deploymentUrl)
|
||||
? existingWebUrls
|
||||
: [...existingWebUrls, deploymentUrl];
|
||||
|
||||
// Create updated repository announcement event
|
||||
const eventTemplate = createRepositoryAnnouncementEvent({
|
||||
repoId: nostrURI.identifier,
|
||||
name,
|
||||
description,
|
||||
webUrls: updatedWebUrls,
|
||||
cloneUrls,
|
||||
relays,
|
||||
tTags: tTags.length > 0 ? tTags : undefined,
|
||||
earliestCommit,
|
||||
});
|
||||
|
||||
// Publish the updated event
|
||||
await publishEvent(eventTemplate);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// Silently fail - updating web tag is not critical for deployment
|
||||
console.warn('Failed to update repository announcement with deployment URL:', err);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Deployment failed');
|
||||
} finally {
|
||||
@@ -374,7 +406,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
setVercelForm({ projectName: projectName || projectId, teamId: '' });
|
||||
setCloudflareForm({ projectName: projectName || projectId });
|
||||
setDenoDeployForm({ projectName: projectName || projectId });
|
||||
onOpenChange(false);
|
||||
onClose();
|
||||
};
|
||||
|
||||
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
|
||||
@@ -409,7 +441,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
if (!selectedProvider) return null;
|
||||
|
||||
if (selectedProvider.type === 'shakespeare') {
|
||||
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
|
||||
const shakespeareProvider = selectedProvider;
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedSubdomain = savedConfig?.type === 'shakespeare' ? savedConfig.data.subdomain : undefined;
|
||||
|
||||
@@ -471,7 +503,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'cloudflare') {
|
||||
const cloudflareProvider = selectedProvider as CloudflareProvider;
|
||||
const cloudflareProvider = selectedProvider;
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedProjectName = savedConfig?.type === 'cloudflare' ? savedConfig.data.projectName : undefined;
|
||||
|
||||
@@ -491,7 +523,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'deno') {
|
||||
const denoProvider = selectedProvider as DenoDeployProvider;
|
||||
const denoProvider = selectedProvider;
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedProjectName = savedConfig?.type === 'deno' ? savedConfig.data.projectName : undefined;
|
||||
|
||||
@@ -514,184 +546,199 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Rocket className="h-5 w-5" />
|
||||
Deploy Project
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Deploy your project to a hosting platform
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h3 className="font-semibold mb-1">Deploy your project</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Choose a provider to deploy your project
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{deployResult ? (
|
||||
<div className="space-y-4">
|
||||
<Alert>
|
||||
<Rocket className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Your project has been successfully deployed!
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
{deployResult ? (
|
||||
<div className="space-y-4">
|
||||
<Alert>
|
||||
<Rocket className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Your project has been successfully deployed!
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Deployed URL</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={deployResult.url}
|
||||
readOnly
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => window.open(deployResult.url, '_blank')}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button onClick={handleClose}>
|
||||
{t('close')}
|
||||
<div className="space-y-2">
|
||||
<Label>Deployed URL</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={deployResult.url}
|
||||
readOnly
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => window.open(deployResult.url, '_blank')}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{settings.providers.length === 0 ? (
|
||||
<Alert>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
No deployment providers configured.{' '}
|
||||
<Link
|
||||
to="/settings/deploy"
|
||||
className="underline hover:no-underline"
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button onClick={handleClose}>
|
||||
{t('close')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{settings.providers.length === 0 ? (
|
||||
<div className="py-8 px-4">
|
||||
<div className="max-w-md mx-auto space-y-6 text-center">
|
||||
{/* Icon */}
|
||||
<div className="flex justify-center">
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 bg-primary/10 rounded-full blur-xl"></div>
|
||||
<div className="relative bg-gradient-to-br from-primary/20 to-primary/5 p-6 rounded-2xl border border-primary/20">
|
||||
<Cloud className="h-12 w-12 text-primary" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Heading */}
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-xl font-semibold">Choose Your Deployment Platform</h3>
|
||||
<p className="text-sm text-muted-foreground leading-relaxed">
|
||||
Deploy your Shakespeare projects to any hosting provider. Configure your preferred platform to get started.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* CTA */}
|
||||
<div className="pt-2">
|
||||
<Button
|
||||
asChild
|
||||
size="lg"
|
||||
className="w-full"
|
||||
onClick={handleClose}
|
||||
>
|
||||
Configure deployment settings
|
||||
</Link>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="provider">Select Provider</Label>
|
||||
<Select value={selectedProviderId} onValueChange={setSelectedProviderId}>
|
||||
<SelectTrigger id="provider">
|
||||
{selectedProvider ? (
|
||||
<div className="flex items-center gap-2">
|
||||
{renderProviderIcon(selectedProvider, 14)}
|
||||
<span>{selectedProvider.name}</span>
|
||||
</div>
|
||||
) : (
|
||||
<SelectValue placeholder="Choose a deployment provider..." />
|
||||
)}
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{settings.providers.map((provider) => (
|
||||
<SelectItem key={provider.id} value={provider.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
{renderProviderIcon(provider, 14)}
|
||||
<span>{provider.name}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Link to="/settings/deploy">
|
||||
<Settings className="h-4 w-4 mr-2" />
|
||||
Configure Deployment Provider
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{selectedProvider && selectedProviderId && (() => {
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const url = savedConfig?.url;
|
||||
|
||||
if (url) {
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label>Select Provider</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{settings.providers.map((provider) => {
|
||||
const preset = PRESET_DEPLOY_PROVIDERS.find(p => p.type === provider.type);
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label>Last Deployment</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={url}
|
||||
readOnly
|
||||
className="flex-1 text-muted-foreground"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => window.open(url, '_blank')}
|
||||
title="Visit last deployment"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
})()}
|
||||
|
||||
{selectedProvider && renderProviderFields()}
|
||||
|
||||
{selectedProvider?.type === 'shakespeare' && !user && (
|
||||
<Alert>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
You must be logged in with Nostr to use Shakespeare Deploy.{' '}
|
||||
<Link
|
||||
to="/settings/nostr"
|
||||
className="underline hover:no-underline"
|
||||
onClick={handleClose}
|
||||
<button
|
||||
key={provider.id}
|
||||
type="button"
|
||||
onClick={() => setSelectedProviderId(provider.id)}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-all",
|
||||
"border-2 hover:scale-105 active:scale-95",
|
||||
selectedProviderId === provider.id
|
||||
? "bg-primary text-primary-foreground border-primary shadow-sm"
|
||||
: "bg-background text-foreground border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
Go to Nostr Settings
|
||||
</Link>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={handleClose}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleDeploy}
|
||||
disabled={
|
||||
!selectedProvider ||
|
||||
isDeploying ||
|
||||
(selectedProvider.type === 'shakespeare' && !user) ||
|
||||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
|
||||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
|
||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
|
||||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
|
||||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
|
||||
}
|
||||
>
|
||||
{isDeploying ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
|
||||
Deploying...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Rocket className="h-4 w-4 mr-2" />
|
||||
Deploy
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
{renderProviderIcon(provider, preset, 14)}
|
||||
<span>{provider.name}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{selectedProvider && selectedProviderId && (() => {
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const url = savedConfig?.url;
|
||||
|
||||
if (url) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label>Last Deployment</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={url}
|
||||
readOnly
|
||||
className="flex-1 text-muted-foreground"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => window.open(url, '_blank')}
|
||||
title="Visit last deployment"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
})()}
|
||||
|
||||
{selectedProvider && renderProviderFields()}
|
||||
|
||||
{selectedProvider?.type === 'shakespeare' && !user && (
|
||||
<Alert>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
You must be logged in with Nostr to use Shakespeare Deploy.{' '}
|
||||
<Link
|
||||
to="/settings/nostr"
|
||||
className="underline hover:no-underline"
|
||||
onClick={handleClose}
|
||||
>
|
||||
Go to Nostr Settings
|
||||
</Link>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{selectedProvider && (
|
||||
<Button
|
||||
onClick={handleDeploy}
|
||||
disabled={
|
||||
isDeploying ||
|
||||
(selectedProvider.type === 'shakespeare' && !user) ||
|
||||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
|
||||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
|
||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
|
||||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
|
||||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
|
||||
}
|
||||
className="w-full"
|
||||
>
|
||||
{isDeploying ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
|
||||
Deploying...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Rocket className="h-4 w-4 mr-2" />
|
||||
Deploy
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
export { ShakespeareDeployForm } from './ShakespeareDeployForm';
|
||||
export { NetlifyDeployForm } from './NetlifyDeployForm';
|
||||
export { VercelDeployForm } from './VercelDeployForm';
|
||||
export { NsiteDeployForm } from './NsiteDeployForm';
|
||||
export { CloudflareDeployForm } from './CloudflareDeployForm';
|
||||
export { DenoDeployForm } from './DenoDeployForm';
|
||||
@@ -0,0 +1,199 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { CloudUpload, Loader2, Check, AlertTriangle } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { useGitSyncState } from '@/hooks/useGitSyncState';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { GitSyncSteps } from './GitSyncSteps';
|
||||
|
||||
interface GitSyncButtonProps {
|
||||
projectId: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [syncSuccess, setSyncSuccess] = useState(false);
|
||||
const [showWarningPopover, setShowWarningPopover] = useState(false);
|
||||
const warningDismissed = useRef(false);
|
||||
|
||||
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
|
||||
const { getError, getState } = useGitSyncState();
|
||||
const { projectsPath } = useFSPaths();
|
||||
|
||||
const dir = `${projectsPath}/${projectId}`;
|
||||
const hasError = !!getError(dir);
|
||||
const gitSyncState = getState(dir);
|
||||
const isGitActionOccurring = gitSyncState?.isActive ?? false;
|
||||
const prevIsGitActionOccurring = useRef(isGitActionOccurring);
|
||||
const prevProjectId = useRef(projectId);
|
||||
|
||||
// Reset state when projectId changes
|
||||
useEffect(() => {
|
||||
if (prevProjectId.current !== projectId) {
|
||||
setSyncSuccess(false);
|
||||
setShowWarningPopover(false);
|
||||
warningDismissed.current = false;
|
||||
prevIsGitActionOccurring.current = isGitActionOccurring;
|
||||
prevProjectId.current = projectId;
|
||||
}
|
||||
}, [projectId, isGitActionOccurring]);
|
||||
|
||||
// Detect when a git action completes successfully
|
||||
useEffect(() => {
|
||||
// If we were syncing and now we're not, and there's no error, show success
|
||||
if (prevIsGitActionOccurring.current && !isGitActionOccurring && !hasError) {
|
||||
setSyncSuccess(true);
|
||||
const timer = setTimeout(() => setSyncSuccess(false), 2500);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
prevIsGitActionOccurring.current = isGitActionOccurring;
|
||||
}, [isGitActionOccurring, hasError]);
|
||||
|
||||
// Check if we need to show the warning popover
|
||||
const needsRemote = !isGitStatusLoading && gitStatus &&
|
||||
!gitStatus.remotes.find(r => r.name === 'origin') &&
|
||||
gitStatus.totalCommits > 1;
|
||||
|
||||
// Show warning popover when purple indicator is visible (only if not dismissed)
|
||||
useEffect(() => {
|
||||
if (needsRemote && !warningDismissed.current && gitStatus.totalCommits > 1) {
|
||||
setShowWarningPopover(true);
|
||||
} else {
|
||||
setShowWarningPopover(false);
|
||||
}
|
||||
}, [gitStatus?.totalCommits, needsRemote]);
|
||||
|
||||
// Handle button click - dismiss warning popover permanently
|
||||
const handleButtonClick = () => {
|
||||
if (showWarningPopover) {
|
||||
warningDismissed.current = true;
|
||||
setShowWarningPopover(false);
|
||||
}
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
// Determine which indicator to show (only one at a time, in priority order)
|
||||
const renderIndicator = () => {
|
||||
// Checkmark: sync just completed successfully - highest priority
|
||||
if (syncSuccess) {
|
||||
return <IndicatorCheck />;
|
||||
}
|
||||
|
||||
// Spinner: git action occurring - second priority
|
||||
if (isGitActionOccurring) {
|
||||
return <IndicatorSpinner />;
|
||||
}
|
||||
|
||||
// Red indicator: error state - second priority
|
||||
if (hasError) {
|
||||
return <IndicatorDot color="red" />;
|
||||
}
|
||||
|
||||
if (isGitStatusLoading || !gitStatus) return null;
|
||||
|
||||
const originRemote = gitStatus.remotes.find(r => r.name === 'origin');
|
||||
const hasRemote = !!originRemote;
|
||||
|
||||
const { remoteBranchExists, ahead, behind, totalCommits } = gitStatus;
|
||||
|
||||
// Yellow indicator: unsynced changes (ahead or behind remote) - third priority
|
||||
const hasUnsyncedChanges = hasRemote && remoteBranchExists && (ahead > 0 || behind > 0);
|
||||
if (hasUnsyncedChanges) {
|
||||
return <IndicatorDot color="yellow" />;
|
||||
}
|
||||
|
||||
// Purple indicator: no remote configured, but has commits - lowest priority
|
||||
const needsRemote = !hasRemote && totalCommits > 1;
|
||||
if (needsRemote) {
|
||||
return <IndicatorDot color="primary" />;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Warning popover - shown when purple indicator is visible */}
|
||||
<Popover open={showWarningPopover} modal={false}>
|
||||
<PopoverTrigger asChild>
|
||||
<div className="relative">
|
||||
{/* Main Git Sync popover */}
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn("size-8 p-0 group relative", className)}
|
||||
aria-label="Sync with Git"
|
||||
onClick={handleButtonClick}
|
||||
>
|
||||
<CloudUpload className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
|
||||
{renderIndicator()}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
className="w-96"
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
<GitSyncSteps projectId={projectId} onClose={() => setOpen(false)} />
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
side="bottom"
|
||||
align="center"
|
||||
className="w-80 pointer-events-none z-40"
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
>
|
||||
<div className="space-y-3 pointer-events-auto">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertTriangle className="size-5 text-primary shrink-0" />
|
||||
<h4 className="font-semibold text-sm">Your project files are not safe</h4>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Your project files are stored in your browser session and could be deleted. Sync with git to back up your project.
|
||||
</p>
|
||||
<Button
|
||||
onClick={handleButtonClick}
|
||||
className="w-full"
|
||||
size="sm"
|
||||
>
|
||||
Continue
|
||||
</Button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function IndicatorDot({ color }: { color: 'primary' | 'yellow' | 'red' }) {
|
||||
return (
|
||||
<span className={cn(
|
||||
"absolute top-1 right-1 h-2 w-2 rounded-full",
|
||||
{
|
||||
'bg-primary': color === 'primary',
|
||||
'bg-yellow-500': color === 'yellow',
|
||||
'bg-red-500': color === 'red',
|
||||
},
|
||||
)} />
|
||||
);
|
||||
}
|
||||
|
||||
function IndicatorSpinner() {
|
||||
return (
|
||||
<Loader2 className="absolute top-1 right-1 size-2.5 animate-spin text-blue-600 dark:text-blue-400" />
|
||||
);
|
||||
}
|
||||
|
||||
function IndicatorCheck() {
|
||||
return (
|
||||
<Check className="absolute top-1 right-1 size-2.5 text-green-600 dark:text-green-400" />
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { SelectProviderStep } from './steps/SelectProviderStep';
|
||||
import { ConfigureRepoStep } from './steps/ConfigureRepoStep';
|
||||
import { SyncStep } from './steps/SyncStep';
|
||||
import { InitSuccessStep } from './steps/InitSuccessStep';
|
||||
import type { StepType, ProviderOption } from './types';
|
||||
|
||||
interface GitSyncStepsProps {
|
||||
projectId: string;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function GitSyncSteps({ projectId, onClose }: GitSyncStepsProps) {
|
||||
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
|
||||
|
||||
const originRemote = gitStatus?.remotes.find(r => r.name === 'origin');
|
||||
|
||||
const remoteUrl = useMemo(() => {
|
||||
if (originRemote) {
|
||||
try {
|
||||
return new URL(originRemote.url);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}, [originRemote]);
|
||||
|
||||
const hasRemote = !!remoteUrl;
|
||||
|
||||
const [currentStep, setCurrentStep] = useState<StepType>(hasRemote ? 'sync' : 'select-provider');
|
||||
const [selectedProvider, setSelectedProvider] = useState<ProviderOption | null>(null);
|
||||
|
||||
// Handle a remote being added after loading
|
||||
useEffect(() => {
|
||||
if (hasRemote && currentStep === 'select-provider') {
|
||||
setCurrentStep('sync');
|
||||
} else if (!hasRemote && currentStep === 'sync') {
|
||||
setCurrentStep('select-provider');
|
||||
}
|
||||
}, [hasRemote, currentStep]);
|
||||
|
||||
// Auto-reset success state after 2 seconds
|
||||
useEffect(() => {
|
||||
if (currentStep === 'init-success') {
|
||||
const timer = setTimeout(() => {
|
||||
setCurrentStep('sync');
|
||||
}, 2000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [currentStep]);
|
||||
|
||||
const handleSelectProvider = (provider: ProviderOption) => {
|
||||
setSelectedProvider(provider);
|
||||
setCurrentStep('configure-repo');
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
setCurrentStep('select-provider');
|
||||
setSelectedProvider(null);
|
||||
};
|
||||
|
||||
const handleSuccess = () => {
|
||||
setCurrentStep('init-success');
|
||||
};
|
||||
|
||||
if (currentStep === 'init-success') {
|
||||
return (
|
||||
<InitSuccessStep
|
||||
projectId={projectId}
|
||||
onChangeStep={setCurrentStep}
|
||||
onClose={onClose}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Don't render anything while loading git status
|
||||
if (isGitStatusLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (currentStep === 'configure-repo' && selectedProvider) {
|
||||
return (
|
||||
<ConfigureRepoStep
|
||||
projectId={projectId}
|
||||
selectedProvider={selectedProvider}
|
||||
onBack={handleBack}
|
||||
onSuccess={handleSuccess}
|
||||
onChangeStep={setCurrentStep}
|
||||
onClose={onClose}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Render the appropriate step
|
||||
if (!remoteUrl || currentStep === 'select-provider') {
|
||||
return (
|
||||
<SelectProviderStep
|
||||
projectId={projectId}
|
||||
onSelectProvider={handleSelectProvider}
|
||||
onChangeStep={setCurrentStep}
|
||||
onClose={onClose}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (currentStep === 'sync') {
|
||||
return (
|
||||
<SyncStep
|
||||
projectId={projectId}
|
||||
remoteUrl={remoteUrl}
|
||||
onChangeStep={setCurrentStep}
|
||||
onClose={onClose}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { GitSyncButton } from './GitSyncButton';
|
||||
export type { ProviderOption, StepType } from './types';
|
||||
@@ -0,0 +1,412 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { createRepositoryAnnouncementEvent } from '@/lib/announceRepository';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import type { ConfigureRepoStepProps } from '../types';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
import { useGitAutosync } from '@/hooks/useGitAutosync';
|
||||
import { ArrowUp } from 'lucide-react';
|
||||
|
||||
// Helper function to convert kebab-case to Title Case
|
||||
function kebabToTitleCase(str: string): string {
|
||||
return str
|
||||
.split('-')
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
export function ConfigureRepoStep({
|
||||
projectId,
|
||||
selectedProvider,
|
||||
onBack,
|
||||
onSuccess,
|
||||
onClose,
|
||||
}: ConfigureRepoStepProps) {
|
||||
const [repositoryUrl, setRepositoryUrl] = useState('');
|
||||
const [repoIdentifier, setRepoIdentifier] = useState(projectId);
|
||||
const [repoName, setRepoName] = useState(kebabToTitleCase(projectId));
|
||||
const [isRepoNameManuallyEdited, setIsRepoNameManuallyEdited] = useState(false);
|
||||
const [isPushing, setIsPushing] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
|
||||
const dir = `${projectsPath}/${projectId}`;
|
||||
|
||||
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
|
||||
const { refetch: refetchAutosync } = useGitAutosync(dir);
|
||||
const { nostr } = useNostr();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const { fs } = useFS();
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Auto-update repo name when repo identifier changes (unless manually edited)
|
||||
useEffect(() => {
|
||||
if (!isRepoNameManuallyEdited) {
|
||||
setRepoName(kebabToTitleCase(repoIdentifier));
|
||||
}
|
||||
}, [repoIdentifier, isRepoNameManuallyEdited]);
|
||||
|
||||
// Handler for repo identifier changes
|
||||
const handleRepoIdentifierChange = (value: string) => {
|
||||
setRepoIdentifier(value);
|
||||
};
|
||||
|
||||
// Handler for repo name changes
|
||||
const handleRepoNameChange = (value: string) => {
|
||||
setRepoName(value);
|
||||
setIsRepoNameManuallyEdited(true);
|
||||
};
|
||||
|
||||
const handlePushInitial = async () => {
|
||||
setIsPushing(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (selectedProvider.id === 'nostr') {
|
||||
if (!user) {
|
||||
throw new Error('User is not logged in');
|
||||
}
|
||||
|
||||
// Check if a NIP-34 repo announcement already exists for this project
|
||||
const existingRepos = await nostr.query(
|
||||
[{ kinds: [30617], authors: [user.pubkey], '#d': [repoIdentifier], limit: 1 }],
|
||||
{ signal: AbortSignal.timeout(5000) }
|
||||
);
|
||||
|
||||
// Convert user's GRASP servers to clone URLs and relay URLs
|
||||
const npub = nip19.npubEncode(user.pubkey);
|
||||
const cloneUrls = new Set<string>();
|
||||
const relays = new Set<string>();
|
||||
|
||||
for (const graspRelay of config.graspMetadata.relays) {
|
||||
try {
|
||||
const relayUrl = new URL(graspRelay.url);
|
||||
relays.add(relayUrl.href);
|
||||
|
||||
const cloneUrl = new URL(`/${npub}/${repoIdentifier}.git`, `https://${relayUrl.host}`);
|
||||
|
||||
cloneUrls.add(cloneUrl.href);
|
||||
} catch {
|
||||
// fallthrough
|
||||
}
|
||||
}
|
||||
|
||||
for (const relay of config.relayMetadata.relays.filter(r => r.write)) {
|
||||
try {
|
||||
const relayUrl = new URL(relay.url);
|
||||
relays.add(relayUrl.href);
|
||||
} catch {
|
||||
// fallthrough
|
||||
}
|
||||
}
|
||||
|
||||
// Validate that we have at least one clone URL and relay
|
||||
if (cloneUrls.size === 0 || relays.size === 0) {
|
||||
throw new Error('No Nostr git servers configured. Please configure Nostr git servers in Settings > Nostr.');
|
||||
}
|
||||
|
||||
let repoEvent: NostrEvent;
|
||||
|
||||
if (existingRepos.length > 0) {
|
||||
// Use existing repo announcement as template and update with current GRASP servers
|
||||
const existingEvent = existingRepos[0];
|
||||
|
||||
// Extract existing data from the event
|
||||
const description = existingEvent.tags.find(([tagName]) => tagName === 'description')?.[1];
|
||||
const webTag = existingEvent.tags.find(([tagName]) => tagName === 'web');
|
||||
const webUrls = webTag ? webTag.slice(1) : undefined;
|
||||
const tTags = existingEvent.tags
|
||||
.filter(([tagName]) => tagName === 't')
|
||||
.map(([, value]) => value);
|
||||
const eucTag = existingEvent.tags.find(([tagName, , marker]) => tagName === 'r' && marker === 'euc');
|
||||
const earliestCommit = eucTag?.[1];
|
||||
|
||||
// Create updated repository announcement event with new clone URLs and relays
|
||||
const eventTemplate = createRepositoryAnnouncementEvent({
|
||||
repoId: repoIdentifier,
|
||||
name: repoName,
|
||||
description,
|
||||
webUrls,
|
||||
cloneUrls: [...cloneUrls].slice(0, 10), // Limit to first 10 clone URLs
|
||||
relays: [...relays].slice(0, 10), // Limit to first 10 relays
|
||||
tTags: tTags.length > 0 ? tTags : undefined,
|
||||
earliestCommit,
|
||||
});
|
||||
|
||||
// Publish the updated event
|
||||
repoEvent = await publishEvent(eventTemplate);
|
||||
} else {
|
||||
// Create and publish new NIP-34 repository announcement
|
||||
|
||||
// Get the template name
|
||||
const dotAI = new DotAI(fs, `${projectsPath}/${projectId}`);
|
||||
const template = await dotAI.readTemplate();
|
||||
|
||||
// Build t-tags array
|
||||
const tTags = ['shakespeare'];
|
||||
|
||||
if (template) {
|
||||
tTags.push(template.name);
|
||||
}
|
||||
|
||||
// Create the repository announcement event
|
||||
const eventTemplate = createRepositoryAnnouncementEvent({
|
||||
repoId: repoIdentifier,
|
||||
name: repoName,
|
||||
cloneUrls: [...cloneUrls],
|
||||
relays: [...relays],
|
||||
tTags,
|
||||
});
|
||||
|
||||
// Publish the event
|
||||
repoEvent = await publishEvent(eventTemplate);
|
||||
}
|
||||
|
||||
// Wait 5 seconds for Nostr git servers to update
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
|
||||
// Construct Nostr URI
|
||||
const nostrURI = new NostrURI({
|
||||
pubkey: repoEvent.pubkey,
|
||||
identifier: repoIdentifier,
|
||||
relay: [...relays][0],
|
||||
});
|
||||
|
||||
// Configure the Nostr URI as the origin
|
||||
await git.addRemote({
|
||||
dir,
|
||||
remote: 'origin',
|
||||
url: nostrURI.toString(),
|
||||
force: true,
|
||||
});
|
||||
|
||||
// Push to Nostr (the rest of the Nostr logic is handled internally by git.push)
|
||||
await git.push({
|
||||
dir,
|
||||
remote: 'origin',
|
||||
ref: gitStatus?.currentBranch || 'main',
|
||||
});
|
||||
} else {
|
||||
// Validate repository URL
|
||||
if (!repositoryUrl.trim()) {
|
||||
throw new Error('Repository URL is required');
|
||||
}
|
||||
|
||||
// Add remote
|
||||
await git.addRemote({
|
||||
dir,
|
||||
remote: 'origin',
|
||||
url: repositoryUrl,
|
||||
force: true, // Override if exists
|
||||
});
|
||||
|
||||
// Push to remote
|
||||
await git.push({
|
||||
dir,
|
||||
remote: 'origin',
|
||||
ref: gitStatus?.currentBranch || 'main',
|
||||
});
|
||||
}
|
||||
|
||||
// Enable autosync by default after successfully setting up the remote
|
||||
await git.setConfig({
|
||||
dir,
|
||||
path: 'shakespeare.autosync',
|
||||
value: 'true',
|
||||
});
|
||||
|
||||
// Refresh git status before showing success
|
||||
await refetchAutosync();
|
||||
await refetchGitStatus();
|
||||
// Show success state
|
||||
onSuccess();
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to push';
|
||||
setError(message);
|
||||
} finally {
|
||||
setIsPushing(false);
|
||||
}
|
||||
};
|
||||
|
||||
// "Other" provider - show link to git settings
|
||||
if (selectedProvider.id === 'other') {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
{selectedProvider.icon}
|
||||
<h3 className="font-semibold">{selectedProvider.name}</h3>
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Configure additional git providers in{' '}
|
||||
<Link
|
||||
to="/settings/git"
|
||||
className="underline hover:no-underline font-medium"
|
||||
onClick={onClose}
|
||||
>
|
||||
Git Settings
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
|
||||
<Button
|
||||
onClick={onBack}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
>
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Nostr provider - check if user is logged in
|
||||
if (selectedProvider.id === 'nostr') {
|
||||
if (!user) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
{selectedProvider.icon}
|
||||
<h3 className="font-semibold">{selectedProvider.name}</h3>
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
You need to be logged in with Nostr to use this feature. Please visit{' '}
|
||||
<Link
|
||||
to="/settings/nostr"
|
||||
className="underline hover:no-underline font-medium"
|
||||
onClick={onClose}
|
||||
>
|
||||
Nostr Settings
|
||||
</Link>{' '}
|
||||
to log in.
|
||||
</p>
|
||||
|
||||
<Button
|
||||
onClick={onBack}
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
>
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
{selectedProvider.icon}
|
||||
<h3 className="font-semibold">{selectedProvider.name}</h3>
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Push your code to Nostr with one click. Your repository will be stored on public Nostr git <Link className="underline" to="/settings/nostr">servers</Link>.
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="repo-identifier">Repo Identifier <span className="text-destructive">*</span></Label>
|
||||
<Input
|
||||
id="repo-identifier"
|
||||
placeholder="my-project"
|
||||
value={repoIdentifier}
|
||||
onChange={(e) => handleRepoIdentifierChange(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="repo-name">Repo Name</Label>
|
||||
<Input
|
||||
id="repo-name"
|
||||
placeholder="My Project"
|
||||
value={repoName}
|
||||
onChange={(e) => handleRepoNameChange(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription className="text-sm">{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handlePushInitial}
|
||||
disabled={isPushing}
|
||||
className="flex-1"
|
||||
>
|
||||
{isPushing
|
||||
? <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2" />
|
||||
: <ArrowUp className="h-4 w-4" />}
|
||||
{isPushing ? 'Pushing...' : 'Push'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Regular git provider - show repository URL input
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
{selectedProvider.icon}
|
||||
<h3 className="font-semibold">{selectedProvider.name}</h3>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="repo-url">Repository URL</Label>
|
||||
<Input
|
||||
id="repo-url"
|
||||
placeholder="https://github.com/username/repo.git"
|
||||
value={repositoryUrl}
|
||||
onChange={(e) => setRepositoryUrl(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
First create the repository on {selectedProvider.origin ? <a href={selectedProvider.origin} className="underline" target="_blank">{selectedProvider.name}</a> : selectedProvider.name}, then paste the URL here.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription className="text-sm">{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handlePushInitial}
|
||||
disabled={isPushing || !repositoryUrl.trim()}
|
||||
className="flex-1"
|
||||
>
|
||||
{isPushing ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2" />
|
||||
Pushing...
|
||||
</>
|
||||
) : (
|
||||
'Push'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { AlertTriangle } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
interface ForcePullDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onConfirm: () => void;
|
||||
remoteName: string;
|
||||
}
|
||||
|
||||
export function ForcePullDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
remoteName,
|
||||
}: ForcePullDialogProps) {
|
||||
const handleConfirm = () => {
|
||||
onOpenChange(false);
|
||||
onConfirm();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5 text-destructive" />
|
||||
Force Pull - Discard Local Changes?
|
||||
</DialogTitle>
|
||||
<DialogDescription className="space-y-3">
|
||||
<p>
|
||||
This will <strong className="text-destructive">completely reset your local repository</strong> to match the repository pushed to <strong>{remoteName}</strong>, permanently deleting all local commits and changes that don't exist on {remoteName}.
|
||||
</p>
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm border border-destructive/20">
|
||||
<p className="font-medium text-destructive mb-1">What will be deleted:</p>
|
||||
<ul className="list-disc list-outside space-y-1 text-muted-foreground ml-5">
|
||||
<li>All local commits that haven't been pushed to {remoteName}</li>
|
||||
<li>Any work not available on {remoteName}</li>
|
||||
<li>All uncommitted changes</li>
|
||||
</ul>
|
||||
</div>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleConfirm}
|
||||
variant="destructive"
|
||||
className="gap-2"
|
||||
>
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
Force Pull
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { AlertTriangle } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
interface ForcePushDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onConfirm: () => void;
|
||||
remoteName: string;
|
||||
}
|
||||
|
||||
export function ForcePushDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
remoteName,
|
||||
}: ForcePushDialogProps) {
|
||||
const handleConfirm = () => {
|
||||
onOpenChange(false);
|
||||
onConfirm();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5 text-destructive" />
|
||||
Force Push to {remoteName}?
|
||||
</DialogTitle>
|
||||
<DialogDescription className="space-y-3">
|
||||
<p>
|
||||
This will <strong className="text-destructive">completely overwrite the commit history on {remoteName}</strong> with your local version, permanently deleting any commits and changes on {remoteName} that don't exist locally.
|
||||
</p>
|
||||
<div className="rounded-md bg-destructive/10 p-3 text-sm border border-destructive/20">
|
||||
<p className="font-medium text-destructive mb-1">What will be deleted from {remoteName}:</p>
|
||||
<ul className="list-disc list-outside space-y-1 text-muted-foreground ml-5">
|
||||
<li>All commits on {remoteName} that aren't in your local repository</li>
|
||||
<li>Any work by other contributors not in your local copy</li>
|
||||
<li>The entire commit history will be replaced with your local history</li>
|
||||
</ul>
|
||||
</div>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleConfirm}
|
||||
variant="destructive"
|
||||
className="gap-2"
|
||||
>
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
Force Push
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { CheckCircle2 } from 'lucide-react';
|
||||
import type { StepProps } from '../types';
|
||||
|
||||
export function InitSuccessStep(_props: StepProps) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-8 space-y-4">
|
||||
<div className="relative">
|
||||
<CheckCircle2 className="h-20 w-20 text-green-500 animate-in zoom-in duration-300" />
|
||||
<div className="absolute inset-0 h-20 w-20 rounded-full bg-green-500/20 animate-ping" />
|
||||
</div>
|
||||
<div className="text-center space-y-1">
|
||||
<h3 className="font-semibold text-lg">Successfully Synced!</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Your code has been synced to the remote repository.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { Zap, GitBranch } from 'lucide-react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { SelectProviderStepProps, ProviderOption } from '../types';
|
||||
|
||||
export function SelectProviderStep({
|
||||
onSelectProvider,
|
||||
}: SelectProviderStepProps) {
|
||||
const { settings } = useGitSettings();
|
||||
|
||||
const providerOptions: ProviderOption[] = [
|
||||
{
|
||||
id: 'nostr',
|
||||
name: 'Nostr',
|
||||
icon: <Zap className="h-4 w-4" />,
|
||||
},
|
||||
...settings.credentials.map(credential => ({
|
||||
id: credential.id,
|
||||
name: credential.name,
|
||||
origin: credential.origin,
|
||||
icon: (
|
||||
<ExternalFavicon
|
||||
url={credential.origin}
|
||||
size={16}
|
||||
fallback={<GitBranch className="h-4 w-4" />}
|
||||
/>
|
||||
),
|
||||
credential,
|
||||
})),
|
||||
{
|
||||
id: 'other',
|
||||
name: 'Other',
|
||||
icon: <GitBranch className="h-4 w-4" />,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h3 className="font-semibold mb-1">Sync your code to git</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Choose a provider to sync your project
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs text-muted-foreground">Select Provider</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{providerOptions.map((provider) => (
|
||||
<button
|
||||
key={provider.id}
|
||||
type="button"
|
||||
onClick={() => onSelectProvider(provider)}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-all",
|
||||
"border-2 hover:scale-105 active:scale-95",
|
||||
"bg-background text-foreground border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
{provider.icon}
|
||||
<span>{provider.name}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { Zap, Copy, Check, RefreshCw, EllipsisVertical, CloudOff, ExternalLink, ChevronDown, ArrowDown, ArrowUp, LoaderCircle, History, Edit } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { SyncStepError } from './SyncStepError';
|
||||
import { ForcePullDialog } from './ForcePullDialog';
|
||||
import { ForcePushDialog } from './ForcePushDialog';
|
||||
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
|
||||
import { NostrRepoEditDialog } from '@/components/NostrRepoEditDialog';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useGitSyncState } from '@/hooks/useGitSyncState';
|
||||
import { useGitAutosync } from '@/hooks/useGitAutosync';
|
||||
import { useNostrRepo } from '@/hooks/useNostrRepo';
|
||||
import type { SyncStepProps } from '../types';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
import { ngitWebUrl } from '@/lib/ngitWebUrl';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
|
||||
export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [copiedUrl, setCopiedUrl] = useState(false);
|
||||
const [syncSuccess, setSyncSuccess] = useState(false);
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
const [showForcePullDialog, setShowForcePullDialog] = useState(false);
|
||||
const [showForcePushDialog, setShowForcePushDialog] = useState(false);
|
||||
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
|
||||
const [editRepoOpen, setEditRepoOpen] = useState(false);
|
||||
const [repoIdentifier, setRepoIdentifier] = useState<string | null>(null);
|
||||
|
||||
const { data: gitStatus } = useGitStatus(projectId);
|
||||
const { settings } = useGitSettings();
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { config } = useAppContext();
|
||||
const gitSync = useGitSyncState();
|
||||
|
||||
const dir = `${projectsPath}/${projectId}`;
|
||||
const ref = gitStatus?.currentBranch || 'main';
|
||||
|
||||
// Use the new hook for autosync state
|
||||
const { autosync, isLoading: isLoadingAutosync, setAutosync } = useGitAutosync(dir);
|
||||
|
||||
// Get unified sync state and error
|
||||
const syncState = gitSync.getState(dir);
|
||||
const isSyncing = syncState?.isActive || false;
|
||||
const currentOperation = syncState?.operation || null;
|
||||
const error = gitSync.getError(dir) || null;
|
||||
|
||||
const hasRemoteChanges = gitStatus?.remoteBranchExists && ((gitStatus?.ahead ?? 0) > 0 || (gitStatus?.behind ?? 0) > 0);
|
||||
const commitsAhead = gitStatus?.ahead ?? 0;
|
||||
const commitsBehind = gitStatus?.behind ?? 0;
|
||||
|
||||
// Helper to set error for this directory
|
||||
const setError = useCallback((err: Error | null) => {
|
||||
gitSync.setError(dir, err);
|
||||
}, [dir, gitSync]);
|
||||
|
||||
// Generic git operation handler with success feedback
|
||||
const executeGitOperation = useCallback(async (
|
||||
action: () => Promise<void>
|
||||
) => {
|
||||
if (!remoteUrl) return;
|
||||
|
||||
setError(null);
|
||||
setSyncSuccess(false);
|
||||
|
||||
try {
|
||||
await action();
|
||||
|
||||
// Show success feedback
|
||||
setSyncSuccess(true);
|
||||
setTimeout(() => setSyncSuccess(false), 2500);
|
||||
} catch (err) {
|
||||
console.warn(err);
|
||||
// Error is already set by the provider
|
||||
}
|
||||
}, [remoteUrl, setError]);
|
||||
|
||||
const handleSync = async () => {
|
||||
await executeGitOperation(() => gitSync.sync(dir, ref));
|
||||
};
|
||||
|
||||
const handlePull = async () => {
|
||||
await executeGitOperation(() => gitSync.pull(dir, ref));
|
||||
};
|
||||
|
||||
const handlePush = async () => {
|
||||
await executeGitOperation(() => gitSync.push(dir, ref));
|
||||
};
|
||||
|
||||
const handleForcePull = async () => {
|
||||
await executeGitOperation(() => gitSync.forcePull(dir, ref));
|
||||
};
|
||||
|
||||
const handleForcePush = async () => {
|
||||
await executeGitOperation(() => gitSync.forcePush(dir, ref));
|
||||
};
|
||||
|
||||
// Temporary feedback state helper
|
||||
const showTemporaryFeedback = useCallback((
|
||||
setter: (value: boolean) => void,
|
||||
duration: number
|
||||
) => {
|
||||
setter(true);
|
||||
setTimeout(() => setter(false), duration);
|
||||
}, []);
|
||||
|
||||
const handleCopyUrl = async () => {
|
||||
if (!remoteUrl) return;
|
||||
|
||||
try {
|
||||
await navigator.clipboard.writeText(remoteUrl.href);
|
||||
showTemporaryFeedback(setCopiedUrl, 2000);
|
||||
} catch (err) {
|
||||
console.error('Failed to copy URL:', err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDisconnect = async () => {
|
||||
if (!remoteUrl) return;
|
||||
|
||||
try {
|
||||
await git.deleteRemote({ dir, remote: 'origin' });
|
||||
// Clear any errors when disconnecting
|
||||
setError(null);
|
||||
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err : new Error('Failed to disconnect');
|
||||
setError(message);
|
||||
}
|
||||
};
|
||||
|
||||
const getExternalUrl = useCallback(async (url: URL): Promise<string | null> => {
|
||||
if (url.protocol === 'http:' || url.protocol === 'https:') {
|
||||
return url.href;
|
||||
}
|
||||
|
||||
if (url.protocol === 'nostr:') {
|
||||
const nostrUri = await NostrURI.parse(url.href);
|
||||
return ngitWebUrl(config.ngitWebUrl, nostrUri);
|
||||
}
|
||||
|
||||
return null;
|
||||
}, [config.ngitWebUrl]);
|
||||
|
||||
const handleOpenExternal = async () => {
|
||||
if (!remoteUrl) return;
|
||||
|
||||
try {
|
||||
const externalUrl = await getExternalUrl(remoteUrl);
|
||||
if (externalUrl) {
|
||||
window.open(externalUrl, '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to open external URL:', err);
|
||||
}
|
||||
};
|
||||
|
||||
const getProviderInfo = useCallback(() => {
|
||||
if (!remoteUrl) return null;
|
||||
|
||||
// Check if it's a Nostr URI
|
||||
if (remoteUrl.protocol === 'nostr:') {
|
||||
return {
|
||||
name: 'Nostr Git',
|
||||
icon: <Zap className="size-4" />,
|
||||
isNostr: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Check if we have a matched credential
|
||||
const matchedCredential = findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
|
||||
return {
|
||||
name: matchedCredential? matchedCredential.name : remoteUrl.hostname,
|
||||
icon: <ExternalFavicon url={remoteUrl} size={16} />,
|
||||
isNostr: false,
|
||||
};
|
||||
}, [remoteUrl, settings.credentials]);
|
||||
|
||||
const providerInfo = getProviderInfo();
|
||||
const remoteName = providerInfo?.name ?? 'the remote';
|
||||
|
||||
// Extract repo identifier from Nostr URI if applicable
|
||||
const getRepoIdentifier = useCallback(async (): Promise<string | null> => {
|
||||
if (!remoteUrl || remoteUrl.protocol !== 'nostr:') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const nostrUri = await NostrURI.parse(remoteUrl.href);
|
||||
return nostrUri.identifier;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}, [remoteUrl]);
|
||||
|
||||
// Warm up the Nostr repo query if this is a Nostr URI
|
||||
// This prefetches the data so it's ready when the edit dialog opens
|
||||
useNostrRepo({
|
||||
repoIdentifier: repoIdentifier || '',
|
||||
enabled: !!repoIdentifier && remoteUrl?.protocol === 'nostr:',
|
||||
});
|
||||
|
||||
// Extract and set repo identifier on mount if it's a Nostr URI
|
||||
useEffect(() => {
|
||||
if (remoteUrl?.protocol === 'nostr:') {
|
||||
getRepoIdentifier().then(id => {
|
||||
if (id) setRepoIdentifier(id);
|
||||
});
|
||||
}
|
||||
}, [remoteUrl, getRepoIdentifier]);
|
||||
|
||||
// Get the button label based on current operation
|
||||
const getButtonLabel = (): string => {
|
||||
if (!isSyncing) return 'Sync';
|
||||
|
||||
switch (currentOperation) {
|
||||
case 'fetch':
|
||||
return 'Fetching';
|
||||
case 'pull':
|
||||
return 'Pulling';
|
||||
case 'push':
|
||||
return 'Pushing';
|
||||
default:
|
||||
return 'Syncing';
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditRepo = () => {
|
||||
if (repoIdentifier) {
|
||||
setEditRepoOpen(true);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRepoEditSuccess = () => {
|
||||
// Refresh git status after successful edit
|
||||
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
{providerInfo?.icon}
|
||||
<h3 className="font-semibold">{providerInfo?.name}</h3>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<EllipsisVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{providerInfo?.isNostr && (
|
||||
<DropdownMenuItem onClick={handleEditRepo} className="gap-2">
|
||||
<Edit className="h-4 w-4" />
|
||||
Edit Repository
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem onClick={() => setGitHistoryOpen(true)} className="gap-2">
|
||||
<History className="h-4 w-4" />
|
||||
Rollback
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={handleDisconnect} className="text-destructive gap-2">
|
||||
<CloudOff className="h-4 w-4" />
|
||||
Disconnect
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs text-muted-foreground">Repository URL</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={remoteUrl.href}
|
||||
readOnly
|
||||
className="flex-1 text-sm"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleCopyUrl}
|
||||
className="shrink-0 h-10"
|
||||
>
|
||||
{copiedUrl ? (
|
||||
<Check className="h-4 w-4" />
|
||||
) : (
|
||||
<Copy className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleOpenExternal}
|
||||
className="shrink-0 h-10"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Switch
|
||||
id="autosync"
|
||||
checked={autosync}
|
||||
onCheckedChange={setAutosync}
|
||||
disabled={isLoadingAutosync}
|
||||
className="scale-75"
|
||||
/>
|
||||
<Label htmlFor="autosync" className="text-xs cursor-pointer font-normal text-muted-foreground">
|
||||
Automatic sync
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<SyncStepError
|
||||
error={error}
|
||||
onDismiss={() => setError(null)}
|
||||
onForcePull={() => setShowForcePullDialog(true)}
|
||||
onForcePush={() => setShowForcePushDialog(true)}
|
||||
onPull={handlePull}
|
||||
remoteName={remoteName}
|
||||
remoteUrl={remoteUrl}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Unsynced changes notification */}
|
||||
{hasRemoteChanges && !error && (
|
||||
<div className="rounded-md bg-yellow-500/10 border border-yellow-500/20 p-3">
|
||||
<p className="text-sm text-yellow-900 dark:text-yellow-100">
|
||||
This branch is{' '}
|
||||
{commitsAhead > 0 && (
|
||||
<>
|
||||
<span className="font-medium">{commitsAhead} commit{commitsAhead !== 1 ? 's' : ''} ahead of</span>
|
||||
{commitsBehind > 0 ? ' and ' : ' '}
|
||||
</>
|
||||
)}
|
||||
{commitsBehind > 0 && (
|
||||
<>
|
||||
<span className="font-medium">{commitsBehind} commit{commitsBehind !== 1 ? 's' : ''} behind</span>{' '}
|
||||
</>
|
||||
)}
|
||||
<span className="font-medium">{ref}</span> on {remoteName}.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
|
||||
<div className="space-y-2">
|
||||
<div className="rounded-md bg-primary relative">
|
||||
<div className="flex">
|
||||
<Button
|
||||
onClick={handleSync}
|
||||
disabled={isSyncing}
|
||||
className="flex-1 rounded-r-none bg-transparent hover:bg-white/10 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{syncSuccess
|
||||
? <Check className="h-4 w-4" />
|
||||
: <RefreshCw className={cn("size-4", { "animate-spin": isSyncing })} />}
|
||||
<span>{getButtonLabel()}</span>
|
||||
</div>
|
||||
</Button>
|
||||
<div className="w-px bg-border/20" />
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button className="px-3 rounded-l-none bg-transparent hover:bg-white/10 transition-colors">
|
||||
<ChevronDown className={cn(
|
||||
"h-4 w-4 transition-transform duration-200",
|
||||
{ "rotate-180": isExpanded }
|
||||
)} />
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CollapsibleContent className="space-y-2">
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Button
|
||||
onClick={handlePull}
|
||||
variant="outline"
|
||||
disabled={isSyncing}
|
||||
className="w-full"
|
||||
>
|
||||
{currentOperation === 'pull' ? (
|
||||
<LoaderCircle className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<ArrowDown className="h-4 w-4" />
|
||||
)}
|
||||
Pull
|
||||
</Button>
|
||||
</div>
|
||||
<div className="relative flex-1">
|
||||
<Button
|
||||
onClick={handlePush}
|
||||
variant="outline"
|
||||
disabled={isSyncing}
|
||||
className="w-full"
|
||||
>
|
||||
{currentOperation === 'push' ? (
|
||||
<LoaderCircle className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<ArrowUp className="h-4 w-4" />
|
||||
)}
|
||||
Push
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</div>
|
||||
</Collapsible>
|
||||
|
||||
<ForcePullDialog
|
||||
open={showForcePullDialog}
|
||||
onOpenChange={setShowForcePullDialog}
|
||||
onConfirm={handleForcePull}
|
||||
remoteName={remoteName}
|
||||
/>
|
||||
|
||||
<ForcePushDialog
|
||||
open={showForcePushDialog}
|
||||
onOpenChange={setShowForcePushDialog}
|
||||
onConfirm={handleForcePush}
|
||||
remoteName={remoteName}
|
||||
/>
|
||||
|
||||
<GitHistoryDialog
|
||||
projectId={projectId}
|
||||
open={gitHistoryOpen}
|
||||
onOpenChange={setGitHistoryOpen}
|
||||
/>
|
||||
|
||||
{repoIdentifier && (
|
||||
<NostrRepoEditDialog
|
||||
open={editRepoOpen}
|
||||
onOpenChange={setEditRepoOpen}
|
||||
repoIdentifier={repoIdentifier}
|
||||
onSuccess={handleRepoEditSuccess}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { Errors as GitErrors } from 'isomorphic-git';
|
||||
import { X, ArrowDown, ArrowUp } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { getSentryInstance } from '@/lib/sentry';
|
||||
|
||||
interface SyncStepErrorProps {
|
||||
error: Error;
|
||||
onDismiss: () => void;
|
||||
onForcePull: () => void;
|
||||
onForcePush: () => void;
|
||||
onPull: () => void;
|
||||
remoteUrl: URL;
|
||||
remoteName: string;
|
||||
}
|
||||
|
||||
export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPull, remoteName, remoteUrl }: SyncStepErrorProps) {
|
||||
const renderForcePullButton = () => (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onForcePull}
|
||||
className="w-full hover:bg-destructive-foreground/20 border-destructive-foreground/20"
|
||||
>
|
||||
<ArrowDown className="size-4" />
|
||||
Force Pull
|
||||
</Button>
|
||||
);
|
||||
|
||||
const renderForcePushButton = () => (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onForcePush}
|
||||
className="w-full hover:bg-destructive-foreground/20 border-destructive-foreground/20"
|
||||
>
|
||||
<ArrowUp className="size-4" />
|
||||
Force Push
|
||||
</Button>
|
||||
);
|
||||
|
||||
const renderPullButton = () => (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onPull}
|
||||
>
|
||||
<ArrowDown className="size-4" />
|
||||
Pull
|
||||
</Button>
|
||||
);
|
||||
|
||||
const renderDismissButton = () => (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-5 shrink-0 hover:bg-destructive-foreground/10"
|
||||
onClick={onDismiss}
|
||||
>
|
||||
<X className="size-4" />
|
||||
</Button>
|
||||
);
|
||||
|
||||
// MergeNotSupportedError - offer force pull or force push
|
||||
if (error instanceof GitErrors.MergeNotSupportedError) {
|
||||
return (
|
||||
<Alert variant="destructive">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<AlertDescription className="text-sm flex-1">
|
||||
Cannot merge changes automatically. Your local changes conflict with the remote repository.
|
||||
</AlertDescription>
|
||||
{renderDismissButton()}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{renderForcePullButton()}
|
||||
{renderForcePushButton()}
|
||||
</div>
|
||||
</div>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
// FastForwardError - offer force pull or force push
|
||||
if (error instanceof GitErrors.FastForwardError) {
|
||||
return (
|
||||
<Alert variant="destructive">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<AlertDescription className="text-sm flex-1">
|
||||
Cannot fast-forward. The remote has changes that conflict with your local commits.
|
||||
</AlertDescription>
|
||||
{renderDismissButton()}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{renderForcePullButton()}
|
||||
{renderForcePushButton()}
|
||||
</div>
|
||||
</div>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
// PushRejectedError - remote has changes
|
||||
if (error instanceof GitErrors.PushRejectedError) {
|
||||
return (
|
||||
<Alert variant="destructive">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<AlertDescription className="text-sm flex-1">
|
||||
Push rejected. The remote repository has changes you don't have locally. Try pulling first.
|
||||
</AlertDescription>
|
||||
{renderDismissButton()}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{renderPullButton()}
|
||||
{renderForcePushButton()}
|
||||
</div>
|
||||
</div>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
// HTTP errors
|
||||
if (error instanceof GitErrors.HttpError) {
|
||||
let message: React.ReactNode = `HTTP Error: ${error.data.statusCode} ${error.data.statusMessage}`;
|
||||
|
||||
if (remoteUrl.protocol === 'nostr:') {
|
||||
// This should never happen
|
||||
getSentryInstance()?.captureException(error);
|
||||
message = `There was an HTTP (${error.data.statusCode}) error communicating with Nostr Git servers.`
|
||||
} else if (remoteUrl.protocol !== 'http:' && remoteUrl.protocol !== 'https:') {
|
||||
switch (error.data.statusCode) {
|
||||
case 401:
|
||||
message = <>Your API token for {remoteName} is probably invalid or expired. Please try logging out and back into {remoteName} in <Link to="/settings/git" className="underline">Git Settings</Link>.</>
|
||||
break;
|
||||
case 403:
|
||||
message = <>You don't have permission to access this repository on {remoteName}. Try checking your permissions on <a href={remoteUrl.origin} target="_blank" className="underline">{remoteName}</a>.</>;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Alert variant="destructive">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<AlertDescription className="text-sm flex-1">
|
||||
{message}
|
||||
</AlertDescription>
|
||||
{renderDismissButton()}
|
||||
</div>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
// Generic error fallback
|
||||
return (
|
||||
<Alert variant="destructive">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<AlertDescription className="text-sm flex-1 whitespace-pre overflow-x-auto">
|
||||
{error.message}
|
||||
</AlertDescription>
|
||||
{renderDismissButton()}
|
||||
</div>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { GitCredential } from '@/contexts/GitSettingsContext';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
export interface ProviderOption {
|
||||
id: string;
|
||||
name: string;
|
||||
origin?: string;
|
||||
icon: ReactNode;
|
||||
credential?: GitCredential;
|
||||
}
|
||||
|
||||
export type StepType =
|
||||
| 'select-provider'
|
||||
| 'configure-repo'
|
||||
| 'sync'
|
||||
| 'init-success';
|
||||
|
||||
export interface StepProps {
|
||||
projectId: string;
|
||||
onChangeStep: (step: StepType) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export interface SyncStepProps extends StepProps {
|
||||
remoteUrl: URL;
|
||||
}
|
||||
|
||||
export interface SelectProviderStepProps extends StepProps {
|
||||
onSelectProvider: (provider: ProviderOption) => void;
|
||||
}
|
||||
|
||||
export interface ConfigureRepoStepProps extends StepProps {
|
||||
selectedProvider: ProviderOption;
|
||||
onBack: () => void;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
describe('AnnounceRepositoryDialog - NIP-34 Tag Structure', () => {
|
||||
it('should create tags with multiple values in single tag per NIP-34', () => {
|
||||
// Test the tag structure that would be created
|
||||
const webUrls = ['https://example.com/browse', 'https://mirror.example.com'];
|
||||
const cloneUrls = [
|
||||
'https://git.shakespeare.diy/npub1.../repo.git',
|
||||
'https://relay.ngit.dev/npub1.../repo.git',
|
||||
];
|
||||
const relays = ['wss://git.shakespeare.diy', 'wss://relay.ngit.dev'];
|
||||
|
||||
const tags: string[][] = [['d', 'test-repo']];
|
||||
|
||||
// Simulate the tag creation logic from AnnounceRepositoryDialog
|
||||
if (webUrls.length > 0) {
|
||||
const trimmedUrls = webUrls.map((url) => url.trim()).filter((url) => url);
|
||||
if (trimmedUrls.length > 0) {
|
||||
tags.push(['web', ...trimmedUrls]);
|
||||
}
|
||||
}
|
||||
|
||||
if (cloneUrls.length > 0) {
|
||||
const trimmedUrls = cloneUrls.map((url) => url.trim()).filter((url) => url);
|
||||
if (trimmedUrls.length > 0) {
|
||||
tags.push(['clone', ...trimmedUrls]);
|
||||
}
|
||||
}
|
||||
|
||||
if (relays.length > 0) {
|
||||
const trimmedRelays = relays.map((relay) => relay.trim()).filter((relay) => relay);
|
||||
if (trimmedRelays.length > 0) {
|
||||
tags.push(['relays', ...trimmedRelays]);
|
||||
}
|
||||
}
|
||||
|
||||
// Verify the structure matches NIP-34 spec
|
||||
expect(tags).toEqual([
|
||||
['d', 'test-repo'],
|
||||
['web', 'https://example.com/browse', 'https://mirror.example.com'],
|
||||
[
|
||||
'clone',
|
||||
'https://git.shakespeare.diy/npub1.../repo.git',
|
||||
'https://relay.ngit.dev/npub1.../repo.git',
|
||||
],
|
||||
['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev'],
|
||||
]);
|
||||
|
||||
// Verify we have single tags with multiple values, not multiple tags
|
||||
const cloneTags = tags.filter((t) => t[0] === 'clone');
|
||||
expect(cloneTags.length).toBe(1);
|
||||
expect(cloneTags[0].length).toBe(3); // ['clone', url1, url2]
|
||||
|
||||
const relayTags = tags.filter((t) => t[0] === 'relays');
|
||||
expect(relayTags.length).toBe(1);
|
||||
expect(relayTags[0].length).toBe(3); // ['relays', relay1, relay2]
|
||||
});
|
||||
|
||||
it('should handle reading relays from single tag with multiple values', () => {
|
||||
// Simulate the event structure from Nostr
|
||||
const repoEvent = {
|
||||
tags: [
|
||||
['d', 'hello-shakespeare'],
|
||||
[
|
||||
'clone',
|
||||
'https://git.shakespeare.diy/npub1.../hello-shakespeare.git',
|
||||
'https://relay.ngit.dev/npub1.../hello-shakespeare.git',
|
||||
],
|
||||
['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev'],
|
||||
],
|
||||
};
|
||||
|
||||
// Simulate the reading logic from PullRequestDialog
|
||||
const relayTag = repoEvent.tags.find((t: string[]) => t[0] === 'relays');
|
||||
let publishRelays: string[] = [];
|
||||
|
||||
if (relayTag && relayTag.length > 1) {
|
||||
publishRelays = relayTag.slice(1);
|
||||
}
|
||||
|
||||
// Verify we extracted all relay URLs correctly
|
||||
expect(publishRelays).toEqual(['wss://git.shakespeare.diy', 'wss://relay.ngit.dev']);
|
||||
});
|
||||
|
||||
it('should handle reading clone URLs from single tag with multiple values', () => {
|
||||
const repoEvent = {
|
||||
tags: [
|
||||
['d', 'hello-shakespeare'],
|
||||
[
|
||||
'clone',
|
||||
'https://git.shakespeare.diy/npub1.../hello-shakespeare.git',
|
||||
'https://relay.ngit.dev/npub1.../hello-shakespeare.git',
|
||||
],
|
||||
],
|
||||
};
|
||||
|
||||
const cloneTag = repoEvent.tags.find((t: string[]) => t[0] === 'clone');
|
||||
let cloneUrls: string[] = [];
|
||||
|
||||
if (cloneTag && cloneTag.length > 1) {
|
||||
cloneUrls = cloneTag.slice(1);
|
||||
}
|
||||
|
||||
expect(cloneUrls).toEqual([
|
||||
'https://git.shakespeare.diy/npub1.../hello-shakespeare.git',
|
||||
'https://relay.ngit.dev/npub1.../hello-shakespeare.git',
|
||||
]);
|
||||
});
|
||||
|
||||
it('should handle reading maintainers from single tag with multiple values', () => {
|
||||
const repoEvent = {
|
||||
tags: [
|
||||
['d', 'hello-shakespeare'],
|
||||
['maintainers', 'pubkey1', 'pubkey2', 'pubkey3'],
|
||||
],
|
||||
};
|
||||
|
||||
// Simulate the reading logic from NostrGitProvider
|
||||
const maintainerTag = repoEvent.tags.find((t: string[]) => t[0] === 'maintainers');
|
||||
const maintainers = maintainerTag ? maintainerTag.slice(1) : [];
|
||||
|
||||
expect(maintainers).toEqual(['pubkey1', 'pubkey2', 'pubkey3']);
|
||||
});
|
||||
});
|
||||
@@ -1,738 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { TagInput } from '@/components/ui/tag-input';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from '@/components/ui/collapsible';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import {
|
||||
GitBranch,
|
||||
Loader2,
|
||||
AlertCircle,
|
||||
Plus,
|
||||
X,
|
||||
Settings,
|
||||
ChevronDown,
|
||||
} from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostr } from '@/hooks/useNostr';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import {
|
||||
createRepositoryAnnouncementEvent,
|
||||
createRepositoryNaddr,
|
||||
validateRepositoryAnnouncementData,
|
||||
validateRepositoryId,
|
||||
parseRepositoryAnnouncement,
|
||||
} from '@/lib/announceRepository';
|
||||
|
||||
export interface AnnounceRepositoryResult {
|
||||
repoId: string;
|
||||
cloneUrls: string[];
|
||||
relays: string[];
|
||||
naddr: string;
|
||||
}
|
||||
|
||||
interface AnnounceRepositoryDialogProps {
|
||||
projectId: string;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
onSuccess?: (result: AnnounceRepositoryResult) => void;
|
||||
/** Repository naddr to edit (if editing existing repo) */
|
||||
editNaddr?: string;
|
||||
}
|
||||
|
||||
export function AnnounceRepositoryDialog({
|
||||
projectId,
|
||||
open,
|
||||
onOpenChange,
|
||||
onSuccess,
|
||||
editNaddr,
|
||||
}: AnnounceRepositoryDialogProps) {
|
||||
const [isOpen, setIsOpen] = useState(open ?? false);
|
||||
const [isPrepopulated, setIsPrepopulated] = useState(false);
|
||||
const [repoId, setRepoId] = useState('');
|
||||
const [repoIdError, setRepoIdError] = useState<string | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||
const [webUrls, setWebUrls] = useState<string[]>([]);
|
||||
const [cloneUrls, setCloneUrls] = useState<string[]>([]);
|
||||
const [relays, setRelays] = useState<string[]>([]);
|
||||
const [tTags, setTTags] = useState<string[]>([]);
|
||||
const [earliestCommit, setEarliestCommit] = useState('');
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [newWebUrl, setNewWebUrl] = useState('');
|
||||
const [newCloneUrl, setNewCloneUrl] = useState('');
|
||||
const [newRelay, setNewRelay] = useState('');
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
const { toast } = useToast();
|
||||
const { config } = useAppContext();
|
||||
const { fs } = useFS();
|
||||
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
useEffect(() => {
|
||||
if (open !== undefined) {
|
||||
setIsOpen(open);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// Convert projectId to kebab-case for repo ID
|
||||
const toKebabCase = (str: string): string => {
|
||||
return str
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
};
|
||||
|
||||
// Validate repository ID on change
|
||||
const handleRepoIdChange = (value: string) => {
|
||||
setRepoId(value);
|
||||
try {
|
||||
validateRepositoryId(value);
|
||||
setRepoIdError(null);
|
||||
} catch (err) {
|
||||
setRepoIdError(err instanceof Error ? err.message : 'Invalid repository ID');
|
||||
}
|
||||
};
|
||||
|
||||
const getEarliestCommit = useCallback(async () => {
|
||||
try {
|
||||
const commits = await git.log({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
|
||||
if (commits.length > 0) {
|
||||
// Get the earliest commit (last in the log)
|
||||
const earliest = commits[commits.length - 1];
|
||||
setEarliestCommit(earliest.oid);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Failed to get earliest commit:', err);
|
||||
}
|
||||
}, [git, projectPath]);
|
||||
|
||||
const prepopulateFields = useCallback(async () => {
|
||||
// Set default repo ID from project ID (kebab-case)
|
||||
const defaultRepoId = toKebabCase(projectId);
|
||||
setRepoId(defaultRepoId);
|
||||
|
||||
// Set default name from project ID (title case)
|
||||
const defaultName = projectId
|
||||
.split(/[-_]/)
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ');
|
||||
setName(defaultName);
|
||||
|
||||
// Prepopulate clone URLs and relays from ngitServers (matching original handlePushToNostr)
|
||||
if (user?.pubkey && config.ngitServers && config.ngitServers.length > 0) {
|
||||
// Clone URLs: https://{server}/{npub}/{repo-id}.git
|
||||
const npub = nip19.npubEncode(user.pubkey);
|
||||
const cloneUrls = config.ngitServers.map(server =>
|
||||
`https://${server}/${npub}/${defaultRepoId}.git`
|
||||
);
|
||||
setCloneUrls(cloneUrls);
|
||||
|
||||
// Relay URLs: wss://{server}
|
||||
const relayUrls = config.ngitServers.map(server => `wss://${server}`);
|
||||
setRelays(relayUrls);
|
||||
} else {
|
||||
// Fallback to write relays if no ngitServers configured
|
||||
const writeRelays = config.relayMetadata.relays
|
||||
.filter(r => r.write)
|
||||
.map(r => r.url);
|
||||
setRelays(writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']);
|
||||
}
|
||||
|
||||
// Prepopulate t-tags
|
||||
const defaultTTags: string[] = ['shakespeare'];
|
||||
|
||||
// Try to read template.json to get template name
|
||||
try {
|
||||
const dotAI = new DotAI(fs, projectPath);
|
||||
const template = await dotAI.readTemplate();
|
||||
if (template?.name) {
|
||||
// Convert template name to lowercase and add as t-tag
|
||||
const templateTag = template.name.toLowerCase();
|
||||
if (!defaultTTags.includes(templateTag)) {
|
||||
defaultTTags.push(templateTag);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to read template for t-tags:', error);
|
||||
}
|
||||
|
||||
setTTags(defaultTTags);
|
||||
|
||||
// Get earliest commit
|
||||
await getEarliestCommit();
|
||||
}, [projectId, projectPath, fs, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit]);
|
||||
|
||||
// Load existing repository data if editing, or prepopulate fields for new repos
|
||||
useEffect(() => {
|
||||
// Only run when dialog opens
|
||||
if (!isOpen || isPrepopulated) return;
|
||||
|
||||
const loadExistingRepo = async () => {
|
||||
if (!editNaddr) return;
|
||||
|
||||
try {
|
||||
// Decode the naddr to get repository coordinates
|
||||
const decoded = nip19.decode(editNaddr);
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Invalid repository identifier');
|
||||
}
|
||||
|
||||
const { identifier, pubkey, kind, relays: naddrRelays } = decoded.data;
|
||||
|
||||
// Query for the repository announcement event
|
||||
const filter = {
|
||||
kinds: [kind],
|
||||
authors: [pubkey],
|
||||
'#d': [identifier],
|
||||
};
|
||||
|
||||
const signal = AbortSignal.timeout(3000);
|
||||
const readRelays = config.relayMetadata.relays
|
||||
.filter(r => r.read)
|
||||
.map(r => r.url);
|
||||
const events = await nostr.query([filter], {
|
||||
signal,
|
||||
relays: naddrRelays && naddrRelays.length > 0 ? naddrRelays : readRelays
|
||||
});
|
||||
|
||||
if (events.length === 0) {
|
||||
throw new Error('Repository announcement not found');
|
||||
}
|
||||
|
||||
// Use the most recent event
|
||||
const event = events.sort((a, b) => b.created_at - a.created_at)[0];
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
|
||||
setRepoId(parsed.identifier);
|
||||
setName(parsed.name || '');
|
||||
setDescription(parsed.description || '');
|
||||
setWebUrls(parsed.webUrls);
|
||||
setCloneUrls(parsed.httpsCloneUrls);
|
||||
setRelays(parsed.relays);
|
||||
setEarliestCommit(parsed.earliestCommit || '');
|
||||
|
||||
// Extract t-tags from the event
|
||||
const extractedTTags = parsed.event.tags
|
||||
.filter(([name]) => name === 't')
|
||||
.map(([, value]) => value)
|
||||
.filter((value): value is string => !!value);
|
||||
setTTags(extractedTTags);
|
||||
|
||||
setIsPrepopulated(true);
|
||||
} catch (error) {
|
||||
console.error('Failed to load repository data:', error);
|
||||
toast({
|
||||
title: 'Failed to load repository',
|
||||
description: error instanceof Error ? error.message : 'Unknown error',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (editNaddr) {
|
||||
loadExistingRepo();
|
||||
} else {
|
||||
prepopulateFields();
|
||||
setIsPrepopulated(true);
|
||||
}
|
||||
}, [isOpen, isPrepopulated, editNaddr, nostr, config.relayMetadata, toast, prepopulateFields]);
|
||||
|
||||
const addWebUrl = () => {
|
||||
if (newWebUrl.trim() && !webUrls.includes(newWebUrl.trim())) {
|
||||
setWebUrls([...webUrls, newWebUrl.trim()]);
|
||||
setNewWebUrl('');
|
||||
}
|
||||
};
|
||||
|
||||
const removeWebUrl = (index: number) => {
|
||||
setWebUrls(webUrls.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const addCloneUrl = () => {
|
||||
const trimmedUrl = newCloneUrl.trim();
|
||||
|
||||
// Prevent nostr:// URLs in clone URLs
|
||||
if (trimmedUrl.startsWith('nostr://')) {
|
||||
toast({
|
||||
title: 'Invalid clone URL',
|
||||
description: 'Clone URLs must be HTTPS URLs, not nostr:// URLs',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (trimmedUrl && !cloneUrls.includes(trimmedUrl)) {
|
||||
setCloneUrls([...cloneUrls, trimmedUrl]);
|
||||
setNewCloneUrl('');
|
||||
}
|
||||
};
|
||||
|
||||
const removeCloneUrl = (index: number) => {
|
||||
setCloneUrls(cloneUrls.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const addRelay = () => {
|
||||
if (newRelay.trim() && !relays.includes(newRelay.trim())) {
|
||||
setRelays([...relays, newRelay.trim()]);
|
||||
setNewRelay('');
|
||||
}
|
||||
};
|
||||
|
||||
const removeRelay = (index: number) => {
|
||||
setRelays(relays.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const announceRepository = async () => {
|
||||
if (!user || !user.signer) {
|
||||
toast({
|
||||
title: 'Authentication required',
|
||||
description: 'Please log in with Nostr to announce repositories',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCreating(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Validate data
|
||||
validateRepositoryAnnouncementData({
|
||||
repoId,
|
||||
cloneUrls,
|
||||
});
|
||||
|
||||
// Create repository announcement event using shared utility
|
||||
const repoEvent = createRepositoryAnnouncementEvent({
|
||||
repoId,
|
||||
name,
|
||||
description,
|
||||
webUrls,
|
||||
cloneUrls,
|
||||
relays,
|
||||
tTags,
|
||||
earliestCommit,
|
||||
});
|
||||
|
||||
console.log('=== ANNOUNCING REPOSITORY ===');
|
||||
console.log('Repository ID:', repoId.trim());
|
||||
console.log('Owner pubkey:', user.pubkey);
|
||||
console.log('Creating repository announcement event:', repoEvent);
|
||||
|
||||
// Sign the event
|
||||
const signedEvent = await user.signer.signEvent(repoEvent);
|
||||
|
||||
console.log('Signed repository announcement:', signedEvent);
|
||||
console.log('Event coordinate:', `30617:${user.pubkey}:${repoId.trim()}`);
|
||||
|
||||
// Publish to Nostr relays
|
||||
// Repository announcements go to: write relays + relays specified in the announcement
|
||||
const writeRelays = config.relayMetadata.relays
|
||||
.filter(r => r.write)
|
||||
.map(r => r.url);
|
||||
const publishRelays = [...new Set([...writeRelays, ...relays])];
|
||||
console.log('Publishing repository announcement to relays:', publishRelays);
|
||||
|
||||
await nostr.event(signedEvent, { relays: publishRelays });
|
||||
|
||||
console.log('Published repository announcement to Nostr relays');
|
||||
console.log('To verify: Query for kind 30617 with authors=[' + user.pubkey + '] and #d=[' + repoId.trim() + ']');
|
||||
|
||||
// Create naddr for the repository using shared utility
|
||||
const naddr = createRepositoryNaddr(repoId, user.pubkey, relays);
|
||||
|
||||
toast({
|
||||
title: 'Published Nostr announcement',
|
||||
description: 'Configuring repository...',
|
||||
});
|
||||
|
||||
// Close the dialog
|
||||
handleOpenChange(false);
|
||||
|
||||
// Call success callback with the data needed for Git operations
|
||||
onSuccess?.({
|
||||
repoId: repoId.trim(),
|
||||
cloneUrls,
|
||||
relays,
|
||||
naddr,
|
||||
});
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
|
||||
setError(errorMessage);
|
||||
toast({
|
||||
title: 'Failed to announce repository',
|
||||
description: errorMessage,
|
||||
variant: 'destructive',
|
||||
duration: Infinity,
|
||||
});
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
setIsOpen(newOpen);
|
||||
onOpenChange?.(newOpen);
|
||||
|
||||
// Reset form when closing
|
||||
if (!newOpen) {
|
||||
setIsPrepopulated(false);
|
||||
setRepoId('');
|
||||
setName('');
|
||||
setDescription('');
|
||||
setWebUrls([]);
|
||||
setCloneUrls([]);
|
||||
setRelays(['wss://relay.nostr.band']);
|
||||
setTTags([]);
|
||||
setEarliestCommit('');
|
||||
setError(null);
|
||||
setNewWebUrl('');
|
||||
setNewCloneUrl('');
|
||||
setNewRelay('');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Settings className="h-5 w-5" />
|
||||
{editNaddr ? 'Edit' : ''} Nostr Repository Settings
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{editNaddr
|
||||
? 'Update your repository announcement (NIP-34) for Nostr git clients'
|
||||
: 'Configure your repository announcement (NIP-34) for Nostr git clients'
|
||||
}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<ScrollArea className="max-h-[60vh]">
|
||||
<div className="space-y-6 p-1 pr-4">
|
||||
{/* Error alert */}
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Repository ID */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="repo-id">Repository ID *</Label>
|
||||
<Input
|
||||
id="repo-id"
|
||||
placeholder="e.g., my-project"
|
||||
value={repoId}
|
||||
onChange={(e) => handleRepoIdChange(e.target.value)}
|
||||
disabled={isCreating}
|
||||
className={repoIdError ? 'border-destructive' : ''}
|
||||
/>
|
||||
{repoIdError ? (
|
||||
<p className="text-xs text-destructive">{repoIdError}</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Kebab-case short name (e.g., "my-project", "awesome-app")
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Name */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="repo-name">Name</Label>
|
||||
<Input
|
||||
id="repo-name"
|
||||
placeholder="Human-readable project name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
disabled={isCreating}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Display name for your repository
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="repo-description">Description</Label>
|
||||
<Textarea
|
||||
id="repo-description"
|
||||
placeholder="Brief description of your project"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
rows={3}
|
||||
disabled={isCreating}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Advanced Settings */}
|
||||
<Collapsible open={showAdvanced} onOpenChange={setShowAdvanced}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="w-full justify-between p-0 hover:bg-transparent"
|
||||
>
|
||||
<span className="text-sm font-medium">Advanced Settings</span>
|
||||
<ChevronDown
|
||||
className={`h-4 w-4 transition-transform ${
|
||||
showAdvanced ? 'rotate-180' : ''
|
||||
}`}
|
||||
/>
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="space-y-6 pt-4">
|
||||
{/* Web URLs */}
|
||||
<div className="space-y-2">
|
||||
<Label>Web URLs (Optional)</Label>
|
||||
<div className="space-y-2">
|
||||
{webUrls.map((url, index) => (
|
||||
<div key={index} className="flex gap-2">
|
||||
<Input
|
||||
value={url}
|
||||
onChange={(e) => {
|
||||
const newUrls = [...webUrls];
|
||||
newUrls[index] = e.target.value;
|
||||
setWebUrls(newUrls);
|
||||
}}
|
||||
className="flex-1"
|
||||
disabled={isCreating}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => removeWebUrl(index)}
|
||||
disabled={isCreating}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="https://example.com/browse"
|
||||
value={newWebUrl}
|
||||
onChange={(e) => setNewWebUrl(e.target.value)}
|
||||
onKeyDown={(e) =>
|
||||
e.key === 'Enter' && (e.preventDefault(), addWebUrl())
|
||||
}
|
||||
disabled={isCreating}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={addWebUrl}
|
||||
disabled={isCreating}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
URLs where the repository can be browsed online
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Clone URLs */}
|
||||
<div className="space-y-2">
|
||||
<Label>Git Server Clone URLs</Label>
|
||||
<div className="space-y-2">
|
||||
{cloneUrls.map((url, index) => (
|
||||
<div key={index} className="flex gap-2">
|
||||
<Input
|
||||
value={url}
|
||||
onChange={(e) => {
|
||||
const newUrls = [...cloneUrls];
|
||||
newUrls[index] = e.target.value;
|
||||
setCloneUrls(newUrls);
|
||||
}}
|
||||
className="flex-1 font-mono text-sm"
|
||||
disabled={isCreating}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => removeCloneUrl(index)}
|
||||
disabled={isCreating}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="https://gitnostr.com/..."
|
||||
value={newCloneUrl}
|
||||
onChange={(e) => setNewCloneUrl(e.target.value)}
|
||||
onKeyDown={(e) =>
|
||||
e.key === 'Enter' && (e.preventDefault(), addCloneUrl())
|
||||
}
|
||||
disabled={isCreating}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={addCloneUrl}
|
||||
disabled={isCreating}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
HTTPS URLs for cloning the repository (nostr:// URLs not allowed)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Relays */}
|
||||
<div className="space-y-2">
|
||||
<Label>Git Nostr Relays</Label>
|
||||
<div className="space-y-2">
|
||||
{relays.map((relay, index) => (
|
||||
<div key={index} className="flex gap-2">
|
||||
<Input
|
||||
value={relay}
|
||||
onChange={(e) => {
|
||||
const newRelays = [...relays];
|
||||
newRelays[index] = e.target.value;
|
||||
setRelays(newRelays);
|
||||
}}
|
||||
className="flex-1 font-mono text-sm"
|
||||
disabled={isCreating}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => removeRelay(index)}
|
||||
disabled={isCreating || relays.length === 1}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="wss://relay.example.com"
|
||||
value={newRelay}
|
||||
onChange={(e) => setNewRelay(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addRelay())}
|
||||
disabled={isCreating}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={addRelay}
|
||||
disabled={isCreating}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Nostr relays where patches and issues will be published and monitored
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Category Tags (t-tags) */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="category-tags">Category Tags</Label>
|
||||
<TagInput
|
||||
id="category-tags"
|
||||
value={tTags}
|
||||
onChange={setTTags}
|
||||
placeholder="e.g., nostr, social, web"
|
||||
disabled={isCreating}
|
||||
transformTag={(tag) => tag.trim().toLowerCase()}
|
||||
allowDuplicates={false}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Tags for categorizing your repository. Press space or comma to add a tag.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Earliest Commit */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="earliest-commit">Earliest Unique Commit</Label>
|
||||
<Input
|
||||
id="earliest-commit"
|
||||
placeholder="Commit hash"
|
||||
value={earliestCommit}
|
||||
onChange={(e) => setEarliestCommit(e.target.value)}
|
||||
disabled={isCreating}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
The root commit of your repository (auto-detected)
|
||||
</p>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={isCreating}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={announceRepository}
|
||||
disabled={isCreating || !!repoIdError || !repoId.trim()}
|
||||
>
|
||||
{isCreating ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{editNaddr ? 'Updating...' : 'Publishing...'}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GitBranch className="h-4 w-4 mr-2" />
|
||||
{editNaddr ? 'Update on Nostr' : 'Publish to Nostr'}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,522 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
GitBranch,
|
||||
Plus,
|
||||
Trash2,
|
||||
Check,
|
||||
Loader2,
|
||||
ArrowUpRight,
|
||||
} from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface BranchInfo {
|
||||
name: string;
|
||||
isCurrent: boolean;
|
||||
isRemote: boolean;
|
||||
remoteName?: string;
|
||||
commitId?: string;
|
||||
ahead?: number;
|
||||
behind?: number;
|
||||
}
|
||||
|
||||
interface BranchManagerProps {
|
||||
projectId: string;
|
||||
currentBranch: string | null;
|
||||
onBranchChange?: () => void;
|
||||
}
|
||||
|
||||
export function BranchManager({ projectId, currentBranch, onBranchChange }: BranchManagerProps) {
|
||||
const [branches, setBranches] = useState<BranchInfo[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [newBranchName, setNewBranchName] = useState('');
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
|
||||
const [deletingBranch, setDeletingBranch] = useState<string | null>(null);
|
||||
const [switchingToBranch, setSwitchingToBranch] = useState<string | null>(null);
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { toast } = useToast();
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
const loadBranches = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
// Get local branches
|
||||
const localBranches = await git.listBranches({
|
||||
dir: projectPath,
|
||||
});
|
||||
|
||||
// Get remote branches
|
||||
let remoteBranches: string[] = [];
|
||||
try {
|
||||
remoteBranches = await git.listBranches({
|
||||
dir: projectPath,
|
||||
remote: 'origin',
|
||||
});
|
||||
} catch {
|
||||
// No remote or error fetching remote branches
|
||||
}
|
||||
|
||||
// Get current branch
|
||||
const current = await git.currentBranch({ dir: projectPath }).catch(() => null);
|
||||
|
||||
// Build branch info
|
||||
const branchInfos: BranchInfo[] = [];
|
||||
|
||||
// Add local branches
|
||||
for (const branch of localBranches) {
|
||||
const isCurrent = branch === current;
|
||||
let commitId: string | undefined;
|
||||
try {
|
||||
commitId = await git.resolveRef({
|
||||
dir: projectPath,
|
||||
ref: `refs/heads/${branch}`,
|
||||
});
|
||||
} catch {
|
||||
// Skip branches we can't resolve
|
||||
}
|
||||
|
||||
branchInfos.push({
|
||||
name: branch,
|
||||
isCurrent,
|
||||
isRemote: false,
|
||||
commitId,
|
||||
});
|
||||
}
|
||||
|
||||
// Add remote branches
|
||||
for (const branch of remoteBranches) {
|
||||
// Skip if we already have this as a local branch
|
||||
if (localBranches.includes(branch)) continue;
|
||||
|
||||
let commitId: string | undefined;
|
||||
try {
|
||||
commitId = await git.resolveRef({
|
||||
dir: projectPath,
|
||||
ref: `refs/remotes/origin/${branch}`,
|
||||
});
|
||||
} catch {
|
||||
// Skip branches we can't resolve
|
||||
}
|
||||
|
||||
branchInfos.push({
|
||||
name: branch,
|
||||
isCurrent: false,
|
||||
isRemote: true,
|
||||
remoteName: 'origin',
|
||||
commitId,
|
||||
});
|
||||
}
|
||||
|
||||
setBranches(branchInfos);
|
||||
} catch (error) {
|
||||
console.error('Failed to load branches:', error);
|
||||
toast({
|
||||
title: 'Failed to load branches',
|
||||
description: error instanceof Error ? error.message : 'Unknown error',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [git, projectPath, toast]);
|
||||
|
||||
useEffect(() => {
|
||||
loadBranches();
|
||||
}, [projectId, currentBranch, loadBranches]);
|
||||
|
||||
const handleCreateBranch = async () => {
|
||||
if (!newBranchName.trim()) {
|
||||
toast({
|
||||
title: 'Invalid branch name',
|
||||
description: 'Please enter a branch name',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate branch name
|
||||
const invalidChars = /[~^: \\?*[\]]/;
|
||||
if (invalidChars.test(newBranchName)) {
|
||||
toast({
|
||||
title: 'Invalid branch name',
|
||||
description: 'Branch name contains invalid characters',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCreating(true);
|
||||
try {
|
||||
// Get current HEAD to base the new branch on
|
||||
const currentRef = await git.resolveRef({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
|
||||
// Create the new branch
|
||||
await git.branch({
|
||||
dir: projectPath,
|
||||
ref: newBranchName.trim(),
|
||||
object: currentRef,
|
||||
});
|
||||
|
||||
// Automatically check out the new branch
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: newBranchName.trim(),
|
||||
force: true,
|
||||
});
|
||||
|
||||
// Close the dialog before showing the toast
|
||||
setNewBranchName('');
|
||||
setIsCreateDialogOpen(false);
|
||||
|
||||
// Show success toast indicating the branch was created and checked out
|
||||
toast({
|
||||
title: 'Branch created and checked out',
|
||||
description: `Switched to new branch "${newBranchName.trim()}"`,
|
||||
});
|
||||
|
||||
await loadBranches();
|
||||
onBranchChange?.();
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Failed to create branch',
|
||||
description: error instanceof Error ? error.message : 'Unknown error',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSwitchBranch = async (branchName: string) => {
|
||||
setSwitchingToBranch(branchName);
|
||||
try {
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: branchName,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Branch switched',
|
||||
description: `Switched to branch "${branchName}"`,
|
||||
});
|
||||
|
||||
await loadBranches();
|
||||
onBranchChange?.();
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Failed to switch branch',
|
||||
description: error instanceof Error ? error.message : 'Unknown error',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setSwitchingToBranch(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteBranch = async (branchName: string) => {
|
||||
setDeletingBranch(branchName);
|
||||
try {
|
||||
await git.deleteBranch({
|
||||
dir: projectPath,
|
||||
ref: branchName,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Branch deleted',
|
||||
description: `Deleted branch "${branchName}"`,
|
||||
});
|
||||
|
||||
await loadBranches();
|
||||
onBranchChange?.();
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Failed to delete branch',
|
||||
description: error instanceof Error ? error.message : 'Unknown error',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setDeletingBranch(null);
|
||||
}
|
||||
};
|
||||
|
||||
const localBranches = branches.filter(b => !b.isRemote);
|
||||
const remoteBranches = branches.filter(b => b.isRemote);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Header with create button */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-medium">Branches</h3>
|
||||
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="h-8 gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
New Branch
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create New Branch</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create a new branch from the current HEAD
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="branch-name">Branch Name</Label>
|
||||
<Input
|
||||
id="branch-name"
|
||||
placeholder="feature/my-new-feature"
|
||||
value={newBranchName}
|
||||
onChange={(e) => setNewBranchName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && !isCreating) {
|
||||
handleCreateBranch();
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
{currentBranch && (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Creating from: <span className="font-medium">{currentBranch}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setIsCreateDialogOpen(false)}
|
||||
disabled={isCreating}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleCreateBranch} disabled={isCreating}>
|
||||
{isCreating ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Create Branch
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{/* Local Branches */}
|
||||
{localBranches.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
|
||||
Local Branches
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{localBranches.map((branch) => (
|
||||
<BranchItem
|
||||
key={branch.name}
|
||||
branch={branch}
|
||||
onSwitch={handleSwitchBranch}
|
||||
onDelete={handleDeleteBranch}
|
||||
isSwitching={switchingToBranch === branch.name}
|
||||
isDeleting={deletingBranch === branch.name}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Remote Branches */}
|
||||
{remoteBranches.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
|
||||
Remote Branches
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{remoteBranches.map((branch) => (
|
||||
<BranchItem
|
||||
key={`remote-${branch.name}`}
|
||||
branch={branch}
|
||||
onSwitch={handleSwitchBranch}
|
||||
onDelete={handleDeleteBranch}
|
||||
isSwitching={switchingToBranch === branch.name}
|
||||
isDeleting={deletingBranch === branch.name}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Empty state */}
|
||||
{localBranches.length === 0 && remoteBranches.length === 0 && (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<GitBranch className="h-12 w-12 mx-auto mb-2 opacity-50" />
|
||||
<p className="text-sm">No branches found</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface BranchItemProps {
|
||||
branch: BranchInfo;
|
||||
onSwitch: (name: string) => void;
|
||||
onDelete: (name: string) => void;
|
||||
isSwitching: boolean;
|
||||
isDeleting: boolean;
|
||||
}
|
||||
|
||||
function BranchItem({ branch, onSwitch, onDelete, isSwitching, isDeleting }: BranchItemProps) {
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center gap-3 p-3 rounded-lg border transition-colors group',
|
||||
branch.isCurrent
|
||||
? 'bg-primary/5 border-primary/20'
|
||||
: 'hover:bg-muted/50 border-transparent'
|
||||
)}
|
||||
>
|
||||
{/* Branch icon and name */}
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
{branch.isCurrent ? (
|
||||
<Check className="h-4 w-4 text-primary shrink-0" />
|
||||
) : (
|
||||
<GitBranch className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
)}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
'font-mono text-sm truncate',
|
||||
branch.isCurrent && 'font-semibold text-primary'
|
||||
)}
|
||||
>
|
||||
{branch.name}
|
||||
</span>
|
||||
{branch.isRemote && (
|
||||
<ArrowUpRight className="h-3 w-3 text-muted-foreground shrink-0" />
|
||||
)}
|
||||
</div>
|
||||
{branch.commitId && (
|
||||
<div className="text-xs text-muted-foreground font-mono">
|
||||
{branch.commitId.substring(0, 7)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Current badge */}
|
||||
{branch.isCurrent && (
|
||||
<Badge variant="secondary" className="shrink-0">
|
||||
Current
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
{!branch.isCurrent && !branch.isRemote && (
|
||||
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-2"
|
||||
onClick={() => onSwitch(branch.name)}
|
||||
disabled={isSwitching || isDeleting}
|
||||
>
|
||||
{isSwitching ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
<GitBranch className="h-4 w-4 mr-1" />
|
||||
Switch
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-2 text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
onClick={() => setShowDeleteDialog(true)}
|
||||
disabled={isSwitching || isDeleting}
|
||||
>
|
||||
{isDeleting ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Delete confirmation dialog */}
|
||||
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Branch</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete the branch <strong>{branch.name}</strong>?
|
||||
This action cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => {
|
||||
onDelete(branch.name);
|
||||
setShowDeleteDialog(false);
|
||||
}}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
Delete Branch
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,352 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { GitCompare, Loader2, GitCommit, FileIcon } from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { DiffViewer } from './DiffViewer';
|
||||
|
||||
interface CompareViewProps {
|
||||
projectId: string;
|
||||
}
|
||||
|
||||
interface CommitInfo {
|
||||
oid: string;
|
||||
message: string;
|
||||
author: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export function CompareView({ projectId }: CompareViewProps) {
|
||||
const [branches, setBranches] = useState<string[]>([]);
|
||||
const [commits, setCommits] = useState<CommitInfo[]>([]);
|
||||
const [baseRef, setBaseRef] = useState<string>('');
|
||||
const [compareRef, setCompareRef] = useState<string>('');
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isComparing, setIsComparing] = useState(false);
|
||||
const [comparisonStats, setComparisonStats] = useState<{
|
||||
ahead: number;
|
||||
behind: number;
|
||||
filesChanged: number;
|
||||
} | null>(null);
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { toast } = useToast();
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
const loadReferences = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
// Get all branches
|
||||
const localBranches = await git.listBranches({ dir: projectPath });
|
||||
setBranches(localBranches);
|
||||
|
||||
// Set defaults
|
||||
const currentBranch = await git.currentBranch({ dir: projectPath }).catch(() => null);
|
||||
if (currentBranch) {
|
||||
setCompareRef(currentBranch);
|
||||
}
|
||||
|
||||
// Set base to main/master if available
|
||||
if (localBranches.includes('main')) {
|
||||
setBaseRef('main');
|
||||
} else if (localBranches.includes('master')) {
|
||||
setBaseRef('master');
|
||||
} else if (localBranches.length > 0) {
|
||||
setBaseRef(localBranches[0]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load references:', error);
|
||||
toast({
|
||||
title: 'Failed to load branches',
|
||||
description: error instanceof Error ? error.message : 'Unknown error',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [git, projectPath, toast]);
|
||||
|
||||
const performComparison = useCallback(async () => {
|
||||
if (!baseRef || !compareRef) return;
|
||||
|
||||
setIsComparing(true);
|
||||
try {
|
||||
// Get commits in compareRef that are not in baseRef
|
||||
const baseCommits = await git.log({ dir: projectPath, ref: baseRef, depth: 100 });
|
||||
const compareCommits = await git.log({ dir: projectPath, ref: compareRef, depth: 100 });
|
||||
|
||||
const baseCommitIds = new Set(baseCommits.map(c => c.oid));
|
||||
const compareCommitIds = new Set(compareCommits.map(c => c.oid));
|
||||
|
||||
// Commits ahead (in compare but not in base)
|
||||
const aheadCommits = compareCommits.filter(c => !baseCommitIds.has(c.oid));
|
||||
|
||||
// Commits behind (in base but not in compare)
|
||||
const behindCommits = baseCommits.filter(c => !compareCommitIds.has(c.oid));
|
||||
|
||||
// Get list of changed files
|
||||
const baseFiles = await git.listFiles({ dir: projectPath, ref: baseRef });
|
||||
const compareFiles = await git.listFiles({ dir: projectPath, ref: compareRef });
|
||||
|
||||
const changedFiles = new Set<string>();
|
||||
|
||||
// Check files in compare ref
|
||||
for (const file of compareFiles) {
|
||||
try {
|
||||
const baseBlob = await git.readBlob({ dir: projectPath, oid: baseRef, filepath: file });
|
||||
const compareBlob = await git.readBlob({ dir: projectPath, oid: compareRef, filepath: file });
|
||||
|
||||
if (Buffer.from(baseBlob.blob).toString() !== Buffer.from(compareBlob.blob).toString()) {
|
||||
changedFiles.add(file);
|
||||
}
|
||||
} catch {
|
||||
// File exists in one but not the other
|
||||
changedFiles.add(file);
|
||||
}
|
||||
}
|
||||
|
||||
// Check for deleted files
|
||||
for (const file of baseFiles) {
|
||||
if (!compareFiles.includes(file)) {
|
||||
changedFiles.add(file);
|
||||
}
|
||||
}
|
||||
|
||||
setComparisonStats({
|
||||
ahead: aheadCommits.length,
|
||||
behind: behindCommits.length,
|
||||
filesChanged: changedFiles.size,
|
||||
});
|
||||
|
||||
// Set commit info for display
|
||||
const commitInfos: CommitInfo[] = aheadCommits.map(c => ({
|
||||
oid: c.oid,
|
||||
message: c.commit.message,
|
||||
author: c.commit.author.name,
|
||||
timestamp: c.commit.author.timestamp,
|
||||
}));
|
||||
|
||||
setCommits(commitInfos);
|
||||
} catch (error) {
|
||||
console.error('Failed to compare:', error);
|
||||
toast({
|
||||
title: 'Comparison failed',
|
||||
description: error instanceof Error ? error.message : 'Unknown error',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsComparing(false);
|
||||
}
|
||||
}, [baseRef, compareRef, git, projectPath, toast]);
|
||||
|
||||
useEffect(() => {
|
||||
loadReferences();
|
||||
}, [projectId, loadReferences]);
|
||||
|
||||
useEffect(() => {
|
||||
if (baseRef && compareRef && baseRef !== compareRef) {
|
||||
performComparison();
|
||||
}
|
||||
}, [baseRef, compareRef, performComparison]);
|
||||
|
||||
const formatDate = (timestamp: number) => {
|
||||
const date = new Date(timestamp * 1000);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
|
||||
|
||||
if (diffDays === 0) {
|
||||
return 'today';
|
||||
} else if (diffDays === 1) {
|
||||
return 'yesterday';
|
||||
} else if (diffDays < 7) {
|
||||
return `${diffDays} days ago`;
|
||||
} else {
|
||||
return date.toLocaleDateString();
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Comparison selectors */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<GitCompare className="h-5 w-5" />
|
||||
Compare Branches
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Select two branches to compare changes
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex-1">
|
||||
<label className="text-sm font-medium mb-2 block">Base Branch</label>
|
||||
<Select value={baseRef} onValueChange={setBaseRef}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select base branch" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{branches.map((branch) => (
|
||||
<SelectItem key={branch} value={branch}>
|
||||
{branch}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="pt-6">
|
||||
<GitCompare className="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
|
||||
<div className="flex-1">
|
||||
<label className="text-sm font-medium mb-2 block">Compare Branch</label>
|
||||
<Select value={compareRef} onValueChange={setCompareRef}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select compare branch" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{branches.map((branch) => (
|
||||
<SelectItem key={branch} value={branch}>
|
||||
{branch}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Comparison stats */}
|
||||
{comparisonStats && !isComparing && (
|
||||
<div className="mt-6 grid grid-cols-3 gap-4">
|
||||
<div className="bg-muted/30 rounded-lg p-4 text-center">
|
||||
<div className="text-2xl font-bold text-green-600">
|
||||
{comparisonStats.ahead}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-1">
|
||||
Commits Ahead
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-muted/30 rounded-lg p-4 text-center">
|
||||
<div className="text-2xl font-bold text-orange-600">
|
||||
{comparisonStats.behind}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-1">
|
||||
Commits Behind
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-muted/30 rounded-lg p-4 text-center">
|
||||
<div className="text-2xl font-bold text-blue-600">
|
||||
{comparisonStats.filesChanged}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-1">
|
||||
Files Changed
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isComparing && (
|
||||
<div className="mt-6 flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground mr-2" />
|
||||
<span className="text-muted-foreground">Comparing branches...</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Comparison results */}
|
||||
{baseRef && compareRef && baseRef !== compareRef && !isComparing && (
|
||||
<Tabs defaultValue="commits" className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="commits" className="gap-2">
|
||||
<GitCommit className="h-4 w-4" />
|
||||
Commits ({commits.length})
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="files" className="gap-2">
|
||||
<FileIcon className="h-4 w-4" />
|
||||
Files ({comparisonStats?.filesChanged || 0})
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* Commits tab */}
|
||||
<TabsContent value="commits" className="mt-6">
|
||||
{commits.length > 0 ? (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">
|
||||
Commits in {compareRef} not in {baseRef}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{commits.map((commit) => (
|
||||
<div
|
||||
key={commit.oid}
|
||||
className="flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<GitCommit className="h-5 w-5 text-muted-foreground shrink-0 mt-0.5" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-sm">
|
||||
{commit.message.split('\n')[0]}
|
||||
</p>
|
||||
<div className="flex items-center gap-3 mt-1 text-xs text-muted-foreground">
|
||||
<span>{commit.author}</span>
|
||||
<span>•</span>
|
||||
<span>{formatDate(commit.timestamp)}</span>
|
||||
<span>•</span>
|
||||
<span className="font-mono">{commit.oid.substring(0, 7)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="py-12 text-center">
|
||||
<GitCommit className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
|
||||
<p className="text-muted-foreground">
|
||||
No commits difference between branches
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
{/* Files tab */}
|
||||
<TabsContent value="files" className="mt-6">
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<DiffViewer
|
||||
projectId={projectId}
|
||||
compareFrom={baseRef}
|
||||
compareTo={compareRef}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,558 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import {
|
||||
FileIcon,
|
||||
Plus,
|
||||
Minus,
|
||||
Edit,
|
||||
Loader2,
|
||||
SplitSquareHorizontal,
|
||||
ListTree,
|
||||
Copy,
|
||||
Check,
|
||||
} from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface DiffHunk {
|
||||
oldStart: number;
|
||||
oldLines: number;
|
||||
newStart: number;
|
||||
newLines: number;
|
||||
lines: DiffLine[];
|
||||
}
|
||||
|
||||
interface DiffLine {
|
||||
type: 'add' | 'delete' | 'context';
|
||||
content: string;
|
||||
oldLineNumber?: number;
|
||||
newLineNumber?: number;
|
||||
}
|
||||
|
||||
interface FileDiff {
|
||||
filepath: string;
|
||||
status: 'modified' | 'added' | 'deleted';
|
||||
hunks: DiffHunk[];
|
||||
oldContent?: string;
|
||||
newContent?: string;
|
||||
}
|
||||
|
||||
interface DiffViewerProps {
|
||||
projectId: string;
|
||||
compareFrom?: string; // commit, branch, or 'HEAD'
|
||||
compareTo?: string; // commit, branch, or working directory
|
||||
filepath?: string; // If provided, show only this file
|
||||
}
|
||||
|
||||
export function DiffViewer({ projectId, compareFrom = 'HEAD', compareTo, filepath }: DiffViewerProps) {
|
||||
const [diffs, setDiffs] = useState<FileDiff[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||
const [viewMode, setViewMode] = useState<'unified' | 'split'>('split');
|
||||
const [copiedHunk, setCopiedHunk] = useState<number | null>(null);
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { fs } = useFS();
|
||||
const { toast } = useToast();
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
const getChangedFilesBetweenRefs = useCallback(async (from: string, to: string): Promise<string[]> => {
|
||||
// Get list of files from both refs and find differences
|
||||
const filesFrom = await git.listFiles({ dir: projectPath, ref: from });
|
||||
const filesTo = await git.listFiles({ dir: projectPath, ref: to });
|
||||
|
||||
const changedFiles = new Set<string>();
|
||||
|
||||
// Check files that exist in 'to'
|
||||
for (const file of filesTo) {
|
||||
try {
|
||||
const blobFrom = await git.readBlob({ dir: projectPath, oid: from, filepath: file });
|
||||
const blobTo = await git.readBlob({ dir: projectPath, oid: to, filepath: file });
|
||||
|
||||
// Compare content
|
||||
if (Buffer.from(blobFrom.blob).toString() !== Buffer.from(blobTo.blob).toString()) {
|
||||
changedFiles.add(file);
|
||||
}
|
||||
} catch {
|
||||
// File exists in one but not the other
|
||||
changedFiles.add(file);
|
||||
}
|
||||
}
|
||||
|
||||
// Check files that were deleted
|
||||
for (const file of filesFrom) {
|
||||
if (!filesTo.includes(file)) {
|
||||
changedFiles.add(file);
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(changedFiles);
|
||||
}, [git, projectPath]);
|
||||
|
||||
const generateFileDiff = useCallback(async (
|
||||
file: string,
|
||||
from: string,
|
||||
to?: string
|
||||
): Promise<FileDiff | null> => {
|
||||
try {
|
||||
let oldContent = '';
|
||||
let newContent = '';
|
||||
let status: 'modified' | 'added' | 'deleted' = 'modified';
|
||||
|
||||
// Get old content
|
||||
try {
|
||||
const blob = await git.readBlob({ dir: projectPath, oid: from, filepath: file });
|
||||
oldContent = Buffer.from(blob.blob).toString('utf-8');
|
||||
} catch {
|
||||
// File didn't exist in old version
|
||||
status = 'added';
|
||||
}
|
||||
|
||||
// Get new content
|
||||
try {
|
||||
if (to) {
|
||||
const blob = await git.readBlob({ dir: projectPath, oid: to, filepath: file });
|
||||
newContent = Buffer.from(blob.blob).toString('utf-8');
|
||||
} else {
|
||||
// Working directory
|
||||
const content = await fs.readFile(`${projectPath}/${file}`, { encoding: 'utf8' });
|
||||
newContent = content;
|
||||
}
|
||||
} catch {
|
||||
// File doesn't exist in new version
|
||||
if (status !== 'added') {
|
||||
status = 'deleted';
|
||||
}
|
||||
}
|
||||
|
||||
// Generate hunks
|
||||
const hunks = generateDiffHunks(oldContent, newContent);
|
||||
|
||||
return {
|
||||
filepath: file,
|
||||
status,
|
||||
hunks,
|
||||
oldContent,
|
||||
newContent,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(`Error generating diff for ${file}:`, error);
|
||||
return null;
|
||||
}
|
||||
}, [git, projectPath, fs]);
|
||||
|
||||
const generateDiffHunks = (oldContent: string, newContent: string): DiffHunk[] => {
|
||||
const oldLines = oldContent.split('\n');
|
||||
const newLines = newContent.split('\n');
|
||||
|
||||
// Simple line-by-line diff
|
||||
const hunks: DiffHunk[] = [];
|
||||
let currentHunk: DiffHunk | null = null;
|
||||
|
||||
let oldIndex = 0;
|
||||
let newIndex = 0;
|
||||
|
||||
while (oldIndex < oldLines.length || newIndex < newLines.length) {
|
||||
const oldLine = oldLines[oldIndex];
|
||||
const newLine = newLines[newIndex];
|
||||
|
||||
if (oldLine === newLine) {
|
||||
// Context line
|
||||
if (currentHunk) {
|
||||
currentHunk.lines.push({
|
||||
type: 'context',
|
||||
content: oldLine || '',
|
||||
oldLineNumber: oldIndex + 1,
|
||||
newLineNumber: newIndex + 1,
|
||||
});
|
||||
}
|
||||
oldIndex++;
|
||||
newIndex++;
|
||||
} else {
|
||||
// Start a new hunk if needed
|
||||
if (!currentHunk) {
|
||||
currentHunk = {
|
||||
oldStart: oldIndex + 1,
|
||||
oldLines: 0,
|
||||
newStart: newIndex + 1,
|
||||
newLines: 0,
|
||||
lines: [],
|
||||
};
|
||||
|
||||
// Add context before the change
|
||||
const contextStart = Math.max(0, oldIndex - 3);
|
||||
for (let i = contextStart; i < oldIndex; i++) {
|
||||
currentHunk.lines.push({
|
||||
type: 'context',
|
||||
content: oldLines[i] || '',
|
||||
oldLineNumber: i + 1,
|
||||
newLineNumber: i + 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Determine if this is an addition, deletion, or modification
|
||||
if (oldIndex >= oldLines.length) {
|
||||
// Addition
|
||||
currentHunk.lines.push({
|
||||
type: 'add',
|
||||
content: newLine || '',
|
||||
newLineNumber: newIndex + 1,
|
||||
});
|
||||
currentHunk.newLines++;
|
||||
newIndex++;
|
||||
} else if (newIndex >= newLines.length) {
|
||||
// Deletion
|
||||
currentHunk.lines.push({
|
||||
type: 'delete',
|
||||
content: oldLine || '',
|
||||
oldLineNumber: oldIndex + 1,
|
||||
});
|
||||
currentHunk.oldLines++;
|
||||
oldIndex++;
|
||||
} else {
|
||||
// Changed line - show as delete + add
|
||||
currentHunk.lines.push({
|
||||
type: 'delete',
|
||||
content: oldLine || '',
|
||||
oldLineNumber: oldIndex + 1,
|
||||
});
|
||||
currentHunk.lines.push({
|
||||
type: 'add',
|
||||
content: newLine || '',
|
||||
newLineNumber: newIndex + 1,
|
||||
});
|
||||
currentHunk.oldLines++;
|
||||
currentHunk.newLines++;
|
||||
oldIndex++;
|
||||
newIndex++;
|
||||
}
|
||||
|
||||
// Check if we should close this hunk
|
||||
const contextAfter = 3;
|
||||
let contextCount = 0;
|
||||
let tempOldIndex = oldIndex;
|
||||
let tempNewIndex = newIndex;
|
||||
|
||||
while (
|
||||
contextCount < contextAfter &&
|
||||
tempOldIndex < oldLines.length &&
|
||||
tempNewIndex < newLines.length
|
||||
) {
|
||||
if (oldLines[tempOldIndex] === newLines[tempNewIndex]) {
|
||||
currentHunk.lines.push({
|
||||
type: 'context',
|
||||
content: oldLines[tempOldIndex] || '',
|
||||
oldLineNumber: tempOldIndex + 1,
|
||||
newLineNumber: tempNewIndex + 1,
|
||||
});
|
||||
contextCount++;
|
||||
tempOldIndex++;
|
||||
tempNewIndex++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (contextCount >= contextAfter || tempOldIndex >= oldLines.length) {
|
||||
hunks.push(currentHunk);
|
||||
currentHunk = null;
|
||||
oldIndex = tempOldIndex;
|
||||
newIndex = tempNewIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Close any remaining hunk
|
||||
if (currentHunk) {
|
||||
hunks.push(currentHunk);
|
||||
}
|
||||
|
||||
return hunks;
|
||||
};
|
||||
|
||||
const loadDiffs = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
let files: string[] = [];
|
||||
|
||||
if (filepath) {
|
||||
files = [filepath];
|
||||
} else if (compareTo) {
|
||||
// Compare two commits/branches
|
||||
files = await getChangedFilesBetweenRefs(compareFrom, compareTo);
|
||||
} else {
|
||||
// Compare against working directory
|
||||
const statusMatrix = await git.statusMatrix({ dir: projectPath });
|
||||
files = statusMatrix
|
||||
.filter(([, head, workdir]) => head !== workdir)
|
||||
.map(([file]) => file);
|
||||
}
|
||||
|
||||
const fileDiffs: FileDiff[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const diff = await generateFileDiff(file, compareFrom, compareTo);
|
||||
if (diff) {
|
||||
fileDiffs.push(diff);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to generate diff for ${file}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
setDiffs(fileDiffs);
|
||||
if (fileDiffs.length > 0 && !selectedFile) {
|
||||
setSelectedFile(fileDiffs[0].filepath);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load diffs:', error);
|
||||
toast({
|
||||
title: 'Failed to load diffs',
|
||||
description: error instanceof Error ? error.message : 'Unknown error',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [compareFrom, compareTo, filepath, git, projectPath, selectedFile, toast, getChangedFilesBetweenRefs, generateFileDiff]);
|
||||
|
||||
useEffect(() => {
|
||||
loadDiffs();
|
||||
}, [projectId, compareFrom, compareTo, filepath, loadDiffs]);
|
||||
|
||||
const copyHunkToClipboard = async (hunk: DiffHunk, index: number) => {
|
||||
const hunkText = hunk.lines.map(line => line.content).join('\n');
|
||||
await navigator.clipboard.writeText(hunkText);
|
||||
setCopiedHunk(index);
|
||||
setTimeout(() => setCopiedHunk(null), 2000);
|
||||
};
|
||||
|
||||
const selectedDiff = diffs.find(d => d.filepath === selectedFile);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (diffs.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<FileIcon className="h-12 w-12 text-muted-foreground mb-4" />
|
||||
<p className="text-muted-foreground">No changes to display</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full">
|
||||
{/* File list sidebar */}
|
||||
<div className="w-64 border-r">
|
||||
<div className="p-4 border-b">
|
||||
<h3 className="font-semibold text-sm">Changed Files</h3>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{diffs.length} file{diffs.length !== 1 ? 's' : ''} changed
|
||||
</p>
|
||||
</div>
|
||||
<ScrollArea className="h-[calc(100%-73px)]">
|
||||
<div className="p-2 space-y-1">
|
||||
{diffs.map((diff) => (
|
||||
<button
|
||||
key={diff.filepath}
|
||||
onClick={() => setSelectedFile(diff.filepath)}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-2 p-2 rounded-lg text-left transition-colors',
|
||||
selectedFile === diff.filepath
|
||||
? 'bg-primary/10 text-primary'
|
||||
: 'hover:bg-muted/50'
|
||||
)}
|
||||
>
|
||||
{diff.status === 'added' && <Plus className="h-4 w-4 text-green-600 shrink-0" />}
|
||||
{diff.status === 'deleted' && <Minus className="h-4 w-4 text-red-600 shrink-0" />}
|
||||
{diff.status === 'modified' && <Edit className="h-4 w-4 text-blue-600 shrink-0" />}
|
||||
<span className="font-mono text-sm truncate">{diff.filepath}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
{/* Diff content */}
|
||||
<div className="flex-1 flex flex-col">
|
||||
{selectedDiff && (
|
||||
<>
|
||||
{/* Header */}
|
||||
<div className="p-4 border-b flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<h3 className="font-mono text-sm font-medium">{selectedDiff.filepath}</h3>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn(
|
||||
selectedDiff.status === 'added' && 'border-green-600 text-green-600',
|
||||
selectedDiff.status === 'deleted' && 'border-red-600 text-red-600',
|
||||
selectedDiff.status === 'modified' && 'border-blue-600 text-blue-600'
|
||||
)}
|
||||
>
|
||||
{selectedDiff.status}
|
||||
</Badge>
|
||||
</div>
|
||||
<Tabs value={viewMode} onValueChange={(v) => setViewMode(v as 'unified' | 'split')}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="split" className="gap-2">
|
||||
<SplitSquareHorizontal className="h-4 w-4" />
|
||||
Split
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="unified" className="gap-2">
|
||||
<ListTree className="h-4 w-4" />
|
||||
Unified
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
{/* Diff content */}
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-4">
|
||||
{selectedDiff.hunks.map((hunk, hunkIndex) => (
|
||||
<div key={hunkIndex} className="mb-6 border rounded-lg overflow-hidden">
|
||||
{/* Hunk header */}
|
||||
<div className="bg-muted/50 px-4 py-2 flex items-center justify-between border-b">
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
@@ -{hunk.oldStart},{hunk.oldLines} +{hunk.newStart},{hunk.newLines} @@
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-2"
|
||||
onClick={() => copyHunkToClipboard(hunk, hunkIndex)}
|
||||
>
|
||||
{copiedHunk === hunkIndex ? (
|
||||
<>
|
||||
<Check className="h-3 w-3 mr-1" />
|
||||
Copied
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Copy className="h-3 w-3 mr-1" />
|
||||
Copy
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Hunk lines */}
|
||||
{viewMode === 'split' ? (
|
||||
<SplitDiffView hunk={hunk} filepath={selectedDiff.filepath} />
|
||||
) : (
|
||||
<UnifiedDiffView hunk={hunk} filepath={selectedDiff.filepath} />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SplitDiffView({ hunk }: { hunk: DiffHunk; filepath: string }) {
|
||||
return (
|
||||
<div className="grid grid-cols-2 divide-x font-mono text-sm">
|
||||
{/* Old (left) side */}
|
||||
<div>
|
||||
{hunk.lines.map((line, i) => (
|
||||
line.type !== 'add' && (
|
||||
<div
|
||||
key={i}
|
||||
className={cn(
|
||||
'flex',
|
||||
line.type === 'delete' && 'bg-red-50 dark:bg-red-950/20'
|
||||
)}
|
||||
>
|
||||
<span className="px-2 py-1 text-muted-foreground select-none w-12 text-right shrink-0">
|
||||
{line.oldLineNumber}
|
||||
</span>
|
||||
<pre className="px-2 py-1 flex-1 overflow-x-auto">
|
||||
<code
|
||||
className={cn(line.type === 'delete' && 'text-red-700 dark:text-red-400')}
|
||||
dangerouslySetInnerHTML={{ __html: line.content }}
|
||||
/>
|
||||
</pre>
|
||||
</div>
|
||||
)
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* New (right) side */}
|
||||
<div>
|
||||
{hunk.lines.map((line, i) => (
|
||||
line.type !== 'delete' && (
|
||||
<div
|
||||
key={i}
|
||||
className={cn(
|
||||
'flex',
|
||||
line.type === 'add' && 'bg-green-50 dark:bg-green-950/20'
|
||||
)}
|
||||
>
|
||||
<span className="px-2 py-1 text-muted-foreground select-none w-12 text-right shrink-0">
|
||||
{line.newLineNumber}
|
||||
</span>
|
||||
<pre className="px-2 py-1 flex-1 overflow-x-auto">
|
||||
<code
|
||||
className={cn(line.type === 'add' && 'text-green-700 dark:text-green-400')}
|
||||
dangerouslySetInnerHTML={{ __html: line.content }}
|
||||
/>
|
||||
</pre>
|
||||
</div>
|
||||
)
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UnifiedDiffView({ hunk }: { hunk: DiffHunk; filepath: string }) {
|
||||
return (
|
||||
<div className="font-mono text-sm">
|
||||
{hunk.lines.map((line, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={cn(
|
||||
'flex',
|
||||
line.type === 'add' && 'bg-green-50 dark:bg-green-950/20',
|
||||
line.type === 'delete' && 'bg-red-50 dark:bg-red-950/20'
|
||||
)}
|
||||
>
|
||||
<span className="px-2 py-1 text-muted-foreground select-none w-12 text-right shrink-0">
|
||||
{line.oldLineNumber || line.newLineNumber}
|
||||
</span>
|
||||
<span className="px-2 py-1 select-none w-6 shrink-0">
|
||||
{line.type === 'add' ? '+' : line.type === 'delete' ? '-' : ' '}
|
||||
</span>
|
||||
<pre className="px-2 py-1 flex-1 overflow-x-auto">
|
||||
<code
|
||||
className={cn(
|
||||
line.type === 'add' && 'text-green-700 dark:text-green-400',
|
||||
line.type === 'delete' && 'text-red-700 dark:text-red-400'
|
||||
)}
|
||||
dangerouslySetInnerHTML={{ __html: line.content }}
|
||||
/>
|
||||
</pre>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import {
|
||||
GitBranch,
|
||||
GitCompare,
|
||||
Settings,
|
||||
GitPullRequest,
|
||||
} from 'lucide-react';
|
||||
import { BranchManager } from './BranchManager';
|
||||
import { CompareView } from './CompareView';
|
||||
import { DiffViewer } from './DiffViewer';
|
||||
import { PullRequestForm } from './PullRequestForm';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
|
||||
interface GitManagementDialogProps{
|
||||
projectId: string;
|
||||
children?: React.ReactNode;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
defaultTab?: string;
|
||||
}
|
||||
|
||||
export function GitManagementDialog({
|
||||
projectId,
|
||||
children,
|
||||
open,
|
||||
onOpenChange,
|
||||
defaultTab = 'branches',
|
||||
}: GitManagementDialogProps) {
|
||||
const [activeTab, setActiveTab] = useState(defaultTab);
|
||||
const [remoteUrl, setRemoteUrl] = useState<string | null>(null);
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
|
||||
|
||||
useEffect(() => {
|
||||
const loadRemoteUrl = async () => {
|
||||
try {
|
||||
const url = await git.getRemoteURL(projectPath, 'origin');
|
||||
setRemoteUrl(url);
|
||||
} catch {
|
||||
setRemoteUrl(null);
|
||||
}
|
||||
};
|
||||
if (open) {
|
||||
loadRemoteUrl();
|
||||
}
|
||||
}, [open, git, projectPath]);
|
||||
|
||||
const handleBranchChange = () => {
|
||||
// Refetch git status when branches change
|
||||
refetchGitStatus();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
{children && <DialogTrigger asChild>{children}</DialogTrigger>}
|
||||
<DialogContent className="max-w-6xl h-[90vh] p-0 flex flex-col gap-0">
|
||||
{/* Fixed Header */}
|
||||
<DialogHeader className="px-6 pt-6 pb-4 border-b shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<GitBranch className="h-5 w-5" />
|
||||
Git Management
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Tabs Container - takes remaining space */}
|
||||
<div className="flex-1 flex flex-col min-h-0">
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className="flex-1 flex flex-col">
|
||||
{/* Fixed Tab List */}
|
||||
<div className="border-b px-6 shrink-0">
|
||||
<TabsList className="h-auto p-0 bg-transparent">
|
||||
<TabsTrigger
|
||||
value="branches"
|
||||
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
|
||||
>
|
||||
<GitBranch className="h-4 w-4" />
|
||||
Branches
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="changes"
|
||||
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
|
||||
>
|
||||
<Settings className="h-4 w-4" />
|
||||
Changes
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="compare"
|
||||
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
|
||||
>
|
||||
<GitCompare className="h-4 w-4" />
|
||||
Compare
|
||||
</TabsTrigger>
|
||||
{remoteUrl && (
|
||||
<TabsTrigger
|
||||
value="pr"
|
||||
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
|
||||
>
|
||||
<GitPullRequest className="h-4 w-4" />
|
||||
Pull Request
|
||||
</TabsTrigger>
|
||||
)}
|
||||
</TabsList>
|
||||
</div>
|
||||
|
||||
{/* Scrollable Tab Content */}
|
||||
<TabsContent value="branches" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col">
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-6">
|
||||
<BranchManager
|
||||
projectId={projectId}
|
||||
currentBranch={gitStatus?.currentBranch || null}
|
||||
onBranchChange={handleBranchChange}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="changes" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col min-h-0">
|
||||
<div className="flex-1 min-h-0">
|
||||
<DiffViewer
|
||||
projectId={projectId}
|
||||
compareFrom="HEAD"
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="compare" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col">
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-6">
|
||||
<CompareView projectId={projectId} />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
|
||||
{remoteUrl && (
|
||||
<TabsContent value="pr" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col">
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-6">
|
||||
<PullRequestForm
|
||||
projectId={projectId}
|
||||
currentBranch={gitStatus?.currentBranch || null}
|
||||
remoteUrl={remoteUrl}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
)}
|
||||
</Tabs>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,576 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import {
|
||||
GitMerge,
|
||||
Loader2,
|
||||
AlertCircle,
|
||||
CheckCircle,
|
||||
GitCommit,
|
||||
AlertTriangle,
|
||||
} from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
|
||||
interface MergeDialogProps {
|
||||
projectId: string;
|
||||
currentBranch: string | null;
|
||||
sourceBranch?: string;
|
||||
targetBranch?: string;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
onMergeComplete?: () => void;
|
||||
}
|
||||
|
||||
interface MergePreview {
|
||||
sourceBranch: string;
|
||||
targetBranch: string;
|
||||
commitsToMerge: Array<{
|
||||
oid: string;
|
||||
message: string;
|
||||
author: string;
|
||||
timestamp: number;
|
||||
}>;
|
||||
filesChanged: string[];
|
||||
canFastForward: boolean;
|
||||
hasConflicts: boolean;
|
||||
conflictingFiles: string[];
|
||||
}
|
||||
|
||||
export function MergeDialog({
|
||||
projectId,
|
||||
currentBranch,
|
||||
sourceBranch: initialSourceBranch,
|
||||
targetBranch: _initialTargetBranch,
|
||||
open,
|
||||
onOpenChange,
|
||||
onMergeComplete,
|
||||
}: MergeDialogProps) {
|
||||
const [isOpen, setIsOpen] = useState(open ?? false);
|
||||
const [branches, setBranches] = useState<string[]>([]);
|
||||
const [sourceBranch, setSourceBranch] = useState<string>(initialSourceBranch || '');
|
||||
const [isLoadingBranches, setIsLoadingBranches] = useState(false);
|
||||
const [isLoadingPreview, setIsLoadingPreview] = useState(false);
|
||||
const [isMerging, setIsMerging] = useState(false);
|
||||
const [mergePreview, setMergePreview] = useState<MergePreview | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [mergeComplete, setMergeComplete] = useState(false);
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { toast } = useToast();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
useEffect(() => {
|
||||
if (open !== undefined) {
|
||||
setIsOpen(open);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const loadBranches = useCallback(async () => {
|
||||
setIsLoadingBranches(true);
|
||||
try {
|
||||
const localBranches = await git.listBranches({ dir: projectPath });
|
||||
// Filter out current branch from source options
|
||||
const availableBranches = localBranches.filter(b => b !== currentBranch);
|
||||
setBranches(availableBranches);
|
||||
|
||||
// Set default source branch
|
||||
if (availableBranches.length > 0) {
|
||||
setSourceBranch(availableBranches[0]);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to load branches:', err);
|
||||
toast({
|
||||
title: 'Failed to load branches',
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsLoadingBranches(false);
|
||||
}
|
||||
}, [git, projectPath, currentBranch, toast]);
|
||||
|
||||
const loadMergePreview = useCallback(async () => {
|
||||
if (!sourceBranch || !currentBranch) return;
|
||||
|
||||
setIsLoadingPreview(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Get commits that will be merged
|
||||
const sourceCommits = await git.log({ dir: projectPath, ref: sourceBranch, depth: 50 });
|
||||
const targetCommits = await git.log({ dir: projectPath, ref: currentBranch, depth: 50 });
|
||||
|
||||
const targetCommitIds = new Set(targetCommits.map(c => c.oid));
|
||||
const commitsToMerge = sourceCommits.filter(c => !targetCommitIds.has(c.oid));
|
||||
|
||||
// Get changed files
|
||||
const sourceFiles = await git.listFiles({ dir: projectPath, ref: sourceBranch });
|
||||
const targetFiles = await git.listFiles({ dir: projectPath, ref: currentBranch });
|
||||
|
||||
const changedFiles = new Set<string>();
|
||||
for (const file of [...sourceFiles, ...targetFiles]) {
|
||||
try {
|
||||
const sourceBlob = await git.readBlob({
|
||||
dir: projectPath,
|
||||
oid: sourceBranch,
|
||||
filepath: file,
|
||||
}).catch(() => null);
|
||||
|
||||
const targetBlob = await git.readBlob({
|
||||
dir: projectPath,
|
||||
oid: currentBranch,
|
||||
filepath: file,
|
||||
}).catch(() => null);
|
||||
|
||||
if (!sourceBlob || !targetBlob ||
|
||||
Buffer.from(sourceBlob.blob).toString() !== Buffer.from(targetBlob.blob).toString()) {
|
||||
changedFiles.add(file);
|
||||
}
|
||||
} catch {
|
||||
changedFiles.add(file);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if can fast-forward
|
||||
const sourceOid = await git.resolveRef({ dir: projectPath, ref: sourceBranch });
|
||||
const targetOid = await git.resolveRef({ dir: projectPath, ref: currentBranch });
|
||||
|
||||
const canFastForward = await git.isDescendent({
|
||||
dir: projectPath,
|
||||
oid: sourceOid,
|
||||
ancestor: targetOid,
|
||||
}).catch(() => false);
|
||||
|
||||
// Try to detect conflicts (simplified - real detection happens during merge)
|
||||
const conflictingFiles: string[] = [];
|
||||
// For now, we'll set this during actual merge
|
||||
|
||||
setMergePreview({
|
||||
sourceBranch,
|
||||
targetBranch: currentBranch,
|
||||
commitsToMerge: commitsToMerge.map(c => ({
|
||||
oid: c.oid,
|
||||
message: c.commit.message,
|
||||
author: c.commit.author.name,
|
||||
timestamp: c.commit.author.timestamp,
|
||||
})),
|
||||
filesChanged: Array.from(changedFiles),
|
||||
canFastForward,
|
||||
hasConflicts: false,
|
||||
conflictingFiles,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Failed to load merge preview:', err);
|
||||
setError(err instanceof Error ? err.message : 'Unknown error');
|
||||
} finally {
|
||||
setIsLoadingPreview(false);
|
||||
}
|
||||
}, [sourceBranch, currentBranch, git, projectPath]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
loadBranches();
|
||||
}
|
||||
}, [isOpen, loadBranches]);
|
||||
|
||||
useEffect(() => {
|
||||
if (sourceBranch && currentBranch && sourceBranch !== currentBranch) {
|
||||
loadMergePreview();
|
||||
} else {
|
||||
setMergePreview(null);
|
||||
}
|
||||
}, [sourceBranch, currentBranch, loadMergePreview]);
|
||||
|
||||
const performMerge = async () => {
|
||||
if (!sourceBranch || !currentBranch) return;
|
||||
|
||||
setIsMerging(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Check if can fast-forward
|
||||
const sourceOid = await git.resolveRef({ dir: projectPath, ref: sourceBranch });
|
||||
const targetOid = await git.resolveRef({ dir: projectPath, ref: currentBranch });
|
||||
|
||||
const canFastForward = await git.isDescendent({
|
||||
dir: projectPath,
|
||||
oid: sourceOid,
|
||||
ancestor: targetOid,
|
||||
}).catch(() => false);
|
||||
|
||||
if (canFastForward) {
|
||||
// Fast-forward merge: update the current branch to point to source branch commit
|
||||
await git.writeRef({
|
||||
dir: projectPath,
|
||||
ref: `refs/heads/${currentBranch}`,
|
||||
value: sourceOid,
|
||||
force: true,
|
||||
});
|
||||
|
||||
// Update working directory to match the new HEAD
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: currentBranch,
|
||||
force: true,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Fast-forward merge successful',
|
||||
description: `Successfully fast-forwarded ${currentBranch} to ${sourceBranch}`,
|
||||
});
|
||||
} else {
|
||||
// Three-way merge
|
||||
const result = await git.merge({
|
||||
dir: projectPath,
|
||||
ours: currentBranch,
|
||||
theirs: sourceBranch,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
message: `Merge branch '${sourceBranch}' into ${currentBranch}`,
|
||||
});
|
||||
|
||||
if (result.alreadyMerged) {
|
||||
toast({
|
||||
title: 'Already merged',
|
||||
description: 'The branches are already merged',
|
||||
});
|
||||
setMergeComplete(true);
|
||||
onMergeComplete?.();
|
||||
return;
|
||||
}
|
||||
|
||||
// The merge result contains the new tree OID
|
||||
// We need to create a commit with this tree
|
||||
const mergeCommitOid = await git.commit({
|
||||
dir: projectPath,
|
||||
message: `Merge branch '${sourceBranch}' into ${currentBranch}`,
|
||||
parent: [targetOid, sourceOid], // Two parents for merge commit
|
||||
tree: result.tree,
|
||||
});
|
||||
|
||||
console.log('Created merge commit:', mergeCommitOid);
|
||||
|
||||
// Update working directory to match the merge
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: currentBranch,
|
||||
force: true,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Merge successful',
|
||||
description: `Successfully merged ${sourceBranch} into ${currentBranch}`,
|
||||
});
|
||||
}
|
||||
|
||||
setMergeComplete(true);
|
||||
|
||||
// Trigger rebuild
|
||||
setTimeout(() => {
|
||||
const newSearchParams = new URLSearchParams(searchParams);
|
||||
newSearchParams.set('build', '');
|
||||
setSearchParams(newSearchParams);
|
||||
}, 500);
|
||||
|
||||
onMergeComplete?.();
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
|
||||
|
||||
if (errorMessage.includes('conflict') || errorMessage.includes('CONFLICT')) {
|
||||
setError('Merge conflicts detected. Please resolve conflicts manually using the terminal.');
|
||||
} else {
|
||||
setError(errorMessage);
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Merge failed',
|
||||
description: errorMessage,
|
||||
variant: 'destructive',
|
||||
duration: Infinity,
|
||||
});
|
||||
} finally {
|
||||
setIsMerging(false);
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (timestamp: number) => {
|
||||
const date = new Date(timestamp * 1000);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
|
||||
|
||||
if (diffDays === 0) {
|
||||
return 'today';
|
||||
} else if (diffDays === 1) {
|
||||
return 'yesterday';
|
||||
} else if (diffDays < 7) {
|
||||
return `${diffDays} days ago`;
|
||||
} else {
|
||||
return date.toLocaleDateString();
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
setIsOpen(newOpen);
|
||||
onOpenChange?.(newOpen);
|
||||
|
||||
if (!newOpen) {
|
||||
setSourceBranch('');
|
||||
setMergePreview(null);
|
||||
setError(null);
|
||||
setMergeComplete(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!currentBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" className="gap-2">
|
||||
<GitMerge className="h-4 w-4" />
|
||||
Merge Branch
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<GitMerge className="h-5 w-5" />
|
||||
Merge Branch
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Merge changes from another branch into {currentBranch}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{mergeComplete ? (
|
||||
// Success state
|
||||
<div className="py-8 text-center space-y-4">
|
||||
<CheckCircle className="h-16 w-16 text-green-600 mx-auto" />
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-2">Merge Complete!</h3>
|
||||
<p className="text-muted-foreground">
|
||||
Successfully merged {sourceBranch} into {currentBranch}
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => handleOpenChange(false)}>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<ScrollArea className="max-h-[60vh]">
|
||||
<div className="space-y-6 pr-4">
|
||||
{/* Source branch selection */}
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">Source Branch</label>
|
||||
<Select
|
||||
value={sourceBranch}
|
||||
onValueChange={setSourceBranch}
|
||||
disabled={isLoadingBranches || isMerging}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select branch to merge from" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{branches.map((branch) => (
|
||||
<SelectItem key={branch} value={branch}>
|
||||
{branch}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
The branch to merge into {currentBranch}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Merge direction visualization */}
|
||||
{sourceBranch && (
|
||||
<div className="bg-muted/30 rounded-lg p-4">
|
||||
<div className="flex items-center gap-2 justify-center text-sm">
|
||||
<Badge variant="outline" className="font-mono">
|
||||
{sourceBranch}
|
||||
</Badge>
|
||||
<GitMerge className="h-4 w-4 text-muted-foreground" />
|
||||
<Badge variant="default" className="font-mono">
|
||||
{currentBranch}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error alert */}
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Loading preview */}
|
||||
{isLoadingPreview && (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground mr-2" />
|
||||
<span className="text-muted-foreground">Loading merge preview...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Merge preview */}
|
||||
{mergePreview && !isLoadingPreview && (
|
||||
<div className="space-y-4">
|
||||
{/* Stats */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Card>
|
||||
<CardContent className="pt-6 text-center">
|
||||
<div className="text-2xl font-bold text-green-600">
|
||||
{mergePreview.commitsToMerge.length}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-1">
|
||||
Commits to Merge
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="pt-6 text-center">
|
||||
<div className="text-2xl font-bold text-blue-600">
|
||||
{mergePreview.filesChanged.length}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-1">
|
||||
Files Changed
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Fast-forward badge */}
|
||||
{mergePreview.canFastForward && (
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
This merge can be fast-forwarded (no merge commit needed)
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Commits to merge */}
|
||||
{mergePreview.commitsToMerge.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-sm font-medium mb-3">Commits to be merged:</h4>
|
||||
<div className="space-y-2 max-h-60 overflow-y-auto">
|
||||
{mergePreview.commitsToMerge.slice(0, 10).map((commit) => (
|
||||
<div
|
||||
key={commit.oid}
|
||||
className="flex items-start gap-3 p-3 rounded-lg border bg-card"
|
||||
>
|
||||
<GitCommit className="h-4 w-4 text-muted-foreground shrink-0 mt-0.5" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium">
|
||||
{commit.message.split('\n')[0]}
|
||||
</p>
|
||||
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
|
||||
<span>{commit.author}</span>
|
||||
<span>•</span>
|
||||
<span>{formatDate(commit.timestamp)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{mergePreview.commitsToMerge.length > 10 && (
|
||||
<p className="text-xs text-muted-foreground text-center py-2">
|
||||
+ {mergePreview.commitsToMerge.length - 10} more commits
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* No changes */}
|
||||
{mergePreview.commitsToMerge.length === 0 && (
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
No new commits to merge. The branches are already in sync.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Warning about conflicts */}
|
||||
{mergePreview.hasConflicts && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Conflicts detected in {mergePreview.conflictingFiles.length} file(s).
|
||||
You may need to resolve conflicts manually.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)}
|
||||
|
||||
{!mergeComplete && (
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={isMerging}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={performMerge}
|
||||
disabled={
|
||||
isMerging ||
|
||||
isLoadingPreview ||
|
||||
!mergePreview ||
|
||||
mergePreview.commitsToMerge.length === 0
|
||||
}
|
||||
>
|
||||
{isMerging ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Merging...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GitMerge className="h-4 w-4 mr-2" />
|
||||
Merge Branch
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
Loaded 100 of 205 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user