Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
764319223a |
No files matched your search
@@ -1,11 +1,2 @@
|
||||
# GitHub OAuth Configuration
|
||||
VITE_GITHUB_OAUTH_CLIENT_ID="********************"
|
||||
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
|
||||
|
||||
# Netlify OAuth Configuration
|
||||
VITE_NETLIFY_OAUTH_CLIENT_ID="********************"
|
||||
VITE_NETLIFY_OAUTH_CLIENT_SECRET="****************************************"
|
||||
|
||||
# Vercel OAuth Configuration
|
||||
VITE_VERCEL_OAUTH_CLIENT_ID="********************"
|
||||
VITE_VERCEL_OAUTH_CLIENT_SECRET="****************************************"
|
||||
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
|
||||
@@ -12,8 +12,6 @@ dist
|
||||
dist-ssr
|
||||
*.local
|
||||
.ai-history/
|
||||
*.apk
|
||||
*.aab
|
||||
|
||||
# Editor directories and files
|
||||
.idea
|
||||
@@ -32,4 +30,3 @@ dist-ssr
|
||||
.env.*
|
||||
!.env.example
|
||||
.ai/
|
||||
*.keystore
|
||||
@@ -1,4 +1,3 @@
|
||||
{
|
||||
"editor.tabSize": 2,
|
||||
"editor.insertSpaces": true
|
||||
}
|
||||
"editor.tabSize": 2
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
# Shakespeare - AI-Powered App Builder
|
||||
# Shakespeare - AI-Powered Nostr Website Builder
|
||||
|
||||
Shakespeare is a browser-based AI chat application that allows users to build custom web applications through natural language conversation. All operations including AI chat and Git operations are executed in client-side JavaScript, with API keys stored in browser storage. Simply describe what you want to build, and AI will help you create it.
|
||||
Shakespeare is a browser-based AI chat application that allows users to build custom Nostr websites through natural language conversation. All operations including AI chat and Git operations are executed in client-side JavaScript, with API keys stored in browser storage. Simply describe what you want to build, and AI will help you create it.
|
||||
|
||||
### Virtual Filesystem Layout
|
||||
|
||||
|
||||
@@ -1,34 +1,85 @@
|
||||
# Shakespeare 🎭
|
||||
# Shakespeare - AI-Powered Nostr Website Builder
|
||||
|
||||
[](https://shakespeare.diy/clone?url=https://gitlab.com/soapbox-pub/shakespeare.git)
|
||||
|
||||
Shakespeare is an open-source AI app builder that runs entirely in your browser.
|
||||
|
||||
https://shakespeare.diy
|
||||
Shakespeare is an AI chat application that allows users to build custom Nostr websites through natural language conversation. Simply describe what you want to build, and AI will help you create it.
|
||||
|
||||
## Features
|
||||
|
||||
- **Use any AI provider** OpenAI, Anthropic, OpenRouter, xAI, ZAI, Deepseek, and more
|
||||
- **Buy credits anonymously** with Nostr and Lightning ⚡
|
||||
- **Runs entirely in the browser** No backend required
|
||||
- **AI-Powered Development**: Chat with an AI assistant to build your Nostr website
|
||||
- **File Attachments**: Attach files directly to chat messages with structured text parts, visual badges, and deduplication. Supports both file selection and clipboard image pasting
|
||||
- **Project Management**: Create and manage multiple projects with sidebar navigation
|
||||
- **Real-time Editing**: Edit files directly in the browser with syntax highlighting
|
||||
- **File Explorer**: Browse and manage your project files
|
||||
- **Project Preview**: Preview your website as you build it
|
||||
- **Template Cloning**: Start from a pre-configured Nostr template
|
||||
|
||||
## How it Works
|
||||
## Getting Started
|
||||
|
||||
Shakespeare is a React PWA that stores files in IndexedDB with [LightningFS](https://github.com/isomorphic-git/lightning-fs). Your browser connects directly to AI providers and git services (through [isomorphic-git](https://github.com/isomorphic-git/isomorphic-git)) to enable you to build and deploy AI apps entirely from your device.
|
||||
1. **Create a Project**: Enter a description of what you want to build in the prompt textarea
|
||||
2. **Chat with AI**: Use the AI assistant to add features, edit files, and build your website
|
||||
3. **Attach Files**: Click the paperclip icon to attach files or paste images directly from your clipboard - they'll show as "Added file: /path/filename"
|
||||
4. **Edit Code**: Switch to the code view to manually edit files if needed
|
||||
5. **Preview**: View your website in the preview pane
|
||||
|
||||
Shakespeare hosts no backend (except for a couple microservices in the `services/` directory; these are fully configurable within Shakespeare's settings). All your code and configuration is stored in your browser.
|
||||
## Project Structure
|
||||
|
||||
Configure any AI providers and git services you want. Configuration is stored entirely in the browser in localStorage.
|
||||
Each project includes:
|
||||
- React 18 with TypeScript
|
||||
- Vite for building
|
||||
- TailwindCSS for styling
|
||||
- Nostrify for Nostr integration
|
||||
- shadcn/ui components
|
||||
|
||||
You can then push and pull code to syncronize your work across devices.
|
||||
## AI Capabilities
|
||||
|
||||
Shakespeare can work on any type of project. But it is specialized to build React applications in TypeScript, which it compiles in the browser with [esbuild-wasm](https://www.npmjs.com/package/esbuild-wasm) and custom plugins. Any codebase can be worked on, but only compatible projects can be previewed directly in Shakespeare.
|
||||
The AI assistant can:
|
||||
- Read and write project files
|
||||
- Add new components and pages
|
||||
- Configure Nostr functionality
|
||||
- Build the project
|
||||
- Search through files
|
||||
- Provide project structure overview
|
||||
- Add and remove npm packages
|
||||
- Install dependencies and dev dependencies
|
||||
|
||||
## Open Source
|
||||
## Usage
|
||||
|
||||
Shakespeare is proudly Open Source software licensed under the GNU AGPLv3. The purpose of Shakespeare is to provide a free and open platform for building AI applications that respects user privacy and freedom.
|
||||
1. **Homepage**: Enter a project description in the textarea to create new projects, with existing projects listed in the sidebar
|
||||
2. **Project View**: Split-pane interface with AI chat on the left and preview/code on the right
|
||||
3. **File Explorer**: Navigate your project files in the code view
|
||||
4. **File Editor**: Edit files with syntax highlighting and save changes
|
||||
|
||||
## Alternatives
|
||||
## Git Integration
|
||||
|
||||
- [goose](https://github.com/block/goose) - open-source desktop app and cli utilizing your full computer for AI tasks
|
||||
- [bolt.diy](https://github.com/stackblitz-labs/bolt.diy) - similar to Shakespeare, but built on closed-source WebContainers technology
|
||||
Shakespeare includes full Git functionality with credential management:
|
||||
|
||||
### Features
|
||||
- **Version Control**: Full Git repository support with commit history and branch management
|
||||
- **Global Credentials**: Configure Git credentials once and use them across all projects
|
||||
- **Automatic Matching**: Credentials are automatically matched to repository origins
|
||||
- **Popular Providers**: Built-in support for GitHub, GitLab, and custom Git providers
|
||||
- **Secure Storage**: Credentials are stored locally in your browser using IndexedDB
|
||||
|
||||
### Setting Up Git Credentials
|
||||
|
||||
1. **Access Git Settings**: Click the gear icon in any Git dialog or use the Git Settings option
|
||||
2. **Add Provider**: Choose from GitHub, GitLab, or add a custom Git provider
|
||||
3. **Enter Token**: Use your username and personal access token for authentication
|
||||
4. **Automatic Usage**: Credentials are automatically used for push/pull operations in matching repositories
|
||||
|
||||
### Repository Operations
|
||||
|
||||
- **Push/Pull**: Sync changes with remote repositories using configured credentials
|
||||
- **Status Monitoring**: Real-time Git status with file changes and sync information
|
||||
- **Commit History**: View commit history and repository information
|
||||
- **Branch Management**: Work with different branches and track remote changes
|
||||
|
||||
## Development
|
||||
|
||||
Built with:
|
||||
- React 18
|
||||
- TypeScript
|
||||
- Vite
|
||||
- TailwindCSS
|
||||
- shadcn/ui
|
||||
- LightningFS for filesystem
|
||||
- isomorphic-git for template cloning
|
||||
@@ -1,544 +0,0 @@
|
||||
# Unified OAuth System
|
||||
|
||||
Shakespeare implements a unified OAuth 2.0 authentication system that supports multiple providers with a consistent API. This document explains how the system works and how to add new OAuth providers.
|
||||
|
||||
## Architecture
|
||||
|
||||
The OAuth system consists of three main components:
|
||||
|
||||
1. **Generic OAuth Hook** (`useOAuth`) - Core OAuth logic that works with any provider
|
||||
2. **Provider-Specific Hooks** - Thin wrappers that configure the generic hook for specific providers
|
||||
3. **OAuth Callback Pages** - React components that handle the OAuth redirect flow
|
||||
|
||||
### Current Supported Providers
|
||||
|
||||
- **GitHub** - Git repository hosting (with PKCE support)
|
||||
- **Netlify** - Static site deployment
|
||||
- **Vercel** - Static site deployment
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── hooks/
|
||||
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
|
||||
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
|
||||
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
|
||||
│ └── useVercelOAuth.ts # Vercel-specific configuration
|
||||
├── pages/
|
||||
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
|
||||
│ ├── NetlifyOAuth.tsx # Netlify OAuth callback page
|
||||
│ └── VercelOAuth.tsx # Vercel OAuth callback page
|
||||
└── AppRouter.tsx # Routes for OAuth callbacks
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
OAuth credentials are stored in environment variables and loaded from `process.env`:
|
||||
|
||||
```bash
|
||||
# GitHub OAuth Configuration
|
||||
VITE_GITHUB_OAUTH_CLIENT_ID="your_github_client_id"
|
||||
VITE_GITHUB_OAUTH_CLIENT_SECRET="your_github_client_secret"
|
||||
|
||||
# Netlify OAuth Configuration
|
||||
VITE_NETLIFY_OAUTH_CLIENT_ID="your_netlify_client_id"
|
||||
VITE_NETLIFY_OAUTH_CLIENT_SECRET="your_netlify_client_secret"
|
||||
|
||||
# Vercel OAuth Configuration
|
||||
VITE_VERCEL_OAUTH_CLIENT_ID="your_vercel_client_id"
|
||||
VITE_VERCEL_OAUTH_CLIENT_SECRET="your_vercel_client_secret"
|
||||
```
|
||||
|
||||
### Security Note
|
||||
|
||||
**Client secrets are stored in environment variables** and bundled into the client-side JavaScript. This is necessary because the OAuth flow runs entirely in the browser. While this approach is less secure than a traditional server-side OAuth flow, it's acceptable for this use case because:
|
||||
|
||||
1. Shakespeare is a client-side application with no backend
|
||||
2. The OAuth tokens are scoped to specific permissions
|
||||
3. Users can revoke tokens at any time from the provider's settings
|
||||
4. The redirect URIs are validated by the OAuth provider
|
||||
|
||||
For production deployments, consider using a serverless function or backend service to handle the token exchange step, keeping client secrets secure.
|
||||
|
||||
## How It Works
|
||||
|
||||
### 1. Generic OAuth Hook (`useOAuth`)
|
||||
|
||||
The `useOAuth` hook implements the OAuth 2.0 authorization code flow with optional PKCE (Proof Key for Code Exchange) support. It accepts a configuration object and returns methods to initiate and handle the OAuth flow.
|
||||
|
||||
**Configuration Interface:**
|
||||
|
||||
```typescript
|
||||
interface OAuthConfig {
|
||||
provider: 'github' | 'netlify' | 'vercel'; // Provider identifier
|
||||
clientId: string; // OAuth client ID
|
||||
clientSecret: string; // OAuth client secret
|
||||
authorizeUrl: string; // Provider's authorization endpoint
|
||||
tokenUrl: string; // Provider's token exchange endpoint
|
||||
scope?: string; // Requested OAuth scopes (optional)
|
||||
redirectUri: string; // Callback URL after authorization
|
||||
usePKCE?: boolean; // Enable PKCE (default: false)
|
||||
getUserInfo?: ( // Optional function to fetch user info
|
||||
accessToken: string,
|
||||
corsProxy: string
|
||||
) => Promise<{
|
||||
username: string;
|
||||
[key: string]: unknown;
|
||||
}>;
|
||||
}
|
||||
```
|
||||
|
||||
**Returned API:**
|
||||
|
||||
```typescript
|
||||
{
|
||||
isLoading: boolean; // True during token exchange
|
||||
error: string | null; // Error message if OAuth fails
|
||||
isOAuthConfigured: boolean; // True if client ID and secret are set
|
||||
initiateOAuth: () => void; // Start the OAuth flow
|
||||
handleCallback: ( // Handle the OAuth callback
|
||||
code: string,
|
||||
state: string
|
||||
) => Promise<OAuthResult | null>;
|
||||
}
|
||||
```
|
||||
|
||||
### 2. OAuth Flow Steps
|
||||
|
||||
#### Step 1: Initiate OAuth
|
||||
|
||||
When the user clicks "Connect to [Provider]", the `initiateOAuth()` function:
|
||||
|
||||
1. Generates a random `state` parameter for CSRF protection
|
||||
2. Optionally generates PKCE parameters (code verifier and challenge)
|
||||
3. Stores the state and code verifier in localStorage
|
||||
4. Redirects to the provider's authorization page
|
||||
|
||||
```typescript
|
||||
const { initiateOAuth } = useGitHubOAuth();
|
||||
|
||||
// User clicks button
|
||||
<Button onClick={initiateOAuth}>Connect to GitHub</Button>
|
||||
```
|
||||
|
||||
#### Step 2: User Authorizes
|
||||
|
||||
The user is redirected to the provider's authorization page where they:
|
||||
1. Log in to their account (if not already logged in)
|
||||
2. Review the requested permissions
|
||||
3. Approve or deny the authorization request
|
||||
|
||||
#### Step 3: OAuth Callback
|
||||
|
||||
After authorization, the provider redirects back to the callback URL with:
|
||||
- `code` - Authorization code
|
||||
- `state` - The state parameter we sent
|
||||
- `error` (optional) - Error code if authorization failed
|
||||
- `error_description` (optional) - Human-readable error description
|
||||
|
||||
The callback page (e.g., `GitHubOAuth.tsx`) extracts these parameters and calls `handleCallback()`.
|
||||
|
||||
#### Step 4: Token Exchange
|
||||
|
||||
The `handleCallback()` function:
|
||||
|
||||
1. Verifies the `state` parameter matches what we stored
|
||||
2. Retrieves the PKCE code verifier (if PKCE is enabled)
|
||||
3. Exchanges the authorization code for an access token
|
||||
4. Optionally fetches user information using the access token
|
||||
5. Returns an `OAuthResult` object with the token and user data
|
||||
|
||||
```typescript
|
||||
interface OAuthResult {
|
||||
accessToken: string; // OAuth access token
|
||||
username?: string; // User's username/email
|
||||
scopes?: string[]; // Granted OAuth scopes
|
||||
userData?: Record<string, unknown>; // Additional user data
|
||||
}
|
||||
```
|
||||
|
||||
#### Step 5: Store Credentials
|
||||
|
||||
Provider-specific hooks override `handleCallback` to store the credentials appropriately:
|
||||
|
||||
- **GitHub**: Stores in Git settings (for push/pull operations)
|
||||
- **Netlify/Vercel**: Stores in Deploy settings (for deployment operations)
|
||||
|
||||
### 3. PKCE Support
|
||||
|
||||
PKCE (Proof Key for Code Exchange) adds an extra layer of security to the OAuth flow by preventing authorization code interception attacks. It's recommended for public clients like browser-based apps.
|
||||
|
||||
**How PKCE works:**
|
||||
|
||||
1. Generate a random `code_verifier` (cryptographically random string)
|
||||
2. Create a `code_challenge` by hashing the verifier with SHA-256
|
||||
3. Send the `code_challenge` during authorization
|
||||
4. Send the `code_verifier` during token exchange
|
||||
5. The server verifies that the verifier matches the challenge
|
||||
|
||||
**Enabling PKCE:**
|
||||
|
||||
```typescript
|
||||
const config: OAuthConfig = {
|
||||
// ... other config
|
||||
usePKCE: true, // Enable PKCE
|
||||
};
|
||||
```
|
||||
|
||||
**Provider Support:**
|
||||
- ✅ GitHub - Supports PKCE (enabled)
|
||||
- ❌ Netlify - Doesn't support PKCE (disabled)
|
||||
- ❌ Vercel - Doesn't support PKCE (disabled)
|
||||
|
||||
### Scope Parameter
|
||||
|
||||
The `scope` parameter is optional in the OAuth configuration. Some providers (like Netlify) don't use scopes in the authorization request - instead, permissions are configured when you create the OAuth application in the provider's settings.
|
||||
|
||||
**Provider Scope Usage:**
|
||||
- ✅ 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`)
|
||||
|
||||
## Adding a New OAuth Provider
|
||||
|
||||
To add a new OAuth provider, follow these steps:
|
||||
|
||||
### 1. Add Environment Variables
|
||||
|
||||
Add the client ID and secret to `.env.example`:
|
||||
|
||||
```bash
|
||||
# NewProvider OAuth Configuration
|
||||
VITE_NEWPROVIDER_OAUTH_CLIENT_ID="********************"
|
||||
VITE_NEWPROVIDER_OAUTH_CLIENT_SECRET="****************************************"
|
||||
```
|
||||
|
||||
### 2. Create Provider-Specific Hook
|
||||
|
||||
Create a new file `src/hooks/useNewProviderOAuth.ts`:
|
||||
|
||||
```typescript
|
||||
import { useCallback } from 'react';
|
||||
import { useOAuth, type OAuthConfig, type OAuthResult } from './useOAuth';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
|
||||
interface NewProviderUserInfo {
|
||||
id: string;
|
||||
email: string;
|
||||
// ... other user fields
|
||||
}
|
||||
|
||||
export function useNewProviderOAuth() {
|
||||
// Get the context where you want to store credentials
|
||||
// e.g., useDeploySettings() or useGitSettings()
|
||||
const { setProviders, settings } = useDeploySettings();
|
||||
|
||||
const config: OAuthConfig = {
|
||||
provider: 'newprovider',
|
||||
clientId: import.meta.env.VITE_NEWPROVIDER_OAUTH_CLIENT_ID || '',
|
||||
clientSecret: import.meta.env.VITE_NEWPROVIDER_OAUTH_CLIENT_SECRET || '',
|
||||
authorizeUrl: 'https://provider.com/oauth/authorize',
|
||||
tokenUrl: 'https://provider.com/oauth/token',
|
||||
scope: 'read write', // Optional - omit if provider doesn't use scopes
|
||||
redirectUri: window.location.origin + '/oauth/newprovider',
|
||||
usePKCE: false, // Set to true if provider supports PKCE
|
||||
getUserInfo: async (accessToken: string, corsProxy: string) => {
|
||||
const userUrl = proxyUrl(corsProxy, 'https://api.provider.com/user');
|
||||
const userResponse = await fetch(userUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!userResponse.ok) {
|
||||
throw new Error(`Failed to verify token: ${userResponse.statusText}`);
|
||||
}
|
||||
|
||||
const userData: NewProviderUserInfo = await userResponse.json();
|
||||
return {
|
||||
username: userData.email,
|
||||
...userData,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const oauth = useOAuth(config);
|
||||
|
||||
const handleCallbackAndStore = useCallback(async (
|
||||
code: string,
|
||||
state: string
|
||||
): Promise<boolean> => {
|
||||
const result: OAuthResult | null = await oauth.handleCallback(code, state);
|
||||
|
||||
if (!result) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Store the credentials in the appropriate context
|
||||
// This will vary based on what the provider is used for
|
||||
const newProvider = {
|
||||
id: crypto.randomUUID(),
|
||||
name: result.username ? `NewProvider (${result.username})` : 'NewProvider',
|
||||
type: 'newprovider',
|
||||
apiKey: result.accessToken,
|
||||
proxy: true,
|
||||
};
|
||||
|
||||
setProviders([...settings.providers, newProvider]);
|
||||
return true;
|
||||
}, [oauth, setProviders, settings.providers]);
|
||||
|
||||
return {
|
||||
...oauth,
|
||||
handleCallback: handleCallbackAndStore,
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Create OAuth Callback Page
|
||||
|
||||
Create a new file `src/pages/NewProviderOAuth.tsx`:
|
||||
|
||||
```typescript
|
||||
import { useEffect } from 'react';
|
||||
import { useSearchParams, useNavigate } from 'react-router-dom';
|
||||
import { useNewProviderOAuth } from '@/hooks/useNewProviderOAuth';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
export default function NewProviderOAuth() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const { handleCallback } = useNewProviderOAuth();
|
||||
const { toast } = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
const code = searchParams.get('code');
|
||||
const state = searchParams.get('state');
|
||||
const error = searchParams.get('error');
|
||||
const errorDescription = searchParams.get('error_description');
|
||||
const storedState = localStorage.getItem('newprovider_oauth_state');
|
||||
|
||||
if (error) {
|
||||
toast({
|
||||
title: "NewProvider OAuth Error",
|
||||
description: errorDescription || error,
|
||||
variant: "destructive",
|
||||
});
|
||||
navigate('/settings/deploy'); // or appropriate settings page
|
||||
return;
|
||||
}
|
||||
|
||||
if (code && state && storedState) {
|
||||
handleCallback(code, state).then((success) => {
|
||||
if (success) {
|
||||
toast({
|
||||
title: "NewProvider Connected",
|
||||
description: "Successfully connected to NewProvider.",
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: "Connection Failed",
|
||||
description: "Failed to connect to NewProvider. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
navigate('/settings/deploy'); // or appropriate settings page
|
||||
});
|
||||
} else {
|
||||
navigate('/settings/deploy');
|
||||
}
|
||||
}, [searchParams, handleCallback, toast, navigate]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="space-y-6">
|
||||
{/* Provider logo/icon */}
|
||||
<div className="flex justify-center">
|
||||
<svg className="h-12 w-12 text-primary" viewBox="0 0 24 24">
|
||||
{/* Provider icon SVG */}
|
||||
</svg>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-xl font-semibold">Connecting to NewProvider</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Processing your NewProvider authentication...
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex justify-center">
|
||||
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Add Route
|
||||
|
||||
Add the OAuth callback route to `src/AppRouter.tsx`:
|
||||
|
||||
```typescript
|
||||
import NewProviderOAuth from "./pages/NewProviderOAuth";
|
||||
|
||||
// ...
|
||||
|
||||
<Route path="/oauth/newprovider" element={<NewProviderOAuth />} />
|
||||
```
|
||||
|
||||
### 5. Add to UI
|
||||
|
||||
Add the provider to the appropriate settings page (e.g., `DeploySettings.tsx`):
|
||||
|
||||
```typescript
|
||||
import { useNewProviderOAuth } from '@/hooks/useNewProviderOAuth';
|
||||
|
||||
// In component:
|
||||
const newProviderOAuth = useNewProviderOAuth();
|
||||
|
||||
// In PRESET_PROVIDERS array:
|
||||
{
|
||||
id: 'newprovider',
|
||||
type: 'newprovider',
|
||||
name: 'NewProvider',
|
||||
description: 'Deploy to NewProvider',
|
||||
apiKeyLabel: 'Access Token',
|
||||
apiKeyURL: 'https://provider.com/settings/tokens',
|
||||
proxy: true,
|
||||
}
|
||||
|
||||
// In the render logic, add the OAuth hook to the switch:
|
||||
const oauthHook = preset.type === 'netlify' ? netlifyOAuth :
|
||||
preset.type === 'vercel' ? vercelOAuth :
|
||||
preset.type === 'newprovider' ? newProviderOAuth : null;
|
||||
```
|
||||
|
||||
### 6. Register OAuth Application
|
||||
|
||||
Register your OAuth application with the provider:
|
||||
|
||||
1. Go to the provider's developer settings
|
||||
2. Create a new OAuth application
|
||||
3. Set the **redirect URI** to: `https://yourdomain.com/oauth/newprovider`
|
||||
4. Note the **client ID** and **client secret**
|
||||
5. Add them to your `.env` file
|
||||
|
||||
## Testing OAuth Flow
|
||||
|
||||
To test the OAuth flow locally:
|
||||
|
||||
1. **Set up a tunnel** (e.g., ngrok, cloudflared) to expose localhost:
|
||||
```bash
|
||||
npx cloudflared tunnel --url http://localhost:5173
|
||||
```
|
||||
|
||||
2. **Register OAuth app** with the tunnel URL as the redirect URI:
|
||||
```
|
||||
https://your-tunnel-url.trycloudflare.com/oauth/provider
|
||||
```
|
||||
|
||||
3. **Add credentials** to `.env`:
|
||||
```bash
|
||||
VITE_PROVIDER_OAUTH_CLIENT_ID="your_client_id"
|
||||
VITE_PROVIDER_OAUTH_CLIENT_SECRET="your_client_secret"
|
||||
```
|
||||
|
||||
4. **Start the dev server**:
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
5. **Test the flow** by clicking the "Connect to Provider" button
|
||||
|
||||
## Error Handling
|
||||
|
||||
The OAuth system handles several types of errors:
|
||||
|
||||
### User Denies Authorization
|
||||
|
||||
If the user denies authorization, the provider redirects with an `error` parameter:
|
||||
```
|
||||
/oauth/provider?error=access_denied&error_description=User+denied+access
|
||||
```
|
||||
|
||||
The callback page displays an error toast and redirects to settings.
|
||||
|
||||
### Invalid State Parameter
|
||||
|
||||
If the `state` parameter doesn't match what we stored (CSRF attack), the flow is aborted and an error is shown.
|
||||
|
||||
### Token Exchange Failure
|
||||
|
||||
If the token exchange fails (invalid code, expired, etc.), an error is logged and shown to the user.
|
||||
|
||||
### Missing PKCE Verifier
|
||||
|
||||
If PKCE is enabled but the code verifier is missing from localStorage, the flow is aborted.
|
||||
|
||||
## Security Considerations
|
||||
|
||||
1. **State Parameter**: Always used for CSRF protection
|
||||
2. **PKCE**: Used when supported by the provider for additional security
|
||||
3. **HTTPS Only**: OAuth should only be used over HTTPS in production
|
||||
4. **Token Storage**: Tokens are stored in browser storage (localStorage/IndexedDB)
|
||||
5. **Token Revocation**: Users can revoke tokens from the provider's settings
|
||||
6. **Scope Limitation**: Request only the minimum required scopes
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "OAuth client ID not configured"
|
||||
|
||||
The environment variables are not set. Check your `.env` file and ensure the variables are prefixed with `VITE_`.
|
||||
|
||||
### "Invalid OAuth state parameter"
|
||||
|
||||
The state parameter doesn't match. This could be caused by:
|
||||
- Multiple OAuth flows running simultaneously
|
||||
- Browser localStorage being cleared mid-flow
|
||||
- CSRF attack attempt
|
||||
|
||||
### "Failed to verify token"
|
||||
|
||||
The provider's API rejected the access token. This could be caused by:
|
||||
- Incorrect API endpoint URL
|
||||
- Token doesn't have required scopes
|
||||
- Provider API is down
|
||||
|
||||
### Redirect URI Mismatch
|
||||
|
||||
The redirect URI in your OAuth app registration must exactly match the URI in your code:
|
||||
```typescript
|
||||
redirectUri: window.location.origin + '/oauth/provider'
|
||||
```
|
||||
|
||||
For local development with a tunnel, this would be:
|
||||
```
|
||||
https://your-tunnel-url.trycloudflare.com/oauth/provider
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Always use PKCE** when the provider supports it
|
||||
2. **Request minimal scopes** - only what you need
|
||||
3. **Handle errors gracefully** - show user-friendly error messages
|
||||
4. **Clear localStorage** on errors to prevent stuck states
|
||||
5. **Validate tokens** by fetching user info after exchange
|
||||
6. **Store tokens securely** - use appropriate browser storage APIs
|
||||
7. **Provide token revocation** - link to provider's token management page
|
||||
8. **Test error cases** - user denial, network failures, etc.
|
||||
|
||||
## Future Improvements
|
||||
|
||||
Potential enhancements to the OAuth system:
|
||||
|
||||
1. **Token Refresh**: Implement refresh token flow for long-lived sessions
|
||||
2. **Token Expiry**: Track token expiration and prompt for re-authentication
|
||||
3. **Multiple Accounts**: Support multiple accounts per provider
|
||||
4. **Backend Proxy**: Optional backend service for secure token exchange
|
||||
5. **Device Flow**: Support OAuth device flow for CLI tools
|
||||
6. **Biometric Auth**: Integrate with WebAuthn for passwordless OAuth
|
||||
@@ -40,18 +40,11 @@ export default tseslint.config(
|
||||
"ignoreRestSiblings": true,
|
||||
},
|
||||
],
|
||||
"indent": [
|
||||
"warn",
|
||||
2,
|
||||
{ SwitchCase: 1 },
|
||||
],
|
||||
"no-tabs": "warn",
|
||||
"custom/no-placeholder-comments": "error",
|
||||
"no-warning-comments": [
|
||||
"error",
|
||||
{ terms: ["fixme"] },
|
||||
],
|
||||
"no-control-regex": "off", // Allow ANSI escape sequences in regex
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -3,18 +3,13 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||
<title>Shakespeare - Open Source AI Builder</title>
|
||||
<meta name="description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
|
||||
<title>Shakespeare - AI-Powered Nostr Development</title>
|
||||
<meta name="description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:title" content="Shakespeare - Open Source AI Builder">
|
||||
<meta property="og:description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
|
||||
<meta property="og:image" content="https://shakespeare.diy/og-image.png">
|
||||
<meta property="og:title" content="Shakespeare - AI-Powered Nostr Development">
|
||||
<meta property="og:description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<link rel="icon" type="image/png" href="/shakespeare-192x192.png">
|
||||
<link rel="apple-touch-icon" href="/shakespeare-192x192.png" sizes="192x192">
|
||||
<meta name="theme-color" content="#2b0037">
|
||||
<link rel="icon" type="image/png" href="/shakespeare.png">
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -52,8 +52,6 @@
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@unhead/addons": "^2.0.10",
|
||||
"@unhead/react": "^2.0.10",
|
||||
"@webpm/store": "file:../webpm/packages/store",
|
||||
"@webpm/webpm": "file:../webpm/packages/webpm",
|
||||
"buffer": "^6.0.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
@@ -61,19 +59,15 @@
|
||||
"decimal.js": "^10.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"esbuild-wasm": "^0.25.8",
|
||||
"fflate": "^0.8.2",
|
||||
"i18next": "^25.5.2",
|
||||
"ignore": "^7.0.5",
|
||||
"input-otp": "^1.2.4",
|
||||
"isomorphic-git": "^1.32.1",
|
||||
"jsonc-parser": "^3.3.1",
|
||||
"jszip": "^3.10.1",
|
||||
"lucide-react": "^0.525.0",
|
||||
"mime": "^4.1.0",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"openai": "^5.15.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"prismjs": "^1.30.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^18.3.1",
|
||||
"react-day-picker": "^8.10.1",
|
||||
@@ -88,13 +82,10 @@
|
||||
"streamdown": "~1.0.0",
|
||||
"tailwind-merge": "^2.5.2",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"tailwindcss-safe-area": "^0.8.0",
|
||||
"tar-stream": "^3.1.7",
|
||||
"turndown": "^7.2.1",
|
||||
"uri-templates": "^0.2.0",
|
||||
"use-stick-to-bottom": "^1.1.1",
|
||||
"vaul": "^0.9.3",
|
||||
"vite-plugin-node-polyfills": "^0.24.0",
|
||||
"webln": "^0.3.2",
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
@@ -109,7 +100,6 @@
|
||||
"@types/jszip": "^3.4.0",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/path-browserify": "^1.0.3",
|
||||
"@types/prismjs": "^1.26.5",
|
||||
"@types/qrcode": "^1.5.5",
|
||||
"@types/react": "^18.3.1",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
|
||||
@@ -1,70 +1,21 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/web-manifest-combined.json",
|
||||
"name": "Shakespeare - Open Source AI Builder",
|
||||
"name": "Shakespeare - AI-Powered Nostr Development",
|
||||
"short_name": "Shakespeare",
|
||||
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
|
||||
"categories": ["productivity", "devtools"],
|
||||
"id": "/",
|
||||
"scope": "/",
|
||||
"description": "Build custom Nostr websites with AI assistance",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"orientation": "any",
|
||||
"background_color": "#2b0037",
|
||||
"theme_color": "#2b0037",
|
||||
"background_color": "#ffffff",
|
||||
"theme_color": "#000000",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/shakespeare-192x192.png",
|
||||
"src": "/shakespeare.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/shakespeare-512x512.png",
|
||||
"src": "/shakespeare.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "/shakespeare-maskable-192x192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
},
|
||||
{
|
||||
"src": "/shakespeare-maskable-512x512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
}
|
||||
],
|
||||
"screenshots": [
|
||||
{
|
||||
"label": "Home",
|
||||
"src": "/screenshot-mobile-home.png",
|
||||
"sizes": "1179x2556",
|
||||
"type": "image/png",
|
||||
"form_factor": "narrow"
|
||||
},
|
||||
{
|
||||
"label": "Project",
|
||||
"src": "/screenshot-mobile-project.png",
|
||||
"sizes": "1179x2556",
|
||||
"type": "image/png",
|
||||
"form_factor": "narrow"
|
||||
},
|
||||
{
|
||||
"label": "Preview",
|
||||
"src": "/screenshot-mobile-preview.png",
|
||||
"sizes": "1179x2556",
|
||||
"type": "image/png",
|
||||
"form_factor": "narrow"
|
||||
},
|
||||
{
|
||||
"label": "Desktop",
|
||||
"src": "/screenshot-desktop.png",
|
||||
"sizes": "1920x1080",
|
||||
"type": "image/png",
|
||||
"form_factor": "wide"
|
||||
"type": "image/png"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
Before Width: | Height: | Size: 70 KiB |
@@ -1,2 +0,0 @@
|
||||
User-agent: *
|
||||
Allow: /
|
||||
|
Before Width: | Height: | Size: 219 KiB |
|
Before Width: | Height: | Size: 266 KiB |
|
Before Width: | Height: | Size: 321 KiB |
|
Before Width: | Height: | Size: 167 KiB |
|
Before Width: | Height: | Size: 7.9 KiB |
|
Before Width: | Height: | Size: 8.6 KiB |
|
Before Width: | Height: | Size: 4.8 KiB |
|
Before Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 18 KiB |
@@ -1,16 +0,0 @@
|
||||
// Shakespeare Service Worker
|
||||
// Simple passthrough fetch handler
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
console.log('[ServiceWorker] Install');
|
||||
self.skipWaiting();
|
||||
});
|
||||
|
||||
self.addEventListener('activate', (event) => {
|
||||
console.log('[ServiceWorker] Activate');
|
||||
event.waitUntil(self.clients.claim());
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', (event) => {
|
||||
// Passthrough: just fetch the request normally
|
||||
});
|
||||
@@ -1,3 +0,0 @@
|
||||
# Shakespeare Services
|
||||
|
||||
This directory contains additional microservices that can be optionally deployed alongside Shakespeare to host a complete Shakespeare instance.
|
||||
@@ -1,26 +0,0 @@
|
||||
export default {
|
||||
async fetch(request) {
|
||||
const url = new URL(request.url);
|
||||
|
||||
if (url.pathname === "/") {
|
||||
return Response.redirect("https://shakespeare.diy", 302);
|
||||
}
|
||||
|
||||
url.hostname = "esm.sh";
|
||||
|
||||
// Cache response via Cloudflare
|
||||
const response = await fetch(url, {
|
||||
cf: { cacheEverything: true }
|
||||
});
|
||||
|
||||
const headers = new Headers(response.headers);
|
||||
headers.set("Cache-Control", "public, max-age=86400, immutable");
|
||||
headers.set("Access-Control-Allow-Origin", "*");
|
||||
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,11 +1,8 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { test, expect } from 'vitest';
|
||||
import { test } from 'vitest';
|
||||
|
||||
import App from './App';
|
||||
|
||||
test('App', () => {
|
||||
const { container } = render(<App />);
|
||||
|
||||
// Basic smoke test to ensure App renders without crashing
|
||||
expect(container).toBeInTheDocument();
|
||||
render(<App />);
|
||||
})
|
||||
@@ -14,13 +14,10 @@ import { AppProvider } from '@/components/AppProvider';
|
||||
import { AppConfig } from '@/contexts/AppContext';
|
||||
import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||
import { DeploySettingsProvider } from '@/components/DeploySettingsProvider';
|
||||
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
|
||||
import { DynamicFavicon } from '@/components/DynamicFavicon';
|
||||
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
@@ -42,19 +39,12 @@ const queryClient = new QueryClient({
|
||||
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "system",
|
||||
relayUrl: "wss://relay.ditto.pub",
|
||||
projectTemplate: "https://gitlab.com/soapbox-pub/mkstack.git",
|
||||
esmUrl: "https://esm.shakespeare.diy",
|
||||
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
|
||||
faviconUrl: "https://external-content.duckduckgo.com/ip3/{hostname}.ico",
|
||||
previewDomain: "local-shakespeare.dev",
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
|
||||
ngitServers: ["git.shakespeare.diy", "relay.ngit.dev"],
|
||||
relayUrl: "wss://relay.primal.net",
|
||||
deployServer: "shakespeare.wtf",
|
||||
};
|
||||
|
||||
const presetRelays = [
|
||||
{ url: 'wss://relay.ditto.pub', name: 'Ditto' },
|
||||
{ url: 'wss://ditto.pub/relay', name: 'Ditto' },
|
||||
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
|
||||
{ url: 'wss://relay.damus.io', name: 'Damus' },
|
||||
{ url: 'wss://relay.primal.net', name: 'Primal' },
|
||||
@@ -83,27 +73,22 @@ export function App() {
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||
<FSProvider fs={fs}>
|
||||
<FSCleanupHandler />
|
||||
<ConsoleErrorProvider>
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<DeploySettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<DynamicFavicon />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</DeploySettingsProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</ConsoleErrorProvider>
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { BrowserRouter, Route, Routes } from "react-router-dom";
|
||||
import { ScrollToTop } from "./components/ScrollToTop";
|
||||
import { SessionMonitor } from "./components/SessionMonitor";
|
||||
import { URLFragmentHandler } from "./components/URLFragmentHandler";
|
||||
|
||||
import Index from "./pages/Index";
|
||||
import Clone from "./pages/Clone";
|
||||
@@ -10,14 +9,10 @@ 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 SystemSettings from "./pages/SystemSettings";
|
||||
import StorageSettings from "./pages/StorageSettings";
|
||||
import DataSettings from "./pages/DataSettings";
|
||||
import AboutSettings from "./pages/AboutSettings";
|
||||
|
||||
import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import NetlifyOAuth from "./pages/NetlifyOAuth";
|
||||
import VercelOAuth from "./pages/VercelOAuth";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { ProjectView } from "./pages/ProjectView";
|
||||
@@ -28,22 +23,17 @@ export function AppRouter() {
|
||||
<BrowserRouter>
|
||||
<ScrollToTop />
|
||||
<SessionMonitor />
|
||||
<URLFragmentHandler />
|
||||
<Routes>
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/clone" element={<Clone />} />
|
||||
<Route path="/oauth/github" element={<GitHubOAuth />} />
|
||||
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
||||
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
||||
<Route path="/settings" element={<SettingsLayout />}>
|
||||
<Route index element={<Settings />} />
|
||||
<Route path="preferences" element={<Preferences />} />
|
||||
<Route path="nostr" element={<NostrSettings />} />
|
||||
<Route path="ai" element={<AISettings />} />
|
||||
<Route path="git" element={<GitSettings />} />
|
||||
<Route path="deploy" element={<DeploySettings />} />
|
||||
<Route path="system" element={<SystemSettings />} />
|
||||
<Route path="storage" element={<StorageSettings />} />
|
||||
<Route path="data" element={<DataSettings />} />
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
</Route>
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
|
||||
@@ -6,7 +6,6 @@ import { cn } from '@/lib/utils';
|
||||
import { UserMessage } from '@/components/UserMessage';
|
||||
import OpenAI from 'openai';
|
||||
import { useTheme } from '@/hooks/useTheme';
|
||||
import { isEmptyMessage } from '@/lib/isEmptyMessage';
|
||||
|
||||
// Type guard to check if message has reasoning content
|
||||
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
|
||||
@@ -70,8 +69,8 @@ export const AIMessageItem = memo(({
|
||||
case 'text_editor_view': {
|
||||
const title = args.path
|
||||
? (args.start_line || args.end_line
|
||||
? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})`
|
||||
: `Viewed ${args.path}`)
|
||||
? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})`
|
||||
: `Viewed ${args.path}`)
|
||||
: 'Viewed File';
|
||||
return { icon: Eye, title };
|
||||
}
|
||||
@@ -300,12 +299,8 @@ export const AIMessageItem = memo(({
|
||||
);
|
||||
}
|
||||
|
||||
if (message.role !== 'assistant') {
|
||||
return null; // Only render assistant and user messages
|
||||
}
|
||||
|
||||
// If the message is empty (no content or reasoning), render nothing
|
||||
if (isEmptyMessage({ ...message, tool_calls: [] })) {
|
||||
// If there's no reasoning content and the main content is empty, render nothing
|
||||
if (!hasReasoningContent(message) && !getContent().trim()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -182,4 +182,36 @@ describe('AISettingsProvider', () => {
|
||||
|
||||
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-models'] });
|
||||
});
|
||||
|
||||
it('should not invalidate provider-models query when updateSettings is called without providers', async () => {
|
||||
// Mock the QueryClient.invalidateQueries method
|
||||
const mockInvalidateQueries = vi.fn();
|
||||
|
||||
// Create a custom TestApp that mocks the query client
|
||||
const MockedTestApp = ({ children }: { children: React.ReactNode }) => {
|
||||
const queryClient = useQueryClient();
|
||||
vi.spyOn(queryClient, 'invalidateQueries').mockImplementation(mockInvalidateQueries);
|
||||
return <>{children}</>;
|
||||
};
|
||||
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => (
|
||||
<TestApp>
|
||||
<MockedTestApp>{children}</MockedTestApp>
|
||||
</TestApp>
|
||||
),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.updateSettings({
|
||||
recentlyUsedModels: ['test-model']
|
||||
});
|
||||
});
|
||||
|
||||
expect(mockInvalidateQueries).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -4,8 +4,10 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
|
||||
// import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
import { getShakespeareProvider } from '@/lib/aiProviderPresets';
|
||||
// import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
|
||||
interface Act1DialogProps {
|
||||
open: boolean;
|
||||
@@ -14,12 +16,42 @@ interface Act1DialogProps {
|
||||
|
||||
type DialogStep = 'welcome' | 'migration' | 'credits' | 'conclusion';
|
||||
|
||||
const SHAKESPEARE_PROVIDER = {
|
||||
id: "shakespeare",
|
||||
baseURL: "https://ai.shakespeare.diy/v1",
|
||||
nostr: true,
|
||||
};
|
||||
|
||||
// const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack';
|
||||
|
||||
export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
|
||||
const [step, setStep] = useState<DialogStep>('welcome');
|
||||
const { data: creditsData } = useAICredits(getShakespeareProvider());
|
||||
// const { setProvider, updateSettings } = useAISettings();
|
||||
|
||||
// // Get the selectedNSPAddr from localStorage
|
||||
// const [selectedNSPAddr] = useLocalStorage<string | null>('selectedNSPAddr', null);
|
||||
|
||||
// Get user's credits
|
||||
const { data: creditsData } = useAICredits(SHAKESPEARE_PROVIDER);
|
||||
|
||||
const handleGetStarted = async () => {
|
||||
try {
|
||||
// // Add Shakespeare provider to their config
|
||||
// setProvider(SHAKESPEARE_PROVIDER);
|
||||
|
||||
// // Configure recently used models based on credits or NSP
|
||||
// const hasCredits = creditsData?.amount && creditsData.amount > 0;
|
||||
// const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR;
|
||||
|
||||
// if (hasCredits || hasMKStackNSP) {
|
||||
// // User has credits or MKStack NSP - set to shakespeare model
|
||||
// updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] });
|
||||
// } else {
|
||||
// // No credits - set to tybalt model (free)
|
||||
// updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] });
|
||||
// }
|
||||
|
||||
// Move to migration step
|
||||
setStep('migration');
|
||||
} catch (error) {
|
||||
console.error('Failed to configure Shakespeare provider:', error);
|
||||
@@ -237,21 +269,36 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
|
||||
|
||||
<Card className="max-w-md mx-auto">
|
||||
<CardContent className="pt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<div className="space-y-2">
|
||||
<div className="text-3xl font-bold text-green-600 dark:text-green-400">
|
||||
${(creditsData?.amount ?? 0).toFixed(2)}
|
||||
{creditsData?.amount && creditsData.amount > 0 ? (
|
||||
<div className="text-center space-y-4">
|
||||
<div className="space-y-2">
|
||||
<div className="text-3xl font-bold text-green-600 dark:text-green-400">
|
||||
${creditsData.amount.toFixed(2)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Available credits
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
|
||||
<p className="text-sm text-green-800 dark:text-green-200">
|
||||
✅ You're all set! We've configured the premium Shakespeare model for you.
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Available credits
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
|
||||
<p className="text-sm text-green-800 dark:text-green-200">
|
||||
✅ You're all set! We've configured the premium Shakespeare model for you.
|
||||
</p>
|
||||
) : (
|
||||
<div className="text-center space-y-4">
|
||||
<div className="space-y-2">
|
||||
<div className="text-2xl">🆓</div>
|
||||
<p className="font-medium">Free Access</p>
|
||||
</div>
|
||||
<div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
|
||||
<p className="text-sm text-blue-800 dark:text-blue-200">
|
||||
You can continue using Shakespeare for free with the Tybalt model.
|
||||
It's perfect for learning and building amazing projects!
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -12,11 +12,9 @@ import {
|
||||
MessageSquarePlus,
|
||||
History,
|
||||
Folder,
|
||||
Rocket,
|
||||
} from 'lucide-react';
|
||||
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
|
||||
import { GitDialog } from '@/components/GitDialog';
|
||||
import { DeployDialog } from '@/components/DeployDialog';
|
||||
|
||||
interface ActionsMenuProps {
|
||||
projectId: string;
|
||||
@@ -31,7 +29,7 @@ interface ActionsMenuProps {
|
||||
|
||||
export function ActionsMenu({
|
||||
projectId,
|
||||
projectName,
|
||||
projectName: _projectName,
|
||||
onNewChat,
|
||||
onProjectDetails,
|
||||
isLoading = false,
|
||||
@@ -41,7 +39,6 @@ export function ActionsMenu({
|
||||
}: ActionsMenuProps) {
|
||||
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
|
||||
const [gitDialogOpen, setGitDialogOpen] = useState(false);
|
||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||
|
||||
const isAnyLoading = isLoading || isBuildLoading;
|
||||
|
||||
@@ -89,15 +86,6 @@ export function ActionsMenu({
|
||||
Repository
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setDeployDialogOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<Rocket className="h-4 w-4" />
|
||||
Deploy
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onProjectDetails}
|
||||
disabled={isAnyLoading}
|
||||
@@ -124,12 +112,6 @@ export function ActionsMenu({
|
||||
onOpenChange={setGitHistoryOpen}
|
||||
/>
|
||||
|
||||
<DeployDialog
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
open={deployDialogOpen}
|
||||
onOpenChange={setDeployDialogOpen}
|
||||
/>
|
||||
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
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 type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
describe('AddProviderDialog', () => {
|
||||
const mockProvider: AIProvider = {
|
||||
id: 'test-provider',
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'sk-test-key-123',
|
||||
};
|
||||
|
||||
it('renders new provider dialog', () => {
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</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();
|
||||
});
|
||||
|
||||
it('shows add provider button for new provider', () => {
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// No cancel button, only add provider button
|
||||
expect(screen.queryByRole('button', { name: /cancel/i })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /add provider/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onOpenChange when add provider is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const addButton = screen.getByRole('button', { name: /add provider/i });
|
||||
await user.click(addButton);
|
||||
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it('does not display provider details for new provider', () => {
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Provider details (API key, base URL, etc.) are not displayed for new providers
|
||||
expect(screen.queryByText('••••••••')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('sk-test-key-123')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('https://api.test.com/v1')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays provider name from presets when available', () => {
|
||||
const onOpenChange = vi.fn();
|
||||
// Use a provider that exists in presets
|
||||
const openrouterProvider: AIProvider = {
|
||||
id: 'openrouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'sk-test-123',
|
||||
};
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={openrouterProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show the preset name "OpenRouter" instead of the id
|
||||
expect(screen.getByText(/Add OpenRouter to your configuration/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses provider id as fallback name when not in presets', () => {
|
||||
const onOpenChange = vi.fn();
|
||||
const customProvider: AIProvider = {
|
||||
id: 'my-custom-provider',
|
||||
baseURL: 'https://api.custom.com/v1',
|
||||
};
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<AddProviderDialog
|
||||
open={true}
|
||||
onOpenChange={onOpenChange}
|
||||
provider={customProvider}
|
||||
/>
|
||||
</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();
|
||||
});
|
||||
});
|
||||
@@ -1,179 +0,0 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { Check, Sparkles, ArrowRight, AlertCircle } from 'lucide-react';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface AddProviderDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
provider: AIProvider;
|
||||
}
|
||||
|
||||
export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderDialogProps) {
|
||||
const scrollableContentRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { settings, setProvider } = useAISettings();
|
||||
|
||||
// Check if provider already exists and if it's identical
|
||||
const existingProvider = settings.providers.find(p => p.id === provider.id);
|
||||
const isIdentical = existingProvider &&
|
||||
existingProvider.baseURL === provider.baseURL &&
|
||||
existingProvider.apiKey === provider.apiKey &&
|
||||
existingProvider.nostr === provider.nostr &&
|
||||
existingProvider.proxy === provider.proxy;
|
||||
|
||||
// Get provider name from presets or fallback to id
|
||||
const getProviderName = () => {
|
||||
const preset = AI_PROVIDER_PRESETS.find(
|
||||
p => p.id === provider.id && p.baseURL === provider.baseURL
|
||||
);
|
||||
return preset?.name || provider.id;
|
||||
};
|
||||
|
||||
const providerName = getProviderName();
|
||||
|
||||
const handleAddProvider = () => {
|
||||
setProvider(provider);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
// Scroll to top when dialog opens
|
||||
useEffect(() => {
|
||||
if (open && scrollableContentRef.current) {
|
||||
scrollableContentRef.current.scrollTop = 0;
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl h-dvh-safe sm:h-auto sm:max-h-[90vh] flex flex-col">
|
||||
<DialogHeader className="flex-shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<span className="text-xl">Add Provider</span>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div ref={scrollableContentRef} className="flex-1 overflow-y-auto min-h-0">
|
||||
<div className="space-y-6 py-4">
|
||||
{isIdentical ? (
|
||||
// Provider already exists with identical configuration
|
||||
<div className="text-center space-y-6">
|
||||
<div className="mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
|
||||
<Check className="h-8 w-8 text-primary" />
|
||||
</div>
|
||||
<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.
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => onOpenChange(false)} className="gap-2">
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
) : existingProvider ? (
|
||||
// Provider exists but with different configuration
|
||||
<div className="space-y-6">
|
||||
<div className="mx-auto w-16 h-16 rounded-full bg-yellow-500/10 flex items-center justify-center">
|
||||
<AlertCircle className="h-8 w-8 text-yellow-500" />
|
||||
</div>
|
||||
<div className="text-center space-y-2">
|
||||
<h2 className="text-2xl font-bold">Provider Already Exists</h2>
|
||||
<p className="text-muted-foreground max-w-md mx-auto">
|
||||
A provider with this ID already exists but with different settings. Would you like to overwrite it?
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-2xl mx-auto">
|
||||
<div className="space-y-2 p-4 rounded-lg border">
|
||||
<h3 className="font-semibold text-sm">Current Settings</h3>
|
||||
<div className="text-xs text-muted-foreground space-y-1">
|
||||
<div>
|
||||
<span className="font-medium">Base URL:</span>
|
||||
<div className="font-mono break-all">{existingProvider.baseURL}</div>
|
||||
</div>
|
||||
{existingProvider.apiKey && (
|
||||
<div>
|
||||
<span className="font-medium">API Key:</span>
|
||||
<div className="font-mono">••••••••</div>
|
||||
</div>
|
||||
)}
|
||||
{existingProvider.nostr && (
|
||||
<div>
|
||||
<span className="font-medium">Nostr Auth:</span> Enabled
|
||||
</div>
|
||||
)}
|
||||
{existingProvider.proxy && (
|
||||
<div>
|
||||
<span className="font-medium">Proxy:</span> Enabled
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 p-4 rounded-lg border border-primary">
|
||||
<h3 className="font-semibold text-sm">New Settings</h3>
|
||||
<div className="text-xs text-muted-foreground space-y-1">
|
||||
<div>
|
||||
<span className="font-medium">Base URL:</span>
|
||||
<div className="font-mono break-all">{provider.baseURL}</div>
|
||||
</div>
|
||||
{provider.apiKey && (
|
||||
<div>
|
||||
<span className="font-medium">API Key:</span>
|
||||
<div className="font-mono">••••••••</div>
|
||||
</div>
|
||||
)}
|
||||
{provider.nostr && (
|
||||
<div>
|
||||
<span className="font-medium">Nostr Auth:</span> Enabled
|
||||
</div>
|
||||
)}
|
||||
{provider.proxy && (
|
||||
<div>
|
||||
<span className="font-medium">Proxy:</span> Enabled
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center gap-3">
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleAddProvider} className="gap-2">
|
||||
Overwrite Provider
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
// New provider
|
||||
<div className="space-y-6">
|
||||
<div className="mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
|
||||
<Sparkles className="h-8 w-8 text-primary" />
|
||||
</div>
|
||||
<div className="text-center space-y-2">
|
||||
<h2 className="text-2xl font-bold">{providerName}</h2>
|
||||
<p className="text-muted-foreground max-w-md mx-auto">
|
||||
Add {providerName} to your configuration?
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button onClick={handleAddProvider}>
|
||||
Add Provider
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -72,22 +72,20 @@ export function AppLayout({
|
||||
return (
|
||||
<div className="min-h-dvh bg-gradient-to-br from-primary/5 to-accent/5">
|
||||
{/* Mobile Header */}
|
||||
<header className="bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur pt-safe">
|
||||
<div className="h-12 px-4 py-3 flex items-center justify-between border-b">
|
||||
<div className="flex items-center space-x-2">
|
||||
{showSidebar && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
|
||||
aria-label="Toggle sidebar"
|
||||
>
|
||||
<Menu className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{headerContent}
|
||||
<header className="h-12 border-b bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur px-4 py-3 flex items-center justify-between">
|
||||
<div className="flex items-center space-x-2">
|
||||
{showSidebar && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
|
||||
aria-label="Toggle sidebar"
|
||||
>
|
||||
<Menu className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{headerContent}
|
||||
</header>
|
||||
|
||||
{/* Mobile Sidebar Overlay - show if showSidebar is true and sidebar is visible */}
|
||||
|
||||
@@ -15,19 +15,12 @@ interface AppProviderProps {
|
||||
}
|
||||
|
||||
// Zod schema for AppConfig validation
|
||||
const AppConfigSchema = z.object({
|
||||
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
|
||||
theme: z.enum(['dark', 'light', 'system']),
|
||||
relayUrl: z.string().url(),
|
||||
projectTemplate: z.string().url(),
|
||||
esmUrl: z.string().url(),
|
||||
corsProxy: z.string().url(),
|
||||
faviconUrl: z.string().url(),
|
||||
previewDomain: z.string().min(1),
|
||||
language: z.string(),
|
||||
showcaseEnabled: z.boolean(),
|
||||
showcaseModerator: z.string(),
|
||||
ngitServers: z.array(z.string()),
|
||||
}) satisfies z.ZodType<AppConfig>;
|
||||
deployServer: z.string().min(1),
|
||||
language: z.string().optional(),
|
||||
});
|
||||
|
||||
export function AppProvider(props: AppProviderProps) {
|
||||
const {
|
||||
@@ -38,25 +31,23 @@ export function AppProvider(props: AppProviderProps) {
|
||||
} = props;
|
||||
|
||||
// App configuration state with localStorage persistence
|
||||
const [rawConfig, setConfig] = useLocalStorage<Partial<AppConfig>>(
|
||||
const [config, setConfig] = useLocalStorage<AppConfig>(
|
||||
storageKey,
|
||||
{},
|
||||
defaultConfig,
|
||||
{
|
||||
serialize: JSON.stringify,
|
||||
deserialize: (value: string) => {
|
||||
const parsed = JSON.parse(value);
|
||||
return AppConfigSchema.partial().parse(parsed);
|
||||
return AppConfigSchema.parse(parsed);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Generic config updater with callback pattern
|
||||
const updateConfig = (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => {
|
||||
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
|
||||
setConfig(updater);
|
||||
};
|
||||
|
||||
const config = { ...defaultConfig, ...rawConfig };
|
||||
|
||||
const appContextValue: AppContextType = {
|
||||
config,
|
||||
updateConfig,
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
import React, { useState, useMemo } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useAppSubmissions } from "@/hooks/useAppSubmissions";
|
||||
import { AppShowcaseCard } from "@/components/AppShowcaseCard";
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from "@/components/ui/collapsible";
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { shuffleArray } from "@/lib/utils";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { RelaySelector } from "@/components/RelaySelector";
|
||||
import { useAppContext } from "@/hooks/useAppContext";
|
||||
|
||||
export function AppShowcase() {
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
const { data: submissions = [], isLoading } = useAppSubmissions();
|
||||
const [showAllApps, setShowAllApps] = useState(false);
|
||||
|
||||
// Get moderator hex from config
|
||||
const MODERATOR_HEX = useMemo(() => {
|
||||
try {
|
||||
const decoded = nip19.decode(config.showcaseModerator);
|
||||
return decoded.type === 'npub' ? decoded.data : '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}, [config.showcaseModerator]);
|
||||
const isModerator = user?.pubkey === MODERATOR_HEX;
|
||||
|
||||
// Filter and shuffle submissions - memoized with stable dependency
|
||||
const { templateApps, halloweenApps, 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'));
|
||||
|
||||
// Get Halloween Hackathon 2025 apps that are featured (for main showcase)
|
||||
const halloween = shuffleArray(nonTemplateSubmissions.filter(app =>
|
||||
app.appTags.includes('Halloween Hackathon 2025') && app.isFeatured
|
||||
));
|
||||
|
||||
// Filter out Halloween Hackathon 2025 apps from other sections (unless featured, they go in Halloween section)
|
||||
const nonHalloweenSubmissions = nonTemplateSubmissions.filter(app =>
|
||||
!app.appTags.includes('Halloween Hackathon 2025')
|
||||
);
|
||||
|
||||
// Shuffle featured and approved apps for random display order
|
||||
const featured = shuffleArray(nonHalloweenSubmissions.filter(app => app.isFeatured));
|
||||
const approved = shuffleArray(nonHalloweenSubmissions.filter(app => app.isApproved && !app.isFeatured));
|
||||
|
||||
return {
|
||||
templateApps: templates,
|
||||
halloweenApps: halloween,
|
||||
featuredApps: featured,
|
||||
approvedApps: approved,
|
||||
};
|
||||
}, [submissions]); // Only depend on submissions, not intermediate filtered arrays
|
||||
|
||||
// Don't show showcase if disabled in settings
|
||||
if (!config.showcaseEnabled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Don't show showcase if no apps exist
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="mt-16 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Card key={i} className="h-full flex flex-col">
|
||||
<Skeleton className="aspect-video rounded-t-lg" />
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<Skeleton className="w-12 h-12 rounded-lg" />
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-32" />
|
||||
<Skeleton className="h-3 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2 mb-4">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-4/5" />
|
||||
</div>
|
||||
<div className="flex gap-1 mb-4">
|
||||
<Skeleton className="h-5 w-16" />
|
||||
<Skeleton className="h-5 w-20" />
|
||||
</div>
|
||||
<div className="mt-auto flex gap-2">
|
||||
<Skeleton className="h-6 flex-1" />
|
||||
<Skeleton className="h-8 w-8" />
|
||||
<Skeleton className="h-8 w-8" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!submissions.length) {
|
||||
return (
|
||||
<div className="mt-16 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="max-w-sm mx-auto space-y-6">
|
||||
<p className="text-muted-foreground">
|
||||
No apps found. Try another relay?
|
||||
</p>
|
||||
<RelaySelector className="w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-16 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||
{/* Apps Grid */}
|
||||
<div className="space-y-12">
|
||||
{/* Featured Apps */}
|
||||
{featuredApps.length > 0 && (
|
||||
<div>
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-8 h-8 bg-yellow-100 rounded-lg flex items-center justify-center">
|
||||
<span className="text-sm">⭐</span>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold text-foreground">Featured Apps</h3>
|
||||
<p className="text-sm text-muted-foreground">Handpicked applications showcasing the best of our community</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{featuredApps.slice(0, 6).map((app) => (
|
||||
<AppShowcaseCard
|
||||
key={app.id}
|
||||
app={app}
|
||||
showModerationControls={isModerator}
|
||||
hideApprovalStatus={true}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Halloween Hackathon 2025 Apps */}
|
||||
{halloweenApps.length > 0 && (
|
||||
<div>
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-8 h-8 bg-orange-100 rounded-lg flex items-center justify-center">
|
||||
<span className="text-sm">🎃</span>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold text-foreground">Halloween Hackathon 2025</h3>
|
||||
<p className="text-sm text-muted-foreground">Featured spooky creations from our Halloween hackathon</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{halloweenApps.slice(0, 6).map((app) => (
|
||||
<AppShowcaseCard
|
||||
key={app.id}
|
||||
app={app}
|
||||
showModerationControls={isModerator}
|
||||
hideApprovalStatus={true}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Templates Section */}
|
||||
{templateApps.length > 0 && (
|
||||
<div>
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-8 h-8 bg-purple-100 rounded-lg flex items-center justify-center">
|
||||
<span className="text-sm">📋</span>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-bold text-foreground">Templates</h3>
|
||||
<p className="text-sm text-muted-foreground">Ready-to-use templates to kickstart your project</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{templateApps.slice(0, 6).map((app) => (
|
||||
<AppShowcaseCard
|
||||
key={app.id}
|
||||
app={app}
|
||||
showModerationControls={isModerator}
|
||||
hideApprovalStatus={true}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* More Apps (Approved) - Collapsible */}
|
||||
{approvedApps.length > 0 && (
|
||||
<div>
|
||||
<Collapsible open={showAllApps} onOpenChange={setShowAllApps}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button variant="ghost" className="p-0 h-auto mb-6 hover:bg-transparent">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
|
||||
<span className="text-sm">📱</span>
|
||||
</div>
|
||||
<div className="text-left">
|
||||
<h3 className="text-xl font-bold text-foreground">
|
||||
More Apps ({approvedApps.length})
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{showAllApps ? 'Click to collapse' : 'Click to view more community apps'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{approvedApps.map((app) => (
|
||||
<AppShowcaseCard
|
||||
key={app.id}
|
||||
app={app}
|
||||
showModerationControls={isModerator}
|
||||
hideApprovalStatus={true}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,589 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import {
|
||||
ExternalLink,
|
||||
Edit,
|
||||
Star,
|
||||
StarOff,
|
||||
Eye,
|
||||
EyeOff,
|
||||
MoreVertical,
|
||||
CheckCircle,
|
||||
XCircle,
|
||||
User,
|
||||
Home,
|
||||
Contact
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import type { AppSubmission } from '@/hooks/useAppSubmissions';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
interface AppShowcaseCardProps {
|
||||
app: AppSubmission;
|
||||
onEdit?: (app: AppSubmission) => void;
|
||||
showModerationControls?: boolean;
|
||||
hideApprovalStatus?: boolean; // Hide pending/approval badges
|
||||
}
|
||||
|
||||
export function AppShowcaseCard({ app, onEdit, showModerationControls, hideApprovalStatus: _hideApprovalStatus }: AppShowcaseCardProps) {
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
const { mutate: publishEvent, isPending } = useNostrPublish();
|
||||
const queryClient = useQueryClient();
|
||||
const [imageError, setImageError] = useState(false);
|
||||
const { toast } = useToast();
|
||||
|
||||
// Get author pubkey from authorNpub field
|
||||
const authorPubkey = React.useMemo(() => {
|
||||
if (!app.authorNpub) return app.pubkey; // Fallback to event pubkey
|
||||
|
||||
try {
|
||||
// If it's already a hex key, use it directly
|
||||
if (app.authorNpub.length === 64 && /^[0-9a-f]+$/i.test(app.authorNpub)) {
|
||||
return app.authorNpub;
|
||||
}
|
||||
|
||||
// Otherwise try to decode as npub
|
||||
const decoded = nip19.decode(app.authorNpub);
|
||||
return decoded.type === 'npub' ? decoded.data : app.pubkey;
|
||||
} catch {
|
||||
return app.pubkey; // Fallback to event pubkey if decode fails
|
||||
}
|
||||
}, [app.authorNpub, app.pubkey]);
|
||||
|
||||
const { data: authorData } = useAuthor(authorPubkey);
|
||||
const isOwner = user?.pubkey === app.pubkey;
|
||||
const MODERATOR_NPUB = 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc';
|
||||
const MODERATOR_HEX = (() => {
|
||||
try {
|
||||
const decoded = nip19.decode(MODERATOR_NPUB);
|
||||
return decoded.type === 'npub' ? decoded.data : '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
})();
|
||||
const isModerator = user?.pubkey === MODERATOR_HEX;
|
||||
|
||||
// Check if this is a Halloween submission by looking for Halloween tags
|
||||
const isHalloweenSubmission = app.appTags.includes('Halloween Hackathon 2025');
|
||||
|
||||
// Get contact info from Halloween submissions (these have lightning/email tags)
|
||||
const getContactInfo = () => {
|
||||
if (!isHalloweenSubmission) return null;
|
||||
|
||||
// Look for lightning and email tags in the event tags
|
||||
const lightningTag = app.tags?.find((tag: string[]) => tag[0] === 'lightning')?.[1];
|
||||
const emailTag = app.tags?.find((tag: string[]) => tag[0] === 'email')?.[1];
|
||||
|
||||
return { lightning: lightningTag, email: emailTag };
|
||||
};
|
||||
|
||||
const handleCopyContactInfo = () => {
|
||||
const contactInfo = getContactInfo();
|
||||
if (!contactInfo) return;
|
||||
|
||||
const info: string[] = [];
|
||||
if (contactInfo.lightning) info.push(`Lightning: ${contactInfo.lightning}`);
|
||||
if (contactInfo.email) info.push(`Email: ${contactInfo.email}`);
|
||||
|
||||
const textToCopy = info.join('\n');
|
||||
navigator.clipboard.writeText(textToCopy);
|
||||
|
||||
toast({
|
||||
title: 'Contact Info Copied!',
|
||||
description: `Copied ${info.length} contact method(s) to clipboard`
|
||||
});
|
||||
};
|
||||
|
||||
const handleModerationAction = async (action: 'feature' | 'unfeature' | 'approve' | 'unapprove' | 'hide' | 'unhide' | 'homepage' | 'unhomepage') => {
|
||||
if (!isModerator || !user) return;
|
||||
|
||||
const dTag = app.tags.find(tag => tag[0] === 'd')?.[1];
|
||||
if (!dTag) {
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Cannot perform moderation action: missing app identifier',
|
||||
variant: 'destructive'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const appCoordinate = `${app.kind}:${app.pubkey}:${dTag}`;
|
||||
|
||||
try {
|
||||
if (action === 'homepage' || action === 'unhomepage') {
|
||||
// Get current homepage apps list
|
||||
const currentHomepageLists = await nostr.query([{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-homepage-apps'],
|
||||
limit: 1
|
||||
}]);
|
||||
|
||||
const currentHomepageList = currentHomepageLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
// Get current homepage app coordinates
|
||||
const currentHomepageApps = new Set<string>();
|
||||
if (currentHomepageList) {
|
||||
currentHomepageList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => currentHomepageApps.add(tag[1]));
|
||||
}
|
||||
|
||||
// Update the homepage set
|
||||
if (action === 'homepage') {
|
||||
currentHomepageApps.add(appCoordinate);
|
||||
} else {
|
||||
currentHomepageApps.delete(appCoordinate);
|
||||
}
|
||||
|
||||
// Publish updated homepage apps list
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Soapbox homepage apps curated by moderators',
|
||||
tags: [
|
||||
['d', 'soapbox-homepage-apps'],
|
||||
['title', 'Soapbox Homepage Apps'],
|
||||
['description', 'Apps displayed on the Soapbox homepage'],
|
||||
...Array.from(currentHomepageApps).map(coord => ['a', coord])
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
|
||||
// If adding to homepage, also ensure it's approved
|
||||
if (action === 'homepage') {
|
||||
// Get current approved apps list
|
||||
const currentApprovedLists = await nostr.query([{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-approved-apps'],
|
||||
limit: 1
|
||||
}]);
|
||||
|
||||
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
// Get current approved app coordinates
|
||||
const currentApprovedApps = new Set<string>();
|
||||
if (currentApprovedList) {
|
||||
currentApprovedList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => currentApprovedApps.add(tag[1]));
|
||||
}
|
||||
|
||||
// Add to approved list if not already there
|
||||
currentApprovedApps.add(appCoordinate);
|
||||
|
||||
// Publish updated approved apps list
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Soapbox approved apps curated by moderators',
|
||||
tags: [
|
||||
['d', 'soapbox-approved-apps'],
|
||||
['title', 'Soapbox Approved Apps'],
|
||||
['description', 'Apps approved for the Soapbox showcase'],
|
||||
...Array.from(currentApprovedApps).map(coord => ['a', coord])
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
}
|
||||
|
||||
} else if (action === 'feature' || action === 'unfeature') {
|
||||
// Get current featured apps list
|
||||
const currentFeaturedLists = await nostr.query([{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-featured-apps'],
|
||||
limit: 1
|
||||
}]);
|
||||
|
||||
const currentFeaturedList = currentFeaturedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
// Get current featured app coordinates
|
||||
const currentFeaturedApps = new Set<string>();
|
||||
if (currentFeaturedList) {
|
||||
currentFeaturedList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => currentFeaturedApps.add(tag[1]));
|
||||
}
|
||||
|
||||
// Update the featured set
|
||||
if (action === 'feature') {
|
||||
currentFeaturedApps.add(appCoordinate);
|
||||
} else {
|
||||
currentFeaturedApps.delete(appCoordinate);
|
||||
}
|
||||
|
||||
// Publish updated featured apps list
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Soapbox featured apps curated by moderators',
|
||||
tags: [
|
||||
['d', 'soapbox-featured-apps'],
|
||||
['title', 'Soapbox Featured Apps'],
|
||||
['description', 'Apps featured in the Soapbox showcase'],
|
||||
...Array.from(currentFeaturedApps).map(coord => ['a', coord])
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
|
||||
// If featuring an app, also ensure it's approved
|
||||
if (action === 'feature') {
|
||||
// Get current approved apps list
|
||||
const currentApprovedLists = await nostr.query([{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-approved-apps'],
|
||||
limit: 1
|
||||
}]);
|
||||
|
||||
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
// Get current approved app coordinates
|
||||
const currentApprovedApps = new Set<string>();
|
||||
if (currentApprovedList) {
|
||||
currentApprovedList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => currentApprovedApps.add(tag[1]));
|
||||
}
|
||||
|
||||
// Add to approved list if not already there
|
||||
currentApprovedApps.add(appCoordinate);
|
||||
|
||||
// Publish updated approved apps list
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Soapbox approved apps curated by moderators',
|
||||
tags: [
|
||||
['d', 'soapbox-approved-apps'],
|
||||
['title', 'Soapbox Approved Apps'],
|
||||
['description', 'Apps approved for the Soapbox showcase'],
|
||||
...Array.from(currentApprovedApps).map(coord => ['a', coord])
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
}
|
||||
|
||||
} else if (action === 'approve' || action === 'unapprove') {
|
||||
// Get current approved apps list
|
||||
const currentApprovedLists = await nostr.query([{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': ['soapbox-approved-apps'],
|
||||
limit: 1
|
||||
}]);
|
||||
|
||||
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
|
||||
!latest || current.created_at > latest.created_at ? current : latest,
|
||||
null as NostrEvent | null
|
||||
);
|
||||
|
||||
// Get current approved app coordinates
|
||||
const currentApprovedApps = new Set<string>();
|
||||
if (currentApprovedList) {
|
||||
currentApprovedList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => currentApprovedApps.add(tag[1]));
|
||||
}
|
||||
|
||||
// Update the approved set
|
||||
if (action === 'approve') {
|
||||
currentApprovedApps.add(appCoordinate);
|
||||
} else {
|
||||
currentApprovedApps.delete(appCoordinate);
|
||||
}
|
||||
|
||||
// Publish updated approved apps list
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Soapbox approved apps curated by moderators',
|
||||
tags: [
|
||||
['d', 'soapbox-approved-apps'],
|
||||
['title', 'Soapbox Approved Apps'],
|
||||
['description', 'Apps approved for the Soapbox showcase'],
|
||||
...Array.from(currentApprovedApps).map(coord => ['a', coord])
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
|
||||
} else if (action === 'hide' || action === 'unhide') {
|
||||
// Create NIP-56 report event
|
||||
publishEvent({
|
||||
kind: 1984,
|
||||
content: `App ${action}den by moderator: "${app.appName}"`,
|
||||
tags: [
|
||||
['a', appCoordinate, action === 'hide' ? 'spam' : 'other'],
|
||||
['p', app.pubkey],
|
||||
['L', 'soapbox.moderation'],
|
||||
['l', action === 'hide' ? 'hidden' : 'unhidden', 'soapbox.moderation']
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
}
|
||||
|
||||
// Invalidate queries to refresh the data
|
||||
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
|
||||
|
||||
// If this is a Halloween app, also invalidate Halloween queries
|
||||
if (isHalloweenSubmission) {
|
||||
queryClient.invalidateQueries({ queryKey: ['halloween-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['halloween-submissions-with-contacts'] });
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Success!',
|
||||
description: `App "${app.appName}" ${action}d successfully`
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Moderation action failed:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: `Failed to ${action} app "${app.appName}"`,
|
||||
variant: 'destructive'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="group hover:shadow-lg transition-all duration-300 hover:border-primary/20 h-full flex flex-col">
|
||||
<div className="relative">
|
||||
{/* App Screenshot */}
|
||||
<a
|
||||
href={app.websiteUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block aspect-video bg-gradient-to-br from-muted/50 to-muted rounded-t-lg overflow-hidden cursor-pointer"
|
||||
>
|
||||
{!imageError ? (
|
||||
<img
|
||||
src={app.screenshotUrl}
|
||||
alt={`${app.appName} screenshot`}
|
||||
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
|
||||
onError={() => setImageError(true)}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
|
||||
<div className="text-center">
|
||||
<div className="w-16 h-16 mx-auto mb-2 bg-muted rounded-lg flex items-center justify-center">
|
||||
<ExternalLink className="w-8 h-8" />
|
||||
</div>
|
||||
<p className="text-sm">Screenshot unavailable</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</a>
|
||||
|
||||
{/* Actions Menu */}
|
||||
{(isOwner || showModerationControls) && (
|
||||
<div className="absolute top-3 right-3">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="secondary" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{isOwner && (
|
||||
<DropdownMenuItem onClick={() => onEdit?.(app)}>
|
||||
<Edit className="w-4 h-4 mr-2" />
|
||||
Edit App
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{showModerationControls && isModerator && (
|
||||
<>
|
||||
{isHalloweenSubmission && getContactInfo() && (getContactInfo()?.lightning || getContactInfo()?.email) && (
|
||||
<DropdownMenuItem
|
||||
onClick={handleCopyContactInfo}
|
||||
>
|
||||
<Contact className="w-4 h-4 mr-2" />
|
||||
View Contact Info
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{!app.isApproved && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleModerationAction('approve')}
|
||||
disabled={isPending}
|
||||
>
|
||||
<CheckCircle className="w-4 h-4 mr-2" />
|
||||
Approve
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{app.isApproved && !app.isFeatured && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleModerationAction('unapprove')}
|
||||
disabled={isPending}
|
||||
>
|
||||
<XCircle className="w-4 h-4 mr-2" />
|
||||
Unapprove
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleModerationAction(app.isFeatured ? 'unfeature' : 'feature')}
|
||||
disabled={isPending}
|
||||
>
|
||||
{app.isFeatured ? (
|
||||
<>
|
||||
<StarOff className="w-4 h-4 mr-2" />
|
||||
Un-feature
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Star className="w-4 h-4 mr-2" />
|
||||
Feature
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleModerationAction(app.isHomepage ? 'unhomepage' : 'homepage')}
|
||||
disabled={isPending}
|
||||
>
|
||||
{app.isHomepage ? (
|
||||
<>
|
||||
<Home className="w-4 h-4 mr-2" />
|
||||
Remove from Homepage
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Home className="w-4 h-4 mr-2" />
|
||||
Add to Homepage
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleModerationAction(app.isHidden ? 'unhide' : 'hide')}
|
||||
disabled={isPending}
|
||||
>
|
||||
{app.isHidden ? (
|
||||
<>
|
||||
<Eye className="w-4 h-4 mr-2" />
|
||||
Unhide
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<EyeOff className="w-4 h-4 mr-2" />
|
||||
Hide
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<CardContent className="p-6 flex flex-col flex-1">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-3">
|
||||
{/* App Icon */}
|
||||
<div className="w-12 h-12 rounded-lg overflow-hidden bg-muted flex-shrink-0">
|
||||
<img
|
||||
src={app.appIconUrl}
|
||||
alt={`${app.appName} icon`}
|
||||
className="w-full h-full object-cover"
|
||||
onError={(e) => {
|
||||
const target = e.target as HTMLImageElement;
|
||||
target.style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-xl font-semibold text-foreground mb-1" title={app.appName}>
|
||||
{app.appName.length > 50 ? `${app.appName.slice(0, 50)}...` : app.appName}
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-muted-foreground mb-3 line-clamp-3">{app.description}</p>
|
||||
|
||||
{/* Author Information */}
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<div className="w-6 h-6 rounded-full overflow-hidden bg-muted flex-shrink-0">
|
||||
{authorData?.metadata?.picture ? (
|
||||
<img
|
||||
src={authorData.metadata.picture}
|
||||
alt={`${authorData.metadata.name || 'Author'} avatar`}
|
||||
className="w-full h-full object-cover"
|
||||
onError={(e) => {
|
||||
const target = e.target as HTMLImageElement;
|
||||
target.style.display = 'none';
|
||||
target.parentElement!.innerHTML = '<div class="w-full h-full flex items-center justify-center"><svg class="w-3 h-3 text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd"></path></svg></div>';
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center">
|
||||
<User className="w-3 h-3 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
by{' '}
|
||||
<a
|
||||
href={`https://ditto.pub/${app.authorNpub || nip19.npubEncode(authorPubkey)}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:text-primary/80 transition-colors hover:underline"
|
||||
>
|
||||
{authorData?.metadata?.name || authorData?.metadata?.display_name || 'Anonymous'}
|
||||
</a>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Spacer to push action links to bottom */}
|
||||
<div className="flex-1"></div>
|
||||
|
||||
{/* Action Links */}
|
||||
<div className="flex items-center gap-2 mt-auto">
|
||||
<Link
|
||||
to={`/clone?url=${encodeURIComponent(app.repositoryUrl)}`}
|
||||
className="flex-1"
|
||||
>
|
||||
<img
|
||||
src="/badge.svg"
|
||||
alt="Edit with Shakespeare"
|
||||
className="h-6 hover:opacity-80 transition-opacity"
|
||||
/>
|
||||
</Link>
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<a
|
||||
href={app.websiteUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
title="Visit app"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { ReactNode } from 'react';
|
||||
import { ConsoleErrorProvider } from './ConsoleErrorProvider';
|
||||
import { useConsoleError } from '@/hooks/useConsoleError';
|
||||
import { addConsoleMessage, clearConsoleMessages, ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
|
||||
// Wrapper component for testing
|
||||
function TestWrapper({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<ConsoleErrorProvider>
|
||||
{children}
|
||||
</ConsoleErrorProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe('ConsoleErrorProvider', () => {
|
||||
beforeEach(() => {
|
||||
clearConsoleMessages();
|
||||
});
|
||||
|
||||
it('should provide initial state with no errors', () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(false);
|
||||
expect(result.current.consoleError).toBeNull();
|
||||
});
|
||||
|
||||
it('should update hasErrors when console error is added', async () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(false);
|
||||
|
||||
// Add an error message
|
||||
act(() => {
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(true);
|
||||
expect(result.current.consoleError).toBeInstanceOf(ProjectPreviewConsoleError);
|
||||
expect(result.current.consoleError?.message).toBe('Console error detected: Test error message');
|
||||
});
|
||||
|
||||
it('should not update hasErrors for non-error messages', async () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
// Add non-error messages
|
||||
act(() => {
|
||||
addConsoleMessage('log', 'Test log message');
|
||||
addConsoleMessage('warn', 'Test warning message');
|
||||
addConsoleMessage('info', 'Test info message');
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(false);
|
||||
expect(result.current.consoleError).toBeNull();
|
||||
});
|
||||
|
||||
it('should update consoleError with latest error message', () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
// Add first error
|
||||
act(() => {
|
||||
addConsoleMessage('error', 'First error');
|
||||
});
|
||||
|
||||
expect(result.current.consoleError?.message).toBe('Console error detected: First error');
|
||||
|
||||
// Add second error - should update to show latest error
|
||||
act(() => {
|
||||
addConsoleMessage('error', 'Second error');
|
||||
});
|
||||
|
||||
expect(result.current.consoleError?.message).toBe('Console error detected: Second error');
|
||||
expect(result.current.consoleError?.logs).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should clear errors when clearErrors is called', async () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
// Add error to set state
|
||||
act(() => {
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(true);
|
||||
expect(result.current.consoleError).not.toBeNull();
|
||||
|
||||
// Clear errors
|
||||
act(() => {
|
||||
result.current.clearErrors();
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(false);
|
||||
expect(result.current.consoleError).toBeNull();
|
||||
});
|
||||
|
||||
it('should dismiss console error when dismissConsoleError is called', async () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
// Add error to create console error
|
||||
act(() => {
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(result.current.consoleError).not.toBeNull();
|
||||
|
||||
// Dismiss console error (this only clears the Quilly error, not the global state)
|
||||
act(() => {
|
||||
result.current.dismissConsoleError();
|
||||
});
|
||||
|
||||
expect(result.current.consoleError).toBeNull();
|
||||
// hasErrors should still be true since we only dismissed the Quilly display
|
||||
expect(result.current.hasErrors).toBe(true);
|
||||
});
|
||||
|
||||
it('should include all error messages in console error logs', () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
// Add multiple errors and non-errors
|
||||
act(() => {
|
||||
addConsoleMessage('log', 'Log message');
|
||||
addConsoleMessage('error', 'First error');
|
||||
addConsoleMessage('warn', 'Warning message');
|
||||
addConsoleMessage('error', 'Second error');
|
||||
addConsoleMessage('info', 'Info message');
|
||||
addConsoleMessage('error', 'Third error');
|
||||
});
|
||||
|
||||
expect(result.current.consoleError?.message).toBe('Console error detected: Third error');
|
||||
expect(result.current.consoleError?.logs).toHaveLength(3);
|
||||
expect(result.current.consoleError?.logs.map(log => log.message)).toEqual([
|
||||
'First error',
|
||||
'Second error',
|
||||
'Third error'
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,63 +0,0 @@
|
||||
import { useState, useEffect, useCallback, ReactNode } from 'react';
|
||||
import {
|
||||
addConsoleMessageListener,
|
||||
removeConsoleMessageListener,
|
||||
getHasConsoleErrors,
|
||||
getConsoleMessages,
|
||||
clearConsoleMessages,
|
||||
ProjectPreviewConsoleError
|
||||
} from '@/lib/consoleMessages';
|
||||
import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext';
|
||||
|
||||
interface ConsoleErrorProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) {
|
||||
const [hasErrors, setHasErrors] = useState(() => getHasConsoleErrors());
|
||||
const [consoleError, setConsoleError] = useState<ProjectPreviewConsoleError | null>(null);
|
||||
|
||||
const updateState = useCallback(() => {
|
||||
const hasConsoleErrors = getHasConsoleErrors();
|
||||
setHasErrors(hasConsoleErrors);
|
||||
|
||||
if (hasConsoleErrors) {
|
||||
const errorMessages = getConsoleMessages().filter(msg => msg.level === 'error');
|
||||
const latestError = errorMessages[errorMessages.length - 1];
|
||||
setConsoleError(new ProjectPreviewConsoleError(
|
||||
`Console error detected: ${latestError.message}`,
|
||||
errorMessages
|
||||
));
|
||||
} else {
|
||||
setConsoleError(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
addConsoleMessageListener(updateState);
|
||||
updateState(); // Initial sync
|
||||
|
||||
return () => removeConsoleMessageListener(updateState);
|
||||
}, [updateState]);
|
||||
|
||||
const clearErrors = useCallback(() => {
|
||||
clearConsoleMessages();
|
||||
}, []);
|
||||
|
||||
const dismissConsoleError = useCallback(() => {
|
||||
setConsoleError(null);
|
||||
}, []);
|
||||
|
||||
const value = {
|
||||
hasErrors,
|
||||
consoleError,
|
||||
clearErrors,
|
||||
dismissConsoleError,
|
||||
};
|
||||
|
||||
return (
|
||||
<ConsoleErrorContext.Provider value={value}>
|
||||
{children}
|
||||
</ConsoleErrorContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -9,11 +9,10 @@ import { Label } from '@/components/ui/label';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface CreditsDialogProps {
|
||||
@@ -184,7 +183,6 @@ function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
|
||||
|
||||
export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogProps) {
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
@@ -197,7 +195,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
const { data: payments, isLoading: isLoadingPayments } = useQuery({
|
||||
queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
|
||||
queryFn: async (): Promise<Payment[]> => {
|
||||
const ai = createAIClient(provider, user, config.corsProxy);
|
||||
const ai = createAIClient(provider, user);
|
||||
const data = await ai.get('/credits/payments?limit=50') as PaymentsResponse;
|
||||
return data.data;
|
||||
},
|
||||
@@ -209,7 +207,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
// Mutation for adding credits
|
||||
const addCreditsMutation = useMutation({
|
||||
mutationFn: async (request: AddCreditsRequest): Promise<Payment> => {
|
||||
const ai = createAIClient(provider, user, config.corsProxy);
|
||||
const ai = createAIClient(provider, user);
|
||||
return await ai.post('/credits/add', {
|
||||
body: request,
|
||||
}) as Payment;
|
||||
@@ -250,7 +248,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
// Mutation for checking payment status
|
||||
const checkPaymentMutation = useMutation({
|
||||
mutationFn: async (paymentId: string): Promise<Payment> => {
|
||||
const ai = createAIClient(provider, user, config.corsProxy);
|
||||
const ai = createAIClient(provider, user);
|
||||
return await ai.get(`/credits/payments/${paymentId}`) as Payment;
|
||||
},
|
||||
onMutate: async (paymentId: string) => {
|
||||
@@ -401,7 +399,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent onOpenAutoFocus={(e) => e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-dvh-safe max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none">
|
||||
<DialogContent onOpenAutoFocus={(e) => e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none">
|
||||
<DialogHeader className="flex-shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2 text-lg">
|
||||
{lightningInvoice ? (
|
||||
@@ -436,61 +434,68 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
<div className="flex-1 flex flex-col min-h-0">
|
||||
{/* Add Credits Form - Fixed size section */}
|
||||
<div className="flex-shrink-0 space-y-4 px-1 -mx-1">
|
||||
<div className="space-y-3">
|
||||
<Label htmlFor="amount" className="text-sm font-medium">Amount (USD)</Label>
|
||||
<div className="space-y-3">
|
||||
<Label htmlFor="amount" className="text-sm font-medium">Amount (USD)</Label>
|
||||
<div className="space-y-3">
|
||||
<Input
|
||||
id="amount"
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(Number(e.target.value))}
|
||||
placeholder="Enter amount"
|
||||
className="text-center text-lg font-medium"
|
||||
/>
|
||||
<div className="grid grid-cols-5 gap-2">
|
||||
{PRESET_AMOUNTS.map((preset) => (
|
||||
<Button
|
||||
key={preset}
|
||||
variant={amount === preset ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => setAmount(preset)}
|
||||
className="text-xs"
|
||||
>
|
||||
<Input
|
||||
id="amount"
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(Number(e.target.value))}
|
||||
placeholder="Enter amount"
|
||||
className="text-center text-lg font-medium"
|
||||
/>
|
||||
<div className="grid grid-cols-5 gap-2">
|
||||
{PRESET_AMOUNTS.map((preset) => (
|
||||
<Button
|
||||
key={preset}
|
||||
variant={amount === preset ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => setAmount(preset)}
|
||||
className="text-xs"
|
||||
>
|
||||
${preset}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Label className="text-sm font-medium">Payment Method</Label>
|
||||
<Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="stripe" className="flex items-center gap-2">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Label htmlFor="payment-method" className="text-sm font-medium">Payment Method</Label>
|
||||
<Select value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="stripe">
|
||||
<div className="flex items-center gap-2">
|
||||
<CreditCard className="h-4 w-4" />
|
||||
Credit Card
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="lightning" className="flex items-center gap-2">
|
||||
Credit Card
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="lightning">
|
||||
<div className="flex items-center gap-2">
|
||||
<Zap className="h-4 w-4" />
|
||||
Lightning
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
Lightning
|
||||
</div>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleAddCredits}
|
||||
disabled={amount <= 0 || addCreditsMutation.isPending}
|
||||
className="w-full h-12 text-base font-medium"
|
||||
size="lg"
|
||||
>
|
||||
{addCreditsMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
|
||||
{paymentMethod === 'stripe' ? 'Pay with Card' : 'Generate Invoice'}
|
||||
{amount > 0 && ` - ${formatCurrency(amount)}`}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleAddCredits}
|
||||
disabled={amount <= 0 || addCreditsMutation.isPending}
|
||||
className="w-full h-12 text-base font-medium"
|
||||
size="lg"
|
||||
>
|
||||
{addCreditsMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
|
||||
{paymentMethod === 'stripe' ? 'Pay with Card' : 'Generate Invoice'}
|
||||
{amount > 0 && ` - ${formatCurrency(amount)}`}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex-shrink-0 px-1 -mx-1 py-4">
|
||||
@@ -523,65 +528,65 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
) : (
|
||||
<div className="space-y-2 pb-2">
|
||||
{payments.map((payment) => (
|
||||
<div
|
||||
key={payment.id}
|
||||
className="p-3 border rounded-lg space-y-2 hover:bg-muted/30 transition-colors"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
{getStatusIcon(payment.status)}
|
||||
<span className="text-sm font-medium truncate">
|
||||
{payment.method === 'stripe' ? 'Credit Card' : 'Lightning'}
|
||||
</span>
|
||||
<Badge variant={getStatusVariant(payment.status)} className="text-xs flex-shrink-0">
|
||||
{payment.status}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-right flex-shrink-0">
|
||||
<p className="text-sm font-medium">{formatCurrency(payment.amount)}</p>
|
||||
{payment.fee > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<div
|
||||
key={payment.id}
|
||||
className="p-3 border rounded-lg space-y-2 hover:bg-muted/30 transition-colors"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
{getStatusIcon(payment.status)}
|
||||
<span className="text-sm font-medium truncate">
|
||||
{payment.method === 'stripe' ? 'Credit Card' : 'Lightning'}
|
||||
</span>
|
||||
<Badge variant={getStatusVariant(payment.status)} className="text-xs flex-shrink-0">
|
||||
{payment.status}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-right flex-shrink-0">
|
||||
<p className="text-sm font-medium">{formatCurrency(payment.amount)}</p>
|
||||
{payment.fee > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
+{formatCurrency(payment.fee)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>{formatDate(payment.created_at)}</span>
|
||||
{payment.status === 'pending' && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => checkPaymentMutation.mutate(payment.id)}
|
||||
disabled={refreshingPayments.has(payment.id)}
|
||||
className="h-6 px-2 text-xs"
|
||||
title="Refresh payment status"
|
||||
>
|
||||
<RotateCcw className={`h-3 w-3 ${refreshingPayments.has(payment.id) ? 'animate-spin' : ''}`} />
|
||||
</Button>
|
||||
{payment.url && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (payment.method === 'lightning') {
|
||||
setLightningInvoice(payment.url);
|
||||
} else {
|
||||
window.open(payment.url, '_blank');
|
||||
}
|
||||
}}
|
||||
className="h-6 px-2 text-xs"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3 mr-1" />
|
||||
{payment.method === 'lightning' ? 'Pay' : 'Pay'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>{formatDate(payment.created_at)}</span>
|
||||
{payment.status === 'pending' && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => checkPaymentMutation.mutate(payment.id)}
|
||||
disabled={refreshingPayments.has(payment.id)}
|
||||
className="h-6 px-2 text-xs"
|
||||
title="Refresh payment status"
|
||||
>
|
||||
<RotateCcw className={`h-3 w-3 ${refreshingPayments.has(payment.id) ? 'animate-spin' : ''}`} />
|
||||
</Button>
|
||||
{payment.url && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (payment.method === 'lightning') {
|
||||
setLightningInvoice(payment.url);
|
||||
} else {
|
||||
window.open(payment.url, '_blank');
|
||||
}
|
||||
}}
|
||||
className="h-6 px-2 text-xs"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3 mr-1" />
|
||||
{payment.method === 'lightning' ? 'Pay' : 'Pay'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,520 +1,182 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Rocket, ExternalLink, AlertCircle } from 'lucide-react';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} 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';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, DeployAdapter } from '@/lib/deploy';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider } from '@/contexts/DeploySettingsContext';
|
||||
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
|
||||
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
|
||||
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
|
||||
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
|
||||
|
||||
/**
|
||||
* Helper function to get provider URL for favicon
|
||||
*/
|
||||
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 'nsite':
|
||||
return null;
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render provider icon using favicon or fallback
|
||||
*/
|
||||
function renderProviderIcon(provider: DeployProvider, size = 14) {
|
||||
const url = getProviderUrl(provider);
|
||||
|
||||
if (url) {
|
||||
return (
|
||||
<ExternalFavicon
|
||||
url={url}
|
||||
size={size}
|
||||
fallback={<Rocket size={size} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <Rocket size={size} />;
|
||||
}
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { deployProject } from '@/lib/deploy';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import {
|
||||
CloudUpload,
|
||||
Loader2,
|
||||
} from 'lucide-react';
|
||||
|
||||
interface DeployDialogProps {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onFirstInteraction?: () => void;
|
||||
}
|
||||
|
||||
interface ShakespeareFormData {
|
||||
subdomain: string;
|
||||
}
|
||||
|
||||
interface NsiteFormData {
|
||||
nsec: string;
|
||||
}
|
||||
|
||||
interface NetlifyFormData {
|
||||
siteId: string;
|
||||
siteName: string;
|
||||
}
|
||||
|
||||
interface VercelFormData {
|
||||
projectName: string;
|
||||
teamId: string;
|
||||
}
|
||||
|
||||
export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const { settings } = useDeploySettings();
|
||||
const { settings: projectSettings, updateSettings: updateProjectSettings } = useProjectDeploySettings(projectId);
|
||||
export function DeployDialog({
|
||||
projectId,
|
||||
projectName,
|
||||
open,
|
||||
onOpenChange,
|
||||
onFirstInteraction
|
||||
}: DeployDialogProps) {
|
||||
const { config } = useAppContext();
|
||||
const { user } = useCurrentUser();
|
||||
const { fs } = useFS();
|
||||
const { config } = useAppContext();
|
||||
const { nostr } = useNostr();
|
||||
const { toast } = useToast();
|
||||
|
||||
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
|
||||
const [isDeploying, setIsDeploying] = useState(false);
|
||||
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// State for the deploy URL input
|
||||
const [deployUrl, setDeployUrl] = useState('');
|
||||
|
||||
// Provider-specific form data
|
||||
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
|
||||
subdomain: projectId,
|
||||
});
|
||||
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
|
||||
nsec: '',
|
||||
});
|
||||
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
|
||||
siteId: '',
|
||||
siteName: '',
|
||||
});
|
||||
const [vercelForm, setVercelForm] = useState<VercelFormData>({
|
||||
projectName: projectName || projectId,
|
||||
teamId: '',
|
||||
});
|
||||
|
||||
// Load project settings when dialog opens
|
||||
// Initialize deploy URL when dialog opens
|
||||
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]);
|
||||
}
|
||||
}
|
||||
setDeployUrl(`${projectId}.${config.deployServer}`);
|
||||
}
|
||||
}, [open, projectSettings, settings.providers]);
|
||||
}, [open, projectId, config.deployServer]);
|
||||
|
||||
const selectedProvider = settings.providers.find(p => p.id === selectedProviderId);
|
||||
|
||||
const handleDeploy = async () => {
|
||||
if (!selectedProvider) return;
|
||||
|
||||
setIsDeploying(true);
|
||||
setError(null);
|
||||
setDeployResult(null);
|
||||
|
||||
try {
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
let adapter: DeployAdapter;
|
||||
|
||||
if (selectedProvider.type === 'shakespeare') {
|
||||
if (!user) {
|
||||
throw new Error('You must be logged in with Nostr to use Shakespeare Deploy');
|
||||
}
|
||||
|
||||
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
|
||||
adapter = new ShakespeareAdapter({
|
||||
fs,
|
||||
signer: user.signer,
|
||||
host: shakespeareProvider.host,
|
||||
subdomain: shakespeareForm.subdomain || undefined,
|
||||
corsProxy: shakespeareProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else if (selectedProvider.type === 'nsite') {
|
||||
const nsiteProvider = selectedProvider as import('@/contexts/DeploySettingsContext').NsiteProvider;
|
||||
|
||||
if (!nsiteForm.nsec) {
|
||||
throw new Error('Site private key (nsec) is required');
|
||||
}
|
||||
|
||||
adapter = new NsiteAdapter({
|
||||
fs,
|
||||
nostr,
|
||||
nsec: nsiteForm.nsec,
|
||||
gateway: nsiteProvider.gateway,
|
||||
relayUrls: nsiteProvider.relayUrls,
|
||||
blossomServers: nsiteProvider.blossomServers,
|
||||
});
|
||||
} else if (selectedProvider.type === 'netlify') {
|
||||
const netlifyProvider = selectedProvider as NetlifyProvider;
|
||||
if (!netlifyProvider.apiKey) {
|
||||
throw new Error('Netlify API key is required');
|
||||
}
|
||||
|
||||
// If siteId is empty, we're creating a new site, so only pass siteName
|
||||
// If siteId is set, we're updating an existing site
|
||||
adapter = new NetlifyAdapter({
|
||||
fs,
|
||||
apiKey: netlifyProvider.apiKey,
|
||||
baseURL: netlifyProvider.baseURL,
|
||||
siteName: netlifyForm.siteId ? undefined : (netlifyForm.siteName || undefined),
|
||||
siteId: netlifyForm.siteId || undefined,
|
||||
corsProxy: netlifyProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else if (selectedProvider.type === 'vercel') {
|
||||
const vercelProvider = selectedProvider as VercelProvider;
|
||||
if (!vercelProvider.apiKey) {
|
||||
throw new Error('Vercel API key is required');
|
||||
}
|
||||
|
||||
adapter = new VercelAdapter({
|
||||
fs,
|
||||
apiKey: vercelProvider.apiKey,
|
||||
baseURL: vercelProvider.baseURL,
|
||||
teamId: vercelForm.teamId || undefined,
|
||||
projectName: vercelForm.projectName || undefined,
|
||||
corsProxy: vercelProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else {
|
||||
throw new Error('Unknown provider type');
|
||||
const deployMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!user) {
|
||||
throw new Error("You must be logged into Nostr to deploy a project");
|
||||
}
|
||||
|
||||
const result = await adapter.deploy({
|
||||
projectId,
|
||||
projectPath,
|
||||
// Parse the deploy URL to extract hostname and server
|
||||
const hostname = deployUrl.trim();
|
||||
const parts = hostname.split('.');
|
||||
|
||||
if (parts.length < 2) {
|
||||
throw new Error("Invalid deploy URL format. Please use format: subdomain.domain.com");
|
||||
}
|
||||
|
||||
// Extract the deploy server (everything after the first dot)
|
||||
const deployServer = parts.slice(1).join('.');
|
||||
|
||||
return await deployProject({
|
||||
fs,
|
||||
projectId, // Keep the original projectId for file path
|
||||
deployServer,
|
||||
projectPath: `/projects/${projectId}`,
|
||||
signer: user.signer,
|
||||
customHostname: hostname, // Pass the custom hostname
|
||||
});
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
toast({
|
||||
title: "Deployment successful!",
|
||||
description: `Your project is now live at ${result.hostname}`,
|
||||
});
|
||||
|
||||
// Save project-specific settings (updateSettings now automatically sets currentProvider)
|
||||
if (selectedProvider.type === 'shakespeare') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'shakespeare',
|
||||
data: {
|
||||
subdomain: shakespeareForm.subdomain || undefined,
|
||||
},
|
||||
});
|
||||
} else if (selectedProvider.type === 'nsite') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'nsite',
|
||||
data: {
|
||||
nsec: nsiteForm.nsec,
|
||||
},
|
||||
});
|
||||
} else if (selectedProvider.type === 'netlify') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'netlify',
|
||||
data: {
|
||||
siteId: result.metadata?.siteId as string | undefined,
|
||||
},
|
||||
});
|
||||
} else if (selectedProvider.type === 'vercel') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'vercel',
|
||||
data: {
|
||||
teamId: vercelForm.teamId || undefined,
|
||||
projectId: vercelForm.projectName || undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
// Open the deployed site in a new tab
|
||||
window.open(result.url, '_blank');
|
||||
|
||||
setDeployResult(result);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Deployment failed');
|
||||
} finally {
|
||||
setIsDeploying(false);
|
||||
// Close the dialog
|
||||
onOpenChange(false);
|
||||
},
|
||||
onError: (error) => {
|
||||
toast({
|
||||
title: "Deployment failed",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const handleDeploy = () => {
|
||||
if (onFirstInteraction) {
|
||||
onFirstInteraction();
|
||||
}
|
||||
deployMutation.mutate();
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setSelectedProviderId('');
|
||||
setDeployResult(null);
|
||||
setError(null);
|
||||
// Reset forms
|
||||
setShakespeareForm({ subdomain: projectId });
|
||||
setNsiteForm({ nsec: '' });
|
||||
setNetlifyForm({ siteId: '', siteName: '' });
|
||||
setVercelForm({ projectName: projectName || projectId, teamId: '' });
|
||||
onOpenChange(false);
|
||||
const handleUrlChange = (value: string) => {
|
||||
// Remove protocol if user enters it
|
||||
const cleanValue = value.replace(/^https?:\/\//, '');
|
||||
setDeployUrl(cleanValue);
|
||||
};
|
||||
|
||||
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
|
||||
setShakespeareForm({ subdomain });
|
||||
}, []);
|
||||
|
||||
const handleNsiteNsecChange = useCallback((nsec: string) => {
|
||||
setNsiteForm({ nsec });
|
||||
}, []);
|
||||
|
||||
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
|
||||
setNetlifyForm({ siteId, siteName });
|
||||
}, []);
|
||||
|
||||
const handleVercelConfigChange = useCallback((projectName: string, teamId: string) => {
|
||||
setVercelForm({ projectName, teamId });
|
||||
}, []);
|
||||
|
||||
const renderProviderFields = () => {
|
||||
if (!selectedProvider) return null;
|
||||
|
||||
if (selectedProvider.type === 'shakespeare') {
|
||||
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
|
||||
|
||||
return (
|
||||
<ShakespeareDeployForm
|
||||
host={shakespeareProvider.host}
|
||||
projectId={projectId}
|
||||
onSubdomainChange={handleShakespeareSubdomainChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'nsite') {
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedNsec = savedConfig?.type === 'nsite' ? savedConfig.data.nsec : undefined;
|
||||
|
||||
return (
|
||||
<NsiteDeployForm
|
||||
gateway={selectedProvider.gateway}
|
||||
savedNsec={savedNsec}
|
||||
onNsecChange={handleNsiteNsecChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'netlify') {
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedSiteId = savedConfig?.type === 'netlify' ? savedConfig.data.siteId : undefined;
|
||||
|
||||
return (
|
||||
<NetlifyDeployForm
|
||||
apiKey={selectedProvider.apiKey}
|
||||
baseURL={selectedProvider.baseURL}
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
savedSiteId={savedSiteId}
|
||||
onSiteChange={handleNetlifySiteChange}
|
||||
corsProxy={selectedProvider.proxy ? config.corsProxy : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'vercel') {
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedTeamId = savedConfig?.type === 'vercel' ? savedConfig.data.teamId : undefined;
|
||||
const savedProjectName = savedConfig?.type === 'vercel' ? savedConfig.data.projectId : undefined;
|
||||
|
||||
return (
|
||||
<VercelDeployForm
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
savedTeamId={savedTeamId}
|
||||
savedProjectName={savedProjectName}
|
||||
onConfigChange={handleVercelConfigChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
const isValidUrl = () => {
|
||||
const trimmed = deployUrl.trim();
|
||||
return trimmed.length > 0 && trimmed.includes('.') && !trimmed.startsWith('.') && !trimmed.endsWith('.');
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Rocket className="h-5 w-5" />
|
||||
Deploy Project
|
||||
<CloudUpload className="h-5 w-5" />
|
||||
Deploy "{projectName}"
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Deploy your project to a hosting platform
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{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')}
|
||||
</Button>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="deploy-url">Deploy URL</Label>
|
||||
<div className="relative">
|
||||
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground">
|
||||
https://
|
||||
</span>
|
||||
<Input
|
||||
id="deploy-url"
|
||||
value={deployUrl}
|
||||
onChange={(e) => handleUrlChange(e.target.value)}
|
||||
placeholder={`${projectId}.${config.deployServer}`}
|
||||
className="pl-16"
|
||||
disabled={deployMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Your project will be deployed to this URL. You can customize the subdomain.
|
||||
</p>
|
||||
</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"
|
||||
onClick={handleClose}
|
||||
>
|
||||
Configure deployment settings
|
||||
</Link>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
{!user && (
|
||||
<div className="p-3 bg-muted rounded-lg">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
You must be logged into Nostr to deploy projects.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={deployMutation.isPending}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleDeploy}
|
||||
disabled={!user || !isValidUrl() || deployMutation.isPending}
|
||||
className="gap-2"
|
||||
>
|
||||
{deployMutation.isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
<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>
|
||||
</div>
|
||||
|
||||
{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>
|
||||
)}
|
||||
|
||||
<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 === 'nsite' && !nsiteForm.nsec) ||
|
||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName)
|
||||
}
|
||||
>
|
||||
{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>
|
||||
</>
|
||||
<CloudUpload className="h-4 w-4" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{deployMutation.isPending ? 'Deploying...' : 'Deploy'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import { useState, useEffect, useMemo, type ReactNode } from 'react';
|
||||
import { DeploySettingsContext, type DeploySettings, type DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
|
||||
|
||||
const DEFAULT_SETTINGS: DeploySettings = {
|
||||
providers: [],
|
||||
};
|
||||
|
||||
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
|
||||
const { fs } = useFS();
|
||||
const [settings, setSettings] = useState<DeploySettings>(DEFAULT_SETTINGS);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
// Initialize settings from VFS on mount
|
||||
useEffect(() => {
|
||||
const initializeSettings = async () => {
|
||||
try {
|
||||
const settings = await readDeploySettings(fs);
|
||||
setSettings(settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize deploy settings:', error);
|
||||
setSettings(DEFAULT_SETTINGS);
|
||||
} finally {
|
||||
setIsInitialized(true);
|
||||
}
|
||||
};
|
||||
|
||||
initializeSettings();
|
||||
}, [fs]);
|
||||
|
||||
// Save settings to VFS whenever they change (but not during initialization)
|
||||
useEffect(() => {
|
||||
if (!isInitialized) return;
|
||||
|
||||
const saveSettings = async () => {
|
||||
try {
|
||||
await writeDeploySettings(fs, settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to save deploy settings:', error);
|
||||
}
|
||||
};
|
||||
|
||||
saveSettings();
|
||||
}, [fs, settings, isInitialized]);
|
||||
|
||||
const updateSettings = (updates: Partial<DeploySettings>) => {
|
||||
setSettings(prev => ({ ...prev, ...updates }));
|
||||
};
|
||||
|
||||
const removeProvider = (index: number) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
providers: prev.providers.filter((_, i) => i !== index),
|
||||
}));
|
||||
};
|
||||
|
||||
const setProviders = (providers: DeployProvider[]) => {
|
||||
setSettings(prev => ({ ...prev, providers }));
|
||||
};
|
||||
|
||||
const isConfigured = useMemo(() => {
|
||||
return settings.providers.length > 0;
|
||||
}, [settings.providers]);
|
||||
|
||||
const value = {
|
||||
settings,
|
||||
updateSettings,
|
||||
removeProvider,
|
||||
setProviders,
|
||||
isConfigured,
|
||||
isInitialized,
|
||||
};
|
||||
|
||||
return (
|
||||
<DeploySettingsContext.Provider value={value}>
|
||||
{children}
|
||||
</DeploySettingsContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useAnyProjectBusy } from '@/hooks/useAnyProjectBusy';
|
||||
|
||||
/**
|
||||
* Component that dynamically updates the favicon when any project is busy with AI
|
||||
* Rotates the favicon counter-clockwise when busy
|
||||
*/
|
||||
export function DynamicFavicon() {
|
||||
const isBusy = useAnyProjectBusy();
|
||||
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||
const animationRef = useRef<number | null>(null);
|
||||
const rotationRef = useRef(0);
|
||||
const originalFaviconRef = useRef<string | null>(null);
|
||||
const originalImageRef = useRef<HTMLImageElement | null>(null);
|
||||
|
||||
// Initialize canvas and save original favicon
|
||||
useEffect(() => {
|
||||
// Create canvas element for drawing the favicon
|
||||
if (!canvasRef.current) {
|
||||
canvasRef.current = document.createElement('canvas');
|
||||
canvasRef.current.width = 32;
|
||||
canvasRef.current.height = 32;
|
||||
}
|
||||
|
||||
// Store the original favicon URL
|
||||
const faviconElement = document.querySelector('link[rel="icon"]');
|
||||
if (faviconElement && !originalFaviconRef.current) {
|
||||
originalFaviconRef.current = faviconElement.getAttribute('href');
|
||||
}
|
||||
|
||||
// Preload the favicon image
|
||||
if (!originalImageRef.current) {
|
||||
const img = new Image();
|
||||
img.crossOrigin = 'anonymous';
|
||||
img.src = originalFaviconRef.current || '/shakespeare-192x192.png';
|
||||
img.onload = () => {
|
||||
originalImageRef.current = img;
|
||||
};
|
||||
}
|
||||
|
||||
return () => {
|
||||
// Restore original favicon on unmount
|
||||
if (originalFaviconRef.current) {
|
||||
const faviconElement = document.querySelector('link[rel="icon"]');
|
||||
if (faviconElement) {
|
||||
faviconElement.setAttribute('href', originalFaviconRef.current);
|
||||
}
|
||||
}
|
||||
|
||||
// Cancel any ongoing animation
|
||||
if (animationRef.current !== null) {
|
||||
cancelAnimationFrame(animationRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Handle busy state changes
|
||||
useEffect(() => {
|
||||
if (!canvasRef.current) return;
|
||||
|
||||
// If busy, start rotation animation
|
||||
if (isBusy) {
|
||||
const startRotationAnimation = () => {
|
||||
if (!canvasRef.current || !originalImageRef.current) {
|
||||
// If image isn't loaded yet, try again in a moment
|
||||
setTimeout(startRotationAnimation, 100);
|
||||
return;
|
||||
}
|
||||
|
||||
const canvas = canvasRef.current;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
const img = originalImageRef.current;
|
||||
|
||||
const animate = () => {
|
||||
if (!ctx || !canvas) return;
|
||||
|
||||
// Clear canvas
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
// Save context state
|
||||
ctx.save();
|
||||
|
||||
// Translate to center for rotation
|
||||
ctx.translate(canvas.width / 2, canvas.height / 2);
|
||||
|
||||
// Rotate counter-clockwise
|
||||
ctx.rotate(-rotationRef.current);
|
||||
|
||||
// Draw the image centered
|
||||
ctx.drawImage(
|
||||
img,
|
||||
-canvas.width / 2,
|
||||
-canvas.height / 2,
|
||||
canvas.width,
|
||||
canvas.height
|
||||
);
|
||||
|
||||
// Restore context state
|
||||
ctx.restore();
|
||||
|
||||
// Update rotation for next frame (slower rotation)
|
||||
rotationRef.current += 0.05;
|
||||
|
||||
// Update favicon
|
||||
const faviconElement = document.querySelector('link[rel="icon"]');
|
||||
if (faviconElement) {
|
||||
faviconElement.setAttribute('href', canvas.toDataURL('image/png'));
|
||||
}
|
||||
|
||||
// Continue animation
|
||||
animationRef.current = requestAnimationFrame(animate);
|
||||
};
|
||||
|
||||
// Start animation loop
|
||||
animate();
|
||||
};
|
||||
|
||||
startRotationAnimation();
|
||||
} else {
|
||||
// If not busy, restore original favicon and stop animation
|
||||
if (animationRef.current !== null) {
|
||||
cancelAnimationFrame(animationRef.current);
|
||||
animationRef.current = null;
|
||||
}
|
||||
|
||||
// Reset rotation
|
||||
rotationRef.current = 0;
|
||||
|
||||
// Restore original favicon
|
||||
if (originalFaviconRef.current) {
|
||||
const faviconElement = document.querySelector('link[rel="icon"]');
|
||||
if (faviconElement) {
|
||||
faviconElement.setAttribute('href', originalFaviconRef.current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
// Cancel animation on effect cleanup
|
||||
if (animationRef.current !== null) {
|
||||
cancelAnimationFrame(animationRef.current);
|
||||
animationRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [isBusy]);
|
||||
|
||||
// This component doesn't render anything visible
|
||||
return null;
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { faviconUrl, normalizeUrl } from '@/lib/faviconUrl';
|
||||
import { ReactNode } from 'react';
|
||||
|
||||
interface ExternalFaviconProps {
|
||||
/** The URL to fetch the favicon for */
|
||||
url: string;
|
||||
/** Size of the favicon in pixels */
|
||||
size?: number;
|
||||
/** Fallback element to display if favicon fails to load */
|
||||
fallback?: ReactNode;
|
||||
/** Additional CSS classes */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* ExternalFavicon component that fetches and displays a favicon for a given URL
|
||||
* using the configurable favicon service from app settings.
|
||||
*/
|
||||
export function ExternalFavicon({
|
||||
url,
|
||||
size = 16,
|
||||
fallback,
|
||||
className = '',
|
||||
}: ExternalFaviconProps) {
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Normalize the URL to ensure it has a protocol
|
||||
const normalizedUrl = normalizeUrl(url);
|
||||
|
||||
// Generate the favicon URL using the configured template
|
||||
const faviconSrc = faviconUrl(config.faviconUrl, normalizedUrl);
|
||||
|
||||
return (
|
||||
<span className={`inline-flex items-center justify-center ${className}`}>
|
||||
<img
|
||||
src={faviconSrc}
|
||||
alt=""
|
||||
className="object-contain"
|
||||
style={{ width: size, height: size }}
|
||||
onError={(e) => {
|
||||
// Hide the image and show the fallback on error
|
||||
e.currentTarget.style.display = 'none';
|
||||
const fallbackElement = e.currentTarget.nextElementSibling as HTMLElement;
|
||||
if (fallbackElement) {
|
||||
fallbackElement.style.display = 'inline-block';
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{fallback && (
|
||||
<span style={{ display: 'none' }}>
|
||||
{fallback}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
@@ -21,13 +20,6 @@ import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
GitBranch,
|
||||
Upload,
|
||||
@@ -43,9 +35,6 @@ import {
|
||||
AlertTriangle,
|
||||
Zap,
|
||||
Save,
|
||||
Settings2,
|
||||
GitPullRequest,
|
||||
ExternalLink,
|
||||
} from 'lucide-react';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
@@ -54,14 +43,11 @@ import { useToast } from '@/hooks/useToast';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { usePullRequests } from '@/hooks/usePullRequests';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { GitManagementDialog } from '@/components/git/GitManagementDialog';
|
||||
import { MergeDialog } from '@/components/git/MergeDialog';
|
||||
import { PullRequestDialog } from '@/components/git/PullRequestDialog';
|
||||
|
||||
const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev"];
|
||||
|
||||
interface GitDialogProps {
|
||||
projectId: string;
|
||||
@@ -79,14 +65,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
|
||||
// Branch management state
|
||||
const [branches, setBranches] = useState<string[]>([]);
|
||||
const [isLoadingBranches, setIsLoadingBranches] = useState(false);
|
||||
const [isSwitchingBranch, setIsSwitchingBranch] = useState(false);
|
||||
const [isCreatingBranch, setIsCreatingBranch] = useState(false);
|
||||
const [newBranchName, setNewBranchName] = useState('');
|
||||
const [isCreateBranchDialogOpen, setIsCreateBranchDialogOpen] = useState(false);
|
||||
|
||||
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
|
||||
const { settings } = useGitSettings();
|
||||
const { git } = useGit();
|
||||
@@ -94,8 +72,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const { data: pullRequests, isLoading: isLoadingPRs } = usePullRequests(originUrl);
|
||||
const { config } = useAppContext();
|
||||
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
@@ -107,111 +83,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
}
|
||||
}, [gitStatus?.remotes]);
|
||||
|
||||
const loadBranches = useCallback(async () => {
|
||||
setIsLoadingBranches(true);
|
||||
try {
|
||||
const localBranches = await git.listBranches({ dir: projectPath });
|
||||
setBranches(localBranches);
|
||||
} catch (error) {
|
||||
console.error('Failed to load branches:', error);
|
||||
} finally {
|
||||
setIsLoadingBranches(false);
|
||||
}
|
||||
}, [git, projectPath]);
|
||||
|
||||
// Load branches when dialog opens
|
||||
useEffect(() => {
|
||||
if (open && gitStatus?.isGitRepo) {
|
||||
loadBranches();
|
||||
}
|
||||
}, [open, gitStatus?.isGitRepo, loadBranches]);
|
||||
|
||||
const handleSwitchBranch = async (branchName: string) => {
|
||||
setIsSwitchingBranch(true);
|
||||
try {
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: branchName,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Branch switched',
|
||||
description: `Switched to branch "${branchName}"`,
|
||||
});
|
||||
|
||||
await refetchGitStatus();
|
||||
|
||||
// Trigger rebuild
|
||||
const newSearchParams = new URLSearchParams(searchParams);
|
||||
newSearchParams.set('build', '');
|
||||
setSearchParams(newSearchParams);
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Failed to switch branch',
|
||||
description: error instanceof Error ? error.message : 'Unknown error',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsSwitchingBranch(false);
|
||||
}
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
setIsCreatingBranch(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,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Branch created',
|
||||
description: `Created branch "${newBranchName}"`,
|
||||
});
|
||||
|
||||
setNewBranchName('');
|
||||
setIsCreateBranchDialogOpen(false);
|
||||
await loadBranches();
|
||||
await refetchGitStatus();
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Failed to create branch',
|
||||
description: error instanceof Error ? error.message : 'Unknown error',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsCreatingBranch(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveOrigin = async () => {
|
||||
if (!gitStatus?.isGitRepo) {
|
||||
toast({
|
||||
@@ -303,10 +174,10 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
}
|
||||
|
||||
// Create repo announcement event (NIP-34 kind 30617)
|
||||
const cloneUrls = config.ngitServers.map(server =>
|
||||
const cloneUrls = GRASP_SERVERS.map(server =>
|
||||
`https://${server}/${nip19.npubEncode(user.pubkey)}/${projectId}.git`
|
||||
);
|
||||
const relayUrls = config.ngitServers.map(server => `wss://${server}`);
|
||||
const relayUrls = GRASP_SERVERS.map(server => `wss://${server}`);
|
||||
|
||||
await publishEvent({
|
||||
kind: 30617,
|
||||
@@ -424,8 +295,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
});
|
||||
|
||||
// Set origin remote to Nostr URL
|
||||
// Format: nostr://<npub>/<repo-id>
|
||||
const nostrUrl = `nostr://${nip19.npubEncode(user.pubkey)}/${projectId}`;
|
||||
const nostrUrl = `nostr://${nip19.npubEncode(user.pubkey)}/git.shakespeare.diy/${projectId}`;
|
||||
|
||||
try {
|
||||
// Remove existing origin if it exists
|
||||
@@ -680,525 +550,256 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
|
||||
const syncStatus = getSyncStatus();
|
||||
|
||||
const [isGitManagementOpen, setIsGitManagementOpen] = useState(false);
|
||||
const [gitManagementDefaultTab, setGitManagementDefaultTab] = useState<string>('branches');
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
{children && <DialogTrigger asChild>{children}</DialogTrigger>}
|
||||
<DialogContent className="max-w-2xl h-[90vh] flex flex-col p-0 overflow-hidden" onOpenAutoFocus={(e) => e.preventDefault()}>
|
||||
<DialogHeader className="flex-shrink-0 px-6 pt-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<GitBranch className="h-5 w-5" />
|
||||
Repository
|
||||
</DialogTitle>
|
||||
{gitStatus?.isGitRepo && (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
{children && <DialogTrigger asChild>{children}</DialogTrigger>}
|
||||
<DialogContent className="max-w-2xl max-h-[80vh]" onOpenAutoFocus={(e) => e.preventDefault()}>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<GitBranch className="h-5 w-5" />
|
||||
Repository
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{/* URL Configuration */}
|
||||
{gitStatus?.isGitRepo && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm">Git URL</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex gap-2">
|
||||
<div className="flex-1">
|
||||
<Label htmlFor="origin-url" className="sr-only">
|
||||
URL
|
||||
</Label>
|
||||
<Input
|
||||
id="origin-url"
|
||||
placeholder="https://github.com/username/repository.git"
|
||||
value={originUrl}
|
||||
onChange={(e) => setOriginUrl(e.target.value)}
|
||||
disabled={isSavingOrigin}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={handleSaveOrigin}
|
||||
disabled={isSavingOrigin}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-2"
|
||||
onClick={() => {
|
||||
setGitManagementDefaultTab('branches');
|
||||
setIsGitManagementOpen(true);
|
||||
onOpenChange?.(false);
|
||||
}}
|
||||
className="h-10 shrink-0"
|
||||
>
|
||||
<Settings2 className="h-4 w-4" />
|
||||
Advanced
|
||||
{isSavingOrigin ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isSavingOrigin ? 'Saving...' : 'Save'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-hidden px-6 pb-6">
|
||||
<ScrollArea className="h-full">
|
||||
<div className="space-y-4 pr-4">
|
||||
{/* Section 1: Git URL, Current Branch, Sync Status, Merge Branch */}
|
||||
{gitStatus?.isGitRepo && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm">Repository Info</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Git URL */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="origin-url" className="text-xs font-medium text-muted-foreground">
|
||||
Git URL
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="origin-url"
|
||||
placeholder="https://github.com/username/repository.git"
|
||||
value={originUrl}
|
||||
onChange={(e) => setOriginUrl(e.target.value)}
|
||||
disabled={isSavingOrigin}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
onClick={handleSaveOrigin}
|
||||
disabled={isSavingOrigin}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-10 shrink-0"
|
||||
>
|
||||
{isSavingOrigin ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isSavingOrigin ? 'Saving...' : 'Save'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Credentials Warning */}
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
(() => {
|
||||
const remoteWithoutCredentials = gitStatus.remotes.find((remote) => !findCredentialsForRepo(remote.url, settings.credentials));
|
||||
if (!remoteWithoutCredentials) return null;
|
||||
|
||||
let protocol = '';
|
||||
let hostname = 'the remote host';
|
||||
try {
|
||||
const url = new URL(remoteWithoutCredentials.url);
|
||||
protocol = url.protocol;
|
||||
hostname = url.hostname;
|
||||
} catch {
|
||||
return (
|
||||
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50 mt-2">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
Invalid URL format. Enter an https URL.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
if (protocol !== 'https:' && protocol !== 'nostr:') {
|
||||
return (
|
||||
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50 mt-2">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
The {protocol.replace(':', '')} URL type is not supported. Enter an https URL.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
if (protocol === 'nostr:' && !user) {
|
||||
return (
|
||||
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50 mt-2">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
You are not logged into Nostr. Push & pull might not work unless you{' '}
|
||||
<button
|
||||
onClick={() => navigate('/settings/nostr')}
|
||||
className="underline hover:no-underline font-medium text-amber-700 dark:text-amber-300"
|
||||
>
|
||||
log in
|
||||
</button>.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
if (protocol === 'https:') {
|
||||
return (
|
||||
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50 mt-2">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
You are not logged into {hostname}. Push & pull might not work unless you{' '}
|
||||
<button
|
||||
onClick={() => navigate('/settings/git')}
|
||||
className="underline hover:no-underline font-medium text-amber-700 dark:text-amber-300"
|
||||
>
|
||||
log in
|
||||
</button>.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
})()
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Current Branch */}
|
||||
{gitStatus.currentBranch && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs font-medium text-muted-foreground">
|
||||
Current Branch
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<Select
|
||||
value={gitStatus.currentBranch}
|
||||
onValueChange={handleSwitchBranch}
|
||||
disabled={isSwitchingBranch || isLoadingBranches}
|
||||
>
|
||||
<SelectTrigger className="flex-1">
|
||||
<SelectValue>
|
||||
{isSwitchingBranch ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Switching...
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-2">
|
||||
<GitBranch className="h-4 w-4" />
|
||||
{gitStatus.currentBranch}
|
||||
</span>
|
||||
)}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{branches.map((branch) => (
|
||||
<SelectItem key={branch} value={branch}>
|
||||
<span className="flex items-center gap-2">
|
||||
{branch === gitStatus.currentBranch && (
|
||||
<CheckCircle className="h-4 w-4 text-primary" />
|
||||
)}
|
||||
{branch}
|
||||
</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="shrink-0"
|
||||
onClick={() => setIsCreateBranchDialogOpen(true)}
|
||||
disabled={isSwitchingBranch}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Sync Status */}
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs font-medium text-muted-foreground">
|
||||
Sync Status
|
||||
</Label>
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<syncStatus.icon className={cn("h-4 w-4", syncStatus.color)} />
|
||||
<span className={cn("text-sm font-medium", syncStatus.color)}>
|
||||
{syncStatus.text}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handlePull}
|
||||
disabled={isPulling || isPushing || isPushingToNostr}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
>
|
||||
{isPulling ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isPulling ? 'Pulling...' : 'Pull'}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={handlePush}
|
||||
disabled={isPushing || isPulling || isPushingToNostr || gitStatus.ahead === 0}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
>
|
||||
{isPushing ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Upload className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isPushing ? 'Pushing...' : 'Push'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{gitStatus.remotes.length === 0 && user && (
|
||||
<Button
|
||||
onClick={handlePushToNostr}
|
||||
disabled={isPushingToNostr || isPushing || isPulling}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
>
|
||||
{isPushingToNostr ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isPushingToNostr ? 'Publishing to Nostr...' : 'Push to Nostr'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Merge Branch Action */}
|
||||
{gitStatus.currentBranch && (
|
||||
<div className="pt-2 border-t">
|
||||
<MergeDialog
|
||||
projectId={projectId}
|
||||
currentBranch={gitStatus.currentBranch}
|
||||
onMergeComplete={() => refetchGitStatus()}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Section 2: Your Open PRs and Create PR Button */}
|
||||
{gitStatus?.isGitRepo && gitStatus.remotes.length > 0 && originUrl && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm">
|
||||
{originUrl.startsWith('nostr://') ? 'Patches' : 'Pull Requests'}
|
||||
</CardTitle>
|
||||
<CardDescription className="text-xs">
|
||||
{originUrl.startsWith('nostr://')
|
||||
? 'Submit patches to the repository'
|
||||
: 'Manage pull requests for this repository'
|
||||
}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{/* Open Pull Requests List */}
|
||||
{!originUrl.startsWith('nostr://') && isLoadingPRs && (
|
||||
<div className="flex items-center justify-center py-4 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Loading pull requests...
|
||||
</div>
|
||||
)}
|
||||
{!isLoadingPRs && pullRequests && pullRequests.length > 0 && (
|
||||
<div className="space-y-2 mb-3">
|
||||
<div className="text-xs font-medium text-muted-foreground mb-2">
|
||||
{pullRequests.some(pr => !pr.isOwner)
|
||||
? (originUrl.startsWith('nostr://') ? 'Incoming Patches' : 'Incoming PRs')
|
||||
: (originUrl.startsWith('nostr://') ? 'Your Patches' : 'Your Open PRs')
|
||||
}
|
||||
</div>
|
||||
{pullRequests.map((pr) => (
|
||||
<div
|
||||
key={pr.id}
|
||||
className="p-3 rounded-md border bg-muted/20 hover:bg-muted/40 transition-colors space-y-2"
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<GitPullRequest className={cn(
|
||||
"h-4 w-4 mt-0.5 shrink-0",
|
||||
pr.state === 'merged' ? 'text-purple-600' : 'text-green-600'
|
||||
)} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<h4 className="text-sm font-medium truncate">
|
||||
{pr.title}
|
||||
</h4>
|
||||
{pr.state === 'merged' && (
|
||||
<Badge variant="secondary" className="text-xs shrink-0">
|
||||
Merged
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
#{pr.number} by {pr.isOwner ? 'you' : pr.author} • {pr.sourceBranch} → {pr.targetBranch}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions row */}
|
||||
{(!pr.isOwner && pr.state === 'open') || !originUrl.startsWith('nostr://') ? (
|
||||
<div className="flex items-center gap-2 pl-7">
|
||||
{!pr.isOwner && pr.state === 'open' && (
|
||||
<>
|
||||
{!originUrl.startsWith('nostr://') && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 text-xs"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: pr.sourceBranch,
|
||||
});
|
||||
await refetchGitStatus();
|
||||
toast({
|
||||
title: 'Branch checked out',
|
||||
description: `Switched to ${pr.sourceBranch}`,
|
||||
});
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: 'Checkout failed',
|
||||
description: err instanceof Error ? err.message : 'Unknown error',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
<GitBranch className="h-3 w-3 mr-1" />
|
||||
Review
|
||||
</Button>
|
||||
)}
|
||||
<MergeDialog
|
||||
projectId={projectId}
|
||||
currentBranch={gitStatus.currentBranch}
|
||||
sourceBranch={pr.sourceBranch}
|
||||
targetBranch={pr.targetBranch}
|
||||
onMergeComplete={refetchGitStatus}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{!originUrl.startsWith('nostr://') && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 text-xs ml-auto"
|
||||
onClick={() => window.open(pr.url, '_blank')}
|
||||
>
|
||||
<ExternalLink className="h-3 w-3 mr-1" />
|
||||
View
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Create PR/Patch Button */}
|
||||
<PullRequestDialog
|
||||
projectId={projectId}
|
||||
currentBranch={gitStatus.currentBranch}
|
||||
remoteUrl={originUrl}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Section 3: Working Directory */}
|
||||
{gitStatus?.isGitRepo && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm">Working Directory</CardTitle>
|
||||
{gitStatus.changedFiles.length > 0 && (
|
||||
<CardDescription>
|
||||
{gitStatus.changedFiles.length} file{gitStatus.changedFiles.length !== 1 ? 's' : ''} with changes
|
||||
</CardDescription>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{gitStatus.changedFiles.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{gitStatus.changedFiles.map((file, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center gap-2 p-2 rounded-md border bg-muted/20"
|
||||
>
|
||||
{getFileStatusIcon(file.status)}
|
||||
<span className="font-mono text-sm flex-1 truncate">
|
||||
{file.filepath}
|
||||
</span>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn("text-xs", getFileStatusColor(file.status))}
|
||||
>
|
||||
{file.status}
|
||||
</Badge>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center text-muted-foreground py-6">
|
||||
<CheckCircle className="h-8 w-8 mx-auto mb-2 text-green-500" />
|
||||
<p>Working directory is clean</p>
|
||||
<p className="text-xs">No uncommitted changes</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Advanced Git Management Dialog */}
|
||||
<GitManagementDialog
|
||||
projectId={projectId}
|
||||
open={isGitManagementOpen}
|
||||
onOpenChange={setIsGitManagementOpen}
|
||||
defaultTab={gitManagementDefaultTab}
|
||||
/>
|
||||
{/* Credentials Warning */}
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
(() => {
|
||||
const remoteWithoutCredentials = gitStatus.remotes.find((remote) => !findCredentialsForRepo(remote.url, settings.credentials));
|
||||
if (!remoteWithoutCredentials) return null;
|
||||
|
||||
{/* Create Branch Dialog */}
|
||||
<Dialog open={isCreateBranchDialogOpen} onOpenChange={setIsCreateBranchDialogOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create New Branch</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create a new branch from {gitStatus?.currentBranch || 'current HEAD'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="new-branch-name">Branch Name</Label>
|
||||
<Input
|
||||
id="new-branch-name"
|
||||
placeholder="feature/my-new-feature"
|
||||
value={newBranchName}
|
||||
onChange={(e) => setNewBranchName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && !isCreatingBranch) {
|
||||
handleCreateBranch();
|
||||
let protocol = '';
|
||||
let hostname = 'the remote host';
|
||||
try {
|
||||
const url = new URL(remoteWithoutCredentials.url);
|
||||
protocol = url.protocol;
|
||||
hostname = url.hostname;
|
||||
} catch {
|
||||
// Invalid URL
|
||||
return (
|
||||
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
Invalid URL format. Enter an https URL.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
{gitStatus?.currentBranch && (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Creating from: <span className="font-medium">{gitStatus.currentBranch}</span>
|
||||
</div>
|
||||
|
||||
// Check for unsupported protocols
|
||||
if (protocol !== 'https:' && protocol !== 'nostr:') {
|
||||
return (
|
||||
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
The {protocol.replace(':', '')} URL type is not supported. Enter an https URL.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
// For nostr protocol, only show warning if user is not logged in
|
||||
if (protocol === 'nostr:' && !user) {
|
||||
return (
|
||||
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
You are not logged into Nostr. Push & pull might not work unless you{' '}
|
||||
<button
|
||||
onClick={() => navigate('/settings/nostr')}
|
||||
className="underline hover:no-underline font-medium text-amber-700 dark:text-amber-300"
|
||||
>
|
||||
log in
|
||||
</button>.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
// For https protocol, show warning if no credentials
|
||||
if (protocol === 'https:') {
|
||||
return (
|
||||
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
You are not logged into {hostname}. Push & pull might not work unless you{' '}
|
||||
<button
|
||||
onClick={() => navigate('/settings/git')}
|
||||
className="underline hover:no-underline font-medium text-amber-700 dark:text-amber-300"
|
||||
>
|
||||
log in
|
||||
</button>.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
})()
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<ScrollArea className="max-h-[60vh]">
|
||||
<div className="space-y-4">
|
||||
|
||||
{/* Sync Status */}
|
||||
{gitStatus?.isGitRepo && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm">Sync Status</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<syncStatus.icon className={cn("h-4 w-4", syncStatus.color)} />
|
||||
<span className={cn("text-sm font-medium", syncStatus.color)}>
|
||||
{syncStatus.text}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handlePull}
|
||||
disabled={isPulling || isPushing || isPushingToNostr}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
>
|
||||
{isPulling ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isPulling ? 'Pulling...' : 'Pull'}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={handlePush}
|
||||
disabled={isPushing || isPulling || isPushingToNostr || gitStatus.ahead === 0}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
>
|
||||
{isPushing ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Upload className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isPushing ? 'Pushing...' : 'Push'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Push to Nostr button when no remote is configured and user is logged in */}
|
||||
{gitStatus.remotes.length === 0 && user && (
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handlePushToNostr}
|
||||
disabled={isPushingToNostr || isPushing || isPulling}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
>
|
||||
{isPushingToNostr ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isPushingToNostr ? 'Publishing to Nostr...' : 'Push to Nostr'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Working Directory Changes */}
|
||||
{gitStatus?.isGitRepo && gitStatus.changedFiles.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm">Working Directory Changes</CardTitle>
|
||||
<CardDescription>
|
||||
{gitStatus.changedFiles.length} file{gitStatus.changedFiles.length !== 1 ? 's' : ''} with changes
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{gitStatus.changedFiles.map((file, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center gap-2 p-2 rounded-md border bg-muted/20"
|
||||
>
|
||||
{getFileStatusIcon(file.status)}
|
||||
<span className="font-mono text-sm flex-1 truncate">
|
||||
{file.filepath}
|
||||
</span>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn("text-xs", getFileStatusColor(file.status))}
|
||||
>
|
||||
{file.status}
|
||||
</Badge>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Clean Working Directory */}
|
||||
{gitStatus?.isGitRepo && gitStatus.changedFiles.length === 0 && (
|
||||
<Card>
|
||||
<CardContent className="py-6">
|
||||
<div className="text-center text-muted-foreground">
|
||||
<CheckCircle className="h-8 w-8 mx-auto mb-2 text-green-500" />
|
||||
<p>Working directory is clean</p>
|
||||
<p className="text-xs">No uncommitted changes</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setIsCreateBranchDialogOpen(false);
|
||||
setNewBranchName('');
|
||||
}}
|
||||
disabled={isCreatingBranch}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleCreateBranch} disabled={isCreatingBranch}>
|
||||
{isCreatingBranch ? (
|
||||
<>
|
||||
<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>
|
||||
</>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -14,7 +14,7 @@ vi.mock('@/lib/configUtils', () => ({
|
||||
|
||||
// Test component that uses the hook
|
||||
function TestComponent() {
|
||||
const { settings, addCredential, removeCredential, updateCredential, isConfigured } = useGitSettings();
|
||||
const { settings, updateSettings, addCredential, removeCredential, updateCredential, isConfigured } = useGitSettings();
|
||||
|
||||
const handleAdd = () => {
|
||||
const credential: GitCredential = {
|
||||
@@ -32,13 +32,21 @@ function TestComponent() {
|
||||
removeCredential('https://github.com');
|
||||
};
|
||||
|
||||
const handleUpdateCorsProxy = () => {
|
||||
updateSettings({ corsProxy: 'https://custom-cors.example.com' });
|
||||
};
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div data-testid="configured">{isConfigured ? 'configured' : 'not-configured'}</div>
|
||||
<div data-testid="count">{Object.keys(settings.credentials).length}</div>
|
||||
<div data-testid="cors-proxy">{settings.corsProxy}</div>
|
||||
<button onClick={handleAdd}>Add GitHub</button>
|
||||
<button onClick={handleUpdate}>Update GitHub</button>
|
||||
<button onClick={handleRemove}>Remove GitHub</button>
|
||||
<button onClick={handleUpdateCorsProxy}>Update CORS Proxy</button>
|
||||
{settings.credentials['https://github.com'] && (
|
||||
<div data-testid="github-creds">
|
||||
{settings.credentials['https://github.com'].username}:
|
||||
@@ -68,7 +76,7 @@ describe('GitSettingsProvider', () => {
|
||||
const { readGitSettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readGitSettings).mockResolvedValue({
|
||||
credentials: {},
|
||||
hostTokens: {},
|
||||
corsProxy: 'https://cors.isomorphic-git.org',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -170,7 +178,8 @@ describe('GitSettingsProvider', () => {
|
||||
username: 'git',
|
||||
password: 'test-token',
|
||||
}
|
||||
}
|
||||
},
|
||||
corsProxy: 'https://proxy.shakespeare.diy/?url={href}'
|
||||
})
|
||||
);
|
||||
});
|
||||
@@ -184,7 +193,7 @@ describe('GitSettingsProvider', () => {
|
||||
password: 'gitlab-token',
|
||||
},
|
||||
},
|
||||
hostTokens: {},
|
||||
corsProxy: 'https://custom-cors.example.com',
|
||||
};
|
||||
|
||||
const { readGitSettings } = await import('@/lib/configUtils');
|
||||
@@ -199,8 +208,37 @@ describe('GitSettingsProvider', () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('configured')).toHaveTextContent('configured');
|
||||
expect(screen.getByTestId('count')).toHaveTextContent('1');
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://custom-cors.example.com');
|
||||
});
|
||||
});
|
||||
|
||||
it('provides default CORS proxy', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://proxy.shakespeare.diy/?url={href}');
|
||||
});
|
||||
});
|
||||
|
||||
it('can update CORS proxy', async () => {
|
||||
render(
|
||||
<TestWrapper>
|
||||
<TestComponent />
|
||||
</TestWrapper>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://proxy.shakespeare.diy/?url={href}');
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText('Update CORS Proxy'));
|
||||
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://custom-cors.example.com');
|
||||
});
|
||||
|
||||
|
||||
});
|
||||
@@ -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 { readGitSettings, writeGitSettings } from '@/lib/configUtils';
|
||||
|
||||
@@ -9,7 +9,7 @@ interface GitSettingsProviderProps {
|
||||
|
||||
const DEFAULT_SETTINGS: GitSettings = {
|
||||
credentials: {},
|
||||
hostTokens: {},
|
||||
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
|
||||
};
|
||||
|
||||
export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
@@ -22,6 +22,10 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
const initializeSettings = async () => {
|
||||
try {
|
||||
const settings = await readGitSettings(fs);
|
||||
// Migrate old CORS proxy format
|
||||
if (settings.corsProxy === 'https://cors.isomorphic-git.org') {
|
||||
settings.corsProxy = DEFAULT_SETTINGS.corsProxy;
|
||||
}
|
||||
setSettings(settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize Git settings:', error);
|
||||
@@ -86,39 +90,6 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
}));
|
||||
};
|
||||
|
||||
const addHostToken = (host: string, token: GitHostToken) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
hostTokens: {
|
||||
...prev.hostTokens,
|
||||
[host]: token,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
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 contextValue: GitSettingsContextType = {
|
||||
@@ -127,11 +98,7 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
addCredential,
|
||||
removeCredential,
|
||||
updateCredential,
|
||||
addHostToken,
|
||||
removeHostToken,
|
||||
updateHostToken,
|
||||
isConfigured,
|
||||
isInitialized,
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import { Decimal } from 'decimal.js';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ModelPricingProps {
|
||||
pricing: { prompt: Decimal; completion: Decimal };
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single normalized "price per token" for a model,
|
||||
* combining input and output pricing with agentic-coding-aware weights.
|
||||
*
|
||||
* Default behavior:
|
||||
* - Uses inputWeight = 0.20 (based on typical 3–5x output premium seen in practice).
|
||||
*
|
||||
* Optional behavior:
|
||||
* - If you pass observed token usage, the function will compute the weight
|
||||
* as the observed share of spend from inputs over total spend.
|
||||
*/
|
||||
function getNormalizedModelPrice(
|
||||
pricing: { prompt: Decimal; completion: Decimal },
|
||||
inputWeight = 0.2,
|
||||
): Decimal {
|
||||
if (!(inputWeight >= 0 && inputWeight <= 1)) {
|
||||
throw new Error("Computed inputWeight is out of range [0,1]. Check inputs.");
|
||||
}
|
||||
if (pricing.prompt.equals(0) && pricing.completion.equals(0)) {
|
||||
return new Decimal(0);
|
||||
}
|
||||
const outputWeight = 1 - inputWeight;
|
||||
return pricing.prompt.times(inputWeight).plus(pricing.completion.times(outputWeight));
|
||||
}
|
||||
|
||||
export function ModelPricing({ pricing, className }: ModelPricingProps) {
|
||||
const normalizedPrice = getNormalizedModelPrice(pricing).times(1_000_000).toNumber();
|
||||
|
||||
if (normalizedPrice === 0) {
|
||||
return <span className={cn("text-green-600 font-semibold", className)}>Free</span>;
|
||||
} else if (normalizedPrice < 10) {
|
||||
return <span className={cn("text-green-600 font-semibold", className)}>$</span>;
|
||||
} else if (normalizedPrice >= 10 && normalizedPrice < 15) {
|
||||
return <span className={cn("text-yellow-600 font-semibold", className)}>$$</span>;
|
||||
} else if (normalizedPrice >= 15 && normalizedPrice < 50) {
|
||||
return <span className={cn("text-red-600 font-semibold", className)}>$$$</span>;
|
||||
} else if (normalizedPrice >= 50) {
|
||||
return <span className={cn("text-red-800 font-semibold", className)}>$$$$</span>;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { Decimal } from 'decimal.js';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { ModelSelector } from './ModelSelector';
|
||||
|
||||
@@ -14,10 +12,6 @@ vi.mock('@/hooks/useProviderModels', () => ({
|
||||
useProviderModels: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useIsMobile', () => ({
|
||||
useIsMobile: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('react-router-dom', async (importOriginal) => {
|
||||
const actual = await importOriginal() as Record<string, unknown>;
|
||||
return {
|
||||
@@ -28,11 +22,9 @@ vi.mock('react-router-dom', async (importOriginal) => {
|
||||
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
|
||||
const mockUseAISettings = vi.mocked(useAISettings);
|
||||
const mockUseProviderModels = vi.mocked(useProviderModels);
|
||||
const mockUseIsMobile = vi.mocked(useIsMobile);
|
||||
|
||||
describe('ModelSelector', () => {
|
||||
const mockOnChange = vi.fn();
|
||||
@@ -49,7 +41,7 @@ describe('ModelSelector', () => {
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
});
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
@@ -58,8 +50,6 @@ describe('ModelSelector', () => {
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
mockUseIsMobile.mockReturnValue(false);
|
||||
});
|
||||
|
||||
it('hides recently used section when less than 5 models and all recently used are available', async () => {
|
||||
@@ -87,7 +77,7 @@ describe('ModelSelector', () => {
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
});
|
||||
|
||||
render(
|
||||
@@ -102,17 +92,11 @@ describe('ModelSelector', () => {
|
||||
|
||||
// Wait for the dropdown to open
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('provider2')).toBeInTheDocument();
|
||||
expect(screen.getByText('provider1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Recently used section should NOT be visible
|
||||
expect(screen.queryByText('Recently Used')).not.toBeInTheDocument();
|
||||
|
||||
// provider1 should be hidden since all its models are in recently used
|
||||
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
|
||||
|
||||
// provider2 should still show with model3
|
||||
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows recently used section when less than 5 models but some recently used are not available', async () => {
|
||||
@@ -140,7 +124,7 @@ describe('ModelSelector', () => {
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
});
|
||||
|
||||
render(
|
||||
@@ -189,7 +173,7 @@ describe('ModelSelector', () => {
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
});
|
||||
|
||||
render(
|
||||
@@ -204,19 +188,11 @@ describe('ModelSelector', () => {
|
||||
|
||||
// Wait for the dropdown to open
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('provider2')).toBeInTheDocument();
|
||||
expect(screen.getByText('provider1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Recently used section SHOULD be visible
|
||||
expect(screen.getByText('Recently Used')).toBeInTheDocument();
|
||||
|
||||
// provider1 should be hidden since all its models are in recently used
|
||||
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
|
||||
|
||||
// provider2 and provider3 should still show
|
||||
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
|
||||
expect(screen.getByText('provider2/model4')).toBeInTheDocument();
|
||||
expect(screen.getByText('provider3/model5')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides recently used section when no recently used models exist', async () => {
|
||||
@@ -240,7 +216,7 @@ describe('ModelSelector', () => {
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
});
|
||||
|
||||
render(
|
||||
@@ -261,374 +237,4 @@ describe('ModelSelector', () => {
|
||||
// Recently used section should NOT be visible
|
||||
expect(screen.queryByText('Recently Used')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows caution icon for free models', async () => {
|
||||
const freeModel = {
|
||||
fullId: 'provider1/free-model',
|
||||
provider: 'provider1',
|
||||
id: 'free-model',
|
||||
pricing: {
|
||||
prompt: new Decimal('0'),
|
||||
completion: new Decimal('0'),
|
||||
},
|
||||
};
|
||||
|
||||
const paidModel = {
|
||||
fullId: 'provider1/paid-model',
|
||||
provider: 'provider1',
|
||||
id: 'paid-model',
|
||||
pricing: {
|
||||
prompt: new Decimal('0.01'),
|
||||
completion: new Decimal('0.02'),
|
||||
},
|
||||
};
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: [freeModel, paidModel],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
// Test with free model selected
|
||||
const { rerender } = render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show caution icon for free model
|
||||
expect(screen.getByTestId('triangle-alert')).toBeInTheDocument();
|
||||
|
||||
// Test with paid model selected
|
||||
rerender(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/paid-model" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should not show caution icon for paid model
|
||||
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show caution icon when no model is selected', () => {
|
||||
const freeModel = {
|
||||
fullId: 'provider1/free-model',
|
||||
provider: 'provider1',
|
||||
id: 'free-model',
|
||||
pricing: {
|
||||
prompt: new Decimal('0'),
|
||||
completion: new Decimal('0'),
|
||||
},
|
||||
};
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: [freeModel],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should not show caution icon when no model is selected
|
||||
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show caution icon for models without pricing information', () => {
|
||||
const modelWithoutPricing = {
|
||||
fullId: 'provider1/unknown-pricing',
|
||||
provider: 'provider1',
|
||||
id: 'unknown-pricing',
|
||||
// No pricing property
|
||||
};
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: [modelWithoutPricing],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/unknown-pricing" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should not show caution icon for models without pricing info
|
||||
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows tooltip when hovering over caution icon', async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
const freeModel = {
|
||||
fullId: 'provider1/free-model',
|
||||
provider: 'provider1',
|
||||
id: 'free-model',
|
||||
pricing: {
|
||||
prompt: new Decimal('0'),
|
||||
completion: new Decimal('0'),
|
||||
},
|
||||
};
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: [freeModel],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const cautionIcon = screen.getByTestId('triangle-alert');
|
||||
expect(cautionIcon).toBeInTheDocument();
|
||||
|
||||
// Hover over the caution icon
|
||||
await user.hover(cautionIcon);
|
||||
|
||||
// Wait for tooltip to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('makes caution icon tappable on mobile with click-to-toggle tooltip', async () => {
|
||||
const user = userEvent.setup();
|
||||
mockUseIsMobile.mockReturnValue(true);
|
||||
|
||||
const freeModel = {
|
||||
fullId: 'provider1/free-model',
|
||||
provider: 'provider1',
|
||||
id: 'free-model',
|
||||
pricing: {
|
||||
prompt: new Decimal('0'),
|
||||
completion: new Decimal('0'),
|
||||
},
|
||||
};
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: [freeModel],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const cautionButton = screen.getByRole('button', { name: 'Model warning' });
|
||||
expect(cautionButton).toBeInTheDocument();
|
||||
expect(cautionButton).toHaveAttribute('tabIndex', '0'); // Should be tappable on mobile
|
||||
|
||||
// Click to open tooltip - just verify the click works without errors
|
||||
await user.click(cautionButton);
|
||||
|
||||
// Tooltip should appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
// The button should still be clickable (no errors)
|
||||
await user.click(cautionButton);
|
||||
expect(cautionButton).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('makes caution icon not focusable on desktop', () => {
|
||||
mockUseIsMobile.mockReturnValue(false);
|
||||
|
||||
const freeModel = {
|
||||
fullId: 'provider1/free-model',
|
||||
provider: 'provider1',
|
||||
id: 'free-model',
|
||||
pricing: {
|
||||
prompt: new Decimal('0'),
|
||||
completion: new Decimal('0'),
|
||||
},
|
||||
};
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: [freeModel],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const cautionButton = screen.getByRole('button', { name: 'Model warning' });
|
||||
expect(cautionButton).toBeInTheDocument();
|
||||
expect(cautionButton).toHaveAttribute('tabIndex', '-1'); // Should not be focusable on desktop
|
||||
});
|
||||
|
||||
it('shows warning icon when selected model is not in provider models list', () => {
|
||||
const availableModels = [
|
||||
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
|
||||
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
|
||||
];
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: availableModels,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/unknown-model" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show warning icon for model not in list
|
||||
expect(screen.getByTestId('triangle-alert')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show warning icon when selected model is in provider models list', () => {
|
||||
const availableModels = [
|
||||
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
|
||||
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
|
||||
];
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: availableModels,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/model1" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should not show warning icon when model is in list
|
||||
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show warning icon while models are loading', () => {
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: [],
|
||||
isLoading: true,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/unknown-model" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should not show warning icon while loading
|
||||
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not show warning icon when no models are loaded', () => {
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: [],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/some-model" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should not show warning icon when no models loaded
|
||||
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows correct tooltip message for model not in list', async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
const availableModels = [
|
||||
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
|
||||
];
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: availableModels,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/unknown-model" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const warningIcon = screen.getByTestId('triangle-alert');
|
||||
expect(warningIcon).toBeInTheDocument();
|
||||
|
||||
// Hover over the warning icon
|
||||
await user.hover(warningIcon);
|
||||
|
||||
// Wait for tooltip to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByText("This model is not available in your provider's model list. It may not work or may have been deprecated.").length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('prioritizes "not in list" warning over "free model" warning in tooltip', async () => {
|
||||
const user = userEvent.setup();
|
||||
|
||||
const freeModel = {
|
||||
fullId: 'provider1/free-model',
|
||||
provider: 'provider1',
|
||||
id: 'free-model',
|
||||
pricing: {
|
||||
prompt: new Decimal('0'),
|
||||
completion: new Decimal('0'),
|
||||
},
|
||||
};
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
models: [freeModel],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
refetch: vi.fn(),
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<ModelSelector value="provider1/unknown-free-model" onChange={mockOnChange} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const warningIcon = screen.getByTestId('triangle-alert');
|
||||
expect(warningIcon).toBeInTheDocument();
|
||||
|
||||
// Hover over the warning icon
|
||||
await user.hover(warningIcon);
|
||||
|
||||
// Wait for tooltip to appear - should show "not in list" message, not "free model" message
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByText("This model is not available in your provider's model list. It may not work or may have been deprecated.").length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
// Should not show the free model message
|
||||
expect(screen.queryByText('You are using a free model. For better results, switch to a paid model.')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,17 +1,14 @@
|
||||
import { useState, useMemo, useEffect, memo } from 'react';
|
||||
import { useState, useMemo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert } from 'lucide-react';
|
||||
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { ModelPricing } from '@/components/ModelPricing';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ModelSelectorProps {
|
||||
@@ -24,7 +21,7 @@ interface ModelSelectorProps {
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export const ModelSelector = memo(function ModelSelector({
|
||||
export function ModelSelector({
|
||||
value,
|
||||
onChange,
|
||||
className,
|
||||
@@ -35,7 +32,6 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
}: ModelSelectorProps) {
|
||||
const { t } = useTranslation();
|
||||
const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
|
||||
const [isTooltipOpen, setIsTooltipOpen] = useState(false);
|
||||
|
||||
// Use controlled state if provided, otherwise use local state
|
||||
const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen;
|
||||
@@ -46,31 +42,22 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
const { settings, addRecentlyUsedModel, isConfigured } = useAISettings();
|
||||
const { models, isLoading, error, refetch } = useProviderModels();
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
const defaultPlaceholder = t('selectOrEnterModel');
|
||||
|
||||
const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]);
|
||||
|
||||
// Create a Set of recently used model IDs for efficient lookup
|
||||
const recentlyUsedSet = useMemo(() => new Set(recentlyUsedModels), [recentlyUsedModels]);
|
||||
|
||||
// Group models by provider, excluding models that are in the recently used section
|
||||
// Group models by provider
|
||||
const modelsByProvider = useMemo(() => {
|
||||
const groups: Record<string, typeof models> = {};
|
||||
for (const model of models) {
|
||||
// Skip models that are already shown in recently used
|
||||
if (recentlyUsedSet.has(model.fullId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!groups[model.provider]) {
|
||||
groups[model.provider] = [];
|
||||
}
|
||||
groups[model.provider].push(model);
|
||||
}
|
||||
return groups;
|
||||
}, [models, recentlyUsedSet]);
|
||||
}, [models]);
|
||||
|
||||
// Determine if we should show the "Recently Used" section
|
||||
const shouldShowRecentlyUsed = useMemo(() => {
|
||||
@@ -95,67 +82,9 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
return !allRecentlyUsedAreAvailable;
|
||||
}, [recentlyUsedModels, models]);
|
||||
|
||||
// Check if the current model is free
|
||||
const isCurrentModelFree = useMemo(() => {
|
||||
if (!value) return false;
|
||||
|
||||
const currentModel = models.find(model => model.fullId === value);
|
||||
if (!currentModel?.pricing) return false;
|
||||
|
||||
return currentModel.pricing.prompt.equals(0) && currentModel.pricing.completion.equals(0);
|
||||
}, [value, models]);
|
||||
|
||||
// Check if the current model is not in the provider's model list
|
||||
const isCurrentModelNotInList = useMemo(() => {
|
||||
if (!value) return false;
|
||||
if (isLoading) return false; // Don't show warning while loading
|
||||
if (models.length === 0) return false; // Don't show warning if no models loaded
|
||||
|
||||
const currentModel = models.find(model => model.fullId === value);
|
||||
return !currentModel;
|
||||
}, [value, models, isLoading]);
|
||||
|
||||
// Determine if we should show the warning icon
|
||||
const shouldShowWarning = isCurrentModelFree || isCurrentModelNotInList;
|
||||
|
||||
// Get the warning message
|
||||
const warningMessage = useMemo(() => {
|
||||
if (isCurrentModelNotInList) {
|
||||
return "This model is not available in your provider's model list. It may not work or may have been deprecated.";
|
||||
}
|
||||
if (isCurrentModelFree) {
|
||||
return "You are using a free model. For better results, switch to a paid model.";
|
||||
}
|
||||
return "";
|
||||
}, [isCurrentModelNotInList, isCurrentModelFree]);
|
||||
|
||||
// Don't auto-initialize with recently used models
|
||||
// Let the parent component handle initialization
|
||||
|
||||
// Close tooltip when clicking outside on mobile
|
||||
useEffect(() => {
|
||||
if (!isMobile || !isTooltipOpen) return;
|
||||
|
||||
const handleClickOutside = (event: MouseEvent | TouchEvent) => {
|
||||
const target = event.target as Element;
|
||||
// Check if the click is outside the tooltip and trigger
|
||||
if (!target.closest('[data-radix-tooltip-content]') &&
|
||||
!target.closest('[data-radix-tooltip-trigger]') &&
|
||||
!target.closest('[data-testid="triangle-alert"]')) {
|
||||
setIsTooltipOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Add both click and touch event listeners
|
||||
document.addEventListener('click', handleClickOutside, true);
|
||||
document.addEventListener('touchstart', handleClickOutside, true);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('click', handleClickOutside, true);
|
||||
document.removeEventListener('touchstart', handleClickOutside, true);
|
||||
};
|
||||
}, [isMobile, isTooltipOpen]);
|
||||
|
||||
const handleSelect = (selectedValue: string) => {
|
||||
if (selectedValue === '__custom__') {
|
||||
setIsCustomInput(true);
|
||||
@@ -196,231 +125,169 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
|
||||
if (isCustomInput) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<div className={cn("flex items-center gap-1", className)}>
|
||||
<Input
|
||||
value={customValue}
|
||||
onChange={(e) => setCustomValue(e.target.value)}
|
||||
onKeyDown={handleCustomKeyDown}
|
||||
onBlur={handleCustomSubmit}
|
||||
placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)"
|
||||
className="h-8 text-xs"
|
||||
autoFocus
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 w-8 p-0"
|
||||
onClick={handleCustomSubmit}
|
||||
>
|
||||
<Check className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
<div className={cn("flex items-center gap-1", className)}>
|
||||
<Input
|
||||
value={customValue}
|
||||
onChange={(e) => setCustomValue(e.target.value)}
|
||||
onKeyDown={handleCustomKeyDown}
|
||||
onBlur={handleCustomSubmit}
|
||||
placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)"
|
||||
className="h-8 text-xs"
|
||||
autoFocus
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 w-8 p-0"
|
||||
onClick={handleCustomSubmit}
|
||||
>
|
||||
<Check className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<div className={cn("flex justify-end gap-0.5", className)}>
|
||||
{shouldShowWarning && (
|
||||
<Tooltip
|
||||
open={isMobile ? isTooltipOpen : undefined}
|
||||
onOpenChange={isMobile ? setIsTooltipOpen : undefined}
|
||||
delayDuration={isMobile ? 0 : 700}
|
||||
disableHoverableContent={isMobile}
|
||||
>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex items-center p-0 rounded-none border-0 bg-transparent hover:bg-transparent focus:bg-transparent active:bg-transparent focus:outline-none focus-visible:outline-none focus:ring-0 focus-visible:ring-0 focus:border-0 active:outline-none"
|
||||
aria-label="Model warning"
|
||||
tabIndex={isMobile ? 0 : -1}
|
||||
onClick={isMobile ? (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsTooltipOpen(!isTooltipOpen);
|
||||
} : undefined}
|
||||
onTouchStart={isMobile ? (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
} : undefined}
|
||||
onTouchEnd={isMobile ? (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsTooltipOpen(!isTooltipOpen);
|
||||
} : undefined}
|
||||
style={{
|
||||
WebkitTapHighlightColor: 'transparent',
|
||||
outline: 'none',
|
||||
border: 'none',
|
||||
boxShadow: 'none'
|
||||
}}
|
||||
>
|
||||
<TriangleAlert className="h-3 w-3 text-amber-500 flex-shrink-0" data-testid="triangle-alert" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="top"
|
||||
sideOffset={4}
|
||||
className="max-w-xs text-center"
|
||||
avoidCollisions={true}
|
||||
collisionPadding={8}
|
||||
>
|
||||
<p>{warningMessage}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
className={cn(
|
||||
"h-8 p-0 gap-0.5 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}
|
||||
>
|
||||
<span className="truncate">
|
||||
{value || placeholder || defaultPlaceholder}
|
||||
</span>
|
||||
<ChevronDown className="size-3 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="p-0 w-80" align="end">
|
||||
<Command>
|
||||
{(isConfigured && models.length >= 5) && (
|
||||
<CommandInput placeholder={t('searchModels')} className="h-9" />
|
||||
)}
|
||||
<CommandList>
|
||||
<CommandEmpty>
|
||||
<div className="py-6 text-center text-sm text-muted-foreground">
|
||||
<p>{t('noModelsFound')}</p>
|
||||
<p className="mt-2 text-xs">{t('tryCustomModel')}</p>
|
||||
</div>
|
||||
</CommandEmpty>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
className={cn(
|
||||
"h-8 p-0 gap-0.5 justify-between text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right",
|
||||
className
|
||||
)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<span className="w-full truncate">
|
||||
{value || placeholder || defaultPlaceholder}
|
||||
</span>
|
||||
<ChevronDown className="size-3 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-96 p-0" align="end">
|
||||
<Command>
|
||||
{(isConfigured && models.length >= 5) && (
|
||||
<CommandInput placeholder={t('searchModels')} className="h-9" />
|
||||
)}
|
||||
<CommandList className="max-h-[300px]">
|
||||
<CommandEmpty>
|
||||
<div className="py-6 text-center text-sm text-muted-foreground">
|
||||
<p>{t('noModelsFound')}</p>
|
||||
<p className="mt-2 text-xs">{t('tryCustomModel')}</p>
|
||||
</div>
|
||||
</CommandEmpty>
|
||||
|
||||
{shouldShowRecentlyUsed && (
|
||||
<CommandGroup heading={t('recentlyUsed')}>
|
||||
{recentlyUsedModels.map((modelId) => {
|
||||
const modelData = models.find(m => m.fullId === modelId);
|
||||
return (
|
||||
<CommandItem
|
||||
key={modelId}
|
||||
value={modelId}
|
||||
onSelect={() => handleSelect(modelId)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
value === modelId ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
<span className="truncate flex-1">{modelId}</span>
|
||||
{modelData?.pricing && (
|
||||
<ModelPricing pricing={modelData.pricing} className="ml-2" />
|
||||
)}
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</CommandGroup>
|
||||
)}
|
||||
|
||||
{shouldShowRecentlyUsed && <CommandSeparator />}
|
||||
|
||||
{/* Loading state */}
|
||||
{isLoading && (
|
||||
<CommandGroup heading={t('loading')}>
|
||||
<div className="px-2 py-1.5">
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4 w-1/2" />
|
||||
</div>
|
||||
</div>
|
||||
</CommandGroup>
|
||||
)}
|
||||
|
||||
{/* Error state */}
|
||||
{error && !isLoading && (
|
||||
<CommandGroup heading={t('errorLoadingModels')}>
|
||||
<div className="px-2 py-1.5 text-sm text-muted-foreground">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
|
||||
<div className="space-y-2">
|
||||
<p className="text-destructive">{error}</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={refetch}
|
||||
className="h-7 text-xs"
|
||||
>
|
||||
<RefreshCw className="h-3 w-3 mr-1" />
|
||||
{t('retry')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CommandGroup>
|
||||
)}
|
||||
|
||||
{/* Provider models */}
|
||||
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
|
||||
<div key={provider}>
|
||||
<CommandSeparator />
|
||||
<CommandGroup heading={provider}>
|
||||
{providerModels.map((model) => (
|
||||
<CommandItem
|
||||
key={model.fullId}
|
||||
value={model.fullId}
|
||||
onSelect={() => handleSelect(model.fullId)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
value === model.fullId ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
<span className="truncate flex-1">{model.fullId}</span>
|
||||
{model.pricing && (
|
||||
<ModelPricing pricing={model.pricing} className="ml-2" />
|
||||
)}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Custom model option and manage providers - moved to bottom */}
|
||||
<CommandSeparator />
|
||||
<CommandGroup>
|
||||
{isConfigured && (
|
||||
<CommandItem
|
||||
value="__custom_model_option__"
|
||||
onSelect={() => handleSelect('__custom__')}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Edit3 className="mr-2 h-4 w-4" />
|
||||
{t('enterCustomModel')}
|
||||
</CommandItem>
|
||||
)}
|
||||
{shouldShowRecentlyUsed && (
|
||||
<CommandGroup heading={t('recentlyUsed')}>
|
||||
{recentlyUsedModels.map((model) => (
|
||||
<CommandItem
|
||||
value="__manage_providers_option__"
|
||||
onSelect={() => handleSelect('__manage_providers__')}
|
||||
key={model}
|
||||
value={model}
|
||||
onSelect={() => handleSelect(model)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
{t('manageProviders')}
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
value === model ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
<span className="truncate">{model}</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
)}
|
||||
|
||||
{shouldShowRecentlyUsed && <CommandSeparator />}
|
||||
|
||||
{/* Loading state */}
|
||||
{isLoading && (
|
||||
<CommandGroup heading={t('loading')}>
|
||||
<div className="px-2 py-1.5">
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4 w-1/2" />
|
||||
</div>
|
||||
</div>
|
||||
</CommandGroup>
|
||||
)}
|
||||
|
||||
{/* Error state */}
|
||||
{error && !isLoading && (
|
||||
<CommandGroup heading={t('errorLoadingModels')}>
|
||||
<div className="px-2 py-1.5 text-sm text-muted-foreground">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
|
||||
<div className="space-y-2">
|
||||
<p className="text-destructive">{error}</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={refetch}
|
||||
className="h-7 text-xs"
|
||||
>
|
||||
<RefreshCw className="h-3 w-3 mr-1" />
|
||||
{t('retry')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CommandGroup>
|
||||
)}
|
||||
|
||||
{/* Provider models */}
|
||||
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
|
||||
<div key={provider}>
|
||||
<CommandSeparator />
|
||||
<CommandGroup heading={provider}>
|
||||
{providerModels.map((model) => (
|
||||
<CommandItem
|
||||
key={model.fullId}
|
||||
value={model.fullId}
|
||||
onSelect={() => handleSelect(model.fullId)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
value === model.fullId ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
<span className="truncate">{model.fullId}</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Custom model option and manage providers - moved to bottom */}
|
||||
<CommandSeparator />
|
||||
<CommandGroup>
|
||||
{isConfigured && (
|
||||
<CommandItem
|
||||
value="__custom_model_option__"
|
||||
onSelect={() => handleSelect('__custom__')}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Edit3 className="mr-2 h-4 w-4" />
|
||||
{t('enterCustomModel')}
|
||||
</CommandItem>
|
||||
)}
|
||||
<CommandItem
|
||||
value="__manage_providers_option__"
|
||||
onSelect={() => handleSelect('__manage_providers__')}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
{t('manageProviders')}
|
||||
</CommandItem>
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -15,11 +15,15 @@ const GIT_KINDS = [
|
||||
1621, // NIP-34 Issue
|
||||
];
|
||||
|
||||
const GIT_RELAYS = [
|
||||
'wss://git.shakespeare.diy/',
|
||||
'wss://relay.ngit.dev/',
|
||||
];
|
||||
|
||||
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
const { children } = props;
|
||||
const { config, presetRelays } = useAppContext();
|
||||
|
||||
const gitRelays = config.ngitServers.map(server => `wss://${server}/`);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Create NPool instance only once
|
||||
@@ -31,7 +35,7 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
// Update refs when config changes
|
||||
useEffect(() => {
|
||||
relayUrl.current = config.relayUrl;
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr'] });
|
||||
queryClient.resetQueries();
|
||||
}, [config.relayUrl, queryClient]);
|
||||
|
||||
// Initialize NPool only once
|
||||
@@ -46,7 +50,7 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
|
||||
if (filters.every((f) => f.kinds?.every((k) => GIT_KINDS.includes(k)))) {
|
||||
// If all filters are git-related, route to all git relays
|
||||
for (const url of gitRelays) {
|
||||
for (const url of GIT_RELAYS) {
|
||||
routes.set(url, filters);
|
||||
}
|
||||
}
|
||||
@@ -58,7 +62,7 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
|
||||
// If it's a git-related event, also publish to the git relays
|
||||
if (GIT_KINDS.includes(event.kind)) {
|
||||
for (const url of gitRelays) {
|
||||
for (const url of GIT_RELAYS) {
|
||||
allRelays.add(url);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { Decimal } from 'decimal.js';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { generateSecretKey } from 'nostr-tools';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink } from 'lucide-react';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
@@ -15,7 +17,6 @@ import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { CreditsDialog } from '@/components/CreditsDialog';
|
||||
import { OnboardingCreditsBadge } from '@/components/OnboardingCreditsBadge';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
import { ModelPricing } from '@/components/ModelPricing';
|
||||
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
@@ -138,6 +139,14 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const formatPrice = (price: Decimal | undefined) => {
|
||||
if (!price) return 'unknown';
|
||||
if (price.equals(0)) return 'Free';
|
||||
// Convert from per-token to per-1M tokens and format with $ prefix
|
||||
const pricePerMillion = price.times(1_000_000);
|
||||
return '$' + pricePerMillion.toFixed(2).toString().replace(/\.00$/, '') + '/M tokens';
|
||||
};
|
||||
|
||||
// Reset state when dialog opens/closes
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
@@ -162,7 +171,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl h-dvh-safe sm:h-auto sm:max-h-[90vh] flex flex-col">
|
||||
<DialogContent className="max-w-2xl h-[100dvh] sm:h-auto sm:max-h-[90vh] flex flex-col">
|
||||
<DialogHeader className="flex-shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
{step === 'open-source' && (
|
||||
@@ -222,7 +231,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
Welcome to Shakespeare!
|
||||
</h2>
|
||||
<p className="text-lg text-muted-foreground max-w-md mx-auto">
|
||||
Your AI-powered development assistant for building custom applications.
|
||||
Your AI-powered development assistant for building custom Nostr applications.
|
||||
Simply describe what you want to build, and AI will help you create it.
|
||||
</p>
|
||||
</div>
|
||||
@@ -266,15 +275,13 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
{step === 'open-source' && (
|
||||
<div className="space-y-6 py-4">
|
||||
<div className="text-center space-y-4">
|
||||
<h2 className="text-2xl font-bold">
|
||||
Shakespeare is Open Source software that runs entirely in your web browser
|
||||
</h2>
|
||||
<h2 className="text-2xl font-bold">Shakespeare is Open Source software that runs entirely in your web browser</h2>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-1 max-w-md mx-auto">
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||
<p className="text-sm">Your device connects directly to third-party AI providers of your choice</p>
|
||||
<p className="text-sm">Your browser connects directly to third-party AI providers of your choice</p>
|
||||
</div>
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||
@@ -296,7 +303,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
|
||||
<div className="space-y-3 max-w-md mx-auto">
|
||||
<p className="text-xs text-muted-foreground max-w-xl mx-auto">
|
||||
Shakespeare is not a cloud service. It's Open Source software that runs on your device.
|
||||
Shakespeare is not a cloud service. It's Open Source software that runs in your web browser.
|
||||
You agree to the Terms of Service of AI providers you interact with.
|
||||
Shakespeare is provided "as is" without warranty of any kind.
|
||||
</p>
|
||||
@@ -503,12 +510,14 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
) : (
|
||||
providerModels.map((model) => {
|
||||
const isSelected = selectedModel === model.fullId;
|
||||
const isFree = model.pricing?.prompt.equals(0) && model.pricing?.completion.equals(0);
|
||||
const isPremium = !!model.pricing && !isFree;
|
||||
const modelName = model.name || model.id;
|
||||
|
||||
return (
|
||||
<Card
|
||||
key={model.fullId}
|
||||
className={`relative cursor-pointer transition-all hover:shadow-md ${
|
||||
className={`cursor-pointer transition-all hover:shadow-md ${
|
||||
isSelected ? 'ring-2 ring-primary' : ''
|
||||
}`}
|
||||
onClick={() => handleModelSelect(model.fullId)}
|
||||
@@ -516,25 +525,53 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex-1">
|
||||
<CardTitle className="text-sm font-semibold flex gap-1">
|
||||
<span>{modelName}</span>
|
||||
{model.pricing && <ModelPricing pricing={model.pricing} />}
|
||||
<CardTitle className={cn('text-xl font-semibold', {
|
||||
'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent': isPremium,
|
||||
})}>
|
||||
{modelName}
|
||||
</CardTitle>
|
||||
{model.description && (
|
||||
<p className="text-lg text-muted-foreground mt-1">
|
||||
{model.description.length > 500
|
||||
? model.description.slice(0, 500) + '...'
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{model.description.length > 70
|
||||
? model.description.slice(0, 70) + '...'
|
||||
: model.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{isSelected && (
|
||||
<div className="absolute top-5 right-5 h-5 w-5 rounded-full bg-primary flex items-center justify-center">
|
||||
<Check className="h-3 w-3 text-primary-foreground" />
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
{isFree && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
Free
|
||||
</Badge>
|
||||
)}
|
||||
{isPremium && (
|
||||
<Badge className="text-xs bg-primary text-white border-0">
|
||||
Premium
|
||||
</Badge>
|
||||
)}
|
||||
{isSelected && (
|
||||
<div className="h-5 w-5 rounded-full bg-primary flex items-center justify-center">
|
||||
<Check className="h-3 w-3 text-primary-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
{(model.pricing || model.contextLength) && (
|
||||
<CardContent className="pt-0">
|
||||
<div className="flex items-end justify-end gap-4 text-xs text-muted-foreground">
|
||||
{model.pricing && (
|
||||
<div className="text-right">
|
||||
<div>Input: {formatPrice(model.pricing.prompt)}</div>
|
||||
<div>Output: {formatPrice(model.pricing.completion)}</div>
|
||||
</div>
|
||||
)}
|
||||
{model.contextLength && (
|
||||
<span>Context: {model.contextLength.toLocaleString()} tokens</span>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
})
|
||||
|
||||
@@ -131,36 +131,34 @@ export function ProjectSidebar({
|
||||
return (
|
||||
<div className={cn("flex flex-col h-full bg-gradient-to-b from-sidebar to-sidebar/95", className)}>
|
||||
{/* Header with Logo */}
|
||||
<div className="pt-safe bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
|
||||
<div className="flex px-4 h-12 border-b border-sidebar-border">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<button
|
||||
onClick={() => navigateAndClose('/')}
|
||||
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
|
||||
>
|
||||
<ShakespeareLogo className="w-6 h-6" />
|
||||
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
Shakespeare
|
||||
</h1>
|
||||
</button>
|
||||
{(onToggleSidebar || (onClose && isMobile)) && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
|
||||
onClick={handleToggleSidebar}
|
||||
aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')}
|
||||
>
|
||||
{(onClose && isMobile) ? (
|
||||
<X className="h-4 w-4 text-primary/60 hover:text-primary" />
|
||||
) : (
|
||||
<Columns2 className="h-4 w-4 text-primary/60 hover:text-primary" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex px-4 h-12 border-b border-sidebar-border bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<button
|
||||
onClick={() => navigateAndClose('/')}
|
||||
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
|
||||
>
|
||||
<ShakespeareLogo className="w-6 h-6" />
|
||||
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
|
||||
Shakespeare
|
||||
</h1>
|
||||
</button>
|
||||
{(onToggleSidebar || (onClose && isMobile)) && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
|
||||
onClick={handleToggleSidebar}
|
||||
aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')}
|
||||
>
|
||||
{(onClose && isMobile) ? (
|
||||
<X className="h-4 w-4 text-primary/60 hover:text-primary" />
|
||||
) : (
|
||||
<Columns2 className="h-4 w-4 text-primary/60 hover:text-primary" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -231,8 +229,8 @@ export function ProjectSidebar({
|
||||
</div>
|
||||
|
||||
{/* Settings and Help at Bottom */}
|
||||
<div className="border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto pb-safe">
|
||||
<div className="p-2 flex items-center gap-2">
|
||||
<div className="p-2 border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@@ -253,6 +251,8 @@ export function ProjectSidebar({
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { Quilly } from './Quilly';
|
||||
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
|
||||
// Mock all required hooks and components
|
||||
vi.mock('@/hooks/useAISettings', () => ({
|
||||
useAISettings: () => ({
|
||||
settings: {
|
||||
providers: []
|
||||
}
|
||||
})
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useAICredits', () => ({
|
||||
useAICredits: () => ({
|
||||
data: null
|
||||
})
|
||||
}));
|
||||
|
||||
vi.mock('react-router-dom', () => ({
|
||||
useNavigate: () => vi.fn()
|
||||
}));
|
||||
|
||||
// Mock CreditsDialog to avoid NostrProvider dependency
|
||||
vi.mock('./CreditsDialog', () => ({
|
||||
CreditsDialog: () => null
|
||||
}));
|
||||
|
||||
describe('Quilly', () => {
|
||||
const defaultProps = {
|
||||
error: new Error('Generic error'),
|
||||
onDismiss: vi.fn(),
|
||||
onNewChat: vi.fn(),
|
||||
onOpenModelSelector: vi.fn(),
|
||||
providerModel: 'test/model'
|
||||
};
|
||||
|
||||
it('renders generic error message', () => {
|
||||
render(<Quilly {...defaultProps} />);
|
||||
|
||||
expect(screen.getByText(/AI service error: Generic error/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders correctly for malformed tool call errors', () => {
|
||||
const error = new MalformedToolCallError(
|
||||
'The AI provider sent an incomplete response.',
|
||||
'call_abc123',
|
||||
'test/model'
|
||||
);
|
||||
|
||||
render(
|
||||
<Quilly
|
||||
{...defaultProps}
|
||||
error={error}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/The AI sent an incomplete response/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Change model/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders correctly for console errors', () => {
|
||||
const error = new ProjectPreviewConsoleError(
|
||||
'Console error',
|
||||
[]
|
||||
);
|
||||
|
||||
render(
|
||||
<Quilly
|
||||
{...defaultProps}
|
||||
error={error}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText(/I noticed some console errors/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/Help fix errors/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { APIError } from 'openai';
|
||||
import OpenAI from 'openai';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -7,30 +7,27 @@ import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
import { CreditsDialog } from './CreditsDialog';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { useState } from 'react';
|
||||
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
|
||||
import { EmptyMessageError } from '@/lib/errors/EmptyMessageError';
|
||||
|
||||
export interface QuillyProps {
|
||||
error: Error;
|
||||
onDismiss: () => void;
|
||||
onNewChat: () => void;
|
||||
onOpenModelSelector: () => void;
|
||||
onTryAgain?: () => void;
|
||||
onRequestConsoleErrorHelp?: (error: ProjectPreviewConsoleError) => void;
|
||||
providerModel: string;
|
||||
}
|
||||
|
||||
interface ErrorBody {
|
||||
message: string;
|
||||
actions?: Array<{
|
||||
action?: {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
|
||||
const navigate = useNavigate();
|
||||
const { settings } = useAISettings();
|
||||
|
||||
@@ -46,151 +43,86 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
const credits = useAICredits(provider || { id: '', name: '', apiKey: '', nostr: false });
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
|
||||
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody => {
|
||||
const renderBody = (error: Error): ErrorBody => {
|
||||
// Handle Project Preview Console Errors
|
||||
if (error instanceof ProjectPreviewConsoleError) {
|
||||
return {
|
||||
message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?',
|
||||
actions: [{
|
||||
action: {
|
||||
label: 'Help fix errors',
|
||||
onClick: () => {
|
||||
onRequestConsoleErrorHelp?.(error);
|
||||
onDismiss();
|
||||
},
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
if (error instanceof MalformedToolCallError) {
|
||||
return {
|
||||
message: 'The AI sent an incomplete response, possibly due to a network issue or provider problem. Try sending your message again, or switch to a different model if this persists.',
|
||||
actions: [{
|
||||
label: 'Change model',
|
||||
onClick: onOpenModelSelector,
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
if (error instanceof EmptyMessageError) {
|
||||
return {
|
||||
message: 'The AI generated an empty response. This may be due to a provider issue or model configuration problem. Try generating again, or switch to a different model.',
|
||||
actions: onTryAgain ? [{
|
||||
label: 'Try again',
|
||||
onClick: () => {
|
||||
onTryAgain();
|
||||
onDismiss();
|
||||
},
|
||||
}] : [{
|
||||
label: 'Change model',
|
||||
onClick: onOpenModelSelector,
|
||||
}],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Handle OpenAI API errors with specific error codes
|
||||
if (error instanceof APIError) {
|
||||
switch (true) {
|
||||
case error.code ==='invalid_api_key':
|
||||
case error.code === 'invalid_request_error':
|
||||
if (error instanceof OpenAI.APIError) {
|
||||
switch (error.code) {
|
||||
case 'invalid_api_key':
|
||||
case 'invalid_request_error':
|
||||
return {
|
||||
message: 'Authentication error: Please check your API key in AI settings.',
|
||||
actions: [{
|
||||
action: {
|
||||
label: 'Check API key',
|
||||
onClick: () => navigate('/settings/ai'),
|
||||
}],
|
||||
}
|
||||
};
|
||||
|
||||
case error.code === 'insufficient_quota': {
|
||||
case 'insufficient_quota': {
|
||||
if (credits.data) {
|
||||
return {
|
||||
message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
|
||||
actions: [{
|
||||
action: {
|
||||
label: 'Add credits',
|
||||
onClick: () => setShowCreditsDialog(true),
|
||||
}],
|
||||
}
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.',
|
||||
actions: [{
|
||||
action: {
|
||||
label: 'Check AI settings',
|
||||
onClick: () => navigate('/settings/ai'),
|
||||
}],
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
case error.code === 'rate_limit_exceeded':
|
||||
case 'rate_limit_exceeded':
|
||||
return {
|
||||
message: 'Rate limit exceeded. Please wait a moment before trying again.',
|
||||
actions: [],
|
||||
};
|
||||
|
||||
case error.code === 'model_not_found':
|
||||
case 'model_not_found':
|
||||
return {
|
||||
message: 'The selected AI model is not available. Please choose a different model.',
|
||||
actions: [{
|
||||
action: {
|
||||
label: 'Choose model',
|
||||
onClick: onOpenModelSelector,
|
||||
}],
|
||||
},
|
||||
};
|
||||
|
||||
case error.code === 'context_length_exceeded':
|
||||
case 'context_length_exceeded':
|
||||
return {
|
||||
message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.',
|
||||
actions: [{
|
||||
action: {
|
||||
label: 'New chat',
|
||||
onClick: onNewChat,
|
||||
}, {
|
||||
label: 'Change model',
|
||||
onClick: onOpenModelSelector,
|
||||
}],
|
||||
},
|
||||
};
|
||||
|
||||
case error.status === 403:
|
||||
return {
|
||||
message: `It seems your API key has been used up. Check your API provider's settings, or try a different API key or different provider/model combo:`,
|
||||
actions: [{
|
||||
label: 'Check API settings',
|
||||
onClick: () => navigate('/settings/ai'),
|
||||
}, {
|
||||
label: 'Change model',
|
||||
onClick: onOpenModelSelector,
|
||||
}],
|
||||
};
|
||||
|
||||
case error.status === 400:
|
||||
return {
|
||||
message: 'The AI provider did not understand the message / data it got. If it persists, try stating a new conversation or using a different model.',
|
||||
actions: [{
|
||||
label: 'New chat',
|
||||
onClick: onNewChat,
|
||||
}, {
|
||||
label: 'Change model',
|
||||
onClick: onOpenModelSelector,
|
||||
}],
|
||||
};
|
||||
|
||||
case error.status === 422:
|
||||
return {
|
||||
message: 'Request rejected by AI provider. Try a different model.',
|
||||
actions: [{
|
||||
label: 'Choose model',
|
||||
onClick: onOpenModelSelector,
|
||||
}],
|
||||
};
|
||||
|
||||
case error.code === 'server_error':
|
||||
case error.code === 'service_unavailable':
|
||||
case 'server_error':
|
||||
case 'service_unavailable':
|
||||
return {
|
||||
message: 'The AI service is temporarily unavailable. Please try again in a moment.',
|
||||
actions: [],
|
||||
};
|
||||
|
||||
default:
|
||||
return {
|
||||
message: `AI service error: ${error.message}`,
|
||||
actions: [],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -200,11 +132,10 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
message: error.message
|
||||
? `AI service error: ${error.message}`
|
||||
: 'Sorry, I encountered an unexpected error. Please try again.',
|
||||
actions: [],
|
||||
};
|
||||
};
|
||||
|
||||
const { message, actions = [] } = renderBody(error);
|
||||
const { message, action } = renderBody(error);
|
||||
|
||||
return (
|
||||
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
|
||||
@@ -217,18 +148,11 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
</h4>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{message}
|
||||
{actions.length > 0 && (
|
||||
<>
|
||||
{' '}
|
||||
{actions.map((action, i) => (
|
||||
<span key={action.label}>
|
||||
<button className="text-primary underline" onClick={action.onClick}>
|
||||
{action.label}
|
||||
</button>
|
||||
{i < actions.length - 1 && <> or </>}
|
||||
</span>
|
||||
))}
|
||||
</>
|
||||
{' '}
|
||||
{action && (
|
||||
<button className="text-primary underline" onClick={action.onClick}>
|
||||
{action.label}
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -5,7 +5,6 @@ import { useFS } from '@/hooks/useFS';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
|
||||
interface SessionManagerProviderProps {
|
||||
children: ReactNode;
|
||||
@@ -19,13 +18,12 @@ export function SessionManagerProvider({ children }: SessionManagerProviderProps
|
||||
const { settings } = useAISettings();
|
||||
const { models } = useProviderModels();
|
||||
const { user, metadata } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
|
||||
const sessionManager = useMemo(() => {
|
||||
const getProviderModels = () => models;
|
||||
const getCurrentUser = () => ({ user, metadata });
|
||||
return new SessionManager(fs, settings, getProviderModels, getCurrentUser, config.corsProxy);
|
||||
}, [fs, settings, models, user, metadata, config.corsProxy]);
|
||||
return new SessionManager(fs, settings, getProviderModels, getCurrentUser);
|
||||
}, [fs, settings, models, user, metadata]);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,15 +1,69 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Menu } from 'lucide-react';
|
||||
import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { type Project } from '@/lib/ProjectsManager';
|
||||
import { useCallback } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { getSettingsItems } from '@/lib/settingsItems';
|
||||
|
||||
interface SettingsItem {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
href: string;
|
||||
}
|
||||
|
||||
// Define settings items as a function to get fresh translations
|
||||
const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
|
||||
{
|
||||
id: 'preferences',
|
||||
title: t('preferences'),
|
||||
description: t('preferencesDescription'),
|
||||
icon: Settings2,
|
||||
href: '/settings/preferences',
|
||||
},
|
||||
{
|
||||
id: 'ai',
|
||||
title: t('aiSettings'),
|
||||
description: t('aiSettingsDescription'),
|
||||
icon: Bot,
|
||||
href: '/settings/ai',
|
||||
},
|
||||
{
|
||||
id: 'git',
|
||||
title: t('gitSettings'),
|
||||
description: t('gitSettingsDescription'),
|
||||
icon: GitBranch,
|
||||
href: '/settings/git',
|
||||
},
|
||||
{
|
||||
id: 'nostr',
|
||||
title: t('nostrSettings'),
|
||||
description: t('nostrSettingsDescription'),
|
||||
icon: Wifi,
|
||||
href: '/settings/nostr',
|
||||
},
|
||||
{
|
||||
id: 'data',
|
||||
title: t('dataSettings'),
|
||||
description: t('dataSettingsDescription'),
|
||||
icon: Database,
|
||||
href: '/settings/data',
|
||||
},
|
||||
{
|
||||
id: 'about',
|
||||
title: t('aboutShakespeare'),
|
||||
description: t('aboutShakespeareDescription'),
|
||||
icon: Info,
|
||||
href: '/settings/about',
|
||||
},
|
||||
];
|
||||
|
||||
export function SettingsLayout() {
|
||||
const { t } = useTranslation();
|
||||
@@ -66,10 +120,10 @@ export function SettingsLayout() {
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<div className="min-h-dvh pb-safe bg-background">
|
||||
<div className="min-h-dvh bg-background">
|
||||
{/* Mobile Header */}
|
||||
<header className="pt-safe bg-background">
|
||||
<div className="flex items-center space-x-2 h-12 border-b px-4 py-3">
|
||||
<header className="h-12 border-b bg-background px-4 py-3 flex items-center justify-between">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
|
||||
@@ -1,249 +0,0 @@
|
||||
import { useState, useCallback, memo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { CircularProgress } from '@/components/ui/circular-progress';
|
||||
import { FileAttachment } from '@/components/ui/file-attachment';
|
||||
import { Square, ArrowUp } from 'lucide-react';
|
||||
import { ModelSelector } from '@/components/ModelSelector';
|
||||
|
||||
interface ChatInputProps {
|
||||
isLoading: boolean;
|
||||
isConfigured: boolean;
|
||||
providerModel: string;
|
||||
onProviderModelChange: (model: string) => void;
|
||||
onSend: (input: string, files: File[]) => void;
|
||||
onStop: () => void;
|
||||
onFocus: () => void;
|
||||
onFirstInteraction: () => void;
|
||||
isModelSelectorOpen: boolean;
|
||||
onModelSelectorOpenChange: (open: boolean) => void;
|
||||
contextUsagePercentage: number;
|
||||
currentModelContextLength?: number;
|
||||
lastInputTokens?: number;
|
||||
totalCost: number;
|
||||
isDragOver: boolean;
|
||||
onDragEnter: (e: React.DragEvent) => void;
|
||||
onDragOver: (e: React.DragEvent) => void;
|
||||
onDragLeave: (e: React.DragEvent) => void;
|
||||
onDrop: (e: React.DragEvent) => void;
|
||||
}
|
||||
|
||||
export const ChatInput = memo(function ChatInput({
|
||||
isLoading,
|
||||
isConfigured,
|
||||
providerModel,
|
||||
onProviderModelChange,
|
||||
onSend,
|
||||
onStop,
|
||||
onFocus,
|
||||
onFirstInteraction,
|
||||
isModelSelectorOpen,
|
||||
onModelSelectorOpenChange,
|
||||
contextUsagePercentage,
|
||||
currentModelContextLength,
|
||||
lastInputTokens,
|
||||
totalCost,
|
||||
isDragOver,
|
||||
onDragEnter,
|
||||
onDragOver,
|
||||
onDragLeave,
|
||||
onDrop,
|
||||
}: ChatInputProps) {
|
||||
const { t } = useTranslation();
|
||||
const [input, setInput] = useState('');
|
||||
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
|
||||
|
||||
const handleFileSelect = useCallback((file: File) => {
|
||||
setAttachedFiles(prev => [...prev, file]);
|
||||
}, []);
|
||||
|
||||
const handleFileRemove = useCallback((fileToRemove: File) => {
|
||||
setAttachedFiles(prev => prev.filter(file => file !== fileToRemove));
|
||||
}, []);
|
||||
|
||||
const handleSend = useCallback(() => {
|
||||
if ((!input.trim() && attachedFiles.length === 0) || isLoading) return;
|
||||
if (!isConfigured || !providerModel.trim()) return;
|
||||
|
||||
const currentInput = input;
|
||||
const currentFiles = [...attachedFiles];
|
||||
|
||||
setInput('');
|
||||
setAttachedFiles([]);
|
||||
|
||||
onSend(currentInput, currentFiles);
|
||||
}, [input, attachedFiles, isLoading, isConfigured, providerModel, onSend]);
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
}
|
||||
}, [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);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="border-t p-4">
|
||||
{/* Chat Input Container */}
|
||||
<div
|
||||
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${
|
||||
isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
|
||||
}`}
|
||||
onDragEnter={onDragEnter}
|
||||
onDragOver={onDragOver}
|
||||
onDragLeave={onDragLeave}
|
||||
onDrop={onDrop}
|
||||
>
|
||||
<Textarea
|
||||
value={input}
|
||||
onChange={handleInputChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
onFocus={onFocus}
|
||||
placeholder={
|
||||
!isConfigured
|
||||
? t('askToAddFeatures')
|
||||
: providerModel.trim()
|
||||
? t('askToAddFeatures')
|
||||
: 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())}
|
||||
rows={1}
|
||||
aria-label="Chat message input"
|
||||
style={{
|
||||
height: 'auto',
|
||||
minHeight: '96px'
|
||||
}}
|
||||
onInput={(e) => {
|
||||
const target = e.target as HTMLTextAreaElement;
|
||||
target.style.height = 'auto';
|
||||
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Bottom Controls Row */}
|
||||
<div className="flex items-center gap-4 px-2 py-2">
|
||||
{/* File Attachment */}
|
||||
<FileAttachment
|
||||
onFileSelect={handleFileSelect}
|
||||
onFileRemove={handleFileRemove}
|
||||
selectedFiles={attachedFiles}
|
||||
disabled={isLoading}
|
||||
multiple={true}
|
||||
/>
|
||||
|
||||
{/* Context Usage Wheel */}
|
||||
{contextUsagePercentage >= 10 && currentModelContextLength && lastInputTokens && lastInputTokens > 0 && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="cursor-help">
|
||||
<CircularProgress
|
||||
value={contextUsagePercentage}
|
||||
size={20}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{t('contextUsage', {
|
||||
tokens: lastInputTokens.toLocaleString(),
|
||||
total: currentModelContextLength.toLocaleString(),
|
||||
percentage: contextUsagePercentage.toFixed(1)
|
||||
})}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
|
||||
{/* Cost Display */}
|
||||
{totalCost >= 0.01 && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="text-xs text-muted-foreground px-2 py-1 bg-muted/50 rounded-md whitespace-nowrap cursor-help">
|
||||
${totalCost.toFixed(2)}
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{t('totalCostSession')}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
|
||||
{/* Model Selector */}
|
||||
<div className="flex-1 max-w-72 ml-auto overflow-hidden">
|
||||
<ModelSelector
|
||||
value={providerModel}
|
||||
onChange={onProviderModelChange}
|
||||
disabled={isLoading}
|
||||
placeholder={t('chooseModel')}
|
||||
open={isModelSelectorOpen}
|
||||
onOpenChange={onModelSelectorOpenChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Send/Stop Button */}
|
||||
<div>
|
||||
{isLoading ? (
|
||||
<Button
|
||||
onClick={onStop}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="size-8 rounded-full p-0 bg-foreground/10 [&_svg]:size-3.5 [&_svg]:fill-foreground hover:bg-foreground/20"
|
||||
>
|
||||
<Square />
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
onMouseDown={onFirstInteraction}
|
||||
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
|
||||
size="sm"
|
||||
className="size-8 [&_svg]:size-5 rounded-full p-0"
|
||||
>
|
||||
<ArrowUp />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -2,16 +2,20 @@ import { useState, useRef, useEffect, forwardRef, useImperativeHandle, useMemo,
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { CircularProgress } from '@/components/ui/circular-progress';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { FileAttachment } from '@/components/ui/file-attachment';
|
||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||
import { Loader2, ChevronDown } from 'lucide-react';
|
||||
import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useKeepAlive } from '@/hooks/useKeepAlive';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useAIChat } from '@/hooks/useAIChat';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { ModelSelector } from '@/components/ModelSelector';
|
||||
import { AIMessageItem } from '@/components/AIMessageItem';
|
||||
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
|
||||
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
|
||||
@@ -30,8 +34,7 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
|
||||
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
||||
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
import { ReadConsoleMessagesTool, ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
import OpenAI from 'openai';
|
||||
@@ -39,7 +42,6 @@ import { saveFileToTmp } from '@/lib/fileUtils';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { Quilly } from '@/components/Quilly';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
||||
|
||||
// Clean interfaces now handled by proper hooks
|
||||
|
||||
@@ -74,8 +76,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const { git } = useGit();
|
||||
const { user } = useCurrentUser();
|
||||
const { models } = useProviderModels();
|
||||
const { config } = useAppContext();
|
||||
const [input, setInput] = useState('');
|
||||
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
|
||||
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const [scrolledProjects] = useState(() => new Set<string>());
|
||||
const [showOnboarding, setShowOnboarding] = useState(false);
|
||||
@@ -98,11 +101,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const [shouldAutostart, setShouldAutostart] = useState(false);
|
||||
const autostartedRef = useRef(false);
|
||||
|
||||
// Memoize model selector onChange handler to prevent unnecessary re-renders
|
||||
const handleModelChange = useCallback((newModel: string) => {
|
||||
setProviderModel(newModel);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!providerModel && settings.recentlyUsedModels?.length) {
|
||||
setProviderModel(settings.recentlyUsedModels[0]);
|
||||
@@ -134,7 +132,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
// Initialize AI chat with tools
|
||||
const cwd = `/projects/${projectId}`;
|
||||
const esmUrlRef = useRef(config.esmUrl);
|
||||
const customTools = useMemo(() => {
|
||||
const baseTools = {
|
||||
git_commit: new GitCommitTool(fs, cwd, git),
|
||||
@@ -143,7 +140,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd),
|
||||
npm_add_package: new NpmAddPackageTool(fs, cwd),
|
||||
npm_remove_package: new NpmRemovePackageTool(fs, cwd),
|
||||
build_project: new BuildProjectTool(fs, cwd, esmUrlRef.current),
|
||||
build_project: new BuildProjectTool(fs, cwd),
|
||||
typecheck: new TypecheckTool(fs, cwd),
|
||||
nostr_read_nip: new NostrReadNipTool(),
|
||||
nostr_fetch_event: new NostrFetchEventTool(),
|
||||
@@ -183,7 +180,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
artist: `Working on ${projectId}...`,
|
||||
artwork: [
|
||||
{
|
||||
src: '/shakespeare-512x512.png',
|
||||
src: '/shakespeare.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png'
|
||||
}
|
||||
@@ -372,22 +369,30 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
}, [projectId, scrolledProjects, scrollToBottom]);
|
||||
|
||||
const handleFileSelect = (file: File) => {
|
||||
setAttachedFiles(prev => [...prev, file]);
|
||||
};
|
||||
|
||||
const handleFileRemove = (fileToRemove: File) => {
|
||||
setAttachedFiles(prev => prev.filter(file => file !== fileToRemove));
|
||||
};
|
||||
|
||||
// Drag and drop handlers
|
||||
const handleDragEnter = useCallback((e: React.DragEvent) => {
|
||||
const handleDragEnter = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOver(true);
|
||||
}, []);
|
||||
};
|
||||
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
const handleDragOver = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (!isDragOver) {
|
||||
setIsDragOver(true);
|
||||
}
|
||||
}, [isDragOver]);
|
||||
};
|
||||
|
||||
const handleDragLeave = useCallback((e: React.DragEvent) => {
|
||||
const handleDragLeave = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
@@ -399,15 +404,23 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
if (!container.contains(relatedTarget)) {
|
||||
setIsDragOver(false);
|
||||
}
|
||||
}, []);
|
||||
};
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
const handleDrop = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOver(false);
|
||||
}, []);
|
||||
|
||||
const handleSend = useCallback(async (input: string, attachedFiles: File[]) => {
|
||||
if (isLoading || !providerModel.trim()) return;
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
if (files.length === 0) return;
|
||||
|
||||
// Add all files without validation
|
||||
setAttachedFiles(prev => [...prev, ...files]);
|
||||
};
|
||||
|
||||
const send = useCallback(async (input: string, attachedFiles: File[]) => {
|
||||
if ((!input.trim() && attachedFiles.length === 0) || isLoading) return;
|
||||
|
||||
// If AI is not configured, show onboarding dialog
|
||||
@@ -457,6 +470,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
});
|
||||
}
|
||||
|
||||
setInput('');
|
||||
setAttachedFiles([]);
|
||||
|
||||
// Add model to recently used when sending a message
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
|
||||
@@ -465,24 +481,64 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
await sendMessage(messageContent, modelToUse);
|
||||
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]);
|
||||
|
||||
const handleSend = useCallback(async () => {
|
||||
await send(input, attachedFiles);
|
||||
}, [input, attachedFiles, send]);
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
}
|
||||
};
|
||||
|
||||
const handlePaste = 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
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Handle textarea focus - show onboarding if not configured
|
||||
const handleTextareaFocus = useCallback(() => {
|
||||
const handleTextareaFocus = () => {
|
||||
if (!isConfigured) {
|
||||
setShowOnboarding(true);
|
||||
}
|
||||
if (onFirstInteraction) {
|
||||
onFirstInteraction();
|
||||
}
|
||||
}, [isConfigured, onFirstInteraction]);
|
||||
};
|
||||
|
||||
// Handle first user interaction to enable audio context
|
||||
const handleFirstInteraction = useCallback(() => {
|
||||
const handleFirstInteraction = () => {
|
||||
// This will be handled automatically by the useKeepAlive hook
|
||||
// when isLoading becomes true after user interaction
|
||||
if (onFirstInteraction) {
|
||||
onFirstInteraction();
|
||||
}
|
||||
}, [onFirstInteraction]);
|
||||
};
|
||||
|
||||
// Expose startNewSession function via ref
|
||||
useImperativeHandle(ref, () => ({
|
||||
@@ -585,14 +641,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error Alert (Console or AI) - Don't show while assistant is loading */}
|
||||
{displayError && !isLoading && (
|
||||
{/* Error Alert (Console or AI) */}
|
||||
{displayError && (
|
||||
<Quilly
|
||||
error={displayError}
|
||||
onDismiss={handleErrorDismiss}
|
||||
onNewChat={onNewChat}
|
||||
onOpenModelSelector={openModelSelector}
|
||||
onTryAgain={() => startGeneration(providerModel)}
|
||||
onRequestConsoleErrorHelp={handleConsoleErrorHelp}
|
||||
providerModel={providerModel}
|
||||
/>
|
||||
@@ -614,27 +669,134 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ChatInput
|
||||
isLoading={isLoading}
|
||||
isConfigured={isConfigured}
|
||||
providerModel={providerModel}
|
||||
onProviderModelChange={handleModelChange}
|
||||
onSend={handleSend}
|
||||
onStop={stopGeneration}
|
||||
onFocus={handleTextareaFocus}
|
||||
onFirstInteraction={handleFirstInteraction}
|
||||
isModelSelectorOpen={isModelSelectorOpen}
|
||||
onModelSelectorOpenChange={setIsModelSelectorOpen}
|
||||
contextUsagePercentage={contextUsagePercentage}
|
||||
currentModelContextLength={currentModel?.contextLength}
|
||||
lastInputTokens={lastInputTokens}
|
||||
totalCost={totalCost}
|
||||
isDragOver={isDragOver}
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
/>
|
||||
<div className="border-t p-4">
|
||||
{/* Chat Input Container */}
|
||||
<div
|
||||
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
|
||||
}`}
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
<Textarea
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
onFocus={handleTextareaFocus}
|
||||
placeholder={
|
||||
!isConfigured
|
||||
? t('askToAddFeatures')
|
||||
: providerModel.trim()
|
||||
? t('askToAddFeatures')
|
||||
: 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())}
|
||||
rows={1}
|
||||
aria-label="Chat message input"
|
||||
style={{
|
||||
height: 'auto',
|
||||
minHeight: '96px'
|
||||
}}
|
||||
onInput={(e) => {
|
||||
const target = e.target as HTMLTextAreaElement;
|
||||
target.style.height = 'auto';
|
||||
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Bottom Controls Row */}
|
||||
<div className="flex items-center gap-4 px-2 py-2">
|
||||
{/* File Attachment */}
|
||||
<FileAttachment
|
||||
onFileSelect={handleFileSelect}
|
||||
onFileRemove={handleFileRemove}
|
||||
selectedFiles={attachedFiles}
|
||||
disabled={isLoading}
|
||||
multiple={true}
|
||||
/>
|
||||
|
||||
{/* Context Usage Wheel */}
|
||||
{contextUsagePercentage >= 10 && currentModel?.contextLength && lastInputTokens > 0 && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="cursor-help">
|
||||
<CircularProgress
|
||||
value={contextUsagePercentage}
|
||||
size={20}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{t('contextUsage', {
|
||||
tokens: lastInputTokens.toLocaleString(),
|
||||
total: currentModel.contextLength.toLocaleString(),
|
||||
percentage: contextUsagePercentage.toFixed(1)
|
||||
})}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
|
||||
{/* Cost Display */}
|
||||
{totalCost >= 0.01 && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="text-xs text-muted-foreground px-2 py-1 bg-muted/50 rounded-md whitespace-nowrap cursor-help">
|
||||
${totalCost.toFixed(2)}
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{t('totalCostSession')}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
|
||||
{/* Model Selector */}
|
||||
<div className="flex-1 max-w-72 ml-auto overflow-hidden">
|
||||
<ModelSelector
|
||||
value={providerModel}
|
||||
onChange={setProviderModel}
|
||||
className="w-full"
|
||||
disabled={isLoading}
|
||||
placeholder={t('chooseModel')}
|
||||
open={isModelSelectorOpen}
|
||||
onOpenChange={setIsModelSelectorOpen}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Send/Stop Button */}
|
||||
<div>
|
||||
{isLoading ? (
|
||||
<Button
|
||||
onClick={stopGeneration}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="size-8 rounded-full p-0 bg-foreground/10 [&_svg]:size-3.5 [&_svg]:fill-foreground hover:bg-foreground/20"
|
||||
>
|
||||
<Square />
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
onMouseDown={handleFirstInteraction}
|
||||
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
|
||||
size="sm"
|
||||
className="size-8 [&_svg]:size-5 rounded-full p-0"
|
||||
>
|
||||
<ArrowUp />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Onboarding Dialog */}
|
||||
<OnboardingDialog
|
||||
|
||||
@@ -30,7 +30,7 @@ export function FileTree({ projectId, onFileSelect, selectedFile }: FileTreeProp
|
||||
const [gitignoreFilter, setGitignoreFilter] = useState<{
|
||||
isIgnored: (path: string) => boolean;
|
||||
shouldShow: (path: string) => boolean;
|
||||
} | null>(null);
|
||||
} | null>(null);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [isSearching, setIsSearching] = useState(false);
|
||||
const { fs } = useFS();
|
||||
|
||||
@@ -3,13 +3,12 @@ import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages';
|
||||
import { useConsoleError } from '@/hooks/useConsoleError';
|
||||
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
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, Play, Loader2, MenuIcon, Code, CloudUpload, X, Terminal } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
||||
@@ -30,7 +29,9 @@ 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';
|
||||
|
||||
// Get iframe domain from environment variable
|
||||
const IFRAME_DOMAIN = import.meta.env.VITE_IFRAME_DOMAIN || 'local-shakespeare.dev';
|
||||
|
||||
interface PreviewPaneProps {
|
||||
projectId: string;
|
||||
@@ -71,10 +72,8 @@ interface JSONRPCResponse {
|
||||
id: number;
|
||||
}
|
||||
|
||||
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction: _onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
|
||||
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
|
||||
const { t } = useTranslation();
|
||||
const { config } = useAppContext();
|
||||
const { previewDomain } = config;
|
||||
const [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||
const [fileContent, setFileContent] = useState<string>('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
@@ -91,9 +90,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const { fs } = useFS();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
// Use console error state from provider
|
||||
const { hasErrors: hasConsoleErrors, clearErrors } = useConsoleError();
|
||||
|
||||
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
@@ -184,26 +180,26 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
// Use a small timeout to ensure the src is cleared before setting it back
|
||||
setTimeout(() => {
|
||||
if (iframeRef.current) {
|
||||
iframeRef.current.src = `https://${projectId}.${previewDomain}/`;
|
||||
iframeRef.current.src = `https://${projectId}.${IFRAME_DOMAIN}/`;
|
||||
}
|
||||
}, 10);
|
||||
}
|
||||
}, [projectId, previewDomain]);
|
||||
}, [projectId]);
|
||||
|
||||
const sendResponse = useCallback((message: JSONRPCResponse) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
|
||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
||||
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
}
|
||||
}, [projectId, previewDomain]);
|
||||
}, [projectId]);
|
||||
|
||||
const sendError = useCallback((message: JSONRPCResponse) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
||||
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
}
|
||||
}, [projectId, previewDomain]);
|
||||
}, [projectId]);
|
||||
|
||||
const handleConsoleMessage = useCallback((message: {
|
||||
jsonrpc: '2.0';
|
||||
@@ -266,10 +262,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
params: params || {},
|
||||
id: Date.now()
|
||||
};
|
||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
||||
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
}
|
||||
}, [projectId, previewDomain]);
|
||||
}, [projectId]);
|
||||
|
||||
const navigateIframe = useCallback((url: string) => {
|
||||
// Send semantic path directly (e.g., "/about", "/contact")
|
||||
@@ -316,7 +312,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
try {
|
||||
// Parse the URL and validate origin
|
||||
const url = new URL(fetchRequest.url);
|
||||
const expectedOrigin = `https://${projectId}.${previewDomain}`;
|
||||
const expectedOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
|
||||
if (url.origin !== expectedOrigin) {
|
||||
console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`);
|
||||
@@ -423,13 +419,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
id
|
||||
});
|
||||
}
|
||||
}, [projectId, projectsManager, sendResponse, sendError, previewDomain]);
|
||||
}, [projectId, projectsManager, sendResponse, sendError]);
|
||||
|
||||
// Setup messaging protocol for iframe communication
|
||||
useEffect(() => {
|
||||
const handleMessage = (event: MessageEvent) => {
|
||||
// Verify origin for security
|
||||
const expectedOrigin = `https://${projectId}.${previewDomain}`;
|
||||
const expectedOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
if (event.origin !== expectedOrigin) {
|
||||
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
|
||||
return;
|
||||
@@ -448,7 +444,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
|
||||
window.addEventListener('message', handleMessage);
|
||||
return () => window.removeEventListener('message', handleMessage);
|
||||
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
|
||||
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedFile) {
|
||||
@@ -457,7 +453,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
}, [selectedFile, loadFileContent]);
|
||||
|
||||
// Reset selected file and navigation history when projectId changes
|
||||
const prevProjectIdRef = useRef<string>();
|
||||
useEffect(() => {
|
||||
setSelectedFile(null);
|
||||
setFileContent('');
|
||||
@@ -468,13 +463,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
setCurrentPath('/');
|
||||
setNavigationHistory(['/']);
|
||||
setHistoryIndex(0);
|
||||
|
||||
// Only clear console messages when projectId actually changes (not on initial mount)
|
||||
if (prevProjectIdRef.current && prevProjectIdRef.current !== projectId) {
|
||||
clearErrors();
|
||||
}
|
||||
prevProjectIdRef.current = projectId;
|
||||
}, [projectId, clearErrors]);
|
||||
}, [projectId]);
|
||||
|
||||
useEffect(() => {
|
||||
checkForBuiltProject();
|
||||
@@ -523,8 +512,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
||||
|
||||
const messages = isOpen ? getConsoleMessages() : [];
|
||||
|
||||
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(msg.message);
|
||||
@@ -535,7 +522,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
}
|
||||
};
|
||||
|
||||
const messageCount = messages.length;
|
||||
const consoleMessages = getConsoleMessages();
|
||||
const messageCount = consoleMessages.length;
|
||||
const hasErrors = consoleMessages.some(msg => msg.level === 'error');
|
||||
|
||||
return (
|
||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||
@@ -546,7 +535,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
className="h-8 w-8 p-0 relative"
|
||||
>
|
||||
<Bug className="h-4 w-4" />
|
||||
{hasConsoleErrors && (
|
||||
{hasErrors && (
|
||||
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
|
||||
)}
|
||||
</Button>
|
||||
@@ -566,7 +555,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
|
||||
</div>
|
||||
) : (
|
||||
messages.map((msg, index) => (
|
||||
consoleMessages.map((msg, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
|
||||
@@ -578,9 +567,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<div className={cn(
|
||||
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
|
||||
msg.level === 'error' ? "text-destructive" :
|
||||
msg.level === 'warn' ? "text-warning" :
|
||||
msg.level === 'info' ? "text-primary" :
|
||||
"text-muted-foreground"
|
||||
msg.level === 'warn' ? "text-warning" :
|
||||
msg.level === 'info' ? "text-primary" :
|
||||
"text-muted-foreground"
|
||||
)}>
|
||||
{msg.message}
|
||||
</div>
|
||||
@@ -651,7 +640,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<Rocket className="h-4 w-4" />
|
||||
<CloudUpload className="h-4 w-4" />
|
||||
Deploy
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
@@ -664,87 +653,87 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<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>
|
||||
|
||||
{/* Content area */}
|
||||
<div className="flex-1">
|
||||
{hasBuiltProject ? (
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.${previewDomain}/`}
|
||||
className="w-full h-full border-0"
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin"
|
||||
/>
|
||||
) : (
|
||||
<div className="h-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">
|
||||
{t('buildProjectToSeePreview')}
|
||||
</p>
|
||||
<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
|
||||
onClick={handleBuildProject}
|
||||
disabled={isBuildLoading}
|
||||
variant="outline"
|
||||
className="gap-2"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onToggleView}
|
||||
className="h-8 gap-2"
|
||||
>
|
||||
{isBuildLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
Building...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="h-5 w-5" />
|
||||
Build Project
|
||||
</>
|
||||
)}
|
||||
<Code className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<ConsoleDropdown />
|
||||
<Menu />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Build loading overlay */}
|
||||
{isBuildLoading && (
|
||||
<div className="absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10">
|
||||
<div className="bg-background/90 border rounded-lg p-4 shadow-lg flex items-center gap-3">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-primary" />
|
||||
<span className="text-sm font-medium">Building project...</span>
|
||||
{/* Content area */}
|
||||
<div className="flex-1">
|
||||
{hasBuiltProject ? (
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.${IFRAME_DOMAIN}/`}
|
||||
className="w-full h-full border-0"
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin"
|
||||
/>
|
||||
) : (
|
||||
<div className="h-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">
|
||||
{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>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
{/* Build loading overlay */}
|
||||
{isBuildLoading && (
|
||||
<div className="absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10">
|
||||
<div className="bg-background/90 border rounded-lg p-4 shadow-lg flex items-center gap-3">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-primary" />
|
||||
<span className="text-sm font-medium">Building project...</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
)}
|
||||
|
||||
<TabsContent value="code" className="h-full mt-0">
|
||||
@@ -767,7 +756,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
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"
|
||||
className="fixed right-4 bottom-safe-nav z-20 h-12 w-12 p-0 rounded-full shadow-lg bg-background border-2"
|
||||
>
|
||||
<Terminal className="h-6 w-6" />
|
||||
</Button>
|
||||
@@ -933,6 +922,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
projectName={projectName}
|
||||
open={deployDialogOpen}
|
||||
onOpenChange={setDeployDialogOpen}
|
||||
onFirstInteraction={onFirstInteraction}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -6,7 +6,6 @@ import { cn } from '@/lib/utils';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml';
|
||||
|
||||
interface TerminalProps {
|
||||
projectId: string;
|
||||
@@ -153,9 +152,7 @@ export function Terminal({ projectId, 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);
|
||||
}
|
||||
@@ -190,9 +187,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
||||
${' '}
|
||||
</span>
|
||||
) : null}
|
||||
{containsAnsiCodes(line.content)
|
||||
? <span dangerouslySetInnerHTML={{ __html: ansiToHtml(line.content) }} />
|
||||
: line.content}
|
||||
{line.content}
|
||||
</pre>
|
||||
<Button
|
||||
variant="ghost"
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
import { Terminal } from './Terminal';
|
||||
|
||||
/**
|
||||
* A test component to verify ANSI color code rendering in the terminal
|
||||
*/
|
||||
export function TerminalTest() {
|
||||
return (
|
||||
<div className="h-[500px] w-full">
|
||||
<Terminal projectId="test" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
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 } }) => {
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div data-testid="add-provider-dialog">
|
||||
<div>Provider ID: {provider.id}</div>
|
||||
<div>Base URL: {provider.baseURL}</div>
|
||||
{provider.apiKey && <div>API Key: {provider.apiKey}</div>}
|
||||
{provider.nostr && <div>Nostr: true</div>}
|
||||
{provider.proxy && <div>Proxy: true</div>}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
describe('URLFragmentHandler', () => {
|
||||
const originalHash = window.location.hash;
|
||||
|
||||
beforeEach(() => {
|
||||
// Clear hash before each test
|
||||
window.location.hash = '';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Restore original hash
|
||||
window.location.hash = originalHash;
|
||||
});
|
||||
|
||||
it('does not render dialog when no hash is present', () => {
|
||||
window.location.hash = '';
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<URLFragmentHandler />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.queryByTestId('add-provider-dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render dialog when hash does not contain provider params', () => {
|
||||
window.location.hash = '#some-random-hash';
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<URLFragmentHandler />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.queryByTestId('add-provider-dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('parses provider from URL fragment and displays dialog', async () => {
|
||||
window.location.hash = '#id=openrouter&baseURL=https://openrouter.ai/api/v1';
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<URLFragmentHandler />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('add-provider-dialog')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText('Provider ID: openrouter')).toBeInTheDocument();
|
||||
expect(screen.getByText('Base URL: https://openrouter.ai/api/v1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('parses API key from URL fragment', async () => {
|
||||
window.location.hash = '#id=openrouter&baseURL=https://openrouter.ai/api/v1&apiKey=sk-test-123';
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<URLFragmentHandler />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('add-provider-dialog')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText('API Key: sk-test-123')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('parses nostr flag from URL fragment', async () => {
|
||||
window.location.hash = '#id=shakespeare&baseURL=https://ai.shakespeare.diy/v1&nostr=true';
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<URLFragmentHandler />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('add-provider-dialog')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText('Nostr: true')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('parses proxy flag from URL fragment', async () => {
|
||||
window.location.hash = '#id=custom&baseURL=https://api.custom.com/v1&proxy=true';
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<URLFragmentHandler />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('add-provider-dialog')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText('Proxy: true')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('parses all parameters from complete URL', async () => {
|
||||
window.location.hash = '#id=openrouter&baseURL=https://openrouter.ai/api&apiKey=sk-b7719bfc06f04bb29086f380969c76eb&nostr=false&proxy=true';
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<URLFragmentHandler />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('add-provider-dialog')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByText('Provider ID: openrouter')).toBeInTheDocument();
|
||||
expect(screen.getByText('Base URL: https://openrouter.ai/api')).toBeInTheDocument();
|
||||
expect(screen.getByText('API Key: sk-b7719bfc06f04bb29086f380969c76eb')).toBeInTheDocument();
|
||||
expect(screen.getByText('Proxy: true')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('requires both id and baseURL to show dialog', () => {
|
||||
window.location.hash = '#id=openrouter';
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<URLFragmentHandler />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.queryByTestId('add-provider-dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,80 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import { AddProviderDialog } from '@/components/AddProviderDialog';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
/**
|
||||
* Component that handles URL fragments for adding AI providers
|
||||
* Example URL: https://shakespeare.diy/#id=openrouter&baseURL=https://openrouter.ai/api&apiKey=sk-123
|
||||
*/
|
||||
export function URLFragmentHandler() {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const [providerFromURL, setProviderFromURL] = useState<AIProvider | null>(null);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Only process if there's a hash
|
||||
if (!location.hash) return;
|
||||
|
||||
// Remove the leading '#' and parse as URLSearchParams
|
||||
const fragment = location.hash.slice(1);
|
||||
const params = new URLSearchParams(fragment);
|
||||
|
||||
// Check if we have the required parameters for a provider
|
||||
const id = params.get('id');
|
||||
const baseURL = params.get('baseURL');
|
||||
|
||||
if (!id || !baseURL) {
|
||||
// Not a provider URL, ignore
|
||||
return;
|
||||
}
|
||||
|
||||
// Build the provider object
|
||||
const provider: AIProvider = {
|
||||
id,
|
||||
baseURL,
|
||||
};
|
||||
|
||||
// Add optional parameters
|
||||
const apiKey = params.get('apiKey');
|
||||
if (apiKey) {
|
||||
provider.apiKey = apiKey;
|
||||
}
|
||||
|
||||
const nostr = params.get('nostr');
|
||||
if (nostr === 'true') {
|
||||
provider.nostr = true;
|
||||
}
|
||||
|
||||
const proxy = params.get('proxy');
|
||||
if (proxy === 'true') {
|
||||
provider.proxy = true;
|
||||
}
|
||||
|
||||
// Set the provider and open dialog
|
||||
setProviderFromURL(provider);
|
||||
setDialogOpen(true);
|
||||
|
||||
// Remove the fragment from the URL immediately
|
||||
// Preserve the current path and search params
|
||||
navigate(location.pathname + location.search, { replace: true });
|
||||
}, [location, navigate]);
|
||||
|
||||
const handleDialogClose = () => {
|
||||
setDialogOpen(false);
|
||||
setProviderFromURL(null);
|
||||
};
|
||||
|
||||
if (!providerFromURL) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<AddProviderDialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={handleDialogClose}
|
||||
provider={providerFromURL}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -41,29 +41,29 @@ const AddWalletContent = forwardRef<HTMLDivElement, {
|
||||
setAlias: (value: string) => void;
|
||||
connectionUri: string;
|
||||
setConnectionUri: (value: string) => void;
|
||||
}>(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (
|
||||
<div className="space-y-4 px-4" ref={ref}>
|
||||
<div>
|
||||
<Label htmlFor="alias">Wallet Name (optional)</Label>
|
||||
<Input
|
||||
id="alias"
|
||||
placeholder="My Lightning Wallet"
|
||||
value={alias}
|
||||
onChange={(e) => setAlias(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="connection-uri">Connection URI</Label>
|
||||
<Textarea
|
||||
id="connection-uri"
|
||||
placeholder="nostr+walletconnect://..."
|
||||
value={connectionUri}
|
||||
onChange={(e) => setConnectionUri(e.target.value)}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
));
|
||||
}>(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (
|
||||
<div className="space-y-4 px-4" ref={ref}>
|
||||
<div>
|
||||
<Label htmlFor="alias">Wallet Name (optional)</Label>
|
||||
<Input
|
||||
id="alias"
|
||||
placeholder="My Lightning Wallet"
|
||||
value={alias}
|
||||
onChange={(e) => setAlias(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="connection-uri">Connection URI</Label>
|
||||
<Textarea
|
||||
id="connection-uri"
|
||||
placeholder="nostr+walletconnect://..."
|
||||
value={connectionUri}
|
||||
onChange={(e) => setConnectionUri(e.target.value)}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
));
|
||||
AddWalletContent.displayName = 'AddWalletContent';
|
||||
|
||||
// Extracted WalletContent to prevent re-renders
|
||||
@@ -77,132 +77,132 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
||||
handleSetActive: (cs: string) => void;
|
||||
handleRemoveConnection: (cs: string) => void;
|
||||
setAddDialogOpen: (open: boolean) => void;
|
||||
}>(({
|
||||
hasWebLN,
|
||||
isDetecting,
|
||||
hasNWC,
|
||||
connections,
|
||||
connectionInfo,
|
||||
activeConnection,
|
||||
handleSetActive,
|
||||
handleRemoveConnection,
|
||||
setAddDialogOpen
|
||||
}, ref) => (
|
||||
<div className="space-y-6 px-4 pb-4" ref={ref}>
|
||||
{/* Current Status */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="font-medium">Current Status</h3>
|
||||
<div className="grid gap-3">
|
||||
{/* WebLN */}
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<Globe className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">WebLN</p>
|
||||
<p className="text-xs text-muted-foreground">Browser extension</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
|
||||
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
{/* NWC */}
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">Nostr Wallet Connect</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{connections.length > 0
|
||||
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
|
||||
: "Remote wallet connection"
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{hasNWC && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={hasNWC ? "default" : "secondary"} className="text-xs">
|
||||
{hasNWC ? "Ready" : "None"}
|
||||
</Badge>
|
||||
</div>
|
||||
}>(({
|
||||
hasWebLN,
|
||||
isDetecting,
|
||||
hasNWC,
|
||||
connections,
|
||||
connectionInfo,
|
||||
activeConnection,
|
||||
handleSetActive,
|
||||
handleRemoveConnection,
|
||||
setAddDialogOpen
|
||||
}, ref) => (
|
||||
<div className="space-y-6 px-4 pb-4" ref={ref}>
|
||||
{/* Current Status */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="font-medium">Current Status</h3>
|
||||
<div className="grid gap-3">
|
||||
{/* WebLN */}
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<Globe className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">WebLN</p>
|
||||
<p className="text-xs text-muted-foreground">Browser extension</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Separator />
|
||||
{/* NWC Management */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-medium">Nostr Wallet Connect</h3>
|
||||
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add
|
||||
</Button>
|
||||
<div className="flex items-center gap-2">
|
||||
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
|
||||
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
|
||||
</Badge>
|
||||
</div>
|
||||
{/* Connected Wallets List */}
|
||||
{connections.length === 0 ? (
|
||||
<div className="text-center py-6 text-muted-foreground">
|
||||
<p className="text-sm">No wallets connected</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{connections.map((connection) => {
|
||||
const info = connectionInfo[connection.connectionString];
|
||||
const isActive = activeConnection === connection.connectionString;
|
||||
return (
|
||||
<div key={connection.connectionString} className={`flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`}>
|
||||
<div className="flex items-center gap-3">
|
||||
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
{connection.alias || info?.alias || 'Lightning Wallet'}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
NWC Connection
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{isActive && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
{!isActive && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleSetActive(connection.connectionString)}
|
||||
>
|
||||
<Zap className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleRemoveConnection(connection.connectionString)}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* Help */}
|
||||
{!hasWebLN && connections.length === 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="text-center py-4 space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Install a WebLN extension or connect a NWC wallet for zaps.
|
||||
{/* NWC */}
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">Nostr Wallet Connect</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{connections.length > 0
|
||||
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
|
||||
: "Remote wallet connection"
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{hasNWC && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={hasNWC ? "default" : "secondary"} className="text-xs">
|
||||
{hasNWC ? "Ready" : "None"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
));
|
||||
</div>
|
||||
<Separator />
|
||||
{/* NWC Management */}
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-medium">Nostr Wallet Connect</h3>
|
||||
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
{/* Connected Wallets List */}
|
||||
{connections.length === 0 ? (
|
||||
<div className="text-center py-6 text-muted-foreground">
|
||||
<p className="text-sm">No wallets connected</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{connections.map((connection) => {
|
||||
const info = connectionInfo[connection.connectionString];
|
||||
const isActive = activeConnection === connection.connectionString;
|
||||
return (
|
||||
<div key={connection.connectionString} className={`flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`}>
|
||||
<div className="flex items-center gap-3">
|
||||
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm font-medium">
|
||||
{connection.alias || info?.alias || 'Lightning Wallet'}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
NWC Connection
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{isActive && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
{!isActive && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleSetActive(connection.connectionString)}
|
||||
>
|
||||
<Zap className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleRemoveConnection(connection.connectionString)}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* Help */}
|
||||
{!hasWebLN && connections.length === 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="text-center py-4 space-y-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Install a WebLN extension or connect a NWC wallet for zaps.
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
));
|
||||
WalletContent.displayName = 'WalletContent';
|
||||
|
||||
export function WalletModal({ children, className }: WalletModalProps) {
|
||||
|
||||
@@ -199,13 +199,17 @@ This reverts the codebase back to the state at commit ${targetCommit.oid.substri
|
||||
|
||||
Reverted ${commitsToRevert.length} commit(s):
|
||||
${commitsToRevert.map(c => {
|
||||
const commitFirstLine = getCommitMessageLines(c.commit.message).firstLine;
|
||||
return `- ${c.oid.substring(0, 7)}: ${commitFirstLine}`;
|
||||
}).join('\n')}`;
|
||||
const commitFirstLine = getCommitMessageLines(c.commit.message).firstLine;
|
||||
return `- ${c.oid.substring(0, 7)}: ${commitFirstLine}`;
|
||||
}).join('\n')}`;
|
||||
|
||||
await git.commit({
|
||||
dir: projectPath,
|
||||
message: revertMessage,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
|
||||
toast({
|
||||
|
||||
@@ -186,9 +186,9 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
>
|
||||
<DialogHeader className={cn('px-6 pt-6 pb-1 relative')}>
|
||||
|
||||
<DialogDescription className="text-center">
|
||||
<DialogDescription className="text-center">
|
||||
Sign up or log in to continue
|
||||
</DialogDescription>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1'>
|
||||
{/* Prominent Sign Up Section */}
|
||||
@@ -370,7 +370,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
);
|
||||
};
|
||||
|
||||
export default LoginDialog;
|
||||
@@ -505,11 +505,11 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
|
||||
|
||||
<div className='grid grid-cols-1 gap-2'>
|
||||
{/* Download Option */}
|
||||
<Card className={`cursor-pointer transition-all duration-200 ${
|
||||
<Card className={`cursor-pointer transition-all duration-200 ${
|
||||
keySecured === 'downloaded'
|
||||
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
|
||||
: 'hover:bg-primary/5 hover:border-primary/20'
|
||||
}`}>
|
||||
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
|
||||
: 'hover:bg-primary/5 hover:border-primary/20'
|
||||
}`}>
|
||||
<CardContent className='p-3'>
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -519,39 +519,39 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
|
||||
<div className='flex items-center gap-3 w-full'>
|
||||
<div className={`p-1.5 rounded-lg ${
|
||||
keySecured === 'downloaded'
|
||||
? 'bg-green-100 dark:bg-green-900'
|
||||
: 'bg-primary/10'
|
||||
}`}>
|
||||
? 'bg-green-100 dark:bg-green-900'
|
||||
: 'bg-primary/10'
|
||||
}`}>
|
||||
{keySecured === 'downloaded' ? (
|
||||
<CheckCircle className='w-4 h-4 text-green-600' />
|
||||
) : (
|
||||
<Download className='w-4 h-4 text-primary' />
|
||||
)}
|
||||
<CheckCircle className='w-4 h-4 text-green-600' />
|
||||
) : (
|
||||
<Download className='w-4 h-4 text-primary' />
|
||||
)}
|
||||
</div>
|
||||
<div className='flex-1 text-left'>
|
||||
<div className='font-medium text-sm'>
|
||||
<div className='font-medium text-sm'>
|
||||
Download as File
|
||||
</div>
|
||||
<div className='text-xs text-muted-foreground'>
|
||||
</div>
|
||||
<div className='text-xs text-muted-foreground'>
|
||||
Save as secret-key.txt file
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{keySecured === 'downloaded' && (
|
||||
<div className='text-xs font-medium text-green-600'>
|
||||
<div className='text-xs font-medium text-green-600'>
|
||||
✓ Downloaded
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Copy Option */}
|
||||
<Card className={`cursor-pointer transition-all duration-200 ${
|
||||
<Card className={`cursor-pointer transition-all duration-200 ${
|
||||
keySecured === 'copied'
|
||||
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
|
||||
: 'hover:bg-primary/5 hover:border-primary/20'
|
||||
}`}>
|
||||
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
|
||||
: 'hover:bg-primary/5 hover:border-primary/20'
|
||||
}`}>
|
||||
<CardContent className='p-3'>
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -561,20 +561,20 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
|
||||
<div className='flex items-center gap-3 w-full'>
|
||||
<div className={`p-1.5 rounded-lg ${
|
||||
keySecured === 'copied'
|
||||
? 'bg-green-100 dark:bg-green-900'
|
||||
: 'bg-primary/10'
|
||||
}`}>
|
||||
? 'bg-green-100 dark:bg-green-900'
|
||||
: 'bg-primary/10'
|
||||
}`}>
|
||||
{keySecured === 'copied' ? (
|
||||
<CheckCircle className='w-4 h-4 text-green-600' />
|
||||
) : (
|
||||
<Copy className='w-4 h-4 text-primary' />
|
||||
)}
|
||||
<CheckCircle className='w-4 h-4 text-green-600' />
|
||||
) : (
|
||||
<Copy className='w-4 h-4 text-primary' />
|
||||
)}
|
||||
</div>
|
||||
<div className='flex-1 text-left'>
|
||||
<div className='font-medium text-sm'>
|
||||
<div className='font-medium text-sm'>
|
||||
Copy to Clipboard
|
||||
</div>
|
||||
<div className='text-xs text-muted-foreground'>
|
||||
</div>
|
||||
<div className='text-xs text-muted-foreground'>
|
||||
Save to password manager
|
||||
</div>
|
||||
<div className='text-[.7rem] text-muted-foreground'>
|
||||
@@ -582,10 +582,10 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
|
||||
</div>
|
||||
</div>
|
||||
{keySecured === 'copied' && (
|
||||
<div className='text-xs font-medium text-green-600'>
|
||||
<div className='text-xs font-medium text-green-600'>
|
||||
✓ Copied
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Button>
|
||||
</CardContent>
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Plus, ExternalLink } from 'lucide-react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
|
||||
interface NetlifySite {
|
||||
id: string;
|
||||
site_id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
admin_url: string;
|
||||
}
|
||||
|
||||
interface NetlifyDeployFormProps {
|
||||
apiKey: string;
|
||||
baseURL?: string;
|
||||
projectId: string;
|
||||
projectName?: string;
|
||||
savedSiteId?: string;
|
||||
onSiteChange: (siteId: string, siteName: string) => void;
|
||||
corsProxy?: string;
|
||||
}
|
||||
|
||||
export function NetlifyDeployForm({
|
||||
apiKey,
|
||||
baseURL = 'https://api.netlify.com/api/v1',
|
||||
projectId,
|
||||
projectName,
|
||||
savedSiteId,
|
||||
onSiteChange,
|
||||
corsProxy,
|
||||
}: NetlifyDeployFormProps) {
|
||||
const [sites, setSites] = useState<NetlifySite[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [selectedSiteId, setSelectedSiteId] = useState<string>('');
|
||||
const [newSiteName, setNewSiteName] = useState(projectName || projectId);
|
||||
|
||||
const fetchSites = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const url = `${baseURL}/sites`;
|
||||
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${apiKey}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch sites: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data: NetlifySite[] = await response.json();
|
||||
setSites(data);
|
||||
|
||||
// If there's a saved site ID and it exists in the list, select it
|
||||
// Otherwise leave it empty (showing placeholder)
|
||||
if (savedSiteId && data.some(s => s.id === savedSiteId)) {
|
||||
setSelectedSiteId(savedSiteId);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to fetch sites');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [apiKey, baseURL, savedSiteId, corsProxy]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchSites();
|
||||
}, [fetchSites]);
|
||||
|
||||
// Update newSiteName when switching to "new" if it's empty
|
||||
useEffect(() => {
|
||||
if (selectedSiteId === 'new' && !newSiteName) {
|
||||
setNewSiteName(projectName || projectId);
|
||||
}
|
||||
}, [selectedSiteId, newSiteName, projectName, projectId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedSiteId === '') {
|
||||
// No selection yet - don't call onSiteChange
|
||||
return;
|
||||
} else if (selectedSiteId === 'new') {
|
||||
onSiteChange('', newSiteName);
|
||||
} else {
|
||||
const site = sites.find(s => s.id === selectedSiteId);
|
||||
if (site) {
|
||||
onSiteChange(site.id, site.name);
|
||||
}
|
||||
}
|
||||
}, [selectedSiteId, newSiteName, sites, onSiteChange]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Site</Label>
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const selectedSite = sites.find(s => s.id === selectedSiteId);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="netlify-site">Select Site</Label>
|
||||
<Select value={selectedSiteId} onValueChange={setSelectedSiteId}>
|
||||
<SelectTrigger id="netlify-site">
|
||||
<SelectValue placeholder="Select a site or create new..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="new">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
Create new site
|
||||
</div>
|
||||
</SelectItem>
|
||||
{sites.map((site) => (
|
||||
<SelectItem key={site.id} value={site.id}>
|
||||
{site.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{selectedSiteId === 'new' ? (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="new-site-name">New Site Name</Label>
|
||||
<Input
|
||||
id="new-site-name"
|
||||
value={newSiteName}
|
||||
onChange={(e) => setNewSiteName(e.target.value)}
|
||||
placeholder={projectName || projectId}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Domain: <span className="font-mono">{newSiteName || projectId}.netlify.app</span>
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A new site will be created when you deploy
|
||||
</p>
|
||||
</div>
|
||||
) : selectedSite ? (
|
||||
<div className="space-y-2">
|
||||
<div className="rounded-lg border p-3 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium">{selectedSite.name}</p>
|
||||
<p className="text-xs text-muted-foreground font-mono">{selectedSite.url}</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => window.open(selectedSite.admin_url, '_blank')}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Deployment will update this existing site
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { RefreshCw } from 'lucide-react';
|
||||
|
||||
interface NsiteDeployFormProps {
|
||||
gateway: string;
|
||||
savedNsec?: string;
|
||||
onNsecChange: (nsec: string) => void;
|
||||
}
|
||||
|
||||
export function NsiteDeployForm({
|
||||
gateway,
|
||||
savedNsec,
|
||||
onNsecChange,
|
||||
}: NsiteDeployFormProps) {
|
||||
const [nsec, setNsec] = useState(savedNsec || '');
|
||||
const [npub, setNpub] = useState('');
|
||||
const initialized = useRef(false);
|
||||
|
||||
// Initialize nsec on mount
|
||||
useEffect(() => {
|
||||
if (!initialized.current) {
|
||||
initialized.current = true;
|
||||
if (savedNsec) {
|
||||
// If we have a saved nsec, notify parent immediately
|
||||
onNsecChange(savedNsec);
|
||||
} else if (!nsec) {
|
||||
// Generate a new nsec if none exists
|
||||
const sk = generateSecretKey();
|
||||
const newNsec = nip19.nsecEncode(sk);
|
||||
setNsec(newNsec);
|
||||
onNsecChange(newNsec);
|
||||
}
|
||||
}
|
||||
}, [savedNsec, nsec, onNsecChange]);
|
||||
|
||||
// Update npub when nsec changes
|
||||
useEffect(() => {
|
||||
if (nsec) {
|
||||
try {
|
||||
const decoded = nip19.decode(nsec);
|
||||
if (decoded.type === 'nsec') {
|
||||
const pk = getPublicKey(decoded.data);
|
||||
const npubEncoded = nip19.npubEncode(pk);
|
||||
setNpub(npubEncoded);
|
||||
}
|
||||
} catch {
|
||||
setNpub('');
|
||||
}
|
||||
}
|
||||
}, [nsec]);
|
||||
|
||||
const handleNsecChange = (value: string) => {
|
||||
setNsec(value);
|
||||
onNsecChange(value);
|
||||
};
|
||||
|
||||
const handleGenerateNew = () => {
|
||||
const sk = generateSecretKey();
|
||||
const newNsec = nip19.nsecEncode(sk);
|
||||
setNsec(newNsec);
|
||||
onNsecChange(newNsec);
|
||||
};
|
||||
|
||||
const fullDomain = npub ? `${npub}.${gateway}` : `npub1...${gateway}`;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Site URL</Label>
|
||||
<p className="text-sm font-mono bg-muted p-2 rounded-md break-all">
|
||||
{fullDomain}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Each site has a unique Nostr keypair
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nsite-nsec">Site Private Key (nsec)</Label>
|
||||
<div className="flex gap-2">
|
||||
<PasswordInput
|
||||
id="nsite-nsec"
|
||||
value={nsec}
|
||||
onChange={(e) => handleNsecChange(e.target.value)}
|
||||
placeholder="nsec1..."
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleGenerateNew}
|
||||
title="Generate new key"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Keep this private key secure. It's used to sign site metadata.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
|
||||
interface ShakespeareDeployFormProps {
|
||||
host?: string;
|
||||
projectId: string;
|
||||
onSubdomainChange: (subdomain: string) => void;
|
||||
}
|
||||
|
||||
export function ShakespeareDeployForm({
|
||||
host = 'shakespeare.wtf',
|
||||
projectId,
|
||||
onSubdomainChange,
|
||||
}: ShakespeareDeployFormProps) {
|
||||
const [subdomain, setSubdomain] = useState(projectId);
|
||||
|
||||
useEffect(() => {
|
||||
onSubdomainChange(subdomain);
|
||||
}, [subdomain, onSubdomainChange]);
|
||||
|
||||
const fullDomain = subdomain ? `${subdomain}.${host}` : `${projectId}.${host}`;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="shakespeare-subdomain">Subdomain</Label>
|
||||
<Input
|
||||
id="shakespeare-subdomain"
|
||||
value={subdomain}
|
||||
onChange={(e) => setSubdomain(e.target.value)}
|
||||
placeholder={projectId}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Will deploy to: <span className="font-mono">{fullDomain}</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
|
||||
interface VercelDeployFormProps {
|
||||
projectId: string;
|
||||
projectName?: string;
|
||||
savedTeamId?: string;
|
||||
savedProjectName?: string;
|
||||
onConfigChange: (projectName: string, teamId: string) => void;
|
||||
}
|
||||
|
||||
export function VercelDeployForm({
|
||||
projectId,
|
||||
projectName: initialProjectName,
|
||||
savedTeamId,
|
||||
savedProjectName,
|
||||
onConfigChange,
|
||||
}: VercelDeployFormProps) {
|
||||
const [projectName, setProjectName] = useState(savedProjectName || initialProjectName || projectId);
|
||||
const [teamId, setTeamId] = useState(savedTeamId || '');
|
||||
|
||||
useEffect(() => {
|
||||
onConfigChange(projectName, teamId);
|
||||
}, [projectName, teamId, onConfigChange]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="vercel-project-name">Project Name</Label>
|
||||
<Input
|
||||
id="vercel-project-name"
|
||||
value={projectName}
|
||||
onChange={(e) => setProjectName(e.target.value)}
|
||||
placeholder={initialProjectName || projectId}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
URL: <span className="font-mono">{projectName || projectId}.vercel.app</span>
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="vercel-team-id">Team ID (optional)</Label>
|
||||
<Input
|
||||
id="vercel-team-id"
|
||||
value={teamId}
|
||||
onChange={(e) => setTeamId(e.target.value)}
|
||||
placeholder="Leave empty for personal account"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Deploy to a team account instead of your personal account
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
export { ShakespeareDeployForm } from './ShakespeareDeployForm';
|
||||
export { NetlifyDeployForm } from './NetlifyDeployForm';
|
||||
export { VercelDeployForm } from './VercelDeployForm';
|
||||
export { NsiteDeployForm } from './NsiteDeployForm';
|
||||
@@ -1,569 +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 {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import {
|
||||
GitBranch,
|
||||
Loader2,
|
||||
AlertCircle,
|
||||
CheckCircle,
|
||||
Plus,
|
||||
X,
|
||||
Megaphone,
|
||||
} from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostr } from '@/hooks/useNostr';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
interface AnnounceRepositoryDialogProps {
|
||||
projectId: string;
|
||||
remoteUrl?: string;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function AnnounceRepositoryDialog({
|
||||
projectId,
|
||||
remoteUrl,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: AnnounceRepositoryDialogProps) {
|
||||
const [isOpen, setIsOpen] = useState(open ?? false);
|
||||
const [repoId, setRepoId] = useState('');
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [webUrls, setWebUrls] = useState<string[]>([]);
|
||||
const [cloneUrls, setCloneUrls] = useState<string[]>([]);
|
||||
const [relays, setRelays] = useState<string[]>(['wss://relay.nostr.band']);
|
||||
const [earliestCommit, setEarliestCommit] = useState('');
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [createdNaddr, setCreatedNaddr] = useState<string | null>(null);
|
||||
|
||||
const [newWebUrl, setNewWebUrl] = useState('');
|
||||
const [newCloneUrl, setNewCloneUrl] = useState('');
|
||||
const [newRelay, setNewRelay] = useState('');
|
||||
|
||||
const { git } = useGit();
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
const { toast } = useToast();
|
||||
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
useEffect(() => {
|
||||
if (open !== undefined) {
|
||||
setIsOpen(open);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const parseRemoteUrl = useCallback((url: string) => {
|
||||
// Extract repo ID from Nostr URL
|
||||
if (url.startsWith('nostr://')) {
|
||||
const match = url.match(/^nostr:\/\/[^/]+\/(.+)$/);
|
||||
if (match) {
|
||||
const id = match[1];
|
||||
setRepoId(id);
|
||||
setName(id.split('/').pop() || id);
|
||||
}
|
||||
}
|
||||
|
||||
// Add the remote URL as a clone URL
|
||||
if (url && !cloneUrls.includes(url)) {
|
||||
setCloneUrls([url]);
|
||||
}
|
||||
}, [cloneUrls]);
|
||||
|
||||
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]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen && remoteUrl) {
|
||||
// Parse remote URL to pre-fill data
|
||||
parseRemoteUrl(remoteUrl);
|
||||
// Get earliest commit
|
||||
getEarliestCommit();
|
||||
}
|
||||
}, [isOpen, remoteUrl, parseRemoteUrl, getEarliestCommit]);
|
||||
|
||||
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 = () => {
|
||||
if (newCloneUrl.trim() && !cloneUrls.includes(newCloneUrl.trim())) {
|
||||
setCloneUrls([...cloneUrls, newCloneUrl.trim()]);
|
||||
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;
|
||||
}
|
||||
|
||||
if (!repoId.trim()) {
|
||||
toast({
|
||||
title: 'Repository ID required',
|
||||
description: 'Please enter a repository identifier',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (cloneUrls.length === 0) {
|
||||
toast({
|
||||
title: 'Clone URL required',
|
||||
description: 'Please add at least one clone URL',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCreating(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Build tags array per NIP-34
|
||||
const tags: string[][] = [
|
||||
['d', repoId.trim()], // Required: repository identifier
|
||||
];
|
||||
|
||||
if (name.trim()) {
|
||||
tags.push(['name', name.trim()]);
|
||||
}
|
||||
|
||||
if (description.trim()) {
|
||||
tags.push(['description', description.trim()]);
|
||||
}
|
||||
|
||||
// Add web URLs
|
||||
webUrls.forEach(url => {
|
||||
if (url.trim()) tags.push(['web', url.trim()]);
|
||||
});
|
||||
|
||||
// Add clone URLs (required)
|
||||
cloneUrls.forEach(url => {
|
||||
if (url.trim()) tags.push(['clone', url.trim()]);
|
||||
});
|
||||
|
||||
// Add relays for patch submissions
|
||||
relays.forEach(relay => {
|
||||
if (relay.trim()) tags.push(['relays', relay.trim()]);
|
||||
});
|
||||
|
||||
// Add earliest unique commit (euc) for repository identification
|
||||
if (earliestCommit.trim()) {
|
||||
tags.push(['r', earliestCommit.trim(), 'euc']);
|
||||
}
|
||||
|
||||
// Create repository announcement event (kind 30617)
|
||||
const repoEvent = {
|
||||
kind: 30617,
|
||||
content: '',
|
||||
tags,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
};
|
||||
|
||||
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
|
||||
await nostr.event(signedEvent);
|
||||
|
||||
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
|
||||
const naddr = nip19.naddrEncode({
|
||||
identifier: repoId.trim(),
|
||||
pubkey: user.pubkey,
|
||||
kind: 30617,
|
||||
relays: relays.length > 0 ? relays : undefined,
|
||||
});
|
||||
|
||||
setCreatedNaddr(naddr);
|
||||
|
||||
toast({
|
||||
title: 'Repository announced!',
|
||||
description: 'Your repository has been announced on Nostr',
|
||||
});
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
|
||||
setError(errorMessage);
|
||||
toast({
|
||||
title: 'Failed to announce repository',
|
||||
description: errorMessage,
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
setIsOpen(newOpen);
|
||||
onOpenChange?.(newOpen);
|
||||
|
||||
// Reset form when closing
|
||||
if (!newOpen) {
|
||||
setRepoId('');
|
||||
setName('');
|
||||
setDescription('');
|
||||
setWebUrls([]);
|
||||
setCloneUrls([]);
|
||||
setRelays(['wss://relay.nostr.band']);
|
||||
setEarliestCommit('');
|
||||
setCreatedNaddr(null);
|
||||
setError(null);
|
||||
setNewWebUrl('');
|
||||
setNewCloneUrl('');
|
||||
setNewRelay('');
|
||||
}
|
||||
};
|
||||
|
||||
const copyNaddr = () => {
|
||||
if (createdNaddr) {
|
||||
navigator.clipboard.writeText(createdNaddr);
|
||||
toast({
|
||||
title: 'Copied to clipboard',
|
||||
description: 'Repository address copied',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" className="gap-2">
|
||||
<Megaphone className="h-4 w-4" />
|
||||
Announce Repository
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Megaphone className="h-5 w-5" />
|
||||
Announce Repository on Nostr
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Publish a repository announcement (NIP-34) to make it discoverable on Nostr git
|
||||
clients
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{createdNaddr ? (
|
||||
// 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">Repository Announced!</h3>
|
||||
<p className="text-muted-foreground">
|
||||
Your repository is now discoverable on Nostr git clients
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-muted/30 rounded-lg p-4 space-y-2">
|
||||
<Label>Repository Address (naddr)</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={createdNaddr}
|
||||
readOnly
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={copyNaddr}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Share this address with others to let them find your repository
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
// Form
|
||||
<ScrollArea className="max-h-[60vh]">
|
||||
<div className="space-y-6 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 or username/repo-name"
|
||||
value={repoId}
|
||||
onChange={(e) => setRepoId(e.target.value)}
|
||||
disabled={isCreating}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Unique identifier for this repository (like GitHub's owner/repo)
|
||||
</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}
|
||||
/>
|
||||
</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>
|
||||
|
||||
{/* 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} readOnly className="flex-1" />
|
||||
<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>Clone URLs *</Label>
|
||||
<div className="space-y-2">
|
||||
{cloneUrls.map((url, index) => (
|
||||
<div key={index} className="flex gap-2">
|
||||
<Input value={url} readOnly className="flex-1 font-mono text-sm" />
|
||||
<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="nostr://npub.../repo-id"
|
||||
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">
|
||||
URLs for cloning the repository (at least one required)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Relays */}
|
||||
<div className="space-y-2">
|
||||
<Label>Relays for Patches</Label>
|
||||
<div className="space-y-2">
|
||||
{relays.map((relay, index) => (
|
||||
<div key={index} className="flex gap-2">
|
||||
<Input value={relay} readOnly className="flex-1 font-mono text-sm" />
|
||||
<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">
|
||||
Relays where patches will be published and monitored
|
||||
</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 when available)
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)}
|
||||
|
||||
{!createdNaddr && (
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={isCreating}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={announceRepository} disabled={isCreating}>
|
||||
{isCreating ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Announcing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GitBranch className="h-4 w-4 mr-2" />
|
||||
Announce Repository
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,510 +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 { 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 { toast } = useToast();
|
||||
const projectPath = `/projects/${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,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Branch created',
|
||||
description: `Created branch "${newBranchName}"`,
|
||||
});
|
||||
|
||||
setNewBranchName('');
|
||||
setIsCreateDialogOpen(false);
|
||||
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,350 +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 { 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 { toast } = useToast();
|
||||
const projectPath = `/projects/${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,556 +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 { 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 { fs } = useFS();
|
||||
const { toast } = useToast();
|
||||
const projectPath = `/projects/${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,166 +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';
|
||||
|
||||
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 projectPath = `/projects/${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,574 +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 { 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 { toast } = useToast();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const projectPath = `/projects/${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>
|
||||
);
|
||||
}
|
||||
@@ -1,563 +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 {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
GitPullRequest,
|
||||
Loader2,
|
||||
AlertCircle,
|
||||
CheckCircle,
|
||||
ExternalLink,
|
||||
GitCompare,
|
||||
GitFork,
|
||||
} from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
|
||||
interface PullRequestFormProps {
|
||||
projectId: string;
|
||||
currentBranch: string | null;
|
||||
remoteUrl: string;
|
||||
}
|
||||
|
||||
interface RemoteInfo {
|
||||
owner: string;
|
||||
repo: string;
|
||||
platform: 'github' | 'gitlab';
|
||||
apiUrl: string;
|
||||
}
|
||||
|
||||
interface ForkInfo {
|
||||
needsFork: boolean;
|
||||
forkOwner?: string;
|
||||
forkRepo?: string;
|
||||
forkUrl?: string;
|
||||
}
|
||||
|
||||
export function PullRequestForm({ projectId, currentBranch, remoteUrl }: PullRequestFormProps) {
|
||||
const [title, setTitle] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [targetBranch, setTargetBranch] = useState('main');
|
||||
const [remoteBranches, setRemoteBranches] = useState<string[]>([]);
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [remoteInfo, setRemoteInfo] = useState<RemoteInfo | null>(null);
|
||||
const [forkInfo, setForkInfo] = useState<ForkInfo>({ needsFork: false });
|
||||
const [isCheckingPermissions, setIsCheckingPermissions] = useState(false);
|
||||
const [createdPrUrl, setCreatedPrUrl] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const { git } = useGit();
|
||||
const { settings } = useGitSettings();
|
||||
const { toast } = useToast();
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
// All the helper functions from PullRequestDialog can be reused here
|
||||
// (parseRemoteUrl, checkPushPermissions, ensureFork, etc.)
|
||||
// For brevity, I'll import them or duplicate the core logic
|
||||
|
||||
const parseRemoteUrl = useCallback((url: string) => {
|
||||
// Same implementation as PullRequestDialog
|
||||
setError(null);
|
||||
try {
|
||||
let match;
|
||||
let owner = '';
|
||||
let repo = '';
|
||||
let platform: 'github' | 'gitlab' = 'github';
|
||||
let apiUrl = '';
|
||||
|
||||
const normalizedUrl = url.replace(/\.git$/, '');
|
||||
|
||||
// GitHub SSH/HTTPS
|
||||
match = normalizedUrl.match(/git@github\.com:([^/]+)\/(.+)$/) ||
|
||||
normalizedUrl.match(/https?:\/\/github\.com\/([^/]+)\/(.+)$/);
|
||||
if (match) {
|
||||
owner = match[1];
|
||||
repo = match[2];
|
||||
platform = 'github';
|
||||
apiUrl = 'https://api.github.com';
|
||||
}
|
||||
|
||||
// GitLab SSH/HTTPS
|
||||
if (!match) {
|
||||
match = normalizedUrl.match(/git@gitlab\.com:([^/]+)\/(.+)$/) ||
|
||||
normalizedUrl.match(/https?:\/\/gitlab\.com\/([^/]+)\/(.+)$/);
|
||||
if (match) {
|
||||
owner = match[1];
|
||||
repo = match[2];
|
||||
platform = 'gitlab';
|
||||
apiUrl = 'https://gitlab.com/api/v4';
|
||||
}
|
||||
}
|
||||
|
||||
if (owner && repo) {
|
||||
setRemoteInfo({ owner, repo, platform, apiUrl });
|
||||
} else {
|
||||
setError('Unsupported remote URL format');
|
||||
}
|
||||
} catch {
|
||||
setError('Failed to parse remote URL');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadRemoteBranches = useCallback(async () => {
|
||||
try {
|
||||
const branches = await git.listBranches({
|
||||
dir: projectPath,
|
||||
remote: 'origin',
|
||||
});
|
||||
setRemoteBranches(branches);
|
||||
|
||||
if (branches.includes('main')) {
|
||||
setTargetBranch('main');
|
||||
} else if (branches.includes('master')) {
|
||||
setTargetBranch('master');
|
||||
} else if (branches.length > 0) {
|
||||
setTargetBranch(branches[0]);
|
||||
}
|
||||
} catch {
|
||||
setRemoteBranches(['main', 'master', 'develop']);
|
||||
}
|
||||
}, [git, projectPath]);
|
||||
|
||||
const checkPermissionsAndFork = useCallback(async () => {
|
||||
if (!remoteInfo) return;
|
||||
|
||||
setIsCheckingPermissions(true);
|
||||
try {
|
||||
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
if (!credentials) {
|
||||
setForkInfo({ needsFork: false });
|
||||
return;
|
||||
}
|
||||
|
||||
// Simplified permission check - assume fork needed if we get 403/404
|
||||
// Full implementation would use the helper functions from PullRequestDialog
|
||||
setForkInfo({ needsFork: false });
|
||||
} catch {
|
||||
setForkInfo({ needsFork: false });
|
||||
} finally {
|
||||
setIsCheckingPermissions(false);
|
||||
}
|
||||
}, [remoteInfo, remoteUrl, settings.credentials]);
|
||||
|
||||
useEffect(() => {
|
||||
if (remoteUrl) {
|
||||
parseRemoteUrl(remoteUrl);
|
||||
loadRemoteBranches();
|
||||
checkPermissionsAndFork();
|
||||
}
|
||||
}, [remoteUrl, parseRemoteUrl, loadRemoteBranches, checkPermissionsAndFork]);
|
||||
|
||||
const createPullRequest = async () => {
|
||||
if (!remoteInfo || !currentBranch) return;
|
||||
|
||||
if (!title.trim()) {
|
||||
toast({
|
||||
title: 'Title required',
|
||||
description: 'Please enter a title for the pull request',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCreating(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
if (!credentials) {
|
||||
throw new Error('No credentials found. Please add credentials in Settings > Git');
|
||||
}
|
||||
|
||||
// Check if user is on main/master - if so, create a feature branch
|
||||
let branchToUse = currentBranch;
|
||||
const isOnDefaultBranch = currentBranch === 'main' || currentBranch === 'master';
|
||||
|
||||
if (isOnDefaultBranch) {
|
||||
console.log(`User is on default branch '${currentBranch}', creating feature branch`);
|
||||
|
||||
// Generate branch name from PR title
|
||||
const sanitizedTitle = title
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9\s-]/g, '')
|
||||
.replace(/\s+/g, '-')
|
||||
.replace(/-+/g, '-')
|
||||
.replace(/^-|-$/g, '')
|
||||
.substring(0, 50);
|
||||
|
||||
const baseName = sanitizedTitle || 'feature';
|
||||
const featureBranchName = `${baseName}-${Date.now().toString(36).slice(-4)}`;
|
||||
console.log(`Creating feature branch: ${featureBranchName}`);
|
||||
|
||||
try {
|
||||
// Check for uncommitted changes BEFORE creating branch
|
||||
const statusMatrix = await git.statusMatrix({ dir: projectPath });
|
||||
const hasUncommittedChanges = statusMatrix.some(([, head, workdir]) => head !== workdir);
|
||||
|
||||
// Create and checkout branch first
|
||||
await git.branch({
|
||||
dir: projectPath,
|
||||
ref: featureBranchName,
|
||||
checkout: true,
|
||||
});
|
||||
|
||||
branchToUse = featureBranchName;
|
||||
console.log(`Successfully created and checked out branch: ${featureBranchName}`);
|
||||
|
||||
// If there were uncommitted changes, commit them to the new branch
|
||||
if (hasUncommittedChanges) {
|
||||
console.log('Committing changes to new branch');
|
||||
|
||||
for (const [filepath, , workdir] of statusMatrix) {
|
||||
if ((workdir as number) === 0) {
|
||||
await git.remove({ dir: projectPath, filepath });
|
||||
} else if ((workdir as number) !== 0) {
|
||||
await git.add({ dir: projectPath, filepath });
|
||||
}
|
||||
}
|
||||
|
||||
await git.commit({
|
||||
dir: projectPath,
|
||||
message: title,
|
||||
});
|
||||
|
||||
console.log('Committed changes to new branch');
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Feature branch created',
|
||||
description: `Created branch '${featureBranchName}' for your changes`,
|
||||
});
|
||||
} catch (branchError) {
|
||||
console.error('Failed to create feature branch:', branchError);
|
||||
throw new Error(
|
||||
`Cannot create PR from '${currentBranch}' branch.\n\n` +
|
||||
`Failed to create a feature branch automatically.\n` +
|
||||
`Please create a new branch manually in the Branches tab first.\n\n` +
|
||||
`Error: ${branchError instanceof Error ? branchError.message : 'Unknown error'}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// If fork is needed, push the branch first
|
||||
const headRef = forkInfo.needsFork && forkInfo.forkOwner
|
||||
? `${forkInfo.forkOwner}:${branchToUse}`
|
||||
: branchToUse;
|
||||
|
||||
console.log('PR head ref will be:', headRef);
|
||||
console.log('PR base ref will be:', targetBranch);
|
||||
|
||||
if (forkInfo.needsFork && forkInfo.forkUrl) {
|
||||
console.log(`Pushing branch ${branchToUse} to fork ${forkInfo.forkUrl}`);
|
||||
|
||||
// Check current remotes
|
||||
const remotes = await git.listRemotes({ dir: projectPath });
|
||||
const originRemote = remotes.find(r => r.remote === 'origin');
|
||||
const forkRemote = remotes.find(r => r.url === forkInfo.forkUrl);
|
||||
|
||||
let pushRemote = 'origin';
|
||||
|
||||
if (originRemote?.url !== forkInfo.forkUrl) {
|
||||
if (forkRemote) {
|
||||
pushRemote = forkRemote.remote;
|
||||
} else {
|
||||
await git.addRemote({
|
||||
dir: projectPath,
|
||||
remote: 'fork',
|
||||
url: forkInfo.forkUrl,
|
||||
});
|
||||
pushRemote = 'fork';
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await git.push({
|
||||
dir: projectPath,
|
||||
remote: pushRemote,
|
||||
ref: branchToUse,
|
||||
onAuth: () => credentials,
|
||||
});
|
||||
console.log('Successfully pushed to fork');
|
||||
} catch (pushError) {
|
||||
const errorMsg = pushError instanceof Error ? pushError.message : 'Unknown error';
|
||||
throw new Error(
|
||||
`Failed to push branch '${branchToUse}' to your fork.\n\n` +
|
||||
`This usually means:\n` +
|
||||
`1. The branch hasn't been committed yet\n` +
|
||||
`2. Network/authentication issues\n\n` +
|
||||
`Error: ${errorMsg}\n\n` +
|
||||
`Try committing and pushing manually first.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const url = `${remoteInfo.apiUrl}/repos/${remoteInfo.owner}/${remoteInfo.repo}/pulls`;
|
||||
|
||||
const prData = {
|
||||
title,
|
||||
body: description,
|
||||
head: headRef,
|
||||
base: targetBranch,
|
||||
maintainer_can_modify: true,
|
||||
};
|
||||
|
||||
console.log('Creating PR with data:', prData);
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `token ${credentials.password}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(prData),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
console.error('PR creation failed:', errorText);
|
||||
|
||||
let error;
|
||||
try {
|
||||
error = JSON.parse(errorText);
|
||||
} catch {
|
||||
error = { message: errorText || 'Unknown error' };
|
||||
}
|
||||
|
||||
// Extract detailed error messages
|
||||
let errorMessage = error.message || `API error: ${response.status} - ${response.statusText}`;
|
||||
|
||||
if (error.errors && Array.isArray(error.errors)) {
|
||||
const errorDetails = error.errors.map((e: { message?: string; field?: string; code?: string }) => {
|
||||
if (e.message) return e.message;
|
||||
if (e.field && e.code) return `${e.field}: ${e.code}`;
|
||||
return JSON.stringify(e);
|
||||
}).join('; ');
|
||||
errorMessage = `${errorMessage}\n\nDetails: ${errorDetails}`;
|
||||
}
|
||||
|
||||
if (error.documentation_url) {
|
||||
errorMessage = `${errorMessage}\n\nSee: ${error.documentation_url}`;
|
||||
}
|
||||
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setCreatedPrUrl(data.html_url);
|
||||
|
||||
toast({
|
||||
title: 'Pull request created',
|
||||
description: 'Successfully created pull request',
|
||||
});
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
|
||||
setError(errorMessage);
|
||||
toast({
|
||||
title: 'Failed to create pull request',
|
||||
description: errorMessage,
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!currentBranch) {
|
||||
return (
|
||||
<Alert>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
No branch selected. Please select or create a branch first.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
if (createdPrUrl) {
|
||||
return (
|
||||
<div className="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">Pull Request Created!</h3>
|
||||
<p className="text-muted-foreground">
|
||||
Your pull request has been created successfully
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => window.open(createdPrUrl, '_blank')}
|
||||
className="gap-2"
|
||||
>
|
||||
View Pull Request
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setCreatedPrUrl(null);
|
||||
setTitle('');
|
||||
setDescription('');
|
||||
}}
|
||||
>
|
||||
Create Another
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Permission/Fork info */}
|
||||
{isCheckingPermissions && (
|
||||
<Alert>
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<AlertDescription>Checking repository permissions...</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{forkInfo.needsFork && forkInfo.forkOwner && (
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
You don't have push access. Your changes will be pushed to your fork at <strong>{forkInfo.forkOwner}/{forkInfo.forkRepo}</strong>.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Auto-branch creation notice */}
|
||||
{currentBranch && (currentBranch === 'main' || currentBranch === 'master') && (
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
You're on the <strong>{currentBranch}</strong> branch. A feature branch will be automatically created from your PR title for this contribution.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Branch comparison */}
|
||||
<div className="bg-muted/30 rounded-lg p-4">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Badge variant="outline" className="font-mono">
|
||||
{targetBranch}
|
||||
</Badge>
|
||||
<GitCompare className="h-4 w-4 text-muted-foreground" />
|
||||
<Badge variant="outline" className="font-mono">
|
||||
{currentBranch}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-2">
|
||||
Merge {currentBranch} into {targetBranch}
|
||||
</p>
|
||||
{(currentBranch === 'main' || currentBranch === 'master') && (
|
||||
<p className="text-xs text-blue-600 dark:text-blue-400 mt-1">
|
||||
Note: A new branch will be created automatically
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Error alert */}
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="whitespace-pre-wrap">{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Target branch */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="target-branch">Target Branch</Label>
|
||||
<Select value={targetBranch} onValueChange={setTargetBranch} disabled={isCreating}>
|
||||
<SelectTrigger id="target-branch">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{remoteBranches.map((branch) => (
|
||||
<SelectItem key={branch} value={branch}>
|
||||
{branch}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Title */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="pr-title">Title *</Label>
|
||||
<Input
|
||||
id="pr-title"
|
||||
placeholder="Brief description of your changes"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
disabled={isCreating}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="pr-description">Description</Label>
|
||||
<Textarea
|
||||
id="pr-description"
|
||||
placeholder="Provide more details about your changes (supports Markdown)"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
rows={8}
|
||||
disabled={isCreating}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Create button */}
|
||||
<Button
|
||||
onClick={createPullRequest}
|
||||
disabled={isCreating || isCheckingPermissions}
|
||||
className="w-full"
|
||||
>
|
||||
{isCreating ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{forkInfo.needsFork ? 'Creating fork & PR...' : 'Creating...'}
|
||||
</>
|
||||
) : forkInfo.needsFork ? (
|
||||
<>
|
||||
<GitFork className="h-4 w-4 mr-2" />
|
||||
Fork & Create PR
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GitPullRequest className="h-4 w-4 mr-2" />
|
||||
Create Pull Request
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Repository info */}
|
||||
{remoteInfo && (
|
||||
<div className="bg-muted/30 rounded-lg p-3">
|
||||
<div className="text-sm space-y-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Repository:</span>
|
||||
<span className="font-medium">
|
||||
{remoteInfo.owner}/{remoteInfo.repo}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Platform:</span>
|
||||
<Badge variant="outline" className="capitalize">
|
||||
{remoteInfo.platform}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
export { AnnounceRepositoryDialog } from './AnnounceRepositoryDialog';
|
||||
export { BranchManager } from './BranchManager';
|
||||
export { CompareView } from './CompareView';
|
||||
export { DiffViewer } from './DiffViewer';
|
||||
export { GitManagementDialog } from './GitManagementDialog';
|
||||
export { MergeDialog } from './MergeDialog';
|
||||
export { PullRequestDialog } from './PullRequestDialog';
|
||||
@@ -1,63 +1,63 @@
|
||||
import React from 'react';
|
||||
|
||||
interface QuillySVGProps extends React.SVGProps<SVGSVGElement> {
|
||||
className?: string;
|
||||
fillColor?: string;
|
||||
className?: string;
|
||||
fillColor?: string;
|
||||
}
|
||||
|
||||
export function QuillySVG({ className = "w-4 h-4", fillColor = "currentColor", ...props }: QuillySVGProps) {
|
||||
return (
|
||||
<svg
|
||||
className={className}
|
||||
viewBox="140 30 220 420"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
{...props}
|
||||
>
|
||||
{/* Main quill head/top part */}
|
||||
<path fill={fillColor} d="M 241.5,33.5 C 246.833,33.5 252.167,33.5 257.5,33.5C 269.508,34.507 280.508,38.3403 290.5,45C 294,47.3342 297,50.1675 299.5,53.5C 298.21,54.0577 297.377,55.0577 297,56.5C 294.888,52.8729 293.221,52.8729 292,56.5C 291.086,55.3463 290.253,55.513 289.5,57C 292.321,58.6213 292.987,60.788 291.5,63.5C 281.078,49.3135 266.911,42.3135 249,42.5C 229.512,42.5414 213.845,50.2081 202,65.5C 196.198,75.0401 193.698,85.3734 194.5,96.5C 193.546,91.1876 192.546,85.1876 191.5,78.5C 189.508,78.6715 187.842,78.0049 186.5,76.5C 183.867,77.7822 183.867,79.1156 186.5,80.5C 185.234,81.3624 183.901,82.0291 182.5,82.5C 183.047,79.2976 184.047,76.2976 185.5,73.5C 186.906,73.0269 187.573,72.0269 187.5,70.5C 188.498,66.4945 190.498,63.1612 193.5,60.5C 194.906,60.0269 195.573,59.0269 195.5,57.5C 196.833,55.8333 198.167,54.1667 199.5,52.5C 211.392,41.6322 225.392,35.2989 241.5,33.5 Z" />
|
||||
return (
|
||||
<svg
|
||||
className={className}
|
||||
viewBox="140 30 220 420"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
{...props}
|
||||
>
|
||||
{/* Main quill head/top part */}
|
||||
<path fill={fillColor} d="M 241.5,33.5 C 246.833,33.5 252.167,33.5 257.5,33.5C 269.508,34.507 280.508,38.3403 290.5,45C 294,47.3342 297,50.1675 299.5,53.5C 298.21,54.0577 297.377,55.0577 297,56.5C 294.888,52.8729 293.221,52.8729 292,56.5C 291.086,55.3463 290.253,55.513 289.5,57C 292.321,58.6213 292.987,60.788 291.5,63.5C 281.078,49.3135 266.911,42.3135 249,42.5C 229.512,42.5414 213.845,50.2081 202,65.5C 196.198,75.0401 193.698,85.3734 194.5,96.5C 193.546,91.1876 192.546,85.1876 191.5,78.5C 189.508,78.6715 187.842,78.0049 186.5,76.5C 183.867,77.7822 183.867,79.1156 186.5,80.5C 185.234,81.3624 183.901,82.0291 182.5,82.5C 183.047,79.2976 184.047,76.2976 185.5,73.5C 186.906,73.0269 187.573,72.0269 187.5,70.5C 188.498,66.4945 190.498,63.1612 193.5,60.5C 194.906,60.0269 195.573,59.0269 195.5,57.5C 196.833,55.8333 198.167,54.1667 199.5,52.5C 211.392,41.6322 225.392,35.2989 241.5,33.5 Z" />
|
||||
|
||||
{/* Main quill feather/plume part */}
|
||||
<path fill={fillColor} d="M 299.5,53.5 C 305.302,58.4362 309.635,64.4362 312.5,71.5C 312.343,72.8734 312.51,74.2068 313,75.5C 313.876,77.7582 315.043,79.7582 316.5,81.5C 318.737,87.0285 320.903,92.6952 323,98.5C 328.732,104.725 334.232,111.058 339.5,117.5C 339.427,119.027 340.094,120.027 341.5,120.5C 343.293,122.426 344.293,124.759 344.5,127.5C 345.22,133.138 345.553,138.804 345.5,144.5C 344.999,150.505 342.499,155.505 338,159.5C 338.33,165.569 338.164,171.569 337.5,177.5C 336.732,178.263 336.232,179.263 336,180.5C 335.261,178.779 334.427,177.113 333.5,175.5C 333.034,177.705 333.034,179.705 333.5,181.5C 332.23,180.438 331.063,179.438 330,178.5C 329.667,178.833 329.333,179.167 329,179.5C 328.333,178.5 328.333,177.5 329,176.5C 329.718,177.451 330.551,177.617 331.5,177C 330.418,175.67 329.751,174.17 329.5,172.5C 329.799,170.396 329.466,168.396 328.5,166.5C 317.499,170.764 306.666,170.431 296,165.5C 295.617,166.056 295.117,166.389 294.5,166.5C 293.533,167.806 292.199,168.473 290.5,168.5C 290.688,170.103 290.188,171.437 289,172.5C 287.477,170.431 286.643,168.097 286.5,165.5C 287.351,161.435 288.517,157.435 290,153.5C 293.306,151.968 296.806,150.801 300.5,150C 303.708,147.229 305.708,143.729 306.5,139.5C 305.527,137.36 304.027,135.693 302,134.5C 299.684,135.367 297.684,134.701 296,132.5C 293.685,129.223 292.351,125.556 292,121.5C 292.692,108.983 293.858,96.4825 295.5,84C 295.554,78.7227 294.887,73.556 293.5,68.5C 293.771,66.6203 293.104,65.287 291.5,64.5C 291.5,64.1667 291.5,63.8333 291.5,63.5C 292.987,60.788 292.321,58.6213 289.5,57C 290.253,55.513 291.086,55.3463 292,56.5C 293.221,52.8729 294.888,52.8729 297,56.5C 297.377,55.0577 298.21,54.0577 299.5,53.5 Z" />
|
||||
{/* Main quill feather/plume part */}
|
||||
<path fill={fillColor} d="M 299.5,53.5 C 305.302,58.4362 309.635,64.4362 312.5,71.5C 312.343,72.8734 312.51,74.2068 313,75.5C 313.876,77.7582 315.043,79.7582 316.5,81.5C 318.737,87.0285 320.903,92.6952 323,98.5C 328.732,104.725 334.232,111.058 339.5,117.5C 339.427,119.027 340.094,120.027 341.5,120.5C 343.293,122.426 344.293,124.759 344.5,127.5C 345.22,133.138 345.553,138.804 345.5,144.5C 344.999,150.505 342.499,155.505 338,159.5C 338.33,165.569 338.164,171.569 337.5,177.5C 336.732,178.263 336.232,179.263 336,180.5C 335.261,178.779 334.427,177.113 333.5,175.5C 333.034,177.705 333.034,179.705 333.5,181.5C 332.23,180.438 331.063,179.438 330,178.5C 329.667,178.833 329.333,179.167 329,179.5C 328.333,178.5 328.333,177.5 329,176.5C 329.718,177.451 330.551,177.617 331.5,177C 330.418,175.67 329.751,174.17 329.5,172.5C 329.799,170.396 329.466,168.396 328.5,166.5C 317.499,170.764 306.666,170.431 296,165.5C 295.617,166.056 295.117,166.389 294.5,166.5C 293.533,167.806 292.199,168.473 290.5,168.5C 290.688,170.103 290.188,171.437 289,172.5C 287.477,170.431 286.643,168.097 286.5,165.5C 287.351,161.435 288.517,157.435 290,153.5C 293.306,151.968 296.806,150.801 300.5,150C 303.708,147.229 305.708,143.729 306.5,139.5C 305.527,137.36 304.027,135.693 302,134.5C 299.684,135.367 297.684,134.701 296,132.5C 293.685,129.223 292.351,125.556 292,121.5C 292.692,108.983 293.858,96.4825 295.5,84C 295.554,78.7227 294.887,73.556 293.5,68.5C 293.771,66.6203 293.104,65.287 291.5,64.5C 291.5,64.1667 291.5,63.8333 291.5,63.5C 292.987,60.788 292.321,58.6213 289.5,57C 290.253,55.513 291.086,55.3463 292,56.5C 293.221,52.8729 294.888,52.8729 297,56.5C 297.377,55.0577 298.21,54.0577 299.5,53.5 Z" />
|
||||
|
||||
{/* Body/torso part */}
|
||||
<path fill={fillColor} d="M 194.5,96.5 C 205.307,90.5958 215.64,91.2624 225.5,98.5C 227.97,102.11 229.304,106.11 229.5,110.5C 227.359,120.522 224.859,130.522 222,140.5C 221.176,143.882 221.343,147.216 222.5,150.5C 223.607,151.022 224.774,151.355 226,151.5C 229.926,150.727 233.759,149.727 237.5,148.5C 240.135,147.461 242.135,145.794 243.5,143.5C 247.778,147.659 247.111,151.159 241.5,154C 245.303,156.071 248.97,158.404 252.5,161C 255.77,162.66 259.103,162.994 262.5,162C 263.935,164.267 263.602,166.267 261.5,168C 258.448,169.211 255.281,170.045 252,170.5C 244.065,169.521 236.398,167.521 229,164.5C 222.843,167.108 216.51,169.108 210,170.5C 207.815,170.079 205.649,169.579 203.5,169C 202.424,167.274 202.257,165.441 203,163.5C 207.408,161.43 211.575,158.93 215.5,156C 213.504,151.729 213.004,147.229 214,142.5C 216.819,132.558 219.319,122.558 221.5,112.5C 221.81,108.306 220.143,105.139 216.5,103C 208.667,100.569 201.501,101.736 195,106.5C 191.661,123.896 191.827,141.229 195.5,158.5C 194.895,160.026 193.729,161.026 192,161.5C 191.14,156.863 188.307,154.697 183.5,155C 184.833,154.333 184.833,153.667 183.5,153C 181.934,152.7 180.601,153.2 179.5,154.5C 166.076,151.07 158.742,142.403 157.5,128.5C 158.051,123.851 159.385,119.518 161.5,115.5C 162.906,115.027 163.573,114.027 163.5,112.5C 167.455,107.373 171.622,102.373 176,97.5C 178.486,92.5113 180.652,87.5113 182.5,82.5C 183.901,82.0291 185.234,81.3624 186.5,80.5C 183.867,79.1156 183.867,77.7822 186.5,76.5C 187.842,78.0049 189.508,78.6715 191.5,78.5C 192.546,85.1876 193.546,91.1876 194.5,96.5 Z" />
|
||||
{/* Body/torso part */}
|
||||
<path fill={fillColor} d="M 194.5,96.5 C 205.307,90.5958 215.64,91.2624 225.5,98.5C 227.97,102.11 229.304,106.11 229.5,110.5C 227.359,120.522 224.859,130.522 222,140.5C 221.176,143.882 221.343,147.216 222.5,150.5C 223.607,151.022 224.774,151.355 226,151.5C 229.926,150.727 233.759,149.727 237.5,148.5C 240.135,147.461 242.135,145.794 243.5,143.5C 247.778,147.659 247.111,151.159 241.5,154C 245.303,156.071 248.97,158.404 252.5,161C 255.77,162.66 259.103,162.994 262.5,162C 263.935,164.267 263.602,166.267 261.5,168C 258.448,169.211 255.281,170.045 252,170.5C 244.065,169.521 236.398,167.521 229,164.5C 222.843,167.108 216.51,169.108 210,170.5C 207.815,170.079 205.649,169.579 203.5,169C 202.424,167.274 202.257,165.441 203,163.5C 207.408,161.43 211.575,158.93 215.5,156C 213.504,151.729 213.004,147.229 214,142.5C 216.819,132.558 219.319,122.558 221.5,112.5C 221.81,108.306 220.143,105.139 216.5,103C 208.667,100.569 201.501,101.736 195,106.5C 191.661,123.896 191.827,141.229 195.5,158.5C 194.895,160.026 193.729,161.026 192,161.5C 191.14,156.863 188.307,154.697 183.5,155C 184.833,154.333 184.833,153.667 183.5,153C 181.934,152.7 180.601,153.2 179.5,154.5C 166.076,151.07 158.742,142.403 157.5,128.5C 158.051,123.851 159.385,119.518 161.5,115.5C 162.906,115.027 163.573,114.027 163.5,112.5C 167.455,107.373 171.622,102.373 176,97.5C 178.486,92.5113 180.652,87.5113 182.5,82.5C 183.901,82.0291 185.234,81.3624 186.5,80.5C 183.867,79.1156 183.867,77.7822 186.5,76.5C 187.842,78.0049 189.508,78.6715 191.5,78.5C 192.546,85.1876 193.546,91.1876 194.5,96.5 Z" />
|
||||
|
||||
{/* Additional body details */}
|
||||
<path fill={fillColor} d="M 272.5,96.5 C 273.785,98.4516 275.451,100.118 277.5,101.5C 279.574,103.715 279.907,106.215 278.5,109C 275.758,109.295 273.425,108.462 271.5,106.5C 271.167,105.5 270.5,104.833 269.5,104.5C 265.505,102.79 261.339,101.456 257,100.5C 252.701,101.544 248.535,102.878 244.5,104.5C 237.97,101.229 237.97,97.7288 244.5,94C 251.789,91.6687 259.122,91.3353 266.5,93C 268.727,93.941 270.727,95.1077 272.5,96.5 Z" />
|
||||
{/* Additional body details */}
|
||||
<path fill={fillColor} d="M 272.5,96.5 C 273.785,98.4516 275.451,100.118 277.5,101.5C 279.574,103.715 279.907,106.215 278.5,109C 275.758,109.295 273.425,108.462 271.5,106.5C 271.167,105.5 270.5,104.833 269.5,104.5C 265.505,102.79 261.339,101.456 257,100.5C 252.701,101.544 248.535,102.878 244.5,104.5C 237.97,101.229 237.97,97.7288 244.5,94C 251.789,91.6687 259.122,91.3353 266.5,93C 268.727,93.941 270.727,95.1077 272.5,96.5 Z" />
|
||||
|
||||
{/* Eyes */}
|
||||
<path fill={fillColor} d="M 216.5,118.5 C 215.603,119.598 214.77,119.598 214,118.5C 213.59,119.901 213.09,121.234 212.5,122.5C 209.43,122.632 206.43,122.299 203.5,121.5C 200.197,118.335 199.697,114.668 202,110.5C 209.746,105.174 214.913,107.008 217.5,116C 217.257,116.902 216.923,117.735 216.5,118.5 Z" />
|
||||
<path fill={fillColor} d="M 254.5,107.5 C 262.982,107.765 266.149,112.099 264,120.5C 258.514,126.08 253.514,125.747 249,119.5C 247.486,113.877 249.319,109.877 254.5,107.5 Z" />
|
||||
{/* Eyes */}
|
||||
<path fill={fillColor} d="M 216.5,118.5 C 215.603,119.598 214.77,119.598 214,118.5C 213.59,119.901 213.09,121.234 212.5,122.5C 209.43,122.632 206.43,122.299 203.5,121.5C 200.197,118.335 199.697,114.668 202,110.5C 209.746,105.174 214.913,107.008 217.5,116C 217.257,116.902 216.923,117.735 216.5,118.5 Z" />
|
||||
<path fill={fillColor} d="M 254.5,107.5 C 262.982,107.765 266.149,112.099 264,120.5C 258.514,126.08 253.514,125.747 249,119.5C 247.486,113.877 249.319,109.877 254.5,107.5 Z" />
|
||||
|
||||
{/* Extended body details */}
|
||||
<path fill={fillColor} d="M 329.5,172.5 C 329.751,174.17 330.418,175.67 331.5,177C 330.551,177.617 329.718,177.451 329,176.5C 328.333,177.5 328.333,178.5 329,179.5C 329.333,179.167 329.667,178.833 330,178.5C 331.063,179.438 332.23,180.438 333.5,181.5C 333.034,179.705 333.034,177.705 333.5,175.5C 334.427,177.113 335.261,178.779 336,180.5C 336.232,179.263 336.732,178.263 337.5,177.5C 337.657,178.873 337.49,180.207 337,181.5C 336.124,183.758 334.957,185.758 333.5,187.5C 331.455,188.923 330.455,190.923 330.5,193.5C 321.603,207.727 311.937,221.394 301.5,234.5C 301.785,232.712 301.452,231.045 300.5,229.5C 297.606,230.909 296.606,230.242 297.5,227.5C 298.167,225.833 298.833,224.167 299.5,222.5C 306.66,212.186 313.827,201.853 321,191.5C 324.438,185.303 327.271,178.969 329.5,172.5 Z" />
|
||||
{/* Extended body details */}
|
||||
<path fill={fillColor} d="M 329.5,172.5 C 329.751,174.17 330.418,175.67 331.5,177C 330.551,177.617 329.718,177.451 329,176.5C 328.333,177.5 328.333,178.5 329,179.5C 329.333,179.167 329.667,178.833 330,178.5C 331.063,179.438 332.23,180.438 333.5,181.5C 333.034,179.705 333.034,177.705 333.5,175.5C 334.427,177.113 335.261,178.779 336,180.5C 336.232,179.263 336.732,178.263 337.5,177.5C 337.657,178.873 337.49,180.207 337,181.5C 336.124,183.758 334.957,185.758 333.5,187.5C 331.455,188.923 330.455,190.923 330.5,193.5C 321.603,207.727 311.937,221.394 301.5,234.5C 301.785,232.712 301.452,231.045 300.5,229.5C 297.606,230.909 296.606,230.242 297.5,227.5C 298.167,225.833 298.833,224.167 299.5,222.5C 306.66,212.186 313.827,201.853 321,191.5C 324.438,185.303 327.271,178.969 329.5,172.5 Z" />
|
||||
|
||||
{/* Main body section */}
|
||||
<path fill={fillColor} d="M 195.5,158.5 C 199.127,167.099 202.794,175.765 206.5,184.5C 206.427,186.027 207.094,187.027 208.5,187.5C 213.391,196.567 220.558,202.9 230,206.5C 254.97,200.996 273.803,187.329 286.5,165.5C 286.643,168.097 287.477,170.431 289,172.5C 290.188,171.437 290.688,170.103 290.5,168.5C 292.199,168.473 293.533,167.806 294.5,166.5C 290.454,177.733 283.787,187.233 274.5,195C 259.369,206.946 243.036,214.112 225.5,216.5C 222.868,215.466 220.201,214.466 217.5,213.5C 217.5,212.833 217.5,212.167 217.5,211.5C 211.822,206.986 206.989,201.653 203,195.5C 198.434,187.483 194.434,179.15 191,170.5C 175.85,181.982 164.684,196.482 157.5,214C 164.095,213.183 170.762,212.683 177.5,212.5C 174.695,213.319 171.695,213.819 168.5,214C 170.167,214.333 171.833,214.667 173.5,215C 171.136,216.012 169.802,217.345 169.5,219C 170.448,219.483 171.448,219.649 172.5,219.5C 172.5,219.833 172.5,220.167 172.5,220.5C 164.95,221.221 157.617,222.888 150.5,225.5C 148.06,224.726 146.727,223.06 146.5,220.5C 146.886,218.068 147.553,215.734 148.5,213.5C 149.906,213.027 150.573,212.027 150.5,210.5C 153.084,202.664 156.751,195.331 161.5,188.5C 169.649,178.517 178.649,169.351 188.5,161C 187.62,159.644 187.286,158.144 187.5,156.5C 184.505,156.706 181.838,156.04 179.5,154.5C 180.601,153.2 181.934,152.7 183.5,153C 184.833,153.667 184.833,154.333 183.5,155C 188.307,154.697 191.14,156.863 192,161.5C 193.729,161.026 194.895,160.026 195.5,158.5 Z M 217.5,211.5 C 216.221,212.968 214.554,213.635 212.5,213.5C 211.167,213.5 209.833,213.5 208.5,213.5C 202.225,212.066 195.725,211.4 189,211.5C 184.985,211.501 181.151,211.835 177.5,212.5C 170.762,212.683 164.095,213.183 157.5,214C 164.684,196.482 175.85,181.982 191,170.5C 194.434,179.15 198.434,187.483 203,195.5C 206.989,201.653 211.822,206.986 217.5,211.5 Z" />
|
||||
{/* Main body section */}
|
||||
<path fill={fillColor} d="M 195.5,158.5 C 199.127,167.099 202.794,175.765 206.5,184.5C 206.427,186.027 207.094,187.027 208.5,187.5C 213.391,196.567 220.558,202.9 230,206.5C 254.97,200.996 273.803,187.329 286.5,165.5C 286.643,168.097 287.477,170.431 289,172.5C 290.188,171.437 290.688,170.103 290.5,168.5C 292.199,168.473 293.533,167.806 294.5,166.5C 290.454,177.733 283.787,187.233 274.5,195C 259.369,206.946 243.036,214.112 225.5,216.5C 222.868,215.466 220.201,214.466 217.5,213.5C 217.5,212.833 217.5,212.167 217.5,211.5C 211.822,206.986 206.989,201.653 203,195.5C 198.434,187.483 194.434,179.15 191,170.5C 175.85,181.982 164.684,196.482 157.5,214C 164.095,213.183 170.762,212.683 177.5,212.5C 174.695,213.319 171.695,213.819 168.5,214C 170.167,214.333 171.833,214.667 173.5,215C 171.136,216.012 169.802,217.345 169.5,219C 170.448,219.483 171.448,219.649 172.5,219.5C 172.5,219.833 172.5,220.167 172.5,220.5C 164.95,221.221 157.617,222.888 150.5,225.5C 148.06,224.726 146.727,223.06 146.5,220.5C 146.886,218.068 147.553,215.734 148.5,213.5C 149.906,213.027 150.573,212.027 150.5,210.5C 153.084,202.664 156.751,195.331 161.5,188.5C 169.649,178.517 178.649,169.351 188.5,161C 187.62,159.644 187.286,158.144 187.5,156.5C 184.505,156.706 181.838,156.04 179.5,154.5C 180.601,153.2 181.934,152.7 183.5,153C 184.833,153.667 184.833,154.333 183.5,155C 188.307,154.697 191.14,156.863 192,161.5C 193.729,161.026 194.895,160.026 195.5,158.5 Z M 217.5,211.5 C 216.221,212.968 214.554,213.635 212.5,213.5C 211.167,213.5 209.833,213.5 208.5,213.5C 202.225,212.066 195.725,211.4 189,211.5C 184.985,211.501 181.151,211.835 177.5,212.5C 170.762,212.683 164.095,213.183 157.5,214C 164.684,196.482 175.85,181.982 191,170.5C 194.434,179.15 198.434,187.483 203,195.5C 206.989,201.653 211.822,206.986 217.5,211.5 Z" />
|
||||
|
||||
{/* Additional body details */}
|
||||
<path fill={fillColor} d="M 221.5,184.5 C 224.113,183.565 226.779,183.398 229.5,184C 227.709,184.415 226.376,185.415 225.5,187C 228.167,187.667 230.833,187.667 233.5,187C 230.983,183.799 231.483,180.966 235,178.5C 235.667,177.167 235.667,175.833 235,174.5C 232.323,172.959 229.49,171.959 226.5,171.5C 232.176,171.072 237.843,170.905 243.5,171C 245.283,172.067 245.783,173.567 245,175.5C 243.247,176.627 241.413,177.627 239.5,178.5C 238.303,181.934 236.636,185.1 234.5,188C 231.167,188.667 227.833,188.667 224.5,188C 223.29,186.961 222.29,185.794 221.5,184.5 Z" />
|
||||
{/* Additional body details */}
|
||||
<path fill={fillColor} d="M 221.5,184.5 C 224.113,183.565 226.779,183.398 229.5,184C 227.709,184.415 226.376,185.415 225.5,187C 228.167,187.667 230.833,187.667 233.5,187C 230.983,183.799 231.483,180.966 235,178.5C 235.667,177.167 235.667,175.833 235,174.5C 232.323,172.959 229.49,171.959 226.5,171.5C 232.176,171.072 237.843,170.905 243.5,171C 245.283,172.067 245.783,173.567 245,175.5C 243.247,176.627 241.413,177.627 239.5,178.5C 238.303,181.934 236.636,185.1 234.5,188C 231.167,188.667 227.833,188.667 224.5,188C 223.29,186.961 222.29,185.794 221.5,184.5 Z" />
|
||||
|
||||
{/* Body shading */}
|
||||
<path fill={fillColor} d="M 226.5,171.5 C 229.49,171.959 232.323,172.959 235,174.5C 235.667,175.833 235.667,177.167 235,178.5C 231.483,180.966 230.983,183.799 233.5,187C 230.833,187.667 228.167,187.667 225.5,187C 226.376,185.415 227.709,184.415 229.5,184C 226.779,183.398 224.113,183.565 221.5,184.5C 221.5,183.833 221.5,183.167 221.5,182.5C 221.656,179.934 221.322,177.434 220.5,175C 220.905,174.055 221.572,173.388 222.5,173C 221.5,172.667 220.5,172.333 219.5,172C 221.81,171.503 224.143,171.337 226.5,171.5 Z" />
|
||||
{/* Body shading */}
|
||||
<path fill={fillColor} d="M 226.5,171.5 C 229.49,171.959 232.323,172.959 235,174.5C 235.667,175.833 235.667,177.167 235,178.5C 231.483,180.966 230.983,183.799 233.5,187C 230.833,187.667 228.167,187.667 225.5,187C 226.376,185.415 227.709,184.415 229.5,184C 226.779,183.398 224.113,183.565 221.5,184.5C 221.5,183.833 221.5,183.167 221.5,182.5C 221.656,179.934 221.322,177.434 220.5,175C 220.905,174.055 221.572,173.388 222.5,173C 221.5,172.667 220.5,172.333 219.5,172C 221.81,171.503 224.143,171.337 226.5,171.5 Z" />
|
||||
|
||||
{/* More body shading */}
|
||||
<path fill={fillColor} d="M 226.5,171.5 C 224.143,171.337 221.81,171.503 219.5,172C 220.5,172.333 221.5,172.667 222.5,173C 221.572,173.388 220.905,174.055 220.5,175C 221.322,177.434 221.656,179.934 221.5,182.5C 220.916,180.257 219.75,178.257 218,176.5C 217.333,174.833 217.333,173.167 218,171.5C 220.937,170.183 223.77,170.183 226.5,171.5 Z" />
|
||||
{/* More body shading */}
|
||||
<path fill={fillColor} d="M 226.5,171.5 C 224.143,171.337 221.81,171.503 219.5,172C 220.5,172.333 221.5,172.667 222.5,173C 221.572,173.388 220.905,174.055 220.5,175C 221.322,177.434 221.656,179.934 221.5,182.5C 220.916,180.257 219.75,178.257 218,176.5C 217.333,174.833 217.333,173.167 218,171.5C 220.937,170.183 223.77,170.183 226.5,171.5 Z" />
|
||||
|
||||
{/* Lower body/legs area */}
|
||||
<path fill={fillColor} d="M 177.5,212.5 C 187.85,212.44 198.183,212.774 208.5,213.5C 209.833,213.5 211.167,213.5 212.5,213.5C 214.167,214.833 215.833,214.833 217.5,213.5C 220.201,214.466 222.868,215.466 225.5,216.5C 225.034,218.201 225.034,219.701 225.5,221C 224.429,221.852 223.429,222.685 222.5,223.5C 219.43,223.632 216.43,223.299 213.5,222.5C 213.44,221.957 213.107,221.624 212.5,221.5C 211.516,224.428 211.183,227.428 211.5,230.5C 209.859,228.797 208.859,226.63 208.5,224C 207.258,223.689 206.258,224.189 205.5,225.5C 204.692,225.192 204.025,224.692 203.5,224C 204.833,222.667 204.833,221.333 203.5,220C 201.866,219.506 200.199,219.34 198.5,219.5C 195.102,219.18 191.768,219.513 188.5,220.5C 188.624,221.107 188.957,221.44 189.5,221.5C 188.891,224.878 190.224,226.878 193.5,227.5C 195.288,228.622 197.288,228.789 199.5,228C 200.756,227.583 201.423,226.75 201.5,225.5C 202.995,225.415 203.995,226.081 204.5,227.5C 203.092,228.243 201.759,229.077 200.5,230C 202.249,232.213 204.249,233.213 206.5,233C 204.881,233.236 203.881,234.069 203.5,235.5C 202.5,235.5 201.5,235.5 200.5,235.5C 198.167,235.5 195.833,235.5 193.5,235.5C 193.333,285.168 193.5,334.834 194,384.5C 194.232,385.737 194.732,386.737 195.5,387.5C 197.821,396.471 201.488,404.805 206.5,412.5C 207.956,415.431 207.123,416.098 204,414.5C 203.333,416.167 203.333,417.833 204,419.5C 204.333,418.833 204.667,418.167 205,417.5C 206.109,420.947 205.109,423.614 202,425.5C 200.086,424.324 200.252,423.324 202.5,422.5C 202.167,422.167 201.833,421.833 201.5,421.5C 199.557,421.535 197.557,421.202 195.5,420.5C 186.876,409.404 181.876,396.738 180.5,382.5C 180.5,328.167 180.5,273.833 180.5,219.5C 177.833,219.5 175.167,219.5 172.5,219.5C 171.448,219.649 170.448,219.483 169.5,219C 169.802,217.345 171.136,216.012 173.5,215C 171.833,214.667 170.167,214.333 168.5,214C 171.695,213.819 174.695,213.319 177.5,212.5 Z M 189.5,221.5 C 192.287,220.523 195.287,220.19 198.5,220.5C 203.5,220.134 204.5,221.8 201.5,225.5C 199.087,227.051 196.421,227.717 193.5,227.5C 191.71,225.728 190.377,223.728 189.5,221.5 Z" />
|
||||
{/* Lower body/legs area */}
|
||||
<path fill={fillColor} d="M 177.5,212.5 C 187.85,212.44 198.183,212.774 208.5,213.5C 209.833,213.5 211.167,213.5 212.5,213.5C 214.167,214.833 215.833,214.833 217.5,213.5C 220.201,214.466 222.868,215.466 225.5,216.5C 225.034,218.201 225.034,219.701 225.5,221C 224.429,221.852 223.429,222.685 222.5,223.5C 219.43,223.632 216.43,223.299 213.5,222.5C 213.44,221.957 213.107,221.624 212.5,221.5C 211.516,224.428 211.183,227.428 211.5,230.5C 209.859,228.797 208.859,226.63 208.5,224C 207.258,223.689 206.258,224.189 205.5,225.5C 204.692,225.192 204.025,224.692 203.5,224C 204.833,222.667 204.833,221.333 203.5,220C 201.866,219.506 200.199,219.34 198.5,219.5C 195.102,219.18 191.768,219.513 188.5,220.5C 188.624,221.107 188.957,221.44 189.5,221.5C 188.891,224.878 190.224,226.878 193.5,227.5C 195.288,228.622 197.288,228.789 199.5,228C 200.756,227.583 201.423,226.75 201.5,225.5C 202.995,225.415 203.995,226.081 204.5,227.5C 203.092,228.243 201.759,229.077 200.5,230C 202.249,232.213 204.249,233.213 206.5,233C 204.881,233.236 203.881,234.069 203.5,235.5C 202.5,235.5 201.5,235.5 200.5,235.5C 198.167,235.5 195.833,235.5 193.5,235.5C 193.333,285.168 193.5,334.834 194,384.5C 194.232,385.737 194.732,386.737 195.5,387.5C 197.821,396.471 201.488,404.805 206.5,412.5C 207.956,415.431 207.123,416.098 204,414.5C 203.333,416.167 203.333,417.833 204,419.5C 204.333,418.833 204.667,418.167 205,417.5C 206.109,420.947 205.109,423.614 202,425.5C 200.086,424.324 200.252,423.324 202.5,422.5C 202.167,422.167 201.833,421.833 201.5,421.5C 199.557,421.535 197.557,421.202 195.5,420.5C 186.876,409.404 181.876,396.738 180.5,382.5C 180.5,328.167 180.5,273.833 180.5,219.5C 177.833,219.5 175.167,219.5 172.5,219.5C 171.448,219.649 170.448,219.483 169.5,219C 169.802,217.345 171.136,216.012 173.5,215C 171.833,214.667 170.167,214.333 168.5,214C 171.695,213.819 174.695,213.319 177.5,212.5 Z M 189.5,221.5 C 192.287,220.523 195.287,220.19 198.5,220.5C 203.5,220.134 204.5,221.8 201.5,225.5C 199.087,227.051 196.421,227.717 193.5,227.5C 191.71,225.728 190.377,223.728 189.5,221.5 Z" />
|
||||
|
||||
{/* Extended body section */}
|
||||
<path fill={fillColor} d="M 225.5,216.5 C 247.583,219.231 268.249,225.898 287.5,236.5C 289.507,234.467 291.507,232.467 293.5,230.5C 294.906,230.027 295.573,229.027 295.5,227.5C 296.167,227.5 296.833,227.5 297.5,227.5C 296.606,230.242 297.606,230.909 300.5,229.5C 301.452,231.045 301.785,232.712 301.5,234.5C 300.585,236.754 299.252,238.754 297.5,240.5C 296.667,276.829 296.167,313.162 296,349.5C 295.065,357.682 292.231,365.016 287.5,371.5C 286.118,372.801 284.452,373.634 282.5,374C 283.252,374.671 283.586,375.504 283.5,376.5C 272.573,387.751 259.239,391.917 243.5,389C 219.325,381.522 207.825,365.022 209,339.5C 208.333,313.833 208.333,288.167 209,262.5C 209.391,257.944 211.891,255.61 216.5,255.5C 219.037,255.435 221.037,256.435 222.5,258.5C 223.333,289.495 223.833,320.495 224,351.5C 227.652,365.323 236.485,373.323 250.5,375.5C 251.793,376.158 253.293,376.492 255,376.5C 257.821,376.592 260.321,375.926 262.5,374.5C 272.878,370.283 279.044,362.616 281,351.5C 281.5,315.835 281.667,280.168 281.5,244.5C 281.027,243.094 280.027,242.427 278.5,242.5C 272.117,238.977 265.451,235.977 258.5,233.5C 257.558,233.608 256.725,233.941 256,234.5C 251.175,245.334 243.342,248.501 232.5,244C 230.622,242.457 229.122,240.624 228,238.5C 226.992,240.259 225.492,241.426 223.5,242C 220.167,242.667 216.833,242.667 213.5,242C 209.903,240.048 206.569,237.881 203.5,235.5C 203.881,234.069 204.881,233.236 206.5,233C 204.249,233.213 202.249,232.213 200.5,230C 201.759,229.077 203.092,228.243 204.5,227.5C 203.995,226.081 202.995,225.415 201.5,225.5C 204.5,221.8 203.5,220.134 198.5,220.5C 198.5,220.167 198.5,219.833 198.5,219.5C 200.199,219.34 201.866,219.506 203.5,220C 204.833,221.333 204.833,222.667 203.5,224C 204.025,224.692 204.692,225.192 205.5,225.5C 206.258,224.189 207.258,223.689 208.5,224C 208.859,226.63 209.859,228.797 211.5,230.5C 211.5,231.167 211.833,231.5 212.5,231.5C 215.518,234.97 218.852,235.304 222.5,232.5C 223.965,230.401 225.299,228.234 226.5,226C 225.644,224.405 224.311,223.572 222.5,223.5C 223.429,222.685 224.429,221.852 225.5,221C 225.034,219.701 225.034,218.201 225.5,216.5 Z M 244.5,228.5 C 245.609,229.29 246.942,229.79 248.5,230C 247.663,231.011 247.33,232.178 247.5,233.5C 238.193,240.515 234.36,238.181 236,226.5C 238.778,227.325 241.611,227.992 244.5,228.5 Z M 213.5,222.5 C 216.43,223.299 219.43,223.632 222.5,223.5C 224.311,223.572 225.644,224.405 226.5,226C 225.299,228.234 223.965,230.401 222.5,232.5C 218.852,235.304 215.518,234.97 212.5,231.5C 212.19,228.287 212.523,225.287 213.5,222.5 Z" />
|
||||
{/* Extended body section */}
|
||||
<path fill={fillColor} d="M 225.5,216.5 C 247.583,219.231 268.249,225.898 287.5,236.5C 289.507,234.467 291.507,232.467 293.5,230.5C 294.906,230.027 295.573,229.027 295.5,227.5C 296.167,227.5 296.833,227.5 297.5,227.5C 296.606,230.242 297.606,230.909 300.5,229.5C 301.452,231.045 301.785,232.712 301.5,234.5C 300.585,236.754 299.252,238.754 297.5,240.5C 296.667,276.829 296.167,313.162 296,349.5C 295.065,357.682 292.231,365.016 287.5,371.5C 286.118,372.801 284.452,373.634 282.5,374C 283.252,374.671 283.586,375.504 283.5,376.5C 272.573,387.751 259.239,391.917 243.5,389C 219.325,381.522 207.825,365.022 209,339.5C 208.333,313.833 208.333,288.167 209,262.5C 209.391,257.944 211.891,255.61 216.5,255.5C 219.037,255.435 221.037,256.435 222.5,258.5C 223.333,289.495 223.833,320.495 224,351.5C 227.652,365.323 236.485,373.323 250.5,375.5C 251.793,376.158 253.293,376.492 255,376.5C 257.821,376.592 260.321,375.926 262.5,374.5C 272.878,370.283 279.044,362.616 281,351.5C 281.5,315.835 281.667,280.168 281.5,244.5C 281.027,243.094 280.027,242.427 278.5,242.5C 272.117,238.977 265.451,235.977 258.5,233.5C 257.558,233.608 256.725,233.941 256,234.5C 251.175,245.334 243.342,248.501 232.5,244C 230.622,242.457 229.122,240.624 228,238.5C 226.992,240.259 225.492,241.426 223.5,242C 220.167,242.667 216.833,242.667 213.5,242C 209.903,240.048 206.569,237.881 203.5,235.5C 203.881,234.069 204.881,233.236 206.5,233C 204.249,233.213 202.249,232.213 200.5,230C 201.759,229.077 203.092,228.243 204.5,227.5C 203.995,226.081 202.995,225.415 201.5,225.5C 204.5,221.8 203.5,220.134 198.5,220.5C 198.5,220.167 198.5,219.833 198.5,219.5C 200.199,219.34 201.866,219.506 203.5,220C 204.833,221.333 204.833,222.667 203.5,224C 204.025,224.692 204.692,225.192 205.5,225.5C 206.258,224.189 207.258,223.689 208.5,224C 208.859,226.63 209.859,228.797 211.5,230.5C 211.5,231.167 211.833,231.5 212.5,231.5C 215.518,234.97 218.852,235.304 222.5,232.5C 223.965,230.401 225.299,228.234 226.5,226C 225.644,224.405 224.311,223.572 222.5,223.5C 223.429,222.685 224.429,221.852 225.5,221C 225.034,219.701 225.034,218.201 225.5,216.5 Z M 244.5,228.5 C 245.609,229.29 246.942,229.79 248.5,230C 247.663,231.011 247.33,232.178 247.5,233.5C 238.193,240.515 234.36,238.181 236,226.5C 238.778,227.325 241.611,227.992 244.5,228.5 Z M 213.5,222.5 C 216.43,223.299 219.43,223.632 222.5,223.5C 224.311,223.572 225.644,224.405 226.5,226C 225.299,228.234 223.965,230.401 222.5,232.5C 218.852,235.304 215.518,234.97 212.5,231.5C 212.19,228.287 212.523,225.287 213.5,222.5 Z" />
|
||||
|
||||
{/* Additional details */}
|
||||
<path fill={fillColor} d="M 325.5,381.5 C 324.176,384.148 322.843,386.814 321.5,389.5C 318.621,387.559 315.788,388.226 313,391.5C 311.798,389.323 311.298,386.989 311.5,384.5C 311.333,336.832 311.5,289.166 312,241.5C 313.399,235.938 316.899,234.105 322.5,236C 324.049,237.214 325.215,238.714 326,240.5C 326.832,287.668 326.665,334.668 325.5,381.5 Z" />
|
||||
{/* Additional details */}
|
||||
<path fill={fillColor} d="M 325.5,381.5 C 324.176,384.148 322.843,386.814 321.5,389.5C 318.621,387.559 315.788,388.226 313,391.5C 311.798,389.323 311.298,386.989 311.5,384.5C 311.333,336.832 311.5,289.166 312,241.5C 313.399,235.938 316.899,234.105 322.5,236C 324.049,237.214 325.215,238.714 326,240.5C 326.832,287.668 326.665,334.668 325.5,381.5 Z" />
|
||||
|
||||
{/* Final details */}
|
||||
<path fill={fillColor} d="M 287.5,371.5 C 286.92,373.749 285.587,375.415 283.5,376.5C 283.586,375.504 283.252,374.671 282.5,374C 284.452,373.634 286.118,372.801 287.5,371.5 Z" />
|
||||
{/* Final details */}
|
||||
<path fill={fillColor} d="M 287.5,371.5 C 286.92,373.749 285.587,375.415 283.5,376.5C 283.586,375.504 283.252,374.671 282.5,374C 284.452,373.634 286.118,372.801 287.5,371.5 Z" />
|
||||
|
||||
{/* Bottom section */}
|
||||
<path fill={fillColor} d="M 325.5,381.5 C 322.774,410.382 308.44,431.215 282.5,444C 280.564,444.813 278.564,445.313 276.5,445.5C 274.447,445.402 272.78,446.069 271.5,447.5C 243.945,453.656 220.111,446.99 200,427.5C 198.25,425.266 196.75,422.932 195.5,420.5C 197.557,421.202 199.557,421.535 201.5,421.5C 201.833,421.833 202.167,422.167 202.5,422.5C 200.252,423.324 200.086,424.324 202,425.5C 205.109,423.614 206.109,420.947 205,417.5C 204.667,418.167 204.333,418.833 204,419.5C 203.333,417.833 203.333,416.167 204,414.5C 207.123,416.098 207.956,415.431 206.5,412.5C 217.31,425.907 231.31,433.573 248.5,435.5C 253.65,436.651 258.984,436.817 264.5,436C 265.416,435.722 266.082,435.222 266.5,434.5C 284.985,429.357 298.318,418.024 306.5,400.5C 307.906,400.027 308.573,399.027 308.5,397.5C 309.598,393.089 310.598,388.755 311.5,384.5C 311.298,386.989 311.798,389.323 313,391.5C 315.788,388.226 318.621,387.559 321.5,389.5C 322.843,386.814 324.176,384.148 325.5,381.5 Z" />
|
||||
</svg>
|
||||
);
|
||||
{/* Bottom section */}
|
||||
<path fill={fillColor} d="M 325.5,381.5 C 322.774,410.382 308.44,431.215 282.5,444C 280.564,444.813 278.564,445.313 276.5,445.5C 274.447,445.402 272.78,446.069 271.5,447.5C 243.945,453.656 220.111,446.99 200,427.5C 198.25,425.266 196.75,422.932 195.5,420.5C 197.557,421.202 199.557,421.535 201.5,421.5C 201.833,421.833 202.167,422.167 202.5,422.5C 200.252,423.324 200.086,424.324 202,425.5C 205.109,423.614 206.109,420.947 205,417.5C 204.667,418.167 204.333,418.833 204,419.5C 203.333,417.833 203.333,416.167 204,414.5C 207.123,416.098 207.956,415.431 206.5,412.5C 217.31,425.907 231.31,433.573 248.5,435.5C 253.65,436.651 258.984,436.817 264.5,436C 265.416,435.722 266.082,435.222 266.5,434.5C 284.985,429.357 298.318,418.024 306.5,400.5C 307.906,400.027 308.573,399.027 308.5,397.5C 309.598,393.089 310.598,388.755 311.5,384.5C 311.298,386.989 311.798,389.323 313,391.5C 315.788,388.226 318.621,387.559 321.5,389.5C 322.843,386.814 324.176,384.148 325.5,381.5 Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -82,13 +82,13 @@ const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
|
||||
([theme, prefix]) => `
|
||||
${prefix} [data-chart=${id}] {
|
||||
${colorConfig
|
||||
.map(([key, itemConfig]) => {
|
||||
const color =
|
||||
.map(([key, itemConfig]) => {
|
||||
const color =
|
||||
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
|
||||
itemConfig.color
|
||||
return color ? ` --color-${key}: ${color};` : null
|
||||
})
|
||||
.join("\n")}
|
||||
return color ? ` --color-${key}: ${color};` : null
|
||||
})
|
||||
.join("\n")}
|
||||
}
|
||||
`
|
||||
)
|
||||
|
||||
@@ -42,7 +42,7 @@ const DialogContent = React.forwardRef<
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
|
||||
@@ -19,8 +19,8 @@ const FormField = <
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
|
||||
>({
|
||||
...props
|
||||
}: ControllerProps<TFieldValues, TName>) => {
|
||||
...props
|
||||
}: ControllerProps<TFieldValues, TName>) => {
|
||||
return (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
|
||||
@@ -35,107 +35,107 @@ const SidebarProvider = React.forwardRef<
|
||||
defaultOpen?: boolean
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}
|
||||
>(
|
||||
(
|
||||
{
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const isMobile = useIsMobile()
|
||||
const [openMobile, setOpenMobile] = React.useState(false)
|
||||
}
|
||||
>(
|
||||
(
|
||||
{
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const isMobile = useIsMobile()
|
||||
const [openMobile, setOpenMobile] = React.useState(false)
|
||||
|
||||
// This is the internal state of the sidebar.
|
||||
// We use openProp and setOpenProp for control from outside the component.
|
||||
const [_open, _setOpen] = React.useState(defaultOpen)
|
||||
const open = openProp ?? _open
|
||||
const setOpen = React.useCallback(
|
||||
(value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState)
|
||||
} else {
|
||||
_setOpen(openState)
|
||||
}
|
||||
// This is the internal state of the sidebar.
|
||||
// We use openProp and setOpenProp for control from outside the component.
|
||||
const [_open, _setOpen] = React.useState(defaultOpen)
|
||||
const open = openProp ?? _open
|
||||
const setOpen = React.useCallback(
|
||||
(value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState)
|
||||
} else {
|
||||
_setOpen(openState)
|
||||
}
|
||||
|
||||
// This sets the cookie to keep the sidebar state.
|
||||
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
|
||||
},
|
||||
[setOpenProp, open]
|
||||
)
|
||||
// This sets the cookie to keep the sidebar state.
|
||||
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
|
||||
},
|
||||
[setOpenProp, open]
|
||||
)
|
||||
|
||||
// Helper to toggle the sidebar.
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
return isMobile
|
||||
? setOpenMobile((open) => !open)
|
||||
: setOpen((open) => !open)
|
||||
}, [isMobile, setOpen, setOpenMobile])
|
||||
// Helper to toggle the sidebar.
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
return isMobile
|
||||
? setOpenMobile((open) => !open)
|
||||
: setOpen((open) => !open)
|
||||
}, [isMobile, setOpen, setOpenMobile])
|
||||
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
|
||||
(event.metaKey || event.ctrlKey)
|
||||
) {
|
||||
event.preventDefault()
|
||||
toggleSidebar()
|
||||
}
|
||||
}
|
||||
) {
|
||||
event.preventDefault()
|
||||
toggleSidebar()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [toggleSidebar])
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [toggleSidebar])
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed"
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed"
|
||||
|
||||
const contextValue = React.useMemo<SidebarContextType>(
|
||||
() => ({
|
||||
state,
|
||||
open,
|
||||
setOpen,
|
||||
isMobile,
|
||||
openMobile,
|
||||
setOpenMobile,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
|
||||
)
|
||||
const contextValue = React.useMemo<SidebarContextType>(
|
||||
() => ({
|
||||
state,
|
||||
open,
|
||||
setOpen,
|
||||
isMobile,
|
||||
openMobile,
|
||||
setOpenMobile,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
|
||||
)
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<div
|
||||
style={
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<div
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH,
|
||||
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||
...style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</SidebarContext.Provider>
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</SidebarContext.Provider>
|
||||
)
|
||||
}
|
||||
)
|
||||
SidebarProvider.displayName = "SidebarProvider"
|
||||
|
||||
const Sidebar = React.forwardRef<
|
||||
|
||||
@@ -14,7 +14,7 @@ const ToastViewport = React.forwardRef<
|
||||
<ToastPrimitives.Viewport
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed top-safe z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-safe sm:right-safe sm:top-auto sm:flex-col md:max-w-[480px]",
|
||||
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[480px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -5,7 +5,6 @@ export interface AIProvider {
|
||||
baseURL: string;
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export interface AISettings {
|
||||
|
||||
@@ -7,31 +7,17 @@ export interface AppConfig {
|
||||
theme: Theme;
|
||||
/** Selected relay URL */
|
||||
relayUrl: string;
|
||||
/** Git repository URL to use as project template */
|
||||
projectTemplate: string;
|
||||
/** ESM CDN URL for package imports */
|
||||
esmUrl: string;
|
||||
/** HTTP proxy used to bypass CORS for AI and Git operations */
|
||||
corsProxy: string;
|
||||
/** Favicon URL template (e.g., "https://external-content.duckduckgo.com/ip3/{hostname}.ico") */
|
||||
faviconUrl: string;
|
||||
/** Preview domain for iframe sandboxing (e.g., "local-shakespeare.dev") */
|
||||
previewDomain: string;
|
||||
/** Deploy server domain (e.g., "shakespeare.wtf") */
|
||||
deployServer: string;
|
||||
/** Selected language */
|
||||
language?: string;
|
||||
/** Whether to show the showcase section */
|
||||
showcaseEnabled: boolean;
|
||||
/** Npub of the showcase moderator */
|
||||
showcaseModerator: string;
|
||||
/** Nostr Git Servers (hostnames) */
|
||||
ngitServers: string[];
|
||||
}
|
||||
|
||||
export interface AppContextType {
|
||||
/** Current application configuration */
|
||||
config: AppConfig;
|
||||
/** Update configuration using a callback that receives current config and returns new config */
|
||||
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
|
||||
updateConfig: (updater: (currentConfig: AppConfig) => AppConfig) => void;
|
||||
/** Optional list of preset relays to display in the RelaySelector */
|
||||
presetRelays?: { name: string; url: string }[];
|
||||
}
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import { createContext } from 'react';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
|
||||
export interface ConsoleErrorContextValue {
|
||||
hasErrors: boolean;
|
||||
consoleError: ProjectPreviewConsoleError | null;
|
||||
clearErrors: () => void;
|
||||
dismissConsoleError: () => void;
|
||||
}
|
||||
|
||||
export const ConsoleErrorContext = createContext<ConsoleErrorContextValue | undefined>(undefined);
|
||||