Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a72eec2966 | ||
|
|
278b7cd3b2 | ||
|
|
a824677fe2 | ||
|
|
0eb8693d10 | ||
|
|
9557356ff5 | ||
|
|
dbbdcc32eb | ||
|
|
acde1d8a3a | ||
|
|
5d02627cff | ||
|
|
317c923532 | ||
|
|
18815f0649 | ||
|
|
98985c29de | ||
|
|
ba422b2d9e | ||
|
|
9313d2e0ee | ||
|
|
0013ece013 | ||
|
|
0da339c214 | ||
|
|
6f3cc62e00 | ||
|
|
5484a57f08 | ||
|
|
09059d87ec | ||
|
|
b9b297d832 | ||
|
|
4ca7e20011 | ||
|
|
e4c4e617c6 | ||
|
|
10edacbccb | ||
|
|
7e93367b5f | ||
|
|
b3fddf6cb3 | ||
|
|
376a982449 | ||
|
|
258dce35d2 | ||
|
|
b2bd91780b | ||
|
|
2335395641 | ||
|
|
af2436a3b8 | ||
|
|
1fd3d23d4f | ||
|
|
b2c5b1d81e | ||
|
|
a7d026e51a | ||
|
|
dd078ed17d | ||
|
|
695a697e88 | ||
|
|
7eab377b7f | ||
|
|
6da4b63a85 | ||
|
|
565ae93aed | ||
|
|
429dafce92 | ||
|
|
49889be240 | ||
|
|
c285dbcd05 | ||
|
|
b80205a942 | ||
|
|
50f85f232d | ||
|
|
c5605c9be8 | ||
|
|
33564842d0 | ||
|
|
0511976688 | ||
|
|
819813a000 | ||
|
|
2736f71687 | ||
|
|
0a2cbf4bca | ||
|
|
c359eda1d6 | ||
|
|
269047d742 | ||
|
|
d2673effd8 | ||
|
|
c49564e70d | ||
|
|
63671ea85b | ||
|
|
46fefd5352 | ||
|
|
13dd307292 | ||
|
|
271013f834 | ||
|
|
31fcb60cd3 | ||
|
|
6bec129e93 | ||
|
|
5f56652479 | ||
|
|
be458ece7b | ||
|
|
1d6ad575f6 | ||
|
|
68c51fb48f | ||
|
|
a81b8420f5 | ||
|
|
ddc1e02431 | ||
|
|
8f9ce95a43 | ||
|
|
d015887338 | ||
|
|
b7e7f5420a | ||
|
|
9daccc1947 | ||
|
|
c3f1cbc50a | ||
|
|
612759ed64 | ||
|
|
b2cfcd7e17 | ||
|
|
08357aa694 | ||
|
|
c23a79dfb0 | ||
|
|
5102028f6b | ||
|
|
18191e3a27 | ||
|
|
b1b451072b | ||
|
|
5d9bc40f51 | ||
|
|
a644994e93 | ||
|
|
ac0e13a09a | ||
|
|
0565eb7aab | ||
|
|
e40504ebc6 | ||
|
|
7ccf9ddcc9 | ||
|
|
4976493be3 | ||
|
|
3192ae7f08 | ||
|
|
e2d615c2c1 | ||
|
|
2ddfa66d9b | ||
|
|
1566a67da4 | ||
|
|
6ff25096d4 | ||
|
|
222b27c8c8 | ||
|
|
43fec2a462 | ||
|
|
a9e3e81195 | ||
|
|
b270651a9c | ||
|
|
5b302cc40b | ||
|
|
3db9848497 | ||
|
|
b0e85aaa60 |
No files matched your search
@@ -27,7 +27,7 @@ Follow these steps in order. Do NOT skip any step.
|
||||
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://shakespeare.diy/** -- Shakespeare product page
|
||||
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.
|
||||
|
||||
|
||||
@@ -3,11 +3,19 @@ image: node:25
|
||||
default:
|
||||
interruptible: true
|
||||
timeout: 1 minute
|
||||
cache:
|
||||
key:
|
||||
files:
|
||||
- package-lock.json
|
||||
paths:
|
||||
- node_modules/
|
||||
|
||||
stages:
|
||||
- test
|
||||
- deploy
|
||||
- build
|
||||
- release
|
||||
- publish
|
||||
|
||||
test:
|
||||
stage: test
|
||||
@@ -20,23 +28,168 @@ test:
|
||||
- npm run build
|
||||
- npm run test
|
||||
|
||||
pages:
|
||||
deploy:
|
||||
stage: deploy
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG
|
||||
when: never
|
||||
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
|
||||
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH && $DEPLOY_SSH_KEY && $DEPLOY_TARGET
|
||||
script:
|
||||
- npm ci
|
||||
- npm run build
|
||||
- rm -rf public
|
||||
- mv dist public
|
||||
- cp dist/index.html dist/404.html
|
||||
- apt-get update -qq && apt-get install -y --no-install-recommends rsync openssh-client >/dev/null
|
||||
- mkdir -p ~/.ssh && chmod 700 ~/.ssh
|
||||
- echo "$DEPLOY_SSH_KEY" | tr -d '\r' > ~/.ssh/id_ed25519 && chmod 600 ~/.ssh/id_ed25519
|
||||
- ssh-keyscan -H "${DEPLOY_TARGET##*@}" >> ~/.ssh/known_hosts 2>/dev/null
|
||||
- rsync -av --exclude=/sw.js --exclude=/index.html -e "ssh -i ~/.ssh/id_ed25519" dist/ "${DEPLOY_TARGET}:/"
|
||||
- rsync -av -e "ssh -i ~/.ssh/id_ed25519" dist/index.html "${DEPLOY_TARGET}:/"
|
||||
- rsync -av -e "ssh -i ~/.ssh/id_ed25519" dist/sw.js "${DEPLOY_TARGET}:/"
|
||||
|
||||
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:
|
||||
- public
|
||||
- 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:
|
||||
@@ -54,3 +207,37 @@ 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
|
||||
@@ -42,6 +42,7 @@ Shakespeare provides AI agents with specialized tools for project development (n
|
||||
- **TextEditorWriteTool**: Create or overwrite files with new content
|
||||
- **TextEditorStrReplaceTool**: Replace strings in files
|
||||
- **BuildProjectTool**: Build and compile projects
|
||||
- **TypecheckProjectTool**: Typecheck projects with the TypeScript compiler, similar to `tsc --noEmit`
|
||||
- **NpmAddPackageTool**: Add npm packages to projects
|
||||
- **NpmRemovePackageTool**: Remove npm packages from projects
|
||||
- **GitCommitTool**: Commit changes to Git repositories
|
||||
@@ -67,7 +68,7 @@ Shakespeare provides a comprehensive set of shell commands that are JavaScript r
|
||||
- **File Operations**: `cat`, `cp`, `mv`, `rm`, `touch`, `find`, `grep`
|
||||
- **Directory Operations**: `cd`, `ls`, `mkdir`, `pwd`, `tree`
|
||||
- **System Commands**: `echo`, `which`, `wc`, `head`, `tail`
|
||||
- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, etc.
|
||||
- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, `git diff`, `git branch`, `git checkout`, `git switch`, `git merge`, `git revert`, `git rm`, `git mv`, `git restore`, `git rev-parse`, `git ls-files`, `git tag`, `git stash`, `git fetch`, `git clone`, `git init`, `git reset`, `git show`, `git remote`, `git config`
|
||||
|
||||
#### Security
|
||||
|
||||
@@ -77,6 +78,41 @@ AI filesystem access through tools (including shell commands via ShellTool) has
|
||||
- **Write operations**: Restricted to current project directory and `/tmp/` directory (including subdirectories)
|
||||
- **Copy operations**: Can copy from any absolute path to relative paths or `/tmp/`, but cannot copy from relative to absolute paths outside allowed areas
|
||||
|
||||
#### Web Workers and Asset URLs
|
||||
|
||||
Shakespeare's esbuild-wasm build pipeline supports the Vite/webpack-compatible patterns for loading Web Workers and static assets:
|
||||
|
||||
```ts
|
||||
// Module Worker (required: { type: 'module' })
|
||||
const worker = new Worker(
|
||||
new URL('./worker.ts', import.meta.url),
|
||||
{ type: 'module' },
|
||||
);
|
||||
|
||||
// SharedWorker, same pattern
|
||||
const shared = new SharedWorker(
|
||||
new URL('./shared.ts', import.meta.url),
|
||||
{ type: 'module' },
|
||||
);
|
||||
|
||||
// Static asset URL (images, wasm, fonts, audio, etc.)
|
||||
const logoUrl = new URL('./logo.svg', import.meta.url);
|
||||
```
|
||||
|
||||
**Supported:**
|
||||
- `new Worker(new URL('<spec>', import.meta.url), { type: 'module' })`
|
||||
- `new SharedWorker(new URL('<spec>', import.meta.url), { type: 'module' })`
|
||||
- `new URL('<spec>', import.meta.url)` where `<spec>` resolves to a non-source file (images, wasm, audio, fonts, etc.)
|
||||
- Relative (`./`, `../`), absolute (`/`), and alias (`@/`) specifiers
|
||||
- String literals with any quote style, including backticks without interpolation
|
||||
|
||||
**Not supported (will emit a build error):**
|
||||
- Classic (non-module) workers — `{ type: 'module' }` is required
|
||||
- Dynamic specifiers — the first argument to `new URL()` must be a string literal
|
||||
- `new URL(..., import.meta.url)` pointing at source files (`.ts/.tsx/.js/.jsx/.mjs/.cjs/.css`); use a regular import or the Worker pattern instead (emits a console warning, then leaves the expression untouched)
|
||||
|
||||
Workers are bundled as separate ESM chunks and can import from npm packages normally — the same ESM-CDN rewrites applied to the main bundle apply to workers. When any workers are emitted, the build also extends the output CSP's `worker-src` and `child-src` directives to permit loading the ESM CDN from within workers.
|
||||
|
||||
### Git Integration with isomorphic-git
|
||||
|
||||
Shakespeare provides full Git functionality in the browser using `isomorphic-git` and `@isomorphic-git/lightning-fs`, with all data persisted in IndexedDB.
|
||||
@@ -236,7 +272,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- Unix-style commands: `cat`, `cd`, `cp`, `find`, `grep`, `ls`, `mkdir`, `mv`, `rm`, etc.
|
||||
- `/src/lib/tools/`: AI tool implementations for project development
|
||||
- File operations: `TextEditorViewTool`, `TextEditorWriteTool`, `TextEditorStrReplaceTool`
|
||||
- Project tools: `BuildProjectTool`
|
||||
- Project tools: `BuildProjectTool`, `TypecheckProjectTool`
|
||||
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
|
||||
- Git integration: `GitCommitTool`
|
||||
- Shell access: `ShellTool`
|
||||
|
||||
@@ -1,5 +1,122 @@
|
||||
# Changelog
|
||||
|
||||
## [9.14.0] - 2026-06-05
|
||||
|
||||
### Added
|
||||
- Log in with a remote signer by scanning a QR code — connect your NIP-46 mobile signer to Shakespeare without copying and pasting bunker strings
|
||||
|
||||
### Changed
|
||||
- Unified the login dialog into a single, streamlined experience across sign-in methods
|
||||
|
||||
### Fixed
|
||||
- Custom fonts now load correctly in previews instead of triggering a runtime error
|
||||
- Builds no longer fail when a project depends on types-only packages
|
||||
- Resolved all known security vulnerabilities in dependencies
|
||||
|
||||
## [9.13.2] - 2026-04-29
|
||||
|
||||
### Changed
|
||||
- Preview pane now uses the new iframe.diy sandboxing service for a faster, more reliable preview experience
|
||||
|
||||
## [9.13.1] - 2026-04-27
|
||||
|
||||
### Changed
|
||||
- AI agents now run commands through a real POSIX-style shell with proper quoting, pipes, redirects, and glob expansion, making multi-step project edits more reliable
|
||||
- Overhauled the built-in `git` commands used by AI agents, adding `ls-files`, `merge`, `mv`, `restore`, `rev-parse`, `revert`, `rm`, and `switch` alongside improvements across existing git operations
|
||||
- Overhauled core shell commands (`cat`, `cp`, `find`, `grep`, `ls`, `sed`, `sort`, and more) for closer POSIX behavior and better ergonomics when AI agents work on your project
|
||||
|
||||
## [9.13.0] - 2026-04-26
|
||||
|
||||
### Added
|
||||
- Build projects with Tailwind CSS v4, including `@import "tailwindcss"` entry files and third-party v4 plugins like `tw-animate-css`
|
||||
|
||||
## [9.12.0] - 2026-04-25
|
||||
|
||||
### Added
|
||||
- Build support for module workers and static asset URLs — projects using `new Worker(new URL('./w.ts', import.meta.url), { type: 'module' })`, `SharedWorker`, and `new URL('./logo.svg', import.meta.url)` now build and run correctly in the preview
|
||||
- Preview pane grants microphone, ambient-light-sensor, and other device permissions so richer apps can run inside the preview
|
||||
|
||||
## [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
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# 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
|
||||
@@ -0,0 +1,28 @@
|
||||
<?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>
|
||||
@@ -0,0 +1,13 @@
|
||||
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
|
||||
@@ -0,0 +1,6 @@
|
||||
<?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>
|
||||
@@ -0,0 +1,2 @@
|
||||
/build/*
|
||||
!/build/.npmkeep
|
||||
@@ -0,0 +1,34 @@
|
||||
<?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>
|
||||
@@ -0,0 +1,2 @@
|
||||
connection.project.dir=..
|
||||
eclipse.preferences.version=1
|
||||
@@ -0,0 +1,73 @@
|
||||
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")
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// 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()
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
# 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
|
||||
@@ -0,0 +1,26 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?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>
|
||||
@@ -0,0 +1,5 @@
|
||||
package diy.shakespeare.app;
|
||||
|
||||
import com.getcapacitor.BridgeActivity;
|
||||
|
||||
public class MainActivity extends BridgeActivity {}
|
||||
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 57 KiB |
|
After Width: | Height: | Size: 79 KiB |
@@ -0,0 +1,82 @@
|
||||
<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>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?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>
|
||||
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,83 @@
|
||||
<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>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?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>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?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>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?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>
|
||||
|
After Width: | Height: | Size: 5.8 KiB |
|
After Width: | Height: | Size: 4.4 KiB |
|
After Width: | Height: | Size: 6.0 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 2.5 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 8.4 KiB |
|
After Width: | Height: | Size: 6.6 KiB |
|
After Width: | Height: | Size: 8.7 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 20 KiB |
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#2b0037</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?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>
|
||||
@@ -0,0 +1,23 @@
|
||||
<?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>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?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>
|
||||
@@ -0,0 +1,18 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// 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')
|
||||
@@ -0,0 +1,22 @@
|
||||
# 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
|
||||
@@ -0,0 +1,7 @@
|
||||
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
|
||||
@@ -0,0 +1,251 @@
|
||||
#!/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" "$@"
|
||||
@@ -0,0 +1,94 @@
|
||||
@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
|
||||
@@ -0,0 +1,5 @@
|
||||
include ':app'
|
||||
include ':capacitor-cordova-android-plugins'
|
||||
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
|
||||
|
||||
apply from: 'capacitor.settings.gradle'
|
||||
@@ -0,0 +1,16 @@
|
||||
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'
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
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;
|
||||
@@ -8,7 +8,7 @@ import htmlParser from "@html-eslint/parser";
|
||||
import customRules from "./eslint-rules/index.js";
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ["dist"] },
|
||||
{ ignores: ["dist", "android"] },
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ["**/*.{ts,tsx}"],
|
||||
|
||||
@@ -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.9.2",
|
||||
"version": "9.14.0",
|
||||
"type": "module",
|
||||
"author": {
|
||||
"name": "shakespeare.diy",
|
||||
@@ -17,9 +17,14 @@
|
||||
"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!'"
|
||||
"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"
|
||||
},
|
||||
"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",
|
||||
@@ -29,8 +34,8 @@
|
||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||
"@modelcontextprotocol/sdk": "^1.22.0",
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
"@nostrify/nostrify": "^0.49.2",
|
||||
"@nostrify/react": "^0.2.24",
|
||||
"@nostrify/nostrify": "^0.51.1",
|
||||
"@nostrify/react": "^0.4.1",
|
||||
"@opensecret/react": "^1.5.4",
|
||||
"@plausible-analytics/tracker": "^0.4.4",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
@@ -63,8 +68,11 @@
|
||||
"@sentry/react": "^10.22.0",
|
||||
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@typescript/ata": "^0.9.8",
|
||||
"@unhead/addons": "^2.0.10",
|
||||
"@unhead/react": "^2.0.10",
|
||||
"acorn": "^8.16.0",
|
||||
"acorn-jsx": "^5.3.2",
|
||||
"buffer": "^6.0.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
@@ -103,6 +111,7 @@
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"tailwindcss-safe-area": "^0.8.0",
|
||||
"turndown": "^7.2.1",
|
||||
"typescript": "^5.8.3",
|
||||
"uri-templates": "^0.2.0",
|
||||
"use-stick-to-bottom": "^1.1.1",
|
||||
"vaul": "^0.9.3",
|
||||
@@ -111,6 +120,8 @@
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"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",
|
||||
@@ -138,10 +149,9 @@
|
||||
"jsdom": "^26.1.0",
|
||||
"postcss": "^8.4.47",
|
||||
"tailwindcss": "^3.4.11",
|
||||
"typescript": "^5.5.3",
|
||||
"typescript-eslint": "^8.0.1",
|
||||
"vite": "^6.3.5",
|
||||
"vite-plugin-pwa": "^1.1.0",
|
||||
"vitest": "^3.1.4"
|
||||
"vitest": "^4.1.8"
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,122 @@
|
||||
# Changelog
|
||||
|
||||
## [9.14.0] - 2026-06-05
|
||||
|
||||
### Added
|
||||
- Log in with a remote signer by scanning a QR code — connect your NIP-46 mobile signer to Shakespeare without copying and pasting bunker strings
|
||||
|
||||
### Changed
|
||||
- Unified the login dialog into a single, streamlined experience across sign-in methods
|
||||
|
||||
### Fixed
|
||||
- Custom fonts now load correctly in previews instead of triggering a runtime error
|
||||
- Builds no longer fail when a project depends on types-only packages
|
||||
- Resolved all known security vulnerabilities in dependencies
|
||||
|
||||
## [9.13.2] - 2026-04-29
|
||||
|
||||
### Changed
|
||||
- Preview pane now uses the new iframe.diy sandboxing service for a faster, more reliable preview experience
|
||||
|
||||
## [9.13.1] - 2026-04-27
|
||||
|
||||
### Changed
|
||||
- AI agents now run commands through a real POSIX-style shell with proper quoting, pipes, redirects, and glob expansion, making multi-step project edits more reliable
|
||||
- Overhauled the built-in `git` commands used by AI agents, adding `ls-files`, `merge`, `mv`, `restore`, `rev-parse`, `revert`, `rm`, and `switch` alongside improvements across existing git operations
|
||||
- Overhauled core shell commands (`cat`, `cp`, `find`, `grep`, `ls`, `sed`, `sort`, and more) for closer POSIX behavior and better ergonomics when AI agents work on your project
|
||||
|
||||
## [9.13.0] - 2026-04-26
|
||||
|
||||
### Added
|
||||
- Build projects with Tailwind CSS v4, including `@import "tailwindcss"` entry files and third-party v4 plugins like `tw-animate-css`
|
||||
|
||||
## [9.12.0] - 2026-04-25
|
||||
|
||||
### Added
|
||||
- Build support for module workers and static asset URLs — projects using `new Worker(new URL('./w.ts', import.meta.url), { type: 'module' })`, `SharedWorker`, and `new URL('./logo.svg', import.meta.url)` now build and run correctly in the preview
|
||||
- Preview pane grants microphone, ambient-light-sensor, and other device permissions so richer apps can run inside the preview
|
||||
|
||||
## [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
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
#!/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)"
|
||||
@@ -1,3 +1,9 @@
|
||||
# Shakespeare Services
|
||||
|
||||
This directory contains additional microservices that can be optionally deployed alongside Shakespeare to host a complete Shakespeare instance.
|
||||
This directory contains additional microservices that can be optionally deployed alongside Shakespeare to host a complete Shakespeare instance.
|
||||
|
||||
## Preview Iframe Service
|
||||
|
||||
Shakespeare uses [iframe.diy](https://iframe.diy/) to sandbox project previews on an isolated origin, protecting the main app's `localStorage` and `IndexedDB` from untrusted preview code. The default `previewDomain` in the app config is `iframe.diy`.
|
||||
|
||||
To self-host the iframe preview service, deploy [soapbox-pub/iframe.diy](https://gitlab.com/soapbox-pub/iframe.diy) on your own domain and set `previewDomain` accordingly.
|
||||
@@ -1,394 +0,0 @@
|
||||
# iframe Fetch Client Messaging Protocol (JSON-RPC)
|
||||
|
||||
This document describes the simplified JSON-RPC based communication protocol
|
||||
between the parent page and the iframe fetch client.
|
||||
|
||||
## Overview
|
||||
|
||||
The iframe fetch client uses JSON-RPC 2.0 over `postMessage` for communication.
|
||||
The ServiceWorker makes JSON-RPC calls directly, with the main thread acting as
|
||||
a relay between the ServiceWorker and parent page. The only required method is
|
||||
`fetch` for handling HTTP requests.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────┐ JSON-RPC over ┌──────────────────────┐
|
||||
│ Parent Page │ postMessage │ Main Thread │
|
||||
│ │ ←─────────────────→ │ (relay only) │
|
||||
│ - Request │ │ │
|
||||
│ handling │ │ ↕ │
|
||||
└─────────────────┘ │ JSON-RPC over │
|
||||
│ postMessage │
|
||||
│ │
|
||||
│ ┌──────────────────┐ │
|
||||
│ │ ServiceWorker │ │
|
||||
│ │ │ │
|
||||
│ │ - Makes JSON-RPC │ │
|
||||
│ │ calls directly │ │
|
||||
│ │ - Handles │ │
|
||||
│ │ requests │ │
|
||||
│ └──────────────────┘ │
|
||||
└──────────────────────┘
|
||||
```
|
||||
|
||||
## JSON-RPC Structure
|
||||
|
||||
All messages follow JSON-RPC 2.0 specification:
|
||||
|
||||
```javascript
|
||||
// GET Request
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "fetch",
|
||||
"params": {
|
||||
"request": {
|
||||
"url": "https://app123.example.com/assets/main.js",
|
||||
"method": "GET",
|
||||
"headers": {
|
||||
"Accept": "application/javascript"
|
||||
},
|
||||
"body": null
|
||||
}
|
||||
},
|
||||
"id": 123
|
||||
}
|
||||
|
||||
// POST Request with JSON body
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "fetch",
|
||||
"params": {
|
||||
"request": {
|
||||
"url": "https://app123.example.com/api/data",
|
||||
"method": "POST",
|
||||
"headers": {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
"body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 encoded: {"name":"John","age":30}
|
||||
}
|
||||
},
|
||||
"id": 124
|
||||
}
|
||||
|
||||
// Success Response
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"result": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": {
|
||||
"Content-Type": "application/javascript",
|
||||
"Cache-Control": "no-cache"
|
||||
},
|
||||
"body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7" // base64 encoded: console.log('hello');
|
||||
},
|
||||
"id": 123
|
||||
}
|
||||
|
||||
// Error Response (still uses JSON-RPC error format for protocol errors)
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"error": {
|
||||
"code": -32001,
|
||||
"message": "Invalid request format",
|
||||
"data": { "url": "/assets/main.js" }
|
||||
},
|
||||
"id": 123
|
||||
}
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
### `fetch`
|
||||
|
||||
**Purpose:** Handle HTTP requests, including GET, POST, PUT, DELETE, etc. with
|
||||
full request body support
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `request` (object): Serialized fetch request
|
||||
- `url` (string): Full URL of the request
|
||||
- `method` (string): HTTP method (GET, POST, etc.)
|
||||
- `headers` (object): Request headers as key-value pairs
|
||||
- `body` (string|null): Request body as base64 encoded string, or null if no body
|
||||
|
||||
**Result:**
|
||||
|
||||
- `status` (number): HTTP status code (200, 404, etc.)
|
||||
- `statusText` (string): HTTP status text ("OK", "Not Found", etc.)
|
||||
- `headers` (object): Response headers as key-value pairs
|
||||
- `body` (string|null): Response body content as base64 encoded string (null if status is 204)
|
||||
|
||||
**Error Codes:**
|
||||
|
||||
- `-32001`: Invalid request format
|
||||
- `-32002`: Request processing error
|
||||
- `-32003`: Invalid URL
|
||||
|
||||
**Request Body Support:** The system fully supports request bodies, enabling:
|
||||
|
||||
- POST/PUT requests with JSON data
|
||||
- Form submissions
|
||||
- API calls with payloads
|
||||
- File uploads (as base64 strings)
|
||||
- Any HTTP method with body content
|
||||
|
||||
Request bodies must be base64-encoded strings when not null. This ensures
|
||||
consistent handling of both text and binary data across the messaging protocol.
|
||||
|
||||
### `console`
|
||||
|
||||
**Purpose:** Forward console messages from iframe to parent for display
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `level` (string): Log level - "log", "warn", "error", "info", "debug"
|
||||
- `message` (string): The log message
|
||||
|
||||
**Result:** None (notification only, no response expected)
|
||||
|
||||
### Navigation Methods
|
||||
|
||||
#### `navigate`
|
||||
**Purpose:** Navigate iframe to a new URL within the same origin
|
||||
**Parameters:** `url` (string) - Target URL (must be same origin)
|
||||
**Result:** None (notification only)
|
||||
|
||||
#### `refresh`
|
||||
**Purpose:** Refresh/reload the current page in the iframe
|
||||
**Parameters:** None
|
||||
**Result:** None (notification only)
|
||||
|
||||
#### `updateNavigationState`
|
||||
**Purpose:** Update parent about iframe's current navigation state
|
||||
**Parameters:**
|
||||
- `currentUrl` (string) - Current URL of the iframe
|
||||
- `canGoBack` (boolean) - Whether iframe can go back in history
|
||||
- `canGoForward` (boolean) - Whether iframe can go forward in history
|
||||
**Result:** None (notification only)
|
||||
|
||||
## Implementation
|
||||
|
||||
### Parent Page
|
||||
|
||||
The parent page acts as a static file server and console log collector:
|
||||
|
||||
```javascript
|
||||
class FetchClientParent {
|
||||
constructor(files) {
|
||||
this.files = files; // Map of path -> {content, contentType}
|
||||
this.consoleLogs = []; // Store console messages
|
||||
this.setupMessageListener();
|
||||
}
|
||||
|
||||
setupMessageListener() {
|
||||
window.addEventListener("message", (event) => {
|
||||
// Verify origin for security
|
||||
if (event.origin !== "https://app123.example.com") return;
|
||||
|
||||
const message = event.data;
|
||||
|
||||
// Handle fetch requests
|
||||
if (message.jsonrpc === "2.0" && message.method === "fetch") {
|
||||
this.handleFetch(message);
|
||||
}
|
||||
|
||||
// Handle console messages
|
||||
if (message.jsonrpc === "2.0" && message.method === "console") {
|
||||
this.handleConsoleMessage(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
handleConsoleMessage(message) {
|
||||
const { params } = message;
|
||||
const { level, message: logMessage } = params;
|
||||
|
||||
// Store the log message
|
||||
this.consoleLogs.push({
|
||||
level,
|
||||
message: logMessage,
|
||||
timestamp: Date.now(),
|
||||
id: Date.now()
|
||||
});
|
||||
|
||||
// Update UI to show new logs
|
||||
this.updateConsoleUI();
|
||||
|
||||
// Also log to parent's console for debugging
|
||||
console[level](`[IFRAME] ${logMessage}`);
|
||||
}
|
||||
|
||||
updateConsoleUI() {
|
||||
// Implementation depends on your UI framework
|
||||
console.log(`Total console logs: ${this.consoleLogs.length}`);
|
||||
}
|
||||
|
||||
handleFetch(request) {
|
||||
const { params, id } = request;
|
||||
const { request: fetchRequest } = params;
|
||||
|
||||
// Extract path from URL
|
||||
const url = new URL(fetchRequest.url);
|
||||
const path = url.pathname;
|
||||
|
||||
const file = this.files.get(path);
|
||||
|
||||
if (file) {
|
||||
this.sendResponse({
|
||||
id,
|
||||
jsonrpc: "2.0",
|
||||
result: {
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: {
|
||||
"Content-Type": file.contentType,
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
body: btoa(file.content),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
this.sendResponse({
|
||||
id,
|
||||
jsonrpc: "2.0",
|
||||
result: {
|
||||
status: 404,
|
||||
statusText: "Not Found",
|
||||
headers: {
|
||||
"Content-Type": "text/plain",
|
||||
},
|
||||
body: btoa(`File not found: ${path}`),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
sendResponse(message) {
|
||||
const iframe = document.getElementById("preview-iframe");
|
||||
iframe.contentWindow.postMessage(message, "https://app123.example.com");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### iframe Client Communication
|
||||
|
||||
The iframe client uses a simplified JSON-RPC client for communication. In the actual implementation, the ServiceWorker makes requests and the main thread acts as a relay:
|
||||
|
||||
```javascript
|
||||
// Simplified JSON-RPC client (actual implementation in _iframe-client/main.js)
|
||||
class JSONRPCClient {
|
||||
constructor() {
|
||||
this.requestId = 0;
|
||||
this.pendingRequests = new Map();
|
||||
this.setupMessageListener();
|
||||
}
|
||||
|
||||
setupMessageListener() {
|
||||
window.addEventListener("message", (event) => {
|
||||
const message = event.data;
|
||||
if (message.jsonrpc === "2.0" && message.id !== undefined) {
|
||||
this.handleResponse(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fetch(request) {
|
||||
const id = ++this.requestId;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.pendingRequests.set(id, { resolve, reject });
|
||||
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "fetch",
|
||||
params: { request },
|
||||
id,
|
||||
}, "*");
|
||||
|
||||
setTimeout(() => {
|
||||
if (this.pendingRequests.has(id)) {
|
||||
this.pendingRequests.delete(id);
|
||||
reject(new Error(`Timeout fetching: ${request.url}`));
|
||||
}
|
||||
}, 10000);
|
||||
});
|
||||
}
|
||||
|
||||
handleResponse(message) {
|
||||
const { id, result, error } = message;
|
||||
const pending = this.pendingRequests.get(id);
|
||||
|
||||
if (!pending) return;
|
||||
|
||||
this.pendingRequests.delete(id);
|
||||
|
||||
if (error) {
|
||||
pending.reject(new Error(`${error.message} (code: ${error.code})`));
|
||||
} else {
|
||||
pending.resolve(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Base64 Encoding
|
||||
|
||||
All request and response bodies are base64 encoded when not null to ensure proper transmission through JSON-RPC:
|
||||
|
||||
- **Consistent Data Handling:** Both text and binary data are handled uniformly
|
||||
- **JSON Compatibility:** Avoids issues with special characters in JSON messages
|
||||
- **Binary Data Support:** Enables transmission of images, files, and other binary content
|
||||
|
||||
**Encoding/Decoding:**
|
||||
```javascript
|
||||
// Encoding text content (parent side)
|
||||
const encodedBody = btoa(textContent);
|
||||
|
||||
// Encoding binary content (ServiceWorker side)
|
||||
const bytes = new Uint8Array(arrayBuffer);
|
||||
const encodedBody = btoa(String.fromCharCode(...bytes));
|
||||
|
||||
// Decoding (receiver side)
|
||||
const decodedText = atob(encodedBody);
|
||||
const decodedBytes = new Uint8Array(atob(encodedBody).split('').map(c => c.charCodeAt(0)));
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
- **Origin Validation:** Always verify message origin
|
||||
- **Path Validation:** Validate file paths to prevent directory traversal
|
||||
- **Timeout:** Requests timeout after 10 seconds
|
||||
- **Error Handling:** Proper JSON-RPC error responses
|
||||
|
||||
## Example Usage
|
||||
|
||||
```html
|
||||
<iframe
|
||||
id="preview-iframe"
|
||||
src="https://app123.example.com"
|
||||
sandbox="allow-scripts allow-same-origin"
|
||||
>
|
||||
</iframe>
|
||||
|
||||
<script>
|
||||
const files = new Map([
|
||||
["/", {
|
||||
content: "<!DOCTYPE html><html><body>Hello world!</body></html>",
|
||||
contentType: "text/html",
|
||||
}],
|
||||
["/app.js", {
|
||||
content: "console.log('App loaded');",
|
||||
contentType: "application/javascript",
|
||||
}],
|
||||
]);
|
||||
|
||||
// Initialize the fetch client parent
|
||||
new FetchClientParent(files);
|
||||
</script>
|
||||
```
|
||||
|
||||
## Console Logging Implementation
|
||||
|
||||
The iframe client automatically intercepts console messages and forwards them to the parent. The implementation (in `_iframe-client/main.js`) overrides console methods.
|
||||
@@ -1,365 +0,0 @@
|
||||
# iframe Fetch Client
|
||||
|
||||
An iframe preview system for **Single Page Applications (SPAs)**.
|
||||
|
||||
## Why?
|
||||
|
||||
We want to display a preview of a project built with Vite, Webpack, etc in an
|
||||
iframe, but the SPA uses root-relative paths (like `/assets/main.js`). This
|
||||
means we can't just load it directly from a file system or a local server
|
||||
without deploying it to a web server.
|
||||
|
||||
To work around this, we can instead deploy this "iframe Fetch Client" to a
|
||||
subdomain, embed it in an iframe, and then respond to its `postMessage` requests
|
||||
from the parent to serve it the files it needs.
|
||||
|
||||
This "iframe Fetch Client" is entirely static files, and only needs to be
|
||||
deployed once. As long as the parent page implements its JSON-RPC protocol, it
|
||||
can serve any web application.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────┐ JSON-RPC over ┌──────────────────────┐
|
||||
│ Parent Page │ postMessage │ iframe Client │
|
||||
│ (example.com) │ ←─────────────────→ │ (*.example.com) │
|
||||
│ │ fetch() │ │
|
||||
│ - Request │ │ ┌──────────────────┐ │
|
||||
│ handling │ │ │ Main Thread │ │
|
||||
└─────────────────┘ │ │ (relay only) │ │
|
||||
│ │ ↕ │ │
|
||||
│ │ JSON-RPC over │ │
|
||||
│ │ postMessage │ │
|
||||
│ │ ↕ │ │
|
||||
│ │ ┌──────────────┐ │ │
|
||||
│ │ │ServiceWorker │ │ │
|
||||
│ │ │ │ │ │
|
||||
│ │ │- Makes │ │ │
|
||||
│ │ │ JSON-RPC │ │ │
|
||||
│ │ │ calls │ │ │
|
||||
│ │ │- Handles │ │ │
|
||||
│ │ │ requests │ │ │
|
||||
│ │ └──────────────┘ │ │
|
||||
│ └──────────────────┘ │
|
||||
└──────────────────────┘
|
||||
```
|
||||
|
||||
## Limitations
|
||||
|
||||
This system uses a ServiceWorker to serve requests, which means the preview site
|
||||
cannot itself register a ServiceWorker. If it tries, the attempt will be
|
||||
blocked.
|
||||
|
||||
## Files Structure
|
||||
|
||||
```
|
||||
/
|
||||
├── index.html # Main iframe client page
|
||||
├── _iframe-client/
|
||||
│ ├── main.js # Main coordination script
|
||||
│ └── client.css # Styles for the iframe client
|
||||
├── sw.js # ServiceWorker
|
||||
├── MESSAGING_PROTOCOL.md # Communication protocol docs
|
||||
└── README.md # This file
|
||||
```
|
||||
|
||||
## Simplified JSON-RPC Protocol
|
||||
|
||||
The system now uses a simplified JSON-RPC 2.0 protocol with two methods:
|
||||
|
||||
- **`fetch(request)`** - Handle HTTP requests with serialized fetch
|
||||
request/response
|
||||
- **`console(level, message)`** - Forward console messages from
|
||||
iframe to parent for display
|
||||
|
||||
**Request:**
|
||||
|
||||
```javascript
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "fetch",
|
||||
"params": {
|
||||
"request": {
|
||||
"url": "https://app123.example.com/assets/main.js",
|
||||
"method": "GET",
|
||||
"headers": {},
|
||||
"body": null
|
||||
}
|
||||
},
|
||||
"id": 123
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
|
||||
```javascript
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"result": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": {
|
||||
"Content-Type": "application/javascript"
|
||||
},
|
||||
"body": "console.log('hello');"
|
||||
},
|
||||
"id": 123
|
||||
}
|
||||
```
|
||||
|
||||
**Console Message:**
|
||||
|
||||
```javascript
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "console",
|
||||
"params": {
|
||||
"level": "error",
|
||||
"message": "Failed to load module"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
1. **Initialization:**
|
||||
- iframe client loads at `app123.example.com`
|
||||
- Registers ServiceWorker at `/sw.js` with scope `/`
|
||||
- Blocks future ServiceWorker registrations
|
||||
- Main thread sets up relay between ServiceWorker and parent
|
||||
|
||||
2. **Request Handling:**
|
||||
- ServiceWorker intercepts all requests (except iframe client system files)
|
||||
- ServiceWorker makes JSON-RPC `fetch()` calls directly with serialized
|
||||
requests
|
||||
- Main thread relays JSON-RPC messages between ServiceWorker and parent
|
||||
- Parent responds with serialized HTTP responses
|
||||
- ServiceWorker creates Response objects and returns them to the client app
|
||||
|
||||
3. **SPA Routing Support:**
|
||||
- ServiceWorker detects navigation requests (HTML page requests with `mode: "navigate"`)
|
||||
- For SPA routes like `/about`, `/contact`, etc., the ServiceWorker serves the site's `index.html`
|
||||
- This allows the SPA's client-side router to handle the route properly
|
||||
- All other requests (assets, API calls, etc.) are handled normally via JSON-RPC
|
||||
|
||||
4. **Semantic Path Navigation:**
|
||||
- **Key Concept**: iframe stays on base URL (`/`) while communicating semantic paths to parent
|
||||
- When user navigates to `/about` in address bar, iframe doesn't actually change URL
|
||||
- Instead, NavigationHandler tracks semantic path (`/about`) and communicates it to parent
|
||||
- Parent displays semantic path while iframe remains on base URL
|
||||
- SPA's client-side router handles navigation internally without page reloads
|
||||
- This prevents 404 errors from literal path navigation
|
||||
|
||||
5. **SPA Navigation Tracking:**
|
||||
- NavigationHandler overrides `history.pushState()` and `history.replaceState()` to detect SPA navigation
|
||||
- When SPAs change URLs via history methods, NavigationHandler detects the change and sends navigation state to parent
|
||||
- Navigation state includes semantic path, back/forward capability, and history tracking
|
||||
- Parent can display current semantic path and enable proper back/forward navigation controls
|
||||
|
||||
6. **Content Replacement:**
|
||||
- Main thread requests `/` from parent via JSON-RPC fetch
|
||||
- Replaces its own content with the site index
|
||||
- Site runs normally, with all requests handled by SW via JSON-RPC
|
||||
|
||||
## Deployment
|
||||
|
||||
### iframe Client Domain (`*.example.com`)
|
||||
|
||||
Deploy these files to your iframe client subdomain:
|
||||
|
||||
```
|
||||
https://*.example.com/
|
||||
├── index.html
|
||||
├── _iframe-client/
|
||||
│ ├── main.js
|
||||
│ └── client.css
|
||||
└── sw.js
|
||||
```
|
||||
|
||||
**Security Note:** It is recommended to serve the client on a wildcard subdomain
|
||||
(like `*.example.com`) if you wish to support multiple projects. That way
|
||||
projects won't share the same localStorage and IndexedDB.
|
||||
|
||||
### Parent Page Integration
|
||||
|
||||
Include the iframe client in your parent page:
|
||||
|
||||
```html
|
||||
<iframe
|
||||
id="preview-iframe"
|
||||
src="https://app123.example.com/"
|
||||
sandbox="allow-scripts allow-same-origin"
|
||||
>
|
||||
</iframe>
|
||||
```
|
||||
|
||||
Implement the JSON-RPC protocol:
|
||||
|
||||
```javascript
|
||||
class FetchClientParent {
|
||||
constructor(files) {
|
||||
this.files = files; // Map of path -> {content, contentType}
|
||||
this.setupMessageListener();
|
||||
}
|
||||
|
||||
setupMessageListener() {
|
||||
window.addEventListener("message", (event) => {
|
||||
if (event.origin !== "https://example.com") return;
|
||||
|
||||
const message = event.data;
|
||||
if (message.jsonrpc === "2.0" && message.method === "fetch") {
|
||||
this.handleFetch(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
handleFetch(request) {
|
||||
const { params, id } = request;
|
||||
const { request: fetchRequest } = params;
|
||||
|
||||
// Extract path from URL
|
||||
const url = new URL(fetchRequest.url);
|
||||
const path = url.pathname;
|
||||
const file = this.files.get(path);
|
||||
|
||||
if (file) {
|
||||
this.sendResponse({
|
||||
id,
|
||||
jsonrpc: "2.0",
|
||||
result: {
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: {
|
||||
"Content-Type": file.contentType,
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
body: file.content,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Return 404 response
|
||||
this.sendResponse({
|
||||
id,
|
||||
jsonrpc: "2.0",
|
||||
result: {
|
||||
status: 404,
|
||||
statusText: "Not Found",
|
||||
headers: {
|
||||
"Content-Type": "text/plain",
|
||||
},
|
||||
body: `File not found: ${path}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
sendResponse(message) {
|
||||
const iframe = document.getElementById("preview-iframe");
|
||||
iframe.contentWindow.postMessage(message, "https://app123.example.com");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Request Handling
|
||||
|
||||
Handle requests by providing responses as a Map or object for static files, or
|
||||
implement custom logic for dynamic requests:
|
||||
|
||||
```javascript
|
||||
const staticFiles = new Map([
|
||||
["/", {
|
||||
content: "<!DOCTYPE html>...",
|
||||
contentType: "text/html",
|
||||
}],
|
||||
["/assets/main.js", {
|
||||
content: 'console.log("app");',
|
||||
contentType: "application/javascript",
|
||||
}],
|
||||
["/assets/style.css", {
|
||||
content: "body { margin: 0; }",
|
||||
contentType: "text/css",
|
||||
}],
|
||||
]);
|
||||
|
||||
// Or handle dynamic requests like APIs
|
||||
function handleRequest(fetchRequest) {
|
||||
const url = new URL(fetchRequest.url);
|
||||
|
||||
if (url.pathname.startsWith("/api/")) {
|
||||
// Handle API requests
|
||||
return handleAPIRequest(fetchRequest);
|
||||
} else {
|
||||
// Serve static files
|
||||
return serveStaticFile(url.pathname);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Security Features
|
||||
|
||||
- **Origin Validation:** Messages are validated by origin
|
||||
- **Sandboxed Iframe:** Client runs in a sandboxed environment
|
||||
- **Isolated ServiceWorker:** SW only affects the iframe client domain
|
||||
- **No Direct Access:** Parent controls all request handling
|
||||
|
||||
## Testing
|
||||
|
||||
1. Create a parent page implementing the JSON-RPC protocol (see example in MESSAGING_PROTOCOL.md)
|
||||
2. Load the iframe client in an iframe pointing to your deployed client domain
|
||||
3. The iframe client should load and display the served content
|
||||
4. Test navigation and functionality within the iframe client
|
||||
|
||||
## Browser Support
|
||||
|
||||
- **ServiceWorker:** Required (supported in all modern browsers)
|
||||
- **postMessage:** Required (universal support)
|
||||
- **iframe sandbox:** Recommended (modern browsers)
|
||||
|
||||
## Limitations
|
||||
|
||||
- Request/response bodies must be JSON-serializable strings (no binary support)
|
||||
- All requests go through the parent page (potential performance impact)
|
||||
- Requires HTTPS for ServiceWorker (except localhost)
|
||||
- Limited to same-origin communication patterns within the iframe
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### iframe client doesn't load
|
||||
|
||||
- Check browser console for ServiceWorker errors
|
||||
- Verify HTTPS is used (required for ServiceWorker)
|
||||
- Ensure parent page implements the messaging protocol
|
||||
|
||||
### Requests fail
|
||||
|
||||
- Check that request paths match your handling logic (case-sensitive)
|
||||
- Verify parent page is responding to JSON-RPC `fetch` requests
|
||||
- Check browser network tab for failed requests
|
||||
|
||||
### Communication issues
|
||||
|
||||
- Verify iframe src points to correct preview domain
|
||||
- Check that JSON-RPC messages are properly formatted
|
||||
- Ensure iframe has appropriate sandbox permissions
|
||||
|
||||
### SPA routes don't work
|
||||
|
||||
- Ensure the parent page serves the correct `index.html` for the root path `/`
|
||||
- Check that the SPA's client-side router is properly configured
|
||||
- Verify that navigation requests are being detected correctly by the ServiceWorker
|
||||
- Make sure the parent page returns the same `index.html` content for SPA routes as it does for the root path
|
||||
- **Important**: iframe should stay on base URL (`/`) while semantic paths are communicated to parent. If you see literal path navigation (iframe URL changing to `/about`), this indicates a configuration issue.
|
||||
|
||||
## Development
|
||||
|
||||
To modify the system:
|
||||
|
||||
1. **iframe Client:** Edit `index.html`, `_iframe-client/main.js`,
|
||||
`_iframe-client/client.css`, `sw.js`
|
||||
2. **Protocol:** Update `MESSAGING_PROTOCOL.md` for any changes
|
||||
3. **Testing:** Create a parent page implementing the JSON-RPC protocol for testing changes
|
||||
|
||||
## License
|
||||
|
||||
This system is designed for development and testing purposes. Ensure appropriate
|
||||
security measures for production use.
|
||||
@@ -1,39 +0,0 @@
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 20px;
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
|
||||
.loading {
|
||||
text-align: center;
|
||||
padding: 50px;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
border: 4px solid #f3f3f3;
|
||||
border-top: 4px solid #3498db;
|
||||
border-radius: 50%;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
animation: spin 2s linear infinite;
|
||||
margin: 0 auto 20px;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #e74c3c;
|
||||
background: #fdf2f2;
|
||||
border: 1px solid #fecaca;
|
||||
border-radius: 4px;
|
||||
padding: 15px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
@@ -1,562 +0,0 @@
|
||||
/**
|
||||
* iframe Fetch Client - Simplified Implementation
|
||||
* Implements JSON-RPC 2.0 messaging protocol per MESSAGING_PROTOCOL.md
|
||||
*/
|
||||
|
||||
// JSON-RPC Client for communication with parent
|
||||
class JSONRPCClient {
|
||||
constructor() {
|
||||
this.requestId = 0;
|
||||
this.pendingRequests = new Map();
|
||||
this.setupMessageListener();
|
||||
}
|
||||
|
||||
setupMessageListener() {
|
||||
window.addEventListener("message", (event) => {
|
||||
// Only accept messages from parent window for security
|
||||
if (event.source !== window.parent) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = event.data;
|
||||
// Check if this is a response to our own request or a ServiceWorker request
|
||||
if (message.jsonrpc === "2.0" && message.id !== undefined) {
|
||||
if (this.pendingRequests.has(message.id)) {
|
||||
this.handleResponse(message);
|
||||
} else {
|
||||
// This is a response to a ServiceWorker request, relay it back
|
||||
this.relayToServiceWorker(message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
relayToServiceWorker(response) {
|
||||
// Forward the JSON-RPC response to ServiceWorker
|
||||
if (navigator.serviceWorker.controller) {
|
||||
navigator.serviceWorker.controller.postMessage(response);
|
||||
}
|
||||
}
|
||||
|
||||
async fetch(request) {
|
||||
const id = ++this.requestId;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.pendingRequests.set(id, { resolve, reject });
|
||||
|
||||
// Send JSON-RPC request to parent
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "fetch",
|
||||
params: { request },
|
||||
id,
|
||||
}, "*");
|
||||
|
||||
// Timeout after 10 seconds
|
||||
setTimeout(() => {
|
||||
if (this.pendingRequests.has(id)) {
|
||||
this.pendingRequests.delete(id);
|
||||
reject(new Error(`Timeout fetching: ${request.url}`));
|
||||
}
|
||||
}, 10000);
|
||||
});
|
||||
}
|
||||
|
||||
handleResponse(message) {
|
||||
const { id, result, error } = message;
|
||||
const pending = this.pendingRequests.get(id);
|
||||
|
||||
if (!pending) return;
|
||||
|
||||
this.pendingRequests.delete(id);
|
||||
|
||||
if (error) {
|
||||
pending.reject(new Error(`${error.message} (code: ${error.code})`));
|
||||
} else {
|
||||
pending.resolve(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Console Interceptor - forwards console messages to parent
|
||||
class ConsoleInterceptor {
|
||||
constructor() {
|
||||
this.originalConsole = {};
|
||||
this.methods = ['log', 'warn', 'error', 'info', 'debug'];
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
// Store original methods and override in single pass
|
||||
this.methods.forEach((method) => {
|
||||
if (typeof console[method] === 'function') {
|
||||
this.originalConsole[method] = console[method];
|
||||
|
||||
console[method] = (...args) => {
|
||||
// Call original method
|
||||
try {
|
||||
this.originalConsole[method](...args);
|
||||
} catch (e) {
|
||||
// Continue if original fails
|
||||
}
|
||||
|
||||
// Send to parent
|
||||
this.sendConsoleMessage(method, ...args);
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
sendConsoleMessage(level, ...args) {
|
||||
const message = args.map((arg) => {
|
||||
if (arg === undefined) return 'undefined';
|
||||
if (arg === null) return 'null';
|
||||
if (typeof arg === 'object') {
|
||||
try {
|
||||
return JSON.stringify(arg, (key, value) => {
|
||||
if (value instanceof Error) {
|
||||
return {
|
||||
name: value.name,
|
||||
message: value.message,
|
||||
stack: value.stack
|
||||
};
|
||||
}
|
||||
return value;
|
||||
});
|
||||
} catch {
|
||||
return String(arg);
|
||||
}
|
||||
}
|
||||
return String(arg);
|
||||
}).join(' ');
|
||||
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "console",
|
||||
params: { level, message }
|
||||
}, "*");
|
||||
} catch (error) {
|
||||
// Retry once after delay if postMessage fails
|
||||
setTimeout(() => {
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "console",
|
||||
params: { level: "error", message: `[DELAYED] ${message}` }
|
||||
}, "*");
|
||||
} catch {
|
||||
// Give up if retry fails
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Navigation Handler - manages iframe navigation and history
|
||||
class NavigationHandler {
|
||||
constructor() {
|
||||
// Get initial path from window property or default to root
|
||||
this.currentSemanticPath = window.__IFRAME_INITIAL_PATH__ || '/';
|
||||
|
||||
this.setupMessageListener();
|
||||
this.setupHistoryListeners();
|
||||
this.overrideHistoryMethods();
|
||||
this.updateNavigationState();
|
||||
}
|
||||
|
||||
// Extract semantic path from URL or string
|
||||
extractSemanticPath(urlOrString) {
|
||||
try {
|
||||
const url = typeof urlOrString === 'string'
|
||||
? new URL(urlOrString, window.location.origin)
|
||||
: urlOrString;
|
||||
return url.pathname + url.search + url.hash;
|
||||
} catch {
|
||||
return window.location.pathname + window.location.search + window.location.hash;
|
||||
}
|
||||
}
|
||||
|
||||
setupMessageListener() {
|
||||
window.addEventListener("message", (event) => {
|
||||
// Only accept messages from parent window for security
|
||||
if (event.source !== window.parent) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = event.data;
|
||||
if (message.jsonrpc === "2.0") {
|
||||
switch (message.method) {
|
||||
case "navigate":
|
||||
this.handleNavigate(message.params.url);
|
||||
break;
|
||||
case "refresh":
|
||||
this.handleRefresh();
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
setupHistoryListeners() {
|
||||
// Listen for popstate events (back/forward navigation)
|
||||
window.addEventListener('popstate', () => {
|
||||
this.currentSemanticPath = this.extractSemanticPath(window.location);
|
||||
this.updateNavigationState();
|
||||
});
|
||||
|
||||
// Listen for hash changes
|
||||
window.addEventListener('hashchange', () => {
|
||||
this.currentSemanticPath = this.extractSemanticPath(window.location);
|
||||
this.updateNavigationState();
|
||||
});
|
||||
}
|
||||
|
||||
overrideHistoryMethods() {
|
||||
// Override history.pushState and history.replaceState to detect SPA navigation
|
||||
this.originalPushState = window.history.pushState;
|
||||
this.originalReplaceState = window.history.replaceState;
|
||||
|
||||
window.history.pushState = (...args) => {
|
||||
const result = this.originalPushState.apply(window.history, args);
|
||||
|
||||
// Extract semantic path from URL argument or use current location
|
||||
const semanticPath = args[2]
|
||||
? this.extractSemanticPath(args[2])
|
||||
: this.extractSemanticPath(window.location);
|
||||
|
||||
this.currentSemanticPath = semanticPath;
|
||||
this.updateNavigationState();
|
||||
return result;
|
||||
};
|
||||
|
||||
window.history.replaceState = (...args) => {
|
||||
const result = this.originalReplaceState.apply(window.history, args);
|
||||
|
||||
const semanticPath = args[2]
|
||||
? this.extractSemanticPath(args[2])
|
||||
: this.extractSemanticPath(window.location);
|
||||
|
||||
this.currentSemanticPath = semanticPath;
|
||||
this.updateNavigationState();
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
handleNavigate(url) {
|
||||
try {
|
||||
// Validate URL - must be same origin
|
||||
const targetUrl = new URL(url, window.location.origin);
|
||||
if (targetUrl.origin !== window.location.origin) {
|
||||
console.error('Navigation to different origin not allowed:', url);
|
||||
return;
|
||||
}
|
||||
|
||||
const semanticPath = this.extractSemanticPath(targetUrl);
|
||||
this.currentSemanticPath = semanticPath;
|
||||
this.updateNavigationState();
|
||||
|
||||
// Trigger SPA navigation
|
||||
window.history.pushState({}, '', semanticPath);
|
||||
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
|
||||
|
||||
} catch (error) {
|
||||
console.error('Invalid navigation URL:', url, error);
|
||||
}
|
||||
}
|
||||
|
||||
handleRefresh() {
|
||||
// Store current semantic path for reload
|
||||
const currentPath = this.currentSemanticPath || '/';
|
||||
|
||||
// Save the current path to sessionStorage so it persists across reload
|
||||
try {
|
||||
sessionStorage.setItem('iframe_initial_path', currentPath);
|
||||
} catch (error) {
|
||||
console.warn('Failed to store initial path in sessionStorage:', error);
|
||||
}
|
||||
|
||||
// Actually reload the iframe to get a fresh SPA instance
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
updateNavigationState() {
|
||||
// Use tracked semantic path, fallback to current location if needed
|
||||
const semanticPath = this.currentSemanticPath || this.extractSemanticPath(window.location);
|
||||
|
||||
const state = {
|
||||
currentUrl: semanticPath,
|
||||
canGoBack: false, // Let parent handle history tracking
|
||||
canGoForward: false // Let parent handle history tracking
|
||||
};
|
||||
|
||||
// Send navigation state to parent
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "updateNavigationState",
|
||||
params: state
|
||||
}, "*");
|
||||
} catch (error) {
|
||||
console.error('Failed to send navigation state:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Main Fetch Client
|
||||
class FetchClient {
|
||||
constructor() {
|
||||
this.rpcClient = new JSONRPCClient();
|
||||
this.consoleInterceptor = new ConsoleInterceptor();
|
||||
this.navigationHandler = new NavigationHandler();
|
||||
this.init();
|
||||
}
|
||||
|
||||
// Ensure SPA navigates to initial path after document is loaded
|
||||
ensureInitialNavigation() {
|
||||
// Wait for the SPA to initialize, then navigate to the initial path
|
||||
setTimeout(() => {
|
||||
const initialPath = window.__IFRAME_INITIAL_PATH__;
|
||||
|
||||
if (initialPath && initialPath !== '/') {
|
||||
const currentPath = window.location.pathname + window.location.search + window.location.hash;
|
||||
|
||||
// If we're not already at the initial path, navigate there
|
||||
if (currentPath !== initialPath) {
|
||||
this.navigationHandler.handleNavigate(initialPath);
|
||||
}
|
||||
}
|
||||
}, 150); // Give SPA more time to initialize
|
||||
}
|
||||
|
||||
async init() {
|
||||
try {
|
||||
await this.setupServiceWorker();
|
||||
await this.loadSiteIndex();
|
||||
} catch (error) {
|
||||
console.error("FetchClient: Initialization failed:", error);
|
||||
this.showError("Failed to initialize fetch client", error);
|
||||
}
|
||||
}
|
||||
|
||||
async setupServiceWorker() {
|
||||
if (!("serviceWorker" in navigator)) {
|
||||
throw new Error("ServiceWorker not supported");
|
||||
}
|
||||
|
||||
// Check if already registered
|
||||
const existing = await navigator.serviceWorker.getRegistration();
|
||||
if (existing) {
|
||||
console.log("ServiceWorker already registered");
|
||||
this.setupServiceWorkerCommunication();
|
||||
return;
|
||||
}
|
||||
|
||||
// Register new ServiceWorker
|
||||
const registration = await navigator.serviceWorker.register("/sw.js", { scope: "/" });
|
||||
console.log("ServiceWorker registered:", registration);
|
||||
|
||||
await navigator.serviceWorker.ready;
|
||||
this.setupServiceWorkerCommunication();
|
||||
this.blockFutureRegistrations(); // Block future registrations to prevent site from registering its own SW
|
||||
}
|
||||
|
||||
setupServiceWorkerCommunication() {
|
||||
// Relay JSON-RPC requests from ServiceWorker to parent
|
||||
navigator.serviceWorker.addEventListener("message", (event) => {
|
||||
const { data } = event;
|
||||
if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) {
|
||||
window.parent.postMessage(data, "*");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
blockFutureRegistrations() {
|
||||
navigator.serviceWorker.register = () => {
|
||||
console.log("Blocked ServiceWorker registration attempt");
|
||||
return Promise.resolve({
|
||||
scope: "/",
|
||||
active: navigator.serviceWorker.controller,
|
||||
installing: null,
|
||||
waiting: null,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
async loadSiteIndex() {
|
||||
// Check if we have a stored initial path from a refresh
|
||||
let initialPath = '/';
|
||||
try {
|
||||
const storedPath = sessionStorage.getItem('iframe_initial_path');
|
||||
if (storedPath) {
|
||||
initialPath = storedPath;
|
||||
// Clear the stored path after using it
|
||||
sessionStorage.removeItem('iframe_initial_path');
|
||||
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('loadSiteIndex: Failed to read initial path from sessionStorage:', error);
|
||||
}
|
||||
|
||||
const serializedRequest = {
|
||||
url: `${location.origin}/`,
|
||||
method: "GET",
|
||||
body: null,
|
||||
headers: {},
|
||||
};
|
||||
|
||||
const response = await this.rpcClient.fetch(serializedRequest);
|
||||
|
||||
if (response?.status !== 200) {
|
||||
throw new Error(`Failed to fetch site index: ${response?.status || 'Invalid response from site: ' + response} ${response?.statusText || ''}`);
|
||||
}
|
||||
|
||||
if (response.headers["Content-Type"] !== "text/html") {
|
||||
throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`);
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
|
||||
const text = new TextDecoder().decode(bytes);
|
||||
|
||||
// Set the initial path on window before replacing the document
|
||||
// This will be available to the NavigationHandler when it initializes
|
||||
if (initialPath && initialPath !== '/') {
|
||||
window.__IFRAME_INITIAL_PATH__ = initialPath;
|
||||
}
|
||||
|
||||
this.replaceDocument(text);
|
||||
}
|
||||
|
||||
replaceDocument(htmlContent) {
|
||||
console.log("replaceDocument: Starting...");
|
||||
|
||||
// Restore the initial path from sessionStorage before replacing document
|
||||
let initialPath = '/';
|
||||
try {
|
||||
const storedPath = sessionStorage.getItem('spa_initial_path');
|
||||
if (storedPath) {
|
||||
initialPath = storedPath;
|
||||
sessionStorage.removeItem('spa_initial_path');
|
||||
console.log('replaceDocument: Restored initial path:', initialPath);
|
||||
// Set it on window for the new document
|
||||
window.__IFRAME_INITIAL_PATH__ = initialPath;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('replaceDocument: Failed to restore initial path:', error);
|
||||
}
|
||||
|
||||
// Create a new document from the HTML content
|
||||
const parser = new DOMParser();
|
||||
const newDoc = parser.parseFromString(htmlContent, "text/html");
|
||||
|
||||
// Extract scripts for re-execution
|
||||
const scripts = [];
|
||||
newDoc.querySelectorAll("script").forEach((script) => {
|
||||
scripts.push({
|
||||
src: script.src,
|
||||
type: script.type,
|
||||
async: script.hasAttribute("async"),
|
||||
defer: script.hasAttribute("defer"),
|
||||
});
|
||||
script.remove();
|
||||
});
|
||||
|
||||
// Replace document content
|
||||
document.head.innerHTML = newDoc.head.innerHTML;
|
||||
document.body.innerHTML = newDoc.body.innerHTML;
|
||||
|
||||
// Re-add scripts to execute them
|
||||
scripts.forEach((script) => {
|
||||
const newScript = document.createElement("script");
|
||||
newScript.src = script.src;
|
||||
newScript.type = script.type;
|
||||
if (script.async) newScript.async = true;
|
||||
if (script.defer) newScript.defer = true;
|
||||
document.body.appendChild(newScript);
|
||||
});
|
||||
|
||||
// Ensure initial navigation after document is loaded
|
||||
this.ensureInitialNavigation();
|
||||
}
|
||||
|
||||
showError(message, error) {
|
||||
console.error(message, error);
|
||||
|
||||
document.body.innerHTML = `
|
||||
<div style="
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
max-width: 600px;
|
||||
margin: 50px auto;
|
||||
padding: 20px;
|
||||
background: #f8f9fa;
|
||||
border-radius: 8px;
|
||||
border-left: 4px solid #dc3545;
|
||||
">
|
||||
<h2 style="color: #dc3545; margin-top: 0;">Fetch Client Error</h2>
|
||||
<p><strong>${message}</strong></p>
|
||||
<p style="color: #6c757d;">${error.message || error}</p>
|
||||
<details style="margin-top: 20px;">
|
||||
<summary style="cursor: pointer; color: #007bff;">Technical Details</summary>
|
||||
<pre style="
|
||||
background: #f1f3f4;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
overflow-x: auto;
|
||||
font-size: 12px;
|
||||
margin-top: 10px;
|
||||
">${error.stack || JSON.stringify(error, null, 2)}</pre>
|
||||
</details>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
// Global error handlers
|
||||
const setupGlobalErrorHandlers = () => {
|
||||
window.addEventListener('error', (event) => {
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "console",
|
||||
params: {
|
||||
level: "error",
|
||||
message: `Uncaught Error: ${event.message}`,
|
||||
source: event.filename,
|
||||
lineno: event.lineno,
|
||||
colno: event.colno,
|
||||
stack: event.error?.stack
|
||||
}
|
||||
}, "*");
|
||||
} catch {
|
||||
// Ignore postMessage errors
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener('unhandledrejection', (event) => {
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "console",
|
||||
params: {
|
||||
level: "error",
|
||||
message: "Unhandled Promise Rejection",
|
||||
reason: event.reason,
|
||||
promise: event.promise ? 'Promise object' : 'No promise object'
|
||||
}
|
||||
}, "*");
|
||||
} catch {
|
||||
// Ignore postMessage errors
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Initialize
|
||||
setupGlobalErrorHandlers();
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", () => new FetchClient());
|
||||
} else {
|
||||
new FetchClient();
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Site Preview</title>
|
||||
<link rel="stylesheet" href="/_iframe-client/client.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="loading">
|
||||
<div class="spinner"></div>
|
||||
<p>Loading preview...</p>
|
||||
<p><small>Waiting for ServiceWorker and parent communication</small></p>
|
||||
</div>
|
||||
<script type="module" src="/_iframe-client/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,205 +0,0 @@
|
||||
/**
|
||||
* iframe Fetch Client ServiceWorker
|
||||
* Intercepts requests and handles them via JSON-RPC communication
|
||||
*/
|
||||
|
||||
let pendingRequests = new Map();
|
||||
let requestIdCounter = 0;
|
||||
|
||||
// Install event
|
||||
self.addEventListener("install", (event) => {
|
||||
console.log("ServiceWorker installing");
|
||||
self.skipWaiting();
|
||||
});
|
||||
|
||||
// Activate event
|
||||
self.addEventListener("activate", (event) => {
|
||||
console.log("ServiceWorker activating");
|
||||
event.waitUntil(self.clients.claim());
|
||||
});
|
||||
|
||||
// Message handling from main thread (JSON-RPC responses)
|
||||
self.addEventListener("message", (event) => {
|
||||
handleMainThreadMessage(event.data);
|
||||
});
|
||||
|
||||
function handleMainThreadMessage(data) {
|
||||
// Handle JSON-RPC responses relayed from main thread
|
||||
if (data.jsonrpc === "2.0" && data.id !== undefined) {
|
||||
handleJSONRPCResponse(data);
|
||||
}
|
||||
}
|
||||
|
||||
function handleJSONRPCResponse(message) {
|
||||
const { id, result, error } = message;
|
||||
const pendingRequest = pendingRequests.get(id);
|
||||
|
||||
if (!pendingRequest) {
|
||||
console.warn("No pending request found for ID:", id);
|
||||
return;
|
||||
}
|
||||
|
||||
pendingRequests.delete(id);
|
||||
|
||||
if (error) {
|
||||
pendingRequest.reject(new Error(`${error.message} (code: ${error.code})`));
|
||||
return;
|
||||
}
|
||||
|
||||
// Create response from serialized response
|
||||
const { status, statusText, headers, body } = result;
|
||||
|
||||
// Decode base64 body if present
|
||||
let decoded = null;
|
||||
if (typeof body === "string") {
|
||||
decoded = new Uint8Array(atob(body).split('').map(c => c.charCodeAt(0)));
|
||||
}
|
||||
|
||||
const response = new Response(decoded, {
|
||||
status: status || 200,
|
||||
statusText: statusText || "OK",
|
||||
headers: headers || {},
|
||||
});
|
||||
|
||||
pendingRequest.resolve(response);
|
||||
}
|
||||
|
||||
async function requestViaJSONRPC(request) {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
const id = ++requestIdCounter;
|
||||
|
||||
// Check if request is a plain object or Request object
|
||||
let url, method, headers, body;
|
||||
|
||||
if (request instanceof Request) {
|
||||
// Handle Request object
|
||||
url = request.url;
|
||||
method = request.method;
|
||||
headers = Object.fromEntries(request.headers.entries());
|
||||
|
||||
if (request.body) {
|
||||
try {
|
||||
// Convert body to Uint8Array then base64 encode
|
||||
const bytes = await request.bytes();
|
||||
body = btoa(String.fromCharCode(...bytes));
|
||||
} catch (error) {
|
||||
reject(new Error(`Failed to serialize request body: ${error.message}`));
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Handle plain request object
|
||||
url = request.url;
|
||||
method = request.method || 'GET';
|
||||
headers = request.headers || {};
|
||||
body = request.body || null;
|
||||
}
|
||||
|
||||
const serializedRequest = {
|
||||
url: url,
|
||||
method: method,
|
||||
headers: headers,
|
||||
body: body,
|
||||
};
|
||||
|
||||
pendingRequests.set(id, { resolve, reject, originalRequest: request });
|
||||
|
||||
// Send JSON-RPC request to main thread for relay to parent
|
||||
self.clients.matchAll().then((clients) => {
|
||||
if (clients.length > 0) {
|
||||
clients[0].postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "fetch",
|
||||
params: { request: serializedRequest },
|
||||
id,
|
||||
});
|
||||
} else {
|
||||
pendingRequests.delete(id);
|
||||
reject(new Error("No clients available"));
|
||||
}
|
||||
});
|
||||
|
||||
// Timeout after 10 seconds
|
||||
setTimeout(() => {
|
||||
if (pendingRequests.has(id)) {
|
||||
pendingRequests.delete(id);
|
||||
reject(new Error(`Timeout requesting: ${url}`));
|
||||
}
|
||||
}, 10000);
|
||||
});
|
||||
}
|
||||
|
||||
// Fetch event - intercept all requests
|
||||
self.addEventListener("fetch", (event) => {
|
||||
const url = new URL(event.request.url);
|
||||
|
||||
// Ignore requests to other origins
|
||||
if (url.origin !== location.origin) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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 === "/favicon.ico" ||
|
||||
url.pathname === "/manifest.webmanifest") {
|
||||
return;
|
||||
}
|
||||
|
||||
// For SPA routes, check if this is a navigation request (HTML page request)
|
||||
// But first check if we need to load the iframe client (this happens during refresh)
|
||||
if (event.request.mode === "navigate" &&
|
||||
(event.request.headers.get("accept") || "").includes("text/html")) {
|
||||
|
||||
// Check if this is a request for the iframe client itself
|
||||
// We need to serve the iframe client HTML first, which will then load the SPA
|
||||
if (url.pathname !== "/") {
|
||||
// Redirect to root to load the iframe client, which will then navigate to the target path
|
||||
const response = Response.redirect(new URL("/", event.request.url).href, 302);
|
||||
event.respondWith(response);
|
||||
return;
|
||||
}
|
||||
|
||||
// This is a request for the root path, serve the site's index.html via JSON-RPC
|
||||
const rootRequest = {
|
||||
url: new URL("/", event.request.url).href,
|
||||
method: event.request.method,
|
||||
headers: Object.fromEntries(event.request.headers.entries()),
|
||||
body: event.request.body
|
||||
};
|
||||
event.respondWith(handleRequest(rootRequest));
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle all other requests through JSON-RPC communication
|
||||
event.respondWith(handleRequest(event.request));
|
||||
});
|
||||
|
||||
async function handleRequest(request) {
|
||||
try {
|
||||
console.log("ServiceWorker handling request for:", request.url);
|
||||
return await requestViaJSONRPC(request);
|
||||
} catch (error) {
|
||||
console.error("Failed to handle request:", request.url, error);
|
||||
|
||||
// Return 404 for failed requests
|
||||
return new Response(`Request failed: ${request.url}`, {
|
||||
status: 404,
|
||||
statusText: "Not Found",
|
||||
headers: {
|
||||
"Content-Type": "text/plain",
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
console.log("ServiceWorker script loaded");
|
||||
@@ -63,6 +63,7 @@ const defaultConfig: AppConfig = {
|
||||
relays: [
|
||||
{ url: 'wss://git.shakespeare.diy/' },
|
||||
{ url: 'wss://relay.ngit.dev/' },
|
||||
{ url: 'wss://git.nostrhub.io/' },
|
||||
],
|
||||
updatedAt: 0,
|
||||
},
|
||||
@@ -78,9 +79,9 @@ const defaultConfig: AppConfig = {
|
||||
gitProxyOrigins: ["https://github.com", "https://gitlab.com"],
|
||||
faviconUrl: "https://favicon.shakespeare.diy/?url={href}",
|
||||
ngitWebUrl: "https://nostrhub.io/{naddr}",
|
||||
previewDomain: "local-shakespeare.dev",
|
||||
previewDomain: "iframe.diy",
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
|
||||
showcaseCurator: "naddr1qvzqqqr4xqpzq7q6z5ns2hm5c8msyv83qwzxpxe52j8c4d4q5m92wsp9sflelkh9qqjrvdrxxajnqvny95mkyc33956xvwfk94sn2vek94sn2et9ve3kycfexfnryvty32j",
|
||||
fsPathProjects: "/projects",
|
||||
fsPathConfig: "/config",
|
||||
fsPathTmp: "/tmp",
|
||||
|
||||
@@ -21,6 +21,7 @@ import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import NetlifyOAuth from "./pages/NetlifyOAuth";
|
||||
import VercelOAuth from "./pages/VercelOAuth";
|
||||
import OpenRouterOAuth from "./pages/OpenRouterOAuth";
|
||||
import RemoteLoginSuccess from "./pages/RemoteLoginSuccess";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { ProjectView } from "./pages/ProjectView";
|
||||
@@ -43,6 +44,7 @@ export function AppRouter() {
|
||||
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
||||
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
||||
<Route path="/oauth/openrouter" element={<OpenRouterOAuth />} />
|
||||
<Route path="/remoteloginsuccess" element={<RemoteLoginSuccess />} />
|
||||
<Route path="/settings" element={<SettingsLayout />}>
|
||||
<Route index element={<Settings />} />
|
||||
<Route path="preferences" element={<Preferences />} />
|
||||
|
||||
@@ -84,9 +84,9 @@ export function AddCustomProviderDialog({
|
||||
provider = {
|
||||
type: 'nsite',
|
||||
name: customName.trim(),
|
||||
gateway: customGateway.trim() || 'nsite.lol',
|
||||
gateway: customGateway.trim() || 'shakespeare.to',
|
||||
relayUrls: customRelayUrls.length > 0 ? customRelayUrls : ['wss://relay.ditto.pub'],
|
||||
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.primal.net/'],
|
||||
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.ditto.pub/', 'https://blossom.dreamith.to/'],
|
||||
};
|
||||
} else if (customProviderType === 'netlify') {
|
||||
if (!customApiKey.trim()) return;
|
||||
@@ -252,7 +252,7 @@ export function AddCustomProviderDialog({
|
||||
<Label htmlFor="custom-gateway">Gateway</Label>
|
||||
<Input
|
||||
id="custom-gateway"
|
||||
placeholder="nsite.lol"
|
||||
placeholder="shakespeare.to"
|
||||
value={customGateway}
|
||||
onChange={(e) => setCustomGateway(e.target.value)}
|
||||
/>
|
||||
@@ -269,7 +269,7 @@ export function AddCustomProviderDialog({
|
||||
items={customBlossomServers}
|
||||
onChange={setCustomBlossomServers}
|
||||
protocol="https"
|
||||
placeholder="blossom.primal.net"
|
||||
placeholder="blossom.ditto.pub"
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
|
||||
@@ -13,6 +13,8 @@ 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';
|
||||
@@ -27,16 +29,15 @@ import { DotAI } from '@/lib/DotAI';
|
||||
import { buildAppEvent } from '@/lib/appEvent';
|
||||
import {
|
||||
Loader2,
|
||||
Save,
|
||||
Plus,
|
||||
X,
|
||||
ExternalLink,
|
||||
Pencil,
|
||||
Upload,
|
||||
ChevronDown,
|
||||
CircleHelp,
|
||||
} from 'lucide-react';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
interface AppDialogProps {
|
||||
projectId: string;
|
||||
@@ -48,10 +49,14 @@ 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 */
|
||||
@@ -75,14 +80,26 @@ function eventToFormData(event: NostrEvent): AppFormData {
|
||||
.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),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -100,13 +117,120 @@ function emptyFormData(projectId: string): AppFormData {
|
||||
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();
|
||||
@@ -117,17 +241,21 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
const cwd = `${projectsPath}/${projectId}`;
|
||||
|
||||
const { event, isLoading, aTag, hasApp, refetch } = useAppEvent({ cwd });
|
||||
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 = (() => {
|
||||
@@ -152,10 +280,36 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
||||
}
|
||||
}, [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)) {
|
||||
@@ -181,6 +335,30 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
||||
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;
|
||||
@@ -216,12 +394,9 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!formData.name.trim()) {
|
||||
toast({
|
||||
title: 'Name required',
|
||||
description: 'Please enter a name for your app.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setSubmitted(true);
|
||||
|
||||
if (!formData.name.trim() || !formData.about.trim() || !formData.website.trim() || !formData.picture.trim() || !formData.banner.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -243,10 +418,14 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
||||
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 },
|
||||
);
|
||||
@@ -285,6 +464,37 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
||||
}
|
||||
};
|
||||
|
||||
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}>
|
||||
@@ -326,88 +536,105 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-5">
|
||||
{/* App Preview Card */}
|
||||
<div className="flex items-start gap-4">
|
||||
{/* Icon with upload */}
|
||||
<div className="relative flex-shrink-0 group">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={handleIconUpload}
|
||||
className="hidden"
|
||||
disabled={isSaving || isUploading}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={isSaving || isUploading}
|
||||
className="relative block rounded-2xl overflow-hidden focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none"
|
||||
>
|
||||
{formData.picture ? (
|
||||
<>
|
||||
<Avatar className="h-20 w-20 rounded-2xl">
|
||||
<AvatarImage src={formData.picture} alt={formData.name || 'App icon'} className="object-cover" />
|
||||
<AvatarFallback className="rounded-2xl bg-muted" />
|
||||
</Avatar>
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-2xl">
|
||||
{isUploading ? (
|
||||
<Loader2 className="h-5 w-5 text-white animate-spin" />
|
||||
) : (
|
||||
<Pencil className="h-4 w-4 text-white" />
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="h-20 w-20 rounded-2xl bg-muted flex items-center justify-center transition-colors group-hover:bg-muted-foreground">
|
||||
{isUploading ? (
|
||||
<Loader2 className="h-6 w-6 text-muted-foreground animate-spin group-hover:text-background" />
|
||||
) : (
|
||||
<Upload className="h-6 w-6 text-muted-foreground transition-colors group-hover:text-background" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Name & Description inline */}
|
||||
<div className="flex-1 min-w-0 space-y-2">
|
||||
<Input
|
||||
value={formData.name}
|
||||
onChange={e => updateField('name', e.target.value)}
|
||||
placeholder="App Name"
|
||||
disabled={isSaving}
|
||||
/>
|
||||
<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"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Website */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="app-website" className="text-xs text-muted-foreground">Website</Label>
|
||||
<Input
|
||||
id="app-website"
|
||||
value={formData.website}
|
||||
onChange={e => updateField('website', e.target.value)}
|
||||
placeholder={deployedUrl || 'https://myapp.example.com'}
|
||||
disabled={isSaving}
|
||||
{/* 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}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Existing app coordinate info */}
|
||||
{aTag && (
|
||||
<div className="text-xs text-muted-foreground space-y-1">
|
||||
<p className="font-medium">Nostr Coordinate</p>
|
||||
<code className="block p-2 bg-muted rounded text-xs break-all select-all">{aTag}</code>
|
||||
{/* 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}>
|
||||
@@ -421,140 +648,242 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
||||
</button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="space-y-4 pt-2">
|
||||
<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>
|
||||
|
||||
{/* Identifier (d-tag) */}
|
||||
<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>
|
||||
<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>
|
||||
|
||||
{/* Supported Kinds */}
|
||||
<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>
|
||||
|
||||
{/* Web Handlers */}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">Web Handlers</Label>
|
||||
{formData.webHandlers.length > 0 && (
|
||||
{/* General tab: Identifier, Git Repo, nsite */}
|
||||
<TabsContent value="general" className="space-y-4 mt-3">
|
||||
<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>
|
||||
))}
|
||||
<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="flex gap-2">
|
||||
<Input
|
||||
value={newHandlerUrl}
|
||||
onChange={e => setNewHandlerUrl(e.target.value)}
|
||||
placeholder="https://app.example.com/e/<bech32>"
|
||||
disabled={isSaving}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Input
|
||||
value={newHandlerType}
|
||||
onChange={e => setNewHandlerType(e.target.value)}
|
||||
placeholder="nevent"
|
||||
disabled={isSaving}
|
||||
className="w-24"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={addHandler}
|
||||
disabled={isSaving || !newHandlerUrl.trim()}
|
||||
className="h-9"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
)}
|
||||
</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 || !formData.name.trim()}
|
||||
disabled={isSaving}
|
||||
className="w-full gap-2"
|
||||
>
|
||||
{isSaving ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Save className="h-4 w-4" />
|
||||
)}
|
||||
{isSaving && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||
{isSaving
|
||||
? (hasApp ? 'Updating...' : 'Publishing...')
|
||||
: (hasApp ? 'Update App' : 'Publish App')}
|
||||
|
||||
@@ -51,7 +51,7 @@ const AppConfigSchema = z.object({
|
||||
previewDomain: z.string().min(1),
|
||||
language: z.string(),
|
||||
showcaseEnabled: z.boolean(),
|
||||
showcaseModerator: z.string(),
|
||||
showcaseCurator: z.string(),
|
||||
fsPathProjects: z.string().min(1),
|
||||
fsPathConfig: z.string().min(1),
|
||||
fsPathTmp: z.string().min(1),
|
||||
|
||||
@@ -1,92 +1,24 @@
|
||||
import React, { useState, useMemo } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import React from "react";
|
||||
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">
|
||||
@@ -106,14 +38,9 @@ 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>
|
||||
@@ -147,95 +74,11 @@ export function AppShowcase() {
|
||||
|
||||
return (
|
||||
<div className="mt-16 max-w-7xl mx-auto">
|
||||
{/* 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 className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{submissions.map((app) => (
|
||||
<AppShowcaseCard key={app.id} app={app} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,541 +2,81 @@ import React, { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import {
|
||||
ExternalLink,
|
||||
Edit,
|
||||
Star,
|
||||
StarOff,
|
||||
Eye,
|
||||
EyeOff,
|
||||
MoreVertical,
|
||||
CheckCircle,
|
||||
XCircle,
|
||||
User,
|
||||
Home,
|
||||
Contact
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { ExternalLink, User } from 'lucide-react';
|
||||
import type { AppSubmission } from '@/hooks/useAppSubmissions';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
interface AppShowcaseCardProps {
|
||||
app: AppSubmission;
|
||||
onEdit?: (app: AppSubmission) => void;
|
||||
showModerationControls?: boolean;
|
||||
hideApprovalStatus?: boolean; // Hide pending/approval badges
|
||||
}
|
||||
|
||||
export function AppShowcaseCard({ app, onEdit, showModerationControls, hideApprovalStatus: _hideApprovalStatus }: AppShowcaseCardProps) {
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
const { mutate: publishEvent, isPending } = useNostrPublish();
|
||||
const queryClient = useQueryClient();
|
||||
const [imageError, setImageError] = useState(false);
|
||||
const { toast } = useToast();
|
||||
export function AppShowcaseCard({ app }: AppShowcaseCardProps) {
|
||||
const [bannerError, setBannerError] = useState(false);
|
||||
const [iconError, setIconError] = useState(false);
|
||||
|
||||
// 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'
|
||||
});
|
||||
}
|
||||
};
|
||||
const { data: authorData } = useAuthor(app.pubkey);
|
||||
const authorNpub = nip19.npubEncode(app.pubkey);
|
||||
|
||||
return (
|
||||
<Card className="group hover:shadow-lg transition-all duration-300 hover:border-primary/20 h-full flex flex-col">
|
||||
<div className="relative">
|
||||
{/* App Screenshot */}
|
||||
<a
|
||||
href={app.websiteUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block aspect-video bg-gradient-to-br from-muted/50 to-muted rounded-t-lg overflow-hidden cursor-pointer"
|
||||
>
|
||||
{!imageError ? (
|
||||
<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 ? (
|
||||
<img
|
||||
src={app.screenshotUrl}
|
||||
alt={`${app.appName} screenshot`}
|
||||
src={app.bannerUrl}
|
||||
alt=""
|
||||
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
|
||||
onError={() => setImageError(true)}
|
||||
onError={() => setBannerError(true)}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
|
||||
<div className="text-center">
|
||||
<div className="w-16 h-16 mx-auto mb-2 bg-muted rounded-lg flex items-center justify-center">
|
||||
<ExternalLink className="w-8 h-8" />
|
||||
</div>
|
||||
<p className="text-sm">Screenshot unavailable</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-full h-full bg-gradient-to-br from-accent/10 via-transparent to-primary/5" />
|
||||
)}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* 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">
|
||||
{/* 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 ? (
|
||||
<img
|
||||
src={app.appIconUrl}
|
||||
alt={`${app.appName} icon`}
|
||||
className="w-full h-full object-cover"
|
||||
onError={(e) => {
|
||||
const target = e.target as HTMLImageElement;
|
||||
target.style.display = 'none';
|
||||
}}
|
||||
onError={() => setIconError(true)}
|
||||
/>
|
||||
</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 className="w-full h-full flex items-center justify-center">
|
||||
<ExternalLink className="w-5 h-5 text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
|
||||
<p className="text-muted-foreground mb-3 line-clamp-3">{app.description}</p>
|
||||
<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>
|
||||
|
||||
{/* Author Information */}
|
||||
{app.description && (
|
||||
<p className="text-sm text-muted-foreground mb-3 line-clamp-2">{app.description}</p>
|
||||
)}
|
||||
|
||||
{/* Author */}
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<div className="w-6 h-6 rounded-full overflow-hidden bg-muted flex-shrink-0">
|
||||
<div className="w-5 h-5 rounded-full overflow-hidden bg-muted flex-shrink-0">
|
||||
{authorData?.metadata?.picture ? (
|
||||
<img
|
||||
src={authorData.metadata.picture}
|
||||
alt={`${authorData.metadata.name || 'Author'} avatar`}
|
||||
alt={authorData.metadata.name || 'Author'}
|
||||
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">
|
||||
@@ -544,10 +84,10 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
by{' '}
|
||||
<a
|
||||
href={`https://ditto.pub/${app.authorNpub || nip19.npubEncode(authorPubkey)}`}
|
||||
href={`https://ditto.pub/${authorNpub}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:text-primary/80 transition-colors hover:underline"
|
||||
@@ -557,33 +97,24 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Spacer to push action links to bottom */}
|
||||
<div className="flex-1"></div>
|
||||
<div className="flex-1" />
|
||||
|
||||
{/* Action Links */}
|
||||
<div className="flex items-center gap-2 mt-auto">
|
||||
<Link
|
||||
to={`/clone?url=${encodeURIComponent(app.repositoryUrl)}`}
|
||||
className="flex-1"
|
||||
>
|
||||
<img
|
||||
src="/badge.svg"
|
||||
alt="Edit with Shakespeare"
|
||||
className="h-6 hover:opacity-80 transition-opacity"
|
||||
/>
|
||||
</Link>
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<a
|
||||
href={app.websiteUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
title="Visit app"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
</a>
|
||||
</Button>
|
||||
{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>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,10 @@ 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: [],
|
||||
providers: [DEFAULT_NSITE_PROVIDER],
|
||||
};
|
||||
|
||||
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
import git from 'isomorphic-git';
|
||||
import { Loader2, Zap } from 'lucide-react';
|
||||
import { DropdownMenuItem } from '@/components/ui/dropdown-menu';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
|
||||
/**
|
||||
* "Optimize Repository" entry for the project dropdown.
|
||||
*
|
||||
* Fully self-contained recovery action: clicking it consolidates the
|
||||
* project's git pack files into a single pack containing every reachable
|
||||
* object, deletes the old packs and redundant loose objects, and reports
|
||||
* the size reduction in a toast. A spinner toast is shown while it runs.
|
||||
*
|
||||
* Everything (UI, gc algorithm, state) lives in this one file so the
|
||||
* feature can be removed by deleting this file and its single render
|
||||
* line in ProjectTitleMenu.
|
||||
*/
|
||||
|
||||
/** Projects with an optimization currently in flight (reentrancy guard). */
|
||||
const running = new Set<string>();
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Repository optimization (simplified `git gc` for isomorphic-git repos)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Yield to the event loop so the UI can paint between batches of work. */
|
||||
function yieldToMain(): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
/** Recursively sum the size of all files under `path`. */
|
||||
async function dirSize(fs: JSRuntimeFS, path: string): Promise<number> {
|
||||
let total = 0;
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = await fs.readdir(path);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
for (const name of entries) {
|
||||
const child = `${path}/${name}`;
|
||||
try {
|
||||
const stat = await fs.stat(child);
|
||||
if (stat.isDirectory()) {
|
||||
total += await dirSize(fs, child);
|
||||
} else {
|
||||
total += stat.size ?? 0;
|
||||
}
|
||||
} catch {
|
||||
// Skip unreadable entries.
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively walk a tree, adding every blob/tree OID to `reachable`.
|
||||
* Returns the number of objects that could not be read.
|
||||
*/
|
||||
async function walkTree(
|
||||
fs: JSRuntimeFS,
|
||||
gitdir: string,
|
||||
treeOid: string,
|
||||
reachable: Set<string>,
|
||||
visitedTrees: Set<string>,
|
||||
): Promise<number> {
|
||||
if (visitedTrees.has(treeOid)) return 0;
|
||||
visitedTrees.add(treeOid);
|
||||
|
||||
let tree: Awaited<ReturnType<typeof git.readTree>>;
|
||||
try {
|
||||
tree = await git.readTree({ fs, gitdir, oid: treeOid });
|
||||
} catch {
|
||||
return 1;
|
||||
}
|
||||
reachable.add(treeOid);
|
||||
|
||||
let errors = 0;
|
||||
for (const entry of tree.tree) {
|
||||
if (entry.type === 'tree') {
|
||||
errors += await walkTree(fs, gitdir, entry.oid, reachable, visitedTrees);
|
||||
} else if (entry.type === 'blob') {
|
||||
reachable.add(entry.oid);
|
||||
}
|
||||
// entry.type === 'commit' is a submodule gitlink; skip.
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
interface OptimizeResult {
|
||||
bytesBefore: number;
|
||||
bytesAfter: number;
|
||||
/** True when some objects could not be read, so the repo was left untouched. */
|
||||
incomplete: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Consolidate all reachable objects into one new pack, then delete the old
|
||||
* packs and redundant loose objects.
|
||||
*
|
||||
* Non-destructive: every object reachable from any ref or HEAD is preserved.
|
||||
* If any object fails to read during the reachability walk, or the new pack
|
||||
* would be larger than the files it replaces, the repository is left
|
||||
* completely untouched.
|
||||
*/
|
||||
async function optimizeRepository(fs: JSRuntimeFS, dir: string): Promise<OptimizeResult> {
|
||||
const gitdir = `${dir}/.git`;
|
||||
const objectsDir = `${gitdir}/objects`;
|
||||
const packDir = `${objectsDir}/pack`;
|
||||
|
||||
const bytesBefore = await dirSize(fs, objectsDir);
|
||||
|
||||
let oldPackEntries: string[];
|
||||
try {
|
||||
oldPackEntries = await fs.readdir(packDir);
|
||||
} catch {
|
||||
oldPackEntries = [];
|
||||
}
|
||||
|
||||
// 1. Collect ref tips (branches, tags, remotes, stash, HEAD).
|
||||
const tips = new Set<string>();
|
||||
let refs: string[] = [];
|
||||
try {
|
||||
refs = await git.listRefs({ fs, gitdir, filepath: 'refs' });
|
||||
} catch {
|
||||
refs = [];
|
||||
}
|
||||
for (const ref of refs) {
|
||||
try {
|
||||
tips.add(await git.resolveRef({ fs, gitdir, ref: `refs/${ref}` }));
|
||||
} catch {
|
||||
// Broken ref; skip.
|
||||
}
|
||||
}
|
||||
try {
|
||||
tips.add(await git.resolveRef({ fs, gitdir, ref: 'HEAD' }));
|
||||
} catch {
|
||||
// No HEAD (fresh repo).
|
||||
}
|
||||
|
||||
// 2. Walk reachability from every tip.
|
||||
const reachable = new Set<string>();
|
||||
const visitedTrees = new Set<string>();
|
||||
const stack = [...tips];
|
||||
let walkErrors = 0;
|
||||
let steps = 0;
|
||||
|
||||
while (stack.length > 0) {
|
||||
const oid = stack.pop()!;
|
||||
if (reachable.has(oid)) continue;
|
||||
|
||||
let parsed: Awaited<ReturnType<typeof git.readObject>>;
|
||||
try {
|
||||
parsed = await git.readObject({ fs, gitdir, oid, format: 'parsed' });
|
||||
} catch {
|
||||
walkErrors++;
|
||||
continue;
|
||||
}
|
||||
|
||||
reachable.add(oid);
|
||||
|
||||
if (parsed.type === 'commit') {
|
||||
const commit = parsed.object as { tree: string; parent: string[] };
|
||||
for (const parent of commit.parent) stack.push(parent);
|
||||
walkErrors += await walkTree(fs, gitdir, commit.tree, reachable, visitedTrees);
|
||||
} else if (parsed.type === 'tag') {
|
||||
stack.push((parsed.object as { object: string }).object);
|
||||
} else if (parsed.type === 'tree') {
|
||||
walkErrors += await walkTree(fs, gitdir, oid, reachable, visitedTrees);
|
||||
}
|
||||
|
||||
if (++steps % 64 === 0) await yieldToMain();
|
||||
}
|
||||
|
||||
if (walkErrors > 0 || reachable.size === 0) {
|
||||
// Damaged repo (or empty repo) — change nothing.
|
||||
return { bytesBefore, bytesAfter: bytesBefore, incomplete: walkErrors > 0 };
|
||||
}
|
||||
|
||||
// 3. Write the consolidated pack and its index.
|
||||
await yieldToMain();
|
||||
const { filename } = await git.packObjects({
|
||||
fs,
|
||||
gitdir,
|
||||
oids: [...reachable],
|
||||
write: true,
|
||||
});
|
||||
await git.indexPack({ fs, dir, gitdir, filepath: `.git/objects/pack/${filename}` });
|
||||
|
||||
// 4. Safety check: isomorphic-git writes undeltified packs, which can be
|
||||
// larger than the (server-deltified) packs they replace. Only proceed if
|
||||
// deleting the old packs and loose copies reclaims more than the new pack
|
||||
// costs; otherwise remove the new pack and leave the repo exactly as-is.
|
||||
const fileSize = async (path: string): Promise<number> => {
|
||||
try {
|
||||
return (await fs.stat(path)).size ?? 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
const newBase = filename!.replace(/\.pack$/, '');
|
||||
const newPackBytes =
|
||||
(await fileSize(`${packDir}/${filename}`)) + (await fileSize(`${packDir}/${newBase}.idx`));
|
||||
let reclaimableBytes = 0;
|
||||
for (const name of oldPackEntries) {
|
||||
if (name.startsWith(`${newBase}.`)) continue;
|
||||
if (!/\.(pack|idx)$/.test(name)) continue;
|
||||
reclaimableBytes += await fileSize(`${packDir}/${name}`);
|
||||
}
|
||||
steps = 0;
|
||||
for (const oid of reachable) {
|
||||
reclaimableBytes += await fileSize(`${objectsDir}/${oid.slice(0, 2)}/${oid.slice(2)}`);
|
||||
if (++steps % 64 === 0) await yieldToMain();
|
||||
}
|
||||
if (newPackBytes >= reclaimableBytes) {
|
||||
for (const name of [filename!, `${newBase}.idx`]) {
|
||||
try {
|
||||
await fs.unlink(`${packDir}/${name}`);
|
||||
} catch {
|
||||
// Best-effort.
|
||||
}
|
||||
}
|
||||
return { bytesBefore, bytesAfter: bytesBefore, incomplete: false };
|
||||
}
|
||||
|
||||
// 5. Delete the old pack files.
|
||||
for (const name of oldPackEntries) {
|
||||
if (name.startsWith(`${newBase}.`)) continue;
|
||||
if (!/\.(pack|idx)$/.test(name)) continue;
|
||||
try {
|
||||
await fs.unlink(`${packDir}/${name}`);
|
||||
} catch {
|
||||
// Best-effort.
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Delete loose copies of objects now stored in the new pack.
|
||||
const touchedDirs = new Set<string>();
|
||||
steps = 0;
|
||||
for (const oid of reachable) {
|
||||
const looseDir = `${objectsDir}/${oid.slice(0, 2)}`;
|
||||
try {
|
||||
await fs.unlink(`${looseDir}/${oid.slice(2)}`);
|
||||
touchedDirs.add(looseDir);
|
||||
} catch {
|
||||
// Object wasn't loose; nothing to do.
|
||||
}
|
||||
if (++steps % 64 === 0) await yieldToMain();
|
||||
}
|
||||
|
||||
// Remove now-empty loose object shards.
|
||||
for (const looseDir of touchedDirs) {
|
||||
try {
|
||||
if ((await fs.readdir(looseDir)).length === 0) await fs.rmdir(looseDir);
|
||||
} catch {
|
||||
// Best-effort.
|
||||
}
|
||||
}
|
||||
|
||||
const bytesAfter = await dirSize(fs, objectsDir);
|
||||
return { bytesBefore, bytesAfter, incomplete: false };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// UI
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
const units = ['KB', 'MB', 'GB'];
|
||||
let value = bytes;
|
||||
let unit = 'B';
|
||||
for (const next of units) {
|
||||
if (value < 1024) break;
|
||||
value /= 1024;
|
||||
unit = next;
|
||||
}
|
||||
return `${value.toFixed(1)} ${unit}`;
|
||||
}
|
||||
|
||||
async function run(fs: JSRuntimeFS, dir: string, projectId: string) {
|
||||
if (running.has(projectId)) return;
|
||||
running.add(projectId);
|
||||
|
||||
const progress = toast({
|
||||
description: (
|
||||
<span className="flex items-center gap-2">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Optimizing repository…
|
||||
</span>
|
||||
),
|
||||
duration: Infinity,
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await optimizeRepository(fs, dir);
|
||||
const saved = result.bytesBefore - result.bytesAfter;
|
||||
|
||||
progress.update({
|
||||
id: progress.id,
|
||||
title: 'Repository optimized',
|
||||
description: result.incomplete
|
||||
? 'Some objects could not be read, so the repository was left untouched for safety.'
|
||||
: saved > 0
|
||||
? `${formatBytes(result.bytesBefore)} → ${formatBytes(result.bytesAfter)} (saved ${formatBytes(saved)})`
|
||||
: `No size reduction (${formatBytes(result.bytesAfter)})`,
|
||||
duration: 10000,
|
||||
});
|
||||
} catch (error) {
|
||||
progress.update({
|
||||
id: progress.id,
|
||||
title: 'Repository optimization failed',
|
||||
description: error instanceof Error ? error.message : String(error),
|
||||
variant: 'destructive',
|
||||
duration: 10000,
|
||||
});
|
||||
} finally {
|
||||
running.delete(projectId);
|
||||
}
|
||||
}
|
||||
|
||||
interface OptimizeRepositoryMenuItemProps {
|
||||
projectId: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function OptimizeRepositoryMenuItem({ projectId, disabled }: OptimizeRepositoryMenuItemProps) {
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
onClick={() => run(fs, `${projectsPath}/${projectId}`, projectId)}
|
||||
disabled={disabled}
|
||||
className="gap-2"
|
||||
>
|
||||
<Zap className="h-4 w-4" />
|
||||
Optimize Repository
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { OptimizeRepositoryMenuItem } from '@/components/OptimizeRepositoryMenuItem';
|
||||
|
||||
interface ProjectTitleMenuProps {
|
||||
projectId: string;
|
||||
@@ -119,6 +120,8 @@ export function ProjectTitleMenu({
|
||||
Rollback
|
||||
</DropdownMenuItem>
|
||||
|
||||
<OptimizeRepositoryMenuItem projectId={projectId} disabled={isAnyLoading} />
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onNewChat}
|
||||
disabled={isAnyLoading}
|
||||
|
||||
@@ -134,7 +134,7 @@ export function ProviderConfigDialog({
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-gateway"
|
||||
placeholder="nsite.lol"
|
||||
placeholder="shakespeare.to"
|
||||
value={localProvider.gateway || ''}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
|
||||
/>
|
||||
@@ -152,7 +152,7 @@ export function ProviderConfigDialog({
|
||||
items={localProvider.blossomServers ?? []}
|
||||
onChange={(servers) => setLocalProvider({ ...localProvider, blossomServers: servers })}
|
||||
protocol="https"
|
||||
placeholder="blossom.primal.net"
|
||||
placeholder="blossom.ditto.pub"
|
||||
required
|
||||
/>
|
||||
</>
|
||||
|
||||
@@ -39,7 +39,7 @@ describe('SentryProvider', () => {
|
||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||
previewDomain: 'test.dev',
|
||||
showcaseEnabled: false,
|
||||
showcaseModerator: '',
|
||||
showcaseCurator: '',
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
@@ -83,7 +83,7 @@ describe('SentryProvider', () => {
|
||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||
previewDomain: 'test.dev',
|
||||
showcaseEnabled: false,
|
||||
showcaseModerator: '',
|
||||
showcaseCurator: '',
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
@@ -128,7 +128,7 @@ describe('SentryProvider', () => {
|
||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||
previewDomain: 'test.dev',
|
||||
showcaseEnabled: false,
|
||||
showcaseModerator: '',
|
||||
showcaseCurator: '',
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
@@ -176,7 +176,7 @@ describe('SentryProvider', () => {
|
||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||
previewDomain: 'test.dev',
|
||||
showcaseEnabled: false,
|
||||
showcaseModerator: '',
|
||||
showcaseCurator: '',
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
|
||||
@@ -27,6 +27,7 @@ import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
|
||||
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
|
||||
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
|
||||
import { BuildProjectTool } from '@/lib/tools/BuildProjectTool';
|
||||
import { TypecheckProjectTool } from '@/lib/tools/TypecheckProjectTool';
|
||||
import { NostrReadNipTool } from '@/lib/tools/NostrReadNipTool';
|
||||
import { NostrFetchEventTool } from '@/lib/tools/NostrFetchEventTool';
|
||||
import { NostrReadKindTool } from '@/lib/tools/NostrReadKindTool';
|
||||
@@ -213,6 +214,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
npm_add_package: new NpmAddPackageTool(fs, cwd),
|
||||
npm_remove_package: new NpmRemovePackageTool(fs, cwd),
|
||||
build_project: new BuildProjectTool(fs, cwd, esmUrlRef.current),
|
||||
typecheck: new TypecheckProjectTool(fs, cwd),
|
||||
nostr_read_nip: new NostrReadNipTool(),
|
||||
nostr_fetch_event: new NostrFetchEventTool(),
|
||||
nostr_read_kind: new NostrReadKindTool(),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { encodeBase64 } from '@std/encoding/base64';
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
@@ -25,6 +25,8 @@ 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;
|
||||
@@ -67,6 +69,13 @@ 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);
|
||||
@@ -82,6 +91,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
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);
|
||||
@@ -182,18 +197,15 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
|
||||
const sendResponse = useCallback((message: JSONRPCResponse) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
|
||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||
}
|
||||
}, [projectId, previewDomain]);
|
||||
}, [previewOrigin]);
|
||||
|
||||
const sendError = useCallback((message: JSONRPCResponse) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||
}
|
||||
}, [projectId, previewDomain]);
|
||||
}, [previewOrigin]);
|
||||
|
||||
const handleConsoleMessage = useCallback((message: {
|
||||
jsonrpc: '2.0';
|
||||
@@ -248,6 +260,17 @@ 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 = {
|
||||
@@ -256,10 +279,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
params: params || {},
|
||||
id: Date.now()
|
||||
};
|
||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||
}
|
||||
}, [projectId, previewDomain]);
|
||||
}, [previewOrigin]);
|
||||
|
||||
const navigateIframe = useCallback((url: string) => {
|
||||
// Send semantic path directly (e.g., "/about", "/contact")
|
||||
@@ -268,13 +290,31 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
}, [sendNavigationCommand]);
|
||||
|
||||
const refreshIframe = useCallback(() => {
|
||||
sendNavigationCommand('refresh');
|
||||
}, [sendNavigationCommand]);
|
||||
// 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);
|
||||
}, []);
|
||||
|
||||
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;
|
||||
@@ -282,16 +322,15 @@ 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 !== expectedOrigin) {
|
||||
console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`);
|
||||
if (url.origin !== previewOrigin) {
|
||||
console.log(`Invalid origin: ${url.origin}, expected: ${previewOrigin}`);
|
||||
sendError({
|
||||
jsonrpc: '2.0',
|
||||
error: {
|
||||
code: -32003,
|
||||
message: 'Invalid URL - origin mismatch',
|
||||
data: { url: fetchRequest.url, expectedOrigin }
|
||||
data: { url: fetchRequest.url, expectedOrigin: previewOrigin }
|
||||
},
|
||||
id
|
||||
});
|
||||
@@ -301,24 +340,52 @@ 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': getContentType(filePath),
|
||||
'Content-Type': contentType,
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
body: encodeBase64(bytes),
|
||||
body,
|
||||
},
|
||||
id
|
||||
});
|
||||
@@ -349,6 +416,10 @@ 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: {
|
||||
@@ -358,7 +429,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
'Content-Type': 'text/html',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
body: encodeBase64(bytes),
|
||||
body,
|
||||
},
|
||||
id
|
||||
});
|
||||
@@ -389,32 +460,37 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
id
|
||||
});
|
||||
}
|
||||
}, [projectId, projectsManager, sendResponse, sendError, previewDomain]);
|
||||
}, [projectId, projectsManager, sendResponse, sendError, previewOrigin, injectScript]);
|
||||
|
||||
// Setup messaging protocol for iframe communication
|
||||
useEffect(() => {
|
||||
const handleMessage = (event: MessageEvent) => {
|
||||
// Verify origin for security
|
||||
const expectedOrigin = `https://${projectId}.${previewDomain}`;
|
||||
if (event.origin !== expectedOrigin) {
|
||||
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
|
||||
if (event.origin !== previewOrigin) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = event.data;
|
||||
console.log('Received message from iframe:', message);
|
||||
if (message.jsonrpc === '2.0' && message.method === 'fetch') {
|
||||
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') {
|
||||
handleFetch(message);
|
||||
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
|
||||
} else if (message.method === 'console') {
|
||||
handleConsoleMessage(message);
|
||||
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
|
||||
} else if (message.method === 'updateNavigationState') {
|
||||
handleUpdateNavigationState(message);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleMessage);
|
||||
return () => window.removeEventListener('message', handleMessage);
|
||||
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
|
||||
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, sendNotification, previewOrigin]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedFile) {
|
||||
@@ -645,12 +721,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
)}
|
||||
>
|
||||
<iframe
|
||||
key={projectId}
|
||||
key={`${projectId}:${iframeReloadKey}`}
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.${previewDomain}/`}
|
||||
src={`${previewOrigin}/`}
|
||||
className="w-full h-full border-0"
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin allow-forms"
|
||||
allow="microphone; camera; display-capture; geolocation; clipboard-read; clipboard-write; encrypted-media; fullscreen; autoplay; midi; accelerometer; gyroscope; magnetometer; ambient-light-sensor; payment; usb; xr-spatial-tracking"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
Search,
|
||||
Clipboard,
|
||||
AppWindow,
|
||||
FileCheck,
|
||||
} from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { VFSImage } from '@/components/VFSImage';
|
||||
@@ -240,6 +241,14 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
|
||||
errorTitle: 'Failed to build project',
|
||||
};
|
||||
|
||||
case 'typecheck':
|
||||
return {
|
||||
icon: FileCheck,
|
||||
title: 'Typechecked project',
|
||||
callingTitle: 'Typechecking project',
|
||||
errorTitle: 'Found type errors',
|
||||
};
|
||||
|
||||
case 'nostr_read_nip':
|
||||
return {
|
||||
icon: BookOpen,
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
// NOTE: This file is stable and usually should not be modified.
|
||||
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
||||
|
||||
import React, { useRef, useState, useEffect } from 'react';
|
||||
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Shield, AlertTriangle, UserPlus, Sparkles } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { cn } from '@/lib/utils';
|
||||
import LoginPanel from '@/components/auth/LoginPanel';
|
||||
|
||||
interface LoginDialogProps {
|
||||
isOpen: boolean;
|
||||
@@ -18,47 +17,21 @@ interface LoginDialogProps {
|
||||
onSignup?: () => void;
|
||||
}
|
||||
|
||||
const validateNsec = (nsec: string) => {
|
||||
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
|
||||
};
|
||||
|
||||
const validateBunkerUri = (uri: string) => {
|
||||
return uri.startsWith('bunker://');
|
||||
};
|
||||
|
||||
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isFileLoading, setIsFileLoading] = useState(false);
|
||||
const [nsec, setNsec] = useState('');
|
||||
const [bunkerUri, setBunkerUri] = useState('');
|
||||
const [errors, setErrors] = useState<{
|
||||
nsec?: string;
|
||||
bunker?: string;
|
||||
file?: string;
|
||||
extension?: string;
|
||||
}>({});
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [isExtensionLoading, setIsExtensionLoading] = useState(false);
|
||||
const [extensionError, setExtensionError] = useState<string | null>(null);
|
||||
const login = useLoginActions();
|
||||
|
||||
// Reset all state when dialog opens/closes
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
// Reset state when dialog opens
|
||||
setIsLoading(false);
|
||||
setIsFileLoading(false);
|
||||
setNsec('');
|
||||
setBunkerUri('');
|
||||
setErrors({});
|
||||
// Reset file input
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = '';
|
||||
}
|
||||
setIsExtensionLoading(false);
|
||||
setExtensionError(null);
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
const handleExtensionLogin = async () => {
|
||||
setIsLoading(true);
|
||||
setErrors(prev => ({ ...prev, extension: undefined }));
|
||||
setIsExtensionLoading(true);
|
||||
setExtensionError(null);
|
||||
|
||||
try {
|
||||
if (!('nostr' in window)) {
|
||||
@@ -69,107 +42,15 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
onClose();
|
||||
} catch (e: unknown) {
|
||||
const error = e as Error;
|
||||
console.error('Bunker login failed:', error);
|
||||
console.error('Nsec login failed:', error);
|
||||
console.error('Extension login failed:', error);
|
||||
setErrors(prev => ({
|
||||
...prev,
|
||||
extension: error instanceof Error ? error.message : 'Extension login failed'
|
||||
}));
|
||||
setExtensionError(
|
||||
error instanceof Error ? error.message : 'Extension login failed',
|
||||
);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setIsExtensionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const executeLogin = (key: string) => {
|
||||
setIsLoading(true);
|
||||
setErrors({});
|
||||
|
||||
// Use a timeout to allow the UI to update before the synchronous login call
|
||||
setTimeout(() => {
|
||||
try {
|
||||
login.nsec(key);
|
||||
onLogin();
|
||||
onClose();
|
||||
} catch {
|
||||
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, 50);
|
||||
};
|
||||
|
||||
const handleKeyLogin = () => {
|
||||
if (!nsec.trim()) {
|
||||
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validateNsec(nsec)) {
|
||||
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
|
||||
return;
|
||||
}
|
||||
executeLogin(nsec);
|
||||
};
|
||||
|
||||
const handleBunkerLogin = async () => {
|
||||
if (!bunkerUri.trim()) {
|
||||
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validateBunkerUri(bunkerUri)) {
|
||||
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setErrors(prev => ({ ...prev, bunker: undefined }));
|
||||
|
||||
try {
|
||||
await login.bunker(bunkerUri);
|
||||
onLogin();
|
||||
onClose();
|
||||
// Clear the URI from memory
|
||||
setBunkerUri('');
|
||||
} catch {
|
||||
setErrors(prev => ({
|
||||
...prev,
|
||||
bunker: 'Failed to connect to bunker. Please check the URI.'
|
||||
}));
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
setIsFileLoading(true);
|
||||
setErrors({});
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
setIsFileLoading(false);
|
||||
const content = event.target?.result as string;
|
||||
if (content) {
|
||||
const trimmedContent = content.trim();
|
||||
if (validateNsec(trimmedContent)) {
|
||||
executeLogin(trimmedContent);
|
||||
} else {
|
||||
setErrors({ file: 'File does not contain a valid secret key.' });
|
||||
}
|
||||
} else {
|
||||
setErrors({ file: 'Could not read file content.' });
|
||||
}
|
||||
};
|
||||
reader.onerror = () => {
|
||||
setIsFileLoading(false);
|
||||
setErrors({ file: 'Failed to read file.' });
|
||||
};
|
||||
reader.readAsText(file);
|
||||
};
|
||||
|
||||
const handleSignupClick = () => {
|
||||
onClose();
|
||||
if (onSignup) {
|
||||
@@ -177,7 +58,12 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
}
|
||||
};
|
||||
|
||||
const defaultTab = 'nostr' in window ? 'extension' : 'key';
|
||||
const handleLoggedIn = () => {
|
||||
onLogin();
|
||||
onClose();
|
||||
};
|
||||
|
||||
const hasExtension = typeof window !== 'undefined' && 'nostr' in window;
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
@@ -225,148 +111,29 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Login Methods */}
|
||||
<Tabs defaultValue={defaultTab} className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4">
|
||||
<TabsTrigger value="extension" className="flex items-center gap-2">
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Extension</span>
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="key" className="flex items-center gap-2">
|
||||
<KeyRound className="w-4 h-4" />
|
||||
<span>Key</span>
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="bunker" className="flex items-center gap-2">
|
||||
<Cloud className="w-4 h-4" />
|
||||
<span>Bunker</span>
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value='extension' className='space-y-3 bg-muted'>
|
||||
{errors.extension && (
|
||||
{/* Unified login panel — QR + nsec/bunker input + file upload */}
|
||||
<LoginPanel onLoggedIn={handleLoggedIn} />
|
||||
|
||||
{/* Extension login (only shown when a NIP-07 extension is present) */}
|
||||
{hasExtension && (
|
||||
<div className='rounded-lg bg-muted p-3 space-y-2'>
|
||||
{extensionError && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>{errors.extension}</AlertDescription>
|
||||
<AlertDescription>{extensionError}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<div className='text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800'>
|
||||
<Shield className='w-12 h-12 mx-auto mb-3 text-primary' />
|
||||
<p className='text-sm text-gray-600 dark:text-gray-300 mb-4'>
|
||||
Login with one click using the browser extension
|
||||
</p>
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
className='w-full rounded-full py-4'
|
||||
onClick={handleExtensionLogin}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? 'Logging in...' : 'Login with Extension'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='key' className='space-y-4'>
|
||||
<div className='space-y-4'>
|
||||
<div className='space-y-2'>
|
||||
<label htmlFor='nsec' className='text-sm font-medium'>
|
||||
Secret Key (nsec)
|
||||
</label>
|
||||
<Input
|
||||
id='nsec'
|
||||
type="password"
|
||||
value={nsec}
|
||||
onChange={(e) => {
|
||||
setNsec(e.target.value);
|
||||
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
|
||||
}}
|
||||
className={`rounded-lg ${
|
||||
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
|
||||
}`}
|
||||
placeholder='nsec1...'
|
||||
autoComplete="off"
|
||||
/>
|
||||
{errors.nsec && (
|
||||
<p className="text-sm text-red-500">{errors.nsec}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
className='w-full rounded-full py-3'
|
||||
onClick={handleKeyLogin}
|
||||
disabled={isLoading || !nsec.trim()}
|
||||
>
|
||||
{isLoading ? 'Verifying...' : 'Log In'}
|
||||
</Button>
|
||||
|
||||
<div className='relative'>
|
||||
<div className='absolute inset-0 flex items-center'>
|
||||
<div className='w-full border-t border-muted'></div>
|
||||
</div>
|
||||
<div className='relative flex justify-center text-xs'>
|
||||
<span className='px-2 bg-background text-muted-foreground'>
|
||||
or
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='text-center'>
|
||||
<input
|
||||
type='file'
|
||||
accept='.txt'
|
||||
className='hidden'
|
||||
ref={fileInputRef}
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
<Button
|
||||
variant='outline'
|
||||
className='w-full'
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={isLoading || isFileLoading}
|
||||
>
|
||||
<Upload className='w-4 h-4 mr-2' />
|
||||
{isFileLoading ? 'Reading File...' : 'Upload Your Key File'}
|
||||
</Button>
|
||||
{errors.file && (
|
||||
<p className="text-sm text-red-500 mt-2">{errors.file}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='bunker' className='space-y-3 bg-muted'>
|
||||
<div className='space-y-2'>
|
||||
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
|
||||
Bunker URI
|
||||
</label>
|
||||
<Input
|
||||
id='bunkerUri'
|
||||
value={bunkerUri}
|
||||
onChange={(e) => {
|
||||
setBunkerUri(e.target.value);
|
||||
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
|
||||
}}
|
||||
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
|
||||
errors.bunker ? 'border-red-500' : ''
|
||||
}`}
|
||||
placeholder='bunker://'
|
||||
autoComplete="off"
|
||||
/>
|
||||
{errors.bunker && (
|
||||
<p className="text-sm text-red-500">{errors.bunker}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
className='w-full rounded-full py-4'
|
||||
onClick={handleBunkerLogin}
|
||||
disabled={isLoading || !bunkerUri.trim()}
|
||||
>
|
||||
{isLoading ? 'Connecting...' : 'Login with Bunker'}
|
||||
</Button>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
<Button
|
||||
variant='outline'
|
||||
className='w-full rounded-full'
|
||||
onClick={handleExtensionLogin}
|
||||
disabled={isExtensionLoading}
|
||||
>
|
||||
<Shield className='w-4 h-4 mr-2' />
|
||||
{isExtensionLoading ? 'Logging in…' : 'Sign in with browser extension'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import QRCode from 'qrcode';
|
||||
import { ExternalLink, Loader2, Upload } from 'lucide-react';
|
||||
import {
|
||||
generateNostrConnectParams,
|
||||
generateNostrConnectURI,
|
||||
type NostrConnectParams,
|
||||
} from '@nostrify/react/login';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
|
||||
interface LoginPanelProps {
|
||||
/** Called after a successful login (nostrconnect QR, nsec, bunker URI, or key file). */
|
||||
onLoggedIn: () => void;
|
||||
}
|
||||
|
||||
const NSEC_REGEX = /^nsec1[a-zA-Z0-9]{58}$/;
|
||||
|
||||
type InputKind = 'nsec' | 'bunker' | 'unknown';
|
||||
|
||||
const detectInputKind = (value: string): InputKind => {
|
||||
const trimmed = value.trim();
|
||||
if (NSEC_REGEX.test(trimmed)) return 'nsec';
|
||||
if (trimmed.startsWith('bunker://')) return 'bunker';
|
||||
return 'unknown';
|
||||
};
|
||||
|
||||
// UA-based mobile check. Distinct from the viewport-based `useIsMobile` —
|
||||
// here we care whether the platform can deep-link into a signer app, not
|
||||
// whether the window is narrow.
|
||||
const isMobileDevice = (): boolean => {
|
||||
if (typeof navigator === 'undefined') return false;
|
||||
return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
|
||||
};
|
||||
|
||||
/**
|
||||
* Unified login panel for all string-based methods:
|
||||
* - `nostrconnect://` flow gated behind a button. Desktop reveals a QR code;
|
||||
* mobile redirects to a signer-app deep-link.
|
||||
* - A single paste input that accepts either an `nsec1…` secret key OR a
|
||||
* `bunker://` URI — the type is detected from the string on submit.
|
||||
* - File upload for plain-text nsec / bunker URI files.
|
||||
*
|
||||
* The nostrconnect session is only opened when the user clicks the button
|
||||
* (so the dialog doesn't open a relay subscription for users who just want
|
||||
* to paste a key). Panel unmount aborts any in-flight listener.
|
||||
*/
|
||||
export const LoginPanel: React.FC<LoginPanelProps> = ({ onLoggedIn }) => {
|
||||
const login = useLoginActions();
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Session is gated: stays idle until the user clicks the remote-signer
|
||||
// button. Bumping `sessionToken` while started restarts the session
|
||||
// (used by "Try again").
|
||||
const [sessionStarted, setSessionStarted] = useState(false);
|
||||
const [sessionToken, setSessionToken] = useState(0);
|
||||
const [nostrConnectUri, setNostrConnectUri] = useState('');
|
||||
const [qrDataUrl, setQrDataUrl] = useState('');
|
||||
const [connectError, setConnectError] = useState<string | null>(null);
|
||||
const [hasOpenedSigner, setHasOpenedSigner] = useState(false);
|
||||
// Mobile-only: tracks "user pressed Open signer app but the URI isn't
|
||||
// generated yet — navigate as soon as it is."
|
||||
const [pendingNavigate, setPendingNavigate] = useState(false);
|
||||
|
||||
// Unified text input — accepts nsec or bunker URI, type detected on submit.
|
||||
const [input, setInput] = useState('');
|
||||
const [inputError, setInputError] = useState<string | null>(null);
|
||||
const [isInputLoggingIn, setIsInputLoggingIn] = useState(false);
|
||||
const [isFileLoading, setIsFileLoading] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const abortControllerRef = useRef<AbortController | null>(null);
|
||||
// Refs so the listener effect can read the latest values without
|
||||
// re-running on every parent re-render. `config` is rebuilt every render
|
||||
// by AppProvider, so we must NOT depend on it in the effect's dep array —
|
||||
// otherwise the in-flight subscription is torn down on each parent render.
|
||||
const loginRef = useRef(login);
|
||||
const onLoggedInRef = useRef(onLoggedIn);
|
||||
const configRef = useRef(config);
|
||||
|
||||
useEffect(() => {
|
||||
loginRef.current = login;
|
||||
onLoggedInRef.current = onLoggedIn;
|
||||
configRef.current = config;
|
||||
});
|
||||
|
||||
const isMobile = isMobileDevice();
|
||||
|
||||
// Open a nostrconnect session and start listening for the signer. Runs
|
||||
// only after the user clicks the start button (`sessionStarted=true`),
|
||||
// and re-runs when `sessionToken` is bumped by "Try again".
|
||||
useEffect(() => {
|
||||
if (!sessionStarted) return;
|
||||
|
||||
let cancelled = false;
|
||||
const controller = new AbortController();
|
||||
abortControllerRef.current?.abort();
|
||||
abortControllerRef.current = controller;
|
||||
|
||||
const run = async () => {
|
||||
const relayUrls = (configRef.current.relayMetadata?.relays ?? [])
|
||||
.filter((r) => r.write !== false)
|
||||
.map((r) => r.url);
|
||||
|
||||
if (relayUrls.length === 0) {
|
||||
if (!cancelled) {
|
||||
setConnectError(
|
||||
'No relays configured. Add a relay in settings to use this login method.',
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const params: NostrConnectParams = generateNostrConnectParams(relayUrls);
|
||||
const uri = generateNostrConnectURI(params, {
|
||||
name: 'Shakespeare',
|
||||
callback: isMobileDevice()
|
||||
? `${window.location.origin}/remoteloginsuccess`
|
||||
: undefined,
|
||||
});
|
||||
|
||||
// Publish the URI ASAP so a pending mobile navigate can fire while
|
||||
// the QR renders in the background.
|
||||
if (cancelled) return;
|
||||
setNostrConnectUri(uri);
|
||||
setConnectError(null);
|
||||
|
||||
// Desktop renders a QR; mobile redirects, so skip the work there.
|
||||
if (!isMobileDevice()) {
|
||||
try {
|
||||
const dataUrl = await QRCode.toDataURL(uri, {
|
||||
width: 400,
|
||||
margin: 2,
|
||||
color: { dark: '#000000', light: '#FFFFFF' },
|
||||
});
|
||||
if (cancelled) return;
|
||||
setQrDataUrl(dataUrl);
|
||||
} catch (e) {
|
||||
console.error('Failed to render nostrconnect QR:', e);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await loginRef.current.nostrconnect(params, controller.signal);
|
||||
if (cancelled || controller.signal.aborted) return;
|
||||
onLoggedInRef.current();
|
||||
} catch (error) {
|
||||
if (cancelled || controller.signal.aborted) return;
|
||||
if (error instanceof Error && error.name === 'AbortError') return;
|
||||
console.error('nostrconnect failed:', error);
|
||||
setConnectError(
|
||||
error instanceof Error ? error.message : 'Failed to connect to signer.',
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
void run();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
controller.abort();
|
||||
};
|
||||
// Intentional: deps limited to `sessionStarted` + `sessionToken` so
|
||||
// parent re-renders don't tear down the in-flight subscription. Config
|
||||
// + login are read via refs that are updated each render.
|
||||
}, [sessionStarted, sessionToken]);
|
||||
|
||||
// Mobile: once the URI is ready and the user already tapped "Open signer
|
||||
// app", navigate to the deep-link. Runs once per click; the flag is
|
||||
// consumed here.
|
||||
useEffect(() => {
|
||||
if (!pendingNavigate || !nostrConnectUri || connectError) return;
|
||||
setPendingNavigate(false);
|
||||
setHasOpenedSigner(true);
|
||||
window.location.href = nostrConnectUri;
|
||||
}, [pendingNavigate, nostrConnectUri, connectError]);
|
||||
|
||||
const handleStartDesktopSession = () => {
|
||||
setSessionStarted(true);
|
||||
};
|
||||
|
||||
const handleOpenSignerApp = () => {
|
||||
// Mobile: arm the navigate-when-ready effect and start the session.
|
||||
// If the session is already running (e.g. retry after error), this
|
||||
// just navigates with the existing URI.
|
||||
setPendingNavigate(true);
|
||||
setSessionStarted(true);
|
||||
};
|
||||
|
||||
const handleConnectRetry = useCallback(() => {
|
||||
setNostrConnectUri('');
|
||||
setQrDataUrl('');
|
||||
setConnectError(null);
|
||||
setHasOpenedSigner(false);
|
||||
setPendingNavigate(false);
|
||||
setSessionToken((t) => t + 1);
|
||||
}, []);
|
||||
|
||||
const submitInput = async (rawValue: string) => {
|
||||
const trimmed = rawValue.trim();
|
||||
if (!trimmed) {
|
||||
setInputError('Enter a secret key or bunker URI');
|
||||
return;
|
||||
}
|
||||
|
||||
const kind = detectInputKind(trimmed);
|
||||
if (kind === 'unknown') {
|
||||
setInputError('Unrecognized format. Expected nsec1… or bunker://…');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsInputLoggingIn(true);
|
||||
setInputError(null);
|
||||
|
||||
try {
|
||||
if (kind === 'nsec') {
|
||||
// login.nsec is synchronous but throws on bad keys.
|
||||
login.nsec(trimmed);
|
||||
} else {
|
||||
await login.bunker(trimmed);
|
||||
}
|
||||
onLoggedIn();
|
||||
} catch {
|
||||
setInputError(
|
||||
kind === 'nsec'
|
||||
? "Failed to log in with this key. Please check that it's correct."
|
||||
: 'Failed to connect to bunker. Please check the URI.',
|
||||
);
|
||||
} finally {
|
||||
setIsInputLoggingIn(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
void submitInput(input);
|
||||
};
|
||||
|
||||
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
setIsFileLoading(true);
|
||||
setInputError(null);
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
setIsFileLoading(false);
|
||||
const content = event.target?.result as string;
|
||||
if (!content) {
|
||||
setInputError('Could not read file content.');
|
||||
return;
|
||||
}
|
||||
const trimmed = content.trim();
|
||||
if (detectInputKind(trimmed) === 'unknown') {
|
||||
setInputError('File does not contain a valid nsec or bunker URI.');
|
||||
return;
|
||||
}
|
||||
setInput(trimmed);
|
||||
void submitInput(trimmed);
|
||||
};
|
||||
reader.onerror = () => {
|
||||
setIsFileLoading(false);
|
||||
setInputError('Failed to read file.');
|
||||
};
|
||||
reader.readAsText(file);
|
||||
// Reset so the same file can be selected again after a failure.
|
||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
||||
};
|
||||
|
||||
const renderRemoteSignerSection = () => {
|
||||
// Idle: just a button. Clicking it generates the session and either
|
||||
// reveals the QR (desktop) or deep-links to a signer app (mobile).
|
||||
if (!sessionStarted) {
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={isMobile ? handleOpenSignerApp : handleStartDesktopSession}
|
||||
className="w-full h-12"
|
||||
>
|
||||
<ExternalLink className="w-5 h-5 mr-2" />
|
||||
{isMobile ? 'Open signer app' : 'Login with remote signer'}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
if (connectError) {
|
||||
return (
|
||||
<div className="flex flex-col items-center space-y-3 py-4 w-full">
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{connectError}</AlertDescription>
|
||||
</Alert>
|
||||
<Button variant="outline" onClick={handleConnectRetry}>
|
||||
Try again
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isMobile && hasOpenedSigner) {
|
||||
return (
|
||||
<div className="flex flex-col items-center space-y-4 py-6 w-full">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
||||
<p className="text-sm text-muted-foreground text-center">
|
||||
Waiting for signer…
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleConnectRetry}
|
||||
className="text-sm text-primary hover:underline underline-offset-4 font-medium"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isMobile && qrDataUrl) {
|
||||
return (
|
||||
<div className="flex flex-col items-center space-y-4 w-full">
|
||||
<div className="p-3 bg-white rounded-xl">
|
||||
<img
|
||||
src={qrDataUrl}
|
||||
alt="nostrconnect QR code"
|
||||
width={200}
|
||||
height={200}
|
||||
className="block"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground text-center max-w-[260px]">
|
||||
Scan this QR code with your Nostr signer app to log in.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleConnectRetry}
|
||||
className="text-xs text-muted-foreground hover:text-foreground underline underline-offset-4"
|
||||
>
|
||||
Generate a new code
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Mobile pre-navigate or desktop pre-QR — short transient state.
|
||||
return (
|
||||
<div className="flex items-center justify-center h-[120px]">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{renderRemoteSignerSection()}
|
||||
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t"></div>
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-background px-2 text-muted-foreground">
|
||||
or paste a key or URI
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
type="password"
|
||||
value={input}
|
||||
onChange={(e) => {
|
||||
setInput(e.target.value);
|
||||
if (inputError) setInputError(null);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && input.trim() && !isInputLoggingIn) {
|
||||
e.preventDefault();
|
||||
handleSubmit();
|
||||
}
|
||||
}}
|
||||
placeholder="nsec1… or bunker://…"
|
||||
className={inputError ? 'border-red-500' : ''}
|
||||
autoComplete="off"
|
||||
/>
|
||||
{inputError && (
|
||||
<p className="text-sm text-red-500">{inputError}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={isInputLoggingIn || isFileLoading || !input.trim()}
|
||||
className="flex-1"
|
||||
>
|
||||
{isInputLoggingIn ? 'Adding…' : 'Add account'}
|
||||
</Button>
|
||||
|
||||
<input
|
||||
type="file"
|
||||
accept=".txt"
|
||||
className="hidden"
|
||||
ref={fileInputRef}
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={isInputLoggingIn || isFileLoading}
|
||||
className="px-3"
|
||||
title="Upload a file containing an nsec or bunker URI"
|
||||
>
|
||||
{isFileLoading ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<Upload className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LoginPanel;
|
||||
@@ -1,13 +1,7 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Cloud, Upload } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
// Alert components removed as they're not used in the simplified design
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// Only using key-add step now
|
||||
import LoginPanel from '@/components/auth/LoginPanel';
|
||||
|
||||
interface SimpleLoginDialogProps {
|
||||
isOpen: boolean;
|
||||
@@ -16,55 +10,27 @@ interface SimpleLoginDialogProps {
|
||||
onSignup?: () => void;
|
||||
}
|
||||
|
||||
const validateNsec = (nsec: string) => {
|
||||
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
|
||||
};
|
||||
|
||||
const validateBunkerUri = (uri: string) => {
|
||||
return uri.startsWith('bunker://');
|
||||
};
|
||||
|
||||
const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
onLogin,
|
||||
onSignup
|
||||
}) => {
|
||||
// Removed step state - we only have one step now
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isFileLoading, setIsFileLoading] = useState(false);
|
||||
const [nsec, setNsec] = useState('');
|
||||
const [bunkerUri, setBunkerUri] = useState('');
|
||||
const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec');
|
||||
const [errors, setErrors] = useState<{
|
||||
nsec?: string;
|
||||
bunker?: string;
|
||||
extension?: string;
|
||||
file?: string;
|
||||
}>({});
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [isExtensionLoading, setIsExtensionLoading] = useState(false);
|
||||
const [extensionError, setExtensionError] = useState<string | null>(null);
|
||||
|
||||
const login = useLoginActions();
|
||||
|
||||
// Reset state when dialog opens/closes
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setIsLoading(false);
|
||||
setIsFileLoading(false);
|
||||
setNsec('');
|
||||
setBunkerUri('');
|
||||
setActiveTab('nsec');
|
||||
setErrors({});
|
||||
// Reset file input
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = '';
|
||||
}
|
||||
setIsExtensionLoading(false);
|
||||
setExtensionError(null);
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
const handleExtensionLogin = async () => {
|
||||
setIsLoading(true);
|
||||
setErrors(prev => ({ ...prev, extension: undefined }));
|
||||
setIsExtensionLoading(true);
|
||||
setExtensionError(null);
|
||||
|
||||
try {
|
||||
if (!('nostr' in window)) {
|
||||
@@ -75,103 +41,12 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
onClose();
|
||||
} catch (e: unknown) {
|
||||
const error = e as Error;
|
||||
setErrors(prev => ({
|
||||
...prev,
|
||||
extension: error instanceof Error ? error.message : 'Extension login failed'
|
||||
}));
|
||||
setExtensionError(error instanceof Error ? error.message : 'Extension login failed');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setIsExtensionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyLogin = () => {
|
||||
if (!nsec.trim()) {
|
||||
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validateNsec(nsec)) {
|
||||
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
|
||||
return;
|
||||
}
|
||||
executeLogin(nsec);
|
||||
};
|
||||
|
||||
const handleBunkerLogin = async () => {
|
||||
if (!bunkerUri.trim()) {
|
||||
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validateBunkerUri(bunkerUri)) {
|
||||
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setErrors(prev => ({ ...prev, bunker: undefined }));
|
||||
|
||||
try {
|
||||
await login.bunker(bunkerUri);
|
||||
onLogin();
|
||||
onClose();
|
||||
setBunkerUri('');
|
||||
} catch {
|
||||
setErrors(prev => ({
|
||||
...prev,
|
||||
bunker: 'Failed to connect to bunker. Please check the URI.'
|
||||
}));
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const executeLogin = (key: string) => {
|
||||
setIsLoading(true);
|
||||
setErrors({});
|
||||
|
||||
// Use a timeout to allow the UI to update before the synchronous login call
|
||||
setTimeout(() => {
|
||||
try {
|
||||
login.nsec(key);
|
||||
onLogin();
|
||||
onClose();
|
||||
} catch {
|
||||
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, 50);
|
||||
};
|
||||
|
||||
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
setIsFileLoading(true);
|
||||
setErrors({});
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
setIsFileLoading(false);
|
||||
const content = event.target?.result as string;
|
||||
if (content) {
|
||||
const trimmedContent = content.trim();
|
||||
if (validateNsec(trimmedContent)) {
|
||||
executeLogin(trimmedContent);
|
||||
} else {
|
||||
setErrors({ file: 'File does not contain a valid secret key.' });
|
||||
}
|
||||
} else {
|
||||
setErrors({ file: 'Could not read file content.' });
|
||||
}
|
||||
};
|
||||
reader.onerror = () => {
|
||||
setIsFileLoading(false);
|
||||
setErrors({ file: 'Failed to read file.' });
|
||||
};
|
||||
reader.readAsText(file);
|
||||
};
|
||||
|
||||
const handleSignupClick = () => {
|
||||
onClose();
|
||||
if (onSignup) {
|
||||
@@ -179,6 +54,11 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
}
|
||||
};
|
||||
|
||||
const handleLoggedIn = () => {
|
||||
onLogin();
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent className="max-w-sm">
|
||||
@@ -186,159 +66,41 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
<DialogTitle className="text-center">Log in</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col items-center space-y-6 py-6">
|
||||
<div className="flex flex-col items-center space-y-6 py-4">
|
||||
<div className="text-center">
|
||||
<h3 className="font-semibold mb-2">Welcome back to Shakespeare</h3>
|
||||
<p className="text-sm text-muted-foreground">Sign in to your existing account</p>
|
||||
</div>
|
||||
|
||||
<div className="w-40 h-40 flex items-center justify-center">
|
||||
<div className="w-40 h-40 bg-primary/10 rounded-full flex items-center justify-center">
|
||||
<span className="text-8xl">🔑</span>
|
||||
</div>
|
||||
<div className="w-full">
|
||||
<LoginPanel onLoggedIn={handleLoggedIn} />
|
||||
</div>
|
||||
|
||||
<div className="w-full space-y-4">
|
||||
{/* Tab selector */}
|
||||
<div className="flex space-x-1 bg-muted rounded-lg p-1">
|
||||
<button
|
||||
onClick={() => setActiveTab('nsec')}
|
||||
className={cn(
|
||||
"flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors",
|
||||
activeTab === 'nsec'
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
Secret Key
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab('bunker')}
|
||||
className={cn(
|
||||
"flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors",
|
||||
activeTab === 'bunker'
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
Bunker
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{activeTab === 'nsec' && (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
type="password"
|
||||
value={nsec}
|
||||
onChange={(e) => {
|
||||
setNsec(e.target.value);
|
||||
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
|
||||
}}
|
||||
placeholder="nsec1..."
|
||||
className={errors.nsec ? 'border-red-500' : ''}
|
||||
/>
|
||||
{errors.nsec && (
|
||||
<p className="text-sm text-red-500">{errors.nsec}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
size="lg"
|
||||
onClick={handleKeyLogin}
|
||||
disabled={isLoading || !nsec.trim()}
|
||||
className="flex-1"
|
||||
>
|
||||
{isLoading ? 'Verifying...' : 'Add Key'}
|
||||
</Button>
|
||||
|
||||
<input
|
||||
type="file"
|
||||
accept=".txt"
|
||||
className="hidden"
|
||||
ref={fileInputRef}
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="lg"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={isLoading || isFileLoading}
|
||||
className="px-3"
|
||||
>
|
||||
<Upload className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{errors.file && (
|
||||
<p className="text-sm text-red-500 text-center">{errors.file}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'bunker' && (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
value={bunkerUri}
|
||||
onChange={(e) => {
|
||||
setBunkerUri(e.target.value);
|
||||
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
|
||||
}}
|
||||
placeholder="bunker://"
|
||||
className={errors.bunker ? 'border-red-500' : ''}
|
||||
/>
|
||||
{errors.bunker && (
|
||||
<p className="text-sm text-red-500">{errors.bunker}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
size="lg"
|
||||
onClick={handleBunkerLogin}
|
||||
disabled={isLoading || !bunkerUri.trim()}
|
||||
className="w-full"
|
||||
{window.nostr && (
|
||||
<div className="w-full rounded-lg bg-muted p-3">
|
||||
<p className="text-xs text-center">
|
||||
<button
|
||||
onClick={handleExtensionLogin}
|
||||
className="text-blue-500 hover:underline disabled:opacity-50"
|
||||
disabled={isExtensionLoading}
|
||||
>
|
||||
<Cloud className="w-4 h-4 mr-2" />
|
||||
{isLoading ? 'Connecting...' : 'Connect'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t"></div>
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-background px-2 text-muted-foreground">or</span>
|
||||
</div>
|
||||
{isExtensionLoading ? 'Connecting…' : 'Sign in with browser extension'}
|
||||
</button>
|
||||
</p>
|
||||
{extensionError && (
|
||||
<p className="text-xs text-red-500 text-center mt-2">{extensionError}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Extension indicator - only show if extension is detected */}
|
||||
{window.nostr && (
|
||||
<div className="rounded-lg bg-muted p-3">
|
||||
<p className="text-xs text-center">
|
||||
<button
|
||||
onClick={handleExtensionLogin}
|
||||
className="text-blue-500 hover:underline"
|
||||
disabled={isLoading}
|
||||
>
|
||||
Sign in with browser extension
|
||||
</button>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-center space-x-2 text-xs">
|
||||
<span className="text-muted-foreground">New to Shakespeare?</span>
|
||||
<button
|
||||
onClick={handleSignupClick}
|
||||
className="text-blue-500 hover:underline"
|
||||
>
|
||||
Create Account
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex justify-center space-x-2 text-xs">
|
||||
<span className="text-muted-foreground">New to Shakespeare?</span>
|
||||
<button
|
||||
onClick={handleSignupClick}
|
||||
className="text-blue-500 hover:underline"
|
||||
>
|
||||
Create Account
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
@@ -346,4 +108,4 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
);
|
||||
};
|
||||
|
||||
export default SimpleLoginDialog;
|
||||
export default SimpleLoginDialog;
|
||||
@@ -612,6 +612,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
<span className="font-medium">{nsiteVfsConfig.title}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Relays</span>
|
||||
<span className="font-medium">{relayCount} configured</span>
|
||||
@@ -798,6 +799,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
|
||||
@@ -44,14 +44,14 @@ export interface AppConfig {
|
||||
faviconUrl: string;
|
||||
/** Nostr Git web URL template (e.g., "https://nostrhub.io/{naddr}") */
|
||||
ngitWebUrl: string;
|
||||
/** Preview domain for iframe sandboxing (e.g., "local-shakespeare.dev") */
|
||||
/** Preview domain for iframe sandboxing (e.g., "iframe.diy") */
|
||||
previewDomain: string;
|
||||
/** Selected language */
|
||||
language?: string;
|
||||
/** Whether to show the showcase section */
|
||||
showcaseEnabled: boolean;
|
||||
/** Npub of the showcase moderator */
|
||||
showcaseModerator: string;
|
||||
/** NIP-19 identifier (note1, nevent1, or naddr1) pointing at an event with p tags used as curator authors */
|
||||
showcaseCurator: string;
|
||||
/** VFS path for projects directory */
|
||||
fsPathProjects: string;
|
||||
/** VFS path for config directory */
|
||||
|
||||
@@ -1,24 +1,9 @@
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
// Kind 31733 for app submissions (addressable events)
|
||||
const APP_SUBMISSION_KIND = 31733;
|
||||
|
||||
// The moderator npub and hex
|
||||
const MODERATOR_NPUB = 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc';
|
||||
const MODERATOR_HEX = (() => {
|
||||
try {
|
||||
const decoded = nip19.decode(MODERATOR_NPUB);
|
||||
return decoded.type === 'npub' ? decoded.data : '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
})();
|
||||
|
||||
// Soapbox team follow pack naddr (same as used on About page)
|
||||
const SOAPBOX_TEAM_NADDR = 'naddr1qvzqqqyckypzpyexz3t34l966ngh5xg7u2q788hthdqmj0av3lv8s2tz9t43zt6dqqxxkdrsx4mnqm3jxfeh2ess5pyrw';
|
||||
import type { NostrEvent, NostrFilter, NRelay, NPool } from '@nostrify/nostrify';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
|
||||
export interface AppSubmission extends NostrEvent {
|
||||
appName: string;
|
||||
@@ -26,195 +11,171 @@ export interface AppSubmission extends NostrEvent {
|
||||
repositoryUrl: string;
|
||||
description: string;
|
||||
appIconUrl: string;
|
||||
screenshotUrl: string;
|
||||
appTags: string[];
|
||||
authorNpub: string;
|
||||
isFeatured: boolean;
|
||||
isApproved: boolean;
|
||||
isHidden: boolean;
|
||||
isHomepage: boolean;
|
||||
bannerUrl: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract pubkeys from the `p` tags of a Nostr event.
|
||||
*/
|
||||
function extractPubkeys(event: NostrEvent): string[] {
|
||||
return event.tags
|
||||
.filter(([name]) => name === 'p')
|
||||
.map(([, pubkey]) => pubkey)
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a NIP-19 identifier (note1, nevent1, or naddr1) to an event.
|
||||
*/
|
||||
async function resolveCuratorEvent(
|
||||
curatorIdentifier: string,
|
||||
nostr: NPool<NRelay>,
|
||||
): Promise<NostrEvent | null> {
|
||||
try {
|
||||
const decoded = nip19.decode(curatorIdentifier);
|
||||
|
||||
if (decoded.type === 'note') {
|
||||
const events = await nostr.query(
|
||||
[{ ids: [decoded.data], limit: 1 }],
|
||||
{ signal: AbortSignal.timeout(3000) },
|
||||
);
|
||||
return events[0] ?? null;
|
||||
}
|
||||
|
||||
if (decoded.type === 'nevent') {
|
||||
const filter: NostrFilter = { ids: [decoded.data.id], limit: 1 };
|
||||
if (decoded.data.author) filter.authors = [decoded.data.author];
|
||||
const events = await nostr.query([filter], { signal: AbortSignal.timeout(3000) });
|
||||
return events[0] ?? null;
|
||||
}
|
||||
|
||||
if (decoded.type === 'naddr') {
|
||||
const { kind, pubkey, identifier } = decoded.data;
|
||||
const events = await nostr.query(
|
||||
[{ kinds: [kind], authors: [pubkey], '#d': [identifier], limit: 1 }],
|
||||
{ signal: AbortSignal.timeout(3000) },
|
||||
);
|
||||
return events[0] ?? null;
|
||||
}
|
||||
} catch {
|
||||
// Invalid identifier or query failure — handled by caller
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a kind 31990 event can render an "Edit with Shakespeare" button.
|
||||
* Requires an `a` tag referencing a kind 30617 git repository event.
|
||||
*/
|
||||
function hasGitRepository(event: NostrEvent): boolean {
|
||||
return event.tags.some(([name, value]) => name === 'a' && value?.startsWith('30617:'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a git clone URL from a kind 30617 `a` tag value (`30617:pubkey:d-tag`).
|
||||
* Returns a nostr:// URI usable with isomorphic-git / Shakespeare clone flow.
|
||||
*/
|
||||
function repositoryUrlFromATag(aTagValue: string): string {
|
||||
const parts = aTagValue.split(':');
|
||||
if (parts.length < 3) return '';
|
||||
const [, pubkey, identifier] = parts;
|
||||
return new NostrURI({ pubkey, identifier }).toString();
|
||||
}
|
||||
|
||||
export function useAppSubmissions() {
|
||||
const { nostr } = useNostr();
|
||||
const { config } = useAppContext();
|
||||
const curatorIdentifier = config.showcaseCurator;
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['nostr', 'app-submissions'],
|
||||
queryKey: ['nostr', 'app-submissions', curatorIdentifier],
|
||||
queryFn: async (): Promise<AppSubmission[]> => {
|
||||
// Get Soapbox team follow pack for auto-approval
|
||||
const teamPubkeys = new Set<string>();
|
||||
try {
|
||||
const decoded = nip19.decode(SOAPBOX_TEAM_NADDR);
|
||||
if (decoded.type === 'naddr') {
|
||||
const addrData = decoded.data;
|
||||
const teamEvents = await nostr.query([{
|
||||
kinds: [addrData.kind],
|
||||
authors: [addrData.pubkey],
|
||||
'#d': [addrData.identifier],
|
||||
limit: 1
|
||||
}], { signal: AbortSignal.timeout(1000) });
|
||||
// No curator configured — nothing to show
|
||||
if (!curatorIdentifier.trim()) return [];
|
||||
|
||||
if (teamEvents.length > 0) {
|
||||
const teamEvent = teamEvents[0];
|
||||
// Extract pubkeys from 'p' tags
|
||||
teamEvent.tags
|
||||
.filter(([name]) => name === 'p')
|
||||
.forEach(([, pubkey]) => {
|
||||
if (pubkey) teamPubkeys.add(pubkey);
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to fetch Soapbox team follow pack:', error);
|
||||
}
|
||||
// 1. Resolve the curator event to extract author pubkeys
|
||||
const curatorEvent = await resolveCuratorEvent(curatorIdentifier, nostr);
|
||||
if (!curatorEvent) return [];
|
||||
|
||||
// Get all app submissions (kind 31733)
|
||||
const submissionEvents = await nostr.query([{
|
||||
kinds: [APP_SUBMISSION_KIND],
|
||||
'#t': ['soapbox-app-submission'],
|
||||
limit: 100,
|
||||
}], { signal: AbortSignal.timeout(3000) });
|
||||
const authorPubkeys = extractPubkeys(curatorEvent);
|
||||
if (authorPubkeys.length === 0) return [];
|
||||
|
||||
// Get list events from moderators (NIP-51 kind 30267)
|
||||
const moderatorListEvents = await nostr.query([{
|
||||
kinds: [30267],
|
||||
authors: [MODERATOR_HEX],
|
||||
'#d': [
|
||||
'soapbox-featured-apps',
|
||||
'soapbox-approved-apps',
|
||||
'soapbox-homepage-apps',
|
||||
],
|
||||
limit: 3,
|
||||
}], { signal: AbortSignal.timeout(1000) });
|
||||
// 2. Query kind 31990 events from those authors tagged with #t:shakespeare
|
||||
const appEvents = await nostr.query(
|
||||
[{
|
||||
kinds: [31990],
|
||||
authors: authorPubkeys,
|
||||
'#t': ['shakespeare'],
|
||||
limit: 200,
|
||||
}],
|
||||
{ signal: AbortSignal.timeout(5000) },
|
||||
);
|
||||
|
||||
// Get reporting events for hidden apps (NIP-56 kind 1984)
|
||||
const reportEvents = await nostr.query([{
|
||||
kinds: [1984],
|
||||
authors: [MODERATOR_HEX],
|
||||
limit: 1000
|
||||
}], { signal: AbortSignal.timeout(1000) });
|
||||
|
||||
// Process submissions and apply moderation
|
||||
const submissions: AppSubmission[] = [];
|
||||
const submissionMap = new Map<string, NostrEvent>();
|
||||
|
||||
// Group regular submissions by d-tag (identifier) to get latest version
|
||||
for (const event of submissionEvents) {
|
||||
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
|
||||
if (!dTag) continue;
|
||||
|
||||
const existing = submissionMap.get(dTag);
|
||||
if (!existing || event.created_at > existing.created_at) {
|
||||
submissionMap.set(dTag, event);
|
||||
}
|
||||
}
|
||||
|
||||
// Get the latest featured list
|
||||
const featuredList = moderatorListEvents.find(e => e.tags.find(tag => tag[0] === 'd' && tag[1] === 'soapbox-featured-apps'));
|
||||
const approvedList = moderatorListEvents.find(e => e.tags.find(tag => tag[0] === 'd' && tag[1] === 'soapbox-approved-apps'));
|
||||
const homepageList = moderatorListEvents.find(e => e.tags.find(tag => tag[0] === 'd' && tag[1] === 'soapbox-homepage-apps'));
|
||||
|
||||
// Extract featured app coordinates from the list
|
||||
const featuredAppCoords = new Set<string>();
|
||||
if (featuredList) {
|
||||
featuredList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => featuredAppCoords.add(tag[1]));
|
||||
}
|
||||
|
||||
// Extract approved app coordinates from the list
|
||||
const approvedAppCoords = new Set<string>();
|
||||
if (approvedList) {
|
||||
approvedList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => approvedAppCoords.add(tag[1]));
|
||||
}
|
||||
|
||||
// Extract homepage app coordinates from the list
|
||||
const homepageAppCoords = new Set<string>();
|
||||
if (homepageList) {
|
||||
homepageList.tags
|
||||
.filter(tag => tag[0] === 'a')
|
||||
.forEach(tag => homepageAppCoords.add(tag[1]));
|
||||
}
|
||||
|
||||
// Get hidden app coordinates from reports
|
||||
const hiddenAppCoords = new Set<string>();
|
||||
const appReports = new Map<string, { hidden: number; unhidden: number }>();
|
||||
|
||||
for (const report of reportEvents) {
|
||||
// Look for app coordinate in 'a' tags
|
||||
const aTag = report.tags.find(tag => tag[0] === 'a');
|
||||
if (!aTag || !aTag[1]) continue;
|
||||
|
||||
const appCoord = aTag[1];
|
||||
const reportType = aTag[2];
|
||||
|
||||
// Check if this is a moderation label
|
||||
const moderationLabel = report.tags.find(tag =>
|
||||
tag[0] === 'l' && tag[2] === 'soapbox.moderation'
|
||||
)?.[1];
|
||||
|
||||
if (moderationLabel === 'hidden' && (reportType === 'spam' || reportType === 'other')) {
|
||||
if (!appReports.has(appCoord)) {
|
||||
appReports.set(appCoord, { hidden: 0, unhidden: 0 });
|
||||
}
|
||||
appReports.get(appCoord)!.hidden = Math.max(
|
||||
appReports.get(appCoord)!.hidden,
|
||||
report.created_at
|
||||
);
|
||||
} else if (moderationLabel === 'unhidden' && reportType === 'other') {
|
||||
if (!appReports.has(appCoord)) {
|
||||
appReports.set(appCoord, { hidden: 0, unhidden: 0 });
|
||||
}
|
||||
appReports.get(appCoord)!.unhidden = Math.max(
|
||||
appReports.get(appCoord)!.unhidden,
|
||||
report.created_at
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Determine which apps are currently hidden (latest action wins)
|
||||
for (const [appCoord, reports] of appReports) {
|
||||
if (reports.hidden > reports.unhidden) {
|
||||
hiddenAppCoords.add(appCoord);
|
||||
}
|
||||
}
|
||||
|
||||
// Convert to AppSubmission objects
|
||||
for (const [dTag, event] of submissionMap) {
|
||||
// 3. Client-side filter: only keep events with a git repo, icon, and banner
|
||||
const filteredEvents = appEvents.filter(event => {
|
||||
if (!hasGitRepository(event)) return false;
|
||||
try {
|
||||
const appName = event.tags.find(tag => tag[0] === 'title')?.[1] || '';
|
||||
const websiteUrl = event.tags.find(tag => tag[0] === 'website')?.[1] || '';
|
||||
const repositoryUrl = event.tags.find(tag => tag[0] === 'repository')?.[1] || '';
|
||||
const appIconUrl = event.tags.find(tag => tag[0] === 'icon')?.[1] || '';
|
||||
const screenshotUrl = event.tags.find(tag => tag[0] === 'screenshot')?.[1] || '';
|
||||
const authorNpub = event.tags.find(tag => tag[0] === 'author')?.[1] || event.pubkey;
|
||||
const appTags = event.tags.filter(tag => tag[0] === 'app-tag').map(tag => tag[1]);
|
||||
const meta = JSON.parse(event.content) as Record<string, unknown>;
|
||||
return typeof meta.picture === 'string' && meta.picture &&
|
||||
typeof meta.banner === 'string' && meta.banner;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
// Check if app is featured, approved, homepage, or hidden
|
||||
const appCoordinate = `${APP_SUBMISSION_KIND}:${event.pubkey}:${dTag}`;
|
||||
const isFeatured = featuredAppCoords.has(appCoordinate);
|
||||
const isHomepage = homepageAppCoords.has(appCoordinate);
|
||||
const isSubmittedByModerator = event.pubkey === MODERATOR_HEX;
|
||||
const isSubmittedByTeamMember = teamPubkeys.has(event.pubkey);
|
||||
const isApproved = approvedAppCoords.has(appCoordinate) || isFeatured || isSubmittedByModerator || isSubmittedByTeamMember;
|
||||
const isHidden = hiddenAppCoords.has(appCoordinate);
|
||||
// 4. Deduplicate: for each pubkey+d-tag, keep only the latest event
|
||||
const latestMap = new Map<string, NostrEvent>();
|
||||
for (const event of filteredEvents) {
|
||||
const dTag = event.tags.find(([name]) => name === 'd')?.[1] ?? '';
|
||||
const key = `${event.pubkey}:${dTag}`;
|
||||
const existing = latestMap.get(key);
|
||||
if (!existing || event.created_at > existing.created_at) {
|
||||
latestMap.set(key, event);
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Shape into AppSubmission objects
|
||||
const submissions: AppSubmission[] = [];
|
||||
for (const event of latestMap.values()) {
|
||||
try {
|
||||
let appName = '';
|
||||
let appIconUrl = '';
|
||||
let bannerUrl = '';
|
||||
let websiteUrl = '';
|
||||
let description = '';
|
||||
|
||||
// Parse kind-0-style metadata from content
|
||||
if (event.content) {
|
||||
try {
|
||||
const meta = JSON.parse(event.content) as Record<string, unknown>;
|
||||
if (typeof meta.name === 'string') appName = meta.name;
|
||||
if (typeof meta.about === 'string') description = meta.about;
|
||||
if (typeof meta.picture === 'string') appIconUrl = meta.picture;
|
||||
if (typeof meta.banner === 'string') bannerUrl = meta.banner;
|
||||
if (typeof meta.website === 'string') websiteUrl = meta.website;
|
||||
} catch {
|
||||
// Non-JSON content — ignore
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: title tag
|
||||
if (!appName) {
|
||||
appName = event.tags.find(([name]) => name === 'title')?.[1] ?? '';
|
||||
}
|
||||
|
||||
// Build repository URL from the first 30617 `a` tag
|
||||
const repoATag = event.tags.find(([name, value]) => name === 'a' && value?.startsWith('30617:'));
|
||||
const repositoryUrl = repoATag ? repositoryUrlFromATag(repoATag[1]) : '';
|
||||
|
||||
submissions.push({
|
||||
...event,
|
||||
appName,
|
||||
websiteUrl,
|
||||
repositoryUrl,
|
||||
description: event.content,
|
||||
description,
|
||||
appIconUrl,
|
||||
screenshotUrl,
|
||||
appTags: appTags,
|
||||
authorNpub,
|
||||
isFeatured,
|
||||
isApproved,
|
||||
isHidden,
|
||||
isHomepage
|
||||
bannerUrl,
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn('Failed to parse app submission:', error);
|
||||
@@ -223,8 +184,8 @@ export function useAppSubmissions() {
|
||||
|
||||
return submissions;
|
||||
},
|
||||
staleTime: 30000, // 30 seconds
|
||||
refetchInterval: 60000, // 1 minute
|
||||
staleTime: 30000,
|
||||
refetchInterval: 60000,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -235,6 +196,6 @@ export function useUserAppSubmissions(userPubkey?: string) {
|
||||
|
||||
return {
|
||||
data: userSubmissions,
|
||||
...rest
|
||||
...rest,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -66,9 +66,9 @@ describe('useGenerateProjectInfo', () => {
|
||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
previewDomain: 'iframe.diy',
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
||||
showcaseCurator: '',
|
||||
graspMetadata: {
|
||||
relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }],
|
||||
updatedAt: 0,
|
||||
@@ -230,9 +230,9 @@ describe('useGenerateProjectInfo', () => {
|
||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
previewDomain: 'iframe.diy',
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
||||
showcaseCurator: '',
|
||||
graspMetadata: {
|
||||
relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }],
|
||||
updatedAt: 0,
|
||||
|
||||
@@ -45,7 +45,7 @@ function createWrapper(corsProxy: string) {
|
||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||
previewDomain: 'local-test.dev',
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
||||
showcaseCurator: '',
|
||||
graspMetadata: { relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }], updatedAt: 0 },
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { NLogin, useNostrLogin } from '@nostrify/react/login';
|
||||
import type { NostrConnectParams } from '@nostrify/react/login';
|
||||
|
||||
// NOTE: This file should not be edited except for adding new login methods.
|
||||
|
||||
@@ -18,6 +19,14 @@ export function useLoginActions() {
|
||||
const login = await NLogin.fromBunker(uri, nostr);
|
||||
addLogin(login);
|
||||
},
|
||||
// Login via client-initiated NIP-46 ("nostrconnect://" QR code).
|
||||
// Caller generates params with `generateNostrConnectParams`, renders the
|
||||
// URI as a QR/deep-link, and awaits this promise — it resolves when the
|
||||
// remote signer connects back over the relay.
|
||||
async nostrconnect(params: NostrConnectParams, signal?: AbortSignal): Promise<void> {
|
||||
const login = await NLogin.fromNostrConnect(params, nostr, { signal });
|
||||
addLogin(login);
|
||||
},
|
||||
// Login with a NIP-07 browser extension
|
||||
async extension(): Promise<void> {
|
||||
const login = await NLogin.fromExtension();
|
||||
|
||||