Compare commits

..
12 Commits
245 changed files with 6671 additions and 16877 deletions

No files matched your search

-121
View File
@@ -1,121 +0,0 @@
---
name: plausible-analytics
description: Add Plausible Analytics tracking to the application, configured through AppConfig and environment variables.
---
# Plausible Analytics
Add privacy-friendly analytics with [Plausible](https://plausible.io/) using the `@plausible-analytics/tracker` npm package. Configuration lives in `AppConfig` so it can be set via `VITE_` environment variables.
## 1. Install the package
```bash
npm install @plausible-analytics/tracker
```
## 2. Add fields to `AppConfig`
In `src/contexts/AppContext.ts`, add two fields to the `AppConfig` interface:
```typescript
export interface AppConfig {
// ...existing fields...
/** Plausible Analytics domain (empty string = disabled). */
plausibleDomain: string;
/** Plausible Analytics API endpoint (empty string = use default). */
plausibleEndpoint: string;
}
```
## 3. Update the Zod schema in `AppProvider.tsx`
Add the new fields to the `AppConfigSchema`:
```typescript
const AppConfigSchema = z.object({
// ...existing fields...
plausibleDomain: z.string(),
plausibleEndpoint: z.string(),
}) satisfies z.ZodType<AppConfig>;
```
## 4. Create `PlausibleProvider`
Create `src/components/PlausibleProvider.tsx`:
```tsx
import { ReactNode, useEffect, useRef } from 'react';
import { useAppContext } from '@/hooks/useAppContext';
interface PlausibleProviderProps {
children: ReactNode;
}
/**
* Reactively initializes Plausible Analytics from AppConfig.
* Plausible's `init()` can only be called once, so we guard with a ref.
*/
export function PlausibleProvider({ children }: PlausibleProviderProps) {
const { config } = useAppContext();
const initializedRef = useRef(false);
useEffect(() => {
if (initializedRef.current || !config.plausibleDomain) return;
initializedRef.current = true;
import('@plausible-analytics/tracker').then(({ init }) => {
init({
domain: config.plausibleDomain,
...(config.plausibleEndpoint && { endpoint: config.plausibleEndpoint }),
});
}).catch(console.error);
}, [config.plausibleDomain, config.plausibleEndpoint]);
return <>{children}</>;
}
```
## 5. Wire into `App.tsx`
Import `PlausibleProvider` and add it inside `AppProvider` (it needs access to `useAppContext`):
```tsx
import { PlausibleProvider } from '@/components/PlausibleProvider';
// In the defaultConfig, add:
const defaultConfig: AppConfig = {
// ...existing fields...
plausibleDomain: import.meta.env.VITE_PLAUSIBLE_DOMAIN || '',
plausibleEndpoint: import.meta.env.VITE_PLAUSIBLE_ENDPOINT || '',
};
// In the JSX, wrap children of AppProvider:
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<PlausibleProvider>
{/* ...rest of providers... */}
</PlausibleProvider>
</AppProvider>
```
## 6. Update `TestApp.tsx`
Add the new fields to the test default config with empty strings (disabled):
```typescript
const defaultConfig: AppConfig = {
// ...existing fields...
plausibleDomain: '',
plausibleEndpoint: '',
};
```
## 7. Configure via environment variables
Create or update `.env`:
```
VITE_PLAUSIBLE_DOMAIN="example.com"
VITE_PLAUSIBLE_ENDPOINT="https://plausible.example.com/api/event"
```
`VITE_PLAUSIBLE_ENDPOINT` is optional -- it defaults to Plausible Cloud's endpoint if omitted. Set it when using a self-hosted Plausible instance.
-198
View File
@@ -1,198 +0,0 @@
---
name: release
description: Publish a new app release with versioning, changelog, and git tagging. Triggered by "publish a new release" or similar requests.
---
# Release Skill
This skill guides you through publishing a new release of the app. It handles version bumping, changelog generation, and git tagging/pushing.
## Overview
- **Version format**: Marketing version (X.Y.Z), starting from 9.9.1. **This is NOT semver.** Version numbers are chosen based on how the release looks to end users, not based on API compatibility or breaking changes. Think of it like an app store version -- the number reflects the perceived significance of the update to a regular user.
- **Version source of truth**: `package.json` `version` field
- **Changelog**: `CHANGELOG.md` in repo root, using [Keep a Changelog](https://keepachangelog.com/) format
- **Version bumping**:
- **Patch (Z)**: Most releases. Bug fixes, tweaks, internal improvements, anything a user wouldn't specifically notice or seek out.
- **Minor (Y)**: Releases with headline features -- things worth announcing. A user should be able to look at the minor bump and think "oh, something new happened."
- **Major (X)**: Only when the user explicitly requests it (milestones, rebrands, major redesigns)
- **CI trigger**: Pushing a version tag (`v9.9.0`) triggers the CI pipeline to build and create a GitLab release
## Release Procedure
Follow these steps in order. Do NOT skip any step.
### Step 1: Required Reading
Before writing any release notes, you MUST read these pages to understand the product context, voice, and values:
1. **https://soapbox.pub/** -- Soapbox company overview and product suite
2. **https://soapbox.pub/shakespeare/** -- Shakespeare product page
These pages define what Shakespeare is, how it's positioned, and the tone of voice to use. Changelog entries should reflect this identity: creative, empowering, user-focused, emphasizing building and self-expression. Avoid dry technical jargon -- write for people who use the app, not developers.
### Step 2: Pre-flight Checks
```bash
# Ensure working directory is clean
git status
# Ensure we're on main branch
git branch --show-current
# Run the full test suite
npm run test
```
- If the working directory has uncommitted changes, ask the user whether to commit them first or abort.
- If not on `main`, warn the user and ask whether to proceed.
- If tests fail, stop and fix the issues before continuing.
### Step 3: Determine What Changed
```bash
# Get the current version from package.json
node -p "require('./package.json').version"
# Get commits since the last version tag
git log v$(node -p "require('./package.json').version")..HEAD --oneline
```
- If there are no commits since the last tag, inform the user there is nothing to release and stop.
- Review the commit list to understand the scope of changes.
### Step 4: Decide the Version Bump
Analyze the commits from Step 3 and determine the appropriate bump level:
| Bump | When to use | Example |
|------|-------------|---------|
| **Patch** | Bug fixes, minor tweaks, dependency updates, small UI polish, internal tooling, developer-facing pages, CI/build changes, settings/admin screens | 9.9.0 -> 9.9.1 |
| **Minor** | Significant new product features that change how users interact with the app -- the kind of thing you'd highlight in an app store update or announce on social media (e.g., new template support, new AI features, new deployment options, major UI overhaul) | 9.9.1 -> 9.10.0 |
| **Major** | ONLY when the user explicitly instructs a major bump | 9.10.0 -> 10.0.0 |
**Default to patch** when in doubt. The bar for a minor bump is high -- ask yourself: "Would a regular user notice and care about this change?" If the answer is no, it's a patch. Internal pages (changelog, settings, about screens), infrastructure improvements, CI fixes, and developer tooling are always patch-level regardless of whether they technically add a new page or screen.
When bumping minor, reset patch to 0 (e.g., 9.9.3 -> 9.10.0).
When bumping major, reset minor and patch to 0 (e.g., 9.3.1 -> 10.0.0).
### Step 5: Write the Changelog Entry
Prepend a new section to `CHANGELOG.md` directly below the `# Changelog` heading.
**Format:**
```markdown
## [X.Y.Z] - YYYY-MM-DD
### Added
- Description of new features
### Changed
- Description of changes to existing features
### Fixed
- Description of bug fixes
### Removed
- Description of removed features
```
**Rules:**
- Only include categories that have entries (omit empty categories)
- Write **user-facing descriptions**, not raw commit messages
- Keep descriptions concise -- one line per change
- Group related commits into single entries where appropriate
- Use present tense ("Add dark mode toggle", not "Added dark mode toggle")
- Focus on what the user sees/experiences, not internal implementation details
- Use the current date in YYYY-MM-DD format
- **Collapse related work into one entry.** If a feature was added and then fixed/tweaked across multiple commits in the same release, present the finished result as a single "Added" entry. Never list something as "Added" and then also list fixes for that same thing -- the user sees the end product, not the development history.
- **Omit purely internal changes.** CI fixes, build pipeline tweaks, developer tooling, and infrastructure changes should be omitted from the changelog entirely unless they have a direct, visible impact on the user experience. The changelog is for users, not developers.
- **Compare the actual code between versions** to understand what really changed, rather than just reading commit messages. Commit messages may over- or under-represent the significance of changes.
### Step 6: Update Version in All Files
#### 6a. `package.json`
Update the `version` field:
```json
"version": "X.Y.Z"
```
### Step 7: Copy Changelog to Public Directory
The changelog is served at runtime by the app from the `public/` directory. After updating `CHANGELOG.md`, copy it:
```bash
cp CHANGELOG.md public/CHANGELOG.md
```
### Step 8: Pull Latest Changes
Before committing the release, pull the latest changes from the remote to ensure the release commit sits on top of the latest code. This **must** happen before committing and tagging.
```bash
git pull origin main
```
**CRITICAL**: Always use `git pull` (merge), NEVER `git pull --rebase`. Rebasing rewrites commit hashes, which would orphan any tag pointing to the original commit. Since version tags are often protected on the remote and cannot be deleted or updated, a broken tag cannot be easily fixed.
If there are merge conflicts with the pulled changes, resolve them before proceeding.
### Step 9: Commit the Release
```bash
git add package.json CHANGELOG.md public/CHANGELOG.md
git commit -m "release: vX.Y.Z"
```
### Step 10: Tag the Release
```bash
git tag vX.Y.Z
```
The tag format is `v` followed by the version with no suffix. Examples: `v9.9.0`, `v9.10.0`, `v10.0.0`.
### Step 11: Push
```bash
git push origin main vX.Y.Z
```
**CRITICAL**: Push only the specific tag being released. NEVER use `--tags` -- that pushes ALL local tags, including stale or deleted ones.
### Step 12: Confirm
After pushing, inform the user:
- The new version number
- A brief summary of what was released
- That CI will handle building and publishing the artifacts
## File Reference
| File | What to update | Notes |
|------|---------------|-------|
| `package.json` | `version` field | Source of truth for the version |
| `CHANGELOG.md` | Prepend new section | User-facing changelog |
| `public/CHANGELOG.md` | Copy from `CHANGELOG.md` | Served at runtime by the app |
## Troubleshooting
### "Nothing to release"
If `git log` shows no commits since the last tag, there genuinely is nothing to release.
### Tests fail
Fix the failing tests before proceeding. The release must not contain broken code.
### Wrong version bumped
If you tagged the wrong version and haven't pushed yet:
```bash
git tag -d vX.Y.Z # delete the local tag
git reset --soft HEAD~1 # undo the commit but keep changes staged
```
Then redo steps 4-10 with the correct version.
### Already pushed a bad release
This requires manual intervention. Inform the user and suggest they delete the tag and release from GitLab manually, then re-run the release process.
-4
View File
@@ -1,10 +1,6 @@
# Sentry
VITE_SENTRY_DSN="https://********************************@*****************.example.com/****************"
# Plausible Analytics
VITE_PLAUSIBLE_DOMAIN="example.com"
VITE_PLAUSIBLE_ENDPOINT="https://plausible.example.com/api/event"
# GitHub OAuth Configuration
VITE_GITHUB_OAUTH_CLIENT_ID="********************"
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
+4 -214
View File
@@ -1,28 +1,15 @@
image: node:25
image: node:22
default:
interruptible: true
timeout: 1 minute
cache:
key:
files:
- package-lock.json
paths:
- node_modules/
stages:
- test
- deploy
- build
- release
- publish
test:
stage: test
rules:
- if: $CI_COMMIT_TAG
when: never
- when: always
script:
- npm run typecheck
- npm run build
@@ -30,10 +17,6 @@ test:
pages:
stage: deploy
rules:
- if: $CI_COMMIT_TAG
when: never
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
script:
- npm run build
- rm -rf public
@@ -41,199 +24,6 @@ pages:
artifacts:
paths:
- public
deploy-nsite:
stage: deploy
timeout: 10 minutes
rules:
- if: $CI_COMMIT_TAG
when: never
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
variables:
NSYTE_VERSION: "v0.24.1"
script:
# Build the web app
- npm ci
- npm run build
- cp dist/index.html dist/404.html
# Remove sourcemaps to stay under nsite's 65KB manifest limit
- find dist -name '*.map' -delete
# Download nsyte binary
- curl -fsSL "https://github.com/sandwichfarm/nsyte/releases/download/${NSYTE_VERSION}/nsyte-linux" -o /usr/local/bin/nsyte
- chmod +x /usr/local/bin/nsyte
# Deploy to nsite via nsyte using the nbunksec credential
- >-
nsyte deploy ./dist
-i
--sec "$NSITE_NBUNKSEC"
--name shakespeare
--relays "wss://relay.ditto.pub,wss://relay.nsite.lol,wss://relay.dreamith.to,wss://relay.primal.net"
--servers "https://blossom.primal.net,https://blossom.ditto.pub,https://blossom.dreamith.to"
--fallback "/index.html"
--use-fallback-relays
--use-fallback-servers
build-apk:
stage: build
image: eclipse-temurin:21-jdk
timeout: 15 minutes
needs: []
rules:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
variables:
ANDROID_SDK_ROOT: /opt/android-sdk
ANDROID_HOME: /opt/android-sdk
before_script:
# Install system dependencies
- apt-get update -qq
- apt-get install -y -qq curl unzip > /dev/null
# Install Node.js 22
- curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
- apt-get install -y -qq nodejs > /dev/null
- node --version
- npm --version
# Install Android SDK command-line tools
- mkdir -p $ANDROID_SDK_ROOT/cmdline-tools
- curl -fsSL https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip -o cmdline-tools.zip
- unzip -q cmdline-tools.zip -d $ANDROID_SDK_ROOT/cmdline-tools
- mv $ANDROID_SDK_ROOT/cmdline-tools/cmdline-tools $ANDROID_SDK_ROOT/cmdline-tools/latest
- export PATH="$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/platform-tools:$PATH"
# Accept licenses and install SDK components
- printf 'y\ny\ny\ny\ny\ny\ny\n' | sdkmanager --licenses > /dev/null 2>&1 || true
- sdkmanager --install "platforms;android-36" "build-tools;36.0.0" "platform-tools" > /dev/null
# Write local.properties for Gradle
- echo "sdk.dir=$ANDROID_SDK_ROOT" > android/local.properties
# Decode signing keystore and migrate JKS -> PKCS12 for Gradle compatibility
- echo "$ANDROID_KEYSTORE_BASE64" | base64 -d > android/app/my-upload-key.jks
- keytool -importkeystore
-srckeystore android/app/my-upload-key.jks
-destkeystore android/app/my-upload-key.keystore
-deststoretype pkcs12
-srcstorepass "$KEYSTORE_PASSWORD"
-deststorepass "$KEYSTORE_PASSWORD"
-srcalias upload
-destalias upload
-noprompt
- rm android/app/my-upload-key.jks
# Write key.properties from CI/CD variables
- |
cat > android/key.properties << EOF
storePassword=$KEYSTORE_PASSWORD
keyPassword=$KEY_PASSWORD
keyAlias=upload
storeFile=my-upload-key.keystore
EOF
script:
# Extract semver version from git tag (e.g., v9.9.2 -> 9.9.2)
- TAG="${CI_COMMIT_TAG#v}"
- VERSION_NAME="${TAG}"
- VERSION_CODE="${CI_PIPELINE_IID}"
- echo "Building version $VERSION_NAME (code $VERSION_CODE) from tag $CI_COMMIT_TAG"
# Stamp version into build.gradle
- sed -i "s/versionCode [0-9]*/versionCode ${VERSION_CODE}/" android/app/build.gradle
- sed -i "s/versionName \"[^\"]*\"/versionName \"${VERSION_NAME}\"/" android/app/build.gradle
# Build web assets
- npm ci
- npx vite build -l error
- cp dist/index.html dist/404.html
# Sync web assets to Capacitor Android project
- npx cap sync android
# Build signed release APK
- cd android && chmod +x gradlew && ./gradlew assembleRelease bundleRelease && cd ..
# Copy APK to a predictable artifact path
- mkdir -p artifacts
- cp android/app/build/outputs/apk/release/app-release.apk "artifacts/Shakespeare.apk"
- cp android/app/build/outputs/bundle/release/app-release.aab "artifacts/Shakespeare.aab"
- ls -lh artifacts/
# Upload to Generic Packages registry for a stable public download URL
- |
curl --fail --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \
--upload-file "artifacts/Shakespeare.apk" \
"${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/shakespeare/${CI_COMMIT_TAG}/Shakespeare-${CI_COMMIT_TAG}.apk"
- |
curl --fail --header "JOB-TOKEN: ${CI_JOB_TOKEN}" \
--upload-file "artifacts/Shakespeare.aab" \
"${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/shakespeare/${CI_COMMIT_TAG}/Shakespeare-${CI_COMMIT_TAG}.aab"
artifacts:
paths:
- artifacts/Shakespeare.apk
- artifacts/Shakespeare.aab
expire_in: 90 days
cache:
key: android-gradle
paths:
- android/.gradle/
- .gradle/
release:
stage: release
image: registry.gitlab.com/gitlab-org/release-cli:latest
needs:
- build-apk
rules:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
script:
- echo "Creating release for $CI_COMMIT_TAG"
# Extract the latest changelog section for the release description.
# Reads from "## [version]" to the next "## [" or end of file.
- |
VERSION="${CI_COMMIT_TAG#v}"
RELEASE_NOTES=$(awk "/^## \\[${VERSION}\\]/{found=1; next} /^## \\[/{if(found) exit} found{print}" CHANGELOG.md)
if [ -z "$RELEASE_NOTES" ]; then
RELEASE_NOTES="Shakespeare ${CI_COMMIT_TAG}"
fi
- echo "$RELEASE_NOTES" > release-notes.md
release:
tag_name: $CI_COMMIT_TAG
name: $CI_COMMIT_TAG
description: './release-notes.md'
assets:
links:
- name: Shakespeare-${CI_COMMIT_TAG}.apk
url: ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/shakespeare/${CI_COMMIT_TAG}/Shakespeare-${CI_COMMIT_TAG}.apk
link_type: package
- name: Shakespeare-${CI_COMMIT_TAG}.aab
url: ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/shakespeare/${CI_COMMIT_TAG}/Shakespeare-${CI_COMMIT_TAG}.aab
link_type: package
publish-zapstore:
stage: publish
image: golang:1.24
needs:
- build-apk
rules:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
variables:
SIGN_WITH: $ZAPSTORE_BUNKER_URL
RELAY_URLS: "wss://relay.zapstore.dev,wss://relay.ditto.pub"
BLOSSOM_URL: "https://blossom.ditto.pub"
script:
- go install github.com/zapstore/zsp@latest
# Restore the persistent NIP-46 client key so the bunker recognizes us across CI runs.
# zsp stores client keys at ~/.config/zsp/bunker-keys/<bunker-pubkey>.key
- BUNKER_PUBKEY=$(echo "$ZAPSTORE_BUNKER_URL" | sed 's|bunker://||;s|?.*||')
- mkdir -p ~/.config/zsp/bunker-keys
- echo "$ZAPSTORE_CLIENT_KEY" > ~/.config/zsp/bunker-keys/${BUNKER_PUBKEY}.key
- APK_PATH="artifacts/Shakespeare.apk"
- VERSION="${CI_COMMIT_TAG#v}"
- sed -i "2i release_source:\ ./${APK_PATH}" zapstore.yaml
- sed -i "2i version:\ ${VERSION}" zapstore.yaml
- zsp publish --quiet --skip-preview zapstore.yaml
only:
variables:
- $CI_DEFAULT_BRANCH == $CI_COMMIT_REF_NAME
+3 -11
View File
@@ -1,7 +1,3 @@
# Agent Rules
- ALWAYS commit after you finish your turn. No exceptions. Don't ask for permission, just do it.
# Shakespeare - AI-Powered App 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.
@@ -45,8 +41,7 @@ Shakespeare provides AI agents with specialized tools for project development (n
- **NpmAddPackageTool**: Add npm packages to projects
- **NpmRemovePackageTool**: Remove npm packages from projects
- **GitCommitTool**: Commit changes to Git repositories
- **WebFetchTool**: Fetch and read web pages with support for markdown, text, and HTML formats
- **WebSearchTool**: Search the web using Exa AI for real-time web searches
- **ReadWebpageTool**: Fetch and read web pages
- **NostrReadNipTool**: Read Nostr protocol NIP documents
- **NostrReadKindTool**: Read Nostr event kind documentation
- **NostrReadTagTool**: Read Nostr tag documentation
@@ -54,9 +49,6 @@ Shakespeare provides AI agents with specialized tools for project development (n
- **NostrReadNipsIndexTool**: Read the full list of NIPs, kinds, and tags
- **NostrFetchEventTool**: Fetch Nostr events using NIP-19 identifiers
- **NostrGenerateKindTool**: Generate unused Nostr event kind numbers
- **NostrEncodeTool**: Encode hex values into NIP-19 bech32 entities (npub, note, nprofile, nevent, naddr)
- **NostrDecodeTool**: Decode NIP-19 bech32 entities into hex and structured data
- **BlossomUploadTool**: Upload files from the project to Blossom media hosting, returns a public URL
- **ReadConsoleMessagesTool**: Read console messages from project preview with filtering capabilities
#### Shell Commands
@@ -240,7 +232,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
- Git integration: `GitCommitTool`
- Shell access: `ShellTool`
- Web access: `WebFetchTool`, `WebSearchTool`
- Web access: `ReadWebpageTool`
- Nostr tools: `NostrReadNipTool`, `NostrFetchEventTool`, `NostrGenerateKindTool`, etc.
- `/src/contexts/`: React context providers
- `AppContext`: Global app configuration and theme
@@ -1099,7 +1091,7 @@ const defaultConfig: AppConfig = {
relayMetadata: {
relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.primal.net', read: true, write: true },
{ url: 'wss://relay.nostr.band', read: true, write: true },
],
updatedAt: 0,
},
-98
View File
@@ -1,98 +0,0 @@
# Changelog
## [9.11.4] - 2026-04-17
### Fixed
- Preview pane no longer gets stuck on stale builds during rapid edits
### Changed
- Reduce AI costs for Anthropic models via OpenRouter by caching tool definitions across turns
## [9.11.3] - 2026-04-12
### Fixed
- App publish dialog now appears on mobile devices
- Changelog available offline via ServiceWorker precache
## [9.11.2] - 2026-04-06
### Fixed
- Derive private preview subdomains with HMAC to prevent cross-project origin collisions on iframe.diy
## [9.11.1] - 2026-04-05
### Changed
- Switch preview pane to iframe.diy for improved reliability and compatibility
- New users start with OpenCode Zen pre-configured for a zero-setup first experience
- Default nsite gateway changed to shakespeare.to with vanity subdomain support
- Update default Blossom servers and relay lists across deployments and uploads
### Fixed
- Default settings no longer override existing users' recently used models
- Showcase card clone URLs now use proper Nostr URI encoding
- Service worker no longer blocks SvelteKit nsite routes
## [9.11.0] - 2026-04-03
### Added
- Upload a banner image for your app directly from the App dialog
- T-tag editor in the App dialog Advanced section for tagging your app by category
- Delete App button in the App dialog Advanced section when editing an existing app
- Ngit repo and nsite deployment address fields in the App dialog Advanced section
- Auto-fill app name, description, and images from your project's OG tags and web manifest on first publish
### Changed
- Redesigned App dialog with an overlapping banner and avatar card layout
- Reorganized App dialog Advanced section into General, Handlers, and Tags tabs
- Showcase cards now show banner and icon images, and require both to appear in the showcase
- Validation summary above the Save button replaces per-field "Required" labels
- Updated showcase curator to the Shakespeare Builders community list
### Fixed
- Upgrade Nostrify to fix bunker connection issues
## [9.10.4] - 2026-04-02
### Fixed
- Fix Android splash screen showing logo masked to white silhouette instead of full color
## [9.10.3] - 2026-04-02
### Fixed
- Fix Android app showing default Capacitor splash screen and icon colors
## [9.10.2] - 2026-04-02
### Fixed
- Fix Android app showing default Capacitor icon instead of Shakespeare logo in app drawer
## [9.10.1] - 2026-04-02
### Fixed
- Replace default Capacitor vector drawable icons with Shakespeare logo
## [9.10.0] - 2026-04-02
### Added
- Android app powered by Capacitor with deep links, splash screen, and signed release builds
- CI pipeline for building APKs, publishing to GitLab releases, and distributing via Zapstore
- Nsite deployment for decentralized hosting via Nostr
### Changed
- Make version number on mobile settings a clickable link to the changelog with build date
## [9.9.2] - 2026-04-02
### Changed
- Simplify nsite deployment to always use named sites, removing the root site option
### Fixed
- Fix crash in "What's new" toast when used outside the router context
- Truncate long changelog excerpts in update notifications so they fit neatly in the toast
- Left-align changelog page content for better readability
## [9.9.1] - 2026-04-02
### Added
- Changelog page and versioning system with "What's new" toast notifications on updates
- Release skill for managing versioned releases with changelog generation and git tagging
-101
View File
@@ -1,101 +0,0 @@
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
*.jks
*.keystore
key.properties
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
# Android Profiling
*.hprof
# Cordova plugins for Capacitor
capacitor-cordova-android-plugins
# Copied web assets
app/src/main/assets/public
# Generated Config files
app/src/main/assets/capacitor.config.json
app/src/main/assets/capacitor.plugins.json
app/src/main/res/xml/config.xml
-28
View File
@@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>android</name>
<comment>Project android created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
<filteredResources>
<filter>
<id>1775119841750</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>
@@ -1,13 +0,0 @@
arguments=--init-script /home/alex/.cache/opencode/bin/jdtls/config_linux/org.eclipse.osgi/58/0/.cp/gradle/init/init.gradle
auto.sync=false
build.scans.enabled=false
connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER)
connection.project.dir=
eclipse.preferences.version=1
gradle.user.home=
java.home=/usr/lib/jvm/java-21-openjdk-amd64
jvm.arguments=
offline.mode=false
override.workspace.settings=true
show.console.view=true
show.executions.view=true
-6
View File
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-21/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>
-2
View File
@@ -1,2 +0,0 @@
/build/*
!/build/.npmkeep
-34
View File
@@ -1,34 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>app</name>
<comment>Project app created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
<filteredResources>
<filter>
<id>1775119841776</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>
@@ -1,2 +0,0 @@
connection.project.dir=..
eclipse.preferences.version=1
-73
View File
@@ -1,73 +0,0 @@
apply plugin: 'com.android.application'
def keystorePropertiesFile = rootProject.file("key.properties")
def keystoreProperties = new Properties()
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}
android {
namespace = "diy.shakespeare.app"
compileSdk = rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "diy.shakespeare.app"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "9.9.2"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
signingConfigs {
release {
if (keystorePropertiesFile.exists()) {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile file(keystoreProperties['storeFile'])
storePassword keystoreProperties['storePassword']
}
}
}
buildTypes {
release {
signingConfig signingConfigs.release
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation project(':capacitor-android')
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
}
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}
-20
View File
@@ -1,20 +0,0 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
}
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
implementation project(':capacitor-app')
implementation project(':capacitor-status-bar')
}
if (hasProperty('postBuildExtras')) {
postBuildExtras()
}
-28
View File
@@ -1,28 +0,0 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Keep Capacitor classes (WebView JS bridge)
-keep class com.getcapacitor.** { *; }
-keep class diy.shakespeare.app.** { *; }
# Keep WebView JS interfaces
-keepclassmembers class * {
@android.webkit.JavascriptInterface <methods>;
}
# Keep OkHttp (used by Capacitor)
-dontwarn okhttp3.**
-dontwarn okio.**
-keep class okhttp3.** { *; }
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -1,26 +0,0 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import android.content.Context;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.getcapacitor.app", appContext.getPackageName());
}
}
-50
View File
@@ -1,50 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation|density"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- Deep links: open shakespeare.diy URLs in the app -->
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="shakespeare.diy" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
</application>
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
@@ -1,5 +0,0 @@
package diy.shakespeare.app;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

@@ -1,82 +0,0 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<!--
Shakespeare theater masks logo from public/shakespeare.svg.
SVG viewBox is "0 0 128 128", with original colors preserved.
Scaled to ~55% and centered within the 108x108 viewport to fit
Android's adaptive icon safe zone (66% of 108dp).
-->
<group
android:translateX="24.3"
android:translateY="15.5"
android:scaleX="0.464"
android:scaleY="0.464">
<!-- Red beak right -->
<path
android:fillColor="#F45125"
android:pathData="M110.28,61.32l2.63,8.84c0,0,7.24,-1.6,7.62,3.2c0.38,4.8,-6.77,8,-6.77,8l2.26,10.63 c0,0,7.9,-6.4,8,-15.61c0,0,0.66,-11.29,-6.11,-13.92C113.67,60.85,110.28,61.32,110.28,61.32z"/>
<!-- Red tail feathers -->
<path
android:fillColor="#F45125"
android:pathData="M68.71,94.99c0,0,-11.1,-4.7,-16.46,1.98c-0.75,0.94,-1.41,1.88,-2.16,2.82 c-0.56,0.75,-1.13,1.5,-1.69,2.16c-0.47,0.56,-1.03,1.13,-1.69,1.5c-0.66,0.38,-1.32,0.66,-2.07,0.85c-0.94,0.19,-1.88,0.19,-2.82,0.09 c-1.32,-0.09,-2.63,-0.38,-3.95,-0.66c-0.47,-0.09,-0.85,-0.19,-1.22,-0.28c-0.09,0,-0.19,-0.09,-0.28,-0.09 s-0.19,-0.09,-0.28,-0.09c-0.38,0.09,0.19,0.75,0.38,0.94c0.28,0.28,0.56,0.66,0.85,0.94c0.85,0.75,1.69,1.5,2.73,1.98 c1.32,0.66,2.73,1.03,4.14,1.13c0.09,0,0.38,0,0.47,0.09c0.19,0.19,-0.28,0.47,-0.47,0.56c-0.28,0.19,-0.47,0.28,-0.75,0.38 c-0.85,0.38,-1.79,0.56,-2.63,0.75c-0.85,0.19,-1.69,0.28,-2.45,0.28c-0.47,0,-0.85,0.09,-1.22,0.09c-0.28,0,-0.56,-0.09,-0.85,0 s0.09,0.47,0.28,0.56c0.38,0.19,0.75,0.47,1.13,0.66c1.13,0.56,2.26,1.03,3.39,1.32c1.5,0.38,3.1,0.56,4.61,0.38 c1.32,-0.19,2.63,-0.56,3.86,-1.03c6.77,-3.1,6.21,-9.59,12.42,-10.16c4.61,-0.38,11.1,2.07,11.1,2.07L68.71,94.99z"/>
<!-- Red beak left -->
<path
android:fillColor="#F45125"
android:pathData="M19.79,38.28c0,0,-12.13,1.98,-15.24,12.79C0.61,64.9,20.26,69.5,20.26,69.5l1.22,-9.41 c0,0,-13.07,-1.32,-12.32,-6.3c0.94,-6.21,11.85,-5.64,11.85,-5.64L19.79,38.28z"/>
<!-- Red wing detail -->
<path
android:fillColor="#F45125"
android:pathData="M20.73,70.92c0,0,-1.88,0.56,-4.61,2.54c-1.88,1.32,-4.42,3.01,-6.87,5.93 c-1.22,1.41,-2.16,3.1,-2.82,4.89c-0.47,1.22,-0.66,2.45,-0.66,3.76c0,0.28,0,0.56,0,0.85c0,0.09,0,0.85,0.28,0.66 c0.09,-0.09,0.19,-0.38,0.28,-0.47c0.19,-0.47,0.47,-0.85,0.75,-1.22c0.85,-1.13,1.88,-2.16,3.01,-3.01c0.38,-0.28,0.75,-0.47,1.13,-0.66 c0.28,-0.28,0.75,-0.66,0.94,-0.28c0.09,0.19,-0.09,0.47,-0.19,0.66c-0.09,0.28,-0.19,0.66,-0.19,0.94c-0.38,1.5,-0.56,3.01,-0.75,4.51 c-0.09,0.85,-0.09,1.69,0,2.45c0,0.38,0.09,0.85,0.09,1.22c0,0.19,0.09,0.38,0.09,0.56c0,0.19,0.19,0.47,0.38,0.19 c0.09,-0.09,0.09,-0.19,0.19,-0.38c0.19,-0.28,0.28,-0.66,0.47,-0.94c0.47,-0.85,0.94,-1.69,1.5,-2.63c0.66,-1.13,1.41,-2.16,2.16,-3.1 c0.85,-1.13,1.88,-2.26,2.92,-3.2c1.13,-1.03,2.35,-2.07,3.67,-2.92c0.75,-0.47,1.6,-0.94,2.45,-1.32L20.73,70.92z"/>
<!-- Yellow body -->
<path
android:fillColor="#FCC21B"
android:pathData="M116.4,79.29c-1.13,-5.55,-2.73,-11.01,-4.51,-16.46c-1.5,-4.61,-3.1,-9.31,-5.83,-13.36 c-1.22,-1.79,-3.01,-3.01,-5.27,-3.86c-4.33,-1.69,-9.97,-1.98,-13.73,-1.98c-5.64,0,-11.48,1.22,-16.74,3.67 c-1.88,5.64,-7.05,19.94,-14.86,26.34c0.47,2.63,1.03,5.36,1.79,8c1.32,4.61,3.01,9.22,4.61,13.83c1.5,4.42,3.29,8.84,6.58,12.23 c0.85,0.94,1.88,1.69,2.82,2.45c2.26,1.88,4.99,3.01,7.71,3.95c2.54,0.85,5.17,1.5,7.81,2.07c4.7,1.03,11.48,2.82,16.08,0.66 c2.54,-1.13,4.61,-2.92,6.3,-5.08c1.79,-2.26,3.2,-4.8,4.42,-7.43c1.88,-3.95,3.86,-8.37,4.14,-12.89 C117.99,87.38,117.24,83.24,116.4,79.29z"/>
<!-- Blue head -->
<path
android:fillColor="#429ADF"
android:pathData="M77.64,33.57c-0.28,-1.03,-1.03,-2.07,-1.6,-3.01c-6.3,-11.01,-20.04,-16.27,-32.26,-15.52 c-3.76,0.28,-9.31,0.85,-13.54,2.73c-2.07,0.94,-3.86,2.35,-4.99,4.14c-2.54,4.23,-3.76,8.94,-5.08,13.64 C18.67,41,17.35,46.55,16.5,52.2c-0.75,4.89,-1.41,10.25,-0.09,15.14c1.03,3.86,3.29,9.22,5.74,12.32 c2.73,3.39,6.58,7.34,10.72,8.84c0.75,0.28,1.6,0.47,2.45,0.66c1.6,0.28,3.29,0.47,4.89,0.19c0.94,-0.19,1.98,-0.28,2.92,-0.56 c1.88,-0.47,3.67,-1.13,5.46,-1.79c7.52,-3.01,13.64,-7.43,17.68,-14.58c1.69,-3.1,3.1,-6.4,4.42,-9.69c0.09,-0.19,0.19,-0.38,0.19,-0.56 c1.98,-5.46,3.29,-11.19,4.61,-16.84c0.66,-2.73,1.41,-5.55,1.79,-8.37C77.55,35.92,77.92,34.7,77.64,33.57z"/>
<!-- Dark eye band -->
<path
android:fillColor="#193D51"
android:pathData="M23.09,40.53c1.69,-3.1,5.74,-5.55,9.31,-5.08c0.56,0.09,1.22,0.19,1.79,0.47 c3.57,1.5,5.74,4.99,4.89,8.56c-0.19,0.75,-0.66,0.85,-1.22,0.38c-1.98,-1.69,-3.57,-3.01,-6.21,-3.67c-2.16,-0.56,-4.61,-0.28,-6.68,0.28 c-0.47,0.09,-1.22,0.56,-1.69,0.38C22.61,41.57,22.9,40.91,23.09,40.53z"/>
<!-- Dark mouth/chin -->
<path
android:fillColor="#193D51"
android:pathData="M62.21,64.9c-1.03,1.6,-2.45,3.01,-3.86,4.33c-0.38,0.28,-0.66,0.66,-1.03,0.94 c-5.64,4.7,-13.26,7.05,-20.51,5.27c-1.98,-0.47,-4.14,-1.5,-5.74,-2.73c-1.22,-0.94,-2.45,-2.16,-3.48,-3.39c-1.88,-2.26,-3.29,-4.89,-4.23,-7.62 c-0.47,-1.41,-0.75,-2.73,-0.94,-4.23c0,-0.47,-0.66,-5.46,0.85,-4.8c0.38,0.19,0.66,0.47,0.94,0.75c0.28,0.38,0.47,0.75,0.75,1.03 c0.66,0.85,1.32,1.69,2.07,2.45c2.35,2.73,5.27,4.89,8.56,6.4c2.26,1.03,4.7,1.6,7.15,1.79c1.41,0.09,2.73,0.19,4.14,0.09 c5.08,-0.28,10.25,-1.79,14.86,-3.76c0.38,-0.19,0.85,-0.47,1.32,-0.47C64.66,61.04,62.5,64.52,62.21,64.9z"/>
<!-- Dark eye detail -->
<path
android:fillColor="#193D51"
android:pathData="M67.58,51.16c0,0.47,-0.19,1.13,-0.75,1.03c-0.47,-0.09,-0.85,-0.94,-1.13,-1.22 c-1.32,-1.69,-3.86,-3.57,-6.4,-4.14c-3.01,-0.75,-5.27,0.56,-8.28,0.85c-0.85,0.09,-1.32,-0.28,-0.94,-1.03c1.6,-3.48,5.83,-6.21,10.25,-5.46 c0.75,0.09,1.41,0.28,2.07,0.56C66.26,43.36,67.86,47.59,67.58,51.16z"/>
<!-- Gold eye detail -->
<path
android:fillColor="#9B7515"
android:pathData="M91.84,63.86c4.23,2.73,9.69,3.48,14.58,3.2c1.41,-0.09,2.26,0.09,1.88,1.69 c-0.75,3.29,-3.86,5.17,-6.87,5.83c-0.75,0.19,-1.5,0.19,-2.26,0.19c-1.41,-0.09,-2.82,-0.66,-4.04,-1.5c-2.63,-1.79,-4.61,-4.89,-5.17,-8 C89.68,63.67,90.25,62.83,91.84,63.86z"/>
<!-- Gold mouth detail -->
<path
android:fillColor="#9B7515"
android:pathData="M65.22,80.79C64,79.57,64.66,79,65.98,78.25c4.51,-2.35,9.03,-5.93,11.38,-10.63 c0.85,-1.79,1.79,-1.41,2.45,0.28c1.13,3.1,1.03,6.87,-0.38,9.88c-0.66,1.41,-1.6,2.63,-2.82,3.57c-0.66,0.47,-1.32,0.75,-2.07,1.03 C71.43,83.33,67.58,83.24,65.22,80.79z"/>
<!-- Gold chin/jaw detail -->
<path
android:fillColor="#9B7515"
android:pathData="M110,96.41c-0.38,0,-0.94,-0.38,-1.41,-0.66c-0.47,-0.28,-0.94,-0.66,-1.22,-0.85 c-1.13,-0.56,-2.45,-1.13,-3.67,-1.5c-3.76,-1.22,-7.9,-1.22,-11.57,0c-2.63,0.85,-5.17,2.45,-7.24,4.33c-2.26,2.16,-3.95,4.8,-6.11,7.05 c-0.28,0.28,-0.56,0.56,-0.85,0.75c-0.56,0.28,-1.13,-0.09,-1.32,-0.66c-0.94,-3.95,1.69,-9.5,3.67,-12.89c2.26,-3.76,5.55,-6.77,9.78,-8 c2.07,-0.66,4.33,-0.66,6.49,-0.38c6.3,0.94,12.79,5.93,14.02,11.66C110.56,95.75,110.47,96.5,110,96.41z"/>
</group>
</vector>
@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#2b0037"
android:pathData="M0,0h108v108h-108z" />
</vector>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

@@ -1,83 +0,0 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="240dp"
android:height="240dp"
android:viewportWidth="1200"
android:viewportHeight="1200">
<!--
Android 12 splash screen masks the icon to a circle at 2/3 of canvas (160dp of 240dp).
The Shakespeare logo SVG has viewBox="0 0 128 128".
We scale the 128x128 logo to fit ~800x800 in the center of 1200x1200,
leaving ~200px padding on each side for the circular safe zone.
Scale factor: 800/128 = 6.25. Translate: (200, 200) to shift origin.
-->
<group
android:translateX="200"
android:translateY="200"
android:scaleX="6.25"
android:scaleY="6.25">
<!-- Red beak right -->
<path
android:fillColor="#F45125"
android:pathData="M110.28,61.32l2.63,8.84c0,0,7.24,-1.6,7.62,3.2c0.38,4.8,-6.77,8,-6.77,8l2.26,10.63 c0,0,7.9,-6.4,8,-15.61c0,0,0.66,-11.29,-6.11,-13.92C113.67,60.85,110.28,61.32,110.28,61.32z"/>
<!-- Red tail feathers -->
<path
android:fillColor="#F45125"
android:pathData="M68.71,94.99c0,0,-11.1,-4.7,-16.46,1.98c-0.75,0.94,-1.41,1.88,-2.16,2.82 c-0.56,0.75,-1.13,1.5,-1.69,2.16c-0.47,0.56,-1.03,1.13,-1.69,1.5c-0.66,0.38,-1.32,0.66,-2.07,0.85c-0.94,0.19,-1.88,0.19,-2.82,0.09 c-1.32,-0.09,-2.63,-0.38,-3.95,-0.66c-0.47,-0.09,-0.85,-0.19,-1.22,-0.28c-0.09,0,-0.19,-0.09,-0.28,-0.09 s-0.19,-0.09,-0.28,-0.09c-0.38,0.09,0.19,0.75,0.38,0.94c0.28,0.28,0.56,0.66,0.85,0.94c0.85,0.75,1.69,1.5,2.73,1.98 c1.32,0.66,2.73,1.03,4.14,1.13c0.09,0,0.38,0,0.47,0.09c0.19,0.19,-0.28,0.47,-0.47,0.56c-0.28,0.19,-0.47,0.28,-0.75,0.38 c-0.85,0.38,-1.79,0.56,-2.63,0.75c-0.85,0.19,-1.69,0.28,-2.45,0.28c-0.47,0,-0.85,0.09,-1.22,0.09c-0.28,0,-0.56,-0.09,-0.85,0 s0.09,0.47,0.28,0.56c0.38,0.19,0.75,0.47,1.13,0.66c1.13,0.56,2.26,1.03,3.39,1.32c1.5,0.38,3.1,0.56,4.61,0.38 c1.32,-0.19,2.63,-0.56,3.86,-1.03c6.77,-3.1,6.21,-9.59,12.42,-10.16c4.61,-0.38,11.1,2.07,11.1,2.07L68.71,94.99z"/>
<!-- Red beak left -->
<path
android:fillColor="#F45125"
android:pathData="M19.79,38.28c0,0,-12.13,1.98,-15.24,12.79C0.61,64.9,20.26,69.5,20.26,69.5l1.22,-9.41 c0,0,-13.07,-1.32,-12.32,-6.3c0.94,-6.21,11.85,-5.64,11.85,-5.64L19.79,38.28z"/>
<!-- Red wing detail -->
<path
android:fillColor="#F45125"
android:pathData="M20.73,70.92c0,0,-1.88,0.56,-4.61,2.54c-1.88,1.32,-4.42,3.01,-6.87,5.93 c-1.22,1.41,-2.16,3.1,-2.82,4.89c-0.47,1.22,-0.66,2.45,-0.66,3.76c0,0.28,0,0.56,0,0.85c0,0.09,0,0.85,0.28,0.66 c0.09,-0.09,0.19,-0.38,0.28,-0.47c0.19,-0.47,0.47,-0.85,0.75,-1.22c0.85,-1.13,1.88,-2.16,3.01,-3.01c0.38,-0.28,0.75,-0.47,1.13,-0.66 c0.28,-0.28,0.75,-0.66,0.94,-0.28c0.09,0.19,-0.09,0.47,-0.19,0.66c-0.09,0.28,-0.19,0.66,-0.19,0.94c-0.38,1.5,-0.56,3.01,-0.75,4.51 c-0.09,0.85,-0.09,1.69,0,2.45c0,0.38,0.09,0.85,0.09,1.22c0,0.19,0.09,0.38,0.09,0.56c0,0.19,0.19,0.47,0.38,0.19 c0.09,-0.09,0.09,-0.19,0.19,-0.38c0.19,-0.28,0.28,-0.66,0.47,-0.94c0.47,-0.85,0.94,-1.69,1.5,-2.63c0.66,-1.13,1.41,-2.16,2.16,-3.1 c0.85,-1.13,1.88,-2.26,2.92,-3.2c1.13,-1.03,2.35,-2.07,3.67,-2.92c0.75,-0.47,1.6,-0.94,2.45,-1.32L20.73,70.92z"/>
<!-- Yellow body -->
<path
android:fillColor="#FCC21B"
android:pathData="M116.4,79.29c-1.13,-5.55,-2.73,-11.01,-4.51,-16.46c-1.5,-4.61,-3.1,-9.31,-5.83,-13.36 c-1.22,-1.79,-3.01,-3.01,-5.27,-3.86c-4.33,-1.69,-9.97,-1.98,-13.73,-1.98c-5.64,0,-11.48,1.22,-16.74,3.67 c-1.88,5.64,-7.05,19.94,-14.86,26.34c0.47,2.63,1.03,5.36,1.79,8c1.32,4.61,3.01,9.22,4.61,13.83c1.5,4.42,3.29,8.84,6.58,12.23 c0.85,0.94,1.88,1.69,2.82,2.45c2.26,1.88,4.99,3.01,7.71,3.95c2.54,0.85,5.17,1.5,7.81,2.07c4.7,1.03,11.48,2.82,16.08,0.66 c2.54,-1.13,4.61,-2.92,6.3,-5.08c1.79,-2.26,3.2,-4.8,4.42,-7.43c1.88,-3.95,3.86,-8.37,4.14,-12.89 C117.99,87.38,117.24,83.24,116.4,79.29z"/>
<!-- Blue head -->
<path
android:fillColor="#429ADF"
android:pathData="M77.64,33.57c-0.28,-1.03,-1.03,-2.07,-1.6,-3.01c-6.3,-11.01,-20.04,-16.27,-32.26,-15.52 c-3.76,0.28,-9.31,0.85,-13.54,2.73c-2.07,0.94,-3.86,2.35,-4.99,4.14c-2.54,4.23,-3.76,8.94,-5.08,13.64 C18.67,41,17.35,46.55,16.5,52.2c-0.75,4.89,-1.41,10.25,-0.09,15.14c1.03,3.86,3.29,9.22,5.74,12.32 c2.73,3.39,6.58,7.34,10.72,8.84c0.75,0.28,1.6,0.47,2.45,0.66c1.6,0.28,3.29,0.47,4.89,0.19c0.94,-0.19,1.98,-0.28,2.92,-0.56 c1.88,-0.47,3.67,-1.13,5.46,-1.79c7.52,-3.01,13.64,-7.43,17.68,-14.58c1.69,-3.1,3.1,-6.4,4.42,-9.69c0.09,-0.19,0.19,-0.38,0.19,-0.56 c1.98,-5.46,3.29,-11.19,4.61,-16.84c0.66,-2.73,1.41,-5.55,1.79,-8.37C77.55,35.92,77.92,34.7,77.64,33.57z"/>
<!-- Dark eye band -->
<path
android:fillColor="#193D51"
android:pathData="M23.09,40.53c1.69,-3.1,5.74,-5.55,9.31,-5.08c0.56,0.09,1.22,0.19,1.79,0.47 c3.57,1.5,5.74,4.99,4.89,8.56c-0.19,0.75,-0.66,0.85,-1.22,0.38c-1.98,-1.69,-3.57,-3.01,-6.21,-3.67c-2.16,-0.56,-4.61,-0.28,-6.68,0.28 c-0.47,0.09,-1.22,0.56,-1.69,0.38C22.61,41.57,22.9,40.91,23.09,40.53z"/>
<!-- Dark mouth/chin -->
<path
android:fillColor="#193D51"
android:pathData="M62.21,64.9c-1.03,1.6,-2.45,3.01,-3.86,4.33c-0.38,0.28,-0.66,0.66,-1.03,0.94 c-5.64,4.7,-13.26,7.05,-20.51,5.27c-1.98,-0.47,-4.14,-1.5,-5.74,-2.73c-1.22,-0.94,-2.45,-2.16,-3.48,-3.39c-1.88,-2.26,-3.29,-4.89,-4.23,-7.62 c-0.47,-1.41,-0.75,-2.73,-0.94,-4.23c0,-0.47,-0.66,-5.46,0.85,-4.8c0.38,0.19,0.66,0.47,0.94,0.75c0.28,0.38,0.47,0.75,0.75,1.03 c0.66,0.85,1.32,1.69,2.07,2.45c2.35,2.73,5.27,4.89,8.56,6.4c2.26,1.03,4.7,1.6,7.15,1.79c1.41,0.09,2.73,0.19,4.14,0.09 c5.08,-0.28,10.25,-1.79,14.86,-3.76c0.38,-0.19,0.85,-0.47,1.32,-0.47C64.66,61.04,62.5,64.52,62.21,64.9z"/>
<!-- Dark eye detail -->
<path
android:fillColor="#193D51"
android:pathData="M67.58,51.16c0,0.47,-0.19,1.13,-0.75,1.03c-0.47,-0.09,-0.85,-0.94,-1.13,-1.22 c-1.32,-1.69,-3.86,-3.57,-6.4,-4.14c-3.01,-0.75,-5.27,0.56,-8.28,0.85c-0.85,0.09,-1.32,-0.28,-0.94,-1.03c1.6,-3.48,5.83,-6.21,10.25,-5.46 c0.75,0.09,1.41,0.28,2.07,0.56C66.26,43.36,67.86,47.59,67.58,51.16z"/>
<!-- Gold eye detail -->
<path
android:fillColor="#9B7515"
android:pathData="M91.84,63.86c4.23,2.73,9.69,3.48,14.58,3.2c1.41,-0.09,2.26,0.09,1.88,1.69 c-0.75,3.29,-3.86,5.17,-6.87,5.83c-0.75,0.19,-1.5,0.19,-2.26,0.19c-1.41,-0.09,-2.82,-0.66,-4.04,-1.5c-2.63,-1.79,-4.61,-4.89,-5.17,-8 C89.68,63.67,90.25,62.83,91.84,63.86z"/>
<!-- Gold mouth detail -->
<path
android:fillColor="#9B7515"
android:pathData="M65.22,80.79C64,79.57,64.66,79,65.98,78.25c4.51,-2.35,9.03,-5.93,11.38,-10.63 c0.85,-1.79,1.79,-1.41,2.45,0.28c1.13,3.1,1.03,6.87,-0.38,9.88c-0.66,1.41,-1.6,2.63,-2.82,3.57c-0.66,0.47,-1.32,0.75,-2.07,1.03 C71.43,83.33,67.58,83.24,65.22,80.79z"/>
<!-- Gold chin/jaw detail -->
<path
android:fillColor="#9B7515"
android:pathData="M110,96.41c-0.38,0,-0.94,-0.38,-1.41,-0.66c-0.47,-0.28,-0.94,-0.66,-1.22,-0.85 c-1.13,-0.56,-2.45,-1.13,-3.67,-1.5c-3.76,-1.22,-7.9,-1.22,-11.57,0c-2.63,0.85,-5.17,2.45,-7.24,4.33c-2.26,2.16,-3.95,4.8,-6.11,7.05 c-0.28,0.28,-0.56,0.56,-0.85,0.75c-0.56,0.28,-1.13,-0.09,-1.32,-0.66c-0.94,-3.95,1.69,-9.5,3.67,-12.89c2.26,-3.76,5.55,-6.77,9.78,-8 c2.07,-0.66,4.33,-0.66,6.49,-0.38c6.3,0.94,12.79,5.93,14.02,11.66C110.56,95.75,110.47,96.5,110,96.41z"/>
</group>
</vector>
@@ -1,12 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#2b0037</color>
</resources>
@@ -1,7 +0,0 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">Shakespeare</string>
<string name="title_activity_main">Shakespeare</string>
<string name="package_name">diy.shakespeare.app</string>
<string name="custom_url_scheme">diy.shakespeare.app</string>
</resources>
@@ -1,23 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
</style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="windowSplashScreenBackground">#2b0037</item>
<item name="windowSplashScreenAnimatedIcon">@drawable/splash_icon_vector</item>
<item name="postSplashScreenTheme">@style/AppTheme.NoActionBar</item>
</style>
</resources>
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." />
<cache-path name="my_cache_images" path="." />
</paths>
@@ -1,18 +0,0 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
-29
View File
@@ -1,29 +0,0 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.13.0'
classpath 'com.google.gms:google-services:4.4.4'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply from: "variables.gradle"
allprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
-9
View File
@@ -1,9 +0,0 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
include ':capacitor-app'
project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android')
include ':capacitor-status-bar'
project(':capacitor-status-bar').projectDir = new File('../node_modules/@capacitor/status-bar/android')
-22
View File
@@ -1,22 +0,0 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
Binary file not shown.
-7
View File
@@ -1,7 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-251
View File
@@ -1,251 +0,0 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
-94
View File
@@ -1,94 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
-5
View File
@@ -1,5 +0,0 @@
include ':app'
include ':capacitor-cordova-android-plugins'
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
apply from: 'capacitor.settings.gradle'
-16
View File
@@ -1,16 +0,0 @@
ext {
minSdkVersion = 24
compileSdkVersion = 36
targetSdkVersion = 36
androidxActivityVersion = '1.11.0'
androidxAppCompatVersion = '1.7.1'
androidxCoordinatorLayoutVersion = '1.3.0'
androidxCoreVersion = '1.17.0'
androidxFragmentVersion = '1.8.9'
coreSplashScreenVersion = '1.2.0'
androidxWebkitVersion = '1.14.0'
junitVersion = '4.13.2'
androidxJunitVersion = '1.3.0'
androidxEspressoCoreVersion = '3.7.0'
cordovaAndroidVersion = '14.0.1'
}
-25
View File
@@ -1,25 +0,0 @@
import type { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'diy.shakespeare.app',
appName: 'Shakespeare',
webDir: 'dist',
server: {
// Handle deep links from your domain
hostname: 'shakespeare.diy',
androidScheme: 'https',
iosScheme: 'https'
},
android: {
// Enable safe area handling for notches and navigation bars
allowMixedContent: false,
backgroundColor: '#2b0037'
},
ios: {
backgroundColor: '#2b0037',
contentInset: 'automatic',
scheme: 'Shakespeare'
}
};
export default config;
+1 -1
View File
@@ -284,7 +284,7 @@ export function useNewProviderOAuth() {
redirectUri: window.location.origin + '/oauth/newprovider',
usePKCE: false, // Set to true if provider supports PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.provider.com/user' });
const userUrl = proxyUrl(corsProxy, 'https://api.provider.com/user');
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
+1 -1
View File
@@ -8,7 +8,7 @@ import htmlParser from "@html-eslint/parser";
import customRules from "./eslint-rules/index.js";
export default tseslint.config(
{ ignores: ["dist", "android"] },
{ ignores: ["dist", "electron/dist"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
+812 -2151
View File
File diff suppressed because it is too large. Load diff
+8 -18
View File
@@ -3,7 +3,7 @@
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
"homepage": "https://shakespeare.diy",
"license": "AGPL-3.0-or-later",
"version": "9.11.4",
"version": "0.0.0",
"type": "module",
"author": {
"name": "shakespeare.diy",
@@ -17,27 +17,20 @@
"dev": "npm i --silent && vite",
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"typecheck": "npm i --silent && tsc --noEmit",
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'",
"keygen": "keytool -genkey -v -keystore android/app/my-upload-key.keystore -keyalg RSA -keysize 2048 -validity 10000 -alias upload",
"icons": "bash scripts/generate-icons.sh"
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'"
},
"dependencies": {
"@capacitor/app": "^8.1.0",
"@capacitor/core": "^8.3.0",
"@capacitor/status-bar": "^8.0.2",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^6.0.1",
"@hookform/resolvers": "^5.2.2",
"@hookform/resolvers": "^3.9.0",
"@isomorphic-git/lightning-fs": "^4.6.2",
"@modelcontextprotocol/sdk": "^1.22.0",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.51.1",
"@nostrify/react": "^0.4.1",
"@opensecret/react": "^1.5.4",
"@plausible-analytics/tracker": "^0.4.4",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -88,7 +81,7 @@
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"nunjucks": "^3.2.4",
"openai": "^6.16.0",
"openai": "^5.15.0",
"path-browserify": "^1.0.1",
"prismjs": "^1.30.0",
"qrcode": "^1.5.4",
@@ -96,7 +89,7 @@
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-error-boundary": "^6.0.0",
"react-hook-form": "^7.71.1",
"react-hook-form": "^7.53.0",
"react-i18next": "^15.7.3",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^3.0.3",
@@ -113,11 +106,9 @@
"vaul": "^0.9.3",
"webln": "^0.3.2",
"workbox-window": "^7.3.0",
"zod": "^4.3.6"
"zod": "^3.25.76"
},
"devDependencies": {
"@capacitor/android": "^8.3.0",
"@capacitor/cli": "^8.3.0",
"@eslint/js": "^9.9.0",
"@html-eslint/eslint-plugin": "^0.41.0",
"@html-eslint/parser": "^0.41.0",
@@ -125,7 +116,6 @@
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^14.6.1",
"@types/jsdom": "^27.0.0",
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/nunjucks": "^3.2.6",
-98
View File
@@ -1,98 +0,0 @@
# Changelog
## [9.11.4] - 2026-04-17
### Fixed
- Preview pane no longer gets stuck on stale builds during rapid edits
### Changed
- Reduce AI costs for Anthropic models via OpenRouter by caching tool definitions across turns
## [9.11.3] - 2026-04-12
### Fixed
- App publish dialog now appears on mobile devices
- Changelog available offline via ServiceWorker precache
## [9.11.2] - 2026-04-06
### Fixed
- Derive private preview subdomains with HMAC to prevent cross-project origin collisions on iframe.diy
## [9.11.1] - 2026-04-05
### Changed
- Switch preview pane to iframe.diy for improved reliability and compatibility
- New users start with OpenCode Zen pre-configured for a zero-setup first experience
- Default nsite gateway changed to shakespeare.to with vanity subdomain support
- Update default Blossom servers and relay lists across deployments and uploads
### Fixed
- Default settings no longer override existing users' recently used models
- Showcase card clone URLs now use proper Nostr URI encoding
- Service worker no longer blocks SvelteKit nsite routes
## [9.11.0] - 2026-04-03
### Added
- Upload a banner image for your app directly from the App dialog
- T-tag editor in the App dialog Advanced section for tagging your app by category
- Delete App button in the App dialog Advanced section when editing an existing app
- Ngit repo and nsite deployment address fields in the App dialog Advanced section
- Auto-fill app name, description, and images from your project's OG tags and web manifest on first publish
### Changed
- Redesigned App dialog with an overlapping banner and avatar card layout
- Reorganized App dialog Advanced section into General, Handlers, and Tags tabs
- Showcase cards now show banner and icon images, and require both to appear in the showcase
- Validation summary above the Save button replaces per-field "Required" labels
- Updated showcase curator to the Shakespeare Builders community list
### Fixed
- Upgrade Nostrify to fix bunker connection issues
## [9.10.4] - 2026-04-02
### Fixed
- Fix Android splash screen showing logo masked to white silhouette instead of full color
## [9.10.3] - 2026-04-02
### Fixed
- Fix Android app showing default Capacitor splash screen and icon colors
## [9.10.2] - 2026-04-02
### Fixed
- Fix Android app showing default Capacitor icon instead of Shakespeare logo in app drawer
## [9.10.1] - 2026-04-02
### Fixed
- Replace default Capacitor vector drawable icons with Shakespeare logo
## [9.10.0] - 2026-04-02
### Added
- Android app powered by Capacitor with deep links, splash screen, and signed release builds
- CI pipeline for building APKs, publishing to GitLab releases, and distributing via Zapstore
- Nsite deployment for decentralized hosting via Nostr
### Changed
- Make version number on mobile settings a clickable link to the changelog with build date
## [9.9.2] - 2026-04-02
### Changed
- Simplify nsite deployment to always use named sites, removing the root site option
### Fixed
- Fix crash in "What's new" toast when used outside the router context
- Truncate long changelog excerpts in update notifications so they fit neatly in the toast
- Left-align changelog page content for better readability
## [9.9.1] - 2026-04-02
### Added
- Changelog page and versioning system with "What's new" toast notifications on updates
- Release skill for managing versioned releases with changelog generation and git tagging
-197
View File
@@ -1,197 +0,0 @@
#!/bin/bash
set -e
# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo -e "${GREEN}Generating app icons...${NC}\n"
# Check for inkscape (preferred) or rsvg-convert as fallback
if command -v inkscape &> /dev/null; then
SVG_RENDERER="inkscape"
elif command -v rsvg-convert &> /dev/null; then
SVG_RENDERER="rsvg"
else
echo -e "${YELLOW}Warning: neither inkscape nor rsvg-convert found. Install one to render SVG icons.${NC}"
echo "On Fedora/RHEL: sudo dnf install inkscape"
echo "On Ubuntu/Debian: sudo apt-get install inkscape"
exit 1
fi
# Check if ImageMagick is installed (needed for compositing).
# ImageMagick 7+ uses `magick`; ImageMagick 6 (Ubuntu/Debian) uses `convert`.
if command -v magick &> /dev/null; then
MAGICK="magick"
elif command -v convert &> /dev/null; then
MAGICK="convert"
else
echo -e "${YELLOW}Warning: ImageMagick not found. Please install it to generate icons.${NC}"
echo "On Fedora/RHEL: sudo dnf install ImageMagick"
echo "On Ubuntu/Debian: sudo apt-get install imagemagick"
exit 1
fi
# Source SVG logo
SOURCE_SVG="public/shakespeare.svg"
if [ ! -f "$SOURCE_SVG" ]; then
echo -e "${YELLOW}Error: Source logo not found at $SOURCE_SVG${NC}"
exit 1
fi
# Brand colors
BG_COLOR="#2b0037" # Shakespeare purple
TMPDIR=$(mktemp -d)
LOGO_COLOR="$TMPDIR/logo_color.png"
# Render the original colorful SVG at high resolution for downscaling.
echo "Rendering colorful SVG at 512x512..."
if [ "$SVG_RENDERER" = "inkscape" ]; then
inkscape --export-type=png --export-filename="$LOGO_COLOR" -w 512 -h 512 "$SOURCE_SVG" 2>/dev/null
else
rsvg-convert -w 512 -h 512 "$SOURCE_SVG" -o "$LOGO_COLOR"
fi
# ── Adaptive icon foreground PNGs (transparent bg, colorful logo, safe-zone padding) ──
# Content at 47% of canvas to fit within Android's adaptive icon safe zone.
echo "Generating adaptive foreground PNGs..."
make_foreground() {
local size=$1
local content_size=$(echo "$size * 47 / 100" | bc)
local dest=$2
$MAGICK -size "${size}x${size}" "xc:none" \
\( "$LOGO_COLOR" -resize "${content_size}x${content_size}" \) \
-gravity center -compose over -composite \
"$dest"
}
make_foreground 48 android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png
make_foreground 72 android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png
make_foreground 96 android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png
make_foreground 144 android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png
make_foreground 192 android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png
# ── Legacy launcher icons (ic_launcher.png and ic_launcher_round.png) ──
# These are used on pre-API-26 devices and as fallback on some launchers.
# They must have the logo composited onto the purple background.
echo "Generating legacy launcher icons (ic_launcher.png and ic_launcher_round.png)..."
# make_legacy_square: logo on flat purple square background
make_legacy_square() {
local size=$1
local content_size=$(echo "$size * 60 / 100" | bc)
local dest=$2
$MAGICK -size "${size}x${size}" "xc:${BG_COLOR}" \
\( "$LOGO_COLOR" -resize "${content_size}x${content_size}" \) \
-gravity center -compose over -composite \
"$dest"
}
# make_legacy_round: logo on circular purple background (alpha-masked circle)
make_legacy_round() {
local size=$1
local content_size=$(echo "$size * 60 / 100" | bc)
local dest=$2
local mask="$TMPDIR/circle_mask_${size}.png"
# Create a white circle mask
$MAGICK -size "${size}x${size}" "xc:none" \
-fill white -draw "circle $((size/2)),$((size/2)) $((size/2)),0" \
"$mask"
# Fill purple, apply circle mask, composite logo
$MAGICK -size "${size}x${size}" "xc:${BG_COLOR}" \
"$mask" -compose dst-in -composite \
\( "$LOGO_COLOR" -resize "${content_size}x${content_size}" \) \
-gravity center -compose over -composite \
"$dest"
}
make_legacy_square 48 android/app/src/main/res/mipmap-mdpi/ic_launcher.png
make_legacy_square 72 android/app/src/main/res/mipmap-hdpi/ic_launcher.png
make_legacy_square 96 android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
make_legacy_square 144 android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
make_legacy_square 192 android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
make_legacy_round 48 android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
make_legacy_round 72 android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
make_legacy_round 96 android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
make_legacy_round 144 android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
make_legacy_round 192 android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
# Update background color
BACKGROUND_COLOR_FILE="android/app/src/main/res/values/ic_launcher_background.xml"
mkdir -p android/app/src/main/res/values
cat > "$BACKGROUND_COLOR_FILE" << 'EOF'
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#2b0037</color>
</resources>
EOF
# ── Splash screen PNGs (logo centered on purple background) ──
# These are the legacy splash screens used by the Capacitor splash screen plugin.
# Logo is sized to ~25% of the shorter dimension, centered on solid purple.
echo "Generating splash screen PNGs..."
make_splash() {
local w=$1
local h=$2
local dest=$3
local shorter=$(( w < h ? w : h ))
local logo_size=$(echo "$shorter * 25 / 100" | bc)
$MAGICK -size "${w}x${h}" "xc:${BG_COLOR}" \
\( "$LOGO_COLOR" -resize "${logo_size}x${logo_size}" \) \
-gravity center -compose over -composite \
"$dest"
}
make_splash 480 320 android/app/src/main/res/drawable/splash.png
make_splash 320 480 android/app/src/main/res/drawable-port-mdpi/splash.png
make_splash 480 800 android/app/src/main/res/drawable-port-hdpi/splash.png
make_splash 720 1280 android/app/src/main/res/drawable-port-xhdpi/splash.png
make_splash 960 1600 android/app/src/main/res/drawable-port-xxhdpi/splash.png
make_splash 1280 1920 android/app/src/main/res/drawable-port-xxxhdpi/splash.png
make_splash 480 320 android/app/src/main/res/drawable-land-mdpi/splash.png
make_splash 800 480 android/app/src/main/res/drawable-land-hdpi/splash.png
make_splash 1280 720 android/app/src/main/res/drawable-land-xhdpi/splash.png
make_splash 1600 960 android/app/src/main/res/drawable-land-xxhdpi/splash.png
make_splash 1920 1280 android/app/src/main/res/drawable-land-xxxhdpi/splash.png
# ── iOS App Icon (1024x1024, colorful logo on purple background) ──
echo "Generating iOS app icon..."
IOS_ICON_DIR="ios/App/App/Assets.xcassets/AppIcon.appiconset"
if [ -d "$IOS_ICON_DIR" ]; then
IOS_ICON="$IOS_ICON_DIR/[email protected]"
# Logo at ~60% of canvas, centered on purple background
$MAGICK -size "1024x1024" "xc:${BG_COLOR}" \
\( "$LOGO_COLOR" -resize "614x614" \) \
-gravity center -compose over -composite \
"$IOS_ICON"
echo -e " ${GREEN}✓${NC} $IOS_ICON"
else
echo -e " ${YELLOW}Skipped: $IOS_ICON_DIR not found${NC}"
fi
# Cleanup temp files
rm -rf "$TMPDIR"
echo -e "\n${GREEN}App icons generated successfully!${NC}"
echo -e "Icon: colorful Shakespeare logo on ${GREEN}${BG_COLOR}${NC} (Shakespeare purple)"
echo -e "Generated:"
echo -e " Android:"
echo -e " - ic_launcher_foreground.png (adaptive, all densities)"
echo -e " - ic_launcher.png (legacy square, all densities)"
echo -e " - ic_launcher_round.png (legacy round, all densities)"
echo -e " - splash.png (portrait + landscape, all densities)"
echo -e " iOS:"
echo -e " - [email protected] (1024x1024)"
-5
View File
@@ -48,11 +48,6 @@ export default {
hostname = 'docs.z.ai';
}
// Deployment-provider-specific hacks
if (url.host === 'backboard.railway.com') {
hostname = 'railway.com';
}
// Fetch the favicon from DuckDuckGo's service
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
},
+11 -3
View File
@@ -138,10 +138,18 @@ self.addEventListener("fetch", (event) => {
return;
}
// Let iframe client system files and common assets be handled normally
// Let iframe client system files be handled normally
if (url.pathname.startsWith("/_") || url.pathname === "/sw.js") {
return;
}
// Let root path be handled normally (loads the iframe client page)
if (url.pathname === "/") {
return;
}
// Let iframe client assets be handled normally (anything in _iframe-client directory and common assets)
if (url.pathname.startsWith("/_iframe-client/") ||
url.pathname === "/sw.js" ||
url.pathname === "/" ||
url.pathname === "/favicon.ico" ||
url.pathname === "/manifest.webmanifest") {
return;
+11
View File
@@ -0,0 +1,11 @@
import { render } from '@testing-library/react';
import { test, expect } from 'vitest';
import App from './App';
test('App', () => {
const { container } = render(<App />);
// Basic smoke test to ensure App renders without crashing
expect(container).toBeInTheDocument();
})
+42 -40
View File
@@ -8,13 +8,13 @@ import { Suspense, useEffect } from 'react';
import LightningFS from '@isomorphic-git/lightning-fs';
import NostrProvider from '@/components/NostrProvider';
import { NostrSync } from '@/components/NostrSync';
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
import { useAppContext } from '@/hooks/useAppContext';
import { SentryProvider } from '@/components/SentryProvider';
import { PlausibleProvider } from '@/components/PlausibleProvider';
import { AISettingsProvider } from '@/components/AISettingsProvider';
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
import { DeploySettingsProvider } from '@/components/DeploySettingsProvider';
@@ -28,8 +28,7 @@ import { DynamicFavicon } from '@/components/DynamicFavicon';
import { OfflineIndicator } from '@/components/OfflineIndicator';
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { LockdownModeDetector } from '@/components/LockdownModeDetector';
import { NWCProvider } from '@/contexts/NWCContext';
import AppRouter from './AppRouter';
@@ -54,7 +53,7 @@ const defaultConfig: AppConfig = {
relayMetadata: {
relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.damus.io', read: true, write: true },
{ url: 'wss://relay.nostr.band', read: true, write: true },
{ url: 'wss://relay.primal.net', read: true, write: true },
],
updatedAt: 0,
@@ -72,6 +71,11 @@ const defaultConfig: AppConfig = {
description: "Build Nostr clients with React. This is the default template that you should choose in the majority of cases. It ships with complete Nostr integration out of the box, enabling a variety of use-cases from social media to blogging to AI-powered apps. If you're not sure which template to choose, choose this one.",
url: "https://gitlab.com/soapbox-pub/mkstack.git",
},
{
name: "Nutstack",
description: "This is a variant of MKStack extended to support Cashu integration. Choose this template only if the user has indicated they require Cashu integration.",
url: "https://gitlab.com/lemonknowsall/nutstack.git",
},
],
esmUrl: "https://esm.sh",
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
@@ -80,7 +84,7 @@ const defaultConfig: AppConfig = {
ngitWebUrl: "https://nostrhub.io/{naddr}",
previewDomain: "local-shakespeare.dev",
showcaseEnabled: true,
showcaseCurator: "naddr1qvzqqqr4xqpzq7q6z5ns2hm5c8msyv83qwzxpxe52j8c4d4q5m92wsp9sflelkh9qqjrvdrxxajnqvny95mkyc33956xvwfk94sn2vek94sn2et9ve3kycfexfnryvty32j",
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
fsPathProjects: "/projects",
fsPathConfig: "/config",
fsPathTmp: "/tmp",
@@ -88,8 +92,6 @@ const defaultConfig: AppConfig = {
fsPathTemplates: "/templates",
sentryDsn: import.meta.env.VITE_SENTRY_DSN || "",
sentryEnabled: true,
plausibleDomain: import.meta.env.VITE_PLAUSIBLE_DOMAIN || "",
plausibleEndpoint: import.meta.env.VITE_PLAUSIBLE_ENDPOINT || "",
};
// Initialize filesystem adapter
@@ -134,39 +136,39 @@ export function App() {
<UnheadProvider head={head}>
<QueryClientProvider client={queryClient}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<PlausibleProvider>
<SentryProvider>
<FSProvider fs={fs}>
<ConsoleErrorProvider>
<FSCleanupHandler />
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NostrSync />
<AISettingsProvider>
<GitSettingsProvider>
<DeploySettingsProvider>
<GitSyncProvider>
<SessionManagerProvider>
<TooltipProvider>
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<LockdownModeDetector />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
</GitSyncProvider>
</DeploySettingsProvider>
</GitSettingsProvider>
</AISettingsProvider>
</NostrProvider>
</NostrLoginProvider>
</ConsoleErrorProvider>
</FSProvider>
</SentryProvider>
</PlausibleProvider>
<SentryProvider>
<FSProvider fs={fs}>
<ConsoleErrorProvider>
<FSCleanupHandler />
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NostrSync />
<NWCProvider>
<AISettingsProvider>
<GitSettingsProvider>
<DeploySettingsProvider>
<GitSyncProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
</GitSyncProvider>
</DeploySettingsProvider>
</GitSettingsProvider>
</AISettingsProvider>
</NWCProvider>
</NostrProvider>
</NostrLoginProvider>
</ConsoleErrorProvider>
</FSProvider>
</SentryProvider>
</AppProvider>
</QueryClientProvider>
</UnheadProvider>
+10 -9
View File
@@ -1,18 +1,18 @@
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { Toaster } from "./components/ui/toaster";
import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import { SessionMonitor } from "./components/SessionMonitor";
import { URLFragmentHandler } from "./components/URLFragmentHandler";
import { VersionCheck } from "./components/VersionCheck";
import Index from "./pages/Index";
import Clone from "./pages/Clone";
import Explore from "./pages/Explore";
import Settings from "./pages/Settings";
import Preferences from "./pages/Preferences";
import NostrSettings from "./pages/NostrSettings";
import AISettings from "./pages/AISettings";
import GitSettings from "./pages/GitSettings";
import DeploySettings from "./pages/DeploySettings";
import WalletSettings from "./pages/WalletSettings";
import SystemSettings from "./pages/SystemSettings";
import StorageSettings from "./pages/StorageSettings";
import AboutSettings from "./pages/AboutSettings";
@@ -25,13 +25,13 @@ import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { ProjectView } from "./pages/ProjectView";
import { SettingsLayout } from "./components/SettingsLayout";
import { ChangelogPage } from "./pages/ChangelogPage";
export function AppRouter() {
// Use HashRouter in Electron, BrowserRouter in web
const Router = globalThis.electron ? HashRouter : BrowserRouter;
return (
<BrowserRouter>
<Toaster />
<VersionCheck />
<Router>
<ScrollToTop />
<SessionMonitor />
<URLFragmentHandler />
@@ -39,6 +39,7 @@ export function AppRouter() {
<Route path="/" element={<Index />} />
<Route path="/giftcard" element={<Index />} />
<Route path="/clone" element={<Clone />} />
<Route path="/explore" element={<Explore />} />
<Route path="/oauth/github" element={<GitHubOAuth />} />
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
<Route path="/oauth/vercel" element={<VercelOAuth />} />
@@ -50,18 +51,18 @@ export function AppRouter() {
<Route path="ai" element={<AISettings />} />
<Route path="git" element={<GitSettings />} />
<Route path="deploy" element={<DeploySettings />} />
<Route path="wallet" element={<WalletSettings />} />
<Route path="system" element={<SystemSettings />} />
<Route path="storage" element={<StorageSettings />} />
<Route path="about" element={<AboutSettings />} />
</Route>
<Route path="/changelog" element={<ChangelogPage />} />
<Route path="/project/:projectId" element={<ProjectView />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
</Router>
);
}
export default AppRouter;
-3
View File
@@ -19,14 +19,12 @@ interface AIMessageItemProps {
message: AIMessage;
isCurrentlyLoading?: boolean;
toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message
projectId: string; // Current project ID for path display
}
export const AIMessageItem = memo(({
message,
isCurrentlyLoading = false,
toolCall,
projectId,
}: AIMessageItemProps) => {
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
@@ -73,7 +71,6 @@ export const AIMessageItem = memo(({
toolArgs={toolArgs}
state="completed"
result={content}
projectId={projectId}
/>
);
}
+7 -41
View File
@@ -1041,31 +1041,12 @@ export function AIProviderConfigDialog({
<div className="grid gap-2">
<Label htmlFor="provider-auth">{t('authentication')}</Label>
<Select
value={localProvider.nostr ? 'nostr' : localProvider.openSecret ? 'opensecret' : 'api-key'}
onValueChange={(value: 'api-key' | 'nostr' | 'opensecret') => {
if (value === 'nostr') {
setLocalProvider({
...localProvider,
nostr: true,
openSecret: undefined,
apiKey: undefined
});
} else if (value === 'opensecret') {
setLocalProvider({
...localProvider,
nostr: undefined,
openSecret: localProvider.openSecret,
apiKey: localProvider.apiKey
});
} else {
setLocalProvider({
...localProvider,
nostr: undefined,
openSecret: undefined,
apiKey: localProvider.apiKey
});
}
}}
value={localProvider.nostr ? 'nostr' : 'api-key'}
onValueChange={(value: 'api-key' | 'nostr') => setLocalProvider({
...localProvider,
nostr: value === 'nostr' || undefined,
apiKey: value === 'nostr' ? undefined : localProvider.apiKey
})}
>
<SelectTrigger>
<SelectValue />
@@ -1073,25 +1054,10 @@ export function AIProviderConfigDialog({
<SelectContent>
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
<SelectItem value="nostr">Nostr</SelectItem>
<SelectItem value="opensecret">OpenSecret</SelectItem>
</SelectContent>
</Select>
</div>
{localProvider.openSecret && (
<div className="grid gap-2">
<Label htmlFor="provider-opensecret-url">
OpenSecret API URL <span className="text-destructive">*</span>
</Label>
<Input
id="provider-opensecret-url"
placeholder="https://enclave.trymaple.ai"
value={localProvider.openSecret || ''}
onChange={(e) => setLocalProvider({ ...localProvider, openSecret: e.target.value })}
/>
</div>
)}
{!localProvider.nostr && (
<div className="grid gap-2">
<Label htmlFor="provider-apiKey">{t('apiKey')}</Label>
@@ -1173,7 +1139,7 @@ export function AIProviderConfigDialog({
<div className="space-y-3">
<Label className="text-sm font-medium">{t('paymentMethod')}</Label>
<Tabs value={paymentMethod} onValueChange={(value) => setPaymentMethod(value as 'stripe' | 'lightning')} className="w-full">
<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">
<CreditCard className="h-4 w-4" />
+2 -33
View File
@@ -36,27 +36,17 @@ describe('AISettingsProvider', () => {
});
});
it('should initialize with OpenCode defaults for new users (no providers)', async () => {
it('should initialize with empty recentlyUsedModels array', async () => {
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
await waitFor(() => {
// New users with no providers get OPENCODE_DEFAULT_SETTINGS with big-pickle
expect(result.current.settings.providers).toHaveLength(1);
expect(result.current.settings.providers[0].id).toBe('opencode');
expect(result.current.settings.recentlyUsedModels).toEqual(['opencode/big-pickle']);
expect(result.current.settings.recentlyUsedModels).toEqual([]);
});
});
it('should add recently used models correctly', async () => {
// Simulate existing user with a provider configured
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue({
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
recentlyUsedModels: [],
});
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
@@ -75,13 +65,6 @@ describe('AISettingsProvider', () => {
});
it('should move existing model to front when used again', async () => {
// Simulate existing user with a provider configured
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue({
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
recentlyUsedModels: [],
});
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
@@ -116,13 +99,6 @@ describe('AISettingsProvider', () => {
});
it('should limit recently used models to 10 items', async () => {
// Simulate existing user with a provider configured
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue({
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
recentlyUsedModels: [],
});
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
@@ -171,13 +147,6 @@ describe('AISettingsProvider', () => {
});
it('should invalidate provider-models query when updateSettings is called with providers', async () => {
// Simulate existing user with a provider configured
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue({
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
recentlyUsedModels: [],
});
// Mock the QueryClient.invalidateQueries method
const mockInvalidateQueries = vi.fn();
+10 -10
View File
@@ -4,33 +4,33 @@ import { AISettingsContext, type AISettings, type AIProvider, type MCPServer, ty
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { readAISettings, writeAISettings } from '@/lib/configUtils';
import { EMPTY_AI_SETTINGS, OPENCODE_DEFAULT_SETTINGS } from '@/lib/opencode-defaults';
interface AISettingsProviderProps {
children: ReactNode;
}
const DEFAULT_SETTINGS: AISettings = {
providers: [],
recentlyUsedModels: [],
mcpServers: {},
};
export function AISettingsProvider({ children }: AISettingsProviderProps) {
const queryClient = useQueryClient();
const { fs } = useFS();
const { configPath } = useFSPaths();
const [settings, setSettings] = useState<AISettings>(EMPTY_AI_SETTINGS);
const [settings, setSettings] = useState<AISettings>(DEFAULT_SETTINGS);
const [isInitialized, setIsInitialized] = useState(false);
// Initialize settings from VFS on mount
useEffect(() => {
const initializeSettings = async () => {
try {
const loaded = await readAISettings(fs, configPath);
// Only apply OpenCode defaults for genuinely new users (no providers configured)
if (loaded.providers.length === 0) {
setSettings(OPENCODE_DEFAULT_SETTINGS);
} else {
setSettings(loaded);
}
const settings = await readAISettings(fs, configPath);
setSettings(settings);
} catch (error) {
console.error('Failed to initialize AI settings:', error);
setSettings(EMPTY_AI_SETTINGS);
setSettings(DEFAULT_SETTINGS);
} finally {
setIsInitialized(true);
}
+3 -26
View File
@@ -50,8 +50,7 @@ export function AddCustomAIProviderDialog({
const [customIdManuallyEdited, setCustomIdManuallyEdited] = useState(false);
const [customBaseURL, setCustomBaseURL] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr' | 'opensecret'>('api-key');
const [customOpenSecretUrl, setCustomOpenSecretUrl] = useState('');
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr'>('api-key');
const [customProxy, setCustomProxy] = useState(false);
const handleAdd = () => {
@@ -67,11 +66,6 @@ export function AddCustomAIProviderDialog({
provider.apiKey = customApiKey.trim();
} else if (customAuthMethod === 'nostr') {
provider.nostr = true;
} else if (customAuthMethod === 'opensecret') {
provider.openSecret = customOpenSecretUrl.trim();
if (customApiKey.trim()) {
provider.apiKey = customApiKey.trim();
}
}
if (customProxy) {
@@ -87,7 +81,6 @@ export function AddCustomAIProviderDialog({
setCustomBaseURL('');
setCustomApiKey('');
setCustomAuthMethod('api-key');
setCustomOpenSecretUrl('');
setCustomProxy(false);
onOpenChange(false);
@@ -96,7 +89,6 @@ export function AddCustomAIProviderDialog({
const isValid = customProviderName.trim() &&
customProviderId.trim() &&
customBaseURL.trim() &&
(customAuthMethod !== 'opensecret' || customOpenSecretUrl.trim()) &&
!existingIds.includes(customProviderId.trim());
const idExists = existingIds.includes(customProviderId.trim());
@@ -164,7 +156,7 @@ export function AddCustomAIProviderDialog({
<Label htmlFor="custom-auth">{t('authentication')}</Label>
<Select
value={customAuthMethod}
onValueChange={(value: 'api-key' | 'nostr' | 'opensecret') => {
onValueChange={(value: 'api-key' | 'nostr') => {
setCustomAuthMethod(value);
if (value === 'nostr') {
setCustomApiKey(''); // Clear API key when switching to Nostr auth
@@ -177,26 +169,11 @@ export function AddCustomAIProviderDialog({
<SelectContent>
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
<SelectItem value="nostr">Nostr</SelectItem>
<SelectItem value="opensecret">OpenSecret</SelectItem>
</SelectContent>
</Select>
</div>
{customAuthMethod === 'opensecret' && (
<div className="grid gap-2">
<Label htmlFor="custom-opensecret-url">
OpenSecret API URL <span className="text-destructive">*</span>
</Label>
<Input
id="custom-opensecret-url"
placeholder="https://enclave.trymaple.ai"
value={customOpenSecretUrl}
onChange={(e) => setCustomOpenSecretUrl(e.target.value)}
/>
</div>
)}
{(customAuthMethod === 'api-key' || customAuthMethod === 'opensecret') && (
{customAuthMethod === 'api-key' && (
<div className="grid gap-2">
<Label htmlFor="custom-apikey">{t('apiKey')}</Label>
<PasswordInput
+39 -48
View File
@@ -1,7 +1,6 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check } from 'lucide-react';
import { UrlListEditor } from '@/components/UrlListEditor';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
@@ -29,7 +28,6 @@ import type {
NsiteProvider,
CloudflareProvider,
DenoDeployProvider,
RailwayProvider,
} from '@/contexts/DeploySettingsContext';
// Type for provider without the 'id' field (will be generated)
@@ -39,8 +37,7 @@ type DeployProviderInput =
| Omit<VercelProvider, 'id'>
| Omit<NsiteProvider, 'id'>
| Omit<CloudflareProvider, 'id'>
| Omit<DenoDeployProvider, 'id'>
| Omit<RailwayProvider, 'id'>;
| Omit<DenoDeployProvider, 'id'>;
interface AddCustomProviderDialogProps {
open: boolean;
@@ -54,7 +51,7 @@ export function AddCustomProviderDialog({
onAdd,
}: AddCustomProviderDialogProps) {
const { t } = useTranslation();
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway' | ''>('');
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | ''>('');
const [customName, setCustomName] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAccountId, setCustomAccountId] = useState('');
@@ -64,8 +61,8 @@ export function AddCustomProviderDialog({
const [customHost, setCustomHost] = useState('');
const [customProxy, setCustomProxy] = useState(false);
const [customGateway, setCustomGateway] = useState('');
const [customRelayUrls, setCustomRelayUrls] = useState<string[]>([]);
const [customBlossomServers, setCustomBlossomServers] = useState<string[]>([]);
const [customRelayUrls, setCustomRelayUrls] = useState('');
const [customBlossomServers, setCustomBlossomServers] = useState('');
const handleAdd = () => {
if (!customProviderType || !customName.trim()) return;
@@ -84,9 +81,13 @@ export function AddCustomProviderDialog({
provider = {
type: 'nsite',
name: customName.trim(),
gateway: customGateway.trim() || 'shakespeare.to',
relayUrls: customRelayUrls.length > 0 ? customRelayUrls : ['wss://relay.ditto.pub'],
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.ditto.pub/', 'https://blossom.dreamith.to/'],
gateway: customGateway.trim() || 'nsite.lol',
relayUrls: customRelayUrls.trim()
? customRelayUrls.split(',').map(s => s.trim()).filter(Boolean)
: ['wss://relay.nostr.band'],
blossomServers: customBlossomServers.trim()
? customBlossomServers.split(',').map(s => s.trim()).filter(Boolean)
: ['https://blossom.primal.net/'],
};
} else if (customProviderType === 'netlify') {
if (!customApiKey.trim()) return;
@@ -128,15 +129,6 @@ export function AddCustomProviderDialog({
...(customBaseDomain?.trim() && { baseDomain: customBaseDomain.trim() }),
...(customProxy && { proxy: true }),
};
} else if (customProviderType === 'railway') {
if (!customApiKey.trim()) return;
provider = {
type: 'railway',
name: customName.trim(),
apiKey: customApiKey.trim(),
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
...(customProxy && { proxy: true }),
};
} else {
return; // Unknown type
}
@@ -154,8 +146,8 @@ export function AddCustomProviderDialog({
setCustomHost('');
setCustomProxy(false);
setCustomGateway('');
setCustomRelayUrls([]);
setCustomBlossomServers([]);
setCustomRelayUrls('');
setCustomBlossomServers('');
onOpenChange(false);
};
@@ -164,8 +156,7 @@ export function AddCustomProviderDialog({
(customProviderType === 'shakespeare' || customProviderType === 'nsite' ||
(customApiKey.trim() &&
(customProviderType !== 'cloudflare' || customAccountId.trim()) &&
(customProviderType !== 'deno' || customOrganizationId.trim()) &&
(customProviderType !== 'railway' || true)));
(customProviderType !== 'deno' || customOrganizationId.trim())));
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -184,7 +175,7 @@ export function AddCustomProviderDialog({
</Label>
<Select
value={customProviderType}
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway') => {
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno') => {
setCustomProviderType(value);
// Reset form when provider type changes
setCustomApiKey('');
@@ -195,8 +186,8 @@ export function AddCustomProviderDialog({
setCustomHost('');
setCustomProxy(false);
setCustomGateway('');
setCustomRelayUrls([]);
setCustomBlossomServers([]);
setCustomRelayUrls('');
setCustomBlossomServers('');
}}
>
<SelectTrigger>
@@ -209,7 +200,6 @@ export function AddCustomProviderDialog({
<SelectItem value="vercel">Vercel</SelectItem>
<SelectItem value="cloudflare">Cloudflare</SelectItem>
<SelectItem value="deno">Deno Deploy</SelectItem>
<SelectItem value="railway">Railway</SelectItem>
</SelectContent>
</Select>
</div>
@@ -246,31 +236,35 @@ export function AddCustomProviderDialog({
) : customProviderType === 'nsite' ? (
<>
<p className="text-sm text-muted-foreground">
Deploy to Nostr as a static website. Uses a kind 15128 site manifest event and Blossom file storage.
Deploy to Nostr as a static website. Uses kind 34128 events and Blossom file storage.
</p>
<div className="grid gap-2">
<Label htmlFor="custom-gateway">Gateway</Label>
<Input
id="custom-gateway"
placeholder="shakespeare.to"
placeholder="nsite.lol"
value={customGateway}
onChange={(e) => setCustomGateway(e.target.value)}
/>
</div>
<UrlListEditor
label="Relay URLs"
items={customRelayUrls}
onChange={setCustomRelayUrls}
protocol="wss"
placeholder="relay.ditto.pub"
/>
<UrlListEditor
label="Blossom Servers"
items={customBlossomServers}
onChange={setCustomBlossomServers}
protocol="https"
placeholder="blossom.ditto.pub"
/>
<div className="grid gap-2">
<Label htmlFor="custom-relays">Relay URLs (comma-separated)</Label>
<Input
id="custom-relays"
placeholder="wss://relay.nostr.band, wss://relay.damus.io"
value={customRelayUrls}
onChange={(e) => setCustomRelayUrls(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-blossom">Blossom Servers (comma-separated)</Label>
<Input
id="custom-blossom"
placeholder="https://blossom.primal.net/"
value={customBlossomServers}
onChange={(e) => setCustomBlossomServers(e.target.value)}
/>
</div>
</>
) : (
<>
@@ -305,8 +299,7 @@ export function AddCustomProviderDialog({
{customProviderType === 'netlify' ? 'Personal Access Token' :
customProviderType === 'cloudflare' ? 'API Token' :
customProviderType === 'deno' ? 'Access Token' :
customProviderType === 'railway' ? 'API Token' :
'Access Token'} <span className="text-destructive">*</span>
'Access Token'} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id="custom-apikey"
@@ -326,9 +319,7 @@ export function AddCustomProviderDialog({
? 'https://api.vercel.com'
: customProviderType === 'deno'
? 'https://api.deno.com/v1'
: customProviderType === 'railway'
? 'https://backboard.railway.com'
: 'https://api.cloudflare.com/client/v4'
: 'https://api.cloudflare.com/client/v4'
}
value={customBaseURL}
onChange={(e) => setCustomBaseURL(e.target.value)}
-896
View File
@@ -1,896 +0,0 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
} from '@/components/ui/dialog';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { useToast } from '@/hooks/useToast';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useUploadFile } from '@/hooks/useUploadFile';
import { useAppEvent } from '@/hooks/useAppEvent';
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
import { useQueryClient } from '@tanstack/react-query';
import { DotAI } from '@/lib/DotAI';
import { buildAppEvent } from '@/lib/appEvent';
import {
Loader2,
Plus,
X,
ExternalLink,
Pencil,
ChevronDown,
CircleHelp,
} from 'lucide-react';
import type { NostrEvent } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
interface AppDialogProps {
projectId: string;
open: boolean;
onOpenChange: (open: boolean) => void;
}
interface AppFormData {
name: string;
about: string;
picture: string;
banner: string;
website: string;
dTag: string;
tTags: string[];
supportedKinds: string[];
webHandlers: Array<{ url: string; type: string }>;
ngitRepo: string;
nsiteDeployment: string;
}
/** Parse a kind 31990 event into form data */
function eventToFormData(event: NostrEvent): AppFormData {
let metadata: Record<string, string> = {};
try {
if (event.content) {
metadata = JSON.parse(event.content);
}
} catch {
// Invalid JSON content, use empty metadata
}
const dTag = event.tags.find(([t]) => t === 'd')?.[1] ?? '';
const supportedKinds = event.tags
.filter(([t]) => t === 'k')
.map(([, v]) => v)
.filter(Boolean);
const webHandlers = event.tags
.filter(([t]) => t === 'web')
.map(([, url, type]) => ({ url: url ?? '', type: type ?? '' }));
const tTags = event.tags
.filter(([t]) => t === 't')
.map(([, v]) => v)
.filter(Boolean);
const ngitATag = event.tags.find(([t, v]) => t === 'a' && v?.startsWith('30617:'))?.[1] ?? '';
const nsiteATag = event.tags.find(([t, v]) => t === 'a' && v?.startsWith('35128:'))?.[1] ?? '';
return {
name: metadata.name ?? '',
about: metadata.about ?? '',
picture: metadata.picture ?? '',
banner: metadata.banner ?? '',
website: metadata.website ?? '',
dTag,
tTags,
supportedKinds,
webHandlers,
ngitRepo: aTagToNaddr(ngitATag),
nsiteDeployment: aTagToNaddr(nsiteATag),
};
}
/** Convert a slug like "my-cool-app" to title case like "My Cool App" */
function toTitleCase(slug: string): string {
return slug
.replace(/[-_]+/g, ' ')
.replace(/\b\w/g, (c) => c.toUpperCase())
.trim();
}
/** Create empty form data for a new app */
function emptyFormData(projectId: string): AppFormData {
return {
name: toTitleCase(projectId),
about: '',
picture: '',
banner: '',
website: '',
dTag: projectId,
tTags: [],
supportedKinds: [],
webHandlers: [],
ngitRepo: '',
nsiteDeployment: '',
};
}
/** Convert a "kind:pubkey:identifier" a-tag value to an naddr string, or return '' on failure. */
function aTagToNaddr(aTag: string): string {
try {
const [kindStr, pubkey, ...rest] = aTag.split(':');
const kind = parseInt(kindStr);
const identifier = rest.join(':');
if (!kind || !pubkey || !identifier) return '';
return nip19.naddrEncode({ kind, pubkey, identifier });
} catch {
return '';
}
}
/** Convert an naddr string to a "kind:pubkey:identifier" a-tag value, or return '' on failure. */
function naddrToATag(naddr: string): string {
try {
const decoded = nip19.decode(naddr.trim());
if (decoded.type !== 'naddr') return '';
const { kind, pubkey, identifier } = decoded.data;
return `${kind}:${pubkey}:${identifier}`;
} catch {
return '';
}
}
/** Read a file from VFS as a UTF-8 string, returning null if it doesn't exist. */
async function readVfsText(fs: { readFile(path: string, options: { encoding: string }): Promise<string> }, path: string): Promise<string | null> {
try {
return await fs.readFile(path, { encoding: 'utf8' });
} catch {
return null;
}
}
/** Extract OG/meta tag content from HTML text. */
function parseMetaContent(html: string, property: string): string | null {
const re = new RegExp(`<meta[^>]+(?:property|name)=["']${property}["'][^>]+content=["']([^"']+)["']`, 'i');
const alt = new RegExp(`<meta[^>]+content=["']([^"']+)["'][^>]+(?:property|name)=["']${property}["']`, 'i');
return (re.exec(html) ?? alt.exec(html))?.[1] ?? null;
}
/** Scrape autofill candidates from the project's built output and source files. */
async function scrapeProjectMeta(
fs: { readFile(path: string, options: { encoding: string }): Promise<string> },
cwd: string,
): Promise<Partial<{ name: string; about: string; picture: string; banner: string }>> {
const result: Partial<{ name: string; about: string; picture: string; banner: string }> = {};
// 1. Try dist/index.html for OG tags
const html = await readVfsText(fs, `${cwd}/dist/index.html`);
if (html) {
const ogTitle = parseMetaContent(html, 'og:title');
const ogDesc = parseMetaContent(html, 'og:description') ?? parseMetaContent(html, 'description');
const ogImage = parseMetaContent(html, 'og:image');
const ogBanner = parseMetaContent(html, 'og:image:banner') ?? parseMetaContent(html, 'twitter:image');
if (ogTitle) result.name = ogTitle;
if (ogDesc) result.about = ogDesc;
if (ogImage) result.picture = ogImage;
if (ogBanner) result.banner = ogBanner;
}
// 2. Try web manifest for name, description, and icons
const manifestPaths = [
`${cwd}/public/manifest.webmanifest`,
`${cwd}/public/manifest.json`,
`${cwd}/dist/manifest.webmanifest`,
`${cwd}/dist/manifest.json`,
];
for (const path of manifestPaths) {
const text = await readVfsText(fs, path);
if (!text) continue;
try {
const manifest = JSON.parse(text);
if (!result.name && (manifest.name || manifest.short_name)) {
result.name = manifest.name ?? manifest.short_name;
}
if (!result.about && manifest.description) {
result.about = manifest.description;
}
if (!result.picture && Array.isArray(manifest.icons) && manifest.icons.length > 0) {
// Prefer the largest icon
const sorted = [...manifest.icons].sort((a, b) => {
const sizeA = parseInt(a.sizes?.split('x')[0] ?? '0');
const sizeB = parseInt(b.sizes?.split('x')[0] ?? '0');
return sizeB - sizeA;
});
const iconSrc = sorted[0]?.src;
if (iconSrc) {
// If it's an absolute URL use it directly, otherwise it's a relative VFS path
result.picture = iconSrc.startsWith('http') ? iconSrc : iconSrc;
}
}
break;
} catch {
// Invalid JSON, try next
}
}
return result;
}
export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
const { fs } = useFS();
const { projectsPath } = useFSPaths();
const { user } = useCurrentUser();
const { toast } = useToast();
const queryClient = useQueryClient();
const { mutateAsync: publishEvent } = useNostrPublish();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const cwd = `${projectsPath}/${projectId}`;
const { event, isLoading, hasApp, refetch } = useAppEvent({ cwd });
const { settings: deploySettings, isLoading: isDeployLoading } = useProjectDeploySettings(projectId);
const [formData, setFormData] = useState<AppFormData>(emptyFormData(projectId));
const [isSaving, setIsSaving] = useState(false);
const [submitted, setSubmitted] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
const [newTag, setNewTag] = useState('');
const [newKind, setNewKind] = useState('');
const [newHandlerUrl, setNewHandlerUrl] = useState('');
const [newHandlerType, setNewHandlerType] = useState('');
const [advancedOpen, setAdvancedOpen] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const bannerFileInputRef = useRef<HTMLInputElement>(null);
// Get the deployed URL from project deploy settings
const deployedUrl = (() => {
if (!deploySettings?.currentProvider || !deploySettings?.providers) return null;
const config = deploySettings.providers[deploySettings.currentProvider];
return config?.url ?? null;
})();
// Populate form when event loads
useEffect(() => {
if (event) {
setFormData(eventToFormData(event));
} else if (!isLoading && !hasApp) {
setFormData(emptyFormData(projectId));
}
}, [event, isLoading, hasApp, projectId]);
// Auto-fill website from deployment URL when creating a new app (not editing existing)
useEffect(() => {
if (!hasApp && !isDeployLoading && deployedUrl && !formData.website) {
setFormData(prev => ({ ...prev, website: deployedUrl }));
}
}, [hasApp, isDeployLoading, deployedUrl, formData.website]);
// Auto-fill form from OG tags / web manifest when opening for the first time
useEffect(() => {
if (!open || hasApp || isLoading) return;
scrapeProjectMeta(fs, cwd).then(meta => {
setFormData(prev => ({
...prev,
name: prev.name && prev.name !== toTitleCase(projectId) ? prev.name : (meta.name ?? prev.name),
about: prev.about || meta.about || '',
picture: prev.picture || meta.picture || '',
banner: prev.banner || meta.banner || '',
}));
}).catch(() => {/* silently ignore */});
}, [open, hasApp, isLoading, fs, cwd, projectId]);
const updateField = useCallback(<K extends keyof AppFormData>(key: K, value: AppFormData[K]) => {
setFormData(prev => ({ ...prev, [key]: value }));
}, []);
const addTag = useCallback(() => {
const tag = newTag.trim().toLowerCase();
if (tag && !formData.tTags.includes(tag)) {
updateField('tTags', [...formData.tTags, tag]);
setNewTag('');
}
}, [newTag, formData.tTags, updateField]);
const removeTag = useCallback((tag: string) => {
updateField('tTags', formData.tTags.filter(t => t !== tag));
}, [formData.tTags, updateField]);
const addKind = useCallback(() => {
const kind = newKind.trim();
if (kind && !formData.supportedKinds.includes(kind)) {
updateField('supportedKinds', [...formData.supportedKinds, kind]);
setNewKind('');
}
}, [newKind, formData.supportedKinds, updateField]);
const removeKind = useCallback((kind: string) => {
updateField('supportedKinds', formData.supportedKinds.filter(k => k !== kind));
}, [formData.supportedKinds, updateField]);
const addHandler = useCallback(() => {
const url = newHandlerUrl.trim();
if (url) {
updateField('webHandlers', [...formData.webHandlers, { url, type: newHandlerType.trim() }]);
setNewHandlerUrl('');
setNewHandlerType('');
}
}, [newHandlerUrl, newHandlerType, formData.webHandlers, updateField]);
const removeHandler = useCallback((index: number) => {
updateField('webHandlers', formData.webHandlers.filter((_, i) => i !== index));
}, [formData.webHandlers, updateField]);
const handleBannerUpload = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
try {
const tags = await uploadFile(file);
const url = tags[0]?.[1];
if (url) {
updateField('banner', url);
toast({ title: 'Banner uploaded', description: 'Your app banner has been uploaded.' });
}
} catch (error) {
toast({
title: 'Upload failed',
description: error instanceof Error ? error.message : 'Failed to upload banner.',
variant: 'destructive',
});
} finally {
if (bannerFileInputRef.current) {
bannerFileInputRef.current.value = '';
}
}
}, [uploadFile, updateField, toast]);
const handleIconUpload = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
try {
const tags = await uploadFile(file);
const url = tags[0]?.[1];
if (url) {
updateField('picture', url);
toast({ title: 'Icon uploaded', description: 'Your app icon has been uploaded.' });
}
} catch (error) {
toast({
title: 'Upload failed',
description: error instanceof Error ? error.message : 'Failed to upload icon.',
variant: 'destructive',
});
} finally {
// Reset input so re-selecting the same file triggers onChange
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
}
}, [uploadFile, updateField, toast]);
const handleSave = async () => {
if (!user) {
toast({
title: 'Not logged in',
description: 'You must be logged in with Nostr to publish an app.',
variant: 'destructive',
});
return;
}
setSubmitted(true);
if (!formData.name.trim() || !formData.about.trim() || !formData.website.trim() || !formData.picture.trim() || !formData.banner.trim()) {
return;
}
if (!formData.dTag.trim()) {
toast({
title: 'Identifier required',
description: 'Please enter a unique identifier (d-tag) for your app.',
variant: 'destructive',
});
return;
}
setIsSaving(true);
try {
// Build event content and tags
const { content, tags } = await buildAppEvent(
{
name: formData.name,
about: formData.about,
picture: formData.picture,
banner: formData.banner,
website: formData.website,
dTag: formData.dTag,
tTags: formData.tTags,
supportedKinds: formData.supportedKinds,
webHandlers: formData.webHandlers,
ngitRepo: naddrToATag(formData.ngitRepo),
nsiteDeployment: naddrToATag(formData.nsiteDeployment),
},
{ fs, cwd, pubkey: user.pubkey },
);
// Publish the event
const published = await publishEvent({
kind: 31990,
content,
tags,
});
// Store the "a" coordinate in .git/shakespeare/app.json
const aValue = `31990:${published.pubkey}:${formData.dTag.trim()}`;
const dotAI = new DotAI(fs, cwd);
await dotAI.writeAppConfig({ a: aValue });
// Invalidate queries
await queryClient.invalidateQueries({ queryKey: ['app-event'] });
await refetch();
toast({
title: hasApp ? 'App updated' : 'App published',
description: `"${formData.name}" has been ${hasApp ? 'updated' : 'published'} to Nostr.`,
});
onOpenChange(false);
} catch (error) {
console.error('Failed to publish app:', error);
toast({
title: 'Failed to publish',
description: error instanceof Error ? error.message : 'An unexpected error occurred',
variant: 'destructive',
});
} finally {
setIsSaving(false);
}
};
const handleDelete = async () => {
if (!event) return;
setIsSaving(true);
try {
// Publish NIP-09 deletion event
await publishEvent({
kind: 5,
content: 'Deleted app',
tags: [['e', event.id], ['a', `31990:${event.pubkey}:${formData.dTag}`]],
});
// Remove the local app config
const dotAI = new DotAI(fs, cwd);
await dotAI.writeAppConfig({ a: '' });
await queryClient.invalidateQueries({ queryKey: ['app-event'] });
toast({ title: 'App deleted', description: `"${formData.name}" has been deleted.` });
onOpenChange(false);
} catch (error) {
toast({
title: 'Failed to delete',
description: error instanceof Error ? error.message : 'An unexpected error occurred',
variant: 'destructive',
});
} finally {
setIsSaving(false);
setConfirmDelete(false);
}
};
if (!user) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>App</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground">
You must be logged in with Nostr to manage your app.
</p>
</DialogContent>
</Dialog>
);
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-lg max-h-[85vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{hasApp ? 'Edit App' : 'Publish App'}</DialogTitle>
<DialogDescription>
{hasApp
? 'Update your app\'s listing on Nostr.'
: 'Publish your project as a Nostr app.'}
</DialogDescription>
</DialogHeader>
{isLoading ? (
<div className="space-y-4">
<div className="flex items-start gap-4">
<Skeleton className="h-20 w-20 rounded-2xl flex-shrink-0" />
<div className="flex-1 space-y-2 pt-1">
<Skeleton className="h-5 w-40" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-2/3" />
</div>
</div>
<Skeleton className="h-10 w-full" />
</div>
) : (
<div className="space-y-5">
{/* App Preview Card — banner + overlapping icon */}
<div className="border rounded-xl overflow-hidden bg-card">
{/* Hidden file inputs */}
<input
ref={bannerFileInputRef}
type="file"
accept="image/*"
onChange={handleBannerUpload}
className="hidden"
disabled={isSaving || isUploading}
/>
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleIconUpload}
className="hidden"
disabled={isSaving || isUploading}
/>
{/* Banner */}
<div
className={`relative h-32 bg-muted cursor-pointer group${submitted && !formData.banner ? ' ring-2 ring-destructive ring-inset' : ''}`}
style={formData.banner ? { backgroundImage: `url(${formData.banner})`, backgroundSize: 'cover', backgroundPosition: 'center' } : undefined}
onClick={() => !isSaving && !isUploading && bannerFileInputRef.current?.click()}
>
{!formData.banner && (
<div className="absolute inset-0 bg-gradient-to-br from-accent/10 via-transparent to-primary/5" />
)}
{!formData.banner && (
<div className="absolute inset-0 flex items-center justify-center">
<Plus className="h-6 w-6 text-muted-foreground" strokeWidth={3} />
</div>
)}
<div className="absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-colors flex items-center justify-center">
<span className="opacity-0 group-hover:opacity-100 transition-opacity flex items-center gap-1.5 text-white text-xs font-medium bg-black/50 rounded-full px-3 py-1.5 backdrop-blur-sm">
{isUploading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Pencil className="h-3.5 w-3.5" />}
{formData.banner ? 'Change banner' : 'Add banner'}
</span>
</div>
{formData.banner && (
<div className="absolute bottom-2 right-2 h-7 w-7 rounded-full bg-background border border-border shadow-sm flex items-center justify-center">
<Pencil className="h-3.5 w-3.5 text-muted-foreground" />
</div>
)}
</div>
{/* Icon + Name/Description */}
<div className="px-4 pb-4">
{/* Icon overlapping banner */}
<div className="-mt-10 mb-3">
<div className={`relative inline-block group cursor-pointer${submitted && !formData.picture ? ' ring-2 ring-destructive rounded-2xl' : ''}`} onClick={() => !isSaving && !isUploading && fileInputRef.current?.click()}>
<Avatar className="h-20 w-20 rounded-2xl border-4 border-background shadow-sm">
<AvatarImage src={formData.picture} alt={formData.name || 'App icon'} className="object-cover" />
<AvatarFallback className="rounded-2xl bg-muted">
{formData.picture ? null : <Plus className="h-7 w-7 text-muted-foreground" strokeWidth={3} />}
</AvatarFallback>
</Avatar>
<div className="absolute inset-0 rounded-2xl bg-black/0 group-hover:bg-black/40 transition-colors flex items-center justify-center">
<Pencil className="h-5 w-5 text-white opacity-0 group-hover:opacity-100 transition-opacity drop-shadow" />
</div>
<div className="absolute bottom-0 right-0 h-6 w-6 rounded-full bg-background border border-border shadow-sm flex items-center justify-center">
<Pencil className="h-3 w-3 text-muted-foreground" />
</div>
</div>
</div>
{/* Name & Description */}
<div className="space-y-2">
<Input
value={formData.name}
onChange={e => updateField('name', e.target.value)}
placeholder="App Name"
disabled={isSaving}
className={submitted && !formData.name.trim() ? 'border-destructive focus-visible:ring-destructive' : ''}
/>
<Textarea
value={formData.about}
onChange={e => updateField('about', e.target.value)}
placeholder="A short description of your app..."
rows={2}
disabled={isSaving}
className={`resize-none${submitted && !formData.about.trim() ? ' border-destructive focus-visible:ring-destructive' : ''}`}
/>
</div>
{/* Website */}
<div className="mt-3">
<Input
id="app-website"
value={formData.website}
onChange={e => updateField('website', e.target.value)}
placeholder={deployedUrl || 'https://myapp.example.com'}
disabled={isSaving}
className={`text-sm${submitted && !formData.website.trim() ? ' border-destructive focus-visible:ring-destructive' : ''}`}
/>
</div>
</div>
</div>
{/* Advanced Section */}
<Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
<CollapsibleTrigger asChild>
<button
type="button"
className="flex items-center gap-2 w-full text-sm text-muted-foreground hover:text-foreground transition-colors py-2 border-t"
>
<ChevronDown className={`h-4 w-4 transition-transform ${advancedOpen ? 'rotate-180' : ''}`} />
<span>Advanced</span>
</button>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="space-y-3 pt-2">
{/* Hint to use AI */}
<div className="flex items-start gap-2 text-xs text-muted-foreground bg-muted/50 rounded-lg p-3">
<CircleHelp className="h-3.5 w-3.5 mt-0.5 flex-shrink-0" />
<span>Not sure? Ask Shakespeare to update your app.</span>
</div>
<Tabs defaultValue="general">
<TabsList className="w-full">
<TabsTrigger value="general" className="flex-1">General</TabsTrigger>
<TabsTrigger value="handlers" className="flex-1">Handlers</TabsTrigger>
<TabsTrigger value="tags" className="flex-1">Tags</TabsTrigger>
</TabsList>
{/* General tab: Identifier, Git Repo, nsite */}
<TabsContent value="general" className="space-y-4 mt-3">
<div className="space-y-1.5">
<Label htmlFor="app-dtag" className="text-xs">Identifier</Label>
<Input
id="app-dtag"
value={formData.dTag}
onChange={e => updateField('dTag', e.target.value)}
placeholder="my-app"
disabled={isSaving || hasApp}
/>
<p className="text-xs text-muted-foreground">
{hasApp ? 'Cannot be changed after publishing.' : 'Unique identifier for this app. Defaults to the project ID.'}
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="app-ngit" className="text-xs">Git Repository</Label>
<Input
id="app-ngit"
value={formData.ngitRepo}
onChange={e => updateField('ngitRepo', e.target.value)}
placeholder="naddr1..."
disabled={isSaving}
className={formData.ngitRepo && !naddrToATag(formData.ngitRepo) ? 'border-destructive focus-visible:ring-destructive' : ''}
/>
{formData.ngitRepo && !naddrToATag(formData.ngitRepo) && (
<p className="text-xs text-destructive">Invalid naddr</p>
)}
<p className="text-xs text-muted-foreground">naddr of the ngit repository (kind 30617). Auto-detected from git remote if left blank.</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="app-nsite" className="text-xs">nsite Deployment</Label>
<Input
id="app-nsite"
value={formData.nsiteDeployment}
onChange={e => updateField('nsiteDeployment', e.target.value)}
placeholder="naddr1..."
disabled={isSaving}
className={formData.nsiteDeployment && !naddrToATag(formData.nsiteDeployment) ? 'border-destructive focus-visible:ring-destructive' : ''}
/>
{formData.nsiteDeployment && !naddrToATag(formData.nsiteDeployment) && (
<p className="text-xs text-destructive">Invalid naddr</p>
)}
<p className="text-xs text-muted-foreground">naddr of the nsite deployment (kind 35128). Auto-detected from .nsite/config.json if left blank.</p>
</div>
</TabsContent>
{/* Handlers tab: Supported Kinds, Web Handlers */}
<TabsContent value="handlers" className="space-y-4 mt-3">
<div className="space-y-1.5">
<Label className="text-xs">Supported Event Kinds</Label>
{formData.supportedKinds.length > 0 && (
<div className="flex flex-wrap gap-1">
{formData.supportedKinds.map(kind => (
<Badge key={kind} variant="secondary" className="gap-1">
{kind}
<button onClick={() => removeKind(kind)} disabled={isSaving} className="hover:text-destructive">
<X className="h-3 w-3" />
</button>
</Badge>
))}
</div>
)}
<div className="flex gap-2">
<Input
value={newKind}
onChange={e => setNewKind(e.target.value)}
placeholder="Kind number (e.g. 1)"
disabled={isSaving}
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); addKind(); } }}
className="flex-1"
/>
<Button variant="outline" size="sm" onClick={addKind} disabled={isSaving || !newKind.trim()} className="h-9">
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Web Handlers</Label>
{formData.webHandlers.length > 0 && (
<div className="space-y-1.5">
{formData.webHandlers.map((handler, index) => (
<div key={index} className="flex items-center gap-2 text-sm bg-muted/50 p-2 rounded-md">
<ExternalLink className="h-3 w-3 text-muted-foreground flex-shrink-0" />
<span className="truncate flex-1">{handler.url}</span>
{handler.type && (
<Badge variant="outline" className="text-xs flex-shrink-0">{handler.type}</Badge>
)}
<button onClick={() => removeHandler(index)} disabled={isSaving} className="hover:text-destructive flex-shrink-0">
<X className="h-3 w-3" />
</button>
</div>
))}
</div>
)}
<div className="flex gap-2">
<Input
value={newHandlerUrl}
onChange={e => setNewHandlerUrl(e.target.value)}
placeholder="https://app.example.com/e/<bech32>"
disabled={isSaving}
className="flex-1"
/>
<Select value={newHandlerType || '_all_'} onValueChange={v => setNewHandlerType(v === '_all_' ? '' : v)} disabled={isSaving}>
<SelectTrigger className="w-28">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="_all_">All</SelectItem>
<SelectItem value="npub">npub</SelectItem>
<SelectItem value="note">note</SelectItem>
<SelectItem value="nprofile">nprofile</SelectItem>
<SelectItem value="nevent">nevent</SelectItem>
<SelectItem value="naddr">naddr</SelectItem>
</SelectContent>
</Select>
<Button variant="outline" size="sm" onClick={addHandler} disabled={isSaving || !newHandlerUrl.trim()} className="h-9">
<Plus className="h-4 w-4" />
</Button>
</div>
<p className="text-xs text-muted-foreground">
URL patterns where <code className="text-xs">{'<bech32>'}</code> will be replaced with the NIP-19 entity.
</p>
</div>
</TabsContent>
{/* Tags tab */}
<TabsContent value="tags" className="space-y-4 mt-3">
<div className="space-y-1.5">
<Label className="text-xs">Tags</Label>
{formData.tTags.length > 0 && (
<div className="flex flex-wrap gap-1">
{formData.tTags.map(tag => (
<Badge key={tag} variant="secondary" className="gap-1">
{tag}
<button onClick={() => removeTag(tag)} disabled={isSaving} className="hover:text-destructive">
<X className="h-3 w-3" />
</button>
</Badge>
))}
</div>
)}
<div className="flex gap-2">
<Input
value={newTag}
onChange={e => setNewTag(e.target.value)}
placeholder="e.g. productivity"
disabled={isSaving}
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); addTag(); } }}
className="flex-1"
/>
<Button variant="outline" size="sm" onClick={addTag} disabled={isSaving || !newTag.trim()} className="h-9">
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
</TabsContent>
</Tabs>
{/* Delete App */}
{hasApp && (
<div className="pt-2 border-t">
{confirmDelete ? (
<div className="space-y-2">
<p className="text-xs text-muted-foreground">Are you sure? This will publish a deletion event to Nostr.</p>
<div className="flex gap-2">
<Button variant="destructive" size="sm" className="flex-1" onClick={handleDelete} disabled={isSaving}>
{isSaving && <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />}
Yes, delete
</Button>
<Button variant="outline" size="sm" className="flex-1" onClick={() => setConfirmDelete(false)} disabled={isSaving}>
Cancel
</Button>
</div>
</div>
) : (
<Button
variant="ghost"
size="sm"
className="w-full text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => setConfirmDelete(true)}
disabled={isSaving}
>
Delete App
</Button>
)}
</div>
)}
</div>
</CollapsibleContent>
</Collapsible>
{/* Validation summary */}
{submitted && (() => {
const missing = [
!formData.banner && 'banner',
!formData.picture && 'icon',
!formData.name.trim() && 'name',
!formData.about.trim() && 'description',
!formData.website.trim() && 'website',
].filter(Boolean) as string[];
if (!missing.length) return null;
const list = missing.length === 1
? missing[0]
: missing.slice(0, -1).join(', ') + ' and ' + missing[missing.length - 1];
return (
<p className="text-sm text-destructive">
Please add a {list} before publishing.
</p>
);
})()}
{/* Save Button */}
<Button
onClick={handleSave}
disabled={isSaving}
className="w-full gap-2"
>
{isSaving && <Loader2 className="h-4 w-4 animate-spin" />}
{isSaving
? (hasApp ? 'Updating...' : 'Publishing...')
: (hasApp ? 'Update App' : 'Publish App')}
</Button>
</div>
)}
</DialogContent>
</Dialog>
);
}
+1 -3
View File
@@ -51,7 +51,7 @@ const AppConfigSchema = z.object({
previewDomain: z.string().min(1),
language: z.string(),
showcaseEnabled: z.boolean(),
showcaseCurator: z.string(),
showcaseModerator: z.string(),
fsPathProjects: z.string().min(1),
fsPathConfig: z.string().min(1),
fsPathTmp: z.string().min(1),
@@ -60,8 +60,6 @@ const AppConfigSchema = z.object({
sentryDsn: z.string(),
sentryEnabled: z.boolean(),
systemPrompt: z.string(),
plausibleDomain: z.string(),
plausibleEndpoint: z.string(),
}) satisfies z.ZodType<AppConfig>;
export function AppProvider(props: AppProviderProps) {
+164 -7
View File
@@ -1,24 +1,92 @@
import React from "react";
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 { useAppContext } from "@/hooks/useAppContext";
import { useTranslation } from 'react-i18next';
import { Button } from "@/components/ui/button";
import { Link } from 'react-router-dom';
import { Settings } from 'lucide-react';
export function AppShowcase() {
const { t } = useTranslation();
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;
// Categorize and organize submissions - single pass for efficiency
const {
displayedFeaturedApps,
displayedTemplateApps,
moreApps
} = useMemo(() => {
const DISPLAY_LIMIT = 6;
// Single pass categorization
const templates: typeof submissions = [];
const featured: typeof submissions = [];
const approved: typeof submissions = [];
for (const app of submissions) {
if (app.isHidden) continue;
const isTemplate = app.appTags.includes('Template');
const isFeatured = app.isFeatured;
const isApproved = app.isApproved;
if (isTemplate) {
templates.push(app);
} else if (isFeatured) {
featured.push(app);
} else if (isApproved) {
approved.push(app);
}
}
// Shuffle each category once
const shuffledTemplates = shuffleArray(templates);
const shuffledFeatured = shuffleArray(featured);
const shuffledApproved = shuffleArray(approved);
// Split into display and more sections
return {
displayedFeaturedApps: shuffledFeatured.slice(0, DISPLAY_LIMIT),
displayedTemplateApps: shuffledTemplates.slice(0, DISPLAY_LIMIT),
moreApps: [
...shuffledFeatured.slice(DISPLAY_LIMIT),
...shuffledTemplates.slice(DISPLAY_LIMIT),
...shuffledApproved,
],
};
}, [submissions]);
// 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">
@@ -38,9 +106,14 @@ export function AppShowcase() {
<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>
@@ -74,11 +147,95 @@ export function AppShowcase() {
return (
<div className="mt-16 max-w-7xl mx-auto">
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{submissions.map((app) => (
<AppShowcaseCard key={app.id} app={app} />
))}
{/* Apps Grid */}
<div className="space-y-12">
{/* Featured Apps */}
{displayedFeaturedApps.length > 0 && (
<div>
<div className="flex items-start gap-3 mb-6">
<div className="flex-none w-8 h-8 bg-yellow-100 dark:bg-yellow-900/30 rounded-lg flex items-center justify-center">
<span className="text-sm">⭐</span>
</div>
<div>
<h3 className="text-xl font-bold text-foreground">{t('featuredApps')}</h3>
<p className="text-sm text-muted-foreground">{t('featuredAppsDescription')}</p>
</div>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{displayedFeaturedApps.map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</div>
)}
{/* Templates Section */}
{displayedTemplateApps.length > 0 && (
<div>
<div className="flex items-start gap-3 mb-6">
<div className="flex-none w-8 h-8 bg-purple-100 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
<span className="text-sm">📋</span>
</div>
<div>
<h3 className="text-xl font-bold text-foreground">{t('templates')}</h3>
<p className="text-sm text-muted-foreground">{t('templatesDescription')}</p>
</div>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{displayedTemplateApps.map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</div>
)}
{/* More Apps (Remaining Featured, Templates, and Approved) - Collapsible */}
{moreApps.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-start gap-3">
<div className="flex-none w-8 h-8 bg-blue-100 dark:bg-blue-900/50 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">
{t('moreAppsCount', { count: moreApps.length })}
</h3>
<p className="text-sm text-muted-foreground">
{showAllApps ? t('clickToCollapse') : t('clickToViewMore')}
</p>
</div>
</div>
</Button>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{moreApps.map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</CollapsibleContent>
</Collapsible>
</div>
)}
</div>
</div>
);
}
}
+529 -60
View File
@@ -2,81 +2,541 @@ 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, User } from 'lucide-react';
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 }: AppShowcaseCardProps) {
const [bannerError, setBannerError] = useState(false);
const [iconError, setIconError] = useState(false);
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();
const { data: authorData } = useAuthor(app.pubkey);
const authorNpub = nip19.npubEncode(app.pubkey);
// 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
}], { signal: AbortSignal.timeout(3000) });
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
}], { signal: AbortSignal.timeout(3000) });
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
}], { signal: AbortSignal.timeout(3000) });
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
}], { signal: AbortSignal.timeout(3000) });
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
}], { signal: AbortSignal.timeout(3000) });
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 overflow-hidden">
{/* Banner + overlapping icon */}
<a
href={app.websiteUrl || undefined}
target="_blank"
rel="noopener noreferrer"
className="block relative"
>
{/* Banner */}
<div className="aspect-[3/1] bg-muted overflow-hidden">
{app.bannerUrl && !bannerError ? (
<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.bannerUrl}
alt=""
src={app.screenshotUrl}
alt={`${app.appName} screenshot`}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
onError={() => setBannerError(true)}
onError={() => setImageError(true)}
/>
) : (
<div className="w-full h-full bg-gradient-to-br from-accent/10 via-transparent to-primary/5" />
<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>
)}
</div>
</a>
{/* Icon overlapping banner */}
<div className="absolute bottom-0 translate-y-1/2 left-4">
<div className="h-14 w-14 rounded-xl border-2 border-background shadow-md overflow-hidden bg-muted flex-shrink-0">
{app.appIconUrl && !iconError ? (
{/* 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={() => setIconError(true)}
onError={(e) => {
const target = e.target as HTMLImageElement;
target.style.display = 'none';
}}
/>
) : (
<div className="w-full h-full flex items-center justify-center">
<ExternalLink className="w-5 h-5 text-muted-foreground" />
</div>
)}
</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>
</a>
<CardContent className="pt-10 px-4 pb-4 flex flex-col flex-1">
<h3 className="text-base font-semibold text-foreground mb-1 truncate" title={app.appName}>
{app.appName}
</h3>
<p className="text-muted-foreground mb-3 line-clamp-3">{app.description}</p>
{app.description && (
<p className="text-sm text-muted-foreground mb-3 line-clamp-2">{app.description}</p>
)}
{/* Author */}
{/* Author Information */}
<div className="flex items-center gap-2 mb-4">
<div className="w-5 h-5 rounded-full overflow-hidden bg-muted flex-shrink-0">
<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'}
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">
@@ -84,10 +544,10 @@ export function AppShowcaseCard({ app }: AppShowcaseCardProps) {
</div>
)}
</div>
<span className="text-xs text-muted-foreground">
<span className="text-sm text-muted-foreground">
by{' '}
<a
href={`https://ditto.pub/${authorNpub}`}
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"
@@ -97,24 +557,33 @@ export function AppShowcaseCard({ app }: AppShowcaseCardProps) {
</span>
</div>
<div className="flex-1" />
{/* Spacer to push action links to bottom */}
<div className="flex-1"></div>
{/* Action Links */}
<div className="flex items-center gap-2 mt-auto">
{app.repositoryUrl && (
<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>
)}
{app.websiteUrl && (
<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>
)}
<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 -2
View File
@@ -3,10 +3,9 @@ import { DeploySettingsContext, type DeploySettings, type DeployProvider } from
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
import { DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets';
const DEFAULT_SETTINGS: DeploySettings = {
providers: [DEFAULT_NSITE_PROVIDER],
providers: [],
};
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
+2 -2
View File
@@ -9,7 +9,7 @@ import { getSentryInstance } from '@/lib/sentry';
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode | ((props: FallbackProps) => ReactNode);
onError?: (error: Error, info: { componentStack?: string | null }) => void;
onError?: (error: Error, info: { componentStack: string | null }) => void;
/** Whether to report errors to Sentry (default: true) */
reportToSentry?: boolean;
}
@@ -91,7 +91,7 @@ export function ErrorBoundary({
onError,
reportToSentry = true,
}: ErrorBoundaryProps) {
const handleError = (error: Error, info: { componentStack?: string | null }) => {
const handleError = (error: Error, info: { componentStack: string | null }) => {
// Log error details for debugging
console.error('ErrorBoundary caught an error:', error, info);
+2 -2
View File
@@ -33,10 +33,10 @@ export function ExternalFavicon({
const parsedUrl = new URL(url);
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
parsedUrl.hostname = parsedUrl.hostname.replace(/^(ai\.|api\.|enclave\.)/, '');
parsedUrl.hostname = parsedUrl.hostname.replace(/^(ai\.|api\.)/, '');
// Normalize the URL to ensure it has a protocol
return faviconUrl({ template: config.faviconUrl, url: parsedUrl });
return faviconUrl(config.faviconUrl, parsedUrl);
} catch {
return;
}
-73
View File
@@ -1,73 +0,0 @@
import { useEffect, useState } from 'react';
import {
AlertDialog,
AlertDialogContent,
AlertDialogDescription,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
/**
* Detects if IndexedDB is unavailable (which happens in iOS lockdown mode)
* and displays a blocking alert dialog informing the user.
*/
export function LockdownModeDetector() {
const [isLockdownMode, setIsLockdownMode] = useState(false);
useEffect(() => {
// Check if IndexedDB is available
const checkIndexedDB = async () => {
try {
// Check if IndexedDB exists
if (!window.indexedDB) {
setIsLockdownMode(true);
return;
}
// Try to open a test database to verify IndexedDB actually works
// In iOS lockdown mode, indexedDB exists but throws errors when used
const testDBName = '_shakespeare_lockdown_test';
const request = window.indexedDB.open(testDBName, 1);
request.onerror = () => {
setIsLockdownMode(true);
};
request.onsuccess = () => {
// IndexedDB is working, clean up test database
request.result.close();
window.indexedDB.deleteDatabase(testDBName);
};
} catch {
// Any error means IndexedDB is not available
setIsLockdownMode(true);
}
};
checkIndexedDB();
}, []);
return (
<AlertDialog open={isLockdownMode}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="text-left">🔒 Lockdown Mode Detected</AlertDialogTitle>
<AlertDialogDescription className="space-y-3 text-left">
<p>
Shakespeare requires IndexedDB to function, which is unavailable in iOS Lockdown Mode.
</p>
<p>
To use Shakespeare, please disable Lockdown Mode in your device settings:
</p>
<ol className="list-decimal list-inside space-y-1 text-left ml-4">
<li>Open Settings</li>
<li>Go to Privacy &amp; Security</li>
<li>Tap Lockdown Mode</li>
<li>Turn off Lockdown Mode</li>
</ol>
</AlertDialogDescription>
</AlertDialogHeader>
</AlertDialogContent>
</AlertDialog>
);
}
-29
View File
@@ -1,29 +0,0 @@
import { ReactNode, useEffect, useRef } from 'react';
import { useAppContext } from '@/hooks/useAppContext';
interface PlausibleProviderProps {
children: ReactNode;
}
/**
* Reactively initializes Plausible Analytics from AppConfig.
* Plausible's `init()` can only be called once, so we guard with a ref.
*/
export function PlausibleProvider({ children }: PlausibleProviderProps) {
const { config } = useAppContext();
const initializedRef = useRef(false);
useEffect(() => {
if (initializedRef.current || !config.plausibleDomain) return;
initializedRef.current = true;
import('@plausible-analytics/tracker').then(({ init }) => {
init({
domain: config.plausibleDomain,
...(config.plausibleEndpoint && { endpoint: config.plausibleEndpoint }),
});
}).catch(console.error);
}, [config.plausibleDomain, config.plausibleEndpoint]);
return <>{children}</>;
}
+8 -2
View File
@@ -1,7 +1,7 @@
import React, { useEffect, useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders } from 'lucide-react';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders, Compass } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Input } from '@/components/ui/input';
@@ -327,7 +327,6 @@ export function ProjectSidebar({
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
onClick={handleToggleSidebar}
aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')}
title={(onClose && isMobile) ? t('closeSidebar') : t('hidePaneButtonTooltip')}
>
{(onClose && isMobile) ? (
<X className="h-4 w-4 text-primary/60 hover:text-primary" />
@@ -368,6 +367,13 @@ export function ProjectSidebar({
<GitBranch className="h-4 w-4" />
{t('importRepository')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => navigateAndClose('/explore')}
className="flex items-center gap-2 w-full"
>
<Compass className="h-4 w-4" />
{t('exploreApps')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setLabelsDialogOpen(true)}
className="flex items-center gap-2 w-full"
+3 -13
View File
@@ -14,7 +14,6 @@ import {
ChevronDown,
Trash2,
Star,
AppWindow,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useLocalStorage } from '@/hooks/useLocalStorage';
@@ -28,7 +27,7 @@ interface ProjectTitleMenuProps {
onDuplicate: () => void;
onDelete: () => void;
onProjectDetails: () => void;
onApp: () => void;
isAILoading: boolean;
isAnyLoading: boolean;
className?: string;
}
@@ -41,7 +40,7 @@ export function ProjectTitleMenu({
onDuplicate,
onDelete,
onProjectDetails,
onApp,
isAILoading,
isAnyLoading,
className = '',
}: ProjectTitleMenuProps) {
@@ -101,15 +100,6 @@ export function ProjectTitleMenu({
Project Details
</DropdownMenuItem>
<DropdownMenuItem
onClick={onApp}
disabled={isAnyLoading}
className="gap-2"
>
<AppWindow className="h-4 w-4" />
App
</DropdownMenuItem>
<DropdownMenuItem
onClick={onGitHistory}
disabled={isAnyLoading}
@@ -121,7 +111,7 @@ export function ProjectTitleMenu({
<DropdownMenuItem
onClick={onNewChat}
disabled={isAnyLoading}
disabled={isAILoading}
className="gap-2"
>
<MessageSquarePlus className="h-4 w-4" />
+30 -24
View File
@@ -17,7 +17,6 @@ import {
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
import type { PresetDeployProvider } from '@/lib/deploy/types';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { UrlListEditor } from '@/components/UrlListEditor';
interface ProviderConfigDialogProps {
open: boolean;
@@ -134,27 +133,39 @@ export function ProviderConfigDialog({
</Label>
<Input
id="provider-gateway"
placeholder="shakespeare.to"
placeholder="nsite.lol"
value={localProvider.gateway || ''}
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
/>
</div>
<UrlListEditor
label="Relay URLs"
items={localProvider.relayUrls ?? []}
onChange={(urls) => setLocalProvider({ ...localProvider, relayUrls: urls })}
protocol="wss"
placeholder="relay.ditto.pub"
required
/>
<UrlListEditor
label="Blossom Servers"
items={localProvider.blossomServers ?? []}
onChange={(servers) => setLocalProvider({ ...localProvider, blossomServers: servers })}
protocol="https"
placeholder="blossom.ditto.pub"
required
/>
<div className="grid gap-2">
<Label htmlFor="provider-relays">
Relay URLs (comma-separated) <span className="text-destructive">*</span>
</Label>
<Input
id="provider-relays"
placeholder="wss://relay.nostr.band, wss://relay.damus.io"
value={localProvider.relayUrls?.join(', ') || ''}
onChange={(e) => setLocalProvider({
...localProvider,
relayUrls: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
})}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="provider-blossom">
Blossom Servers (comma-separated) <span className="text-destructive">*</span>
</Label>
<Input
id="provider-blossom"
placeholder="https://blossom.primal.net/"
value={localProvider.blossomServers?.join(', ') || ''}
onChange={(e) => setLocalProvider({
...localProvider,
blossomServers: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
})}
/>
</div>
</>
) : (
<>
@@ -201,8 +212,6 @@ export function ProviderConfigDialog({
setLocalProvider({ ...localProvider, apiKey: e.target.value });
} else if (localProvider.type === 'deno') {
setLocalProvider({ ...localProvider, apiKey: e.target.value });
} else if (localProvider.type === 'railway') {
setLocalProvider({ ...localProvider, apiKey: e.target.value });
}
}}
/>
@@ -218,8 +227,7 @@ export function ProviderConfigDialog({
localProvider.type === 'vercel' ? 'https://api.vercel.com' :
localProvider.type === 'cloudflare' ? 'https://api.cloudflare.com/client/v4' :
localProvider.type === 'deno' ? 'https://api.deno.com/v1' :
localProvider.type === 'railway' ? 'https://backboard.railway.app/graphql/v2' :
'Base URL'
'Base URL'
}
value={localProvider.baseURL || ''}
onChange={(e) => {
@@ -231,8 +239,6 @@ export function ProviderConfigDialog({
setLocalProvider({ ...localProvider, baseURL: e.target.value });
} else if (localProvider.type === 'deno') {
setLocalProvider({ ...localProvider, baseURL: e.target.value });
} else if (localProvider.type === 'railway') {
setLocalProvider({ ...localProvider, baseURL: e.target.value });
}
}}
/>
+177 -29
View File
@@ -1,14 +1,21 @@
import React, { useState } from 'react';
import React, { useState, useRef, useEffect, memo } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { GitBranch, Loader2, EllipsisVertical, Edit } from 'lucide-react';
import { GitBranch, Loader2, EllipsisVertical, Edit, Code, ExternalLink } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import type { Repository } from '@/hooks/useUserRepositories';
import { useAuthor } from '@/hooks/useAuthor';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
@@ -23,13 +30,26 @@ import { useGitSettings } from '@/hooks/useGitSettings';
import { detectFork } from '@/lib/detectFork';
import { NostrRepoEditDialog } from '@/components/NostrRepoEditDialog';
import { useQueryClient } from '@tanstack/react-query';
import { useOGImage } from '@/hooks/useOGImage';
import { ZapDialog } from '@/components/ZapDialog';
import { Zap } from 'lucide-react';
import type { Event } from 'nostr-tools';
import type { NostrMetadata } from '@nostrify/nostrify';
import { formatRelativeTime } from '@/lib/utils';
interface RepositoryCardProps {
repo: Repository;
/** Pre-fetched author metadata to avoid individual fetches */
authorMetadata?: NostrMetadata;
/** Callback when a tag is clicked - receives the tag value */
onTagClick?: (tag: string) => void;
}
export function RepositoryCard({ repo }: RepositoryCardProps) {
const { data: authorData } = useAuthor(repo.pubkey);
function RepositoryCardInner({ repo, authorMetadata: preloadedMetadata, onTagClick }: RepositoryCardProps) {
// Only fetch author data if not preloaded
const { data: authorData } = useAuthor(preloadedMetadata ? undefined : repo.pubkey);
const metadata = preloadedMetadata ?? authorData?.metadata;
const { user } = useCurrentUser();
const { settings: gitSettings } = useGitSettings();
const navigate = useNavigate();
@@ -39,10 +59,41 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
const queryClient = useQueryClient();
const [isCloning, setIsCloning] = useState(false);
const [editRepoOpen, setEditRepoOpen] = useState(false);
const [imageError, setImageError] = useState(false);
const [eventViewerOpen, setEventViewerOpen] = useState(false);
const [isInViewport, setIsInViewport] = useState(false);
const cardRef = useRef<HTMLDivElement>(null);
const displayName = authorData?.metadata?.name || genUserName(repo.pubkey);
const profileImage = authorData?.metadata?.picture;
// Lazy load OG images - only fetch when card is in viewport
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
setIsInViewport(true);
observer.disconnect();
}
},
{ rootMargin: '100px' } // Start loading slightly before visible
);
if (cardRef.current) {
observer.observe(cardRef.current);
}
return () => observer.disconnect();
}, []);
const displayName = metadata?.name || genUserName(repo.pubkey);
const profileImage = metadata?.picture;
const isOwnRepo = user?.pubkey === repo.pubkey;
const hasLightning = !!(metadata?.lud16 || metadata?.lud06);
const canZap = user && !isOwnRepo && hasLightning;
// Get OG metadata from first web URL - only when in viewport
const firstWebUrl = repo.webUrls?.[0];
const { data: ogMetadata } = useOGImage(isInViewport ? firstWebUrl : undefined);
const ogImageUrl = ogMetadata?.image ?? null;
const ogDescription = ogMetadata?.description ?? null;
// Construct Nostr clone URL
const nostrURI = new NostrURI({
@@ -109,52 +160,117 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
queryClient.invalidateQueries({ queryKey: ['nostr', 'user-repositories', user?.pubkey] });
};
// Check if we have a valid OG image to show
const hasValidImage = ogImageUrl && !imageError;
return (
<Card className="h-full flex flex-col hover:shadow-lg transition-shadow">
<Card ref={cardRef} className="h-full flex flex-col hover:shadow-lg transition-shadow">
{/* Preview Image or Placeholder */}
{hasValidImage && firstWebUrl ? (
<a
href={firstWebUrl}
target="_blank"
rel="noopener noreferrer"
className="block aspect-video bg-muted overflow-hidden rounded-t-lg cursor-pointer hover:opacity-90 transition-opacity"
>
<img
src={ogImageUrl}
alt={`${repo.name} preview`}
className="w-full h-full object-cover"
onError={() => setImageError(true)}
/>
</a>
) : (
<div className="aspect-video bg-gradient-to-br from-primary to-accent rounded-t-lg flex items-center justify-center">
<Code className="h-12 w-12 text-white" />
</div>
)}
<CardContent className="p-6 flex flex-col flex-1">
{/* Header with name and menu */}
<div className="mb-4 flex items-start justify-between">
<div className="flex-1 min-w-0">
<h3 className="font-semibold text-lg leading-tight mb-2 truncate">
{repo.name}
</h3>
<div className="flex items-end gap-2 mb-2">
<h3 className="font-semibold text-lg leading-tight truncate">
{repo.name}
</h3>
<span className="text-sm text-muted-foreground shrink-0">
{formatRelativeTime(repo.created_at)}
</span>
</div>
</div>
{isOwnRepo && (
<div className="flex items-center -mt-1 -mr-2 shrink-0">
{canZap && (
<ZapDialog target={repo as unknown as Event}>
<Button variant="ghost" size="icon" className="h-8 w-8 text-amber-500 hover:text-amber-600 hover:bg-amber-500/10">
<Zap className="h-4 w-4" />
</Button>
</ZapDialog>
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8 -mt-1 -mr-2 shrink-0">
<Button variant="ghost" size="icon" className="h-8 w-8">
<EllipsisVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setEditRepoOpen(true)} className="gap-2">
<Edit className="h-4 w-4" />
Edit Repository
<DropdownMenuContent align="end">
{firstWebUrl && (
<DropdownMenuItem asChild className="gap-2">
<a href={firstWebUrl} target="_blank" rel="noopener noreferrer">
<ExternalLink className="h-4 w-4" />
Open Website
</a>
</DropdownMenuItem>
</DropdownMenuContent>
)}
<DropdownMenuItem onClick={() => setEventViewerOpen(true)} className="gap-2">
<Code className="h-4 w-4" />
View Event
</DropdownMenuItem>
{isOwnRepo && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setEditRepoOpen(true)} className="gap-2">
<Edit className="h-4 w-4" />
Edit Repository
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
</div>
{/* Author */}
<div className="mb-4">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Avatar className="h-4 w-4">
<div className="flex items-center gap-3 text-sm">
<Avatar className="h-10 w-10">
{profileImage && (
<AvatarImage src={profileImage} alt={displayName} />
)}
<AvatarFallback className="text-[8px]">
<AvatarFallback className="text-xs">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<span className="truncate">{displayName}</span>
<div className="flex items-center gap-2 min-w-0 flex-1">
<button
onClick={(e) => {
e.stopPropagation();
onTagClick?.(displayName);
}}
className="truncate font-medium text-base text-foreground hover:text-primary hover:underline transition-colors text-left"
>
{displayName}
</button>
{metadata?.nip05 && (
<span className="text-sm text-muted-foreground shrink-0">{metadata.nip05}</span>
)}
</div>
</div>
</div>
{/* Description */}
{repo.description && (
{(repo.description || ogDescription) && (
<p className="text-sm text-muted-foreground line-clamp-2 mb-4">
{repo.description}
{repo.description || ogDescription}
</p>
)}
@@ -162,14 +278,21 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
{repo.repoTags.length > 0 && (
<div className="flex flex-wrap gap-1 mb-4">
{repo.repoTags.slice(0, 3).map((tag, index) => (
<Badge key={index} variant="secondary" className="text-xs">
{tag}
</Badge>
<button
key={index}
onClick={(e) => {
e.stopPropagation();
onTagClick?.(tag);
}}
className="text-sm text-primary hover:text-primary/80 hover:underline transition-colors font-medium"
>
#{tag}
</button>
))}
{repo.repoTags.length > 3 && (
<Badge variant="secondary" className="text-xs">
<span className="text-sm text-muted-foreground">
+{repo.repoTags.length - 3}
</Badge>
</span>
)}
</div>
)}
@@ -212,6 +335,31 @@ export function RepositoryCard({ repo }: RepositoryCardProps) {
repoIdentifier={repo.repoId}
onSuccess={handleRepoEditSuccess}
/>
{/* Event Viewer Dialog */}
<Dialog open={eventViewerOpen} onOpenChange={setEventViewerOpen}>
<DialogContent className="max-w-2xl max-h-[80vh] flex flex-col">
<DialogHeader>
<DialogTitle>Repository Event</DialogTitle>
</DialogHeader>
<div className="overflow-y-auto flex-1 min-h-0">
<pre className="text-xs p-4 rounded-lg overflow-x-auto">
{JSON.stringify({
id: repo.id,
pubkey: repo.pubkey,
created_at: repo.created_at,
kind: repo.kind,
tags: repo.tags,
content: repo.content,
sig: repo.sig,
}, null, 2)}
</pre>
</div>
</DialogContent>
</Dialog>
</Card>
);
}
// Memoize to prevent re-renders when parent re-renders with same props
export const RepositoryCard = memo(RepositoryCardInner);
+4 -12
View File
@@ -39,14 +39,12 @@ describe('SentryProvider', () => {
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseCurator: '',
showcaseModerator: '',
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
plausibleDomain: '',
plausibleEndpoint: '',
};
render(
@@ -83,14 +81,12 @@ describe('SentryProvider', () => {
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseCurator: '',
showcaseModerator: '',
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
plausibleDomain: '',
plausibleEndpoint: '',
};
render(
@@ -128,14 +124,12 @@ describe('SentryProvider', () => {
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseCurator: '',
showcaseModerator: '',
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
plausibleDomain: '',
plausibleEndpoint: '',
};
render(
@@ -176,14 +170,12 @@ describe('SentryProvider', () => {
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseCurator: '',
showcaseModerator: '',
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
plausibleDomain: '',
plausibleEndpoint: '',
};
render(
+31 -164
View File
@@ -1,20 +1,13 @@
import { useState, useCallback, memo, useRef, useEffect } from 'react';
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 { Command, CommandGroup, CommandItem, CommandList } from '@/components/ui/command';
import { Square, ArrowUp } from 'lucide-react';
import { ModelSelector } from '@/components/ModelSelector';
export interface SlashCommand {
name: string;
description: string;
action: () => void;
}
interface ChatInputProps {
isLoading: boolean;
isConfigured: boolean;
@@ -36,7 +29,6 @@ interface ChatInputProps {
onDragOver: (e: React.DragEvent) => void;
onDragLeave: (e: React.DragEvent) => void;
onDrop: (e: React.DragEvent) => void;
slashCommands?: SlashCommand[];
}
export const ChatInput = memo(function ChatInput({
@@ -60,15 +52,10 @@ export const ChatInput = memo(function ChatInput({
onDragOver,
onDragLeave,
onDrop,
slashCommands = [],
}: ChatInputProps) {
const { t } = useTranslation();
const [input, setInput] = useState('');
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const [showSlashCommands, setShowSlashCommands] = useState(false);
const [filteredCommands, setFilteredCommands] = useState<SlashCommand[]>([]);
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const handleFileSelect = useCallback((file: File) => {
setAttachedFiles(prev => [...prev, file]);
@@ -91,110 +78,16 @@ export const ChatInput = memo(function ChatInput({
onSend(currentInput, currentFiles);
}, [input, attachedFiles, isLoading, isConfigured, providerModel, onSend]);
const executeSlashCommand = useCallback((command: SlashCommand) => {
setInput('');
setShowSlashCommands(false);
setSelectedCommandIndex(0);
command.action();
}, []);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
// Handle arrow key navigation when slash commands are showing
if (showSlashCommands && filteredCommands.length > 0) {
if (e.key === 'ArrowDown') {
e.preventDefault();
setSelectedCommandIndex(prev =>
prev < filteredCommands.length - 1 ? prev + 1 : 0
);
return;
}
if (e.key === 'ArrowUp') {
e.preventDefault();
setSelectedCommandIndex(prev =>
prev > 0 ? prev - 1 : filteredCommands.length - 1
);
return;
}
// If slash commands are showing and user presses Enter or Tab, select the highlighted command
if ((e.key === 'Enter' && !e.shiftKey) || e.key === 'Tab') {
e.preventDefault();
executeSlashCommand(filteredCommands[selectedCommandIndex]);
return;
}
// If slash commands are showing and user presses Escape, close the popover
if (e.key === 'Escape') {
e.preventDefault();
setShowSlashCommands(false);
setSelectedCommandIndex(0);
return;
}
}
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}, [handleSend, showSlashCommands, filteredCommands, selectedCommandIndex, executeSlashCommand]);
}, [handleSend]);
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
const value = e.target.value;
setInput(value);
// Check if slash command autocomplete should be shown
if (value.startsWith('/') && !value.includes(' ') && slashCommands.length > 0) {
const query = value.slice(1).toLowerCase();
const filtered = slashCommands.filter(cmd =>
cmd.name.toLowerCase().includes(query)
);
setFilteredCommands(filtered);
setShowSlashCommands(filtered.length > 0);
setSelectedCommandIndex(0); // Reset selection when filtering
} else {
setShowSlashCommands(false);
setSelectedCommandIndex(0);
}
}, [slashCommands]);
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
// Call parent's drop handler for visual state management
onDrop(e);
// Extract files from the drop event
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
// Add all files without validation
setAttachedFiles(prev => [...prev, ...files]);
}, [onDrop]);
// Close popover when clicking outside
useEffect(() => {
if (!showSlashCommands) return;
const handleClickOutside = (e: MouseEvent) => {
// Check if click is outside the popover and textarea
const target = e.target as Node;
if (textareaRef.current && !textareaRef.current.contains(target)) {
setShowSlashCommands(false);
}
};
// Use a slight delay to avoid closing immediately on focus
const timeoutId = setTimeout(() => {
document.addEventListener('click', handleClickOutside);
}, 100);
return () => {
clearTimeout(timeoutId);
document.removeEventListener('click', handleClickOutside);
};
}, [showSlashCommands]);
setInput(e.target.value);
}, []);
return (
<div className="border-t p-4">
@@ -206,61 +99,35 @@ export const ChatInput = memo(function ChatInput({
onDragEnter={onDragEnter}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={handleDrop}
onDrop={onDrop}
>
<div className="relative">
<Textarea
ref={textareaRef}
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
onFocus={onFocus}
placeholder={
!isConfigured
<Textarea
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
onFocus={onFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: providerModel.trim()
? 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={isLoadingSettings || (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';
}}
/>
{showSlashCommands && filteredCommands.length > 0 && (
<div className="absolute bottom-full left-0 mb-2 w-80 rounded-lg border bg-popover p-0 text-popover-foreground shadow-md z-50">
<Command value={filteredCommands[selectedCommandIndex]?.name}>
<CommandList>
<CommandGroup>
{filteredCommands.map((command) => (
<CommandItem
key={command.name}
value={command.name}
onSelect={() => executeSlashCommand(command)}
className="cursor-pointer"
>
<div className="flex flex-col gap-1">
<div className="font-medium">/{command.name}</div>
<div className="text-xs text-muted-foreground">{command.description}</div>
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</div>
)}
</div>
: 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={isLoadingSettings || (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">
+23 -118
View File
@@ -18,11 +18,9 @@ import { useMCPTools } from '@/hooks/useMCPTools';
import { useQueryClient } from '@tanstack/react-query';
import { AIMessageItem } from '@/components/AIMessageItem';
import { ToolCallDisplay } from '@/components/ToolCallDisplay';
import { ReadTool } from '@/lib/tools/ReadTool';
import { WriteTool } from '@/lib/tools/WriteTool';
import { EditTool } from '@/lib/tools/EditTool';
import { GlobTool } from '@/lib/tools/GlobTool';
import { GrepTool } from '@/lib/tools/GrepTool';
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
@@ -35,21 +33,13 @@ import { NostrReadProtocolTool } from '@/lib/tools/NostrReadProtocolTool';
import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
import { NostrPublishEventsTool } from '@/lib/tools/NostrPublishEventsTool';
import { NostrEncodeTool } from '@/lib/tools/NostrEncodeTool';
import { NostrDecodeTool } from '@/lib/tools/NostrDecodeTool';
import { BlossomUploadTool } from '@/lib/tools/BlossomUploadTool';
import { ShellTool } from '@/lib/tools/ShellTool';
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
import { SkillTool } from '@/lib/tools/SkillTool';
import { GenerateImageTool } from '@/lib/tools/GenerateImageTool';
import { ViewAvailableModelsTool } from '@/lib/tools/ViewAvailableModelsTool';
import { ConfigureImageGenerationTool } from '@/lib/tools/ConfigureImageGenerationTool';
import { WebFetchTool } from '@/lib/tools/WebFetchTool';
import { WebSearchTool } from '@/lib/tools/WebSearchTool';
import { createMCPTools } from '@/lib/tools/MCPTool';
import { TodoWriteTool } from '@/lib/tools/TodoWriteTool';
import { TodoReadTool } from '@/lib/tools/TodoReadTool';
import { AppTool } from '@/lib/tools/AppTool';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool';
@@ -57,13 +47,11 @@ import OpenAI from 'openai';
import { useGit } from '@/hooks/useGit';
import { Quilly } from '@/components/Quilly';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ChatInput, SlashCommand } from '@/components/Shakespeare/ChatInput';
import { ToolsDialog } from '@/components/Shakespeare/ToolsDialog';
import { ChatInput } from '@/components/Shakespeare/ChatInput';
import { buildMessageContent } from '@/lib/buildMessageContent';
import { DotAI } from '@/lib/DotAI';
import { parseProviderModel } from '@/lib/parseProviderModel';
import { AIMessage } from '@/lib/SessionManager';
import { getAllSkills } from '@/lib/skills';
// Clean interfaces now handled by proper hooks
@@ -103,15 +91,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const queryClient = useQueryClient();
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [isDragOver, setIsDragOver] = useState(false);
const scrolledProjectsRef = useRef(new Set<string>());
const shouldScrollToBottomRef = useRef(false);
const [scrolledProjects] = useState(() => new Set<string>());
const [showOnboarding, setShowOnboarding] = useState(false);
const [isStuck, setIsStuck] = useState(false);
const [aiError, setAIError] = useState<Error | null>(null);
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
const [showTemplateInfo, setShowTemplateInfo] = useState(false);
const [showToolsDialog, setShowToolsDialog] = useState(false);
const [availableSkills, setAvailableSkills] = useState<Array<{ name: string; description: string; path: string; plugin: string }>>([]);
// Determine which error to show - AI errors take priority over console errors
// since they are more immediately relevant to the user's current action
@@ -182,34 +167,16 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
queryClient.invalidateQueries({ queryKey: ['git-sync', cwd] });
}, [queryClient, cwd]);
// Load available skills
useEffect(() => {
const loadSkills = async () => {
const skills = await getAllSkills(fs, pluginsPath, cwd);
setAvailableSkills(skills);
};
loadSkills().catch(err => {
console.error('Failed to load skills:', err);
setAvailableSkills([]);
});
}, [fs, pluginsPath, cwd]);
// Fetch MCP tools
const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools();
// Separate built-in tools from MCP tools for clarity
const builtInTools = useMemo(() => {
const tools: Record<string, Tool<unknown>> = {
// File operation tools (OpenCode-compatible API)
read: new ReadTool(fs, cwd, { projectsPath }),
write: new WriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
edit: new EditTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
glob: new GlobTool(fs, cwd),
grep: new GrepTool(fs, cwd),
// Other tools
git_commit: new GitCommitTool(fs, cwd, git, { onCommit: handleCommit }),
text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }),
text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
npm_add_package: new NpmAddPackageTool(fs, cwd),
npm_remove_package: new NpmRemovePackageTool(fs, cwd),
build_project: new BuildProjectTool(fs, cwd, esmUrlRef.current),
@@ -221,23 +188,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
nostr_read_nips_index: new NostrReadNipsIndexTool(),
nostr_generate_kind: new NostrGenerateKindTool(),
nostr_publish_events: new NostrPublishEventsTool(),
nostr_encode: new NostrEncodeTool(),
nostr_decode: new NostrDecodeTool(),
blossom_upload: new BlossomUploadTool(fs, cwd, user?.signer),
shell: new ShellTool(fs, cwd, git, config.corsProxy, user?.signer),
read_console_messages: new ReadConsoleMessagesTool(),
skill: new SkillTool(fs, availableSkills),
webfetch: new WebFetchTool({ corsProxy: config.corsProxy }),
websearch: new WebSearchTool(),
todowrite: new TodoWriteTool(fs, projectId, { projectsPath }),
todoread: new TodoReadTool(fs, projectId, { projectsPath }),
app: new AppTool(
fs,
cwd,
user?.signer,
user?.pubkey,
config.relayMetadata.relays.filter(r => r.write).map(r => r.url),
),
skill: new SkillTool(fs, pluginsPath, cwd),
};
// Add generate_image tool if imageModel is configured
@@ -289,7 +242,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return tools;
}, [fs, git, cwd, user, projectsPath, tmpPath, config.corsProxy, config.relayMetadata, settings, aiSettings, models, handleFileChanged, handleCommit, projectId, availableSkills]);
}, [fs, git, cwd, user, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit]);
// MCP tools wrapped for execution
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
@@ -536,46 +489,30 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
useEffect(() => {
if (scrollAreaRef.current && (messages || streamingMessage)) {
// Check if user was already at or near the bottom (within 100px threshold)
const threshold = 100;
const container = scrollAreaRef.current;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
// Auto-scroll if:
// 1. User just sent a message (shouldScrollToBottomRef is true), OR
// 2. User was already near the bottom
if (shouldScrollToBottomRef.current || isNearBottom) {
// Double requestAnimationFrame ensures scroll happens after layout and paint
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
});
});
shouldScrollToBottomRef.current = false; // Reset the flag
// Only auto-scroll if user was already near the bottom
if (isNearBottom) {
container.scrollTop = container.scrollHeight;
}
}
}, [messages, streamingMessage, isLoading]);
// Remove project from scrolled set when loading starts (so it can scroll again after loading)
useEffect(() => {
if (isLoadingHistory) {
scrolledProjectsRef.current.delete(projectId);
}
}, [projectId, isLoadingHistory]);
// Scroll to bottom when first visiting a project (including page refresh)
useEffect(() => {
if (projectId && !scrolledProjectsRef.current.has(projectId) && !isLoadingHistory && messages.length > 0) {
// Use double RAF to ensure DOM is fully rendered after isLoadingHistory becomes false
requestAnimationFrame(() => {
requestAnimationFrame(() => {
scrollToBottom();
scrolledProjectsRef.current.add(projectId);
});
});
if (projectId && !scrolledProjects.has(projectId)) {
// Small delay to ensure messages have loaded
const timer = setTimeout(() => {
scrollToBottom();
scrolledProjects.add(projectId);
}, 100);
return () => clearTimeout(timer);
}
}, [projectId, isLoadingHistory, messages.length, scrollToBottom]);
}, [projectId, scrolledProjects, scrollToBottom]);
// Drag and drop handlers
const handleDragEnter = useCallback((e: React.DragEvent) => {
@@ -640,9 +577,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
// Mark that we should scroll to bottom when the message is added
shouldScrollToBottomRef.current = true;
await sendMessage(messageContent, modelToUse);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
@@ -665,23 +599,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}, [onFirstInteraction]);
// Slash commands
const slashCommands: SlashCommand[] = [
{
name: 'new',
description: 'Start a new chat session',
action: () => {
internalStartNewSession();
onNewChat();
},
},
{
name: 'tools',
description: "View the current session's available tools",
action: () => setShowToolsDialog(true),
},
];
// Expose startNewSession function via ref
useImperativeHandle(ref, () => ({
startNewSession: () => {
@@ -701,7 +618,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
key="streaming-message"
message={streamingMessage}
isCurrentlyLoading={isLoading}
projectId={projectId}
/>
)}
{/* Show tool call in "calling" state if streaming tool call is in progress */}
@@ -717,7 +633,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
})()}
state="calling"
projectId={projectId}
/>
) : (
<>
@@ -754,7 +669,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
})()}
state="waiting"
projectId={projectId}
/>
);
}
@@ -886,7 +800,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
message={message}
toolCall={toolCall}
projectId={projectId}
/>
);
})}
@@ -959,7 +872,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
slashCommands={slashCommands}
/>
{/* Onboarding Dialog */}
@@ -967,13 +879,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
open={showOnboarding}
onOpenChange={setShowOnboarding}
/>
{/* Tools Dialog */}
<ToolsDialog
open={showToolsDialog}
onOpenChange={setShowToolsDialog}
tools={tools}
/>
</div>
);
});
+175 -386
View File
@@ -1,5 +1,5 @@
import { encodeBase64 } from '@std/encoding/base64';
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS';
@@ -10,14 +10,17 @@ 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, Loader2, Code, X, Terminal, Expand, Shrink, Hammer, RefreshCw } from 'lucide-react';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Loader2, Code, X, Terminal, Expand, Shrink, Hammer } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BranchSwitcher } from '@/components/BranchSwitcher';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
import { type DeviceMode } from '@/components/ui/device-toggle';
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
import type { ImperativePanelHandle } from 'react-resizable-panels';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
@@ -25,8 +28,6 @@ import { Terminal as TerminalComponent } from '@/components/Terminal';
import { useSearchParams } from 'react-router-dom';
import { useAppContext } from '@/hooks/useAppContext';
import { isMediaFile } from '@/lib/fileUtils';
import { deriveIframeSubdomain } from '@/lib/iframeSubdomain';
import { getPreviewInjectedScript } from '@/lib/previewInjectedScript';
interface PreviewPaneProps {
projectId: string;
@@ -69,13 +70,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const { t } = useTranslation();
const { config } = useAppContext();
const { previewDomain } = config;
// Derive a private, stable subdomain from a device-local seed + the project ID.
// This prevents malicious project names from colliding with another project's
// origin on iframe.diy, protecting localStorage/IndexedDB isolation.
const previewSubdomain = useMemo(() => deriveIframeSubdomain('preview', projectId), [projectId]);
const previewOrigin = useMemo(() => `https://${previewSubdomain}.${previewDomain}`, [previewSubdomain, previewDomain]);
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [fileContent, setFileContent] = useState<string>('');
const [isLoading, setIsLoading] = useState(false);
@@ -83,24 +77,14 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const [desktopCodeView, setDesktopCodeView] = useState<'files' | 'terminal'>('files');
const isMobile = useIsMobile();
const [hasBuiltProject, setHasBuiltProject] = useState(false);
const [buildError, setBuildError] = useState<string | null>(null);
const [currentPath, setCurrentPath] = useState('/');
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
const [historyIndex, setHistoryIndex] = useState(0);
const [isFullscreen, setIsFullscreen] = useState(false);
const [deviceMode, setDeviceMode] = useState<DeviceMode>('laptop');
const [isLogsOpen, setIsLogsOpen] = useState(false);
// Incremented to force a full remount of the preview iframe. Using a
// remount (via React key) is more reliable than sending a `refresh`
// JSON-RPC to the nested iframe.diy frames: messages can be silently
// dropped if the inner iframe is mid-reload, not yet mounted, or if
// the outer frame's handshake is still pending. A remount always works.
const [iframeReloadKey, setIframeReloadKey] = useState(0);
const previewContainerRef = useRef<HTMLDivElement>(null);
const iframeRef = useRef<HTMLIFrameElement>(null);
const iframePanelRef = useRef<ImperativePanelHandle>(null);
const logsPanelRef = useRef<ImperativePanelHandle>(null);
const { fs } = useFS();
const { projectsPath } = useFSPaths();
const projectsManager = useProjectsManager();
@@ -193,19 +177,34 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}
}, [projectId, projectsManager]);
// Legacy refresh function for build completion events
const refreshIframeLegacy = useCallback(() => {
if (iframeRef.current) {
// Force reload the iframe by updating its src
iframeRef.current.src = '/';
// Use a small timeout to ensure the src is cleared before setting it back
setTimeout(() => {
if (iframeRef.current) {
iframeRef.current.src = `https://${projectId}.${previewDomain}/`;
}
}, 10);
}
}, [projectId, previewDomain]);
const sendResponse = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [previewOrigin]);
}, [projectId, previewDomain]);
const sendError = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [previewOrigin]);
}, [projectId, previewDomain]);
const handleConsoleMessage = useCallback((message: {
jsonrpc: '2.0';
@@ -260,17 +259,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}
}, [historyIndex, navigationHistory]);
const sendNotification = useCallback((method: string, params?: Record<string, unknown>) => {
if (iframeRef.current?.contentWindow) {
const message = {
jsonrpc: '2.0' as const,
method,
params: params || {},
};
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
}
}, [previewOrigin]);
const sendNavigationCommand = useCallback((method: string, params?: Record<string, unknown>) => {
if (iframeRef.current?.contentWindow) {
const message = {
@@ -279,9 +267,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
params: params || {},
id: Date.now()
};
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [previewOrigin]);
}, [projectId, previewDomain]);
const navigateIframe = useCallback((url: string) => {
// Send semantic path directly (e.g., "/about", "/contact")
@@ -290,31 +279,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}, [sendNavigationCommand]);
const refreshIframe = useCallback(() => {
// Force a full remount of the iframe rather than sending a `refresh`
// JSON-RPC command. The RPC path is unreliable during rapid build
// cycles because the command has to traverse two iframes (outer
// iframe.diy frame → inner app iframe) and can be silently dropped
// if the inner iframe is mid-reload, not yet mounted, or the outer
// frame's handshake is still pending.
setIframeReloadKey((n) => n + 1);
}, []);
sendNavigationCommand('refresh');
}, [sendNavigationCommand]);
const toggleFullscreen = useCallback(() => {
setIsFullscreen(prev => !prev);
}, []);
/** Virtual path where the injected preview script is served. */
const INJECTED_SCRIPT_PATH = '/__injected__/preview.js';
/** Inject a script tag into an HTML string using DOMParser. */
const injectScript = useCallback((html: string): string => {
const doc = new DOMParser().parseFromString(html, 'text/html');
const tag = doc.createElement('script');
tag.src = INJECTED_SCRIPT_PATH;
doc.head.insertBefore(tag, doc.head.firstChild);
return '<!DOCTYPE html>\n' + doc.documentElement.outerHTML;
}, []);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
const { request: fetchRequest } = params;
@@ -322,15 +293,16 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
try {
// Parse the URL and validate origin
const url = new URL(fetchRequest.url);
const expectedOrigin = `https://${projectId}.${previewDomain}`;
if (url.origin !== previewOrigin) {
console.log(`Invalid origin: ${url.origin}, expected: ${previewOrigin}`);
if (url.origin !== expectedOrigin) {
console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`);
sendError({
jsonrpc: '2.0',
error: {
code: -32003,
message: 'Invalid URL - origin mismatch',
data: { url: fetchRequest.url, expectedOrigin: previewOrigin }
data: { url: fetchRequest.url, expectedOrigin }
},
id
});
@@ -340,52 +312,24 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const path = url.pathname;
const filePath = path;
// Serve the injected preview script at its virtual path
if (path === INJECTED_SCRIPT_PATH) {
sendResponse({
jsonrpc: '2.0',
result: {
status: 200,
statusText: 'OK',
headers: {
'Content-Type': 'application/javascript',
'Cache-Control': 'no-cache',
},
body: encodeBase64(new TextEncoder().encode(getPreviewInjectedScript())),
},
id
});
return;
}
// Skip SPA fallback for static assets (files with extensions)
const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path);
// SPA routing: try to serve the exact file first
try {
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
const contentType = getContentType(filePath);
console.log(`Serving file: ${filePath}`);
// Inject preview script into HTML responses
let body: string;
if (contentType === 'text/html') {
const html = new TextDecoder().decode(bytes);
body = encodeBase64(new TextEncoder().encode(injectScript(html)));
} else {
body = encodeBase64(bytes);
}
sendResponse({
jsonrpc: '2.0',
result: {
status: 200,
statusText: 'OK',
headers: {
'Content-Type': contentType,
'Content-Type': getContentType(filePath),
'Cache-Control': 'no-cache',
},
body,
body: encodeBase64(bytes),
},
id
});
@@ -416,10 +360,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
console.log(`Serving index.html fallback for: ${path}`);
// Inject preview script into SPA fallback HTML
const html = new TextDecoder().decode(bytes);
const body = encodeBase64(new TextEncoder().encode(injectScript(html)));
sendResponse({
jsonrpc: '2.0',
result: {
@@ -429,7 +369,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
'Content-Type': 'text/html',
'Cache-Control': 'no-cache',
},
body,
body: encodeBase64(bytes),
},
id
});
@@ -460,37 +400,32 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
id
});
}
}, [projectId, projectsManager, sendResponse, sendError, previewOrigin, injectScript]);
}, [projectId, projectsManager, sendResponse, sendError, previewDomain]);
// Setup messaging protocol for iframe communication
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
// Verify origin for security
if (event.origin !== previewOrigin) {
const expectedOrigin = `https://${projectId}.${previewDomain}`;
if (event.origin !== expectedOrigin) {
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
return;
}
const message = event.data;
if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0') return;
// Handle iframe.diy handshake: respond to "ready" with "init"
if (message.method === 'ready') {
sendNotification('init', { version: 1 });
return;
}
if (message.method === 'fetch') {
console.log('Received message from iframe:', message);
if (message.jsonrpc === '2.0' && message.method === 'fetch') {
handleFetch(message);
} else if (message.method === 'console') {
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
handleConsoleMessage(message);
} else if (message.method === 'updateNavigationState') {
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
handleUpdateNavigationState(message);
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, sendNotification, previewOrigin]);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
useEffect(() => {
if (selectedFile) {
@@ -505,7 +440,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
setFileContent('');
setMobileCodeView('explorer');
setDesktopCodeView('files');
setBuildError(null);
// Reset navigation history and state
setCurrentPath('/');
@@ -530,13 +464,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
console.log('Build completed for project, refreshing preview');
// Check for built project and refresh iframe
checkForBuiltProject();
refreshIframe();
refreshIframeLegacy();
}
};
window.addEventListener('buildComplete', handleBuildComplete as EventListener);
return () => window.removeEventListener('buildComplete', handleBuildComplete as EventListener);
}, [projectId, checkForBuiltProject, refreshIframe]);
}, [projectId, checkForBuiltProject, refreshIframeLegacy]);
const handleFileSelect = (filePath: string) => {
setSelectedFile(filePath);
@@ -566,48 +500,106 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}
};
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
const [copiedAll, setCopiedAll] = useState(false);
const [copiedBuildError, setCopiedBuildError] = useState(false);
const ConsoleDropdown = () => {
const [isOpen, setIsOpen] = useState(false);
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
const messages = isLogsOpen ? getConsoleMessages() : [];
const messages = isOpen ? getConsoleMessages() : [];
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
try {
await navigator.clipboard.writeText(msg.message);
setCopiedMessageIndex(index);
setTimeout(() => setCopiedMessageIndex(null), 2000);
} catch (error) {
console.error('Failed to copy message to clipboard:', error);
}
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
try {
await navigator.clipboard.writeText(msg.message);
setCopiedMessageIndex(index);
setTimeout(() => setCopiedMessageIndex(null), 2000);
} catch (error) {
console.error('Failed to copy message to clipboard:', error);
}
};
const messageCount = messages.length;
return (
<Popover open={isOpen} onOpenChange={setIsOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 gap-2 relative"
>
<Bug className="h-4 w-4" />
<span className="hidden lg:inline">Logs</span>
{hasConsoleErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)}
</Button>
</PopoverTrigger>
<PopoverContent
align="end"
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0 z-[9999]"
sideOffset={4}
>
{/* Messages */}
<div className="h-[60vh] max-h-[512px] w-full bg-background text-foreground font-mono text-xs relative overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
<div className="py-2 px-1 space-y-0">
{messageCount === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-center">
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
</div>
) : (
messages.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"
onClick={(e) => {
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
>
<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.message}
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
>
{copiedMessageIndex === index ? (
<Check className="h-2 w-2 text-success" />
) : (
<Copy className="h-2 w-2" />
)}
</Button>
</div>
))
)}
</div>
</div>
{/* Close button */}
<button
onClick={() => setIsOpen(false)}
className="absolute top-2 right-2 h-8 w-8 p-0 bg-muted/50 hover:bg-muted/70 rounded-md z-10 flex items-center justify-center border"
>
<X className="h-5 w-5 text-muted-foreground" />
</button>
</PopoverContent>
</Popover>
);
};
const copyAllMessagesToClipboard = async () => {
try {
const allMessages = messages.map(msg => msg.message).join('\n');
await navigator.clipboard.writeText(allMessages);
setCopiedAll(true);
setTimeout(() => setCopiedAll(false), 2000);
} catch (error) {
console.error('Failed to copy all messages to clipboard:', error);
}
};
const messageCount = messages.length;
// Programmatically resize panels when isLogsOpen changes
useEffect(() => {
if (isLogsOpen) {
// Open logs panel to 40% and resize iframe to 60%
logsPanelRef.current?.resize(40);
iframePanelRef.current?.resize(60);
} else {
// Close logs panel and expand iframe to 100%
logsPanelRef.current?.resize(0);
iframePanelRef.current?.resize(100);
}
}, [isLogsOpen]);
return (
<div className="h-full">
<Tabs value={activeTab} className="h-full">
@@ -664,7 +656,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
})}
disabled={isBuildLoading}
className="h-8 gap-2"
title={t('buildButtonTooltip')}
title="Build project"
>
{isBuildLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
@@ -679,248 +671,45 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
size="sm"
onClick={onToggleView}
className="h-8 gap-2"
title={t('codeButtonTooltip')}
>
<Code className="h-4 w-4" />
<span className="hidden lg:inline">Code</span>
</Button>
)}
<Button
variant="ghost"
size="sm"
onClick={() => setIsLogsOpen(!isLogsOpen)}
className={cn("h-8 gap-2 relative", isLogsOpen && "bg-muted")}
title={t('logsButtonTooltip')}
>
<Bug className="h-4 w-4" />
<span className="hidden lg:inline">Logs</span>
{hasConsoleErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)}
</Button>
<ConsoleDropdown />
</div>
</div>
{/* Content area */}
<div className="flex-1 bg-muted/30 min-h-0 overflow-hidden">
<ResizablePanelGroup direction="vertical" className="h-full">
<ResizablePanel
ref={iframePanelRef}
defaultSize={isLogsOpen ? 60 : 100}
minSize={30}
className="min-h-0"
<div className="flex-1 flex items-center justify-center bg-muted/30">
{hasBuiltProject ? (
<div
className={cn(
"h-full transition-all duration-300 ease-in-out bg-background",
deviceMode === 'laptop' && "w-full",
deviceMode === 'tablet' && "w-full max-w-3xl shadow-lg",
deviceMode === 'phone' && "w-full max-w-sm shadow-lg"
)}
>
<div className="h-full flex items-center justify-center min-h-0">
{hasBuiltProject ? (
<div
className={cn(
"h-full transition-all duration-300 ease-in-out bg-background",
deviceMode === 'laptop' && "w-full",
deviceMode === 'tablet' && "w-full max-w-3xl shadow-lg",
deviceMode === 'phone' && "w-full max-w-sm shadow-lg"
)}
>
<iframe
key={`${projectId}:${iframeReloadKey}`}
ref={iframeRef}
src={`${previewOrigin}/`}
className="w-full h-full border-0"
title="Project Preview"
/>
</div>
) : (
<div className="h-full w-full flex items-center justify-center bg-muted p-4">
<div className="text-center space-y-4 max-w-2xl w-full">
<div>
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground">
{t('buildProjectToSeePreview')}
</p>
</div>
{buildError && (
<div className="bg-destructive/10 border border-destructive/20 rounded-lg overflow-hidden text-left">
<div className="px-4 py-2 bg-destructive/20 border-b border-destructive/20 flex items-center justify-between">
<p className="font-semibold text-destructive text-sm">Build Failed</p>
<Button
variant="ghost"
size="sm"
onClick={async () => {
try {
await navigator.clipboard.writeText(buildError);
setCopiedBuildError(true);
setTimeout(() => setCopiedBuildError(false), 2000);
} catch (error) {
console.error('Failed to copy error to clipboard:', error);
}
}}
className="h-7 px-2 text-xs hover:bg-destructive/10"
>
{copiedBuildError ? (
<>
<Check className="h-3 w-3 mr-1.5" />
Copied
</>
) : (
<>
<Copy className="h-3 w-3 mr-1.5" />
Copy
</>
)}
</Button>
</div>
<ScrollArea className="max-h-48">
<div className="overflow-x-auto">
<pre className="p-4 text-xs font-mono text-destructive whitespace-pre leading-relaxed">{buildError}</pre>
</div>
<ScrollBar orientation="horizontal" />
</ScrollArea>
</div>
)}
<Button
variant="outline"
onClick={() => {
setBuildError(null);
buildProject(undefined, {
onSuccess: () => {
setBuildError(null);
},
onError: (error) => {
console.error('Build failed:', error);
setBuildError(error instanceof Error ? error.message : String(error));
}
});
}}
disabled={isBuildLoading}
className="gap-2"
>
{isBuildLoading ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Building...
</>
) : buildError ? (
<>
<RefreshCw className="h-4 w-4" />
Retry
</>
) : (
<>
<Hammer className="h-4 w-4" />
Build
</>
)}
</Button>
</div>
</div>
)}
<iframe
key={projectId}
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin allow-forms"
/>
</div>
) : (
<div className="h-full w-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground">
{t('buildProjectToSeePreview')}
</p>
</div>
</ResizablePanel>
<ResizableHandle withHandle className={cn(!isLogsOpen && "hidden")} />
<ResizablePanel
ref={logsPanelRef}
defaultSize={isLogsOpen ? 40 : 0}
minSize={0}
maxSize={isLogsOpen ? undefined : 0}
className="min-h-0 min-w-0"
collapsible
collapsedSize={0}
>
{/* Logs Panel */}
<div className="h-full flex flex-col bg-background border-t overflow-hidden min-h-0 w-full min-w-0">
{/* Logs Header */}
<div className="h-12 px-4 border-b flex items-center justify-between flex-shrink-0">
<div className="flex items-center gap-2">
{hasConsoleErrors && (
<span className="h-2 w-2 rounded-full bg-red-500" />
)}
</div>
<div className="flex items-center gap-2">
{messageCount > 0 && (
<Button
variant="ghost"
size="sm"
onClick={copyAllMessagesToClipboard}
className="h-7 px-2 text-xs"
>
{copiedAll ? (
<>
<Check className="h-3 w-3 mr-1.5 text-success" />
{t('copied')}
</>
) : (
<>
<Copy className="h-3 w-3 mr-1.5" />
{t('copyAll')}
</>
)}
</Button>
)}
<Button
variant="ghost"
size="sm"
onClick={() => setIsLogsOpen(false)}
className="h-7 w-7 p-0"
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
{/* Logs Content */}
<div className="flex-1 min-h-0 overflow-hidden w-full">
<ScrollArea className="h-full w-full">
<div className="p-2 space-y-0 w-full min-w-0 max-w-full">
{messageCount === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-center">
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
</div>
) : (
messages.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 w-full max-w-full"
onClick={(e) => {
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
>
<div
className={cn(
"text-xs font-mono leading-tight whitespace-pre-wrap break-words w-full min-w-0 max-w-full",
msg.level === 'error' ? "text-destructive" :
msg.level === 'warn' ? "text-warning" :
msg.level === 'info' ? "text-primary" :
"text-muted-foreground"
)}
style={{ wordBreak: 'break-word', overflowWrap: 'break-word' }}
>
{msg.message}
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
>
{copiedMessageIndex === index ? (
<Check className="h-2 w-2 text-success" />
) : (
<Copy className="h-2 w-2" />
)}
</Button>
</div>
))
)}
</div>
</ScrollArea>
</div>
</div>
</ResizablePanel>
</ResizablePanelGroup>
</div>
)}
</div>
{/* Build loading overlay */}
Loaded 100 of 245 files, more files were not shown because too many files have changed in this diff. Show more