Compare commits

..
976 changed files with 19834 additions and 125981 deletions

No files matched your search

-20
View File
@@ -1,20 +0,0 @@
{
"name": "yaak",
"interface": {
"displayName": "Yaak"
},
"plugins": [
{
"name": "yaak",
"source": {
"source": "local",
"path": "./crates-cli/yaak-cli"
},
"policy": {
"installation": "AVAILABLE",
"authentication": "ON_INSTALL"
},
"category": "Developer Tools"
}
]
}
-18
View File
@@ -1,18 +0,0 @@
{
"$schema": "https://json.schemastore.org/claude-code-marketplace.json",
"name": "yaak",
"description": "Plugins for Yaak, the desktop API client",
"owner": {
"name": "Yaak",
"url": "https://yaak.app"
},
"plugins": [
{
"name": "yaak",
"source": "./crates-cli/yaak-cli",
"description": "Build, save, and send API requests with the yaak CLI, with its MCP server for agents",
"category": "development",
"tags": ["api", "http", "rest", "graphql", "grpc", "openapi", "api-client"]
}
]
}
-1
View File
@@ -5,4 +5,3 @@ crates/yaak-templates/pkg/* linguist-generated=true
# Ensure consistent line endings for test files that check exact content # Ensure consistent line endings for test files that check exact content
crates/yaak-http/tests/test.txt text eol=lf crates/yaak-http/tests/test.txt text eol=lf
crates-proxy/yaak-proxy-lib/tests/fixtures/export.har text eol=lf
-21
View File
@@ -7,23 +7,6 @@ updates:
interval: weekly interval: weekly
day: monday day: monday
open-pull-requests-limit: 5 open-pull-requests-limit: 5
ignore:
# Build tooling majors are opted into, not queued. These never reach a
# user, so the cost of being a release behind is low and the cost of a
# surprise is a broken build. Note this also suppresses security PRs for
# these, so Dependabot alerts are the backstop.
- dependency-name: typescript
update-types: ["version-update:semver-major"]
- dependency-name: vitest
update-types: ["version-update:semver-major"]
- dependency-name: "@types/*"
update-types: ["version-update:semver-major"]
- dependency-name: "vite-plugin-*"
update-types: ["version-update:semver-major"]
# 0.8 dropped stateExtensions and updateSchema from the package root and
# exposes no subpath to reach them, which GrpcEditor needs. Unpin once
# that editor moves to the jsonSchema helper.
- dependency-name: codemirror-json-schema
groups: groups:
npm-production: npm-production:
dependency-type: production dependency-type: production
@@ -42,10 +25,6 @@ updates:
interval: weekly interval: weekly
day: monday day: monday
open-pull-requests-limit: 5 open-pull-requests-limit: 5
ignore:
# Held at 11.10.0 to pin what rolldown_resolver ("^11") resolves to; it
# does not build against 11.11. See crates-cli/yaak-cli/Cargo.toml.
- dependency-name: oxc_resolver
groups: groups:
cargo: cargo:
patterns: patterns:
@@ -1,79 +0,0 @@
// Retain only distributable bundle files, never the target tree or signing material.
import { createHash } from "node:crypto";
import {
copyFileSync,
createReadStream,
existsSync,
mkdirSync,
readdirSync,
writeFileSync,
} from "node:fs";
import { join, relative } from "node:path";
const env = process.env;
const bundle = join("target", env.RELEASE_TARGET || "", "release", "bundle");
const destination = join(env.RUNNER_TEMP, "yaak-release-artifacts");
const extensions =
/\.(dmg|deb|rpm|AppImage|exe|msi|app\.tar\.gz|AppImage\.tar\.gz|nsis\.zip|msi\.zip)(\.sig)?$/;
const files = [];
function snapshot(directory) {
if (!existsSync(directory)) return;
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const source = join(directory, entry.name);
// Only descend through the bundler's immediate output folders. This excludes
// .app trees and the extracted CEF deb contents (which contain executables).
if (entry.isDirectory() && directory === bundle) {
snapshot(source);
} else if (
entry.isFile() &&
(extensions.test(entry.name) || /^yaak-cef_.*_linux_.*\.tar\.gz$/.test(entry.name))
) {
// Match tauri-action's default macOS updater asset naming exactly.
const arch = env.RELEASE_ARCH === "arm64" ? "aarch64" : "x64";
const assetName = entry.name.replace(/\.app\.tar\.gz(\.sig)?$/, `_${arch}.app.tar.gz$1`);
mkdirSync(destination, { recursive: true });
const retained = join(destination, assetName);
// The second snapshot must not overwrite the original user installer/signature.
if (!existsSync(retained)) copyFileSync(source, retained);
files.push({ source: relative(".", source), assetName });
}
}
}
snapshot(bundle);
if (existsSync(destination)) {
const assets = readdirSync(destination)
.filter((name) => name !== "provenance.json")
.sort();
const checksums = [];
for (const assetName of assets) {
const hash = createHash("sha256");
for await (const chunk of createReadStream(join(destination, assetName))) hash.update(chunk);
checksums.push({ assetName, sha256: hash.digest("hex") });
}
writeFileSync(
join(destination, "provenance.json"),
JSON.stringify(
{
repository: env.GITHUB_REPOSITORY,
tag: env.GITHUB_REF_NAME,
sha: env.GITHUB_SHA,
runId: env.GITHUB_RUN_ID,
runAttempt: env.GITHUB_RUN_ATTEMPT,
workflowRef: env.GITHUB_WORKFLOW_REF,
workflowSha: env.GITHUB_WORKFLOW_SHA,
tauriAction: "tauri-apps/tauri-action@v0",
platform: env.RELEASE_PLATFORM,
runtime: env.RELEASE_RUNTIME,
arch: env.RELEASE_ARCH,
target: env.RELEASE_TARGET,
args: env.RELEASE_ARGS,
assets: checksums,
},
null,
2,
) + "\n",
);
}
console.log(`Found ${files.length} distributable bundle files in ${bundle}`);
-26
View File
@@ -35,29 +35,3 @@ jobs:
run: | run: |
cargo build -p yaak-cli cargo build -p yaak-cli
node plugins/importer-openapi/tests/roundtrip.mjs node plugins/importer-openapi/tests/roundtrip.mjs
test-windows:
name: Rust Tests (Windows)
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: voidzero-dev/setup-vp@v1
with:
node-version: "24"
cache: true
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
shared-key: ci
cache-on-failure: true
- name: Install Protoc for plugin-runtime
uses: arduino/setup-protoc@v3
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
- run: vp install
- run: npm run bootstrap
env:
YAAK_TARGET_ARCH: x64
- name: Run Rust Tests
run: cargo test --all --exclude yaak-cli --features yaak-app-client/wry
+6 -241
View File
@@ -2,24 +2,10 @@ name: Release App Artifacts
on: on:
push: push:
tags: [v*] tags: [v*]
# The Yaak Proxy dry run only: builds, signs and notarizes the proxy for the chosen ref and
# keeps the results as workflow artifacts. It never builds Yaak, releases, tags or publishes.
workflow_dispatch:
inputs:
proxy_dry_run:
description: "Dry-run the Yaak Proxy build (artifacts only; nothing is released)"
type: boolean
required: true
default: true
proxy_version:
description: "Version to stamp into the dry-run build"
type: string
required: true
default: "0.0.1-dryrun"
jobs: jobs:
build-artifacts: build-artifacts:
if: github.repository == 'mountain-loop/yaak' && github.event_name == 'push' if: github.repository == 'mountain-loop/yaak'
permissions: permissions:
contents: write contents: write
@@ -84,7 +70,7 @@ jobs:
runtime: "wry" runtime: "wry"
targets: "aarch64-pc-windows-msvc" targets: "aarch64-pc-windows-msvc"
runs-on: ${{ matrix.platform }} runs-on: ${{ matrix.platform }}
timeout-minutes: 360 timeout-minutes: 60
steps: steps:
- name: Checkout yaakapp/app - name: Checkout yaakapp/app
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -186,8 +172,7 @@ jobs:
codesign --force --options runtime --entitlements crates-tauri/yaak-app-client/macos/entitlements.yaakprotoc.plist --sign "$APPLE_SIGNING_IDENTITY" crates-tauri/yaak-app-client/vendored/protoc/yaakprotoc || true codesign --force --options runtime --entitlements crates-tauri/yaak-app-client/macos/entitlements.yaakprotoc.plist --sign "$APPLE_SIGNING_IDENTITY" crates-tauri/yaak-app-client/vendored/protoc/yaakprotoc || true
codesign --force --options runtime --entitlements crates-tauri/yaak-app-client/macos/entitlements.yaaknode.plist --sign "$APPLE_SIGNING_IDENTITY" crates-tauri/yaak-app-client/vendored/node/yaaknode || true codesign --force --options runtime --entitlements crates-tauri/yaak-app-client/macos/entitlements.yaaknode.plist --sign "$APPLE_SIGNING_IDENTITY" crates-tauri/yaak-app-client/vendored/node/yaaknode || true
- name: Build and upload Tauri bundles - uses: tauri-apps/tauri-action@v0
uses: tauri-apps/tauri-action@v0
env: env:
YAAK_TARGET_ARCH: ${{ matrix.yaak_arch }} YAAK_TARGET_ARCH: ${{ matrix.yaak_arch }}
@@ -209,8 +194,6 @@ jobs:
AZURE_CLIENT_SECRET: ${{ matrix.os == 'windows' && secrets.AZURE_CLIENT_SECRET }} AZURE_CLIENT_SECRET: ${{ matrix.os == 'windows' && secrets.AZURE_CLIENT_SECRET }}
AZURE_TENANT_ID: ${{ matrix.os == 'windows' && secrets.AZURE_TENANT_ID }} AZURE_TENANT_ID: ${{ matrix.os == 'windows' && secrets.AZURE_TENANT_ID }}
with: with:
# Also retries builds; upload retries alone cannot clean up starter assets.
retryAttempts: 3
tauriScript: "node ../../node_modules/@tauri-apps/cli/tauri.js" tauriScript: "node ../../node_modules/@tauri-apps/cli/tauri.js"
tagName: "v__VERSION__" tagName: "v__VERSION__"
releaseName: "Release __VERSION__" releaseName: "Release __VERSION__"
@@ -220,17 +203,6 @@ jobs:
projectPath: ./crates-tauri/yaak-app-client projectPath: ./crates-tauri/yaak-app-client
args: "${{ matrix.args }}" args: "${{ matrix.args }}"
# Snapshot before the per-machine build overwrites the regular NSIS bundle/signature.
- name: Snapshot Tauri bundles
if: ${{ !cancelled() }}
run: node .github/scripts/preserve-release-artifacts.mjs
env:
RELEASE_TARGET: ${{ matrix.targets }}
RELEASE_PLATFORM: ${{ matrix.platform }}
RELEASE_RUNTIME: ${{ matrix.runtime }}
RELEASE_ARCH: ${{ matrix.yaak_arch }}
RELEASE_ARGS: ${{ matrix.args }}
- name: Build and upload CEF tarball from deb (Linux only) - name: Build and upload CEF tarball from deb (Linux only)
if: matrix.os == 'ubuntu' && matrix.runtime == 'cef' if: matrix.os == 'ubuntu' && matrix.runtime == 'cef'
env: env:
@@ -245,13 +217,7 @@ jobs:
mkdir -p "$extract_dir" mkdir -p "$extract_dir"
dpkg-deb -x "$deb" "$extract_dir" dpkg-deb -x "$deb" "$extract_dir"
tar -C "$extract_dir" -czf "$tarball" . tar -C "$extract_dir" -czf "$tarball" .
for attempt in 1 2 3 4; do gh release upload "${{ github.ref_name }}" "$tarball" --clobber
if gh release upload "$GITHUB_REF_NAME" "$tarball" --clobber; then
break
fi
if [ "$attempt" -eq 4 ]; then exit 1; fi
sleep 10
done
# Build a per-machine NSIS installer for enterprise deployment (PDQ, SCCM, Intune) # Build a per-machine NSIS installer for enterprise deployment (PDQ, SCCM, Intune)
- name: Build and upload machine-wide installer (Windows only) - name: Build and upload machine-wide installer (Windows only)
@@ -269,7 +235,6 @@ jobs:
Get-ChildItem -Recurse -Path target -File -Filter "*.exe.sig" | Remove-Item -Force Get-ChildItem -Recurse -Path target -File -Filter "*.exe.sig" | Remove-Item -Force
Push-Location crates-tauri/yaak-app-client Push-Location crates-tauri/yaak-app-client
npx tauri bundle ${{ matrix.args }} --bundles nsis --config '{"bundle":{"createUpdaterArtifacts":true,"windows":{"nsis":{"installMode":"perMachine"}}}}' npx tauri bundle ${{ matrix.args }} --bundles nsis --config '{"bundle":{"createUpdaterArtifacts":true,"windows":{"nsis":{"installMode":"perMachine"}}}}'
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
Pop-Location Pop-Location
$setup = Get-ChildItem -Recurse -Path target -Filter "*setup*.exe" | Select-Object -First 1 $setup = Get-ChildItem -Recurse -Path target -Filter "*setup*.exe" | Select-Object -First 1
$setupSig = "$($setup.FullName).sig" $setupSig = "$($setup.FullName).sig"
@@ -277,205 +242,5 @@ jobs:
$destSig = "$dest.sig" $destSig = "$dest.sig"
Copy-Item $setup.FullName $dest Copy-Item $setup.FullName $dest
Copy-Item $setupSig $destSig Copy-Item $setupSig $destSig
foreach ($asset in @($dest, $destSig)) { gh release upload "${{ github.ref_name }}" "$dest" --clobber
for ($attempt = 1; $attempt -le 4; $attempt++) { gh release upload "${{ github.ref_name }}" "$destSig" --clobber
gh release upload "$env:GITHUB_REF_NAME" "$asset" --clobber
if ($LASTEXITCODE -eq 0) { break }
if ($attempt -eq 4) { exit $LASTEXITCODE }
Start-Sleep -Seconds 10
}
}
- name: Snapshot additional release bundles
if: ${{ !cancelled() }}
run: node .github/scripts/preserve-release-artifacts.mjs
env:
RELEASE_TARGET: ${{ matrix.targets }}
RELEASE_PLATFORM: ${{ matrix.platform }}
RELEASE_RUNTIME: ${{ matrix.runtime }}
RELEASE_ARCH: ${{ matrix.yaak_arch }}
RELEASE_ARGS: ${{ matrix.args }}
- name: Retain release bundles for recovery
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v4
with:
name: release-${{ github.ref_name }}-${{ matrix.platform }}-${{ matrix.runtime }}-${{ matrix.yaak_arch }}-${{ github.run_id }}-attempt-${{ github.run_attempt }}
path: ${{ runner.temp }}/yaak-release-artifacts/
retention-days: 7
if-no-files-found: warn
# Yaak Proxy, macOS only, on the same tag and version as Yaak. Its own job, sharing nothing
# with Yaak's, so a proxy failure never stops Yaak's artifacts; it fails the run, visibly.
#
# On a v* tag it runs only once the repository variable RELEASE_PROXY is "true": the website's
# download links pick Yaak's assets by suffix and architecture, and its release audit expects
# Yaak's exact asset set and this run's success, so the proxy must not join Yaak's release
# until the website expects it there. The dry run (workflow_dispatch) runs regardless, and
# only keeps workflow artifacts.
build-proxy:
if: >-
github.repository == 'mountain-loop/yaak' && (
(github.event_name == 'push' && vars.RELEASE_PROXY == 'true') ||
(github.event_name == 'workflow_dispatch' && inputs.proxy_dry_run)
)
permissions:
contents: write
name: Build Yaak Proxy
strategy:
fail-fast: false
matrix:
include:
- target: "aarch64-apple-darwin" # for Arm-based Macs (M1 and above).
yaak_arch: "arm64"
lipo_arch: "arm64"
asset_arch: "aarch64"
- target: "x86_64-apple-darwin" # for Intel-based Macs.
yaak_arch: "x64"
lipo_arch: "x86_64"
asset_arch: "x64"
runs-on: macos-latest
timeout-minutes: 240
env:
DRY_RUN: ${{ github.event_name == 'workflow_dispatch' }}
# The tag, as Yaak's version is taken, or the dry run's own
PROXY_VERSION: ${{ github.event_name == 'workflow_dispatch' && inputs.proxy_version || github.ref_name }}
steps:
- name: Checkout yaakapp/app
uses: actions/checkout@v4
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version: "24"
cache: true
- name: install Rust stable
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
# A cache of its own, so the proxy's builds never change what Yaak's jobs restore
- uses: Swatinem/rust-cache@v2
with:
shared-key: release-proxy
key: ${{ matrix.target }}
cache-on-failure: true
- name: Install Protoc for plugin-runtime
uses: arduino/setup-protoc@v3
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
- run: vp install
- name: Set version
run: npm run replace-version -- proxy
env:
YAAK_VERSION: ${{ env.PROXY_VERSION }}
- name: Import signing certificate
env:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
run: |
set -euo pipefail
KEYCHAIN_PATH="$RUNNER_TEMP/app-signing.keychain-db"
security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
security set-keychain-settings -lut 21600 "$KEYCHAIN_PATH"
security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
echo "$APPLE_CERTIFICATE" | base64 --decode > "$RUNNER_TEMP/certificate.p12"
security import "$RUNNER_TEMP/certificate.p12" -P "$APPLE_CERTIFICATE_PASSWORD" -A -t cert -f pkcs12 -k "$KEYCHAIN_PATH"
rm "$RUNNER_TEMP/certificate.p12"
# Lets codesign use the key unattended; without it the first signature can wait on a
# prompt nobody answers
security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH" > /dev/null
security list-keychain -d user -s "$KEYCHAIN_PATH"
# Builds the helper for the target and signs it and protoc before bundling (the bundle
# config's before-build step), then signs, notarizes and staples the app and makes the
# updater archive and its signature.
- name: Build, sign and notarize
run: >-
npm run proxy:bundle --
--target ${{ matrix.target }}
--bundles dmg
--config crates-tauri/yaak-app-proxy/tauri.release.conf.json
env:
CI: true
YAAK_TARGET_ARCH: ${{ matrix.yaak_arch }}
APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
# The helper only answers an app signed by this team
YAAK_PROXY_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
- name: Verify the bundle
run: >-
node scripts/verify-proxy-bundle.mjs
"target/${{ matrix.target }}/release/bundle/macos/Yaak Proxy.app"
--signed
--version "$PROXY_VERSION"
--arch ${{ matrix.lipo_arch }}
--team "$YAAK_PROXY_TEAM_ID"
env:
YAAK_PROXY_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
# Named Yaak.Proxy_*, so neither people nor tools take them for Yaak's Yaak_* assets.
# The app refuses an update not named so (ARTIFACT_PREFIX in yaak-app-proxy's updates.rs).
- name: Collect the release assets
run: |
set -euo pipefail
bundle="target/${{ matrix.target }}/release/bundle"
version="${PROXY_VERSION#v}"
out="$RUNNER_TEMP/yaak-proxy-release"
mkdir -p "$out"
dmgs=("$bundle"/dmg/*.dmg)
if [ "${#dmgs[@]}" -ne 1 ] || [ ! -f "${dmgs[0]}" ]; then
echo "Expected one .dmg in $bundle/dmg"; exit 1
fi
cp "${dmgs[0]}" "$out/Yaak.Proxy_${version}_${{ matrix.asset_arch }}.dmg"
cp "$bundle/macos/Yaak Proxy.app.tar.gz" "$out/Yaak.Proxy_${{ matrix.asset_arch }}.app.tar.gz"
cp "$bundle/macos/Yaak Proxy.app.tar.gz.sig" "$out/Yaak.Proxy_${{ matrix.asset_arch }}.app.tar.gz.sig"
(cd "$out" && shasum -a 256 Yaak.Proxy_* > checksums.txt)
ls -l "$out"
- name: Keep the bundles as workflow artifacts
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v4
with:
name: proxy-${{ env.PROXY_VERSION }}-${{ matrix.asset_arch }}-${{ github.run_id }}-attempt-${{ github.run_attempt }}
path: ${{ runner.temp }}/yaak-proxy-release/
retention-days: ${{ env.DRY_RUN == 'true' && 14 || 7 }}
if-no-files-found: error
# Yaak's jobs create the draft release; this waits for it rather than making its own,
# which could race theirs into two drafts.
- name: Upload to the release
if: env.DRY_RUN != 'true'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
for attempt in $(seq 1 120); do
if gh release view "$GITHUB_REF_NAME" > /dev/null 2>&1; then break; fi
if [ "$attempt" -eq 120 ]; then
echo "No release for $GITHUB_REF_NAME after two hours; Yaak's jobs make it"; exit 1
fi
sleep 60
done
for asset in "$RUNNER_TEMP"/yaak-proxy-release/Yaak.Proxy_*; do
for attempt in 1 2 3 4; do
if gh release upload "$GITHUB_REF_NAME" "$asset" --clobber; then
break
fi
if [ "$attempt" -eq 4 ]; then exit 1; fi
sleep 10
done
done
-3
View File
@@ -59,6 +59,3 @@ flatpak/node-sources.json
# Claude Code local settings # Claude Code local settings
.claude/settings.local.json .claude/settings.local.json
.claude/worktrees/ .claude/worktrees/
# Headless screenshots taken while working
.shots/
+1 -2
View File
@@ -3,7 +3,6 @@
"ignorePatterns": [ "ignorePatterns": [
"**/bindings/**", "**/bindings/**",
"crates/yaak-templates/pkg/**", "crates/yaak-templates/pkg/**",
"apps/yaak-client/routeTree.gen.ts", "apps/yaak-client/routeTree.gen.ts"
"plugins/importer-bruno/tests/fixtures/upstream/**"
] ]
} }
Generated
+1496 -1820
View File
File diff suppressed because it is too large. Load diff
+3 -21
View File
@@ -11,15 +11,12 @@ members = [
"crates/yaak-core", "crates/yaak-core",
"crates/yaak-common", "crates/yaak-common",
"crates/yaak-crypto", "crates/yaak-crypto",
"crates/yaak-filter",
"crates/yaak-git", "crates/yaak-git",
"crates/yaak-grpc", "crates/yaak-grpc",
"crates/yaak-http", "crates/yaak-http",
"crates/yaak-lifecycle", "crates/yaak-lifecycle",
"crates/yaak-mcp",
"crates/yaak-models", "crates/yaak-models",
"crates/yaak-plugins", "crates/yaak-plugins",
"crates/yaak-query",
"crates/yaak-sse", "crates/yaak-sse",
"crates/yaak-sync", "crates/yaak-sync",
"crates/yaak-templates", "crates/yaak-templates",
@@ -32,7 +29,6 @@ members = [
"crates-proxy/yaak-proxy-lib", "crates-proxy/yaak-proxy-lib",
# Server crates (the browser tier's hosted send executor) # Server crates (the browser tier's hosted send executor)
"crates-server/yaak-web", "crates-server/yaak-web",
"crates-server/yaak-playground",
# CLI crates # CLI crates
"crates-cli/yaak-cli", "crates-cli/yaak-cli",
# Tauri-specific crates # Tauri-specific crates
@@ -41,10 +37,8 @@ members = [
"crates-tauri/yaak-fonts", "crates-tauri/yaak-fonts",
"crates-tauri/yaak-license", "crates-tauri/yaak-license",
"crates-tauri/yaak-mac-window", "crates-tauri/yaak-mac-window",
"crates-tauri/yaak-proxy-helper",
"crates-tauri/yaak-system-appearance", "crates-tauri/yaak-system-appearance",
"crates-tauri/yaak-tauri-utils", "crates-tauri/yaak-tauri-utils",
"crates-tauri/yaak-updater",
"crates-tauri/yaak-window", "crates-tauri/yaak-window",
] ]
@@ -53,20 +47,13 @@ chrono = "0.4.42"
hex = "0.4.3" hex = "0.4.3"
keyring = "3.6.3" keyring = "3.6.3"
log = "0.4.29" log = "0.4.29"
reqwest = { version = "0.13.5", default-features = false, features = [ reqwest = "0.12.20"
# reqwest 0.13 switched `default-tls` from native-tls to rustls; keep the
# rest of the old default set and stay on native-tls.
"charset",
"http2",
"system-proxy",
"native-tls",
] }
rustls = { version = "0.23.34", default-features = false } rustls = { version = "0.23.34", default-features = false }
rustls-platform-verifier = "0.7.1" rustls-platform-verifier = "0.6.2"
schemars = { version = "0.8.22", features = ["chrono"] } schemars = { version = "0.8.22", features = ["chrono"] }
serde = "1.0.228" serde = "1.0.228"
serde_json = "1.0.145" serde_json = "1.0.145"
sha2 = "0.11.1" sha2 = "0.10.9"
tauri = { version = "2.11.1", default-features = false, features = [ tauri = { version = "2.11.1", default-features = false, features = [
"common-controls-v6", "common-controls-v6",
"compression", "compression",
@@ -90,15 +77,12 @@ yaak = { path = "crates/yaak" }
yaak-commands = { path = "crates/yaak-commands" } yaak-commands = { path = "crates/yaak-commands" }
yaak-common = { path = "crates/yaak-common" } yaak-common = { path = "crates/yaak-common" }
yaak-crypto = { path = "crates/yaak-crypto" } yaak-crypto = { path = "crates/yaak-crypto" }
yaak-filter = { path = "crates/yaak-filter" }
yaak-git = { path = "crates/yaak-git" } yaak-git = { path = "crates/yaak-git" }
yaak-grpc = { path = "crates/yaak-grpc" } yaak-grpc = { path = "crates/yaak-grpc" }
yaak-http = { path = "crates/yaak-http" } yaak-http = { path = "crates/yaak-http" }
yaak-lifecycle = { path = "crates/yaak-lifecycle" } yaak-lifecycle = { path = "crates/yaak-lifecycle" }
yaak-mcp = { path = "crates/yaak-mcp" }
yaak-models = { path = "crates/yaak-models" } yaak-models = { path = "crates/yaak-models" }
yaak-plugins = { path = "crates/yaak-plugins" } yaak-plugins = { path = "crates/yaak-plugins" }
yaak-query = { path = "crates/yaak-query" }
yaak-sse = { path = "crates/yaak-sse" } yaak-sse = { path = "crates/yaak-sse" }
yaak-sync = { path = "crates/yaak-sync" } yaak-sync = { path = "crates/yaak-sync" }
yaak-templates = { path = "crates/yaak-templates" } yaak-templates = { path = "crates/yaak-templates" }
@@ -114,10 +98,8 @@ yaak-proxy-lib = { path = "crates-proxy/yaak-proxy-lib" }
yaak-fonts = { path = "crates-tauri/yaak-fonts" } yaak-fonts = { path = "crates-tauri/yaak-fonts" }
yaak-license = { path = "crates-tauri/yaak-license" } yaak-license = { path = "crates-tauri/yaak-license" }
yaak-mac-window = { path = "crates-tauri/yaak-mac-window" } yaak-mac-window = { path = "crates-tauri/yaak-mac-window" }
yaak-proxy-helper = { path = "crates-tauri/yaak-proxy-helper" }
yaak-system-appearance = { path = "crates-tauri/yaak-system-appearance" } yaak-system-appearance = { path = "crates-tauri/yaak-system-appearance" }
yaak-tauri-utils = { path = "crates-tauri/yaak-tauri-utils" } yaak-tauri-utils = { path = "crates-tauri/yaak-tauri-utils" }
yaak-updater = { path = "crates-tauri/yaak-updater" }
yaak-window = { path = "crates-tauri/yaak-window" } yaak-window = { path = "crates-tauri/yaak-window" }
[profile.release] [profile.release]
-15
View File
@@ -1,15 +0,0 @@
# syntax=docker/dockerfile:1
# The playground API behind yaak.run. See crates-server/yaak-playground/README.md.
FROM rust:1-bookworm AS build
WORKDIR /app
COPY . .
RUN cargo build --release -p yaak-playground
FROM debian:bookworm-slim
COPY --from=build /app/target/release/yaak-playground /usr/local/bin/yaak-playground
ENV HOST=0.0.0.0
ENV PORT=8080
EXPOSE 8080
USER nobody
CMD ["yaak-playground"]
+1 -4
View File
@@ -38,10 +38,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates libssl3 && rm -rf /var/lib/apt/lists/* ca-certificates libssl3 && rm -rf /var/lib/apt/lists/*
COPY --from=server /app/target/release/yaak-web /usr/local/bin/yaak-web COPY --from=server /app/target/release/yaak-web /usr/local/bin/yaak-web
COPY --from=web /app/dist/apps/yaak-client /srv COPY --from=web /app/dist/apps/yaak-client /srv
# 0.0.0.0 so the port is reachable from outside the container. PORT is the variable a ENV YAAK_WEB_BIND=0.0.0.0:8080
# platform-as-a-service assigns, so a deploy that sets it needs nothing else changed.
ENV HOST=0.0.0.0
ENV PORT=8080
EXPOSE 8080 EXPOSE 8080
USER nobody USER nobody
# Overriding the command (dropping --serve) leaves the stateless send executor: # Overriding the command (dropping --serve) leaves the stateless send executor:
-148
View File
@@ -1,148 +0,0 @@
import type { FunctionComponent, ReactElement } from "react";
import { beforeEach, expect, test, vi } from "vite-plus/test";
import type { SyncOp } from "@yaakapp-internal/sync/bindings/gen_sync";
import type { DialogInstance } from "../components/Dialogs";
import { syncWorkspace } from "./commands";
const mocks = vi.hoisted(() => ({
calculateSync: vi.fn(),
applySync: vi.fn(),
showDialog: vi.fn<(dialog: DialogInstance) => void>(),
hideDialog: vi.fn(),
showToast: vi.fn(),
}));
vi.mock("@yaakapp-internal/sync", () => mocks);
vi.mock("@yaakapp-internal/models", () => ({
createWorkspaceModel: vi.fn(),
modelTypeLabel: () => "Request",
}));
vi.mock("@yaakapp-internal/ui", () => ({
Banner: "div",
InlineCode: "code",
Table: "table",
TableBody: "tbody",
TableCell: "td",
TableHead: "thead",
TableHeaderCell: "th",
TableRow: "tr",
TruncatedWideTableCell: "td",
}));
vi.mock("../components/core/Button", () => ({ Button: "button" }));
vi.mock("../hooks/useActiveWorkspace", () => ({ activeWorkspaceIdAtom: null }));
vi.mock("../lib/dialog", () => mocks);
vi.mock("../lib/jotai", () => ({ jotaiStore: { get: vi.fn() } }));
vi.mock("../lib/prompt", () => ({ showPrompt: vi.fn() }));
vi.mock("../lib/resolvedModelName", () => ({ resolvedModelNameWithFolders: () => "Request" }));
vi.mock("../lib/toast", () => mocks);
const staleToast = expect.objectContaining({
message: "Files changed while syncing. Review the changes again.",
});
const params = { workspaceId: "wk_test", syncDir: "/sync" };
const deletion = {
type: "dbDelete",
model: { id: "rq_test", model: "http_request" },
state: {},
} as Extract<SyncOp, { type: "dbDelete" }>;
const update = {
type: "dbUpdate",
model: { id: "rq_test", model: "http_request" },
fs: { model: { id: "rq_test", model: "http_request", name: "Updated" } },
state: {},
} as Extract<SyncOp, { type: "dbUpdate" }>;
async function submit(dialog: DialogInstance) {
const render = dialog.render as FunctionComponent<{ hide: () => void }>;
const form = render({ hide: () => mocks.hideDialog(dialog.id) }) as ReactElement<{
onSubmit: (event: { preventDefault: () => void }) => Promise<void>;
}>;
await form.props.onSubmit({ preventDefault: vi.fn() });
}
function latestDialog() {
const dialog = mocks.showDialog.mock.calls.at(-1)?.[0];
if (dialog == null) throw new Error("Expected a sync dialog");
return dialog;
}
beforeEach(() => {
vi.resetAllMocks();
mocks.applySync.mockResolvedValue(true);
});
test("closes an obsolete dialog when the restored file leaves no changes", async () => {
mocks.calculateSync.mockResolvedValueOnce([deletion]).mockResolvedValueOnce([]);
await syncWorkspace.mutateAsync(params);
mocks.applySync.mockResolvedValueOnce(false);
await submit(latestDialog());
expect(mocks.applySync).toHaveBeenCalledTimes(1);
expect(mocks.applySync).toHaveBeenCalledWith(params.workspaceId, params.syncDir, [deletion]);
expect(mocks.hideDialog).toHaveBeenCalledWith("commit-sync");
expect(mocks.showDialog).toHaveBeenCalledTimes(1);
});
test("requires another confirmation for a changed plan", async () => {
mocks.calculateSync.mockResolvedValueOnce([deletion]).mockResolvedValueOnce([update]);
await syncWorkspace.mutateAsync(params);
const original = latestDialog();
mocks.applySync.mockResolvedValueOnce(false);
await submit(original);
expect(mocks.applySync).toHaveBeenCalledTimes(1);
expect(mocks.showDialog).toHaveBeenCalledTimes(2);
expect(mocks.showToast).toHaveBeenCalledWith(staleToast);
expect(mocks.hideDialog).not.toHaveBeenCalled();
await submit(latestDialog());
expect(mocks.applySync).toHaveBeenLastCalledWith(params.workspaceId, params.syncDir, [update]);
expect(mocks.hideDialog).toHaveBeenCalledWith("commit-sync");
});
test("applies an unchanged reviewed plan and closes the dialog", async () => {
mocks.calculateSync.mockResolvedValue([update]);
await syncWorkspace.mutateAsync(params);
await submit(latestDialog());
expect(mocks.calculateSync).toHaveBeenCalledTimes(1);
expect(mocks.applySync).toHaveBeenCalledTimes(1);
expect(mocks.hideDialog).toHaveBeenCalledWith("commit-sync");
});
test("forced sync retries the current plan without requesting another confirmation", async () => {
mocks.calculateSync.mockResolvedValueOnce([deletion]).mockResolvedValueOnce([update]);
mocks.applySync.mockResolvedValueOnce(false);
await syncWorkspace.mutateAsync({ ...params, force: true });
expect(mocks.applySync).toHaveBeenCalledTimes(2);
expect(mocks.applySync).toHaveBeenLastCalledWith(params.workspaceId, params.syncDir, [update]);
expect(mocks.showDialog).not.toHaveBeenCalled();
});
test("outbound-only changes clear the old dialog and sync automatically", async () => {
const outbound = { type: "fsUpdate", model: update.model, state: {} } as SyncOp;
mocks.calculateSync.mockResolvedValueOnce([deletion]).mockResolvedValueOnce([outbound]);
await syncWorkspace.mutateAsync(params);
await syncWorkspace.mutateAsync(params);
expect(mocks.applySync).toHaveBeenCalledWith(params.workspaceId, params.syncDir, [outbound]);
expect(mocks.hideDialog).toHaveBeenCalledWith("commit-sync");
expect(mocks.showDialog).toHaveBeenCalledTimes(1);
});
test("stops retrying a plan that keeps going stale", async () => {
mocks.calculateSync.mockResolvedValue([update]);
mocks.applySync.mockResolvedValue(false);
await syncWorkspace.mutateAsync({ ...params, force: true });
expect(mocks.calculateSync).toHaveBeenCalledTimes(3);
expect(mocks.applySync).toHaveBeenCalledTimes(3);
expect(mocks.showToast).toHaveBeenCalledTimes(1);
expect(mocks.showToast).toHaveBeenCalledWith(staleToast);
expect(mocks.showDialog).not.toHaveBeenCalled();
});
+11 -34
View File
@@ -14,12 +14,11 @@ import {
} from "@yaakapp-internal/ui"; } from "@yaakapp-internal/ui";
import { activeWorkspaceIdAtom } from "../hooks/useActiveWorkspace"; import { activeWorkspaceIdAtom } from "../hooks/useActiveWorkspace";
import { createFastMutation } from "../hooks/useFastMutation"; import { createFastMutation } from "../hooks/useFastMutation";
import { hideDialog, showDialog } from "../lib/dialog"; import { showDialog } from "../lib/dialog";
import { jotaiStore } from "../lib/jotai"; import { jotaiStore } from "../lib/jotai";
import { pluralizeCount } from "../lib/pluralize";
import { showPrompt } from "../lib/prompt"; import { showPrompt } from "../lib/prompt";
import { resolvedModelNameWithFolders } from "../lib/resolvedModelName"; import { resolvedModelNameWithFolders } from "../lib/resolvedModelName";
import { showToast } from "../lib/toast";
import { pluralizeCount } from "@yaakapp-internal/lib/pluralize";
export const createFolder = createFastMutation< export const createFolder = createFastMutation<
string | null, string | null,
@@ -53,48 +52,24 @@ export const createFolder = createFastMutation<
}, },
}); });
// Files can keep changing under a plan, so stop recalculating after a few stale applies.
const MAX_SYNC_ATTEMPTS = 3;
function showStaleSyncToast() {
showToast({
id: "sync-stale",
color: "warning",
message: "Files changed while syncing. Review the changes again.",
});
}
export const syncWorkspace = createFastMutation< export const syncWorkspace = createFastMutation<
void, void,
void, void,
{ workspaceId: string; syncDir: string; force?: boolean; attempt?: number } { workspaceId: string; syncDir: string; force?: boolean }
>({ >({
mutationKey: [], mutationKey: [],
mutationFn: async ({ workspaceId, syncDir, force, attempt = 1 }) => { mutationFn: async ({ workspaceId, syncDir, force }) => {
const ops = (await calculateSync(workspaceId, syncDir)) ?? []; const ops = (await calculateSync(workspaceId, syncDir)) ?? [];
if (ops.length === 0) { if (ops.length === 0) {
console.log("Nothing to sync", workspaceId, syncDir); console.log("Nothing to sync", workspaceId, syncDir);
hideDialog("commit-sync");
return; return;
} }
console.log("Syncing workspace", workspaceId, syncDir, ops); console.log("Syncing workspace", workspaceId, syncDir, ops);
const dbOps = ops.filter((o) => o.type.startsWith("db")); const dbOps = ops.filter((o) => o.type.startsWith("db"));
const apply = async () => { if (dbOps.length === 0) {
if (await applySync(workspaceId, syncDir, ops)) { await applySync(workspaceId, syncDir, ops);
hideDialog("commit-sync");
} else if (attempt < MAX_SYNC_ATTEMPTS) {
await syncWorkspace.mutateAsync({ workspaceId, syncDir, force, attempt: attempt + 1 });
} else {
hideDialog("commit-sync");
showStaleSyncToast();
}
};
if (dbOps.length === 0 || force) {
hideDialog("commit-sync");
await apply();
return; return;
} }
@@ -104,8 +79,9 @@ export const syncWorkspace = createFastMutation<
console.log("Directory changes detected", { dbOps, ops }); console.log("Directory changes detected", { dbOps, ops });
if (attempt > 1) { if (force) {
showStaleSyncToast(); await applySync(workspaceId, syncDir, ops);
return;
} }
showDialog({ showDialog({
@@ -117,7 +93,8 @@ export const syncWorkspace = createFastMutation<
className="h-full grid grid-rows-[auto_auto_minmax(0,1fr)_auto] gap-3" className="h-full grid grid-rows-[auto_auto_minmax(0,1fr)_auto] gap-3"
onSubmit={async (e) => { onSubmit={async (e) => {
e.preventDefault(); e.preventDefault();
await apply(); await applySync(workspaceId, syncDir, ops);
hide();
}} }}
> >
{isDeletingWorkspace ? ( {isDeletingWorkspace ? (
@@ -6,12 +6,11 @@ import { showDialog } from "../lib/dialog";
import { jotaiStore } from "../lib/jotai"; import { jotaiStore } from "../lib/jotai";
import { setWorkspaceSearchParams } from "../lib/setWorkspaceSearchParams"; import { setWorkspaceSearchParams } from "../lib/setWorkspaceSearchParams";
/** export const createSubEnvironmentAndActivate = createFastMutation<
* Prompt for and create a sub-environment of the given base environment, resolving with the new string | null,
* environment's ID (or null if the dialog was dismissed). This does not change the workspace's unknown,
* active environment. Environment | null
*/ >({
export const createSubEnvironment = createFastMutation<string | null, unknown, Environment | null>({
mutationKey: ["create_environment"], mutationKey: ["create_environment"],
mutationFn: async (baseEnvironment) => { mutationFn: async (baseEnvironment) => {
if (baseEnvironment == null) { if (baseEnvironment == null) {
@@ -42,17 +41,6 @@ export const createSubEnvironment = createFastMutation<string | null, unknown, E
}); });
}); });
}, },
});
/** Same as {@link createSubEnvironment}, but also makes the new environment the active one. */
export const createSubEnvironmentAndActivate = createFastMutation<
string | null,
unknown,
Environment | null
>({
mutationKey: ["create_environment_and_activate"],
mutationFn: (baseEnvironment) => createSubEnvironment.mutateAsync(baseEnvironment),
disableToastError: true, // Already shown by createSubEnvironment
onSuccess: async (environmentId) => { onSuccess: async (environmentId) => {
if (environmentId == null) { if (environmentId == null) {
return; // Was not created return; // Was not created
@@ -3,9 +3,9 @@ import type { GrpcRequest, HttpRequest, WebsocketRequest } from "@yaakapp-intern
import { MoveToWorkspaceDialog } from "../components/MoveToWorkspaceDialog"; import { MoveToWorkspaceDialog } from "../components/MoveToWorkspaceDialog";
import { activeWorkspaceIdAtom } from "../hooks/useActiveWorkspace"; import { activeWorkspaceIdAtom } from "../hooks/useActiveWorkspace";
import { createFastMutation } from "../hooks/useFastMutation"; import { createFastMutation } from "../hooks/useFastMutation";
import { pluralizeCount } from "../lib/pluralize";
import { showDialog } from "../lib/dialog"; import { showDialog } from "../lib/dialog";
import { jotaiStore } from "../lib/jotai"; import { jotaiStore } from "../lib/jotai";
import { pluralizeCount } from "@yaakapp-internal/lib/pluralize";
export const moveToWorkspace = createFastMutation({ export const moveToWorkspace = createFastMutation({
mutationKey: ["move_workspace"], mutationKey: ["move_workspace"],
@@ -17,7 +17,7 @@ export const openWorkspaceFromSyncDir = createFastMutation<void, void, string>({
return; return;
} }
await applySync(workspace.id, dir, ops, { fsOnly: true }); await applySync(workspace.id, dir, ops);
await router.navigate({ await router.navigate({
to: "/workspaces/$workspaceId", to: "/workspaces/$workspaceId",
@@ -1,10 +1,16 @@
import type { WorkspaceSettingsTab } from "../components/WorkspaceSettingsDialog"; import type {
WorkspaceSettingsHighlight,
WorkspaceSettingsTab,
} from "../components/WorkspaceSettingsDialog";
import { WorkspaceSettingsDialog } from "../components/WorkspaceSettingsDialog"; import { WorkspaceSettingsDialog } from "../components/WorkspaceSettingsDialog";
import { activeWorkspaceIdAtom } from "../hooks/useActiveWorkspace"; import { activeWorkspaceIdAtom } from "../hooks/useActiveWorkspace";
import { jotaiStore } from "../lib/jotai"; import { jotaiStore } from "../lib/jotai";
export function openWorkspaceSettings(tab?: WorkspaceSettingsTab) { export function openWorkspaceSettings(
tab?: WorkspaceSettingsTab,
highlight?: WorkspaceSettingsHighlight,
) {
const workspaceId = jotaiStore.get(activeWorkspaceIdAtom); const workspaceId = jotaiStore.get(activeWorkspaceIdAtom);
if (workspaceId == null) return; if (workspaceId == null) return;
WorkspaceSettingsDialog.show(workspaceId, tab); WorkspaceSettingsDialog.show(workspaceId, tab, highlight);
} }
@@ -1,99 +0,0 @@
import { platform } from "@yaakapp-internal/platform";
import {
Banner,
type EditorHost,
EditorHostProvider,
EmptyStateText,
type HostBodyViewerArgs,
type HttpBodyLoader,
LoadingIcon,
type StoredValue,
type StoredValueNamespace,
} from "@yaakapp-internal/ui";
import { lazy, type ReactNode, Suspense } from "react";
import { useKeyValue } from "../hooks/useKeyValue";
import { copyToClipboard } from "../lib/copy";
import { showDialog } from "../lib/dialog";
import { showPrompt } from "../lib/prompt";
import { useDetailsBannerStoredValue } from "./core/DetailsBanner";
import { Editor } from "./core/Editor/LazyEditor";
import { Input } from "./core/Input";
import { ErrorBoundary } from "./ErrorBoundary";
import { MultipartViewer } from "./responseViewers/MultipartViewer";
import { TextViewer } from "./responseViewers/TextViewer";
import { SelectFile } from "./SelectFile";
const PdfViewer = lazy(() =>
import("./responseViewers/PdfViewer").then((m) => ({ default: m.PdfViewer })),
);
function useClientStoredValue<T extends StoredValue>(
key: string | string[] | null,
fallback: T,
namespace: StoredValueNamespace = "global",
) {
// A null key is never written by the shared components, so any stable key will do
const { value, set } = useKeyValue<T>({ namespace, key: key ?? ["tabs", "default"], fallback });
return [value ?? fallback, set] as const;
}
function renderBodyViewer({ source, mimeType, body, complete }: HostBodyViewerArgs) {
if (!mimeType?.match(/pdf/i)) return null;
return source === "response" ? (
<PdfResponseBody body={body} complete={complete} />
) : (
<PdfRequestBody body={body} />
);
}
/** Waits for the whole response, then loads the PDF from its file */
function PdfResponseBody({ body, complete }: { body: HttpBodyLoader; complete: boolean }) {
const bodyUrl = body.useUrl(complete);
if (!complete || bodyUrl.isLoading) {
return (
<EmptyStateText>
<LoadingIcon />
</EmptyStateText>
);
}
if (bodyUrl.error) {
return <Banner color="danger">{String(bodyUrl.error)}</Banner>;
}
if (bodyUrl.data == null) {
return <div>Empty response body</div>;
}
return <PdfViewer bodyUrl={bodyUrl.data} />;
}
function PdfRequestBody({ body }: { body: HttpBodyLoader }) {
const bytes = body.useBytes();
if (bytes.data == null) return null;
return (
<Suspense fallback={<LoadingIcon />}>
<PdfViewer data={bytes.data} />
</Suspense>
);
}
const clientEditorHost: EditorHost = {
Editor,
Input,
SelectFile,
showDialog,
showPrompt,
basename: (path) => platform.files.basename(path),
useStoredValue: useClientStoredValue,
useDetailsBannerStoredValue,
ErrorBoundary,
TextViewer,
MultipartViewer,
renderBodyViewer,
openUrl: (url) => platform.openUrl(url),
copy: (text) => copyToClipboard(text, { disableToast: true }),
};
/** Gives the shared editing components the client's templated editor, dialogs and storage */
export function ClientEditorHost({ children }: { children: ReactNode }) {
return <EditorHostProvider value={clientEditorHost}>{children}</EditorHostProvider>;
}
@@ -1,12 +1,12 @@
import { gitClone } from "@yaakapp-internal/git"; import { gitClone } from "@yaakapp-internal/git";
import { Banner, VStack } from "@yaakapp-internal/ui"; import { Banner, VStack } from "@yaakapp-internal/ui";
import { useId, useState } from "react"; import { useState } from "react";
import { openWorkspaceFromSyncDir } from "../commands/openWorkspaceFromSyncDir"; import { openWorkspaceFromSyncDir } from "../commands/openWorkspaceFromSyncDir";
import { appInfo } from "../lib/appInfo"; import { appInfo } from "../lib/appInfo";
import { CommercialUseBanner } from "./CommercialUseBanner"; import { CommercialUseBanner } from "./CommercialUseBanner";
import { showErrorToast } from "../lib/toast"; import { showErrorToast } from "../lib/toast";
import { Button } from "./core/Button";
import { Checkbox } from "./core/Checkbox"; import { Checkbox } from "./core/Checkbox";
import { DialogFooter } from "./core/Dialog";
import { IconButton } from "./core/IconButton"; import { IconButton } from "./core/IconButton";
import { PlainInput } from "./core/PlainInput"; import { PlainInput } from "./core/PlainInput";
import { promptCredentials } from "./git/credentials"; import { promptCredentials } from "./git/credentials";
@@ -29,7 +29,6 @@ export function CloneGitRepositoryDialog({ hide }: Props) {
const [subdirectory, setSubdirectory] = useState<string>(""); const [subdirectory, setSubdirectory] = useState<string>("");
const [isCloning, setIsCloning] = useState(false); const [isCloning, setIsCloning] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const formId = useId();
const repoName = extractRepoName(url); const repoName = extractRepoName(url);
const sep = getPathSeparator(baseDirectory); const sep = getPathSeparator(baseDirectory);
@@ -84,7 +83,7 @@ export function CloneGitRepositoryDialog({ hide }: Props) {
}; };
return ( return (
<VStack as="form" id={formId} space={3} alignItems="start" onSubmit={handleClone}> <VStack as="form" space={3} alignItems="start" className="pb-3" onSubmit={handleClone}>
{error && ( {error && (
<Banner color="danger" className="w-full"> <Banner color="danger" className="w-full">
{error} {error}
@@ -133,17 +132,15 @@ export function CloneGitRepositoryDialog({ hide }: Props) {
/> />
)} )}
<DialogFooter <Button
actions={[ type="submit"
{ color="primary"
label: isCloning ? "Cloning..." : "Clone Repository", className="w-full mt-3"
color: "primary", disabled={!url || !directory || isCloning}
form: formId, isLoading={isCloning}
disabled: !url || !directory || isCloning, >
isLoading: isCloning, {isCloning ? "Cloning..." : "Clone Repository"}
}, </Button>
]}
/>
</VStack> </VStack>
); );
} }
@@ -1,11 +1,12 @@
import type { HttpRequest } from "@yaakapp-internal/models"; import type { HttpRequest } from "@yaakapp-internal/models";
import { patchModel } from "@yaakapp-internal/models"; import { patchModel } from "@yaakapp-internal/models";
import { Banner, HStack, InlineCode, SizeTag } from "@yaakapp-internal/ui"; import { Banner, HStack, InlineCode } from "@yaakapp-internal/ui";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { useToggle } from "../hooks/useToggle"; import { useToggle } from "../hooks/useToggle";
import { showConfirm } from "../lib/confirm"; import { showConfirm } from "../lib/confirm";
import { Button } from "./core/Button"; import { Button } from "./core/Button";
import { Link } from "./core/Link"; import { Link } from "./core/Link";
import { SizeTag } from "./core/SizeTag";
interface Props { interface Props {
children: ReactNode; children: ReactNode;
@@ -0,0 +1,61 @@
import type { HttpResponse } from "@yaakapp-internal/models";
import { Banner, HStack, InlineCode } from "@yaakapp-internal/ui";
import { type ReactNode, useMemo } from "react";
import { useSaveResponse } from "../hooks/useSaveResponse";
import { useToggle } from "../hooks/useToggle";
import { isProbablyTextContentType } from "../lib/contentType";
import { getContentTypeFromHeaders } from "../lib/model_util";
import { getResponseBodyText } from "../lib/responseBody";
import { CopyButton } from "./CopyButton";
import { Button } from "./core/Button";
import { SizeTag } from "./core/SizeTag";
interface Props {
children: ReactNode;
response: HttpResponse;
}
const LARGE_BYTES = 2 * 1000 * 1000;
export function ConfirmLargeResponse({ children, response }: Props) {
const { mutate: saveResponse } = useSaveResponse(response);
const [showLargeResponse, toggleShowLargeResponse] = useToggle();
const isProbablyText = useMemo(() => {
const contentType = getContentTypeFromHeaders(response.headers);
return isProbablyTextContentType(contentType);
}, [response.headers]);
const contentLength = response.contentLength ?? 0;
const isLarge = contentLength > LARGE_BYTES;
if (!showLargeResponse && isLarge) {
return (
<Banner color="primary" className="flex flex-col gap-3">
<p>
Showing responses over{" "}
<InlineCode>
<SizeTag contentLength={LARGE_BYTES} />
</InlineCode>{" "}
may impact performance
</p>
<HStack wrap space={2}>
<Button color="primary" size="xs" onClick={toggleShowLargeResponse}>
Reveal Response
</Button>
<Button color="secondary" variant="border" size="xs" onClick={() => saveResponse()}>
Save to File
</Button>
{isProbablyText && (
<CopyButton
color="secondary"
variant="border"
size="xs"
text={() => getResponseBodyText({ response, filter: null })}
/>
)}
</HStack>
</Banner>
);
}
return <>{children}</>;
}
@@ -0,0 +1,56 @@
import type { HttpResponse } from "@yaakapp-internal/models";
import { Banner, HStack, InlineCode } from "@yaakapp-internal/ui";
import { type ReactNode, useMemo } from "react";
import { getRequestBodyText as getHttpResponseRequestBodyText } from "../hooks/useHttpRequestBody";
import { useToggle } from "../hooks/useToggle";
import { isProbablyTextContentType } from "../lib/contentType";
import { getContentTypeFromHeaders } from "../lib/model_util";
import { CopyButton } from "./CopyButton";
import { Button } from "./core/Button";
import { SizeTag } from "./core/SizeTag";
interface Props {
children: ReactNode;
response: HttpResponse;
}
const LARGE_BYTES = 2 * 1000 * 1000;
export function ConfirmLargeResponseRequest({ children, response }: Props) {
const [showLargeResponse, toggleShowLargeResponse] = useToggle();
const isProbablyText = useMemo(() => {
const contentType = getContentTypeFromHeaders(response.headers);
return isProbablyTextContentType(contentType);
}, [response.headers]);
const contentLength = response.requestContentLength ?? 0;
const isLarge = contentLength > LARGE_BYTES;
if (!showLargeResponse && isLarge) {
return (
<Banner color="primary" className="flex flex-col gap-3">
<p>
Showing content over{" "}
<InlineCode>
<SizeTag contentLength={LARGE_BYTES} />
</InlineCode>{" "}
may impact performance
</p>
<HStack wrap space={2}>
<Button color="primary" size="xs" onClick={toggleShowLargeResponse}>
Reveal Request Body
</Button>
{isProbablyText && (
<CopyButton
color="secondary"
variant="border"
size="xs"
text={() => getHttpResponseRequestBodyText(response).then((d) => d?.bodyText ?? "")}
/>
)}
</HStack>
</Banner>
);
}
return <>{children}</>;
}
+1 -2
View File
@@ -25,13 +25,12 @@ import {
TableHeaderCell, TableHeaderCell,
TableRow, TableRow,
TruncatedWideTableCell, TruncatedWideTableCell,
KeyValueRows,
} from "@yaakapp-internal/ui"; } from "@yaakapp-internal/ui";
import { IconButton } from "./core/IconButton"; import { IconButton } from "./core/IconButton";
import { Checkbox } from "./core/Checkbox"; import { Checkbox } from "./core/Checkbox";
import classNames from "classnames"; import classNames from "classnames";
import { EventDetailHeader } from "./core/EventViewer"; import { EventDetailHeader } from "./core/EventViewer";
import { KeyValueRow } from "./core/KeyValueRow"; import { KeyValueRow, KeyValueRows } from "./core/KeyValueRow";
import { EmptyStateText } from "./EmptyStateText"; import { EmptyStateText } from "./EmptyStateText";
import { PlainInput } from "./core/PlainInput"; import { PlainInput } from "./core/PlainInput";
import { Select } from "./core/Select"; import { Select } from "./core/Select";
+25 -16
View File
@@ -1,22 +1,31 @@
import { import { IconButton, type IconButtonProps, useTimedBoolean } from "@yaakapp-internal/ui";
CopyIconButton as BaseCopyIconButton,
type CopyIconButtonProps,
} from "@yaakapp-internal/ui";
import { copyToClipboard } from "../lib/copy"; import { copyToClipboard } from "../lib/copy";
import { showToast } from "../lib/toast"; import { showToast } from "../lib/toast";
export function CopyIconButton(props: Omit<CopyIconButtonProps, "copy" | "onCopyFailed">) { interface Props extends Omit<IconButtonProps, "onClick" | "icon"> {
return <BaseCopyIconButton {...props} copy={copy} onCopyFailed={showCopyFailed} />; text: string | (() => Promise<string | null>);
} }
function copy(text: string) { export function CopyIconButton({ text, ...props }: Props) {
copyToClipboard(text, { disableToast: true }); const [copied, setCopied] = useTimedBoolean();
} return (
<IconButton
function showCopyFailed() { {...props}
showToast({ icon={copied ? "check" : "copy"}
id: "failed-to-copy", showConfirm
color: "danger", onClick={async () => {
message: "Failed to copy", const content = typeof text === "function" ? await text() : text;
}); if (content == null) {
showToast({
id: "failed-to-copy",
color: "danger",
message: "Failed to copy",
});
} else {
copyToClipboard(content, { disableToast: true });
setCopied();
}
}}
/>
);
} }
@@ -1,12 +1,12 @@
import { createWorkspaceModel } from "@yaakapp-internal/models"; import { createWorkspaceModel } from "@yaakapp-internal/models";
import { useId, useState } from "react"; import { useState } from "react";
import { useToggle } from "../hooks/useToggle"; import { useToggle } from "../hooks/useToggle";
import { ColorIndicator } from "./ColorIndicator"; import { ColorIndicator } from "./ColorIndicator";
import { Button } from "./core/Button";
import { Checkbox } from "./core/Checkbox"; import { Checkbox } from "./core/Checkbox";
import { ColorPickerWithThemeColors } from "./core/ColorPicker"; import { ColorPickerWithThemeColors } from "./core/ColorPicker";
import { DialogFooter } from "./core/Dialog"; import { Label } from "./core/Label";
import { PlainInput } from "./core/PlainInput"; import { PlainInput } from "./core/PlainInput";
import { Label } from "@yaakapp-internal/ui";
interface Props { interface Props {
onCreate: (id: string) => void; onCreate: (id: string) => void;
@@ -18,11 +18,9 @@ export function CreateEnvironmentDialog({ workspaceId, hide, onCreate }: Props)
const [name, setName] = useState<string>(""); const [name, setName] = useState<string>("");
const [color, setColor] = useState<string | null>(null); const [color, setColor] = useState<string | null>(null);
const [sharable, toggleSharable] = useToggle(false); const [sharable, toggleSharable] = useToggle(false);
const formId = useId();
return ( return (
<form <form
id={formId} className="pb-3 flex flex-col gap-3"
className="flex flex-col gap-3"
onSubmit={async (e) => { onSubmit={async (e) => {
e.preventDefault(); e.preventDefault();
const id = await createWorkspaceModel({ const id = await createWorkspaceModel({
@@ -61,17 +59,10 @@ export function CreateEnvironmentDialog({ workspaceId, hide, onCreate }: Props)
</Label> </Label>
<ColorPickerWithThemeColors onChange={setColor} color={color} /> <ColorPickerWithThemeColors onChange={setColor} color={color} />
</div> </div>
<DialogFooter <Button type="submit" color="secondary" className="mt-3">
inline {color != null && <ColorIndicator color={color} />}
actions={[ Create Environment
{ </Button>
label: "Create Environment",
color: "secondary",
form: formId,
leftSlot: color != null ? <ColorIndicator color={color} /> : undefined,
},
]}
/>
</form> </form>
); );
} }
@@ -1,14 +1,15 @@
import { gitMutations } from "@yaakapp-internal/git"; import { gitMutations } from "@yaakapp-internal/git";
import type { WorkspaceMeta } from "@yaakapp-internal/models"; import type { WorkspaceMeta } from "@yaakapp-internal/models";
import { createGlobalModel, updateModel } from "@yaakapp-internal/models"; import { createGlobalModel, updateModel } from "@yaakapp-internal/models";
import { VStack, Label } from "@yaakapp-internal/ui"; import { VStack } from "@yaakapp-internal/ui";
import { useId, useState } from "react"; import { useState } from "react";
import { router } from "../lib/router"; import { router } from "../lib/router";
import { setupOrConfigureEncryption } from "../lib/setupOrConfigureEncryption"; import { setupOrConfigureEncryption } from "../lib/setupOrConfigureEncryption";
import { rpc } from "../lib/rpc"; import { rpc } from "../lib/rpc";
import { showErrorToast } from "../lib/toast"; import { showErrorToast } from "../lib/toast";
import { Button } from "./core/Button";
import { Checkbox } from "./core/Checkbox"; import { Checkbox } from "./core/Checkbox";
import { DialogFooter } from "./core/Dialog"; import { Label } from "./core/Label";
import { PlainInput } from "./core/PlainInput"; import { PlainInput } from "./core/PlainInput";
import { EncryptionHelp } from "./EncryptionHelp"; import { EncryptionHelp } from "./EncryptionHelp";
import { gitCallbacks } from "./git/callbacks"; import { gitCallbacks } from "./git/callbacks";
@@ -25,13 +26,12 @@ export function CreateWorkspaceDialog({ hide }: Props) {
initGit?: boolean; initGit?: boolean;
}>({ filePath: null, initGit: false }); }>({ filePath: null, initGit: false });
const [setupEncryption, setSetupEncryption] = useState<boolean>(false); const [setupEncryption, setSetupEncryption] = useState<boolean>(false);
const formId = useId();
return ( return (
<VStack <VStack
as="form" as="form"
id={formId}
space={3} space={3}
alignItems="start" alignItems="start"
className="pb-3"
onSubmit={async (e) => { onSubmit={async (e) => {
e.preventDefault(); e.preventDefault();
const workspaceId = await createGlobalModel({ model: "workspace", name }); const workspaceId = await createGlobalModel({ model: "workspace", name });
@@ -89,7 +89,9 @@ export function CreateWorkspaceDialog({ hide }: Props) {
title="Enable Encryption" title="Enable Encryption"
/> />
</div> </div>
<DialogFooter actions={[{ label: "Create Workspace", color: "primary", form: formId }]} /> <Button type="submit" color="primary" className="w-full mt-3">
Create Workspace
</Button>
</VStack> </VStack>
); );
} }
+25 -5
View File
@@ -11,7 +11,7 @@ import type {
FormInputText, FormInputText,
JsonPrimitive, JsonPrimitive,
} from "@yaakapp-internal/plugins"; } from "@yaakapp-internal/plugins";
import { Banner, VStack, Label } from "@yaakapp-internal/ui"; import { Banner, VStack } from "@yaakapp-internal/ui";
import classNames from "classnames"; import classNames from "classnames";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { useCallback, useEffect, useMemo } from "react"; import { useCallback, useEffect, useMemo } from "react";
@@ -26,10 +26,12 @@ import { Editor } from "./core/Editor/LazyEditor";
import { IconButton } from "./core/IconButton"; import { IconButton } from "./core/IconButton";
import type { InputProps } from "./core/Input"; import type { InputProps } from "./core/Input";
import { Input } from "./core/Input"; import { Input } from "./core/Input";
import { Label } from "./core/Label";
import type { Pair } from "./core/PairEditor"; import type { Pair } from "./core/PairEditor";
import { PairEditor } from "./core/PairEditor"; import { PairEditor } from "./core/PairEditor";
import { PlainInput } from "./core/PlainInput"; import { PlainInput } from "./core/PlainInput";
import { Select } from "./core/Select"; import { Select } from "./core/Select";
import { SecretVariableHint } from "./hints/SecretVariableHint";
import { Markdown } from "./Markdown"; import { Markdown } from "./Markdown";
import { SelectFile } from "./SelectFile"; import { SelectFile } from "./SelectFile";
@@ -45,6 +47,8 @@ interface Props<T> {
stateKey: string; stateKey: string;
className?: string; className?: string;
disabled?: boolean; disabled?: boolean;
/** Offer to move literal secrets typed into password fields into a variable */
suggestVariables?: boolean;
} }
export function DynamicForm<T extends Record<string, JsonPrimitive>>({ export function DynamicForm<T extends Record<string, JsonPrimitive>>({
@@ -56,6 +60,7 @@ export function DynamicForm<T extends Record<string, JsonPrimitive>>({
stateKey, stateKey,
className, className,
disabled, disabled,
suggestVariables,
}: Props<T>) { }: Props<T>) {
const setDataAttr = useCallback( const setDataAttr = useCallback(
(name: string, value: JsonPrimitive) => { (name: string, value: JsonPrimitive) => {
@@ -72,6 +77,7 @@ export function DynamicForm<T extends Record<string, JsonPrimitive>>({
stateKey={stateKey} stateKey={stateKey}
autocompleteFunctions={autocompleteFunctions} autocompleteFunctions={autocompleteFunctions}
autocompleteVariables={autocompleteVariables} autocompleteVariables={autocompleteVariables}
suggestVariables={suggestVariables}
data={data} data={data}
className={classNames(className, "pb-4")} // Pad the bottom to look nice className={classNames(className, "pb-4")} // Pad the bottom to look nice
/> />
@@ -102,6 +108,7 @@ type FormInputsProps<T> = Pick<
> & { > & {
setDataAttr: (name: string, value: JsonPrimitive) => void; setDataAttr: (name: string, value: JsonPrimitive) => void;
disabled?: boolean; disabled?: boolean;
suggestVariables?: boolean;
}; };
function FormInputs<T extends Record<string, JsonPrimitive>>({ function FormInputs<T extends Record<string, JsonPrimitive>>({
@@ -112,6 +119,7 @@ function FormInputs<T extends Record<string, JsonPrimitive>>({
setDataAttr, setDataAttr,
data, data,
disabled, disabled,
suggestVariables,
}: FormInputsProps<T>) { }: FormInputsProps<T>) {
return ( return (
<> <>
@@ -146,6 +154,7 @@ function FormInputs<T extends Record<string, JsonPrimitive>>({
arg={input} arg={input}
autocompleteFunctions={autocompleteFunctions || false} autocompleteFunctions={autocompleteFunctions || false}
autocompleteVariables={autocompleteVariables || false} autocompleteVariables={autocompleteVariables || false}
suggestVariables={suggestVariables || false}
onChange={(v) => setDataAttr(input.name, v)} onChange={(v) => setDataAttr(input.name, v)}
value={ value={
data[input.name] != null ? String(data[input.name]) : (input.defaultValue ?? "") data[input.name] != null ? String(data[input.name]) : (input.defaultValue ?? "")
@@ -286,6 +295,7 @@ function TextArg({
value, value,
autocompleteFunctions, autocompleteFunctions,
autocompleteVariables, autocompleteVariables,
suggestVariables,
stateKey, stateKey,
}: { }: {
arg: FormInputText; arg: FormInputText;
@@ -293,6 +303,7 @@ function TextArg({
onChange: (v: string) => void; onChange: (v: string) => void;
autocompleteFunctions: boolean; autocompleteFunctions: boolean;
autocompleteVariables: boolean; autocompleteVariables: boolean;
suggestVariables: boolean;
stateKey: string; stateKey: string;
}) { }) {
const props: InputProps = { const props: InputProps = {
@@ -315,10 +326,19 @@ function TextArg({
autocompleteFunctions, autocompleteFunctions,
autocompleteVariables, autocompleteVariables,
}; };
if (autocompleteVariables || autocompleteFunctions || arg.completionOptions) { const input =
return <Input {...props} />; autocompleteVariables || autocompleteFunctions || arg.completionOptions ? (
} <Input {...props} />
return <PlainInput {...props} />; ) : (
<PlainInput {...props} />
);
if (!suggestVariables || !arg.password) return input;
return (
<div className="flex flex-col gap-2">
{input}
<SecretVariableHint name={arg.name} value={value} onReplace={onChange} />
</div>
);
} }
function EditorArg({ function EditorArg({
+24 -1
View File
@@ -1 +1,24 @@
export { EmptyStateText } from "@yaakapp-internal/ui"; import classNames from "classnames";
import type { ReactNode } from "react";
interface Props {
children: ReactNode;
className?: string;
wrapperClassName?: string;
}
export function EmptyStateText({ children, className, wrapperClassName }: Props) {
return (
<div className={classNames("w-full h-full pb-2", wrapperClassName)}>
<div
className={classNames(
className,
"rounded-lg border border-dashed border-border-subtle",
"h-full py-2 text-text-subtlest flex items-center justify-center italic",
)}
>
{children}
</div>
</div>
);
}
@@ -1,19 +1,11 @@
import type { Environment, Workspace } from "@yaakapp-internal/models"; import type { Environment, Workspace } from "@yaakapp-internal/models";
import { duplicateModel, patchModel } from "@yaakapp-internal/models"; import { duplicateModel, patchModel } from "@yaakapp-internal/models";
import type { TreeHandle, TreeNode, TreeProps } from "@yaakapp-internal/ui"; import type { TreeHandle, TreeNode, TreeProps } from "@yaakapp-internal/ui";
import { Banner, Icon, InlineCode, SplitLayout, Tree, IconTooltip } from "@yaakapp-internal/ui"; import { Banner, Icon, InlineCode, SplitLayout, Tree } from "@yaakapp-internal/ui";
import { atom, useAtomValue } from "jotai"; import { atom, useAtomValue } from "jotai";
import { atomFamily } from "jotai-family"; import { atomFamily } from "jotai-family";
import { import { useCallback, useLayoutEffect, useRef, useState } from "react";
createContext, import { createSubEnvironmentAndActivate } from "../commands/createEnvironment";
useCallback,
useContext,
useEffect,
useLayoutEffect,
useRef,
useState,
} from "react";
import { createSubEnvironment } from "../commands/createEnvironment";
import { activeWorkspaceAtom, activeWorkspaceIdAtom } from "../hooks/useActiveWorkspace"; import { activeWorkspaceAtom, activeWorkspaceIdAtom } from "../hooks/useActiveWorkspace";
import { import {
environmentsBreakdownAtom, environmentsBreakdownAtom,
@@ -30,6 +22,7 @@ import { showColorPicker } from "../lib/showColorPicker";
import type { ContextMenuProps, DropdownItem } from "./core/Dropdown"; import type { ContextMenuProps, DropdownItem } from "./core/Dropdown";
import { ContextMenu } from "./core/Dropdown"; import { ContextMenu } from "./core/Dropdown";
import { IconButton } from "./core/IconButton"; import { IconButton } from "./core/IconButton";
import { IconTooltip } from "./core/IconTooltip";
import type { PairEditorHandle } from "./core/PairEditor"; import type { PairEditorHandle } from "./core/PairEditor";
import { EnvironmentColorIndicator } from "./EnvironmentColorIndicator"; import { EnvironmentColorIndicator } from "./EnvironmentColorIndicator";
import { EnvironmentEditor } from "./EnvironmentEditor"; import { EnvironmentEditor } from "./EnvironmentEditor";
@@ -47,9 +40,6 @@ interface Props {
type TreeModel = Environment | Workspace; type TreeModel = Environment | Workspace;
/** Lets tree row slots create a sub-environment and select it in the editor. */
const CreateSubEnvironmentContext = createContext<() => Promise<void>>(async () => {});
export function EnvironmentEditDialog({ initialEnvironmentId, setRef }: Props) { export function EnvironmentEditDialog({ initialEnvironmentId, setRef }: Props) {
const { allEnvironments, baseEnvironment, baseEnvironments } = useEnvironmentsBreakdown(); const { allEnvironments, baseEnvironment, baseEnvironments } = useEnvironmentsBreakdown();
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<string | null>( const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<string | null>(
@@ -125,7 +115,7 @@ function EnvironmentEditDialogSidebar({
const activeWorkspaceId = useAtomValue(activeWorkspaceIdAtom) ?? ""; const activeWorkspaceId = useAtomValue(activeWorkspaceIdAtom) ?? "";
const treeId = `environment.${activeWorkspaceId}.sidebar`; const treeId = `environment.${activeWorkspaceId}.sidebar`;
const treeRef = useRef<TreeHandle>(null); const treeRef = useRef<TreeHandle>(null);
const { allEnvironments, baseEnvironment, baseEnvironments } = useEnvironmentsBreakdown(); const { baseEnvironment, baseEnvironments } = useEnvironmentsBreakdown();
// oxlint-disable-next-line react-hooks/exhaustive-deps -- none // oxlint-disable-next-line react-hooks/exhaustive-deps -- none
useLayoutEffect(() => { useLayoutEffect(() => {
@@ -134,31 +124,6 @@ function EnvironmentEditDialogSidebar({
treeRef.current?.focus(); treeRef.current?.focus();
}, []); }, []);
// A just-created environment to select once it reaches the model store. Selecting it before
// then would show a "failed to find" error in the editor, and the tree would drop the
// selection of an item it doesn't have yet.
const [pendingSelectionId, setPendingSelectionId] = useState<string | null>(null);
const tree = useAtomValue(treeAtom);
useEffect(() => {
if (pendingSelectionId == null) return;
if (!allEnvironments.some((e) => e.id === pendingSelectionId)) return;
setPendingSelectionId(null);
setSelectedEnvironmentId(pendingSelectionId);
// The tree leaves out sub-environments while there are multiple base environments
const node = tree == null ? null : findTreeNode(tree, pendingSelectionId);
if (node == null) return;
if (node.parent != null) {
// Expand the parent so the new item is visible to be selected
const parentId = node.parent.item.id;
jotaiStore.set(collapsedFamily(treeId), (prev) => ({ ...prev, [parentId]: false }));
}
// Wait a frame so the tree's own pending selection fixups, which may have been scheduled
// before the new item arrived, don't reset this selection
requestAnimationFrame(() => treeRef.current?.selectItem(pendingSelectionId));
}, [allEnvironments, pendingSelectionId, setSelectedEnvironmentId, tree, treeId]);
const handleDeleteEnvironment = useCallback( const handleDeleteEnvironment = useCallback(
async (environment: Environment) => { async (environment: Environment) => {
await deleteModelWithConfirm(environment); await deleteModelWithConfirm(environment);
@@ -169,14 +134,6 @@ function EnvironmentEditDialogSidebar({
[baseEnvironment?.id, selectedEnvironmentId, setSelectedEnvironmentId], [baseEnvironment?.id, selectedEnvironmentId, setSelectedEnvironmentId],
); );
const handleCreateSubEnvironment = useCallback(async () => {
const { baseEnvironment } = jotaiStore.get(environmentsBreakdownAtom);
if (baseEnvironment == null) return;
const id = await createSubEnvironment.mutateAsync(baseEnvironment);
// Show the new environment in the editor without changing the workspace's active environment
if (id != null) setPendingSelectionId(id);
}, []);
const treeHasFocus = useCallback(() => treeRef.current?.hasFocus() ?? false, []); const treeHasFocus = useCallback(() => treeRef.current?.hasFocus() ?? false, []);
const getSelectedTreeModels = useCallback( const getSelectedTreeModels = useCallback(
@@ -238,14 +195,13 @@ function EnvironmentEditDialogSidebar({
const addEnvironmentItem: DropdownItem = { const addEnvironmentItem: DropdownItem = {
label: "Create Sub Environment", label: "Create Sub Environment",
leftSlot: <Icon icon="plus" />, leftSlot: <Icon icon="plus" />,
onSelect: handleCreateSubEnvironment, onSelect: async () => {
await createSubEnvironment();
},
}; };
// Sub-environments aren't shown while there are multiple base environments, same as the
// plus button on the base environment row
const canCreateSubEnvironment = baseEnvironments.length <= 1;
if (environment == null || environment.model !== "environment") { if (environment == null || environment.model !== "environment") {
return canCreateSubEnvironment ? [addEnvironmentItem] : []; return [addEnvironmentItem];
} }
const singleEnvironment = items.length === 1; const singleEnvironment = items.length === 1;
@@ -301,7 +257,7 @@ function EnvironmentEditDialogSidebar({
]; ];
// Add sub environment to base environment // Add sub environment to base environment
if (isBaseEnvironment(environment) && singleEnvironment && canCreateSubEnvironment) { if (isBaseEnvironment(environment) && singleEnvironment) {
menuItems.push({ type: "separator" }); menuItems.push({ type: "separator" });
menuItems.push(addEnvironmentItem); menuItems.push(addEnvironmentItem);
} }
@@ -310,7 +266,6 @@ function EnvironmentEditDialogSidebar({
}, },
[ [
baseEnvironments.length, baseEnvironments.length,
handleCreateSubEnvironment,
handleDeleteEnvironment, handleDeleteEnvironment,
handleDuplicateSelected, handleDuplicateSelected,
handleRenameSelected, handleRenameSelected,
@@ -362,37 +317,34 @@ function EnvironmentEditDialogSidebar({
); );
const renderContextMenuFn = useCallback<NonNullable<TreeProps<TreeModel>["renderContextMenu"]>>( const renderContextMenuFn = useCallback<NonNullable<TreeProps<TreeModel>["renderContextMenu"]>>(
({ items, position, onClose }) => ({ items, position, onClose }) => (
// Right-clicking empty space has nothing to offer while there are multiple base environments <ContextMenu items={items as DropdownItem[]} triggerPosition={position} onClose={onClose} />
items.length === 0 ? null : ( ),
<ContextMenu items={items as DropdownItem[]} triggerPosition={position} onClose={onClose} />
),
[], [],
); );
const tree = useAtomValue(treeAtom);
return ( return (
<aside className="x-theme-sidebar h-full w-full min-w-0 grid overflow-y-auto border-r border-border-subtle "> <aside className="x-theme-sidebar h-full w-full min-w-0 grid overflow-y-auto border-r border-border-subtle ">
{tree != null && ( {tree != null && (
<CreateSubEnvironmentContext.Provider value={handleCreateSubEnvironment}> <div className="pt-2">
<div className="pt-2"> <Tree
<Tree ref={treeRef}
ref={treeRef} treeId={treeId}
treeId={treeId} collapsedAtom={collapsedFamily(treeId)}
collapsedAtom={collapsedFamily(treeId)} className="px-2 pb-10"
className="px-2 pb-10" root={tree}
root={tree} getContextMenu={getContextMenu}
getContextMenu={getContextMenu} renderContextMenu={renderContextMenuFn}
renderContextMenu={renderContextMenuFn} onDragEnd={handleDragEnd}
onDragEnd={handleDragEnd} getItemKey={(i) => `${i.id}::${i.name}`}
getItemKey={(i) => `${i.id}::${i.name}`} ItemLeftSlotInner={ItemLeftSlotInner}
ItemLeftSlotInner={ItemLeftSlotInner} ItemRightSlot={ItemRightSlot}
ItemRightSlot={ItemRightSlot} ItemInner={ItemInner}
ItemInner={ItemInner} onActivate={handleActivate}
onActivate={handleActivate} getEditOptions={getEditOptions}
getEditOptions={getEditOptions} />
/> </div>
</div>
</CreateSubEnvironmentContext.Provider>
)} )}
</aside> </aside>
); );
@@ -432,15 +384,6 @@ const treeAtom = atom<TreeNode<TreeModel> | null>((get) => {
return root; return root;
}); });
function findTreeNode(node: TreeNode<TreeModel>, id: string): TreeNode<TreeModel> | null {
if (node.item.id === id) return node;
for (const child of node.children ?? []) {
const found = findTreeNode(child, id);
if (found != null) return found;
}
return null;
}
function ItemLeftSlotInner({ item }: { item: TreeModel }) { function ItemLeftSlotInner({ item }: { item: TreeModel }) {
const { baseEnvironments } = useEnvironmentsBreakdown(); const { baseEnvironments } = useEnvironmentsBreakdown();
return baseEnvironments.length > 1 ? ( return baseEnvironments.length > 1 ? (
@@ -452,7 +395,6 @@ function ItemLeftSlotInner({ item }: { item: TreeModel }) {
function ItemRightSlot({ item }: { item: TreeModel }) { function ItemRightSlot({ item }: { item: TreeModel }) {
const { baseEnvironments } = useEnvironmentsBreakdown(); const { baseEnvironments } = useEnvironmentsBreakdown();
const handleCreateSubEnvironment = useContext(CreateSubEnvironmentContext);
return ( return (
<> <>
{item.model === "environment" && baseEnvironments.length <= 1 && isBaseEnvironment(item) && ( {item.model === "environment" && baseEnvironments.length <= 1 && isBaseEnvironment(item) && (
@@ -463,7 +405,7 @@ function ItemRightSlot({ item }: { item: TreeModel }) {
icon="plus_circle" icon="plus_circle"
className="opacity-50 hover:opacity-100" className="opacity-50 hover:opacity-100"
title="Add Sub-Environment" title="Add Sub-Environment"
onClick={handleCreateSubEnvironment} onClick={createSubEnvironment}
/> />
)} )}
</> </>
@@ -483,6 +425,13 @@ function ItemInner({ item }: { item: TreeModel }) {
); );
} }
async function createSubEnvironment() {
const { baseEnvironment } = jotaiStore.get(environmentsBreakdownAtom);
if (baseEnvironment == null) return;
const id = await createSubEnvironmentAndActivate.mutateAsync(baseEnvironment);
return id;
}
function getEditOptions(item: TreeModel) { function getEditOptions(item: TreeModel) {
const options: ReturnType<NonNullable<TreeProps<TreeModel>["getEditOptions"]>> = { const options: ReturnType<NonNullable<TreeProps<TreeModel>["getEditOptions"]>> = {
defaultValue: item.name, defaultValue: item.name,
@@ -15,6 +15,7 @@ import {
withEncryptionEnabled, withEncryptionEnabled,
} from "../lib/setupOrConfigureEncryption"; } from "../lib/setupOrConfigureEncryption";
import { DismissibleBanner } from "./core/DismissibleBanner"; import { DismissibleBanner } from "./core/DismissibleBanner";
import { FeatureHint } from "./core/FeatureHint";
import type { GenericCompletionConfig } from "./core/Editor/genericCompletion"; import type { GenericCompletionConfig } from "./core/Editor/genericCompletion";
import type { PairEditorHandle, PairWithId } from "./core/PairEditor"; import type { PairEditorHandle, PairWithId } from "./core/PairEditor";
import { ensurePairId } from "./core/PairEditor.util"; import { ensurePairId } from "./core/PairEditor.util";
@@ -152,6 +153,17 @@ export function EnvironmentEditor({ environment, hideName, className, setRef }:
This sharable environment contains plain-text secrets This sharable environment contains plain-text secrets
</DismissibleBanner> </DismissibleBanner>
)} )}
{!environment.public && !isEncryptionEnabled && hasSecretLookingVariable(environment) && (
<FeatureHint
id="encrypt-secrets"
className="mr-3"
docsUrl="https://yaak.app/docs/collaboration/secrets-encryption"
action={{ label: "Enable Encryption", onClick: setupOrConfigureEncryption }}
>
Some of these look like secrets. Encrypt them so the workspace is safe to sync to a
folder or share with a team.
</FeatureHint>
)}
</div> </div>
<PairOrBulkEditor <PairOrBulkEditor
setRef={setRef} setRef={setRef}
@@ -173,3 +185,9 @@ export function EnvironmentEditor({ environment, hideName, className, setRef }:
</div> </div>
); );
} }
const SECRET_NAME = /token|secret|password|passwd|api[_-]?key|private[_-]?key|credential/i;
function hasSecretLookingVariable(environment: Environment) {
return environment.variables.some((v) => v.value.trim() !== "" && SECRET_NAME.test(v.name));
}
@@ -1,4 +1,4 @@
import { IconTooltip } from "@yaakapp-internal/ui"; import { IconTooltip } from "./core/IconTooltip";
export function EnvironmentSharableTooltip() { export function EnvironmentSharableTooltip() {
return ( return (
+52 -11
View File
@@ -1,19 +1,60 @@
import { ErrorBoundary as BaseErrorBoundary } from "@yaakapp-internal/ui"; import { Banner, Button, InlineCode } from "@yaakapp-internal/ui";
import type { ReactNode } from "react"; import type { ErrorInfo, ReactNode } from "react";
import { useEffect } from "react"; import { Component, useEffect } from "react";
import { showDialog } from "../lib/dialog"; import { showDialog } from "../lib/dialog";
import RouteError from "./RouteError"; import RouteError from "./RouteError";
export function ErrorBoundary({ name, children }: { name: string; children: ReactNode }) { interface ErrorBoundaryProps {
return ( name: string;
<BaseErrorBoundary name={name} onShowError={showErrorDialog}> children: ReactNode;
{children}
</BaseErrorBoundary>
);
} }
export function showErrorDialog(error: unknown) { interface ErrorBoundaryState {
showDialog({ id: "error-boundary", render: () => <RouteError error={error} /> }); hasError: boolean;
error: Error | null;
}
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { hasError: true, error };
}
componentDidCatch(error: Error, info: ErrorInfo) {
console.warn("Error caught by ErrorBoundary:", error, info);
}
render() {
if (this.state.hasError) {
return (
<Banner color="danger" className="flex items-center gap-2 overflow-auto">
<div>
Error rendering <InlineCode>{this.props.name}</InlineCode> component
</div>
<Button
className="inline-flex"
variant="border"
color="danger"
size="2xs"
onClick={() => {
showDialog({
id: "error-boundary",
render: () => <RouteError error={this.state.error} />,
});
}}
>
Show
</Button>
</Banner>
);
}
return this.props.children;
}
} }
export function ErrorBoundaryTestThrow() { export function ErrorBoundaryTestThrow() {
@@ -1,18 +1,18 @@
import type { Workspace } from "@yaakapp-internal/models"; import type { Workspace } from "@yaakapp-internal/models";
import { workspacesAtom } from "@yaakapp-internal/models"; import { workspacesAtom } from "@yaakapp-internal/models";
import { VStack } from "@yaakapp-internal/ui"; import { HStack, VStack } from "@yaakapp-internal/ui";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { useCallback, useMemo, useState } from "react"; import { useCallback, useMemo, useState } from "react";
import slugify from "slugify"; import slugify from "slugify";
import { activeWorkspaceAtom } from "../hooks/useActiveWorkspace"; import { activeWorkspaceAtom } from "../hooks/useActiveWorkspace";
import { pluralizeCount } from "../lib/pluralize";
import { rpc } from "../lib/rpc"; import { rpc } from "../lib/rpc";
import { CommercialUseBanner } from "./CommercialUseBanner"; import { CommercialUseBanner } from "./CommercialUseBanner";
import { Button } from "./core/Button";
import { Checkbox } from "./core/Checkbox"; import { Checkbox } from "./core/Checkbox";
import { DetailsBanner } from "./core/DetailsBanner"; import { DetailsBanner } from "./core/DetailsBanner";
import { DialogFooter } from "./core/Dialog";
import { Link } from "./core/Link"; import { Link } from "./core/Link";
import { platform } from "@yaakapp-internal/platform"; import { platform } from "@yaakapp-internal/platform";
import { pluralizeCount } from "@yaakapp-internal/lib/pluralize";
interface Props { interface Props {
onHide: () => void; onHide: () => void;
@@ -65,30 +65,29 @@ function ExportDataDialogContent({
const ids = Object.keys(selectedWorkspaces).filter((k) => selectedWorkspaces[k]); const ids = Object.keys(selectedWorkspaces).filter((k) => selectedWorkspaces[k]);
const workspace = ids.length === 1 ? workspaces.find((w) => w.id === ids[0]) : undefined; const workspace = ids.length === 1 ? workspaces.find((w) => w.id === ids[0]) : undefined;
const slug = workspace ? slugify(workspace.name, { lower: true }) : "workspaces"; const slug = workspace ? slugify(workspace.name, { lower: true }) : "workspaces";
const document = await rpc<string>("cmd_export_data", { const exportPath = await platform.dialog.save({
workspaceIds: ids, title: "Export Data",
includePrivateEnvironments: includePrivateEnvironments, defaultPath: `yaak.${slug}.json`,
}); });
if (exportPath == null) {
const savedTo = await platform.files.save( return;
`yaak.${slug}.json`,
new TextEncoder().encode(document),
[{ name: "JSON", extensions: ["json"] }],
);
if (savedTo == null) {
return; // Cancelled
} }
await rpc("cmd_export_data", {
workspaceIds: ids,
exportPath,
includePrivateEnvironments: includePrivateEnvironments,
});
onHide(); onHide();
onSuccess(savedTo); onSuccess(exportPath);
}, [includePrivateEnvironments, onHide, onSuccess, selectedWorkspaces, workspaces]); }, [includePrivateEnvironments, onHide, onSuccess, selectedWorkspaces, workspaces]);
const allSelected = workspaces.every((w) => selectedWorkspaces[w.id]); const allSelected = workspaces.every((w) => selectedWorkspaces[w.id]);
const numSelected = Object.values(selectedWorkspaces).filter(Boolean).length; const numSelected = Object.values(selectedWorkspaces).filter(Boolean).length;
const noneSelected = numSelected === 0; const noneSelected = numSelected === 0;
return ( return (
<> <div className="h-full w-full grid grid-rows-[minmax(0,1fr)_auto] overflow-hidden rounded-b-lg">
<VStack space={3} className="pb-4"> <VStack space={3} className="overflow-auto px-5 pb-6">
<CommercialUseBanner source="data-export" title="Exporting work data?" /> <CommercialUseBanner source="data-export" title="Exporting work data?" />
<table className="w-full mb-auto min-w-full max-w-full divide-y divide-surface-highlight"> <table className="w-full mb-auto min-w-full max-w-full divide-y divide-surface-highlight">
@@ -141,22 +140,29 @@ function ExportDataDialogContent({
/> />
</DetailsBanner> </DetailsBanner>
</VStack> </VStack>
<DialogFooter <footer className="px-5 grid grid-cols-[1fr_auto] items-center bg-surface py-3 border-t border-border-subtle">
leftSlot={ <div>
<Link href="https://yaak.app/button/new" noUnderline className="text-text-subtlest"> <Link href="https://yaak.app/button/new" noUnderline className="text-text-subtlest">
Create Run Button Create Run Button
</Link> </Link>
} </div>
actions={[ <HStack space={2} justifyContent="end">
{ label: "Cancel", onClick: onHide }, <Button size="sm" className="focus" variant="border" onClick={onHide}>
{ Cancel
label: `Export ${pluralizeCount("Workspace", numSelected, { omitSingle: true, noneWord: "Nothing" })}`, </Button>
color: "primary", <Button
disabled: noneSelected, size="sm"
onClick: () => handleExport(), type="submit"
}, className="focus"
]} color="primary"
/> disabled={noneSelected}
</> onClick={() => handleExport()}
>
Export{" "}
{pluralizeCount("Workspace", numSelected, { omitSingle: true, noneWord: "Nothing" })}
</Button>
</HStack>
</footer>
</div>
); );
} }
+4 -9
View File
@@ -1,14 +1,6 @@
import type { Folder, GrpcRequest, HttpRequest, WebsocketRequest } from "@yaakapp-internal/models"; import type { Folder, GrpcRequest, HttpRequest, WebsocketRequest } from "@yaakapp-internal/models";
import { foldersAtom } from "@yaakapp-internal/models"; import { foldersAtom } from "@yaakapp-internal/models";
import { import { Heading, HStack, Icon, LoadingIcon } from "@yaakapp-internal/ui";
Heading,
HStack,
Icon,
LoadingIcon,
HttpResponseDurationTag,
HttpStatusTag,
SizeTag,
} from "@yaakapp-internal/ui";
import classNames from "classnames"; import classNames from "classnames";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import type { CSSProperties, ReactNode } from "react"; import type { CSSProperties, ReactNode } from "react";
@@ -21,8 +13,11 @@ import { showDialog } from "../lib/dialog";
import { resolvedModelName } from "../lib/resolvedModelName"; import { resolvedModelName } from "../lib/resolvedModelName";
import { router } from "../lib/router"; import { router } from "../lib/router";
import { Button } from "./core/Button"; import { Button } from "./core/Button";
import { HttpResponseDurationTag } from "./core/HttpResponseDurationTag";
import { HttpStatusTag } from "./core/HttpStatusTag";
import { IconButton } from "./core/IconButton"; import { IconButton } from "./core/IconButton";
import { Separator } from "./core/Separator"; import { Separator } from "./core/Separator";
import { SizeTag } from "./core/SizeTag";
import { HttpResponsePane } from "./HttpResponsePane"; import { HttpResponsePane } from "./HttpResponsePane";
interface Props { interface Props {
@@ -1,5 +1,5 @@
import { createWorkspaceModel, foldersAtom, patchModel } from "@yaakapp-internal/models"; import { createWorkspaceModel, foldersAtom, patchModel } from "@yaakapp-internal/models";
import { HStack, Icon, InlineCode, VStack, CountBadge } from "@yaakapp-internal/ui"; import { HStack, Icon, InlineCode, VStack } from "@yaakapp-internal/ui";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { Fragment, useMemo } from "react"; import { Fragment, useMemo } from "react";
import { useAuthTab } from "../hooks/useAuthTab"; import { useAuthTab } from "../hooks/useAuthTab";
@@ -11,6 +11,7 @@ import { deleteModelWithConfirm } from "../lib/deleteModelWithConfirm";
import { hideDialog } from "../lib/dialog"; import { hideDialog } from "../lib/dialog";
import { CopyIconButton } from "./CopyIconButton"; import { CopyIconButton } from "./CopyIconButton";
import { Button } from "./core/Button"; import { Button } from "./core/Button";
import { CountBadge } from "./core/CountBadge";
import { Input } from "./core/Input"; import { Input } from "./core/Input";
import { Link } from "./core/Link"; import { Link } from "./core/Link";
import type { TabItem } from "./core/Tabs/Tabs"; import type { TabItem } from "./core/Tabs/Tabs";
@@ -1,42 +1,32 @@
import type { HttpRequest } from "@yaakapp-internal/models";
import { useCallback, useMemo } from "react"; import { useCallback, useMemo } from "react";
import type { Pair, PairEditorProps } from "../pairs/PairEditor"; import type { Pair, PairEditorProps } from "./core/PairEditor";
import { PairEditor } from "../pairs/PairEditor"; import { PairEditor } from "./core/PairEditor";
import type { HttpFormFieldView, HttpRequestBodyView } from "./types";
type Props = { type Props = {
forceUpdateKey: string; forceUpdateKey: string;
/** The request's id, keeping each request's editor state apart */ request: HttpRequest;
requestId: string; onChange: (body: HttpRequest["body"]) => void;
form: HttpFormFieldView[] | undefined;
onChange?: (body: HttpRequestBodyView) => void;
/** Show the fields without a way to change them */
readOnly?: boolean;
}; };
export function FormMultipartEditor({ export function FormMultipartEditor({ request, forceUpdateKey, onChange }: Props) {
requestId,
form,
forceUpdateKey,
onChange,
readOnly,
}: Props) {
const pairs = useMemo<Pair[]>( const pairs = useMemo<Pair[]>(
() => () =>
(Array.isArray(form) ? form : []).map((p) => ({ (Array.isArray(request.body.form) ? request.body.form : []).map((p) => ({
enabled: p.enabled, enabled: p.enabled,
name: p.name, name: p.name,
value: (p.file ?? p.value) as string, value: p.file ?? p.value,
contentType: p.contentType, contentType: p.contentType,
filename: p.filename, filename: p.filename,
isFile: !!p.file, isFile: !!p.file,
id: p.id, id: p.id,
})), })),
[form], [request.body.form],
); );
const handleChange = useCallback<PairEditorProps["onChange"]>( const handleChange = useCallback<PairEditorProps["onChange"]>(
(pairs) => (pairs) =>
onChange?.({ onChange({
form: pairs.map((p) => ({ form: pairs.map((p) => ({
enabled: p.enabled, enabled: p.enabled,
name: p.name, name: p.name,
@@ -60,9 +50,8 @@ export function FormMultipartEditor({
allowMultilineValues allowMultilineValues
pairs={pairs} pairs={pairs}
onChange={handleChange} onChange={handleChange}
readOnly={readOnly}
forceUpdateKey={forceUpdateKey} forceUpdateKey={forceUpdateKey}
stateKey={`multipart.${requestId}`} stateKey={`multipart.${request.id}`}
/> />
); );
} }
@@ -0,0 +1,46 @@
import type { HttpRequest } from "@yaakapp-internal/models";
import { useCallback, useMemo } from "react";
import type { Pair, PairEditorProps } from "./core/PairEditor";
import { PairOrBulkEditor } from "./core/PairOrBulkEditor";
type Props = {
forceUpdateKey: string;
request: HttpRequest;
onChange: (headers: HttpRequest["body"]) => void;
};
export function FormUrlencodedEditor({ request, forceUpdateKey, onChange }: Props) {
const pairs = useMemo<Pair[]>(
() =>
(Array.isArray(request.body.form) ? request.body.form : []).map((p) => ({
enabled: !!p.enabled,
name: p.name || "",
value: p.value || "",
id: p.id,
})),
[request.body.form],
);
const handleChange = useCallback<PairEditorProps["onChange"]>(
(pairs) =>
onChange({ form: pairs.map((p) => ({ enabled: p.enabled, name: p.name, value: p.value })) }),
[onChange],
);
return (
<PairOrBulkEditor
allowMultilineValues
preferenceName="form_urlencoded"
valueAutocompleteFunctions
valueAutocompleteVariables
nameAutocompleteFunctions
nameAutocompleteVariables
namePlaceholder="entry_name"
valuePlaceholder="Value"
pairs={pairs}
onChange={handleChange}
forceUpdateKey={forceUpdateKey}
stateKey={`urlencoded.${request.id}`}
/>
);
}
@@ -1,4 +1,3 @@
import type { NavigateWorkspace } from "@yaakapp-internal/tauri-client";
import { activeRequestAtom } from "../hooks/useActiveRequest"; import { activeRequestAtom } from "../hooks/useActiveRequest";
import { useSubscribeActiveWorkspaceId } from "../hooks/useActiveWorkspace"; import { useSubscribeActiveWorkspaceId } from "../hooks/useActiveWorkspace";
import { useActiveWorkspaceChangedToast } from "../hooks/useActiveWorkspaceChangedToast"; import { useActiveWorkspaceChangedToast } from "../hooks/useActiveWorkspaceChangedToast";
@@ -6,13 +5,10 @@ import { useHotKey, useSubscribeHotKeys } from "../hooks/useHotKey";
import { useSubscribeHttpAuthentication } from "../hooks/useHttpAuthentication"; import { useSubscribeHttpAuthentication } from "../hooks/useHttpAuthentication";
import { useSyncFontSizeSetting } from "../hooks/useSyncFontSizeSetting"; import { useSyncFontSizeSetting } from "../hooks/useSyncFontSizeSetting";
import { useSyncWorkspaceChildModels } from "../hooks/useSyncWorkspaceChildModels"; import { useSyncWorkspaceChildModels } from "../hooks/useSyncWorkspaceChildModels";
import { usePlatformEvent } from "../hooks/usePlatformEvent";
import { useSyncZoomSetting } from "../hooks/useSyncZoomSetting"; import { useSyncZoomSetting } from "../hooks/useSyncZoomSetting";
import { useSubscribeTemplateFunctions } from "../hooks/useTemplateFunctions"; import { useSubscribeTemplateFunctions } from "../hooks/useTemplateFunctions";
import { fireAndForget } from "../lib/fireAndForget";
import { jotaiStore } from "../lib/jotai"; import { jotaiStore } from "../lib/jotai";
import { renameModelWithPrompt } from "../lib/renameModelWithPrompt"; import { renameModelWithPrompt } from "../lib/renameModelWithPrompt";
import { router } from "../lib/router";
export function GlobalHooks() { export function GlobalHooks() {
useSyncZoomSetting(); useSyncZoomSetting();
@@ -28,20 +24,6 @@ export function GlobalHooks() {
useActiveWorkspaceChangedToast(); useActiveWorkspaceChangedToast();
useSubscribeHotKeys(); useSubscribeHotKeys();
usePlatformEvent("show_home", () => {
fireAndForget(router.navigate({ to: "/", search: { home: true } }));
});
usePlatformEvent<NavigateWorkspace>("navigate_workspace", ({ workspaceId, environmentId }) => {
fireAndForget(
router.navigate({
to: "/workspaces/$workspaceId",
params: { workspaceId },
search: { environment_id: environmentId },
}),
);
});
useHotKey( useHotKey(
"request.rename", "request.rename",
async () => { async () => {
+1 -2
View File
@@ -20,13 +20,13 @@ import { showConfirm } from "../lib/confirm";
import { showDialog } from "../lib/dialog"; import { showDialog } from "../lib/dialog";
import type { JsonSchema } from "../lib/jsonSchemaExample"; import type { JsonSchema } from "../lib/jsonSchemaExample";
import { buildExampleFromSchema } from "../lib/jsonSchemaExample"; import { buildExampleFromSchema } from "../lib/jsonSchemaExample";
import { pluralizeCount } from "../lib/pluralize";
import { queryClient } from "../lib/queryClient"; import { queryClient } from "../lib/queryClient";
import { Button } from "./core/Button"; import { Button } from "./core/Button";
import { Dropdown } from "./core/Dropdown"; import { Dropdown } from "./core/Dropdown";
import type { EditorProps } from "./core/Editor/Editor"; import type { EditorProps } from "./core/Editor/Editor";
import { Editor } from "./core/Editor/LazyEditor"; import { Editor } from "./core/Editor/LazyEditor";
import { GrpcProtoSelectionDialog } from "./GrpcProtoSelectionDialog"; import { GrpcProtoSelectionDialog } from "./GrpcProtoSelectionDialog";
import { pluralizeCount } from "@yaakapp-internal/lib/pluralize";
type Props = Pick<EditorProps, "heightMode" | "onChange" | "className" | "forceUpdateKey"> & { type Props = Pick<EditorProps, "heightMode" | "onChange" | "className" | "forceUpdateKey"> & {
services: ReflectResponseService[] | null; services: ReflectResponseService[] | null;
@@ -239,7 +239,6 @@ export function GrpcEditor({
showDialog({ showDialog({
title: "Configure Schema", title: "Configure Schema",
size: "md", size: "md",
className: "h-[30rem]",
id: "grpc-configure-schema", id: "grpc-configure-schema",
render: ({ hide }) => <GrpcProtoSelectionDialog onDone={hide} />, render: ({ hide }) => <GrpcProtoSelectionDialog onDone={hide} />,
}); });
@@ -1,13 +1,13 @@
import type { GrpcRequest } from "@yaakapp-internal/models"; import type { GrpcRequest } from "@yaakapp-internal/models";
import { Banner, InlineCode, VStack } from "@yaakapp-internal/ui"; import { Banner, HStack, Icon, InlineCode, VStack } from "@yaakapp-internal/ui";
import { useActiveRequest } from "../hooks/useActiveRequest"; import { useActiveRequest } from "../hooks/useActiveRequest";
import { useGrpc } from "../hooks/useGrpc"; import { useGrpc } from "../hooks/useGrpc";
import { useGrpcProtoFiles } from "../hooks/useGrpcProtoFiles"; import { useGrpcProtoFiles } from "../hooks/useGrpcProtoFiles";
import { DialogFooter } from "./core/Dialog"; import { pluralizeCount } from "../lib/pluralize";
import { PathList } from "./core/PathList"; import { Button } from "./core/Button";
import { IconButton } from "./core/IconButton";
import { Link } from "./core/Link"; import { Link } from "./core/Link";
import { platform } from "@yaakapp-internal/platform"; import { platform } from "@yaakapp-internal/platform";
import { pluralizeCount } from "@yaakapp-internal/lib/pluralize";
interface Props { interface Props {
onDone: () => void; onDone: () => void;
@@ -20,10 +20,7 @@ export function GrpcProtoSelectionDialog(props: Props) {
return <GrpcProtoSelectionDialogWithRequest request={request} {...props} />; return <GrpcProtoSelectionDialogWithRequest request={request} {...props} />;
} }
function GrpcProtoSelectionDialogWithRequest({ function GrpcProtoSelectionDialogWithRequest({ request }: Props & { request: GrpcRequest }) {
request,
onDone,
}: Props & { request: GrpcRequest }) {
const protoFilesKv = useGrpcProtoFiles(request.id); const protoFilesKv = useGrpcProtoFiles(request.id);
const protoFiles = protoFilesKv.value ?? []; const protoFiles = protoFilesKv.value ?? [];
const grpc = useGrpc(request, null, protoFiles); const grpc = useGrpc(request, null, protoFiles);
@@ -41,8 +38,54 @@ function GrpcProtoSelectionDialogWithRequest({
} }
return ( return (
<> <VStack className="flex-col-reverse mb-3" space={3}>
<VStack space={5} className="pb-4"> {/* Buttons on top so they get focus first */}
<HStack space={2} justifyContent="start" className="flex-row-reverse mt-3">
<Button
color="primary"
variant="border"
onClick={async () => {
const selected = await platform.dialog.open({
title: "Select Proto Files",
multiple: true,
filters: [{ name: "Proto Files", extensions: ["proto"] }],
});
if (selected == null) return;
const newFiles = selected.filter((p) => !protoFiles.includes(p));
await protoFilesKv.set([...protoFiles, ...newFiles]);
await grpc.reflect.refetch();
}}
>
Add Proto Files
</Button>
<Button
variant="border"
color="primary"
onClick={async () => {
const selected = await platform.dialog.open({
title: "Select Proto Directory",
directory: true,
});
if (selected == null) return;
await protoFilesKv.set([...protoFiles.filter((f) => f !== selected), selected]);
await grpc.reflect.refetch();
}}
>
Add Import Folders
</Button>
<Button
isLoading={grpc.reflect.isFetching}
disabled={grpc.reflect.isFetching}
variant="border"
color="secondary"
onClick={() => grpc.reflect.refetch()}
>
Refresh Schema
</Button>
</HStack>
<VStack space={5}>
{reflectError && ( {reflectError && (
<Banner color="warning"> <Banner color="warning">
<h1 className="font-bold"> <h1 className="font-bold">
@@ -85,47 +128,46 @@ function GrpcProtoSelectionDialogWithRequest({
</Banner> </Banner>
)} )}
<PathList {protoFiles.length > 0 && (
items={protoFiles.map((path) => ({ <table className="w-full divide-y divide-surface-highlight">
path, <thead>
icon: path.endsWith(".proto") ? "file_code" : "folder_code", <tr>
}))} <th className="text-text-subtlest" colSpan={3}>
onRemove={async (path) => { Added File Paths
await protoFilesKv.set(protoFiles.filter((p) => p !== path)); </th>
await grpc.reflect.refetch(); </tr>
}} </thead>
addLabel="Add proto files or an import folder" <tbody className="divide-y divide-surface-highlight">
addItems={[ {protoFiles.map((f, i) => {
{ const parts = f.split("/");
label: "Proto files", // oxlint-disable-next-line no-array-index-key -- none
icon: "file_code", return (
onSelect: async () => { <tr key={f + i} className="group">
const selected = await platform.dialog.open({ <td>
title: "Select Proto Files", <Icon icon={f.endsWith(".proto") ? "file_code" : "folder_code"} />
multiple: true, </td>
filters: [{ name: "Proto Files", extensions: ["proto"] }], <td className="pl-1 font-mono text-sm" title={f}>
}); {parts.length > 3 && ".../"}
if (selected == null) return; {parts.slice(-3).join("/")}
const newFiles = selected.filter((p) => !protoFiles.includes(p)); </td>
await protoFilesKv.set([...protoFiles, ...newFiles]); <td className="w-0 py-0.5">
await grpc.reflect.refetch(); <IconButton
}, title="Remove file"
}, variant="border"
{ size="xs"
label: "Import folder", icon="trash"
icon: "folder_code", className="my-0.5 ml-auto opacity-50 transition-opacity group-hover:opacity-100"
onSelect: async () => { onClick={async () => {
const selected = await platform.dialog.open({ await protoFilesKv.set(protoFiles.filter((p) => p !== f));
title: "Select Proto Directory", }}
directory: true, />
}); </td>
if (selected == null) return; </tr>
await protoFilesKv.set([...protoFiles.filter((f) => f !== selected), selected]); );
await grpc.reflect.refetch(); })}
}, </tbody>
}, </table>
]} )}
/>
{reflectionUnimplemented && protoFiles.length === 0 && ( {reflectionUnimplemented && protoFiles.length === 0 && (
<Banner> <Banner>
<InlineCode>{request.url}</InlineCode> doesn&apos;t implement{" "} <InlineCode>{request.url}</InlineCode> doesn&apos;t implement{" "}
@@ -136,17 +178,6 @@ function GrpcProtoSelectionDialogWithRequest({
</Banner> </Banner>
)} )}
</VStack> </VStack>
<DialogFooter </VStack>
actions={[
{
label: "Refresh Schema",
isLoading: grpc.reflect.isFetching,
disabled: grpc.reflect.isFetching,
onClick: () => grpc.reflect.refetch(),
},
{ label: "Done", color: "primary", onClick: onDone },
]}
/>
</>
); );
} }
@@ -4,7 +4,7 @@ import {
patchModel, patchModel,
patchModelDebounced, patchModelDebounced,
} from "@yaakapp-internal/models"; } from "@yaakapp-internal/models";
import { HStack, Icon, useContainerSize, VStack, CountBadge } from "@yaakapp-internal/ui"; import { HStack, Icon, useContainerSize, VStack } from "@yaakapp-internal/ui";
import classNames from "classnames"; import classNames from "classnames";
import type { CSSProperties } from "react"; import type { CSSProperties } from "react";
import { useCallback, useMemo, useRef } from "react"; import { useCallback, useMemo, useRef } from "react";
@@ -15,6 +15,7 @@ import { useInheritedHeaders } from "../hooks/useInheritedHeaders";
import { useRequestUpdateKey } from "../hooks/useRequestUpdateKey"; import { useRequestUpdateKey } from "../hooks/useRequestUpdateKey";
import { resolvedModelName } from "../lib/resolvedModelName"; import { resolvedModelName } from "../lib/resolvedModelName";
import { Button } from "./core/Button"; import { Button } from "./core/Button";
import { CountBadge } from "./core/CountBadge";
import { IconButton } from "./core/IconButton"; import { IconButton } from "./core/IconButton";
import { PlainInput } from "./core/PlainInput"; import { PlainInput } from "./core/PlainInput";
import { RadioDropdown } from "./core/RadioDropdown"; import { RadioDropdown } from "./core/RadioDropdown";
@@ -1,13 +1,5 @@
import type { GrpcEvent, GrpcRequest } from "@yaakapp-internal/models"; import type { GrpcEvent, GrpcRequest } from "@yaakapp-internal/models";
import { import { HStack, Icon, type IconProps, LoadingIcon, VStack } from "@yaakapp-internal/ui";
HStack,
Icon,
type IconProps,
LoadingIcon,
VStack,
useStateWithDeps,
KeyValueRows,
} from "@yaakapp-internal/ui";
import { useAtomValue, useSetAtom } from "jotai"; import { useAtomValue, useSetAtom } from "jotai";
import type { CSSProperties } from "react"; import type { CSSProperties } from "react";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
@@ -17,12 +9,13 @@ import {
pinnedGrpcConnectionIdAtom, pinnedGrpcConnectionIdAtom,
useGrpcEvents, useGrpcEvents,
} from "../hooks/usePinnedGrpcConnection"; } from "../hooks/usePinnedGrpcConnection";
import { useStateWithDeps } from "../hooks/useStateWithDeps";
import { Button } from "./core/Button"; import { Button } from "./core/Button";
import { Editor } from "./core/Editor/LazyEditor"; import { Editor } from "./core/Editor/LazyEditor";
import { EventDetailHeader, EventViewer } from "./core/EventViewer"; import { EventDetailHeader, EventViewer } from "./core/EventViewer";
import { EventViewerRow } from "./core/EventViewerRow"; import { EventViewerRow } from "./core/EventViewerRow";
import { HotkeyList } from "./core/HotkeyList"; import { HotkeyList } from "./core/HotkeyList";
import { KeyValueRow } from "./core/KeyValueRow"; import { KeyValueRow, KeyValueRows } from "./core/KeyValueRow";
import { EmptyStateText } from "./EmptyStateText"; import { EmptyStateText } from "./EmptyStateText";
import { ErrorBoundary } from "./ErrorBoundary"; import { ErrorBoundary } from "./ErrorBoundary";
import { RecentGrpcConnectionsDropdown } from "./RecentGrpcConnectionsDropdown"; import { RecentGrpcConnectionsDropdown } from "./RecentGrpcConnectionsDropdown";
+190 -1
View File
@@ -1 +1,190 @@
export { HeadersEditor } from "@yaakapp-internal/ui"; import type { HttpRequestHeader } from "@yaakapp-internal/models";
import { HStack } from "@yaakapp-internal/ui";
import { acceptLanguages } from "../lib/data/acceptLanguages";
import { cacheControlDirectives } from "../lib/data/cacheControl";
import { charsets } from "../lib/data/charsets";
import { connections } from "../lib/data/connections";
import { encodings } from "../lib/data/encodings";
import type { HeaderValuePreset } from "../lib/data/headerValuePresets";
import { headerNames } from "../lib/data/headerNames";
import { mimeTypes } from "../lib/data/mimetypes";
import { userAgents } from "../lib/data/userAgents";
import { CountBadge } from "./core/CountBadge";
import { DetailsBanner } from "./core/DetailsBanner";
import type { GenericCompletion, GenericCompletionConfig } from "./core/Editor/genericCompletion";
import type { InputProps } from "./core/Input";
import type { Pair, PairEditorProps } from "./core/PairEditor";
import { PairEditorRow } from "./core/PairEditor";
import { ensurePairId } from "./core/PairEditor.util";
import { PairOrBulkEditor } from "./core/PairOrBulkEditor";
type Props = {
forceUpdateKey: string;
headers: HttpRequestHeader[];
inheritedHeaders?: HttpRequestHeader[];
inheritedHeadersLabel?: string;
stateKey: string;
onChange: (headers: HttpRequestHeader[]) => void;
label?: string;
};
export function HeadersEditor({
stateKey,
headers,
inheritedHeaders,
inheritedHeadersLabel = "Inherited",
onChange,
forceUpdateKey,
}: Props) {
// Get header names defined at current level (case-insensitive)
const currentHeaderNames = new Set(
headers.filter((h) => h.name).map((h) => h.name.toLowerCase()),
);
// Filter inherited headers: must be enabled, have content, and not be overridden by current level
const validInheritedHeaders =
inheritedHeaders?.filter(
(pair) =>
pair.enabled &&
(pair.name || pair.value) &&
!currentHeaderNames.has(pair.name.toLowerCase()),
) ?? [];
const hasInheritedHeaders = validInheritedHeaders.length > 0;
return (
<div
className={
hasInheritedHeaders
? "@container w-full h-full grid grid-rows-[auto_minmax(0,1fr)] gap-y-1.5"
: "@container w-full h-full"
}
>
{hasInheritedHeaders && (
<DetailsBanner
color="secondary"
className="text-sm"
summary={
<HStack>
{inheritedHeadersLabel} <CountBadge count={validInheritedHeaders.length} />
</HStack>
}
>
<div className="pb-2">
{validInheritedHeaders?.map((pair, i) => (
<PairEditorRow
key={`${pair.id}.${i}`}
index={i}
disabled
disableDrag
className="py-1"
pair={ensurePairId(pair)}
stateKey={null}
nameAutocompleteFunctions
nameAutocompleteVariables
valueAutocompleteFunctions
valueAutocompleteVariables
/>
))}
</div>
</DetailsBanner>
)}
<PairOrBulkEditor
forceUpdateKey={forceUpdateKey}
nameAutocomplete={nameAutocomplete}
nameAutocompleteFunctions
nameAutocompleteVariables
namePlaceholder="Header-Name"
nameValidate={validateHttpHeader}
onChange={onChange}
pairs={headers}
preferenceName="headers"
stateKey={stateKey}
valueType={valueType}
valueAutocomplete={valueAutocomplete}
valueAutocompleteFunctions
valueAutocompleteVariables
/>
</div>
);
}
const MIN_MATCH = 3;
const headerOptionsMap: Record<string, HeaderValuePreset[]> = {
"content-type": mimeTypes,
accept: ["*/*", ...mimeTypes],
"accept-encoding": encodings,
"content-encoding": encodings,
connection: connections,
"accept-charset": charsets,
"accept-language": acceptLanguages,
"cache-control": cacheControlDirectives,
"user-agent": userAgents,
pragma: ["no-cache"],
te: ["trailers", "compress", "deflate", "gzip"],
dnt: ["1", "0"],
"upgrade-insecure-requests": ["1"],
"x-requested-with": ["XMLHttpRequest"],
};
const valueType = (pair: Pair): InputProps["type"] => {
const name = pair.name.toLowerCase().trim();
if (
name.includes("authorization") ||
name.includes("api-key") ||
name.includes("access-token") ||
name.includes("auth") ||
name.includes("secret") ||
name.includes("token") ||
name === "cookie" ||
name === "set-cookie"
) {
return "password";
}
return "text";
};
const valueAutocomplete = (headerName: string): GenericCompletionConfig | undefined => {
const name = headerName.toLowerCase().trim();
const options: GenericCompletion[] =
headerOptionsMap[name]?.map((o) =>
typeof o === "string"
? {
label: o,
type: "constant",
boost: 1, // Put above other completions
}
: {
// Show the short label but insert the full value (e.g. User-Agent)
label: o.label,
apply: o.value,
type: "constant",
boost: 1,
},
) ?? [];
return { minMatch: MIN_MATCH, options };
};
const nameAutocomplete: PairEditorProps["nameAutocomplete"] = {
minMatch: MIN_MATCH,
options: headerNames.map((t) =>
typeof t === "string"
? {
label: t,
type: "constant",
boost: 1, // Put above other completions
}
: {
...t,
boost: 1, // Put above other completions
},
),
};
const validateHttpHeader = (v: string) => {
if (v === "") {
return true;
}
// Template strings are not allowed so we replace them with a valid example string
const withoutTemplateStrings = v.replace(/\$\{\[\s*[^\]\s]+\s*]}/gi, "123");
return withoutTemplateStrings.match(/^[a-zA-Z0-9-_]+$/) !== null;
};
@@ -6,7 +6,7 @@ import type {
Workspace, Workspace,
} from "@yaakapp-internal/models"; } from "@yaakapp-internal/models";
import { patchModel } from "@yaakapp-internal/models"; import { patchModel } from "@yaakapp-internal/models";
import { HStack, Icon, InlineCode, SegmentedControl } from "@yaakapp-internal/ui"; import { HStack, Icon, InlineCode } from "@yaakapp-internal/ui";
import { useCallback } from "react"; import { useCallback } from "react";
import { openFolderSettings } from "../commands/openFolderSettings"; import { openFolderSettings } from "../commands/openFolderSettings";
import { openWorkspaceSettings } from "../commands/openWorkspaceSettings"; import { openWorkspaceSettings } from "../commands/openWorkspaceSettings";
@@ -21,6 +21,7 @@ import { IconButton } from "./core/IconButton";
import { Input, type InputProps } from "./core/Input"; import { Input, type InputProps } from "./core/Input";
import { Link } from "./core/Link"; import { Link } from "./core/Link";
import { RadioDropdown } from "./core/RadioDropdown"; import { RadioDropdown } from "./core/RadioDropdown";
import { SegmentedControl } from "./core/SegmentedControl";
import { DynamicForm } from "./DynamicForm"; import { DynamicForm } from "./DynamicForm";
import { EmptyStateText } from "./EmptyStateText"; import { EmptyStateText } from "./EmptyStateText";
@@ -177,6 +178,7 @@ export function HttpAuthenticationEditor({ model }: Props) {
disabled={model.authentication.disabled === true} disabled={model.authentication.disabled === true}
autocompleteVariables autocompleteVariables
autocompleteFunctions autocompleteFunctions
suggestVariables
stateKey={`auth.${model.id}.${model.authenticationType}`} stateKey={`auth.${model.id}.${model.authenticationType}`}
inputs={authConfig.data?.args ?? []} inputs={authConfig.data?.args ?? []}
data={model.authentication} data={model.authentication}
+200 -165
View File
@@ -1,16 +1,9 @@
import type { HttpRequest } from "@yaakapp-internal/models"; import type { HttpRequest } from "@yaakapp-internal/models";
import { getModel, patchModel, patchModelDebounced } from "@yaakapp-internal/models"; import { getModel, patchModel, patchModelDebounced } from "@yaakapp-internal/models";
import type { GenericCompletionOption } from "@yaakapp-internal/plugins"; import type { GenericCompletionOption } from "@yaakapp-internal/plugins";
import { import classNames from "classnames";
CountBadge,
type EditablePair,
type ExtraPaneTab,
HttpRequestPaneView,
InlineCode,
languageFromContentType,
} from "@yaakapp-internal/ui";
import { atom, useAtomValue } from "jotai"; import { atom, useAtomValue } from "jotai";
import type { CSSProperties, ReactNode } from "react"; import type { CSSProperties } from "react";
import { lazy, Suspense, useCallback, useMemo, useRef, useState } from "react"; import { lazy, Suspense, useCallback, useMemo, useRef, useState } from "react";
import { importCurl, looksLikeCurl } from "../commands/importCurl"; import { importCurl, looksLikeCurl } from "../commands/importCurl";
import { allRequestUrlsAtom } from "../hooks/useAllRequests"; import { allRequestUrlsAtom } from "../hooks/useAllRequests";
@@ -22,8 +15,10 @@ import { usePinnedHttpResponse } from "../hooks/usePinnedHttpResponse";
import { useRequestEditor, useRequestEditorEvent } from "../hooks/useRequestEditor"; import { useRequestEditor, useRequestEditorEvent } from "../hooks/useRequestEditor";
import { useRequestUpdateKey } from "../hooks/useRequestUpdateKey"; import { useRequestUpdateKey } from "../hooks/useRequestUpdateKey";
import { useSendAnyHttpRequest } from "../hooks/useSendAnyHttpRequest"; import { useSendAnyHttpRequest } from "../hooks/useSendAnyHttpRequest";
import { fireAndForget } from "../lib/fireAndForget"; import { languageFromContentType } from "../lib/contentType";
import { httpRequestToView } from "../lib/httpViews"; import { generateId } from "../lib/generateId";
import { derivePathPlaceholderPairs, renamePathPlaceholder } from "../lib/pathPlaceholders";
import { convertRequestBody } from "../lib/requestBodyConversion";
import { import {
BODY_TYPE_BINARY, BODY_TYPE_BINARY,
BODY_TYPE_FORM_MULTIPART, BODY_TYPE_FORM_MULTIPART,
@@ -35,24 +30,31 @@ import {
BODY_TYPE_XML, BODY_TYPE_XML,
getContentTypeFromHeaders, getContentTypeFromHeaders,
} from "../lib/model_util"; } from "../lib/model_util";
import { derivePathPlaceholderPairs, renamePathPlaceholder } from "../lib/pathPlaceholders";
import { prepareImportQuerystring } from "../lib/prepareImportQuerystring"; import { prepareImportQuerystring } from "../lib/prepareImportQuerystring";
import { convertRequestBody } from "../lib/requestBodyConversion";
import { resolvedModelName } from "../lib/resolvedModelName"; import { resolvedModelName } from "../lib/resolvedModelName";
import { showToast } from "../lib/toast"; import { showToast } from "../lib/toast";
import { BinaryFileEditor } from "./BinaryFileEditor"; import { BinaryFileEditor } from "./BinaryFileEditor";
import { ConfirmLargeRequestBody } from "./ConfirmLargeRequestBody"; import { ConfirmLargeRequestBody } from "./ConfirmLargeRequestBody";
import { CountBadge } from "./core/CountBadge";
import type { GenericCompletionConfig } from "./core/Editor/genericCompletion"; import type { GenericCompletionConfig } from "./core/Editor/genericCompletion";
import { getUrlCompletionConfig } from "./core/Editor/url/completion"; import { getUrlCompletionConfig } from "./core/Editor/url/completion";
import { Editor } from "./core/Editor/LazyEditor";
import { InlineCode } from "@yaakapp-internal/ui";
import { PlainInput } from "./core/PlainInput"; import { PlainInput } from "./core/PlainInput";
import type { TabItem, TabsRef } from "./core/Tabs/Tabs"; import type { TabItem, TabsRef } from "./core/Tabs/Tabs";
import { setActiveTab } from "./core/Tabs/Tabs"; import { setActiveTab, TabContent, Tabs } from "./core/Tabs/Tabs";
import { EmptyStateText } from "./EmptyStateText";
import { FormMultipartEditor } from "./FormMultipartEditor";
import { FormUrlencodedEditor } from "./FormUrlencodedEditor";
import { HeadersEditor } from "./HeadersEditor";
import { HttpAuthenticationEditor } from "./HttpAuthenticationEditor"; import { HttpAuthenticationEditor } from "./HttpAuthenticationEditor";
import { JsonBodyEditor } from "./JsonBodyEditor";
import { MarkdownEditor } from "./MarkdownEditor"; import { MarkdownEditor } from "./MarkdownEditor";
import { countOverriddenSettings, ModelSettingsEditor } from "./ModelSettingsEditor";
import { RequestMethodDropdown } from "./RequestMethodDropdown"; import { RequestMethodDropdown } from "./RequestMethodDropdown";
import { countOverriddenSettings, ModelSettingsEditor } from "./ModelSettingsEditor";
import { SharedOriginHint } from "./hints/SharedOriginHint";
import { UrlBar } from "./UrlBar";
import { UrlParametersEditor } from "./UrlParameterEditor"; import { UrlParametersEditor } from "./UrlParameterEditor";
import { generateId } from "@yaakapp-internal/lib/generateId";
const GraphQLEditor = lazy(() => const GraphQLEditor = lazy(() =>
import("./graphql/GraphQLEditor").then((m) => ({ default: m.GraphQLEditor })), import("./graphql/GraphQLEditor").then((m) => ({ default: m.GraphQLEditor })),
@@ -166,9 +168,9 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
const hasDescription = activeRequest.description.trim().length > 0; const hasDescription = activeRequest.description.trim().length > 0;
const bodyTab = useMemo<TabItem>( const tabs = useMemo<TabItem[]>(
() => () => [
({ {
value: TAB_BODY, value: TAB_BODY,
rightSlot: numParams > 0 ? <CountBadge count={numParams} /> : null, rightSlot: numParams > 0 ? <CountBadge count={numParams} /> : null,
options: { options: {
@@ -245,8 +247,36 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
} }
}, },
}, },
}) satisfies TabItem, },
[activeRequest, contentType, handleContentTypeChange, numParams], {
value: TAB_PARAMS,
rightSlot: <CountBadge count={urlParameterPairs.length} />,
label: "Params",
},
...headersTab,
...authTab,
{
value: TAB_SETTINGS,
label: "Settings",
rightSlot: <CountBadge count={numSettingsOverrides} />,
},
{
value: TAB_DESCRIPTION,
label: "Info",
rightSlot: hasDescription && <CountBadge count={true} />,
},
],
[
activeRequest,
authTab,
contentType,
handleContentTypeChange,
hasDescription,
headersTab,
numParams,
numSettingsOverrides,
urlParameterPairs.length,
],
); );
const { mutate: sendRequest } = useSendAnyHttpRequest(); const { mutate: sendRequest } = useSendAnyHttpRequest();
@@ -308,152 +338,157 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
[activeRequest], [activeRequest],
); );
const handleJsonOrBodyTextChange = useCallback(
(text: string, bodyType: string | null) => {
// JSON writes at once, as its editor always has; other text debounces
if (bodyType === BODY_TYPE_JSON) {
return patchModel(activeRequest, { body: { ...activeRequest.body, text } });
}
return handleBodyTextChange(text);
},
[activeRequest, handleBodyTextChange],
);
const handleSendJsonCommentsChange = useCallback(
(sendJsonComments: boolean) => {
const newBody = { ...activeRequest.body };
if (sendJsonComments) {
newBody.sendJsonComments = true;
} else {
delete newBody.sendJsonComments;
}
fireAndForget(patchModel(activeRequest, { body: newBody }));
},
[activeRequest],
);
const requestView = useMemo(() => httpRequestToView(activeRequest), [activeRequest]);
const extraTabs = useMemo<ExtraPaneTab[]>(
() => [
{
tab: {
value: TAB_SETTINGS,
label: "Settings",
rightSlot: <CountBadge count={numSettingsOverrides} />,
},
content: <ModelSettingsEditor model={activeRequest} />,
},
{
tab: {
value: TAB_DESCRIPTION,
label: "Info",
rightSlot: hasDescription && <CountBadge count={true} />,
},
content: (
<div className="grid grid-rows-[auto_minmax(0,1fr)] h-full">
<PlainInput
label="Request Name"
hideLabel
forceUpdateKey={updateKey}
defaultValue={activeRequest.name}
className="font-sans text-xl! px-0!"
containerClassName="border-0"
placeholder={resolvedModelName(activeRequest)}
onChange={(name) => patchModel(activeRequest, { name })}
/>
<MarkdownEditor
name="request-description"
placeholder="Request description"
defaultValue={activeRequest.description}
stateKey={`description.${activeRequest.id}`}
forceUpdateKey={updateKey}
onChange={(description) => patchModel(activeRequest, { description })}
/>
</div>
),
},
],
[activeRequest, hasDescription, numSettingsOverrides, updateKey],
);
const renderBody = useCallback(
(sharedEditor: ReactNode) => (
<ConfirmLargeRequestBody request={activeRequest}>
{activeRequest.bodyType === BODY_TYPE_GRAPHQL ? (
<Suspense>
<GraphQLEditor
forceUpdateKey={forceUpdateKey}
baseRequest={activeRequest}
request={activeRequest}
onChange={handleBodyChange}
/>
</Suspense>
) : activeRequest.bodyType === BODY_TYPE_BINARY ? (
<BinaryFileEditor
requestId={activeRequest.id}
contentType={contentType}
body={activeRequest.body}
onChange={(body) => patchModelDebounced(activeRequest, { body })}
onChangeContentType={handleContentTypeChange}
/>
) : (
sharedEditor
)}
</ConfirmLargeRequestBody>
),
[activeRequest, contentType, forceUpdateKey, handleBodyChange, handleContentTypeChange],
);
const renderUrlParameters = useCallback(
(pairs: EditablePair[]) => (
<UrlParametersEditor
stateKey={`params.${activeRequest.id}`}
forceUpdateKey={forceUpdateKey + urlParametersKey}
pairs={pairs}
onChange={(urlParameters) => patchModelDebounced(activeRequest, { urlParameters })}
/>
),
[activeRequest, forceUpdateKey, urlParametersKey],
);
return ( return (
<HttpRequestPaneView <div
editable
style={style} style={style}
className={className} className={classNames(className, "h-full grid grid-rows-[auto_minmax(0,1fr)] grid-cols-1")}
fullHeight={fullHeight} >
request={requestView} {activeRequest && (
tabsRef={tabsRef} <>
tabsStorageKey={TABS_STORAGE_KEY} <div>
forceUpdateKey={forceUpdateKey} <UrlBar
urlBarKey={forceUpdateKey + urlKey} stateKey={`url.${activeRequest.id}`}
urlForceUpdateKey={updateKey} key={forceUpdateKey + urlKey}
urlAutocomplete={autocomplete} url={activeRequest.url}
onUrlChange={handleUrlChange} placeholder="https://example.com"
onUrlPasteOverwrite={handlePaste} onPasteOverwrite={handlePaste}
onSend={handleSend} autocomplete={autocomplete}
onCancel={cancelResponse} onSend={handleSend}
isSending={activeResponse != null && activeResponse.state !== "closed"} onCancel={cancelResponse}
sendHotkeyAction="request.send" onUrlChange={handleUrlChange}
focusHotkeyAction="url_bar.focus" leftSlot={
methodSlot={<RequestMethodDropdown request={activeRequest} className="ml-0.5 h-full!" />} <div className="py-0.5">
bodyTab={bodyTab} <RequestMethodDropdown request={activeRequest} className="ml-0.5 h-full!" />
renderBody={renderBody} </div>
onBodyChange={handleBodyChange} }
onBodyTextChange={handleJsonOrBodyTextChange} forceUpdateKey={updateKey}
onSendJsonCommentsChange={handleSendJsonCommentsChange} isLoading={activeResponse != null && activeResponse.state !== "closed"}
jsonNoticeStorageKey={activeRequest.workspaceId} />
urlParameterPairs={urlParameterPairs} <SharedOriginHint />
renderUrlParameters={renderUrlParameters} </div>
headersTabs={headersTab} <Tabs
inheritedHeaders={inheritedHeaders} ref={tabsRef}
headersForceUpdateKey={`${forceUpdateHeaderEditorKey}::${forceUpdateKey}`} label="Request"
onHeadersChange={(headers) => patchModelDebounced(activeRequest, { headers })} tabs={tabs}
authTabs={authTab} tabListClassName="mt-1 -mb-1.5"
authContent={<HttpAuthenticationEditor model={activeRequest} />} storageKey={TABS_STORAGE_KEY}
extraTabs={extraTabs} activeTabKey={activeRequestId}
/> >
<TabContent value={TAB_AUTH}>
<HttpAuthenticationEditor model={activeRequest} />
</TabContent>
<TabContent value={TAB_HEADERS}>
<HeadersEditor
inheritedHeaders={inheritedHeaders}
forceUpdateKey={`${forceUpdateHeaderEditorKey}::${forceUpdateKey}`}
headers={activeRequest.headers}
stateKey={`headers.${activeRequest.id}`}
onChange={(headers) => patchModelDebounced(activeRequest, { headers })}
/>
</TabContent>
<TabContent value={TAB_PARAMS}>
<UrlParametersEditor
stateKey={`params.${activeRequest.id}`}
forceUpdateKey={forceUpdateKey + urlParametersKey}
pairs={urlParameterPairs}
onChange={(urlParameters) => patchModelDebounced(activeRequest, { urlParameters })}
/>
</TabContent>
<TabContent value={TAB_SETTINGS}>
<ModelSettingsEditor model={activeRequest} />
</TabContent>
<TabContent value={TAB_BODY}>
<ConfirmLargeRequestBody request={activeRequest}>
{activeRequest.bodyType === BODY_TYPE_JSON ? (
<JsonBodyEditor
forceUpdateKey={forceUpdateKey}
heightMode={fullHeight ? "full" : "auto"}
request={activeRequest}
/>
) : activeRequest.bodyType === BODY_TYPE_XML ? (
<Editor
forceUpdateKey={forceUpdateKey}
autocompleteFunctions
autocompleteVariables
placeholder="..."
heightMode={fullHeight ? "full" : "auto"}
defaultValue={`${activeRequest.body?.text ?? ""}`}
language="xml"
onChange={handleBodyTextChange}
stateKey={`xml.${activeRequest.id}`}
/>
) : activeRequest.bodyType === BODY_TYPE_GRAPHQL ? (
<Suspense>
<GraphQLEditor
forceUpdateKey={forceUpdateKey}
baseRequest={activeRequest}
request={activeRequest}
onChange={handleBodyChange}
/>
</Suspense>
) : activeRequest.bodyType === BODY_TYPE_FORM_URLENCODED ? (
<FormUrlencodedEditor
forceUpdateKey={forceUpdateKey}
request={activeRequest}
onChange={handleBodyChange}
/>
) : activeRequest.bodyType === BODY_TYPE_FORM_MULTIPART ? (
<FormMultipartEditor
forceUpdateKey={forceUpdateKey}
request={activeRequest}
onChange={handleBodyChange}
/>
) : activeRequest.bodyType === BODY_TYPE_BINARY ? (
<BinaryFileEditor
requestId={activeRequest.id}
contentType={contentType}
body={activeRequest.body}
onChange={(body) => patchModelDebounced(activeRequest, { body })}
onChangeContentType={handleContentTypeChange}
/>
) : typeof activeRequest.bodyType === "string" ? (
<Editor
forceUpdateKey={forceUpdateKey}
autocompleteFunctions
autocompleteVariables
language={languageFromContentType(contentType)}
placeholder="..."
heightMode={fullHeight ? "full" : "auto"}
defaultValue={`${activeRequest.body?.text ?? ""}`}
onChange={handleBodyTextChange}
stateKey={`other.${activeRequest.id}`}
/>
) : (
<EmptyStateText>No Body</EmptyStateText>
)}
</ConfirmLargeRequestBody>
</TabContent>
<TabContent value={TAB_DESCRIPTION}>
<div className="grid grid-rows-[auto_minmax(0,1fr)] h-full">
<PlainInput
label="Request Name"
hideLabel
forceUpdateKey={updateKey}
defaultValue={activeRequest.name}
className="font-sans text-xl! px-0!"
containerClassName="border-0"
placeholder={resolvedModelName(activeRequest)}
onChange={(name) => patchModel(activeRequest, { name })}
/>
<MarkdownEditor
name="request-description"
placeholder="Request description"
defaultValue={activeRequest.description}
stateKey={`description.${activeRequest.id}`}
forceUpdateKey={updateKey}
onChange={(description) => patchModel(activeRequest, { description })}
/>
</div>
</TabContent>
</Tabs>
</>
)}
</div>
); );
} }
+356 -181
View File
@@ -1,36 +1,51 @@
import type { HttpResponse, HttpResponseEvent } from "@yaakapp-internal/models"; import type { HttpResponse, HttpResponseEvent } from "@yaakapp-internal/models";
import { import { Banner, HStack, Icon, LoadingIcon, VStack } from "@yaakapp-internal/ui";
CountBadge, import classNames from "classnames";
type ExtraPaneTab, import type { ComponentType, CSSProperties } from "react";
type HostBodyViewerArgs, import { lazy, Suspense, useMemo } from "react";
HttpResponsePaneView,
Icon,
type ResponseTextViewerExtras,
type TextFilterApi,
Tooltip,
VStack,
} from "@yaakapp-internal/ui";
import type { CSSProperties } from "react";
import { useCallback, useMemo } from "react";
import { useCancelHttpResponse } from "../hooks/useCancelHttpResponse"; import { useCancelHttpResponse } from "../hooks/useCancelHttpResponse";
import { useCopyHttpResponse } from "../hooks/useCopyHttpResponse"; import { useCopyHttpResponse } from "../hooks/useCopyHttpResponse";
import { useRequestBodyLoader, useResponseBodyLoader } from "../hooks/useHttpBodyLoaders";
import { useHttpResponseEvents } from "../hooks/useHttpResponseEvents"; import { useHttpResponseEvents } from "../hooks/useHttpResponseEvents";
import { usePinnedHttpResponse } from "../hooks/usePinnedHttpResponse"; import { usePinnedHttpResponse } from "../hooks/usePinnedHttpResponse";
import { useRecentFilters } from "../hooks/useRecentFilters"; import { useResponseBodyBytes, useResponseBodyText } from "../hooks/useResponseBodyText";
import { useResponseBodyUrl } from "../hooks/useResponseBodyUrl";
import { useResponseViewMode } from "../hooks/useResponseViewMode"; import { useResponseViewMode } from "../hooks/useResponseViewMode";
import { useSaveResponse } from "../hooks/useSaveResponse"; import { useSaveResponse } from "../hooks/useSaveResponse";
import { useTimelineViewMode } from "../hooks/useTimelineViewMode"; import { useTimelineViewMode } from "../hooks/useTimelineViewMode";
import { httpResponseToView } from "../lib/httpViews"; import { getMimeTypeFromContentType } from "../lib/contentType";
import { getCookieCounts } from "../lib/model_util"; import { getContentTypeFromHeaders, getCookieCounts } from "../lib/model_util";
import { CopyButton } from "./CopyButton"; import { ConfirmLargeResponse } from "./ConfirmLargeResponse";
import { ConfirmLargeResponseRequest } from "./ConfirmLargeResponseRequest";
import { Button } from "./core/Button";
import { CountBadge } from "./core/CountBadge";
import { HotkeyList } from "./core/HotkeyList"; import { HotkeyList } from "./core/HotkeyList";
import { IconButton } from "./core/IconButton"; import { HttpResponseDurationTag } from "./core/HttpResponseDurationTag";
import { HttpStatusTag } from "./core/HttpStatusTag";
import { PillButton } from "./core/PillButton"; import { PillButton } from "./core/PillButton";
import { SizeTag } from "./core/SizeTag";
import type { TabItem } from "./core/Tabs/Tabs";
import { TabContent, Tabs } from "./core/Tabs/Tabs";
import { Tooltip } from "./core/Tooltip";
import { EmptyStateText } from "./EmptyStateText";
import { ErrorBoundary } from "./ErrorBoundary";
import { ChainingHint } from "./hints/ChainingHint";
import { HttpResponseTimeline } from "./HttpResponseTimeline"; import { HttpResponseTimeline } from "./HttpResponseTimeline";
import { RecentHttpResponsesDropdown } from "./RecentHttpResponsesDropdown"; import { RecentHttpResponsesDropdown } from "./RecentHttpResponsesDropdown";
import { RequestBodyViewer } from "./RequestBodyViewer";
import { ResponseCookies } from "./ResponseCookies";
import { ResponseHeaders } from "./ResponseHeaders";
import { AudioViewer } from "./responseViewers/AudioViewer";
import { CsvViewer } from "./responseViewers/CsvViewer";
import { EventStreamViewer } from "./responseViewers/EventStreamViewer"; import { EventStreamViewer } from "./responseViewers/EventStreamViewer";
import { RecentFiltersDropdown } from "./responseViewers/RecentFiltersDropdown"; import { HTMLOrTextViewer } from "./responseViewers/HTMLOrTextViewer";
import { ImageViewer } from "./responseViewers/ImageViewer";
import { MultipartViewer } from "./responseViewers/MultipartViewer";
import { SvgViewer } from "./responseViewers/SvgViewer";
import { VideoViewer } from "./responseViewers/VideoViewer";
const PdfViewer = lazy(() =>
import("./responseViewers/PdfViewer").then((m) => ({ default: m.PdfViewer })),
);
interface Props { interface Props {
style?: CSSProperties; style?: CSSProperties;
@@ -38,6 +53,10 @@ interface Props {
activeRequestId: string; activeRequestId: string;
} }
const TAB_BODY = "body";
const TAB_REQUEST = "request";
const TAB_HEADERS = "headers";
const TAB_COOKIES = "cookies";
const TAB_TIMELINE = "timeline"; const TAB_TIMELINE = "timeline";
export type TimelineViewMode = "timeline" | "text"; export type TimelineViewMode = "timeline" | "text";
@@ -47,11 +66,12 @@ interface RedirectDropWarning {
droppedHeaders: string[]; droppedHeaders: string[];
} }
/** The shared response pane, bound to the pinned response of the active request */
export function HttpResponsePane({ style, className, activeRequestId }: Props) { export function HttpResponsePane({ style, className, activeRequestId }: Props) {
const { activeResponse, setPinnedResponseId, responses } = usePinnedHttpResponse(activeRequestId); const { activeResponse, setPinnedResponseId, responses } = usePinnedHttpResponse(activeRequestId);
const [viewMode, setViewMode] = useResponseViewMode(activeResponse?.requestId); const [viewMode, setViewMode] = useResponseViewMode(activeResponse?.requestId);
const [timelineViewMode, setTimelineViewMode] = useTimelineViewMode(); const [timelineViewMode, setTimelineViewMode] = useTimelineViewMode();
const contentType = getContentTypeFromHeaders(activeResponse?.headers ?? null);
const mimeType = contentType == null ? null : getMimeTypeFromContentType(contentType).essence;
const responseEvents = useHttpResponseEvents(activeResponse); const responseEvents = useHttpResponseEvents(activeResponse);
const redirectDropWarning = useMemo( const redirectDropWarning = useMemo(
@@ -64,181 +84,281 @@ export function HttpResponsePane({ style, className, activeRequestId }: Props) {
const cookieCounts = useMemo(() => getCookieCounts(responseEvents.data), [responseEvents.data]); const cookieCounts = useMemo(() => getCookieCounts(responseEvents.data), [responseEvents.data]);
const saveResponse = useSaveResponse(activeResponse ?? null); const saveResponse = useSaveResponse(activeResponse ?? null);
const copyResponse = useCopyHttpResponse(activeResponse ?? null); const copyResponse = useCopyHttpResponse(activeResponse ?? null);
const cancel = useCancelHttpResponse(activeResponse?.id ?? null);
const body = useResponseBodyLoader(activeResponse ?? null);
const requestBody = useRequestBodyLoader(activeResponse ?? null);
const textViewer = useResponseTextViewerExtras(activeResponse ?? null);
const responseView = useMemo( const tabs = useMemo<TabItem[]>(
() => (activeResponse == null ? null : httpResponseToView(activeResponse, responseEvents.data)), () => [
[activeResponse, responseEvents.data], {
); value: TAB_BODY,
label: "Response",
const extraTabs = useMemo<ExtraPaneTab[]>( options: {
() => value: viewMode,
activeResponse == null onChange: setViewMode,
? [] items: [
: [ { label: "Response", value: "pretty" },
...(mimeType?.startsWith("image")
? []
: [{ label: "Response (Raw)", shortLabel: "Raw", value: "raw" }]),
],
itemsAfter: [
{ {
tab: { label: "Save to File",
value: TAB_TIMELINE, onSelect: saveResponse.mutate,
rightSlot: <CountBadge count={responseEvents.data?.length ?? 0} />, leftSlot: <Icon icon="save" />,
options: { hidden: activeResponse == null || !!activeResponse.error,
value: timelineViewMode, disabled: activeResponse?.state !== "closed" && (activeResponse?.status ?? 0) >= 100,
onChange: (v) => setTimelineViewMode((v as TimelineViewMode) ?? "timeline"), },
items: [ {
{ label: "Timeline", value: "timeline" }, label: "Copy Body",
{ label: "Timeline (Text)", shortLabel: "Timeline", value: "text" }, onSelect: copyResponse.mutate,
], leftSlot: <Icon icon="copy" />,
}, hidden: activeResponse == null || !!activeResponse.error,
}, disabled: activeResponse?.state !== "closed" && (activeResponse?.status ?? 0) >= 100,
content: (
<HttpResponseTimeline response={activeResponse} viewMode={timelineViewMode} />
),
}, },
], ],
[activeResponse, responseEvents.data?.length, setTimelineViewMode, timelineViewMode], },
},
{
value: TAB_REQUEST,
label: "Request",
rightSlot:
(activeResponse?.requestContentLength ?? 0) > 0 ? <CountBadge count={true} /> : null,
},
{
value: TAB_HEADERS,
label: "Headers",
rightSlot: (
<CountBadge
count={activeResponse?.requestHeaders.length ?? 0}
count2={activeResponse?.headers.length ?? 0}
showZero
/>
),
},
{
value: TAB_COOKIES,
label: "Cookies",
rightSlot:
cookieCounts.sent > 0 || cookieCounts.received > 0 ? (
<CountBadge count={cookieCounts.sent} count2={cookieCounts.received} showZero />
) : null,
},
{
value: TAB_TIMELINE,
rightSlot: <CountBadge count={responseEvents.data?.length ?? 0} />,
options: {
value: timelineViewMode,
onChange: (v) => setTimelineViewMode((v as TimelineViewMode) ?? "timeline"),
items: [
{ label: "Timeline", value: "timeline" },
{ label: "Timeline (Text)", shortLabel: "Timeline", value: "text" },
],
},
},
],
[
activeResponse?.headers,
activeResponse,
activeResponse?.error,
activeResponse?.requestContentLength,
activeResponse?.requestHeaders.length,
activeResponse?.state,
activeResponse?.status,
cookieCounts.sent,
cookieCounts.received,
copyResponse.mutate,
mimeType,
responseEvents.data?.length,
saveResponse.mutate,
setViewMode,
viewMode,
timelineViewMode,
setTimelineViewMode,
],
); );
const renderBodyViewer = useCallback( const cancel = useCancelHttpResponse(activeResponse?.id ?? null);
({ mimeType, viewMode }: HostBodyViewerArgs) =>
activeResponse != null && mimeType?.match(/^text\/event-stream/i) && viewMode === "pretty" ? (
<EventStreamViewer response={activeResponse} />
) : null,
[activeResponse],
);
return ( return (
<HttpResponsePaneView <div
style={style} style={style}
className={className} className={classNames(
response={responseView} className,
body={body} "x-theme-responsePane",
requestBody={requestBody} "max-h-full h-full",
emptyState={ "bg-surface rounded-md border border-border-subtle overflow-hidden",
"relative",
)}
>
{activeResponse == null ? (
<HotkeyList hotkeys={["request.send", "model.create", "sidebar.focus", "url_bar.focus"]} /> <HotkeyList hotkeys={["request.send", "model.create", "sidebar.focus", "url_bar.focus"]} />
} ) : (
viewMode={viewMode === "raw" ? "raw" : "pretty"} <div className="h-full w-full grid grid-rows-[auto_minmax(0,1fr)] grid-cols-1">
onViewModeChange={setViewMode} <HStack
activeTabKey={activeRequestId} className={classNames(
onSaveBody={saveResponse.mutate} "text-text-subtle w-full shrink-0",
onCopyBody={copyResponse.mutate} // Remove a bit of space because the tabs have lots too
onCancel={cancel.mutate} "-mb-1.5",
cookieCounts={cookieCounts} )}
extraTabs={extraTabs}
textViewer={textViewer}
renderBodyViewer={renderBodyViewer}
renderCopyButton={renderCopyButton}
statusLineCenter={
shouldShowRedirectDropWarning ? (
<Tooltip
tabIndex={0}
className="my-auto pl-3 shrink-0 max-w-full justify-self-end overflow-hidden"
content={
<VStack alignItems="start" space={1} className="text-xs">
<span className="font-medium text-warning">Redirect changed this request</span>
{redirectDropWarning.droppedBodyCount > 0 && (
<span>
Body dropped on {redirectDropWarning.droppedBodyCount}{" "}
{redirectDropWarning.droppedBodyCount === 1 ? "redirect hop" : "redirect hops"}
</span>
)}
{redirectDropWarning.droppedHeaders.length > 0 && (
<span>
Headers dropped:{" "}
<span className="font-mono">
{redirectDropWarning.droppedHeaders.join(", ")}
</span>
</span>
)}
<span className="text-text-subtle">See Timeline for details.</span>
</VStack>
}
> >
<span className="inline-flex min-w-0"> {activeResponse && (
<PillButton <div
color="warning" className={classNames(
className="font-sans text-sm shrink! max-w-full" "grid grid-cols-[auto_minmax(4rem,1fr)_auto]",
innerClassName="flex items-center" "cursor-default select-none",
leftSlot={<Icon icon="alert_triangle" size="xs" color="warning" />} "whitespace-nowrap w-full pl-3 overflow-x-auto font-mono text-sm hide-scrollbars",
)}
> >
<span className="truncate">{getRedirectWarningLabel(redirectDropWarning)}</span> <HStack space={2} className="w-full shrink-0">
</PillButton> {activeResponse.state !== "closed" && <LoadingIcon size="sm" />}
</span> <HttpStatusTag showReason response={activeResponse} />
</Tooltip> <span>&bull;</span>
) : null <HttpResponseDurationTag response={activeResponse} />
} <span>&bull;</span>
statusLineRight={ <SizeTag
activeResponse != null && ( contentLength={activeResponse.contentLength ?? 0}
<RecentHttpResponsesDropdown contentLengthCompressed={activeResponse.contentLengthCompressed}
responses={responses} />
activeResponse={activeResponse} </HStack>
onPinnedResponseId={setPinnedResponseId} {shouldShowRedirectDropWarning ? (
/> <Tooltip
) tabIndex={0}
} className="my-auto pl-3 shrink-0 max-w-full justify-self-end overflow-hidden"
/> content={
<VStack alignItems="start" space={1} className="text-xs">
<span className="font-medium text-warning">
Redirect changed this request
</span>
{redirectDropWarning.droppedBodyCount > 0 && (
<span>
Body dropped on {redirectDropWarning.droppedBodyCount}{" "}
{redirectDropWarning.droppedBodyCount === 1
? "redirect hop"
: "redirect hops"}
</span>
)}
{redirectDropWarning.droppedHeaders.length > 0 && (
<span>
Headers dropped:{" "}
<span className="font-mono">
{redirectDropWarning.droppedHeaders.join(", ")}
</span>
</span>
)}
<span className="text-text-subtle">See Timeline for details.</span>
</VStack>
}
>
<span className="inline-flex min-w-0">
<PillButton
color="warning"
className="font-sans text-sm shrink! max-w-full"
innerClassName="flex items-center"
leftSlot={<Icon icon="alert_triangle" size="xs" color="warning" />}
>
<span className="truncate">
{getRedirectWarningLabel(redirectDropWarning)}
</span>
</PillButton>
</span>
</Tooltip>
) : (
<span />
)}
<div className="justify-self-end shrink-0">
<RecentHttpResponsesDropdown
responses={responses}
activeResponse={activeResponse}
onPinnedResponseId={setPinnedResponseId}
/>
</div>
</div>
)}
</HStack>
<div className="overflow-hidden flex flex-col min-h-0">
{activeResponse?.error && (
<Banner color="danger" className="mx-3 mt-1 shrink-0">
{activeResponse.error}
</Banner>
)}
{activeResponse && <ChainingHint response={activeResponse} mimeType={mimeType} />}
{/* Show tabs if we have any data (headers, body, etc.) even if there's an error */}
<Tabs
tabs={tabs}
label="Response"
className="ml-3 mr-3 mb-3 min-h-0 flex-1"
tabListClassName="mt-0.5 -mb-1.5"
storageKey="http_response_tabs"
activeTabKey={activeRequestId}
>
<TabContent value={TAB_BODY}>
<ErrorBoundary name="Http Response Viewer">
<Suspense>
<ConfirmLargeResponse response={activeResponse}>
{activeResponse.state === "initialized" ? (
<EmptyStateText>
<VStack space={3}>
<HStack space={3}>
<LoadingIcon className="text-text-subtlest" />
Sending Request
</HStack>
<Button size="sm" variant="border" onClick={() => cancel.mutate()}>
Cancel
</Button>
</VStack>
</EmptyStateText>
) : activeResponse.state === "closed" &&
(activeResponse.contentLength ?? 0) === 0 ? (
<EmptyStateText>Empty</EmptyStateText>
) : mimeType?.match(/^text\/event-stream/i) && viewMode === "pretty" ? (
<EventStreamViewer response={activeResponse} />
) : mimeType?.match(/^image\/svg/) ? (
<HttpSvgViewer response={activeResponse} />
) : mimeType?.match(/^image/i) ? (
<EnsureCompleteResponse response={activeResponse} Component={ImageViewer} />
) : mimeType?.match(/^audio/i) ? (
<EnsureCompleteResponse response={activeResponse} Component={AudioViewer} />
) : mimeType?.match(/^video/i) ? (
<EnsureCompleteResponse response={activeResponse} Component={VideoViewer} />
) : mimeType?.match(/^multipart/i) && viewMode === "pretty" ? (
<HttpMultipartViewer response={activeResponse} />
) : mimeType?.match(/pdf/i) ? (
<EnsureCompleteResponse response={activeResponse} Component={PdfViewer} />
) : mimeType?.match(/csv|tab-separated/i) && viewMode === "pretty" ? (
<HttpCsvViewer className="pb-2" response={activeResponse} />
) : (
<HTMLOrTextViewer
textViewerClassName="-mr-2 bg-surface" // Pull to the right
response={activeResponse}
pretty={viewMode === "pretty"}
/>
)}
</ConfirmLargeResponse>
</Suspense>
</ErrorBoundary>
</TabContent>
<TabContent value={TAB_REQUEST}>
<ConfirmLargeResponseRequest response={activeResponse}>
<RequestBodyViewer response={activeResponse} />
</ConfirmLargeResponseRequest>
</TabContent>
<TabContent value={TAB_HEADERS}>
<ResponseHeaders response={activeResponse} />
</TabContent>
<TabContent value={TAB_COOKIES}>
<ResponseCookies response={activeResponse} />
</TabContent>
<TabContent value={TAB_TIMELINE}>
<HttpResponseTimeline response={activeResponse} viewMode={timelineViewMode} />
</TabContent>
</Tabs>
</div>
</div>
)}
</div>
); );
} }
/** The client's additions to the response text viewer: filter history, save and copy */
function useResponseTextViewerExtras(
response: HttpResponse | null,
): ResponseTextViewerExtras | undefined {
const filterStateKey = `response.body.${response?.requestId ?? ""}`;
const { recentFilters, addFilter, removeFilter, togglePin, clearFilters } =
useRecentFilters(filterStateKey);
const saveResponse = useSaveResponse(response);
const copyResponse = useCopyHttpResponse(response);
const filterLeftSlot = useCallback(
(filter: TextFilterApi) => (
<div className="py-0.5 flex">
<RecentFiltersDropdown
recentFilters={recentFilters}
activeFilter={filter.appliedFilter}
onSelect={filter.replaceFilter}
onRemove={removeFilter}
onTogglePin={togglePin}
onClear={clearFilters}
/>
</div>
),
[recentFilters, removeFilter, togglePin, clearFilters],
);
if (response == null) return undefined;
const actionsDisabled = response.state !== "closed" && response.status >= 100;
return {
filterStateKey,
onFilterApplied: addFilter,
filterLeftSlot,
footerActions: [
<IconButton
key="save"
size="sm"
icon="save"
title="Save response to file"
disabled={actionsDisabled}
onClick={() => saveResponse.mutate()}
className="border !border-border-subtle"
/>,
<IconButton
key="copy"
size="sm"
icon="copy"
title="Copy response body"
disabled={actionsDisabled}
onClick={() => copyResponse.mutate()}
className="border !border-border-subtle"
/>,
],
};
}
function renderCopyButton(getText: () => Promise<string | null>) {
return <CopyButton color="secondary" variant="border" size="xs" text={getText} />;
}
function getRedirectDropWarning( function getRedirectDropWarning(
events: HttpResponseEvent[] | undefined, events: HttpResponseEvent[] | undefined,
): RedirectDropWarning | null { ): RedirectDropWarning | null {
@@ -286,3 +406,58 @@ function getRedirectWarningLabel(warning: RedirectDropWarning): string {
} }
return "Dropped headers"; return "Dropped headers";
} }
function EnsureCompleteResponse({
response,
Component,
}: {
response: HttpResponse;
Component: ComponentType<{ bodyUrl: string }>;
}) {
// Wait until the response has been fully-downloaded before asking for it
const complete = response.state === "closed";
const bodyUrl = useResponseBodyUrl(complete ? response : null);
if (!complete || bodyUrl.isPending) {
return (
<EmptyStateText>
<LoadingIcon />
</EmptyStateText>
);
}
if (bodyUrl.error) {
return <Banner color="danger">{String(bodyUrl.error)}</Banner>;
}
if (bodyUrl.data == null) {
return <div>Empty response body</div>;
}
return <Component bodyUrl={bodyUrl.data} />;
}
function HttpSvgViewer({ response }: { response: HttpResponse }) {
const body = useResponseBodyText({ response, filter: null });
if (!body.data) return null;
return <SvgViewer text={body.data} />;
}
function HttpCsvViewer({ response, className }: { response: HttpResponse; className?: string }) {
const body = useResponseBodyText({ response, filter: null });
return <CsvViewer text={body.data ?? null} className={className} />;
}
function HttpMultipartViewer({ response }: { response: HttpResponse }) {
const body = useResponseBodyBytes({ response });
if (body.data == null) return null;
const contentTypeHeader = getContentTypeFromHeaders(response.headers);
const boundary = contentTypeHeader?.split("boundary=")[1] ?? "unknown";
return <MultipartViewer data={body.data} boundary={boundary} idPrefix={response.id} />;
}
@@ -13,8 +13,9 @@ import { resolvedModelName } from "../lib/resolvedModelName";
import { Editor } from "./core/Editor/LazyEditor"; import { Editor } from "./core/Editor/LazyEditor";
import { type EventDetailAction, EventDetailHeader, EventViewer } from "./core/EventViewer"; import { type EventDetailAction, EventDetailHeader, EventViewer } from "./core/EventViewer";
import { EventViewerRow } from "./core/EventViewerRow"; import { EventViewerRow } from "./core/EventViewerRow";
import { Icon, type IconProps, HttpStatusTagRaw, KeyValueRows } from "@yaakapp-internal/ui"; import { HttpStatusTagRaw } from "./core/HttpStatusTag";
import { KeyValueRow } from "./core/KeyValueRow"; import { Icon, type IconProps } from "@yaakapp-internal/ui";
import { KeyValueRow, KeyValueRows } from "./core/KeyValueRow";
import type { TimelineViewMode } from "./HttpResponsePane"; import type { TimelineViewMode } from "./HttpResponsePane";
interface Props { interface Props {
+345 -319
View File
@@ -1,42 +1,33 @@
import { import {
type Folder,
type ImportDestination, type ImportDestination,
type ImportPlan, type ImportPlan,
type ImportPlanItem, type ImportPlanItem,
type ImportSource, type ImportSource,
type Workspace, type Workspace,
} from "@yaakapp-internal/models"; } from "@yaakapp-internal/models";
import { import { Banner, HStack, Icon, type IconProps, InlineCode, VStack } from "@yaakapp-internal/ui";
Banner, import { platform } from "@yaakapp-internal/platform";
FormattedError,
HStack,
Icon,
VStack,
IconTooltip,
SegmentedControl,
} from "@yaakapp-internal/ui";
import classNames from "classnames"; import classNames from "classnames";
import { type ComponentProps, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { formatDistanceToNowStrict } from "date-fns";
import { errorMessage } from "../lib/errorMessage"; import { useEffect, useMemo, useRef, useState } from "react";
import { pluralize } from "../lib/pluralize";
import { CommercialUseBanner } from "./CommercialUseBanner"; import { CommercialUseBanner } from "./CommercialUseBanner";
import { import { Button } from "./core/Button";
ImportSourceList, import { Checkbox } from "./core/Checkbox";
type ImportSourceDetection,
type ImportSourcePath,
InlineButton,
toSourcePath,
} from "./ImportSourceList";
import type { CheckboxTreeNode } from "./core/CheckboxTree"; import type { CheckboxTreeNode } from "./core/CheckboxTree";
import { CheckboxTree } from "./core/CheckboxTree"; import { CheckboxTree } from "./core/CheckboxTree";
import { Chip } from "./core/Chip"; import { IconTooltip } from "./core/IconTooltip";
import { DialogFooter } from "./core/Dialog"; import { PlainInput } from "./core/PlainInput";
import { Select } from "./core/Select"; import { Select } from "./core/Select";
import { pluralize } from "@yaakapp-internal/lib/pluralize"; import { SegmentedControl } from "./core/SegmentedControl";
interface Props { interface Props {
currentWorkspace: Workspace | null; currentWorkspace: Workspace | null;
workspaces: Workspace[]; workspaces: Workspace[];
planSources: (sources: ImportSourcePath[], destination: ImportDestination) => Promise<ImportPlan>; selectedFolder: Folder | null;
detectSource: (source: ImportSourcePath) => Promise<string>; planFile: (filePath: string, destination: ImportDestination) => Promise<ImportPlan>;
planUrl: (url: string, destination: ImportDestination) => Promise<ImportPlan>;
listSources: (workspaceId: string) => Promise<ImportSource[]>; listSources: (workspaceId: string) => Promise<ImportSource[]>;
findSourcesForOrigin: (args: { filePath?: string; url?: string }) => Promise<ImportSource[]>; findSourcesForOrigin: (args: { filePath?: string; url?: string }) => Promise<ImportSource[]>;
commit: (plan: ImportPlan) => Promise<void>; commit: (plan: ImportPlan) => Promise<void>;
@@ -44,6 +35,25 @@ interface Props {
onError: (err: unknown) => void; onError: (err: unknown) => void;
} }
/**
* An absolute or relative path is unambiguously a file. Everything else is treated as a URL, so a
* bare host like `example.com/openapi.json` still works (the backend defaults it to https).
*/
function isFilePath(value: string): boolean {
return (
value.startsWith("/") ||
value.startsWith("./") ||
value.startsWith("../") ||
value.startsWith("~/") ||
value.startsWith("\\\\") ||
/^[a-zA-Z]:[\\/]/.test(value)
);
}
function fileName(path: string): string {
return path.split(/[/\\]/).at(-1) || path;
}
/** /**
* Loads the current workspace's linked sources before rendering the dialog, so the inner * Loads the current workspace's linked sources before rendering the dialog, so the inner
* component can construct its initial state (prefilled path, destination) in one pass instead of * component can construct its initial state (prefilled path, destination) in one pass instead of
@@ -72,19 +82,30 @@ export function ImportDataDialog(props: Props) {
return <LoadedImportDataDialog {...props} initialSources={initialSources} />; return <LoadedImportDataDialog {...props} initialSources={initialSources} />;
} }
function latestSource(sources: ImportSource[]): ImportSource | null {
return sources.reduce<ImportSource | null>(
(latest, s) => (latest == null || s.lastImportedAt > latest.lastImportedAt ? s : latest),
null,
);
}
function LoadedImportDataDialog({ function LoadedImportDataDialog({
currentWorkspace, currentWorkspace,
workspaces, workspaces,
planSources, selectedFolder,
detectSource, planFile,
planUrl,
listSources,
findSourcesForOrigin, findSourcesForOrigin,
commit, commit,
cancel, cancel,
onError, onError,
initialSources, initialSources,
}: Props & { initialSources: ImportSource[] }) { }: Props & { initialSources: ImportSource[] }) {
// A workspace with a linked source is probably being re-imported, so start from that source
const prefill = latestSource(initialSources);
const [isLoading, setIsLoading] = useState<boolean>(false); const [isLoading, setIsLoading] = useState<boolean>(false);
const [sourceError, setSourceError] = useState<unknown>(null);
const [plan, setPlan] = useState<ImportPlan | null>(null); const [plan, setPlan] = useState<ImportPlan | null>(null);
const [items, setItems] = useState<ImportPlanItem[]>([]); const [items, setItems] = useState<ImportPlanItem[]>([]);
// null means no explicit choice yet, so the default below applies // null means no explicit choice yet, so the default below applies
@@ -92,82 +113,65 @@ function LoadedImportDataDialog({
null, null,
); );
const [otherWorkspaceId, setOtherWorkspaceId] = useState<string | null>(null); const [otherWorkspaceId, setOtherWorkspaceId] = useState<string | null>(null);
const [originSources, setOriginSources] = useState<ImportSource[]>(initialSources); const [targetSelectedFolder, setTargetSelectedFolder] = useState(selectedFolder != null);
const initialPaths = useMemo( const [linkedSources, setLinkedSources] = useState<ImportSource[]>(
() => [...new Set(initialSources.map((source) => source.origin))].map(toSourcePath), prefill != null ? initialSources : [],
[initialSources],
); );
const [sources, setSources] = useState<ImportSourcePath[]>(initialPaths); const [originSources, setOriginSources] = useState<ImportSource[]>(
const knownPaths = useRef(new Set(initialPaths.map((source) => source.path))); prefill != null ? [prefill] : [],
const [detections, setDetections] = useState<Record<string, ImportSourceDetection>>({});
const detect = useCallback(
(added: ImportSourcePath[]) => {
setDetections((prev) => ({
...prev,
...Object.fromEntries(added.map((s) => [s.path, { status: "loading" as const }])),
}));
for (const source of added) {
const settle = (detection: ImportSourceDetection) =>
setDetections((prev) =>
source.path in prev ? { ...prev, [source.path]: detection } : prev,
);
detectSource(source).then(
(importer) => settle({ status: "ok", importer }),
(err) => settle({ status: "error", message: errorMessage(err) }),
);
}
},
[detectSource],
); );
const allDetected = sources.every((source) => detections[source.path]?.status === "ok"); // A file path or a URL. Both inputs write here, so there is only ever one thing to import
useEffect(() => { const [source, setSource] = useState<string | null>(prefill?.origin ?? null);
detect(initialPaths); const [forceUpdateKey, setForceUpdateKey] = useState<number>(0);
}, [detect, initialPaths]); const [isHovering, setIsHovering] = useState<boolean>(false);
const ref = useRef<HTMLDivElement>(null);
const trimmedSource = source?.trim() ?? "";
const filePath = isFilePath(trimmedSource) ? trimmedSource : null;
const addSources = useCallback( const selectSource = (value: string) => {
(added: ImportSourcePath[]) => { setSource(value);
setSourceError(null); // Remount the input so it shows the path of the newly-picked file
const fresh = added.filter(({ path }) => { setForceUpdateKey((k) => k + 1);
if (knownPaths.current.has(path)) return false;
knownPaths.current.add(path);
return true;
});
if (fresh.length === 0) return;
setSources((existing) => [...existing, ...fresh]);
detect(fresh);
},
[detect],
);
const removeSource = (path: string) => {
setSourceError(null);
knownPaths.current.delete(path);
setSources((current) => current.filter((source) => source.path !== path));
setDetections(({ [path]: _removed, ...rest }) => rest);
}; };
// Accept a file dropped anywhere on the dialog, the way SelectFile does for its button
useEffect(() => { useEffect(() => {
let cancelled = false; return platform.window.onDragDrop((event) => {
if (sources.length === 0) { if (event.type === "over") {
const p = event.position;
const r = ref.current?.getBoundingClientRect();
if (r == null) return;
setIsHovering(p.x >= r.left && p.x <= r.right && p.y >= r.top && p.y <= r.bottom);
} else if (event.type === "drop" && isHovering) {
const p = event.paths[0];
if (p) selectSource(p);
setIsHovering(false);
} else {
setIsHovering(false);
}
});
}, [isHovering, setSource]);
useEffect(() => {
if (trimmedSource === "") {
setOriginSources([]); setOriginSources([]);
return; return;
} }
Promise.all( let cancelled = false;
sources.map(({ path, kind }) => const timeout = setTimeout(() => {
findSourcesForOrigin(kind === "url" ? { url: path } : { filePath: path }), findSourcesForOrigin(filePath != null ? { filePath } : { url: trimmedSource })
), .then((sources) => {
) if (!cancelled) setOriginSources(sources);
.then((found) => { })
if (!cancelled) setOriginSources(found.flat()); .catch(() => setOriginSources([]));
}) }, 300);
.catch(() => {
if (!cancelled) setOriginSources([]);
});
return () => { return () => {
cancelled = true; cancelled = true;
clearTimeout(timeout);
}; };
}, [sources, findSourcesForOrigin]); }, [trimmedSource, filePath, findSourcesForOrigin]);
// The one workspace these sources are linked to, if there is exactly one. // The one workspace this file is linked to, if there is exactly one.
const linkedWorkspace = useMemo(() => { const linkedWorkspace = useMemo(() => {
const ids = [...new Set(originSources.map((s) => s.workspaceId))]; const ids = [...new Set(originSources.map((s) => s.workspaceId))];
if (ids.length !== 1) return null; if (ids.length !== 1) return null;
@@ -189,6 +193,32 @@ function LoadedImportDataDialog({
? otherWorkspaceId ? otherWorkspaceId
: null; : null;
useEffect(() => {
if (destinationWorkspaceId == null) {
setLinkedSources([]);
return;
}
let cancelled = false;
listSources(destinationWorkspaceId)
.then((sources) => {
if (!cancelled) setLinkedSources(sources);
})
.catch(() => setLinkedSources([]));
return () => {
cancelled = true;
};
}, [destinationWorkspaceId, listSources]);
const handleSelectFile = async () => {
const selected = await platform.dialog.open({ title: "Select File", multiple: false });
if (selected == null) return;
selectSource(selected);
};
// The selected folder belongs to the workspace being viewed, so it is only offerable when that
// is also the destination.
const canTargetSelectedFolder = selectedFolder != null && destinationKind === "current";
const destination = (): ImportDestination => { const destination = (): ImportDestination => {
if (destinationWorkspaceId == null) { if (destinationWorkspaceId == null) {
return { type: "new_workspace" }; return { type: "new_workspace" };
@@ -196,18 +226,21 @@ function LoadedImportDataDialog({
return { return {
type: "existing_workspace", type: "existing_workspace",
workspaceId: destinationWorkspaceId, workspaceId: destinationWorkspaceId,
folderId: canTargetSelectedFolder && targetSelectedFolder ? selectedFolder.id : undefined,
}; };
}; };
const handlePreview = async () => { const handlePreview = async () => {
setIsLoading(true); setIsLoading(true);
setSourceError(null);
try { try {
const nextPlan = await planSources(sources, destination()); const nextPlan =
filePath != null
? await planFile(filePath, destination())
: await planUrl(trimmedSource, destination());
setPlan(nextPlan); setPlan(nextPlan);
setItems(nextPlan.items); setItems(nextPlan.items);
} catch (err) { } catch (err) {
setSourceError(err); onError(err);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
@@ -225,6 +258,8 @@ function LoadedImportDataDialog({
} }
}; };
const itemTree = useMemo(() => buildItemTree(items), [items]);
// A folder row's checkbox carries everything beneath it, deletions included — the row labels // A folder row's checkbox carries everything beneath it, deletions included — the row labels
// say which of those are destructive. Checking anything also brings back the folders it needs // say which of those are destructive. Checking anything also brings back the folders it needs
// to live in. // to live in.
@@ -278,215 +313,196 @@ function LoadedImportDataDialog({
if (plan.destination.type === "new_workspace") { if (plan.destination.type === "new_workspace") {
const names = plan.resources.workspaces.map((w) => w.name).filter((n) => n !== ""); const names = plan.resources.workspaces.map((w) => w.name).filter((n) => n !== "");
if (names.length === 0) return ["New workspace", "Untitled"]; if (names.length === 0) return ["New workspace", "Untitled"];
return [ return [pluralize("New workspace", names.length), names.join(", ")];
names.length === 1 ? "New workspace" : `${names.length} new workspaces`,
names.join(", "),
];
} }
const { workspaceId } = plan.destination; const { workspaceId, folderId } = plan.destination;
const name = workspaces.find((w) => w.id === workspaceId)?.name ?? "Unknown workspace"; const name = workspaces.find((w) => w.id === workspaceId)?.name ?? "Unknown workspace";
return ["Destination", name]; return [
"Destination",
folderId != null && folderId === selectedFolder?.id
? `${name} / ${selectedFolder.name}`
: name,
];
})(); })();
// The destination workspace roots the tree. It is not a plan item — commit always applies // The destination workspace roots the tree. It is not a plan item — commit always applies
// it — so its checkbox only aggregates the subtree. // it — so its checkbox only aggregates the subtree.
const workspaceRoots: CheckboxTreeNode<TreeRow>[] = (() => { const workspaceRoot: CheckboxTreeNode<TreeRow> = (() => {
const planned = plan.resources.workspaces[0];
const planDestination = plan.destination; const planDestination = plan.destination;
const existing = const existing =
planDestination.type === "existing_workspace" planDestination.type === "existing_workspace"
? workspaces.find((w) => w.id === planDestination.workspaceId) ? workspaces.find((w) => w.id === planDestination.workspaceId)
: null; : null;
const destinations = existing ? [existing] : plan.resources.workspaces; return {
if (destinations.length === 1) { key: existing?.id ?? planned?.id ?? "workspace",
const workspace = destinations[0]!;
return [
{
key: workspace.id,
data: {
kind: "destination",
label: workspace.name,
isNew: planDestination.type === "new_workspace",
},
children: buildItemTree(items),
},
];
}
const workspaceById = new Map(
[
...plan.resources.environments,
...plan.resources.folders,
...plan.resources.httpRequests,
...plan.resources.grpcRequests,
...plan.resources.websocketRequests,
].map((resource) => [resource.id, resource.workspaceId]),
);
return destinations.map((workspace) => ({
key: workspace.id,
data: { data: {
kind: "destination", kind: "destination",
label: workspace.name, label: existing?.name ?? planned?.name ?? "New workspace",
isNew: planDestination.type === "new_workspace", isNew: planDestination.type === "new_workspace",
}, },
children: buildItemTree( children: itemTree,
items.filter((item) => workspaceById.get(item.modelId) === workspace.id), };
),
}));
})(); })();
return ( return (
<> <VStack space={4} className="pb-4">
<VStack space={4} className="pb-4"> <div className="rounded-lg border border-border-subtle divide-y divide-border-subtle">
<div className="rounded-lg border border-border-subtle divide-y divide-border-subtle"> <PreviewRow label="Detected format" value={plan.importer} />
<PreviewRow label="Detected format" value={plan.importer} /> <PreviewRow label={destinationLabel} value={destinationValue} />
<PreviewRow label={destinationLabel} value={destinationValue} /> </div>
</div>
{plan.warnings {plan.warnings.map((warning) => (
.filter( <Banner
(warning, index, warnings) => key={`${warning.title}:${warning.detail}`}
warnings.findIndex( color={warning.level === "warning" ? "warning" : "info"}
(other) => className="flex items-start gap-2.5"
other.title === warning.title && >
other.detail === warning.detail && <Icon
other.level === warning.level, icon={warning.level === "warning" ? "alert_triangle" : "info"}
) === index, size="sm"
) className="mt-0.5"
.map((warning) => ( />
<Banner <div className="min-w-0">
key={`${warning.level}:${warning.title}:${warning.detail}`} <div className="text-sm font-medium">{warning.title}</div>
color={warning.level === "warning" ? "warning" : "info"} <div className="text-xs text-text-subtle mt-0.5">{warning.detail}</div>
className="flex items-start gap-2.5"
>
<Icon
icon={warning.level === "warning" ? "alert_triangle" : "info"}
size="sm"
className="mt-0.5"
/>
<div className="min-w-0">
<div className="text-sm font-medium">{warning.title}</div>
<div className="text-xs text-text-subtle mt-0.5">{warning.detail}</div>
</div>
</Banner>
))}
{workspaceRoots.map((root) => (
<div key={root.key} className="rounded-lg border border-border-subtle px-3 py-2">
<CheckboxTree
node={root}
checked={nodeCheckedStatus}
onCheck={toggleNode}
isCheckboxDisabled={(n) => disabledIds.has(n.key)}
isCollapsedByDefault={(n) =>
(n.data.kind === "destination" && workspaceRoots.length > 1) ||
(n.data.kind === "item" && n.data.item.action === "ignored")
}
isRelevant={(n) =>
n.data.kind === "destination" ||
(n.data.kind === "item" && n.data.item.action !== "unchanged")
}
renderRow={(n) => (
<ImportTreeRow row={n.data} onResolveConflict={resolveConflict} />
)}
/>
</div> </div>
))} </Banner>
</VStack> ))}
<DialogFooter
leftSlot={ <div className="rounded-lg border border-border-subtle px-3 py-2 overflow-y-auto max-h-[40vh]">
footerNote !== "" ? ( <CheckboxTree
<div className="text-xs text-text-subtle">{footerNote}</div> node={workspaceRoot}
) : undefined checked={nodeCheckedStatus}
} onCheck={toggleNode}
actions={[ isCheckboxDisabled={(n) => disabledIds.has(n.key)}
{ isCollapsedByDefault={(n) => n.data.kind === "item" && n.data.item.action === "ignored"}
label: "Back", isRelevant={(n) =>
disabled: isLoading, n.data.kind === "destination" ||
onClick: () => { (n.data.kind === "item" && n.data.item.action !== "unchanged")
setPlan(null); }
setItems([]); renderRow={(n) => <ImportTreeRow row={n.data} onResolveConflict={resolveConflict} />}
}, />
}, </div>
{
label: isLoading <HStack space={2} alignItems="center" className="mt-3">
? "Importing" {footerNote !== "" && <div className="text-xs text-text-subtle">{footerNote}</div>}
: changeCount > 0 <Button
? `Apply ${changeCount} ${changeCount === 1 ? "Change" : "Changes"}` className="ml-auto"
: "Done", color="secondary"
color: "primary", variant="border"
isLoading, disabled={isLoading}
onClick: handleCommit, onClick={() => {
}, setPlan(null);
]} setItems([]);
/> }}
</> >
Back
</Button>
<Button color="primary" isLoading={isLoading} onClick={handleCommit}>
{isLoading
? "Importing"
: changeCount > 0
? `Apply ${changeCount} ${changeCount === 1 ? "Change" : "Changes"}`
: "Done"}
</Button>
</HStack>
</VStack>
); );
} }
const destinationPicker = ( const lastImported =
<HStack originSources.find((s) => s.workspaceId === destinationWorkspaceId) ??
space={2} linkedSources.reduce<ImportSource | null>(
alignItems="center" (latest, s) => (latest == null || s.lastImportedAt > latest.lastImportedAt ? s : latest),
className={classNames(workspaces.length === 0 && "hidden")} null,
> );
<Select
name="import-destination-kind"
label="Import into"
labelPosition="left"
size="sm"
value={destinationKind}
onChange={setDestinationChoice}
options={[
{ value: "new", label: "New Workspace" },
...(currentWorkspace != null
? [{ value: "current" as const, label: "Current Workspace" }]
: []),
{ value: "other", label: "Other Workspace" },
]}
/>
{destinationKind === "other" && (
<Select
name="import-destination-workspace"
label="Workspace"
hideLabel
size="sm"
value={otherWorkspaceId ?? ""}
onChange={(id) => setOtherWorkspaceId(id === "" ? null : id)}
filterable
options={[
{ value: "", label: "Select a workspace" },
...workspaces
.filter((w) => w.id !== currentWorkspace?.id)
.map((w) => ({ value: w.id, label: w.name })),
]}
/>
)}
</HStack>
);
return ( return (
<> <VStack ref={ref} space={4} className="pb-4">
<VStack space={4} className="h-full pb-4"> <CommercialUseBanner source="data-import" title="Importing work data?" />
<CommercialUseBanner source="data-import" title="Importing work data?" />
<ImportSourceList <button
sources={sources} type="button"
detections={detections} onClick={handleSelectFile}
disabled={isLoading} className={classNames(
onAdd={addSources} "w-full rounded-lg border border-dashed px-4 py-6",
onRemove={removeSource} "flex flex-col items-center gap-1 text-center",
onError={setSourceError} isHovering
/> ? "border-notice bg-surface-highlight"
: "border-border hover:border-text-subtle",
{sourceError != null && (
<Banner color="warning">
<FormattedError>{errorMessage(sourceError)}</FormattedError>
</Banner>
)} )}
>
<Icon icon="folder_input" className="text-text-subtlest w-8! h-8! mb-2" />
{/* Fixed height so the region doesn't resize between the empty and selected states */}
<div className="h-6 w-full flex items-center justify-center">
{filePath == null ? (
<div className="text-text">
<strong className="font-semibold">Choose a file</strong> or drag it here
</div>
) : (
<div className="text-text font-mono text-xs max-w-full truncate" title={filePath}>
{fileName(filePath)}
</div>
)}
</div>
<div className="text-xs text-text-subtlest">
Supports OpenAPI, Swagger, Postman, Insomnia, and curl
</div>
</button>
{linkedWorkspace != null && linkedWorkspace.id !== destinationWorkspaceId && ( <PlainInput
label="Or enter a file path or URL"
size="sm"
placeholder="https://example.com/openapi.json"
defaultValue={source ?? ""}
forceUpdateKey={String(forceUpdateKey)}
onChange={setSource}
/>
<VStack space={2}>
<Select
name="import-destination-kind"
label="Import location"
size="sm"
value={destinationKind}
onChange={setDestinationChoice}
options={[
{ value: "new", label: "New Workspace" },
...(currentWorkspace != null
? [{ value: "current" as const, label: "Current Workspace" }]
: []),
{ value: "other", label: "Other Workspace" },
]}
/>
{destinationKind === "other" && (
<Select
name="import-destination-workspace"
label="Workspace"
hideLabel
size="sm"
value={otherWorkspaceId ?? ""}
onChange={(id) => setOtherWorkspaceId(id === "" ? null : id)}
filterable
options={[
{ value: "", label: "Select a workspace" },
...workspaces
.filter((w) => w.id !== currentWorkspace?.id)
.map((w) => ({ value: w.id, label: w.name })),
]}
/>
)}
{lastImported != null && destinationWorkspaceId != null ? (
<div className="text-xs text-text-subtle"> <div className="text-xs text-text-subtle">
{sources.length === 1 ? "This source was" : "These sources were"} last imported into{" "} Last imported from {lastImported.originLabel} ·{" "}
<InlineButton {formatDistanceToNowStrict(`${lastImported.lastImportedAt}Z`, { addSuffix: true })}
</div>
) : linkedWorkspace != null && linkedWorkspace.id !== destinationWorkspaceId ? (
<div className="text-xs text-text-subtle">
This file was last imported into{" "}
<button
type="button"
className="underline hocus:text-text"
onClick={() => { onClick={() => {
if (linkedWorkspace.id === currentWorkspace?.id) { if (linkedWorkspace.id === currentWorkspace?.id) {
setDestinationChoice("current"); setDestinationChoice("current");
@@ -497,28 +513,36 @@ function LoadedImportDataDialog({
}} }}
> >
{linkedWorkspace.name} {linkedWorkspace.name}
</InlineButton> </button>
</div> </div>
) : null}
{canTargetSelectedFolder && (
<Checkbox
checked={targetSelectedFolder}
title={`Place root resources in selected folder “${selectedFolder.name}”`}
onChange={setTargetSelectedFolder}
/>
)} )}
</VStack> </VStack>
<DialogFooter
leftSlot={destinationPicker} <HStack space={2} justifyContent="end">
actions={[ <Button color="secondary" variant="border" disabled={isLoading} onClick={cancel}>
{ label: "Cancel", disabled: isLoading, onClick: cancel }, Cancel
{ </Button>
label: isLoading ? "Analyzing" : "Preview Import", <Button
color: "primary", color="primary"
disabled: disabled={
sources.length === 0 || trimmedSource === "" ||
!allDetected || isLoading ||
isLoading || (destinationKind === "other" && otherWorkspaceId == null)
(destinationKind === "other" && otherWorkspaceId == null), }
isLoading, isLoading={isLoading}
onClick: handlePreview, onClick={handlePreview}
}, >
]} {isLoading ? "Analyzing" : "Preview Import"}
/> </Button>
</> </HStack>
</VStack>
); );
} }
@@ -532,12 +556,10 @@ function ImportTreeRow({
if (row.kind !== "item") { if (row.kind !== "item") {
return ( return (
<> <>
{row.kind === "destination" && ( <Icon color="secondary" icon={row.kind === "destination" ? "house" : row.icon} />
<Icon icon="box" size="sm" className="shrink-0 text-text-subtle" />
)}
<div className="truncate flex-1">{row.label}</div> <div className="truncate flex-1">{row.label}</div>
{row.kind === "destination" && row.isNew && ( {row.kind === "destination" && row.isNew && (
<ActionChip label="new" help="Created by this import" color="success" /> <ActionChip label="new" help="Created by this import" className="text-success" />
)} )}
</> </>
); );
@@ -547,6 +569,11 @@ function ImportTreeRow({
const label = actionLabel(item); const label = actionLabel(item);
return ( return (
<> <>
{item.model === "folder" || item.model === "environment" ? (
<Icon color="secondary" icon={item.model === "folder" ? "folder" : "variable"} />
) : (
<span aria-hidden className="w-4" />
)}
<div className="truncate flex-1">{item.name}</div> <div className="truncate flex-1">{item.name}</div>
{item.action === "conflict" ? ( {item.action === "conflict" ? (
<div className="shrink-0"> <div className="shrink-0">
@@ -566,7 +593,17 @@ function ImportTreeRow({
</div> </div>
) : ( ) : (
label != null && ( label != null && (
<ActionChip label={label} help={actionHelp(item)} color={actionColor(item)} /> <ActionChip
label={label}
help={actionHelp(item)}
className={classNames(
item.action === "create" && "text-success",
item.action === "update" && "text-info",
item.action === "delete" && "text-danger",
item.action === "keep_local" && item.selected && "text-warning",
item.action === "ignored" && "text-text-subtlest",
)}
/>
) )
)} )}
</> </>
@@ -576,37 +613,26 @@ function ImportTreeRow({
function ActionChip({ function ActionChip({
label, label,
help, help,
color, className,
}: { }: {
label: string; label: string;
help: string | null; help: string | null;
color: ComponentProps<typeof Chip>["color"]; className?: string;
}) { }) {
return ( return (
<Chip color={color}> <InlineCode
className={classNames(
"py-0 bg-transparent w-32 shrink-0 whitespace-nowrap text-xs",
"inline-flex items-center justify-center gap-1.5",
className,
)}
>
{label} {label}
{help != null && <IconTooltip content={help} iconSize="xs" />} {help != null && <IconTooltip content={help} iconSize="xs" />}
</Chip> </InlineCode>
); );
} }
function actionColor(item: ImportPlanItem): ComponentProps<typeof Chip>["color"] {
switch (item.action) {
case "create":
return "success";
case "update":
return "info";
case "delete":
return "danger";
case "keep_local":
return item.selected ? "warning" : "default";
case "unchanged":
case "conflict":
case "ignored":
return "default";
}
}
function actionLabel(item: ImportPlanItem): string | null { function actionLabel(item: ImportPlanItem): string | null {
switch (item.action) { switch (item.action) {
case "create": case "create":
@@ -675,7 +701,7 @@ function ancestorsOf(item: ImportPlanItem, byId: Map<string, ImportPlanItem>): I
*/ */
type TreeRow = type TreeRow =
| { kind: "destination"; label: string; isNew: boolean } | { kind: "destination"; label: string; isNew: boolean }
| { kind: "group"; label: string } | { kind: "group"; label: string; icon: IconProps["icon"] }
| { kind: "item"; item: ImportPlanItem }; | { kind: "item"; item: ImportPlanItem };
function buildItemTree(items: ImportPlanItem[]): CheckboxTreeNode<TreeRow>[] { function buildItemTree(items: ImportPlanItem[]): CheckboxTreeNode<TreeRow>[] {
@@ -717,7 +743,7 @@ function buildItemTree(items: ImportPlanItem[]): CheckboxTreeNode<TreeRow>[] {
return [ return [
{ {
key: "group:environments", key: "group:environments",
data: { kind: "group", label: "Variables" }, data: { kind: "group", label: "Variables", icon: "variable" },
children: environments.map((e) => toNode(e, new Set())), children: environments.map((e) => toNode(e, new Set())),
}, },
...nodes, ...nodes,
@@ -1,271 +0,0 @@
import { platform } from "@yaakapp-internal/platform";
import { Icon, LoadingIcon } from "@yaakapp-internal/ui";
import classNames from "classnames";
import { type KeyboardEvent, type ReactNode, useEffect, useRef, useState } from "react";
import { Button } from "./core/Button";
import { IconButton } from "./core/IconButton";
import { PathList, splitPath } from "./core/PathList";
import { PlainInput } from "./core/PlainInput";
export interface ImportSourcePath {
path: string;
kind?: "file" | "folder" | "url";
}
export type ImportSourceDetection =
| { status: "loading" }
| { status: "ok"; importer: string }
| { status: "error"; message: string };
interface Props {
sources: ImportSourcePath[];
detections: Record<string, ImportSourceDetection>;
disabled?: boolean;
onAdd: (sources: ImportSourcePath[]) => void;
onRemove: (path: string) => void;
onError: (err: unknown) => void;
}
/** A bare hostname is a URL; local paths need an absolute or explicit relative prefix. */
export function isImportFilePath(value: string): boolean {
return (
value.startsWith("/") ||
value.startsWith("./") ||
value.startsWith("../") ||
value.startsWith("~/") ||
value.startsWith("\\\\") ||
/^[a-zA-Z]:[\\/]/.test(value)
);
}
/** A typed or prefilled path is a URL unless it looks like a local path; kind is left for the host */
export function toSourcePath(path: string): ImportSourcePath {
return { path, kind: isImportFilePath(path) ? undefined : "url" };
}
export function ImportSourceList({
sources,
detections,
disabled,
onAdd,
onRemove,
onError,
}: Props) {
const ref = useRef<HTMLDivElement>(null);
const [isHovering, setIsHovering] = useState(false);
const [pathInput, setPathInput] = useState("");
const [showPathInput, setShowPathInput] = useState(false);
const pathInputRef = useRef<{ focus: () => void }>(null);
const trimmedPath = pathInput.trim();
const openPathInput = () => {
setShowPathInput(true);
// The add-row menu hands focus back to its trigger as it closes, on a timer, so focus after it
setTimeout(() => pathInputRef.current?.focus(), 50);
};
const closePathInput = () => {
setPathInput("");
setShowPathInput(false);
};
const addPath = () => {
if (!trimmedPath || disabled) return;
onAdd([toSourcePath(trimmedPath)]);
closePathInput();
};
useEffect(() => {
if (disabled) return;
return platform.window.onDragDrop((event) => {
if (event.type === "leave") {
setIsHovering(false);
return;
}
const rect = ref.current?.getBoundingClientRect();
const { x, y } = event.position;
const isOver =
rect != null && x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
if (event.type === "drop") {
if (isOver) onAdd(event.paths.map((path) => ({ path })));
setIsHovering(false);
} else {
setIsHovering(isOver);
}
});
}, [disabled, onAdd]);
const pick = async (directory: boolean) => {
try {
const selected = await platform.dialog.open({
title: directory ? "Select Import Folder" : "Select Import Files",
multiple: true,
directory,
});
if (selected == null) return;
onAdd(selected.map((path) => ({ path, kind: directory ? "folder" : "file" })));
} catch (err) {
onError(err);
}
};
const handlePathKeyDown = (event: KeyboardEvent) => {
if (event.key === "Enter") {
event.preventDefault();
addPath();
} else if (event.key === "Escape") {
event.stopPropagation();
closePathInput();
}
};
const pathInputEl = (
<PlainInput
ref={pathInputRef}
label="URL or file path"
hideLabel
size="sm"
autoFocus
disabled={disabled}
placeholder="Paste a URL or a file path"
onChange={setPathInput}
onKeyDownCapture={handlePathKeyDown}
rightSlot={
<div className="flex items-center gap-1 my-1 mr-1">
{trimmedPath !== "" && (
<Button size="xs" variant="border" onClick={addPath}>
Add
</Button>
)}
<IconButton size="xs" icon="x" title="Cancel" onClick={closePathInput} />
</div>
}
/>
);
if (sources.length === 0) {
return (
<div className="flex-1 flex flex-col gap-2">
<div
ref={ref}
className={classNames(
"flex-1 rounded-lg border min-h-28 flex flex-col items-center justify-center gap-2 px-4 py-5 text-center text-text-subtle",
isHovering ? "border-notice bg-surface-highlight" : "border-dashed border-border",
)}
>
<Icon icon="folder_input" className="text-text-subtlest w-10! h-10! mb-1" />
{isHovering ? (
<span>Drop to add</span>
) : (
<span>
Choose{" "}
<InlineButton disabled={disabled} onClick={() => pick(false)}>
files
</InlineButton>
, a{" "}
<InlineButton disabled={disabled} onClick={() => pick(true)}>
folder
</InlineButton>
, or a{" "}
<InlineButton disabled={disabled} onClick={openPathInput}>
URL
</InlineButton>
, or drag them here
</span>
)}
<span className="text-xs text-text-subtlest">
Supports OpenAPI, Swagger, Postman, Insomnia, Bruno, curl, and Yaak exports
</span>
</div>
{showPathInput && pathInputEl}
</div>
);
}
return (
<PathList
ref={ref}
hovering={isHovering}
disabled={disabled}
onRemove={onRemove}
addLabel="Add files, a folder, or a URL"
addHint="or drop them here"
addItems={[
{ label: "Files", icon: "file", onSelect: () => pick(false) },
{ label: "Folder", icon: "folder", onSelect: () => pick(true) },
{ label: "URL or file path", icon: "globe", onSelect: openPathInput },
]}
items={sources.map((source) => {
const detection = detections[source.path];
return {
path: source.path,
icon: sourceIcon(source),
failed: detection?.status === "error",
subtitle: <DetectionSubtitle path={source.path} detection={detection} />,
};
})}
>
{showPathInput && pathInputEl}
</PathList>
);
}
function DetectionSubtitle({
path,
detection,
}: {
path: string;
detection: ImportSourceDetection | undefined;
}) {
const { parent } = splitPath(path);
if (detection?.status === "loading") {
return (
<>
<LoadingIcon size="xs" />
Detecting format
</>
);
}
if (detection?.status === "error") return detection.message;
return (
<>
{detection?.status === "ok" && <span>{detection.importer}</span>}
{detection?.status === "ok" && parent !== "" && <span>·</span>}
{parent !== "" && <span className="truncate font-mono">{parent}</span>}
</>
);
}
function sourceIcon({ kind }: ImportSourcePath) {
switch (kind) {
case "url":
return "globe";
case "folder":
return "folder";
case "file":
return "file";
case undefined:
return "import";
}
}
export function InlineButton({
children,
disabled,
onClick,
}: {
children: ReactNode;
disabled?: boolean;
onClick: () => void;
}) {
return (
<button
type="button"
disabled={disabled}
className="underline decoration-current/40 underline-offset-3 hocus:decoration-current disabled:opacity-disabled"
onClick={onClick}
>
{children}
</button>
);
}
@@ -0,0 +1,122 @@
import { linter } from "@codemirror/lint";
import type { HttpRequest } from "@yaakapp-internal/models";
import { patchModel } from "@yaakapp-internal/models";
import { Banner, Icon } from "@yaakapp-internal/ui";
import { useCallback, useMemo } from "react";
import { useKeyValue } from "../hooks/useKeyValue";
import { fireAndForget } from "../lib/fireAndForget";
import { textLikelyContainsJsonComments } from "../lib/jsonComments";
import type { DropdownItem } from "./core/Dropdown";
import { Dropdown } from "./core/Dropdown";
import type { EditorProps } from "./core/Editor/Editor";
import { jsonParseLinter } from "./core/Editor/json-lint";
import { Editor } from "./core/Editor/LazyEditor";
import { IconButton } from "./core/IconButton";
import { IconTooltip } from "./core/IconTooltip";
interface Props {
forceUpdateKey: string;
heightMode: EditorProps["heightMode"];
request: HttpRequest;
}
export function JsonBodyEditor({ forceUpdateKey, heightMode, request }: Props) {
const handleChange = useCallback(
(text: string) => patchModel(request, { body: { ...request.body, text } }),
[request],
);
const autoFix = request.body?.sendJsonComments !== true;
const lintExtension = useMemo(
() =>
linter(
jsonParseLinter(
autoFix
? { allowComments: true, allowTrailingCommas: true }
: { allowComments: false, allowTrailingCommas: false },
),
),
[autoFix],
);
const hasComments = useMemo(
() => textLikelyContainsJsonComments(request.body?.text ?? ""),
[request.body?.text],
);
const { value: bannerDismissed, set: setBannerDismissed } = useKeyValue<boolean>({
namespace: "no_sync",
key: ["json-fix-3", request.workspaceId],
fallback: false,
});
const handleToggleAutoFix = useCallback(() => {
const newBody = { ...request.body };
if (autoFix) {
newBody.sendJsonComments = true;
} else {
delete newBody.sendJsonComments;
}
fireAndForget(patchModel(request, { body: newBody }));
}, [request, autoFix]);
const handleDropdownOpen = useCallback(() => {
if (!bannerDismissed) {
fireAndForget(setBannerDismissed(true));
}
}, [bannerDismissed, setBannerDismissed]);
const showBanner = hasComments && autoFix && !bannerDismissed;
const stripMessage = "Automatically strip comments and trailing commas before sending";
const actions = useMemo<EditorProps["actions"]>(
() => [
showBanner && (
<Banner color="notice" className="opacity-100! h-sm py-0! px-2! flex items-center text-xs">
<p className="inline-flex items-center gap-1 min-w-0">
<span className="truncate">Auto-fix enabled</span>
<Icon icon="arrow_right" size="sm" className="opacity-disabled" />
</p>
</Banner>
),
<div key="settings" className="opacity-100! shadow!">
<Dropdown
onOpen={handleDropdownOpen}
items={
[
{
label: "Automatically Fix JSON",
keepOpenOnSelect: true,
onSelect: handleToggleAutoFix,
rightSlot: <IconTooltip content={stripMessage} />,
leftSlot: (
<Icon icon={autoFix ? "check_square_checked" : "check_square_unchecked"} />
),
},
] satisfies DropdownItem[]
}
>
<IconButton size="sm" variant="border" icon="settings" title="JSON Settings" />
</Dropdown>
</div>,
],
[handleDropdownOpen, handleToggleAutoFix, autoFix, showBanner],
);
return (
<Editor
forceUpdateKey={forceUpdateKey}
autocompleteFunctions
autocompleteVariables
placeholder="..."
heightMode={heightMode}
defaultValue={`${request.body?.text ?? ""}`}
language="json"
onChange={handleChange}
stateKey={`json.${request.id}`}
actions={actions}
lintExtension={lintExtension}
/>
);
}
@@ -1,20 +1,15 @@
import { formatSize } from "@yaakapp-internal/lib/formatSize"; import { formatSize } from "@yaakapp-internal/lib/formatSize";
import { import { Banner, Button, HStack, LoadingIcon } from "@yaakapp-internal/ui";
Banner,
Button,
HStack,
LoadingIcon,
AudioViewer,
ImageViewer,
SvgViewer,
VideoViewer,
} from "@yaakapp-internal/ui";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { lazy, Suspense, useEffect, useMemo, useState } from "react"; import { lazy, Suspense, useEffect, useMemo, useState } from "react";
import type { SniffedValue } from "./core/Editor/sniffValue"; import type { SniffedValue } from "./core/Editor/sniffValue";
import { showDialog } from "../lib/dialog"; import { showDialog } from "../lib/dialog";
import { decodeValue, largeValueActions } from "../lib/largeValue"; import { decodeValue, largeValueActions } from "../lib/largeValue";
import { Dropdown } from "./core/Dropdown"; import { Dropdown } from "./core/Dropdown";
import { AudioViewer } from "./responseViewers/AudioViewer";
import { ImageViewer } from "./responseViewers/ImageViewer";
import { SvgViewer } from "./responseViewers/SvgViewer";
import { VideoViewer } from "./responseViewers/VideoViewer";
const PdfViewer = lazy(() => const PdfViewer = lazy(() =>
import("./responseViewers/PdfViewer").then((m) => ({ default: m.PdfViewer })), import("./responseViewers/PdfViewer").then((m) => ({ default: m.PdfViewer })),
@@ -1,8 +1,8 @@
import { SegmentedControl } from "@yaakapp-internal/ui";
import classNames from "classnames"; import classNames from "classnames";
import { useRef, useState } from "react"; import { useRef, useState } from "react";
import type { EditorProps } from "./core/Editor/Editor"; import type { EditorProps } from "./core/Editor/Editor";
import { Editor } from "./core/Editor/LazyEditor"; import { Editor } from "./core/Editor/LazyEditor";
import { SegmentedControl } from "./core/SegmentedControl";
import { Markdown } from "./Markdown"; import { Markdown } from "./Markdown";
type ViewMode = "edit" | "preview"; type ViewMode = "edit" | "preview";
@@ -3,12 +3,12 @@ import { patchModel, workspacesAtom } from "@yaakapp-internal/models";
import { InlineCode, VStack } from "@yaakapp-internal/ui"; import { InlineCode, VStack } from "@yaakapp-internal/ui";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { useState } from "react"; import { useState } from "react";
import { pluralizeCount } from "../lib/pluralize";
import { resolvedModelName } from "../lib/resolvedModelName"; import { resolvedModelName } from "../lib/resolvedModelName";
import { router } from "../lib/router"; import { router } from "../lib/router";
import { showToast } from "../lib/toast"; import { showToast } from "../lib/toast";
import { Button } from "./core/Button"; import { Button } from "./core/Button";
import { Select } from "./core/Select"; import { Select } from "./core/Select";
import { pluralizeCount } from "@yaakapp-internal/lib/pluralize";
interface Props { interface Props {
activeWorkspaceId: string; activeWorkspaceId: string;
-212
View File
@@ -1,212 +0,0 @@
import type { Color } from "@yaakapp-internal/plugins";
import { platform } from "@yaakapp-internal/platform";
import { settingsAtom } from "@yaakapp-internal/models";
import { HeaderSize, Heading, Icon, type IconProps, LoadingIcon } from "@yaakapp-internal/ui";
import classNames from "classnames";
import { useAtomValue } from "jotai";
import { useState } from "react";
import { openWorkspaceFromSyncDir } from "../commands/openWorkspaceFromSyncDir";
import { showDialog } from "../lib/dialog";
import { importData } from "../lib/importData";
import {
createExampleWorkspace,
createFreshWorkspace,
type OnboardingChoice,
recordOnboardingChoice,
} from "../lib/onboarding";
import { showErrorToast } from "../lib/toast";
import { CloneGitRepositoryDialog } from "./CloneGitRepositoryDialog";
import { Button } from "./core/Button";
/** Shown instead of a workspace when there are none. */
export function Onboarding() {
const settings = useAtomValue(settingsAtom);
const { capabilities } = platform;
const canImport = capabilities.plugins;
const showAlreadyUsing = capabilities.localFiles || capabilities.git || canImport;
const [busy, setBusy] = useState<OnboardingChoice | null>(null);
const choose = (choice: OnboardingChoice, run: () => Promise<void> | void) => async () => {
recordOnboardingChoice(choice);
setBusy(choice);
try {
await run();
} catch (err) {
showErrorToast({
id: "onboarding-failed",
title: "Something went wrong",
message: String(err),
});
} finally {
setBusy(null);
}
};
return (
<div className="grid grid-rows-[auto_minmax(0,1fr)] h-full w-full">
<HeaderSize
data-tauri-drag-region
size="lg"
className="x-theme-appHeader bg-surface"
osType={platform.osType()}
hideWindowControls={settings.hideWindowControls}
useNativeTitlebar={settings.useNativeTitlebar}
interfaceScale={settings.interfaceScale}
/>
<div className="overflow-auto px-6 py-10 grid">
<div className="m-auto w-full max-w-lg flex flex-col gap-7">
<div className="flex flex-col gap-1.5">
<Heading>How would you like to get started?</Heading>
<p className="text-text-subtle">
{canImport
? "Bring over existing work, try a real API, or start fresh."
: "Try a real API, or start fresh."}
</p>
</div>
<div className="flex flex-col gap-2">
{canImport && (
<StartOption
color="primary"
icon="folder_input"
title="Migrate from another tool"
description="Postman, Insomnia, Bruno, OpenAPI, or curl"
busy={busy === "import"}
disabled={busy != null}
onClick={choose("import", () => importData.mutateAsync())}
/>
)}
<StartOption
color="info"
icon="flask"
title="Try Yaak with a real API"
description="Ready-made requests you can send right away"
busy={busy === "example"}
disabled={busy != null}
onClick={choose("example", createExampleWorkspace)}
/>
<StartOption
color="success"
icon="plus"
title="Start fresh"
description="An empty workspace for your first request"
busy={busy === "fresh"}
disabled={busy != null}
onClick={choose("fresh", createFreshWorkspace)}
/>
</div>
{showAlreadyUsing && (
<div className="pt-5 border-t border-dashed border-border-subtle flex flex-col items-start gap-2.5">
<span className="text-sm text-text-subtle">Already using Yaak?</span>
<div className="flex flex-wrap gap-2">
{capabilities.localFiles && (
<Button
size="xs"
variant="border"
color="secondary"
leftSlot={<Icon icon="folder_open" size="sm" />}
disabled={busy != null}
onClick={choose("open_folder", async () => {
const dir = await platform.dialog.open({
title: "Select Workspace Directory",
directory: true,
multiple: false,
});
if (dir == null) return;
await openWorkspaceFromSyncDir.mutateAsync(dir);
})}
>
Open folder
</Button>
)}
{capabilities.git && (
<Button
size="xs"
variant="border"
color="secondary"
leftSlot={<Icon icon="git_branch" size="sm" />}
disabled={busy != null}
onClick={choose("clone_git", () => {
showDialog({
id: "clone-git-repository",
size: "md",
title: "Clone Git Repository",
render: ({ hide }) => <CloneGitRepositoryDialog hide={hide} />,
});
})}
>
Clone repository
</Button>
)}
{canImport && (
<Button
size="xs"
variant="border"
color="secondary"
leftSlot={<Icon icon="import" size="sm" />}
disabled={busy != null}
onClick={choose("import_yaak", () => importData.mutateAsync())}
>
Import
</Button>
)}
</div>
</div>
)}
</div>
</div>
</div>
);
}
function StartOption({
color,
icon,
title,
description,
onClick,
busy,
disabled,
}: {
color: Color;
icon: IconProps["icon"];
title: string;
description: string;
onClick: () => void;
busy: boolean;
disabled: boolean;
}) {
return (
<button
type="button"
disabled={disabled}
onClick={onClick}
className={classNames(
"group w-full text-left rounded-lg px-3 py-2.5 border border-border-subtle",
"grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-3.5",
"enabled:hocus:bg-surface-highlight/50 enabled:hocus:border-border",
"outline-border-focus focus-visible:outline-2",
disabled && !busy && "opacity-disabled",
)}
>
{/* The banner theme tints this tile from the theme's own color for each option */}
<div
className={classNames(
`x-theme-banner--${color}`,
"size-10 rounded-md bg-surface-highlight grid place-items-center",
)}
>
{busy ? <LoadingIcon size="sm" /> : <Icon icon={icon} color={color} size="md" />}
</div>
<div className="min-w-0">
<div className="font-semibold text-text">{title}</div>
<div className="text-sm text-text-subtle">{description}</div>
</div>
<Icon
icon="chevron_right"
className="text-text-subtlest group-enabled:group-hover:text-text-subtle group-enabled:group-focus-visible:text-text-subtle"
/>
</button>
);
}
@@ -1,6 +1,6 @@
import type { GrpcConnection } from "@yaakapp-internal/models"; import type { GrpcConnection } from "@yaakapp-internal/models";
import { deleteModel } from "@yaakapp-internal/models"; import { deleteModel } from "@yaakapp-internal/models";
import { HStack, Icon, formatMillis } from "@yaakapp-internal/ui"; import { HStack, Icon } from "@yaakapp-internal/ui";
import { import {
differenceInHours, differenceInHours,
differenceInMinutes, differenceInMinutes,
@@ -9,9 +9,10 @@ import {
isYesterday, isYesterday,
} from "date-fns"; } from "date-fns";
import { useDeleteGrpcConnections } from "../hooks/useDeleteGrpcConnections"; import { useDeleteGrpcConnections } from "../hooks/useDeleteGrpcConnections";
import { pluralizeCount } from "../lib/pluralize";
import { Dropdown, type DropdownItem } from "./core/Dropdown"; import { Dropdown, type DropdownItem } from "./core/Dropdown";
import { formatMillis } from "./core/HttpResponseDurationTag";
import { IconButton } from "./core/IconButton"; import { IconButton } from "./core/IconButton";
import { pluralizeCount } from "@yaakapp-internal/lib/pluralize";
interface Props { interface Props {
connections: GrpcConnection[]; connections: GrpcConnection[];
@@ -1,6 +1,6 @@
import type { HttpResponse } from "@yaakapp-internal/models"; import type { HttpResponse } from "@yaakapp-internal/models";
import { deleteModel } from "@yaakapp-internal/models"; import { deleteModel } from "@yaakapp-internal/models";
import { HStack, Icon, formatMillis, HttpStatusTag, SizeTag } from "@yaakapp-internal/ui"; import { HStack, Icon } from "@yaakapp-internal/ui";
import { import {
differenceInHours, differenceInHours,
differenceInMinutes, differenceInMinutes,
@@ -9,8 +9,13 @@ import {
isYesterday, isYesterday,
} from "date-fns"; } from "date-fns";
import { useDeleteHttpResponses } from "../hooks/useDeleteHttpResponses"; import { useDeleteHttpResponses } from "../hooks/useDeleteHttpResponses";
import { useKeyValue } from "../hooks/useKeyValue";
import { DismissibleBanner } from "./core/DismissibleBanner";
import { Dropdown, type DropdownItem } from "./core/Dropdown"; import { Dropdown, type DropdownItem } from "./core/Dropdown";
import { formatMillis } from "./core/HttpResponseDurationTag";
import { HttpStatusTag } from "./core/HttpStatusTag";
import { IconButton } from "./core/IconButton"; import { IconButton } from "./core/IconButton";
import { SizeTag } from "./core/SizeTag";
interface Props { interface Props {
responses: HttpResponse[]; responses: HttpResponse[];
@@ -25,6 +30,12 @@ export const RecentHttpResponsesDropdown = function ResponsePane({
onPinnedResponseId, onPinnedResponseId,
}: Props) { }: Props) {
const deleteAllResponses = useDeleteHttpResponses(activeResponse?.requestId); const deleteAllResponses = useDeleteHttpResponses(activeResponse?.requestId);
const movedActionsBannerId = "response-actions-moved-to-response-menu-2026-07-02-v2";
const { value: dismissedMovedActions } = useKeyValue<boolean>({
namespace: "global",
key: ["dismiss-banner", movedActionsBannerId],
fallback: false,
});
const latestResponseId = responses[0]?.id ?? "n/a"; const latestResponseId = responses[0]?.id ?? "n/a";
const responseHistoryItems: DropdownItem[] = []; const responseHistoryItems: DropdownItem[] = [];
let lastHistoryGroup: string | null = null; let lastHistoryGroup: string | null = null;
@@ -115,6 +126,20 @@ export const RecentHttpResponsesDropdown = function ResponsePane({
hidden: latestResponseId === activeResponse.id, hidden: latestResponseId === activeResponse.id,
disabled: responses.length === 0, disabled: responses.length === 0,
}, },
{
type: "content",
hidden: dismissedMovedActions === true,
label: (
<DismissibleBanner
id={movedActionsBannerId}
color="info"
size="xs"
className="max-w-72"
>
<p>Copy and save actions moved to the Response tab menu.</p>
</DismissibleBanner>
),
},
{ {
type: "separator", type: "separator",
label: "Recent", label: "Recent",
@@ -1,6 +1,6 @@
import type { WebsocketConnection } from "@yaakapp-internal/models"; import type { WebsocketConnection } from "@yaakapp-internal/models";
import { deleteModel, getModel } from "@yaakapp-internal/models"; import { deleteModel, getModel } from "@yaakapp-internal/models";
import { HStack, Icon, formatMillis } from "@yaakapp-internal/ui"; import { HStack, Icon } from "@yaakapp-internal/ui";
import { import {
differenceInHours, differenceInHours,
differenceInMinutes, differenceInMinutes,
@@ -9,9 +9,10 @@ import {
isYesterday, isYesterday,
} from "date-fns"; } from "date-fns";
import { deleteWebsocketConnections } from "../commands/deleteWebsocketConnections"; import { deleteWebsocketConnections } from "../commands/deleteWebsocketConnections";
import { pluralizeCount } from "../lib/pluralize";
import { Dropdown, type DropdownItem } from "./core/Dropdown"; import { Dropdown, type DropdownItem } from "./core/Dropdown";
import { formatMillis } from "./core/HttpResponseDurationTag";
import { IconButton } from "./core/IconButton"; import { IconButton } from "./core/IconButton";
import { pluralizeCount } from "@yaakapp-internal/lib/pluralize";
interface Props { interface Props {
connections: WebsocketConnection[]; connections: WebsocketConnection[];
@@ -7,7 +7,6 @@ import { getRecentRequests } from "../hooks/useRecentRequests";
import { useRecentWorkspaces } from "../hooks/useRecentWorkspaces"; import { useRecentWorkspaces } from "../hooks/useRecentWorkspaces";
import { fireAndForget } from "../lib/fireAndForget"; import { fireAndForget } from "../lib/fireAndForget";
import { router } from "../lib/router"; import { router } from "../lib/router";
import { Onboarding } from "./Onboarding";
export function RedirectToLatestWorkspace() { export function RedirectToLatestWorkspace() {
const workspaces = useAtomValue(workspacesAtom); const workspaces = useAtomValue(workspacesAtom);
@@ -15,6 +14,10 @@ export function RedirectToLatestWorkspace() {
useEffect(() => { useEffect(() => {
if (workspaces.length === 0 || recentWorkspaces == null) { if (workspaces.length === 0 || recentWorkspaces == null) {
console.log("No workspaces found to redirect to. Skipping.", {
workspaces,
recentWorkspaces,
});
return; return;
} }
@@ -31,21 +34,11 @@ export function RedirectToLatestWorkspace() {
request_id: requestId, request_id: requestId,
}; };
// Whatever created the first workspace may have already navigated into it
const currentId = router.history.location.pathname.match(/^\/workspaces\/([^/]+)/)?.[1];
if (workspaces.some((w) => w.id === currentId)) return;
console.log("Redirecting to workspace", params, search); console.log("Redirecting to workspace", params, search);
await router.navigate({ to: "/workspaces/$workspaceId", params, search }); await router.navigate({ to: "/workspaces/$workspaceId", params, search });
})(), })(),
); );
}, [recentWorkspaces, workspaces, workspaces.length]); }, [recentWorkspaces, workspaces, workspaces.length]);
// The global models are loaded before the router mounts, so an empty list is a real
// first launch (or the last workspace was just deleted), not a store still loading
if (workspaces.length === 0) {
return <Onboarding />;
}
return null; return null;
} }
@@ -0,0 +1,102 @@
import type { HttpResponse } from "@yaakapp-internal/models";
import { lazy, Suspense } from "react";
import { useHttpRequestBody } from "../hooks/useHttpRequestBody";
import { getMimeTypeFromContentType, languageFromContentType } from "../lib/contentType";
import { LoadingIcon } from "@yaakapp-internal/ui";
import { EmptyStateText } from "./EmptyStateText";
import { AudioViewer } from "./responseViewers/AudioViewer";
import { CsvViewer } from "./responseViewers/CsvViewer";
import { ImageViewer } from "./responseViewers/ImageViewer";
import { MultipartViewer } from "./responseViewers/MultipartViewer";
import { SvgViewer } from "./responseViewers/SvgViewer";
import { TextViewer } from "./responseViewers/TextViewer";
import { VideoViewer } from "./responseViewers/VideoViewer";
import { WebPageViewer } from "./responseViewers/WebPageViewer";
const PdfViewer = lazy(() =>
import("./responseViewers/PdfViewer").then((m) => ({ default: m.PdfViewer })),
);
interface Props {
response: HttpResponse;
}
export function RequestBodyViewer({ response }: Props) {
return <RequestBodyViewerInner key={response.id} response={response} />;
}
function RequestBodyViewerInner({ response }: Props) {
const { data, isLoading, error } = useHttpRequestBody(response);
if (isLoading) {
return (
<EmptyStateText>
<LoadingIcon />
</EmptyStateText>
);
}
if (error) {
return <EmptyStateText>Error loading request body: {error.message}</EmptyStateText>;
}
if (data?.bodyText == null || data.bodyText.length === 0) {
return <EmptyStateText>No request body</EmptyStateText>;
}
const { bodyText, body } = data;
// Try to detect language from content-type header that was sent
const contentTypeHeader = response.requestHeaders.find(
(h) => h.name.toLowerCase() === "content-type",
);
const contentType = contentTypeHeader?.value ?? null;
const mimeType = contentType ? getMimeTypeFromContentType(contentType).essence : null;
const language = languageFromContentType(contentType, bodyText);
// Route to appropriate viewer based on content type
if (mimeType?.match(/^multipart/i)) {
const boundary = contentType?.split("boundary=")[1] ?? "unknown";
// Create a copy because parseMultipart may detach the buffer
const bodyCopy = new Uint8Array(body);
return (
<MultipartViewer data={bodyCopy} boundary={boundary} idPrefix={`request.${response.id}`} />
);
}
if (mimeType?.match(/^image\/svg/i)) {
return <SvgViewer text={bodyText} />;
}
if (mimeType?.match(/^image/i)) {
return <ImageViewer data={body.buffer} />;
}
if (mimeType?.match(/^audio/i)) {
return <AudioViewer data={body} />;
}
if (mimeType?.match(/^video/i)) {
return <VideoViewer data={body} />;
}
if (mimeType?.match(/csv|tab-separated/i)) {
return <CsvViewer text={bodyText} />;
}
if (mimeType?.match(/^text\/html/i)) {
return <WebPageViewer html={bodyText} />;
}
if (mimeType?.match(/pdf/i)) {
return (
<Suspense fallback={<LoadingIcon />}>
<PdfViewer data={body} />
</Suspense>
);
}
return (
<TextViewer text={bodyText} language={language} stateKey={`request.body.${response.id}`} />
);
}
@@ -1,20 +1,38 @@
import type { HttpRequest } from "@yaakapp-internal/models"; import type { HttpRequest } from "@yaakapp-internal/models";
import { patchModel, settingsAtom } from "@yaakapp-internal/models"; import { patchModel } from "@yaakapp-internal/models";
import { RequestMethodDropdown as BaseRequestMethodDropdown } from "@yaakapp-internal/ui"; import classNames from "classnames";
import { useAtomValue } from "jotai"; import { memo, useCallback, useMemo } from "react";
import { memo, useCallback } from "react"; import { showPrompt } from "../lib/prompt";
import { Button } from "./core/Button";
import type { DropdownItem } from "./core/Dropdown";
import { HttpMethodTag, HttpMethodTagRaw } from "./core/HttpMethodTag";
import { Icon } from "@yaakapp-internal/ui";
import type { RadioDropdownItem } from "./core/RadioDropdown";
import { RadioDropdown } from "./core/RadioDropdown";
type Props = { type Props = {
request: HttpRequest; request: HttpRequest;
className?: string; className?: string;
}; };
/** The shared method menu, writing to the request and coloured by the user's setting */ const radioItems: RadioDropdownItem<string>[] = [
"GET",
"PUT",
"POST",
"PATCH",
"DELETE",
"OPTIONS",
"QUERY",
"HEAD",
].map((m) => ({
value: m,
label: <HttpMethodTagRaw method={m} />,
}));
export const RequestMethodDropdown = memo(function RequestMethodDropdown({ export const RequestMethodDropdown = memo(function RequestMethodDropdown({
request, request,
className, className,
}: Props) { }: Props) {
const settings = useAtomValue(settingsAtom);
const handleChange = useCallback( const handleChange = useCallback(
async (method: string) => { async (method: string) => {
await patchModel(request, { method }); await patchModel(request, { method });
@@ -22,12 +40,39 @@ export const RequestMethodDropdown = memo(function RequestMethodDropdown({
[request], [request],
); );
const itemsAfter = useMemo<DropdownItem[]>(
() => [
{
key: "custom",
label: "CUSTOM",
leftSlot: <Icon icon="sparkles" />,
onSelect: async () => {
const newMethod = await showPrompt({
id: "custom-method",
label: "Http Method",
title: "Custom Method",
confirmText: "Save",
description: "Enter a custom method name",
placeholder: "CUSTOM",
});
if (newMethod == null) return;
await handleChange(newMethod);
},
},
],
[handleChange],
);
return ( return (
<BaseRequestMethodDropdown <RadioDropdown
method={request.method} value={request.method}
colored={settings.coloredMethods} items={radioItems}
itemsAfter={itemsAfter}
onChange={handleChange} onChange={handleChange}
className={className} >
/> <Button size="xs" className={classNames(className, "text-text-subtle hover:text")}>
<HttpMethodTag request={request} noAlias />
</Button>
</RadioDropdown>
); );
}); });
@@ -1,17 +1,14 @@
import type { HttpResponse } from "@yaakapp-internal/models";
import classNames from "classnames"; import classNames from "classnames";
import { useMemo } from "react"; import { useMemo } from "react";
import type { JSX } from "react/jsx-runtime"; import type { JSX } from "react/jsx-runtime";
import { CountBadge } from "../CountBadge"; import { useHttpResponseEvents } from "../hooks/useHttpResponseEvents";
import { DetailsBanner } from "../DetailsBanner"; import { CountBadge } from "./core/CountBadge";
import { useEditorHost } from "../EditorHost"; import { DetailsBanner } from "./core/DetailsBanner";
import { KeyValueRows } from "../KeyValueRow"; import { KeyValueRow, KeyValueRows } from "./core/KeyValueRow";
import { KeyValueRow } from "./ResponseHeaders";
import type { HttpResponseView } from "./types";
interface Props { interface Props {
response: HttpResponseView; response: HttpResponse;
/** Only the cookies sent or only those received, for a pane that shows one side */
side?: "sent" | "received";
} }
interface ParsedCookie { interface ParsedCookie {
@@ -83,41 +80,45 @@ function parseSetCookieHeader(setCookieHeader: string): ParsedCookie {
return cookie; return cookie;
} }
/** The cookies a response's headers sent and received, the latest value of each name winning */ export function ResponseCookies({ response }: Props) {
export function parseCookieHeaders({ sent, received }: HttpResponseView["cookieHeaders"]) { const { data: events } = useHttpResponseEvents(response);
const sentMap = new Map<string, { name: string; value: string }>();
const receivedMap = new Map<string, ParsedCookie>();
for (const header of sent) { const { sentCookies, receivedCookies } = useMemo(() => {
for (const cookie of parseCookieHeader(header)) { if (!events) return { sentCookies: [], receivedCookies: [] };
sentMap.set(cookie.name, cookie);
// Use Maps to deduplicate by cookie name (latest value wins)
const sentMap = new Map<string, { name: string; value: string }>();
const receivedMap = new Map<string, ParsedCookie>();
for (const event of events) {
const e = event.event;
// Cookie headers sent (header_up with name=cookie)
if (e.type === "header_up" && e.name.toLowerCase() === "cookie") {
const cookies = parseCookieHeader(e.value);
for (const cookie of cookies) {
sentMap.set(cookie.name, cookie);
}
}
// Set-Cookie headers received (header_down with name=set-cookie)
if (e.type === "header_down" && e.name.toLowerCase() === "set-cookie") {
const cookie = parseSetCookieHeader(e.value);
receivedMap.set(cookie.name, cookie);
}
} }
}
for (const header of received) {
const cookie = parseSetCookieHeader(header);
receivedMap.set(cookie.name, cookie);
}
return { return {
sentCookies: Array.from(sentMap.values()), sentCookies: Array.from(sentMap.values()),
receivedCookies: Array.from(receivedMap.values()), receivedCookies: Array.from(receivedMap.values()),
}; };
} }, [events]);
export function ResponseCookies({ response, side }: Props) {
const { useDetailsBannerStoredValue } = useEditorHost();
const { sentCookies, receivedCookies } = useMemo(
() => parseCookieHeaders(response.cookieHeaders),
[response.cookieHeaders],
);
return ( return (
<div className="overflow-auto h-full pb-4 gap-y-3 flex flex-col pr-0.5"> <div className="overflow-auto h-full pb-4 gap-y-3 flex flex-col pr-0.5">
{side !== "received" && (
<DetailsBanner <DetailsBanner
defaultOpen defaultOpen
useStoredValue={useDetailsBannerStoredValue} storageKey={`${response.requestId}.sent_cookies`}
storageKey={`${response.ownerId}.sent_cookies`}
summary={ summary={
<h2 className="flex items-center"> <h2 className="flex items-center">
Sent Cookies <CountBadge showZero count={sentCookies.length} /> Sent Cookies <CountBadge showZero count={sentCookies.length} />
@@ -137,13 +138,10 @@ export function ResponseCookies({ response, side }: Props) {
</KeyValueRows> </KeyValueRows>
)} )}
</DetailsBanner> </DetailsBanner>
)}
{side !== "sent" && (
<DetailsBanner <DetailsBanner
defaultOpen defaultOpen
useStoredValue={useDetailsBannerStoredValue} storageKey={`${response.requestId}.received_cookies`}
storageKey={`${response.ownerId}.received_cookies`}
summary={ summary={
<h2 className="flex items-center"> <h2 className="flex items-center">
Received Cookies <CountBadge showZero count={receivedCookies.length} /> Received Cookies <CountBadge showZero count={receivedCookies.length} />
@@ -218,7 +216,6 @@ export function ResponseCookies({ response, side }: Props) {
</div> </div>
)} )}
</DetailsBanner> </DetailsBanner>
)}
</div> </div>
); );
} }
@@ -0,0 +1,110 @@
import type { HttpResponse } from "@yaakapp-internal/models";
import { format, formatDistanceToNowStrict } from "date-fns";
import { useMemo } from "react";
import { CountBadge } from "./core/CountBadge";
import { DetailsBanner } from "./core/DetailsBanner";
import { IconButton } from "./core/IconButton";
import { KeyValueRow, KeyValueRows } from "./core/KeyValueRow";
import { platform } from "@yaakapp-internal/platform";
interface Props {
response: HttpResponse;
}
export function ResponseHeaders({ response }: Props) {
const responseHeaders = useMemo(
() =>
[...response.headers].sort((a, b) =>
a.name.toLocaleLowerCase().localeCompare(b.name.toLocaleLowerCase()),
),
[response.headers],
);
const requestHeaders = useMemo(
() =>
[...response.requestHeaders].sort((a, b) =>
a.name.toLocaleLowerCase().localeCompare(b.name.toLocaleLowerCase()),
),
[response.requestHeaders],
);
return (
<div className="overflow-auto h-full pb-4 gap-y-3 flex flex-col pr-0.5">
<DetailsBanner storageKey={`${response.requestId}.general`} summary={<h2>Info</h2>}>
<KeyValueRows>
<KeyValueRow labelColor="secondary" label="Sent">
<time
dateTime={new Date(`${response.createdAt}Z`).toISOString()}
title={formatDistanceToNowStrict(`${response.createdAt}Z`, { addSuffix: true })}
>
{format(`${response.createdAt}Z`, "MMM d, yyyy, h:mm:ss a O")}
</time>
</KeyValueRow>
<KeyValueRow labelColor="secondary" label="Request URL">
<div className="flex items-center gap-1">
<span className="select-text cursor-text">{response.url}</span>
<IconButton
iconSize="sm"
className="inline-block w-auto h-auto! opacity-50 hover:opacity-100"
icon="external_link"
onClick={() => platform.openUrl(response.url)}
title="Open in browser"
/>
</div>
</KeyValueRow>
<KeyValueRow labelColor="secondary" label="Remote Address">
{response.remoteAddr ?? <span className="text-text-subtlest">--</span>}
</KeyValueRow>
<KeyValueRow labelColor="secondary" label="Version">
{response.version ?? <span className="text-text-subtlest">--</span>}
</KeyValueRow>
</KeyValueRows>
</DetailsBanner>
<DetailsBanner
storageKey={`${response.requestId}.request_headers`}
summary={
<h2 className="flex items-center">
Request Headers <CountBadge showZero count={requestHeaders.length} />
</h2>
}
>
{requestHeaders.length === 0 ? (
<NoHeaders />
) : (
<KeyValueRows>
{requestHeaders.map((h, i) => (
// oxlint-disable-next-line react/no-array-index-key
<KeyValueRow labelColor="primary" key={i} label={h.name}>
{h.value}
</KeyValueRow>
))}
</KeyValueRows>
)}
</DetailsBanner>
<DetailsBanner
defaultOpen
storageKey={`${response.requestId}.response_headers`}
summary={
<h2 className="flex items-center">
Response Headers <CountBadge showZero count={responseHeaders.length} />
</h2>
}
>
{responseHeaders.length === 0 ? (
<NoHeaders />
) : (
<KeyValueRows>
{responseHeaders.map((h, i) => (
// oxlint-disable-next-line react/no-array-index-key
<KeyValueRow labelColor="info" key={i} label={h.name}>
{h.value}
</KeyValueRow>
))}
</KeyValueRows>
)}
</DetailsBanner>
</div>
);
}
function NoHeaders() {
return <span className="text-text-subtlest text-sm italic">No Headers</span>;
}
+1 -2
View File
@@ -1,8 +1,7 @@
import type { HttpResponse } from "@yaakapp-internal/models"; import type { HttpResponse } from "@yaakapp-internal/models";
import { IconButton } from "./core/IconButton"; import { IconButton } from "./core/IconButton";
import { KeyValueRow } from "./core/KeyValueRow"; import { KeyValueRow, KeyValueRows } from "./core/KeyValueRow";
import { platform } from "@yaakapp-internal/platform"; import { platform } from "@yaakapp-internal/platform";
import { KeyValueRows } from "@yaakapp-internal/ui";
interface Props { interface Props {
response: HttpResponse; response: HttpResponse;
+3 -1
View File
@@ -1,5 +1,5 @@
import { platform } from "@yaakapp-internal/platform"; import { platform } from "@yaakapp-internal/platform";
import { HStack, IconTooltip, Label } from "@yaakapp-internal/ui"; import { HStack } from "@yaakapp-internal/ui";
import classNames from "classnames"; import classNames from "classnames";
import mime from "mime"; import mime from "mime";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
@@ -7,6 +7,8 @@ import { useEffect, useRef, useState } from "react";
import type { ButtonProps } from "./core/Button"; import type { ButtonProps } from "./core/Button";
import { Button } from "./core/Button"; import { Button } from "./core/Button";
import { IconButton } from "./core/IconButton"; import { IconButton } from "./core/IconButton";
import { IconTooltip } from "./core/IconTooltip";
import { Label } from "./core/Label";
type Props = Omit<ButtonProps, "type"> & { type Props = Omit<ButtonProps, "type"> & {
onChange: (value: { filePath: string | null; contentType: string | null }) => void; onChange: (value: { filePath: string | null; contentType: string | null }) => void;
+100 -67
View File
@@ -1,20 +1,14 @@
import { platform } from "@yaakapp-internal/platform"; import { platform } from "@yaakapp-internal/platform";
import { useLicense } from "@yaakapp-internal/license"; import { useLicense } from "@yaakapp-internal/license";
import { pluginsAtom, settingsAtom } from "@yaakapp-internal/models"; import { pluginsAtom, settingsAtom } from "@yaakapp-internal/models";
import { import { HeaderSize, HStack, Icon } from "@yaakapp-internal/ui";
CountBadge, import classNames from "classnames";
SETTINGS_TAB_GENERAL,
SETTINGS_TAB_INTERFACE,
SETTINGS_TAB_LICENSE,
SETTINGS_TAB_THEME,
SettingsDialog,
type SettingsTabDef,
} from "@yaakapp-internal/ui";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { useKeyPressEvent } from "react-use"; import { useKeyPressEvent } from "react-use";
import { appInfo } from "../../lib/appInfo"; import { appInfo } from "../../lib/appInfo";
import { capitalize } from "../../lib/capitalize"; import { capitalize } from "../../lib/capitalize";
import { SettingsAgents } from "./SettingsAgents"; import { CountBadge } from "../core/CountBadge";
import { TabContent, type TabItem, Tabs } from "../core/Tabs/Tabs";
import { SettingsCertificates } from "./SettingsCertificates"; import { SettingsCertificates } from "./SettingsCertificates";
import { SettingsGeneral } from "./SettingsGeneral"; import { SettingsGeneral } from "./SettingsGeneral";
import { SettingsHotkeys } from "./SettingsHotkeys"; import { SettingsHotkeys } from "./SettingsHotkeys";
@@ -30,22 +24,20 @@ interface Props {
hide?: () => void; hide?: () => void;
} }
const TAB_GENERAL = SETTINGS_TAB_GENERAL; const TAB_GENERAL = "general";
const TAB_INTERFACE = SETTINGS_TAB_INTERFACE; const TAB_INTERFACE = "interface";
const TAB_THEME = SETTINGS_TAB_THEME; const TAB_THEME = "theme";
const TAB_SHORTCUTS = "shortcuts"; const TAB_SHORTCUTS = "shortcuts";
const TAB_PROXY = "proxy"; const TAB_PROXY = "proxy";
const TAB_CERTIFICATES = "certificates"; const TAB_CERTIFICATES = "certificates";
const TAB_PLUGINS = "plugins"; const TAB_PLUGINS = "plugins";
const TAB_AGENTS = "agents"; const TAB_LICENSE = "license";
const TAB_LICENSE = SETTINGS_TAB_LICENSE;
const tabs = [ const tabs = [
TAB_GENERAL, TAB_GENERAL,
TAB_THEME, TAB_THEME,
TAB_INTERFACE, TAB_INTERFACE,
TAB_SHORTCUTS, TAB_SHORTCUTS,
TAB_PLUGINS, TAB_PLUGINS,
TAB_AGENTS,
TAB_CERTIFICATES, TAB_CERTIFICATES,
TAB_PROXY, TAB_PROXY,
TAB_LICENSE, TAB_LICENSE,
@@ -66,57 +58,98 @@ export default function Settings({ tab, hide }: Props) {
if (hide == null) await platform.window.close(); if (hide == null) await platform.window.close();
}); });
const tabDefs: Record<SettingsTab, Omit<SettingsTabDef, "value" | "label">> = {
[TAB_GENERAL]: { icon: "settings", content: <SettingsGeneral /> },
[TAB_THEME]: { icon: "palette", content: <SettingsTheme /> },
[TAB_INTERFACE]: { icon: "columns_2", content: <SettingsInterface /> },
[TAB_SHORTCUTS]: { icon: "keyboard", content: <SettingsHotkeys /> },
[TAB_PLUGINS]: {
icon: "puzzle",
rightSlot: <CountBadge count={plugins.filter((p) => p.source !== "bundled").length} />,
content: <SettingsPlugins defaultSubtab={mainTab === TAB_PLUGINS ? subtab : undefined} />,
contentClassName: "h-full grid grid-rows-1",
},
[TAB_AGENTS]: {
icon: "sparkles",
hidden: !platform.capabilities.agents,
content: <SettingsAgents />,
},
[TAB_CERTIFICATES]: {
icon: "shield_check",
rightSlot: <CountBadge count={settings.clientCertificates.length} />,
content: <SettingsCertificates />,
},
[TAB_PROXY]: {
icon: "wifi",
rightSlot: settings.proxy?.type === "enabled" ? <CountBadge count /> : null,
content: <SettingsProxy />,
},
[TAB_LICENSE]: {
icon: "key_round",
hidden: !appInfo.featureLicense,
rightSlot:
licenseCheck.check.data?.status === "personal_use" ? (
<CountBadge count color="notice" />
) : null,
content: <SettingsLicense />,
},
};
return ( return (
<SettingsDialog <div className={classNames("grid grid-rows-[auto_minmax(0,1fr)] h-full")}>
defaultTab={mainTab} {hide ? (
titlebar={ <span />
hide ) : (
? null <HeaderSize
: { data-tauri-drag-region
osType: platform.osType(), ignoreControlsSpacing
hideWindowControls: settings.hideWindowControls, onlyXWindowControl
useNativeTitlebar: settings.useNativeTitlebar, size="md"
interfaceScale: settings.interfaceScale, className="x-theme-appHeader bg-surface text-text-subtle flex items-center justify-center border-b border-border-subtle text-sm font-semibold"
} osType={platform.osType()}
} hideWindowControls={settings.hideWindowControls}
tabs={tabs.map((value) => ({ value, label: capitalize(value), ...tabDefs[value] }))} useNativeTitlebar={settings.useNativeTitlebar}
/> interfaceScale={settings.interfaceScale}
>
<HStack
space={2}
justifyContent="center"
className="w-full h-full grid grid-cols-[1fr_auto] pointer-events-none"
>
<div className={classNames(platform.osType() === "macos" ? "text-center" : "pl-2")}>Settings</div>
</HStack>
</HeaderSize>
)}
<Tabs
layout="horizontal"
defaultValue={mainTab}
addBorders
tabListClassName="min-w-40 bg-surface x-theme-sidebar border-r border-border pl-3"
label="Settings"
tabs={tabs.map(
(value): TabItem => ({
value,
label: capitalize(value),
hidden: !appInfo.featureLicense && value === TAB_LICENSE,
leftSlot:
value === TAB_GENERAL ? (
<Icon icon="settings" className="text-secondary" />
) : value === TAB_THEME ? (
<Icon icon="palette" className="text-secondary" />
) : value === TAB_INTERFACE ? (
<Icon icon="columns_2" className="text-secondary" />
) : value === TAB_SHORTCUTS ? (
<Icon icon="keyboard" className="text-secondary" />
) : value === TAB_CERTIFICATES ? (
<Icon icon="shield_check" className="text-secondary" />
) : value === TAB_PROXY ? (
<Icon icon="wifi" className="text-secondary" />
) : value === TAB_PLUGINS ? (
<Icon icon="puzzle" className="text-secondary" />
) : value === TAB_LICENSE ? (
<Icon icon="key_round" className="text-secondary" />
) : null,
rightSlot:
value === TAB_CERTIFICATES ? (
<CountBadge count={settings.clientCertificates.length} />
) : value === TAB_PLUGINS ? (
<CountBadge count={plugins.filter((p) => p.source !== "bundled").length} />
) : value === TAB_PROXY && settings.proxy?.type === "enabled" ? (
<CountBadge count />
) : value === TAB_LICENSE && licenseCheck.check.data?.status === "personal_use" ? (
<CountBadge count color="notice" />
) : null,
}),
)}
>
<TabContent value={TAB_GENERAL} className="overflow-y-auto h-full px-6 py-4!">
<SettingsGeneral />
</TabContent>
<TabContent value={TAB_INTERFACE} className="overflow-y-auto h-full px-6 py-4!">
<SettingsInterface />
</TabContent>
<TabContent value={TAB_THEME} className="overflow-y-auto h-full px-6 py-4!">
<SettingsTheme />
</TabContent>
<TabContent value={TAB_SHORTCUTS} className="overflow-y-auto h-full px-6 py-4!">
<SettingsHotkeys />
</TabContent>
<TabContent value={TAB_PLUGINS} className="h-full grid grid-rows-1">
<SettingsPlugins defaultSubtab={mainTab === TAB_PLUGINS ? subtab : undefined} />
</TabContent>
<TabContent value={TAB_PROXY} className="overflow-y-auto h-full px-6 py-4!">
<SettingsProxy />
</TabContent>
<TabContent value={TAB_CERTIFICATES} className="overflow-y-auto h-full px-6 py-4!">
<SettingsCertificates />
</TabContent>
<TabContent value={TAB_LICENSE} className="overflow-y-auto h-full px-6 py-4!">
<SettingsLicense />
</TabContent>
</Tabs>
</div>
); );
} }
@@ -1,131 +0,0 @@
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { platform } from "@yaakapp-internal/platform";
import type { AgentSetupStatus, AppMetaData } from "@yaakapp-internal/rpc-schema";
import { Banner, Icon, InlineCode, SegmentedControl, SettingsPage } from "@yaakapp-internal/ui";
import { useEffect } from "react";
import { useKeyValue } from "../../hooks/useKeyValue";
import { usePluginInfos } from "../../hooks/usePluginInfo";
import {
AGENT_CLIENTS,
type AgentClient,
cliSetup,
skillInstallCommand,
} from "../../lib/agentSetup";
import { appInfo } from "../../lib/appInfo";
import { rpc } from "../../lib/rpc";
import { Link } from "../core/Link";
import { SettingCommand, SettingSnippet, SettingsList, SettingsSection } from "../core/SettingRow";
import { DeprecatedPluginBanner } from "./SettingsPlugins";
const CLI_INSTALL_COMMAND = "npm install -g @yaakapp/cli";
const MCP_SERVER_PLUGIN = "@yaak/mcp-server";
export function SettingsAgents() {
const queryClient = useQueryClient();
const { value: storedClient, set: setClient } = useKeyValue<AgentClient>({
key: "agents_setup_client",
fallback: "claude_code",
});
const client = AGENT_CLIENTS.find((c) => c.value === storedClient)?.value ?? "claude_code";
const clientLabel = AGENT_CLIENTS.find((c) => c.value === client)?.label ?? "your agent";
const cliVersion = useQuery({
queryKey: ["cli_version"],
queryFn: async () => (await rpc<AppMetaData>("cmd_metadata")).cliVersion,
initialData: appInfo.cliVersion,
});
const setupStatus = useQuery({
queryKey: ["agent_setup_status", client],
queryFn: () => rpc<AgentSetupStatus>("cmd_agent_setup_status", { agent: client }),
});
const mcpServerPlugin = usePluginInfos().find(({ info }) => info.name === MCP_SERVER_PLUGIN);
useEffect(() => {
return platform.window.onFocusChanged((focused) => {
if (!focused) return;
void queryClient.invalidateQueries({ queryKey: ["cli_version"] });
void queryClient.invalidateQueries({ queryKey: ["agent_setup_status"] });
});
}, [queryClient]);
const cliInstalled = cliVersion.data != null;
const cli = cliSetup(client);
return (
<SettingsPage
title="Agents"
description="Connect AI coding agents like Claude Code and Cursor to Yaak."
>
<SettingsList>
<SettingsSection title={null}>
<div className="pb-4 border-b border-border-subtle">
<SegmentedControl
name="agents_setup_client"
label="Agent"
hideLabel
value={client}
onChange={setClient}
options={AGENT_CLIENTS}
/>
</div>
{cliInstalled ? (
<div className="flex items-center gap-2 py-3 text-sm text-text-subtle border-b border-border-subtle">
<Icon icon="check" size="sm" color="success" />
<span>
Yaak CLI <span className="text-text">{cliVersion.data}</span> is installed.
</span>
</div>
) : (
<div className="py-4 border-b border-border-subtle">
<Banner color="info">
<div className="flex items-center gap-2 text text-text">
<Icon icon="square_terminal" color="info" />
Install the Yaak CLI first
</div>
<p className="mt-1 text-sm text-text-subtle">
Agents launch it to reach Yaak, even with the app closed.
</p>
<SettingSnippet className="mt-3" language="shell" snippet={CLI_INSTALL_COMMAND} />
<div className="mt-3 mb-1 flex items-center gap-4 text-sm">
<Link href="https://yaak.app/docs/cli">Docs</Link>
<span className="text-text-subtlest">
Checks again when you come back to Yaak.
</span>
</div>
</Banner>
</div>
)}
{mcpServerPlugin != null && (
<div className="py-4 border-b border-border-subtle">
<DeprecatedPluginBanner
plugin={mcpServerPlugin.plugin}
name={mcpServerPlugin.info.displayName}
>
The two steps below replace it. Uninstall it once your agent is connected.
</DeprecatedPluginBanner>
</div>
)}
<SettingCommand
title="Add the MCP server"
description={cli.where}
snippet={cli.snippet}
language={cli.language}
disabled={!cliInstalled}
done={setupStatus.data?.mcpServer ? "Added" : null}
/>
<SettingCommand
title="Install the skill"
description={
<>
Lets {clientLabel} run the <InlineCode>yaak</InlineCode> command directly.
</>
}
snippet={skillInstallCommand(client)}
language="shell"
disabled={!cliInstalled}
done={setupStatus.data?.skill ? "Installed" : null}
/>
</SettingsSection>
</SettingsList>
</SettingsPage>
);
}
@@ -1,6 +1,6 @@
import type { ClientCertificate } from "@yaakapp-internal/models"; import type { ClientCertificate } from "@yaakapp-internal/models";
import { patchModel, settingsAtom } from "@yaakapp-internal/models"; import { patchModel, settingsAtom } from "@yaakapp-internal/models";
import { HStack, InlineCode, SettingsPage, VStack } from "@yaakapp-internal/ui"; import { Heading, HStack, InlineCode, VStack } from "@yaakapp-internal/ui";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { useRef } from "react"; import { useRef } from "react";
import { showConfirmDelete } from "../../lib/confirm"; import { showConfirmDelete } from "../../lib/confirm";
@@ -218,19 +218,24 @@ export function SettingsCertificates() {
}; };
return ( return (
<SettingsPage <VStack space={3}>
title="Client Certificates" <div className="mb-3">
description="Add and manage TLS certificates on a per domain basis" <HStack justifyContent="between" alignItems="start">
actions={ <div>
<Button variant="border" size="sm" color="secondary" onClick={handleAdd}> <Heading>Client Certificates</Heading>
Add Certificate <p className="text-text-subtle">
</Button> Add and manage TLS certificates on a per domain basis
} </p>
banner={ </div>
<CommercialUseBanner source="client-certificates" title="Using certificates for work?" /> <Button variant="border" size="sm" color="secondary" onClick={handleAdd}>
} Add Certificate
> </Button>
{certificates.length > 0 ? ( </HStack>
</div>
<CommercialUseBanner source="client-certificates" title="Using certificates for work?" />
{certificates.length > 0 && (
<VStack space={3}> <VStack space={3}>
{certificates.map((cert, index) => ( {certificates.map((cert, index) => (
<CertificateEditor <CertificateEditor
@@ -243,7 +248,7 @@ export function SettingsCertificates() {
/> />
))} ))}
</VStack> </VStack>
) : null} )}
</SettingsPage> </VStack>
); );
} }
@@ -1,17 +1,32 @@
import { settingsAtom } from "@yaakapp-internal/models"; import { patchModel, settingsAtom } from "@yaakapp-internal/models";
import { SettingsGeneral as SharedSettingsGeneral } from "@yaakapp-internal/ui"; import { Heading, VStack } from "@yaakapp-internal/ui";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { useSettingsView } from "../../hooks/useSettingsView"; import { useCheckForUpdates } from "../../hooks/useCheckForUpdates";
import { appInfo } from "../../lib/appInfo";
import { revealInFinderText } from "../../lib/reveal";
import { CargoFeature } from "../CargoFeature";
import { CommercialUseBanner } from "../CommercialUseBanner"; import { CommercialUseBanner } from "../CommercialUseBanner";
import { DismissibleBanner } from "../core/DismissibleBanner"; import { DismissibleBanner } from "../core/DismissibleBanner";
import { IconButton } from "../core/IconButton";
import { platform } from "@yaakapp-internal/platform";
import {
ModelSettingRowBoolean,
ModelSettingSelectControl,
SettingValue,
SettingRow,
SettingRowBoolean,
SettingRowSelect,
SettingsList,
SettingsSection,
} from "../core/SettingRow";
const WORKSPACE_SETTINGS_MOVED_AT = "2026-06-30"; const WORKSPACE_SETTINGS_MOVED_AT = "2026-06-30";
export function SettingsGeneral() { export function SettingsGeneral() {
const settings = useAtomValue(settingsAtom); const settings = useAtomValue(settingsAtom);
const bound = useSettingsView(); const checkForUpdates = useCheckForUpdates();
if (settings == null || bound == null) { if (settings == null) {
return null; return null;
} }
@@ -19,24 +34,147 @@ export function SettingsGeneral() {
settings.createdAt.slice(0, 10) < WORKSPACE_SETTINGS_MOVED_AT; settings.createdAt.slice(0, 10) < WORKSPACE_SETTINGS_MOVED_AT;
return ( return (
<SharedSettingsGeneral <VStack space={1.5} className="mb-4">
view={bound.view} <div>
callbacks={bound.callbacks} <Heading>General</Heading>
banner={<CommercialUseBanner source="settings-general" title="Using Yaak for work?" />} <p className="text-text-subtle">
extraSections={ Configure general settings for update behavior and more.
showWorkspaceSettingsMovedBanner && ( </p>
</div>
<div className="mt-3 mb-5">
<CommercialUseBanner source="settings-general" title="Using Yaak for work?" />
</div>
<SettingsList className="space-y-8">
<CargoFeature feature="updater">
<SettingsSection title="Updates">
<SettingRow
title="Update Channel"
description="Choose whether Yaak should use stable releases or beta releases."
>
<div className="grid grid-cols-[12rem_auto] gap-1">
<ModelSettingSelectControl
model={settings}
modelKey="updateChannel"
label="Update Channel"
selectClassName="w-full!"
options={[
{ label: "Stable", value: "stable" },
{ label: "Beta", value: "beta" },
]}
/>
<IconButton
variant="border"
size="sm"
title="Check for updates"
icon="refresh"
spin={checkForUpdates.isPending}
onClick={() => checkForUpdates.mutateAsync()}
/>
</div>
</SettingRow>
<SettingRowSelect
title="Update Behavior"
description="Choose whether updates are installed automatically or manually."
name="autoupdate"
value={settings.autoupdate ? "auto" : "manual"}
onChange={(v) =>
patchModel(settings, { autoupdate: v === "auto" })
}
options={[
{ label: "Automatic", value: "auto" },
{ label: "Manual", value: "manual" },
]}
/>
<ModelSettingRowBoolean
model={settings}
modelKey="autoDownloadUpdates"
title="Automatically download updates"
description="Download Yaak updates in the background so they are ready to install."
disabled={!settings.autoupdate}
/>
<ModelSettingRowBoolean
model={settings}
modelKey="checkNotifications"
title="Check for notifications"
description="Periodically ping Yaak servers to check for relevant notifications."
/>
<SettingRowBoolean
title="Send anonymous usage statistics"
description="Yaak is local-first and does not collect analytics or usage data."
disabled
checked={false}
onChange={() => {}}
/>
</SettingsSection>
</CargoFeature>
<CargoFeature feature="license">
<SettingsSection title="Feedback">
<SettingRowBoolean
title="Prompt for feedback"
description="Show rare one-time prompts asking how new features are working."
checked={settings.promptFeedback}
onChange={(promptFeedback) => patchModel(settings, { promptFeedback })}
/>
</SettingsSection>
</CargoFeature>
{showWorkspaceSettingsMovedBanner && (
<DismissibleBanner <DismissibleBanner
id="workspace-settings-moved-2026-06-30" id="workspace-settings-moved-2026-06-30"
color="info" color="info"
className="w-full p-4 max-w-xl mr-auto" className="w-full p-4 max-w-xl mr-auto"
> >
<p> <p>
Workspace specific settings have moved to <b>Workspace Settings</b>, accessible from Workspace specific settings have moved to{" "}
the workspace switcher menu. <b>Workspace Settings</b>, accessible from the workspace switcher
menu.
</p> </p>
</DismissibleBanner> </DismissibleBanner>
) )}
}
/> <SettingsSection title="App Info">
<SettingRow title="Version" description="Current Yaak version.">
<SettingValue value={appInfo.version} />
</SettingRow>
<SettingRow
title="Data Directory"
description="Where Yaak stores application data."
controlClassName="min-w-0 max-w-[min(42rem,55vw)] gap-2"
>
<SettingValue
value={appInfo.appDataDir}
actions={[
{
title: revealInFinderText,
icon: "folder_open",
onClick: () => platform.revealItemInDir(appInfo.appDataDir),
},
]}
/>
</SettingRow>
<SettingRow
title="Logs Directory"
description="Where Yaak writes application logs."
controlClassName="min-w-0 max-w-[min(42rem,55vw)] gap-2"
>
<SettingValue
value={appInfo.appLogDir}
actions={[
{
title: revealInFinderText,
icon: "folder_open",
onClick: () => platform.revealItemInDir(appInfo.appLogDir),
},
]}
/>
</SettingRow>
</SettingsSection>
</SettingsList>
</VStack>
); );
} }
@@ -1,8 +1,8 @@
import { patchModel, settingsAtom } from "@yaakapp-internal/models"; import { patchModel, settingsAtom } from "@yaakapp-internal/models";
import { import {
Heading,
HStack, HStack,
Icon, Icon,
SettingsPage,
Table, Table,
TableBody, TableBody,
TableCell, TableCell,
@@ -94,58 +94,59 @@ export function SettingsHotkeys() {
} }
return ( return (
<SettingsPage <VStack space={3} className="mb-4">
title="Keyboard Shortcuts" <div className="mb-3">
description="Click the menu button to add, remove, or reset keyboard shortcuts." <Heading>Keyboard Shortcuts</Heading>
> <p className="text-text-subtle">
<VStack space={3}> Click the menu button to add, remove, or reset keyboard shortcuts.
<PlainInput </p>
label="Filter" </div>
placeholder="Filter shortcuts..." <PlainInput
defaultValue={filter} label="Filter"
onChange={setFilter} placeholder="Filter shortcuts..."
hideLabel defaultValue={filter}
containerClassName="max-w-xs" onChange={setFilter}
/> hideLabel
<Table> containerClassName="max-w-xs"
<TableHead> />
<TableRow> <Table>
<TableHeaderCell>Scope</TableHeaderCell> <TableHead>
<TableHeaderCell>Action</TableHeaderCell> <TableRow>
<TableHeaderCell>Shortcut</TableHeaderCell> <TableHeaderCell>Scope</TableHeaderCell>
<TableHeaderCell></TableHeaderCell> <TableHeaderCell>Action</TableHeaderCell>
</TableRow> <TableHeaderCell>Shortcut</TableHeaderCell>
</TableHead> <TableHeaderCell></TableHeaderCell>
{/* key={filter} forces re-render on filter change to fix Safari table rendering bug */} </TableRow>
<TableBody key={filter}> </TableHead>
{filteredActions.map((action) => ( {/* key={filter} forces re-render on filter change to fix Safari table rendering bug */}
<HotkeyRow <TableBody key={filter}>
key={action} {filteredActions.map((action) => (
action={action} <HotkeyRow
currentKeys={hotkeys[action] ?? []} key={action}
defaultKeys={defaultHotkeys[action]} action={action}
onSave={async (keys) => { currentKeys={hotkeys[action] ?? []}
const newHotkeys = { ...settings.hotkeys }; defaultKeys={defaultHotkeys[action]}
if (arraysEqual(keys, defaultHotkeys[action])) { onSave={async (keys) => {
// Remove from settings if it matches default (use default) const newHotkeys = { ...settings.hotkeys };
delete newHotkeys[action]; if (arraysEqual(keys, defaultHotkeys[action])) {
} else { // Remove from settings if it matches default (use default)
// Store the keys (including empty array to disable)
newHotkeys[action] = keys;
}
await patchModel(settings, { hotkeys: newHotkeys });
}}
onReset={async () => {
const newHotkeys = { ...settings.hotkeys };
delete newHotkeys[action]; delete newHotkeys[action];
await patchModel(settings, { hotkeys: newHotkeys }); } else {
}} // Store the keys (including empty array to disable)
/> newHotkeys[action] = keys;
))} }
</TableBody> await patchModel(settings, { hotkeys: newHotkeys });
</Table> }}
</VStack> onReset={async () => {
</SettingsPage> const newHotkeys = { ...settings.hotkeys };
delete newHotkeys[action];
await patchModel(settings, { hotkeys: newHotkeys });
}}
/>
))}
</TableBody>
</Table>
</VStack>
); );
} }
@@ -1,30 +1,59 @@
import { platform } from "@yaakapp-internal/platform";
import { useFonts } from "@yaakapp-internal/fonts";
import { useLicense } from "@yaakapp-internal/license"; import { useLicense } from "@yaakapp-internal/license";
import type { Settings } from "@yaakapp-internal/models"; import type { EditorKeymap, Settings } from "@yaakapp-internal/models";
import { patchModel, settingsAtom } from "@yaakapp-internal/models"; import { patchModel, settingsAtom } from "@yaakapp-internal/models";
import { SettingsInterface as SharedSettingsInterface, VStack } from "@yaakapp-internal/ui"; import { clamp, Heading, VStack } from "@yaakapp-internal/ui";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { useState } from "react";
import { activeWorkspaceAtom } from "../../hooks/useActiveWorkspace"; import { activeWorkspaceAtom } from "../../hooks/useActiveWorkspace";
import { useSettingsView } from "../../hooks/useSettingsView";
import { showConfirm } from "../../lib/confirm"; import { showConfirm } from "../../lib/confirm";
import { pricingUrl } from "../../lib/pricingUrl"; import { pricingUrl } from "../../lib/pricingUrl";
import { rpc } from "../../lib/rpc";
import { CargoFeature } from "../CargoFeature"; import { CargoFeature } from "../CargoFeature";
import { Button } from "../core/Button";
import { Checkbox } from "../core/Checkbox";
import { Link } from "../core/Link"; import { Link } from "../core/Link";
import { SettingRowBoolean, SettingRowSelect, SettingsSection } from "../core/SettingRow"; import {
ModelSettingRowBoolean,
ModelSettingRowSelect,
SettingRow,
SettingRowBoolean,
SettingRowSelect,
SettingSelectControl,
SettingsList,
SettingsSection,
} from "../core/SettingRow";
const NULL_FONT_VALUE = "__NULL_FONT__";
const fontSizeOptions = [
8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
].map((n) => ({ label: `${n}`, value: `${n}` }));
const keymaps: { value: EditorKeymap; label: string }[] = [
{ value: "default", label: "Default" },
{ value: "vim", label: "Vim" },
{ value: "vscode", label: "VSCode" },
{ value: "emacs", label: "Emacs" },
];
export function SettingsInterface() { export function SettingsInterface() {
const workspace = useAtomValue(activeWorkspaceAtom); const workspace = useAtomValue(activeWorkspaceAtom);
const settings = useAtomValue(settingsAtom); const settings = useAtomValue(settingsAtom);
const bound = useSettingsView(); const fonts = useFonts();
if (settings == null || workspace == null || bound == null) { if (settings == null || workspace == null) {
return null; return null;
} }
return ( return (
<SharedSettingsInterface <VStack space={1.5} className="mb-4">
view={bound.view} <div className="mb-3">
callbacks={bound.callbacks} <Heading>Interface</Heading>
leadingSections={ <p className="text-text-subtle">Tweak settings related to the user interface.</p>
</div>
<SettingsList className="space-y-8">
<SettingsSection title="Workspaces"> <SettingsSection title="Workspaces">
<SettingRowSelect <SettingRowSelect
title="Open workspace behavior" title="Open workspace behavior"
@@ -49,13 +78,151 @@ export function SettingsInterface() {
]} ]}
/> />
</SettingsSection> </SettingsSection>
}
trailingSections={ <SettingsSection title="Fonts">
<SettingRow
title="Interface font"
description="Font used for Yaak interface controls."
controlClassName="gap-1"
>
{fonts.data && (
<SettingSelectControl
name="uiFont"
label="Interface font"
selectClassName="w-72!"
value={settings.interfaceFont ?? NULL_FONT_VALUE}
defaultValue={NULL_FONT_VALUE}
options={[
{ label: "System default", value: NULL_FONT_VALUE },
...fonts.data.uiFonts.map((f) => ({ label: f, value: f })),
...fonts.data.editorFonts.map((f) => ({ label: f, value: f })),
]}
onChange={async (v) => {
const interfaceFont = v === NULL_FONT_VALUE ? null : v;
await patchModel(settings, { interfaceFont });
}}
/>
)}
<SettingSelectControl
name="interfaceFontSize"
label="Interface Font Size"
selectClassName="w-20!"
value={`${settings.interfaceFontSize}`}
defaultValue="14"
options={fontSizeOptions}
onChange={(v) => patchModel(settings, { interfaceFontSize: Number.parseInt(v, 10) })}
/>
</SettingRow>
<SettingRow
title="Editor font"
description="Font used in request and response editors."
controlClassName="gap-1"
>
{fonts.data && (
<SettingSelectControl
name="editorFont"
label="Editor font"
selectClassName="w-72!"
value={settings.editorFont ?? NULL_FONT_VALUE}
defaultValue={NULL_FONT_VALUE}
options={[
{ label: "System default", value: NULL_FONT_VALUE },
...fonts.data.editorFonts.map((f) => ({ label: f, value: f })),
]}
onChange={async (v) => {
const editorFont = v === NULL_FONT_VALUE ? null : v;
await patchModel(settings, { editorFont });
}}
/>
)}
<SettingSelectControl
name="editorFontSize"
label="Editor Font Size"
selectClassName="w-20!"
value={`${settings.editorFontSize}`}
defaultValue="12"
options={fontSizeOptions}
onChange={(v) =>
patchModel(settings, {
editorFontSize: clamp(Number.parseInt(v, 10) || 14, 8, 30),
})
}
/>
</SettingRow>
</SettingsSection>
<SettingsSection title="Editor">
<ModelSettingRowSelect
model={settings}
modelKey="editorKeymap"
title="Editor keymap"
description="Keyboard shortcut preset used by text editors."
options={keymaps}
/>
<ModelSettingRowBoolean
model={settings}
modelKey="editorSoftWrap"
title="Wrap editor lines"
description="Wrap long lines in request and response editors."
/>
<ModelSettingRowBoolean
model={settings}
modelKey="coloredMethods"
title="Colorize request methods"
description="Use method-specific colors for HTTP request methods."
/>
</SettingsSection>
<SettingsSection title="Window">
<NativeTitlebarSetting settings={settings} />
{platform.osType() !== "macos" && (
<ModelSettingRowBoolean
model={settings}
modelKey="hideWindowControls"
title="Hide window controls"
description="Hide the close, maximize, and minimize controls on Windows or Linux."
/>
)}
</SettingsSection>
<CargoFeature feature="license"> <CargoFeature feature="license">
<LicenseSettings settings={settings} /> <LicenseSettings settings={settings} />
</CargoFeature> </CargoFeature>
} </SettingsList>
/> </VStack>
);
}
function NativeTitlebarSetting({ settings }: { settings: Settings }) {
const [nativeTitlebar, setNativeTitlebar] = useState(settings.useNativeTitlebar);
return (
<SettingRow
title="Native title bar"
description="Use the operating system's standard title bar and window controls."
controlClassName="gap-2"
>
<Checkbox
hideLabel
size="md"
checked={nativeTitlebar}
title="Native title bar"
onChange={setNativeTitlebar}
/>
{settings.useNativeTitlebar !== nativeTitlebar && (
<Button
color="primary"
size="xs"
onClick={async () => {
await patchModel(settings, { useNativeTitlebar: nativeTitlebar });
await rpc("cmd_restart");
}}
>
Apply and Restart
</Button>
)}
</SettingRow>
); );
} }
@@ -1,6 +1,17 @@
import { SettingsLicense as SharedSettingsLicense } from "@yaakapp-internal/ui"; import { useLicense } from "@yaakapp-internal/license";
import { useSettingsView } from "../../hooks/useSettingsView"; import { Banner, HStack, Icon, VStack } from "@yaakapp-internal/ui";
import { differenceInDays } from "date-fns";
import { formatDate } from "date-fns/format";
import { useState } from "react";
import { useToggle } from "../../hooks/useToggle";
import { pluralizeCount } from "../../lib/pluralize";
import { pricingUrl } from "../../lib/pricingUrl";
import { CargoFeature } from "../CargoFeature"; import { CargoFeature } from "../CargoFeature";
import { Button } from "../core/Button";
import { Link } from "../core/Link";
import { PlainInput } from "../core/PlainInput";
import { Separator } from "../core/Separator";
import { platform } from "@yaakapp-internal/platform";
export function SettingsLicense() { export function SettingsLicense() {
return ( return (
@@ -11,7 +22,166 @@ export function SettingsLicense() {
} }
function SettingsLicenseCmp() { function SettingsLicenseCmp() {
const bound = useSettingsView(); const { check, activate, deactivate } = useLicense();
if (bound == null) return null; const [key, setKey] = useState<string>("");
return <SharedSettingsLicense view={bound.view} callbacks={bound.callbacks} />; const [activateFormVisible, toggleActivateFormVisible] = useToggle(false);
if (check.isPending) {
return null;
}
const renderBanner = () => {
if (!check.data) return null;
switch (check.data.status) {
case "active":
return <Banner color="success">Your license is active 🥳</Banner>;
case "trialing":
return (
<Banner color="info" className="max-w-lg">
<p className="w-full">
<strong>
{pluralizeCount("day", differenceInDays(check.data.data.end, new Date()))}
</strong>{" "}
left to evaluate Yaak for commercial use.
<br />
<span className="opacity-50">Personal use is always free, forever.</span>
<Separator className="my-2" />
<div className="flex flex-wrap items-center gap-x-2 text-sm text-notice">
<Link noUnderline href={pricingUrl(`app.license.learn.${check.data.status}`)}>
Learn More
</Link>
</div>
</p>
</Banner>
);
case "personal_use":
return (
<Banner color="notice" className="max-w-lg">
<p className="w-full">
Your commercial-use trial has ended.
<br />
<span className="opacity-50">
You may continue using Yaak for personal use only.
<br />A license is required for commercial use.
</span>
<Separator className="my-2" />
<div className="flex flex-wrap items-center gap-x-2 text-sm text-notice">
<Link noUnderline href={pricingUrl(`app.license.learn.${check.data.status}`)}>
Learn More
</Link>
</div>
</p>
</Banner>
);
case "inactive":
return (
<Banner color="danger">
Your license is invalid. Please <Link href="https://yaak.app/dashboard">Sign In</Link>{" "}
for more details
</Banner>
);
case "expired":
return (
<Banner color="notice">
Your license expired{" "}
<strong>{formatDate(check.data.data.periodEnd, "MMMM dd, yyyy")}</strong>. Please{" "}
<Link href="https://yaak.app/dashboard">Resubscribe</Link> to continue receiving
updates.
{check.data.data.changesUrl && (
<>
<br />
<Link href={check.data.data.changesUrl}>What's new in latest builds</Link>
</>
)}
</Banner>
);
case "past_due":
return (
<Banner color="danger">
<strong>Your payment method needs attention.</strong>
<br />
To re-activate your license, please{" "}
<Link href={check.data.data.billingUrl}>update your billing info</Link>.
</Banner>
);
case "error":
return (
<Banner color="danger">
License check failed: {check.data.data.message} (Code: {check.data.data.code})
</Banner>
);
}
};
return (
<div className="flex flex-col gap-6 max-w-xl">
{renderBanner()}
{check.error && <Banner color="danger">{check.error}</Banner>}
{activate.error && <Banner color="danger">{activate.error}</Banner>}
{check.data?.status === "active" ? (
<HStack space={2}>
<Button variant="border" color="secondary" size="sm" onClick={() => deactivate.mutate()}>
Deactivate License
</Button>
<Button
color="secondary"
size="sm"
onClick={() => platform.openUrl("https://yaak.app/dashboard?intent=app.license.support")}
rightSlot={<Icon icon="external_link" />}
>
Direct Support
</Button>
</HStack>
) : (
<HStack space={2}>
<Button variant="border" color="secondary" size="sm" onClick={toggleActivateFormVisible}>
Activate License
</Button>
<Button
size="sm"
color="primary"
rightSlot={<Icon icon="external_link" />}
onClick={() =>
platform.openUrl(pricingUrl(`app.license.purchase.${check.data?.status ?? "unknown"}`))
}
>
Purchase License
</Button>
</HStack>
)}
{activateFormVisible && (
<VStack
as="form"
space={3}
className="max-w-sm"
onSubmit={async (e) => {
e.preventDefault();
await activate.mutateAsync({ licenseKey: key });
toggleActivateFormVisible();
}}
>
<PlainInput
autoFocus
label="License Key"
name="key"
onChange={setKey}
placeholder="YK1-XXXXX-XXXXX-XXXXX-XXXXX"
/>
<Button type="submit" color="primary" size="sm" isLoading={activate.isPending}>
Submit
</Button>
</VStack>
)}
</div>
);
} }
@@ -2,9 +2,13 @@ import { useMutation, useQuery } from "@tanstack/react-query";
import type { Plugin } from "@yaakapp-internal/models"; import type { Plugin } from "@yaakapp-internal/models";
import { patchModel, pluginsAtom } from "@yaakapp-internal/models"; import { patchModel, pluginsAtom } from "@yaakapp-internal/models";
import type { PluginVersion } from "@yaakapp-internal/plugins"; import type { PluginVersion } from "@yaakapp-internal/plugins";
import { checkPluginUpdates, installPlugin, searchPlugins } from "@yaakapp-internal/plugins";
import { import {
Banner, checkPluginUpdates,
installPlugin,
searchPlugins,
uninstallPlugin,
} from "@yaakapp-internal/plugins";
import {
HStack, HStack,
Icon, Icon,
InlineCode, InlineCode,
@@ -16,17 +20,18 @@ import {
TableHeaderCell, TableHeaderCell,
TableRow, TableRow,
useDebouncedValue, useDebouncedValue,
CountBadge,
} from "@yaakapp-internal/ui"; } from "@yaakapp-internal/ui";
import classNames from "classnames"; import classNames from "classnames";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { type ReactNode, useState } from "react"; import { useState } from "react";
import { useInstallPlugin } from "../../hooks/useInstallPlugin"; import { useInstallPlugin } from "../../hooks/useInstallPlugin";
import { usePluginInfo, usePluginInfos } from "../../hooks/usePluginInfo"; import { usePluginInfo } from "../../hooks/usePluginInfo";
import { usePluginsKey, useRefreshPlugins } from "../../hooks/usePlugins"; import { usePluginsKey, useRefreshPlugins } from "../../hooks/usePlugins";
import { usePromptUninstallPlugin } from "../../hooks/useUninstallPlugin"; import { showConfirmDelete } from "../../lib/confirm";
import { minPromiseMillis } from "../../lib/minPromiseMillis";
import { Button } from "../core/Button"; import { Button } from "../core/Button";
import { Checkbox } from "../core/Checkbox"; import { Checkbox } from "../core/Checkbox";
import { CountBadge } from "../core/CountBadge";
import { IconButton } from "../core/IconButton"; import { IconButton } from "../core/IconButton";
import { Link } from "../core/Link"; import { Link } from "../core/Link";
import { PlainInput } from "../core/PlainInput"; import { PlainInput } from "../core/PlainInput";
@@ -200,7 +205,7 @@ function PluginTableRow({
mutationKey: ["install_plugin", name], mutationKey: ["install_plugin", name],
mutationFn: (name: string) => installPlugin(name, null), mutationFn: (name: string) => installPlugin(name, null),
}); });
const uninstall = usePromptUninstallPlugin(plugin?.id ?? null, displayName); const uninstall = usePromptUninstall(plugin?.id ?? null, displayName);
const refreshPlugins = useRefreshPlugins(); const refreshPlugins = useRefreshPlugins();
return ( return (
@@ -291,10 +296,7 @@ function PluginSearch() {
const debouncedQuery = useDebouncedValue(query); const debouncedQuery = useDebouncedValue(query);
const results = useQuery({ const results = useQuery({
queryKey: ["plugins", debouncedQuery], queryKey: ["plugins", debouncedQuery],
queryFn: async () => { queryFn: () => searchPlugins(query),
const { plugins } = await searchPlugins(query);
return { plugins: plugins.filter((p) => p.deprecated == null) };
},
}); });
return ( return (
@@ -347,77 +349,22 @@ function InstalledPlugins({ plugins, className }: { plugins: Plugin[]; className
</EmptyStateText> </EmptyStateText>
</div> </div>
) : ( ) : (
<div className={classNames(className, "h-full grid grid-rows-[auto_minmax(0,1fr)]")}> <Table scrollable className={className}>
<DeprecatedPluginBanners /> <TableHead>
<Table scrollable> <TableRow>
<TableHead> <TableHeaderCell className="w-0" />
<TableRow> <TableHeaderCell>Display Name</TableHeaderCell>
<TableHeaderCell className="w-0" /> <TableHeaderCell>Name</TableHeaderCell>
<TableHeaderCell>Display Name</TableHeaderCell> <TableHeaderCell>Version</TableHeaderCell>
<TableHeaderCell>Name</TableHeaderCell> <TableHeaderCell />
<TableHeaderCell>Version</TableHeaderCell> </TableRow>
<TableHeaderCell /> </TableHead>
</TableRow> <tbody className="divide-y divide-surface-highlight">
</TableHead> {plugins.map((p) => (
<tbody className="divide-y divide-surface-highlight"> <PluginTableRowForInstalledPlugin key={p.id} plugin={p} />
{plugins.map((p) => ( ))}
<PluginTableRowForInstalledPlugin key={p.id} plugin={p} /> </tbody>
))} </Table>
</tbody>
</Table>
</div>
);
}
function DeprecatedPluginBanners() {
const deprecated = usePluginInfos().filter(
({ plugin, info }) => plugin.source !== "bundled" && info.deprecated != null,
);
return (
<div className={classNames("flex flex-col gap-2", deprecated.length > 0 && "pb-3")}>
{deprecated.map(({ plugin, info }) => (
<DeprecatedPluginBanner key={plugin.id} plugin={plugin} name={info.displayName}>
{withInlineCode(info.deprecated ?? "")}
</DeprecatedPluginBanner>
))}
</div>
);
}
/** Backtick spans in a package.json string, set as code. */
function withInlineCode(text: string): ReactNode {
return text
.split("`")
.map((part, i) => (i % 2 === 1 ? <InlineCode key={i}>{part}</InlineCode> : part));
}
export function DeprecatedPluginBanner({
children,
name,
plugin,
}: {
children: ReactNode;
name: string;
plugin: Plugin;
}) {
const uninstall = usePromptUninstallPlugin(plugin.id, name);
return (
<Banner color="info" className="flex items-center gap-4">
<div className="min-w-0 flex-1">
<div className="text text-text">The {name} plugin is deprecated.</div>
<p className="mt-1 text-sm text-text-subtle">{children}</p>
</div>
<Button
size="xs"
variant="border"
title="Uninstall plugin"
className="shrink-0"
isLoading={uninstall?.isPending}
onClick={() => uninstall?.mutate()}
>
Uninstall
</Button>
</Banner>
); );
} }
@@ -446,6 +393,31 @@ function BundledPlugins({ plugins }: { plugins: Plugin[] }) {
); );
} }
function usePromptUninstall(pluginId: string | null, name: string) {
const mut = useMutation({
mutationKey: ["uninstall_plugin", pluginId],
mutationFn: async () => {
if (pluginId == null) return;
const confirmed = await showConfirmDelete({
id: `uninstall-plugin-${pluginId}`,
title: "Uninstall Plugin",
confirmText: "Uninstall",
description: (
<>
Permanently uninstall <InlineCode>{name}</InlineCode>?
</>
),
});
if (confirmed) {
await minPromiseMillis(uninstallPlugin(pluginId), 700);
}
},
});
return pluginId == null ? null : mut;
}
function usePluginUpdates() { function usePluginUpdates() {
return useQuery({ return useQuery({
queryKey: ["plugin_updates", usePluginsKey()], queryKey: ["plugin_updates", usePluginsKey()],
@@ -1,6 +1,6 @@
import { patchModel, settingsAtom } from "@yaakapp-internal/models"; import { patchModel, settingsAtom } from "@yaakapp-internal/models";
import type { ProxySetting } from "@yaakapp-internal/models"; import type { ProxySetting } from "@yaakapp-internal/models";
import { InlineCode, SettingsPage } from "@yaakapp-internal/ui"; import { Heading, InlineCode, VStack } from "@yaakapp-internal/ui";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { CommercialUseBanner } from "../CommercialUseBanner"; import { CommercialUseBanner } from "../CommercialUseBanner";
import { import {
@@ -26,11 +26,15 @@ export function SettingsProxy() {
}; };
return ( return (
<SettingsPage <VStack space={1.5} className="mb-4">
title="Proxy" <div className="mb-3">
description="Configure a proxy server for HTTP requests. Useful for corporate firewalls, debugging traffic, or routing through specific infrastructure." <Heading>Proxy</Heading>
banner={<CommercialUseBanner source="proxy-settings" title="Using a proxy for work?" />} <p className="text-text-subtle">
> Configure a proxy server for HTTP requests. Useful for corporate firewalls, debugging
traffic, or routing through specific infrastructure.
</p>
</div>
<CommercialUseBanner source="proxy-settings" title="Using a proxy for work?" />
<SettingsList className="space-y-8"> <SettingsList className="space-y-8">
<SettingsSection title="Proxy"> <SettingsSection title="Proxy">
<SettingRowSelect <SettingRowSelect
@@ -156,7 +160,7 @@ export function SettingsProxy() {
</> </>
)} )}
</SettingsList> </SettingsList>
</SettingsPage> </VStack>
); );
} }
@@ -1,15 +1,173 @@
import { SettingsTheme as SharedSettingsTheme } from "@yaakapp-internal/ui"; import { patchModel, settingsAtom } from "@yaakapp-internal/models";
import { Heading, HStack, Icon, type IconProps, VStack } from "@yaakapp-internal/ui";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { lazy, Suspense } from "react";
import { activeWorkspaceAtom } from "../../hooks/useActiveWorkspace"; import { activeWorkspaceAtom } from "../../hooks/useActiveWorkspace";
import { useSettingsView } from "../../hooks/useSettingsView"; import { useResolvedAppearance } from "../../hooks/useResolvedAppearance";
import { useResolvedTheme } from "../../hooks/useResolvedTheme";
import type { ButtonProps } from "../core/Button";
import { IconButton } from "../core/IconButton";
import { Link } from "../core/Link";
import type { SelectProps } from "../core/Select";
import {
ModelSettingRowSelect,
SettingRowSelect,
SettingsList,
SettingsSection,
} from "../core/SettingRow";
const Editor = lazy(() => import("../core/Editor/Editor").then((m) => ({ default: m.Editor })));
const buttonColors: ButtonProps["color"][] = [
"primary",
"info",
"success",
"notice",
"warning",
"danger",
"secondary",
"default",
];
const icons: IconProps["icon"][] = [
"info",
"box",
"update",
"alert_triangle",
"arrow_big_right_dash",
"download",
"copy",
"magic_wand",
"settings",
"trash",
"sparkles",
"pencil",
"paste",
"search",
"send_horizontal",
];
export function SettingsTheme() { export function SettingsTheme() {
const workspace = useAtomValue(activeWorkspaceAtom); const workspace = useAtomValue(activeWorkspaceAtom);
const bound = useSettingsView(); const settings = useAtomValue(settingsAtom);
const appearance = useResolvedAppearance();
const activeTheme = useResolvedTheme();
if (workspace == null || bound == null) { if (settings == null || workspace == null || activeTheme.data == null) {
return null; return null;
} }
return <SharedSettingsTheme view={bound.view} callbacks={bound.callbacks} />; const lightThemes: SelectProps<string>["options"] = activeTheme.data.themes
.filter((theme) => !theme.dark)
.map((theme) => ({
label: theme.label,
value: theme.id,
}));
const darkThemes: SelectProps<string>["options"] = activeTheme.data.themes
.filter((theme) => theme.dark)
.map((theme) => ({
label: theme.label,
value: theme.id,
}));
return (
<VStack space={1.5} className="mb-4">
<div className="mb-3">
<Heading>Theme</Heading>
<p className="text-text-subtle">
Make Yaak your own by selecting a theme, or{" "}
<Link href="https://yaak.app/docs/plugin-development/plugins-quick-start">
Create Your Own
</Link>
</p>
</div>
<SettingsList className="space-y-8">
<SettingsSection title="Theme">
<ModelSettingRowSelect
model={settings}
modelKey="appearance"
title="Appearance"
description="Choose whether Yaak follows your system appearance or uses a fixed mode."
options={[
{ label: "Automatic", value: "system" },
{ label: "Light", value: "light" },
{ label: "Dark", value: "dark" },
]}
/>
{(settings.appearance === "system" || settings.appearance === "light") && (
<SettingRowSelect
name="lightTheme"
title="Light theme"
description="Theme used when Yaak is in light mode."
value={activeTheme.data.light.id}
options={lightThemes}
onChange={(themeLight) => patchModel(settings, { themeLight })}
/>
)}
{(settings.appearance === "system" || settings.appearance === "dark") && (
<SettingRowSelect
name="darkTheme"
title="Dark theme"
description="Theme used when Yaak is in dark mode."
value={activeTheme.data.dark.id}
options={darkThemes}
onChange={(themeDark) => patchModel(settings, { themeDark })}
/>
)}
</SettingsSection>
<SettingsSection title="Preview">
<VStack
space={3}
className="mt-4 w-full bg-surface p-3 border border-dashed border-border-subtle rounded-sm overflow-x-auto"
>
<HStack className="text" space={1.5}>
<Icon icon={appearance === "dark" ? "moon" : "sun"} />
<strong>{activeTheme.data.active.label}</strong>
<em>(preview)</em>
</HStack>
<HStack space={1.5} className="w-full">
{buttonColors.map((c, i) => (
<IconButton
key={c}
color={c}
size="2xs"
iconSize="xs"
icon={icons[i % icons.length] ?? "info"}
iconClassName="text"
title={`${c}`}
/>
))}
{buttonColors.map((c, i) => (
<IconButton
key={c}
color={c}
variant="border"
size="2xs"
iconSize="xs"
icon={icons[i % icons.length] ?? "info"}
iconClassName="text"
title={`${c}`}
/>
))}
</HStack>
<Suspense>
<Editor
defaultValue={[
"let foo = { // Demo code editor",
' foo: ("bar" || "baz" ?? \'qux\'),',
" baz: [1, 10.2, null, false, true],",
"};",
].join("\n")}
heightMode="auto"
language="javascript"
stateKey={null}
/>
</Suspense>
</VStack>
</SettingsSection>
</SettingsList>
</VStack>
);
} }
@@ -82,9 +82,10 @@ export function SettingsDropdown() {
}, },
{ {
label: "Install CLI", label: "Install CLI",
hidden: appInfo.cliVersion != null || !platform.capabilities.agents, hidden: appInfo.cliVersion != null,
leftSlot: <Icon icon="square_terminal" />, leftSlot: <Icon icon="square_terminal" />,
onSelect: () => openSettings.mutate("agents"), rightSlot: <Icon icon="external_link" color="secondary" />,
onSelect: () => platform.openUrl("https://yaak.app/docs/cli"),
}, },
{ {
label: "Feedback", label: "Feedback",
+43 -83
View File
@@ -63,10 +63,13 @@ import { isSidebarFocused } from "../lib/scopes";
import { navigateToRequestOrFolderOrWorkspace } from "../lib/setWorkspaceSearchParams"; import { navigateToRequestOrFolderOrWorkspace } from "../lib/setWorkspaceSearchParams";
import type { ContextMenuProps, DropdownItem } from "./core/Dropdown"; import type { ContextMenuProps, DropdownItem } from "./core/Dropdown";
import { ContextMenu, Dropdown } from "./core/Dropdown"; import { ContextMenu, Dropdown } from "./core/Dropdown";
import type { Node as QueryNode, Schema } from "@yaakapp-internal/query"; import type { FieldDef } from "./core/Editor/filter/extension";
import { formatField, parseQuery, QueryMatcher } from "@yaakapp-internal/query"; import { filter } from "./core/Editor/filter/extension";
import { queryFilter } from "@yaakapp-internal/ui/editor"; import type { Ast } from "./core/Editor/filter/query";
import { evaluate, parseQuery } from "./core/Editor/filter/query";
import { formatFieldFilter } from "./core/Editor/filter/format";
import { HttpMethodTag } from "./core/HttpMethodTag"; import { HttpMethodTag } from "./core/HttpMethodTag";
import { HttpStatusTag } from "./core/HttpStatusTag";
import { import {
Icon, Icon,
LoadingIcon, LoadingIcon,
@@ -74,7 +77,6 @@ import {
isSelectedFamily, isSelectedFamily,
selectedIdsFamily, selectedIdsFamily,
InlineCode, InlineCode,
HttpStatusTag,
} from "@yaakapp-internal/ui"; } from "@yaakapp-internal/ui";
import type { TreeNode, TreeHandle, TreeProps, TreeItemProps } from "@yaakapp-internal/ui"; import type { TreeNode, TreeHandle, TreeProps, TreeItemProps } from "@yaakapp-internal/ui";
import { IconButton } from "./core/IconButton"; import { IconButton } from "./core/IconButton";
@@ -110,7 +112,7 @@ function Sidebar({ className }: { className?: string }) {
const activeWorkspaceId = useAtomValue(activeWorkspaceAtom)?.id; const activeWorkspaceId = useAtomValue(activeWorkspaceAtom)?.id;
const treeId = `tree.${activeWorkspaceId ?? "unknown"}`; const treeId = `tree.${activeWorkspaceId ?? "unknown"}`;
const filterText = useAtomValue(sidebarFilterAtom); const filterText = useAtomValue(sidebarFilterAtom);
const [tree, fieldValues, emptyFilterSuggestions] = useAtomValue(sidebarTreeAtom) ?? []; const [tree, allFields, emptyFilterSuggestions] = useAtomValue(sidebarTreeAtom) ?? [];
const wrapperRef = useRef<HTMLElement>(null); const wrapperRef = useRef<HTMLElement>(null);
const treeRef = useRef<TreeHandle>(null); const treeRef = useRef<TreeHandle>(null);
@@ -551,18 +553,18 @@ function Sidebar({ className }: { className?: string }) {
const filterCompartmentMountExtRef = useRef<Extension | null>(null); const filterCompartmentMountExtRef = useRef<Extension | null>(null);
if (filterCompartmentMountExtRef.current == null) { if (filterCompartmentMountExtRef.current == null) {
filterCompartmentMountExtRef.current = filterLanguageCompartmentRef.current.of( filterCompartmentMountExtRef.current = filterLanguageCompartmentRef.current.of(
queryFilter({ schema: sidebarFilterSchema, values: fieldValues }), filter({ fields: allFields ?? [] }),
); );
} }
useEffect(() => { useEffect(() => {
const view = filterRef.current; const view = filterRef.current;
if (!view) return; if (!view) return;
const ext = queryFilter({ schema: sidebarFilterSchema, values: fieldValues }); const ext = filter({ fields: allFields ?? [] });
view.dispatch({ view.dispatch({
effects: filterLanguageCompartmentRef.current.reconfigure(ext), effects: filterLanguageCompartmentRef.current.reconfigure(ext),
}); });
}, [fieldValues]); }, [allFields]);
if (tree == null || hidden) { if (tree == null || hidden) {
return null; return null;
@@ -850,44 +852,16 @@ function setSidebarFilterText(text: string) {
jotaiStore.set(sidebarFilterAtom, { text, key: `${Math.random()}` }); jotaiStore.set(sidebarFilterAtom, { text, key: `${Math.random()}` });
} }
/** function getSidebarSuggestionValue(ast: Ast | null) {
* The fields `getItemFields` fills in, each with what it is and a term using it, as completion
* shows them. Bare words match `getItemText` by word prefix
*/
const sidebarFilterFields: [name: string, info: string, example: string][] = [
["method", "GET, POST, …", "@method:post"],
["url", "Request URL", "@url:*/users*"],
["name", "Request name", '@name:"Get user"'],
["type", "http, grpc or ws", "@type:grpc"],
["folder", "Parent folder", "@folder:auth"],
["grpc_service", "gRPC service", "@grpc_service:*Greeter"],
["grpc_method", "gRPC method", "@grpc_method:SayHello"],
];
const sidebarFilterColumns = sidebarFilterFields.map(([name]) => name);
const sidebarFilterSchema: Schema = {
fields: sidebarFilterFields.map(([name, info, example]) => ({
name,
kind: { type: "text" },
info,
example,
})),
freeText: "fuzzy",
};
function getSidebarSuggestionValue(ast: QueryNode | null, query: string) {
if (ast == null) return null; if (ast == null) return null;
if (ast.type === "Term" || ast.type === "Phrase") { if (ast.type === "Term" || ast.type === "Phrase") {
const value = ast.text.trim(); const value = ast.value.trim();
return value.length > 0 ? value : null; return value.length > 0 ? value : null;
} }
if (ast.type === "Field") { if (ast.type === "Field") {
const raw = const value = ast.value.trim();
ast.value.type === "text"
? ast.value.text
: query.slice(ast.valueSpan.start, ast.valueSpan.end);
const value = raw.trim();
return value.length > 0 ? value : null; return value.length > 0 ? value : null;
} }
@@ -909,7 +883,7 @@ const sidebarSuggestionFieldOrder = [
]; ];
const sidebarTreeAtom = atom< const sidebarTreeAtom = atom<
[TreeNode<SidebarModel>, Record<string, string[]>, SidebarFilterSuggestion[]] | null [TreeNode<SidebarModel>, FieldDef[], SidebarFilterSuggestion[]] | null
>((get) => { >((get) => {
const allModels = get(memoAllPotentialChildrenAtom); const allModels = get(memoAllPotentialChildrenAtom);
const activeWorkspace = get(activeWorkspaceAtom); const activeWorkspace = get(activeWorkspaceAtom);
@@ -930,18 +904,15 @@ const sidebarTreeAtom = atom<
return null; return null;
} }
const suggestionValue = getSidebarSuggestionValue(parseQuery(filter.text), filter.text); const queryAst = parseQuery(filter.text);
const matcher = new QueryMatcher(filter.text, sidebarFilterSchema); const suggestionValue = getSidebarSuggestionValue(queryAst);
// Every request goes into one flat table (its text, then a cell per column), matched in a
// single call after the tree is built
const leaves: TreeNode<SidebarModel>[] = [];
const cells: (string | null)[] = [];
// returns true if this node OR any child matches the filter
const allFields: Record<string, Set<string>> = {}; const allFields: Record<string, Set<string>> = {};
const suggestionFields = new Set<string>(); const suggestionFields = new Set<string>();
const build = (node: TreeNode<SidebarModel>, depth: number) => { const build = (node: TreeNode<SidebarModel>, depth: number): boolean => {
const childItems = childrenMap[node.item.id] ?? []; const childItems = childrenMap[node.item.id] ?? [];
let matchesSelf = true;
const fields = getItemFields(node); const fields = getItemFields(node);
const model = node.item.model; const model = node.item.model;
const isLeafNode = !(model === "folder" || model === "workspace"); const isLeafNode = !(model === "folder" || model === "workspace");
@@ -959,44 +930,38 @@ const sidebarTreeAtom = atom<
} }
} }
if (isLeafNode && !matcher.isEmpty) { if (queryAst != null) {
leaves.push(node); matchesSelf = isLeafNode && evaluate(queryAst, { text: getItemText(node.item), fields });
cells.push(getItemText(node.item));
for (const column of sidebarFilterColumns) cells.push(fields[column] ?? null);
} }
let matchesChild = false;
// Recurse to children // Recurse to children
node.children = !isLeafNode ? [] : undefined; node.children = !isLeafNode ? [] : undefined;
if (node.children != null) { if (node.children != null) {
childItems.sort((a, b) => { childItems.sort((a, b) => {
if (a.sortPriority !== b.sortPriority) { if (a.sortPriority === b.sortPriority) {
return a.sortPriority - b.sortPriority; return a.updatedAt > b.updatedAt ? 1 : -1;
} }
// Keep equal-priority items in a stable order when they are edited. return a.sortPriority - b.sortPriority;
if (a.createdAt !== b.createdAt) {
return a.createdAt > b.createdAt ? 1 : -1;
}
return a.id === b.id ? 0 : a.id > b.id ? 1 : -1;
}); });
for (const item of childItems) { for (const item of childItems) {
const childNode = { item, parent: node, depth }; const childNode = { item, parent: node, depth };
build(childNode, depth + 1); const childMatches = build(childNode, depth + 1);
if (childMatches) {
matchesChild = true;
}
node.children.push(childNode); node.children.push(childNode);
} }
} }
};
// Hide a node IFF nothing in its subtree matches; with no query, nothing is hidden // hide node IFF nothing in its subtree matches
let matched: Set<TreeNode<SidebarModel>> | null = null; const anyMatch = matchesSelf || matchesChild;
const markHidden = (node: TreeNode<SidebarModel>): boolean => { node.hidden = !anyMatch;
let visible = matched == null || matched.has(node);
for (const child of node.children ?? []) { return anyMatch;
if (markHidden(child)) visible = true;
}
node.hidden = !visible;
return visible;
}; };
const root: TreeNode<SidebarModel> = { const root: TreeNode<SidebarModel> = {
@@ -1006,20 +971,15 @@ const sidebarTreeAtom = atom<
depth: 0, depth: 0,
}; };
// Build tree and mark visibility in one pass
build(root, 1); build(root, 1);
if (!matcher.isEmpty) {
const rows = matcher.matchingRows(sidebarFilterColumns, cells);
matched = new Set(Array.from(rows, (i) => leaves[i]!));
}
matcher.free();
markHidden(root);
// Values offered after `@field:`. URLs and names are left out: nearly every one is unique, const fields: FieldDef[] = [];
// so a list of them is noise rather than a shortcut.
const fieldValues: Record<string, string[]> = {};
for (const [name, values] of Object.entries(allFields)) { for (const [name, values] of Object.entries(allFields)) {
if (name === "url" || name === "name") continue; fields.push({
fieldValues[name] = Array.from(values); name,
values: Array.from(values).filter((v) => v.length < 20),
});
} }
const suggestions = Array.from(suggestionFields) const suggestions = Array.from(suggestionFields)
.sort((a, b) => { .sort((a, b) => {
@@ -1030,9 +990,9 @@ const sidebarTreeAtom = atom<
}) })
.map((field) => ({ .map((field) => ({
field, field,
filterText: formatField(field, suggestionValue ?? ""), filterText: formatFieldFilter(field, suggestionValue ?? ""),
})); }));
return [root, fieldValues, suggestions] as const; return [root, fields, suggestions] as const;
}); });
const sidebarGitStatusByModelIdAtom = atom<Record<string, GitStatus>>((get) => { const sidebarGitStatusByModelIdAtom = atom<Record<string, GitStatus>>((get) => {
@@ -1,11 +1,11 @@
import type { Workspace } from "@yaakapp-internal/models"; import type { Workspace } from "@yaakapp-internal/models";
import { patchModel, settingsAtom } from "@yaakapp-internal/models"; import { patchModel, settingsAtom } from "@yaakapp-internal/models";
import { Icon, InlineCode, VStack } from "@yaakapp-internal/ui"; import { HStack, Icon, InlineCode, VStack } from "@yaakapp-internal/ui";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { useState } from "react"; import { useState } from "react";
import { switchWorkspace } from "../commands/switchWorkspace"; import { switchWorkspace } from "../commands/switchWorkspace";
import { Button } from "./core/Button";
import { Checkbox } from "./core/Checkbox"; import { Checkbox } from "./core/Checkbox";
import { DialogFooter } from "./core/Dialog";
interface Props { interface Props {
hide: () => void; hide: () => void;
@@ -16,33 +16,45 @@ export function SwitchWorkspaceDialog({ hide, workspace }: Props) {
const settings = useAtomValue(settingsAtom); const settings = useAtomValue(settingsAtom);
const [remember, setRemember] = useState<boolean>(false); const [remember, setRemember] = useState<boolean>(false);
const open = async (inNewWindow: boolean) => {
hide();
switchWorkspace.mutate({ workspaceId: workspace.id, inNewWindow });
if (remember) {
await patchModel(settings, { openWorkspaceNewWindow: inNewWindow });
}
};
return ( return (
<VStack space={3}> <VStack space={3}>
<p> <p>
Where would you like to open <InlineCode>{workspace.name}</InlineCode>? Where would you like to open <InlineCode>{workspace.name}</InlineCode>?
</p> </p>
<HStack space={2} justifyContent="start" className="flex-row-reverse">
<Button
className="focus"
color="primary"
onClick={async () => {
hide();
switchWorkspace.mutate({ workspaceId: workspace.id, inNewWindow: false });
if (remember) {
await patchModel(settings, { openWorkspaceNewWindow: false });
}
}}
>
This Window
</Button>
<Button
className="focus"
color="secondary"
rightSlot={<Icon icon="external_link" />}
onClick={async () => {
hide();
switchWorkspace.mutate({ workspaceId: workspace.id, inNewWindow: true });
if (remember) {
await patchModel(settings, { openWorkspaceNewWindow: true });
}
}}
>
New Window
</Button>
</HStack>
{settings && ( {settings && (
<Checkbox checked={remember} title="Remember my choice" onChange={setRemember} /> <HStack justifyContent="end">
<Checkbox checked={remember} title="Remember my choice" onChange={setRemember} />
</HStack>
)} )}
<DialogFooter
inline
actions={[
{
label: "New Window",
rightSlot: <Icon icon="external_link" />,
onClick: () => open(true),
},
{ label: "This Window", color: "primary", autoFocus: true, onClick: () => open(false) },
]}
/>
</VStack> </VStack>
); );
} }
@@ -59,6 +59,7 @@ export function SyncToFilesystemSetting({
)} )}
<SettingRowDirectory <SettingRowDirectory
highlightKey="sync_dir"
title="Local directory sync" title="Local directory sync"
description="Sync data to a folder for backup and Git integration." description="Sync data to a folder for backup and Git integration."
filePath={value.filePath} filePath={value.filePath}
@@ -1,152 +0,0 @@
// @vitest-environment happy-dom
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";
import type { Workspace } from "@yaakapp-internal/models";
import type { TemplateFunction } from "@yaakapp-internal/plugins";
import type { Tokens } from "@yaakapp-internal/templates";
import { act, type ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeAll, beforeEach, expect, test, vi } from "vite-plus/test";
import { TemplateFunctionDialog } from "./TemplateFunctionDialog";
interface FormProps {
data: Record<string, string | boolean>;
onChange: (values: Record<string, string | boolean>) => void;
}
const mocks = vi.hoisted(() => ({
parse: vi.fn<(text: string) => Tokens>(),
print: vi.fn<(tokens: Tokens) => Promise<string>>(),
serialize: vi.fn<(tokens: Tokens) => { data: string }>(),
preview: vi.fn<({ template }: { template: string }) => { data: string }>(),
form: null as FormProps | null,
config: {
name: "timestamp.format",
args: [
{ type: "text", name: "date" },
{ type: "text", name: "format" },
],
} as TemplateFunction,
}));
vi.mock("@yaakapp-internal/templates", () => ({ parseTemplate: mocks.parse }));
vi.mock("@yaakapp-internal/ui", () => ({
HStack: ({ children }: { children: ReactNode }) => <div>{children}</div>,
InlineCode: "code",
LoadingIcon: () => null,
useDebouncedValue: (value: string) => value,
}));
vi.mock("../hooks/useActiveWorkspace", () => ({ activeWorkspaceAtom: null }));
vi.mock("../hooks/useRenderTemplate", () => ({ useRenderTemplate: mocks.preview }));
vi.mock("../hooks/useTemplateFunctionConfig", () => ({
useTemplateFunctionConfig: () => ({ data: mocks.config }),
}));
vi.mock("../hooks/useTemplateTokensToString", () => ({
templateTokensToString: mocks.print,
useTemplateTokensToString: mocks.serialize,
}));
vi.mock("../lib/dialog", () => ({ showDialog: vi.fn() }));
vi.mock("../lib/encryption", () => ({ convertTemplateToInsecure: vi.fn() }));
vi.mock("../lib/jotai", () => ({ jotaiStore: { get: vi.fn() } }));
vi.mock("../lib/setupOrConfigureEncryption", () => ({ setupOrConfigureEncryption: vi.fn() }));
vi.mock("./core/Dialog", () => ({ DialogFooter: () => <button type="submit">Save</button> }));
vi.mock("./core/IconButton", () => ({ IconButton: () => <button type="button" /> }));
vi.mock("./core/PlainInput", () => ({ PlainInput: () => null }));
vi.mock("./DynamicForm", () => ({
DYNAMIC_FORM_NULL_ARG: "__NULL__",
DynamicForm: (props: FormProps) => {
mocks.form = props;
return <input aria-label="Timestamp" readOnly value={String(props.data.date ?? "")} />;
},
}));
beforeAll(async () => {
const base = pathToFileURL(
resolve(import.meta.dirname, "../../../crates/yaak-templates/pkg") + "/",
);
const bindings = await import(new URL("yaak_templates_bg.js", base).href);
const { instance } = await WebAssembly.instantiate(
await readFile(new URL("yaak_templates_bg.wasm", base)),
{ "./yaak_templates_bg.js": bindings },
);
bindings.__wbg_set_wasm(instance.exports);
(instance.exports.__wbindgen_start as () => void)();
mocks.parse.mockImplementation(bindings.parse_template);
});
let root: Root;
let host: HTMLDivElement;
beforeEach(() => {
vi.clearAllMocks();
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
mocks.form = null;
// The transport returns an opaque string. Carry the AST as JSON so the assertions can
// inspect what Preview and Save receive, without duplicating the backend's printer.
mocks.serialize.mockImplementation((tokens) => ({ data: JSON.stringify(tokens) }));
mocks.preview.mockImplementation(({ template }) => ({ data: template }));
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
});
afterEach(async () => {
await act(async () => root.unmount());
host.remove();
vi.unstubAllGlobals();
});
function functionValue(tokens: Tokens) {
const first = tokens.tokens[0];
if (first?.type !== "tag" || first.val.type !== "fn") throw new Error("Expected function");
return first.val;
}
test.each([
["timestamp.offset(expression='-1h')", "${[ timestamp.offset(expression='-1h') ]}"],
["date_var", "${[ date_var ]}"],
["dates.previous", "${[ dates.previous ]}"],
["'${[ date_var ]}'", "${[ date_var ]}"],
])("Preview and Save preserve %s until that input changes", async (expression, display) => {
const initialTokens = mocks.parse(`\${[ timestamp.format(date=${expression}, format='HH:mm') ]}`);
const originalDate = functionValue(initialTokens).args[0];
const saved = vi.fn<(value: string) => void>();
mocks.print.mockResolvedValue(display);
await act(async () =>
root.render(
<TemplateFunctionDialog
templateFunction={mocks.config}
initialTokens={initialTokens}
model={{ id: "wk_test" } as Workspace}
onChange={saved}
hide={() => {}}
/>,
),
);
expect(host.querySelector<HTMLInputElement>("input")?.value).toBe(display);
async function submit() {
const form = host.querySelector("form");
if (form == null) throw new Error("Dialog did not initialize");
await act(async () => {
form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
});
const value = saved.mock.calls.at(-1)?.[0];
expect(value).toBe(mocks.preview.mock.calls.at(-1)?.[0].template);
return functionValue(JSON.parse(value ?? "null") as Tokens).args;
}
expect((await submit())[0]).toEqual(originalDate);
await act(async () => mocks.form?.onChange({ ...mocks.form.data, format: "yyyy" }));
expect(await submit()).toEqual([
originalDate,
{ name: "format", value: { type: "str", text: "yyyy" } },
]);
const edited = "${[ timestamp.offset(expression='-2h') ]}";
await act(async () => mocks.form?.onChange({ ...mocks.form.data, date: edited }));
expect((await submit())[0]).toEqual({ name: "date", value: { type: "str", text: edited } });
await act(async () => mocks.form?.onChange({ ...mocks.form.data, date: "" }));
expect((await submit())[0]).toEqual({ name: "date", value: { type: "str", text: "" } });
});
@@ -11,7 +11,7 @@ import type { FnArg, Tokens } from "@yaakapp-internal/templates";
import { parseTemplate } from "@yaakapp-internal/templates"; import { parseTemplate } from "@yaakapp-internal/templates";
import { HStack, InlineCode, LoadingIcon, useDebouncedValue } from "@yaakapp-internal/ui"; import { HStack, InlineCode, LoadingIcon, useDebouncedValue } from "@yaakapp-internal/ui";
import classNames from "classnames"; import classNames from "classnames";
import { useEffect, useId, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { activeWorkspaceAtom } from "../hooks/useActiveWorkspace"; import { activeWorkspaceAtom } from "../hooks/useActiveWorkspace";
import { useRenderTemplate } from "../hooks/useRenderTemplate"; import { useRenderTemplate } from "../hooks/useRenderTemplate";
import { useTemplateFunctionConfig } from "../hooks/useTemplateFunctionConfig"; import { useTemplateFunctionConfig } from "../hooks/useTemplateFunctionConfig";
@@ -24,11 +24,8 @@ import { showDialog } from "../lib/dialog";
import { convertTemplateToInsecure } from "../lib/encryption"; import { convertTemplateToInsecure } from "../lib/encryption";
import { jotaiStore } from "../lib/jotai"; import { jotaiStore } from "../lib/jotai";
import { setupOrConfigureEncryption } from "../lib/setupOrConfigureEncryption"; import { setupOrConfigureEncryption } from "../lib/setupOrConfigureEncryption";
import { import { Button } from "./core/Button";
collectEditableArgumentValues, import { collectArgumentValues } from "./core/Editor/twig/util";
preserveUnchangedArgumentExpressions,
} from "../lib/templateFunctionArguments";
import { DialogFooter } from "./core/Dialog";
import { IconButton } from "./core/IconButton"; import { IconButton } from "./core/IconButton";
import { PlainInput } from "./core/PlainInput"; import { PlainInput } from "./core/PlainInput";
import { DYNAMIC_FORM_NULL_ARG, DynamicForm } from "./DynamicForm"; import { DYNAMIC_FORM_NULL_ARG, DynamicForm } from "./DynamicForm";
@@ -51,11 +48,7 @@ export function TemplateFunctionDialog({ initialTokens, templateFunction, ...pro
} }
(async () => { (async () => {
const initial = await collectEditableArgumentValues( const initial = collectArgumentValues(initialTokens, templateFunction);
initialTokens,
templateFunction,
templateTokensToString,
);
// HACK: Replace the secure() function's encrypted `value` arg with the decrypted version so // HACK: Replace the secure() function's encrypted `value` arg with the decrypted version so
// we can display it in the editor input. // we can display it in the editor input.
@@ -81,7 +74,6 @@ export function TemplateFunctionDialog({ initialTokens, templateFunction, ...pro
<InitializedTemplateFunctionDialog <InitializedTemplateFunctionDialog
{...props} {...props}
templateFunction={templateFunction} templateFunction={templateFunction}
initialTokens={initialTokens}
initialArgValues={initialArgValues} initialArgValues={initialArgValues}
/> />
); );
@@ -90,17 +82,15 @@ export function TemplateFunctionDialog({ initialTokens, templateFunction, ...pro
function InitializedTemplateFunctionDialog({ function InitializedTemplateFunctionDialog({
templateFunction: { name, previewType: ogPreviewType }, templateFunction: { name, previewType: ogPreviewType },
initialArgValues, initialArgValues,
initialTokens,
hide, hide,
onChange, onChange,
model, model,
}: Props & { }: Omit<Props, "initialTokens"> & {
initialArgValues: Record<string, string | boolean>; initialArgValues: Record<string, string | boolean>;
}) { }) {
const previewType = ogPreviewType == null ? "live" : ogPreviewType; const previewType = ogPreviewType == null ? "live" : ogPreviewType;
const [showSecretsInPreview, toggleShowSecretsInPreview] = useToggle(false); const [showSecretsInPreview, toggleShowSecretsInPreview] = useToggle(false);
const [argValues, setArgValues] = useState<Record<string, string | boolean>>(initialArgValues); const [argValues, setArgValues] = useState<Record<string, string | boolean>>(initialArgValues);
const formId = useId();
const tokens: Tokens = useMemo(() => { const tokens: Tokens = useMemo(() => {
const argTokens: FnArg[] = Object.keys(argValues).map((name) => ({ const argTokens: FnArg[] = Object.keys(argValues).map((name) => ({
@@ -120,17 +110,12 @@ function InitializedTemplateFunctionDialog({
val: { val: {
type: "fn", type: "fn",
name, name,
args: preserveUnchangedArgumentExpressions( args: argTokens,
argTokens,
initialTokens,
initialArgValues,
argValues,
),
}, },
}, },
], ],
}; };
}, [argValues, initialArgValues, initialTokens, name]); }, [argValues, name]);
const tagText = useTemplateTokensToString(tokens); const tagText = useTemplateTokensToString(tokens);
const templateFunction = useTemplateFunctionConfig(name, argValues, model); const templateFunction = useTemplateFunctionConfig(name, argValues, model);
@@ -175,14 +160,13 @@ function InitializedTemplateFunctionDialog({
return ( return (
<form <form
id={formId} className="grid grid-rows-[minmax(0,1fr)_auto_auto] h-full max-h-[90vh]"
className="grid grid-rows-[minmax(0,1fr)_auto] h-full"
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
handleDone(); handleDone();
}} }}
> >
<div className="overflow-y-auto h-full"> <div className="overflow-y-auto h-full px-6">
{name === "secure" ? ( {name === "secure" ? (
<PlainInput <PlainInput
required required
@@ -204,71 +188,75 @@ function InitializedTemplateFunctionDialog({
/> />
)} )}
</div> </div>
{previewType !== "none" ? ( <div className="px-6 border-t border-t-border pt-3 pb-6 bg-surface-highlight w-full flex flex-col gap-4">
<div className="w-full grid grid-cols-1 grid-rows-[auto_auto] border-t border-t-border pt-3"> {previewType !== "none" ? (
<HStack space={0.5}> <div className="w-full grid grid-cols-1 grid-rows-[auto_auto]">
<HStack className="text-sm text-text-subtle" space={1.5}> <HStack space={0.5}>
Rendered Preview <HStack className="text-sm text-text-subtle" space={1.5}>
{rendered.isLoading && <LoadingIcon size="xs" />} Rendered Preview
</HStack> {rendered.isLoading && <LoadingIcon size="xs" />}
<IconButton </HStack>
size="xs"
iconSize="sm"
icon={showSecretsInPreview ? "lock" : "lock_open"}
title={showSecretsInPreview ? "Show preview" : "Hide preview"}
onClick={toggleShowSecretsInPreview}
className={classNames(
"ml-auto text-text-subtlest",
!dataContainsSecrets && "invisible",
)}
/>
</HStack>
<div className="relative w-full max-h-40">
<InlineCode
className={classNames(
"block whitespace-pre-wrap select-text! cursor-text max-h-40 overflow-auto hide-scrollbars border-text-subtlest!",
tooLarge && "italic text-danger",
)}
>
{rendered.error || tagText.error ? (
<em className="text-danger">
{`${rendered.error || tagText.error}`.replace(/^Render Error: /, "")}
</em>
) : dataContainsSecrets && !showSecretsInPreview ? (
<span className="italic text-text-subtle">
------ sensitive values hidden ------
</span>
) : tooLarge ? (
"too large to preview"
) : (
rendered.data || <>&nbsp;</>
)}
</InlineCode>
<div className="absolute right-0.5 top-0 bottom-0 flex items-center">
<IconButton <IconButton
size="xs" size="xs"
icon="refresh" iconSize="sm"
className="text-text-subtle" icon={showSecretsInPreview ? "lock" : "lock_open"}
title="Refresh preview" title={showSecretsInPreview ? "Show preview" : "Hide preview"}
spin={rendered.isPending} onClick={toggleShowSecretsInPreview}
onClick={() => { className={classNames(
setRenderKey(new Date().toISOString()); "ml-auto text-text-subtlest",
}} !dataContainsSecrets && "invisible",
)}
/> />
</HStack>
<div className="relative w-full max-h-40">
<InlineCode
className={classNames(
"block whitespace-pre-wrap select-text! cursor-text max-h-40 overflow-auto hide-scrollbars border-text-subtlest!",
tooLarge && "italic text-danger",
)}
>
{rendered.error || tagText.error ? (
<em className="text-danger">
{`${rendered.error || tagText.error}`.replace(/^Render Error: /, "")}
</em>
) : dataContainsSecrets && !showSecretsInPreview ? (
<span className="italic text-text-subtle">
------ sensitive values hidden ------
</span>
) : tooLarge ? (
"too large to preview"
) : (
rendered.data || <>&nbsp;</>
)}
</InlineCode>
<div className="absolute right-0.5 top-0 bottom-0 flex items-center">
<IconButton
size="xs"
icon="refresh"
className="text-text-subtle"
title="Refresh preview"
spin={rendered.isPending}
onClick={() => {
setRenderKey(new Date().toISOString());
}}
/>
</div>
</div> </div>
</div> </div>
) : (
<span />
)}
<div className="flex justify-stretch w-full grow gap-2 *:flex-1">
{templateFunction.data.name === "secure" && (
<Button variant="border" color="secondary" onClick={setupOrConfigureEncryption}>
Reveal Encryption Key
</Button>
)}
<Button type="submit" color="primary">
Save
</Button>
</div> </div>
) : ( </div>
<span />
)}
<DialogFooter
actions={[
...(templateFunction.data.name === "secure"
? [{ label: "Reveal Encryption Key", onClick: setupOrConfigureEncryption }]
: []),
{ label: "Save", color: "primary", form: formId },
]}
/>
</form> </form>
); );
} }
@@ -284,6 +272,7 @@ TemplateFunctionDialog.show = (
id: `template-function-${Math.random()}`, // Allow multiple at once id: `template-function-${Math.random()}`, // Allow multiple at once
size: "md", size: "md",
className: "h-240", className: "h-240",
noPadding: true,
title: <InlineCode>{fn.name}(…)</InlineCode>, title: <InlineCode>{fn.name}(…)</InlineCode>,
description: fn.description, description: fn.description,
render: ({ hide }) => { render: ({ hide }) => {
+41 -4
View File
@@ -1,6 +1,43 @@
import { Toasts as BaseToasts } from "@yaakapp-internal/ui"; import { useAtomValue } from "jotai";
import { showErrorDialog } from "./ErrorBoundary"; import { AnimatePresence } from "motion/react";
import type { ReactNode } from "react";
import { hideToast, toastsAtom } from "../lib/toast";
import { Toast, type ToastProps } from "./core/Toast";
import { ErrorBoundary } from "./ErrorBoundary";
import { Portal } from "@yaakapp-internal/ui";
export type { ToastInstance } from "@yaakapp-internal/ui"; export type ToastInstance = {
id: string;
uniqueKey: string;
message: ReactNode;
timeout: 3000 | 5000 | 8000 | (number & {}) | null;
onClose?: ToastProps["onClose"];
} & Omit<ToastProps, "onClose" | "open" | "children" | "timeout">;
export const Toasts = () => <BaseToasts onShowError={showErrorDialog} />; export const Toasts = () => {
const toasts = useAtomValue(toastsAtom);
return (
<Portal name="toasts">
<div className="absolute right-0 bottom-0 z-50">
<AnimatePresence>
{toasts.map((toast: ToastInstance) => {
const { message, uniqueKey, ...props } = toast;
return (
<ErrorBoundary key={uniqueKey} name={`Toast ${uniqueKey}`}>
<Toast
open
{...props}
// We call onClose inside actions.hide instead of passing to toast so that
// it gets called from external close calls as well
onClose={() => hideToast(toast)}
>
{message}
</Toast>
</ErrorBoundary>
);
})}
</AnimatePresence>
</div>
</Portal>
);
};
+105 -6
View File
@@ -1,14 +1,113 @@
import { UrlBar as BaseUrlBar, type UrlBarProps } from "@yaakapp-internal/ui"; import type { HttpRequest } from "@yaakapp-internal/models";
import { memo } from "react"; import type { IconProps } from "@yaakapp-internal/ui";
import { HStack } from "@yaakapp-internal/ui";
import classNames from "classnames";
import type { FormEvent, ReactNode } from "react";
import { memo, useCallback, useRef, useState } from "react";
import { useHotKey } from "../hooks/useHotKey";
import { IconButton } from "./core/IconButton";
import type { InputHandle, InputProps } from "./core/Input";
import { Input } from "./core/Input";
type Props = Omit<UrlBarProps, "sendHotkeyAction" | "focusHotkeyAction" | "readOnly"> & { type Props = Pick<HttpRequest, "url"> & {
className?: string;
placeholder: string;
onSend: () => void; onSend: () => void;
onUrlChange: (url: string) => void; onUrlChange: (url: string) => void;
onPaste?: (v: string) => void;
onPasteOverwrite?: InputProps["onPasteOverwrite"];
onCancel: () => void; onCancel: () => void;
submitIcon?: IconProps["icon"] | null;
isLoading: boolean; isLoading: boolean;
forceUpdateKey: string;
rightSlot?: ReactNode;
leftSlot?: ReactNode;
autocomplete?: InputProps["autocomplete"];
stateKey: InputProps["stateKey"];
}; };
/** The shared URL bar, sending and focusing on the client's hotkeys */ export const UrlBar = memo(function UrlBar({
export const UrlBar = memo(function UrlBar(props: Props) { forceUpdateKey,
return <BaseUrlBar {...props} sendHotkeyAction="request.send" focusHotkeyAction="url_bar.focus" />; onUrlChange,
url,
placeholder,
className,
onSend,
onCancel,
onPaste,
onPasteOverwrite,
submitIcon = "send_horizontal",
autocomplete,
leftSlot,
rightSlot,
isLoading,
stateKey,
}: Props) {
const inputRef = useRef<InputHandle>(null);
const [isFocused, setIsFocused] = useState<boolean>(false);
const handleInitInputRef = useCallback((h: InputHandle | null) => {
inputRef.current = h;
}, []);
useHotKey("url_bar.focus", () => {
inputRef.current?.selectAll();
});
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (isLoading) onCancel();
else onSend();
};
return (
<form onSubmit={handleSubmit} className={classNames("x-theme-urlBar", className)}>
<Input
setRef={handleInitInputRef}
autocompleteFunctions
autocompleteVariables
stateKey={stateKey}
size="sm"
wrapLines={isFocused}
hideLabel
language="url"
className="px-1.5 py-0.5"
label="Enter URL"
name="url"
autocomplete={autocomplete}
forceUpdateKey={forceUpdateKey}
onFocus={() => setIsFocused(true)}
onBlur={() => setIsFocused(false)}
onPaste={onPaste}
onPasteOverwrite={onPasteOverwrite}
onChange={onUrlChange}
defaultValue={url}
placeholder={placeholder}
leftSlot={leftSlot}
rightSlot={
<HStack space={0.5}>
{rightSlot && <div className="py-0.5 h-full">{rightSlot}</div>}
{submitIcon !== null && (
<div className="py-0.5 h-full">
<IconButton
size="xs"
iconSize="md"
title="Send Request"
type="submit"
className="w-8 mr-0.5 h-full!"
iconColor="secondary"
icon={isLoading ? "x" : submitIcon}
hotkeyAction="request.send"
onMouseDown={(e) => {
// Prevent the button from taking focus
e.preventDefault();
}}
/>
</div>
)}
</HStack>
}
/>
</form>
);
}); });
@@ -1,11 +1,8 @@
import { import { VStack } from "@yaakapp-internal/ui";
type EditablePair,
type PairEditorHandle,
type PairEditorProps,
UrlParametersEditor as BaseUrlParametersEditor,
} from "@yaakapp-internal/ui";
import { useCallback, useRef } from "react"; import { useCallback, useRef } from "react";
import { useRequestEditor, useRequestEditorEvent } from "../hooks/useRequestEditor"; import { useRequestEditor, useRequestEditorEvent } from "../hooks/useRequestEditor";
import type { EditablePair, PairEditorHandle, PairEditorProps } from "./core/PairEditor";
import { PairOrBulkEditor } from "./core/PairOrBulkEditor";
type Props = { type Props = {
forceUpdateKey: string; forceUpdateKey: string;
@@ -14,7 +11,6 @@ type Props = {
onChange: PairEditorProps["onChange"]; onChange: PairEditorProps["onChange"];
}; };
/** The shared parameters editor, wired to the request editor's focus events */
export function UrlParametersEditor({ pairs, forceUpdateKey, onChange, stateKey }: Props) { export function UrlParametersEditor({ pairs, forceUpdateKey, onChange, stateKey }: Props) {
const pairEditorRef = useRef<PairEditorHandle>(null); const pairEditorRef = useRef<PairEditorHandle>(null);
const handleInitPairEditorRef = useCallback((ref: PairEditorHandle) => { const handleInitPairEditorRef = useCallback((ref: PairEditorHandle) => {
@@ -37,12 +33,22 @@ export function UrlParametersEditor({ pairs, forceUpdateKey, onChange, stateKey
); );
return ( return (
<BaseUrlParametersEditor <VStack className="h-full">
setRef={handleInitPairEditorRef} <PairOrBulkEditor
forceUpdateKey={forceUpdateKey + urlParametersKey} setRef={handleInitPairEditorRef}
onChange={onChange} allowMultilineValues
pairs={pairs} forceUpdateKey={forceUpdateKey + urlParametersKey}
stateKey={stateKey} nameAutocompleteFunctions
/> nameAutocompleteVariables
namePlaceholder="param_name"
onChange={onChange}
pairs={pairs}
preferenceName="url_parameters"
stateKey={stateKey}
valueAutocompleteFunctions
valueAutocompleteVariables
valuePlaceholder="Value"
/>
</VStack>
); );
} }
@@ -22,9 +22,11 @@ import { usePinnedHttpResponse } from "../hooks/usePinnedHttpResponse";
import { activeWebsocketConnectionAtom } from "../hooks/usePinnedWebsocketConnection"; import { activeWebsocketConnectionAtom } from "../hooks/usePinnedWebsocketConnection";
import { useRequestEditor, useRequestEditorEvent } from "../hooks/useRequestEditor"; import { useRequestEditor, useRequestEditorEvent } from "../hooks/useRequestEditor";
import { useRequestUpdateKey } from "../hooks/useRequestUpdateKey"; import { useRequestUpdateKey } from "../hooks/useRequestUpdateKey";
import { languageFromContentType } from "../lib/contentType";
import { derivePathPlaceholderPairs, renamePathPlaceholder } from "../lib/pathPlaceholders"; import { derivePathPlaceholderPairs, renamePathPlaceholder } from "../lib/pathPlaceholders";
import { prepareImportQuerystring } from "../lib/prepareImportQuerystring"; import { prepareImportQuerystring } from "../lib/prepareImportQuerystring";
import { resolvedModelName } from "../lib/resolvedModelName"; import { resolvedModelName } from "../lib/resolvedModelName";
import { CountBadge } from "./core/CountBadge";
import type { GenericCompletionConfig } from "./core/Editor/genericCompletion"; import type { GenericCompletionConfig } from "./core/Editor/genericCompletion";
import { getUrlCompletionConfig } from "./core/Editor/url/completion"; import { getUrlCompletionConfig } from "./core/Editor/url/completion";
import { Editor } from "./core/Editor/LazyEditor"; import { Editor } from "./core/Editor/LazyEditor";
@@ -38,7 +40,6 @@ import { MarkdownEditor } from "./MarkdownEditor";
import { countOverriddenSettings, ModelSettingsEditor } from "./ModelSettingsEditor"; import { countOverriddenSettings, ModelSettingsEditor } from "./ModelSettingsEditor";
import { UrlBar } from "./UrlBar"; import { UrlBar } from "./UrlBar";
import { UrlParametersEditor } from "./UrlParameterEditor"; import { UrlParametersEditor } from "./UrlParameterEditor";
import { languageFromContentType, CountBadge } from "@yaakapp-internal/ui";
interface Props { interface Props {
style: CSSProperties; style: CSSProperties;
@@ -1,14 +1,6 @@
import type { WebsocketEvent, WebsocketRequest } from "@yaakapp-internal/models"; import type { WebsocketEvent, WebsocketRequest } from "@yaakapp-internal/models";
import { import { HStack, Icon, LoadingIcon, VStack } from "@yaakapp-internal/ui";
HStack, import { hexy } from "hexy";
hexdump,
HexdumpViewer,
Icon,
LoadingIcon,
VStack,
useStateWithDeps,
languageFromContentType,
} from "@yaakapp-internal/ui";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { useMemo, useState } from "react"; import { useMemo, useState } from "react";
import { useFormatText } from "../hooks/useFormatText"; import { useFormatText } from "../hooks/useFormatText";
@@ -18,9 +10,10 @@ import {
setPinnedWebsocketConnectionId, setPinnedWebsocketConnectionId,
useWebsocketEvents, useWebsocketEvents,
} from "../hooks/usePinnedWebsocketConnection"; } from "../hooks/usePinnedWebsocketConnection";
import { useStateWithDeps } from "../hooks/useStateWithDeps";
import { languageFromContentType } from "../lib/contentType";
import { Button } from "./core/Button"; import { Button } from "./core/Button";
import { Editor } from "./core/Editor/LazyEditor"; import { Editor } from "./core/Editor/LazyEditor";
import { renderEditor } from "./core/Editor/renderEditor";
import { type EventDetailAction, EventDetailHeader, EventViewer } from "./core/EventViewer"; import { type EventDetailAction, EventDetailHeader, EventViewer } from "./core/EventViewer";
import { EventViewerRow } from "./core/EventViewerRow"; import { EventViewerRow } from "./core/EventViewerRow";
import { HotkeyList } from "./core/HotkeyList"; import { HotkeyList } from "./core/HotkeyList";
@@ -124,10 +117,10 @@ function WebsocketEventRow({
messageType === "error" messageType === "error"
? "alert_triangle" ? "alert_triangle"
: messageType === "close" || messageType === "open" : messageType === "close" || messageType === "open"
? "info" ? "info"
: isServer : isServer
? "arrow_big_down_dash" ? "arrow_big_down_dash"
: "arrow_big_up_dash"; : "arrow_big_up_dash";
const content = const content =
messageType === "close" ? ( messageType === "close" ? (
@@ -174,7 +167,7 @@ function WebsocketEventDetail({
}) { }) {
const message = useMemo(() => { const message = useMemo(() => {
if (hexDump) { if (hexDump) {
return event.message ? hexdump(event.message) : ""; return event.message ? hexy(event.message) : "";
} }
return event.message ? new TextDecoder("utf-8").decode(Uint8Array.from(event.message)) : ""; return event.message ? new TextDecoder("utf-8").decode(Uint8Array.from(event.message)) : "";
}, [event.message, hexDump]); }, [event.message, hexDump]);
@@ -234,8 +227,6 @@ function WebsocketEventDetail({
</VStack> </VStack>
) : event.message.length === 0 ? ( ) : event.message.length === 0 ? (
<EmptyStateText>No Content</EmptyStateText> <EmptyStateText>No Content</EmptyStateText>
) : hexDump ? (
<HexdumpViewer data={event.message} renderEditor={renderEditor} />
) : ( ) : (
<Editor <Editor
language={language} language={language}
+17 -5
View File
@@ -1,10 +1,10 @@
import { platform } from "@yaakapp-internal/platform"; import { platform } from "@yaakapp-internal/platform";
import { settingsAtom, workspacesAtom } from "@yaakapp-internal/models"; import { settingsAtom, workspacesAtom } from "@yaakapp-internal/models";
import { Banner, HeaderSize, HeaderTint, HStack, SidebarLayout } from "@yaakapp-internal/ui"; import { Banner, HeaderSize, HStack, SidebarLayout } from "@yaakapp-internal/ui";
import classNames from "classnames"; import classNames from "classnames";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import * as m from "motion/react-m"; import * as m from "motion/react-m";
import { useState } from "react"; import { useMemo, useState } from "react";
import { import {
getActiveCookieJar, getActiveCookieJar,
useEnsureActiveCookieJar, useEnsureActiveCookieJar,
@@ -40,7 +40,6 @@ import { ErrorBoundary } from "./ErrorBoundary";
import { FolderLayout } from "./FolderLayout"; import { FolderLayout } from "./FolderLayout";
import { GrpcConnectionLayout } from "./GrpcConnectionLayout"; import { GrpcConnectionLayout } from "./GrpcConnectionLayout";
import { HttpRequestLayout } from "./HttpRequestLayout"; import { HttpRequestLayout } from "./HttpRequestLayout";
import { RedirectToLatestWorkspace } from "./RedirectToLatestWorkspace";
import Sidebar from "./Sidebar"; import Sidebar from "./Sidebar";
import { SidebarActions } from "./SidebarActions"; import { SidebarActions } from "./SidebarActions";
import { WebsocketRequestLayout } from "./WebsocketRequestLayout"; import { WebsocketRequestLayout } from "./WebsocketRequestLayout";
@@ -61,8 +60,15 @@ export function Workspace() {
const activeEnvironment = useAtomValue(activeEnvironmentAtom); const activeEnvironment = useAtomValue(activeEnvironmentAtom);
const [floating, setFloating] = useState(false); const [floating, setFloating] = useState(false);
const environmentBgStyle = useMemo(() => {
if (activeEnvironment?.color == null) return undefined;
const background = `linear-gradient(to right, ${activeEnvironment.color} 15%, transparent 40%)`;
return { background };
}, [activeEnvironment?.color]);
// We're loading still
if (workspaces.length === 0) { if (workspaces.length === 0) {
return <RedirectToLatestWorkspace />; return null;
} }
const header = ( const header = (
@@ -75,7 +81,13 @@ export function Workspace() {
useNativeTitlebar={settings.useNativeTitlebar} useNativeTitlebar={settings.useNativeTitlebar}
interfaceScale={settings.interfaceScale} interfaceScale={settings.interfaceScale}
> >
<HeaderTint color={activeEnvironment?.color ?? null} /> <div className="absolute inset-0 pointer-events-none">
<div style={environmentBgStyle} className="absolute inset-0 opacity-[0.07]" />
<div
style={environmentBgStyle}
className="absolute left-0 right-0 -bottom-px h-px opacity-20"
/>
</div>
<WorkspaceHeader className="pointer-events-none" floatingSidebar={floating} /> <WorkspaceHeader className="pointer-events-none" floatingSidebar={floating} />
</HeaderSize> </HeaderSize>
); );
@@ -5,17 +5,20 @@ import {
setWorkspaceKey, setWorkspaceKey,
} from "@yaakapp-internal/crypto"; } from "@yaakapp-internal/crypto";
import type { WorkspaceMeta } from "@yaakapp-internal/models"; import type { WorkspaceMeta } from "@yaakapp-internal/models";
import { Banner, HStack, VStack, useStateWithDeps, IconTooltip, Label } from "@yaakapp-internal/ui"; import { Banner, HStack, VStack } from "@yaakapp-internal/ui";
import classNames from "classnames"; import classNames from "classnames";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { activeWorkspaceAtom, activeWorkspaceMetaAtom } from "../hooks/useActiveWorkspace"; import { activeWorkspaceAtom, activeWorkspaceMetaAtom } from "../hooks/useActiveWorkspace";
import { createFastMutation } from "../hooks/useFastMutation"; import { createFastMutation } from "../hooks/useFastMutation";
import { useStateWithDeps } from "../hooks/useStateWithDeps";
import { showConfirm } from "../lib/confirm"; import { showConfirm } from "../lib/confirm";
import { CopyIconButton } from "./CopyIconButton"; import { CopyIconButton } from "./CopyIconButton";
import type { ButtonProps } from "./core/Button"; import type { ButtonProps } from "./core/Button";
import { Button } from "./core/Button"; import { Button } from "./core/Button";
import { IconButton } from "./core/IconButton"; import { IconButton } from "./core/IconButton";
import { IconTooltip } from "./core/IconTooltip";
import { Label } from "./core/Label";
import { PlainInput } from "./core/PlainInput"; import { PlainInput } from "./core/PlainInput";
import { SettingRow } from "./core/SettingRow"; import { SettingRow } from "./core/SettingRow";
import { EncryptionHelp } from "./EncryptionHelp"; import { EncryptionHelp } from "./EncryptionHelp";
@@ -1,177 +0,0 @@
// @vitest-environment happy-dom
import type { Workspace, WorkspaceMeta } from "@yaakapp-internal/models";
import { workspaceMetasAtom } from "@yaakapp-internal/models";
import { getDefaultStore, type PrimitiveAtom } from "jotai";
import { act, type ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, test, vi } from "vite-plus/test";
import { WorkspaceSettingsDialog } from "./WorkspaceSettingsDialog";
const mocks = vi.hoisted(() => ({
rpc: vi.fn<(cmd: string, payload: unknown) => Promise<unknown>>(),
mergeModelsInStore: vi.fn(),
deleteModelWithConfirm: vi.fn<(model: unknown) => Promise<boolean>>(),
workspace: {
id: "wk_test",
model: "workspace",
name: "Broken",
settingDnsOverrides: [],
} as unknown as Workspace,
workspaceMeta: {
id: "wm_test",
model: "workspace_meta",
workspaceId: "wk_test",
settingSyncDir: "/sync/broken",
encryptionKey: null,
} as WorkspaceMeta,
}));
const { workspace, workspaceMeta } = mocks;
vi.mock("@yaakapp-internal/models", async () => {
const { atom } = await import("jotai");
return {
workspacesAtom: atom([mocks.workspace]),
// Starts empty in each test: the workspace failed to load, so the store has no meta for it
workspaceMetasAtom: atom<WorkspaceMeta[]>([]),
mergeModelsInStore: mocks.mergeModelsInStore,
patchModel: vi.fn(),
};
});
vi.mock("@yaakapp-internal/ui", () => ({
Banner: ({ children }: { children: ReactNode }) => <div role="alert">{children}</div>,
CountBadge: () => null,
HStack: ({ children }: { children: ReactNode }) => <div>{children}</div>,
InlineCode: ({ children }: { children: ReactNode }) => <code>{children}</code>,
}));
vi.mock("../hooks/useAuthTab", () => ({ useAuthTab: () => [] }));
vi.mock("../hooks/useHeadersTab", () => ({ useHeadersTab: () => [] }));
vi.mock("../hooks/useInheritedHeaders", () => ({ useInheritedHeaders: () => [] }));
vi.mock("../lib/deleteModelWithConfirm", () => ({
deleteModelWithConfirm: mocks.deleteModelWithConfirm,
}));
vi.mock("../lib/dialog", () => ({ showDialog: vi.fn() }));
vi.mock("../lib/router", () => ({ router: { navigate: vi.fn() } }));
vi.mock("../lib/rpc", () => ({ rpc: mocks.rpc }));
vi.mock("./CopyIconButton", () => ({ CopyIconButton: () => null }));
vi.mock("./core/Button", () => ({
Button: ({ children, onClick }: { children: ReactNode; onClick: () => void }) => (
<button type="button" onClick={onClick}>
{children}
</button>
),
}));
vi.mock("./core/PlainInput", () => ({
PlainInput: ({ label, defaultValue }: { label: string; defaultValue: string }) => (
<input aria-label={label} defaultValue={defaultValue} />
),
}));
vi.mock("./core/SettingRow", () => ({
SettingsList: ({ children }: { children: ReactNode }) => <div>{children}</div>,
SettingsSection: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}));
// Render every tab at once so the test can see all of them
vi.mock("./core/Tabs/Tabs", () => ({
Tabs: ({ children }: { children: ReactNode }) => <div>{children}</div>,
TabContent: ({ children, value }: { children: ReactNode; value: string }) => (
<div data-tab={value}>{children}</div>
),
}));
vi.mock("./DnsOverridesEditor", () => ({ DnsOverridesEditor: () => null }));
vi.mock("./HeadersEditor", () => ({ HeadersEditor: () => null }));
vi.mock("./HttpAuthenticationEditor", () => ({ HttpAuthenticationEditor: () => null }));
vi.mock("./MarkdownEditor", () => ({ MarkdownEditor: () => null }));
vi.mock("./ModelSettingsEditor", () => ({ ModelSettingsEditor: () => null }));
vi.mock("./SyncToFilesystemSetting", () => ({
SyncToFilesystemSetting: ({ value }: { value: { filePath: string | null } }) => (
<div data-testid="sync-setting">{value.filePath}</div>
),
}));
vi.mock("./WorkspaceEncryptionSetting", () => ({
WorkspaceEncryptionSetting: () => <div data-testid="encryption-setting" />,
}));
let root: Root;
let host: HTMLDivElement;
beforeEach(() => {
vi.clearAllMocks();
// Behave like the real store: merged models land in the atom the dialog reads
const store = getDefaultStore();
const metasAtom = workspaceMetasAtom as unknown as PrimitiveAtom<WorkspaceMeta[]>;
store.set(metasAtom, []);
mocks.mergeModelsInStore.mockImplementation((_model: string, models: WorkspaceMeta[]) =>
store.set(metasAtom, (prev) => [...prev, ...models]),
);
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
});
afterEach(async () => {
await act(async () => root.unmount());
host.remove();
vi.unstubAllGlobals();
});
async function render() {
await act(async () =>
root.render(<WorkspaceSettingsDialog workspaceId="wk_test" hide={() => {}} />),
);
}
function tab(value: string) {
const el = host.querySelector(`[data-tab="${value}"]`);
if (el == null) throw new Error(`No ${value} tab`);
return el;
}
function deleteButton() {
return Array.from(host.querySelectorAll("button")).find(
(b) => b.textContent === "Delete Workspace",
);
}
test("a workspace with no meta in the store still offers Delete", async () => {
mocks.rpc.mockReturnValue(new Promise(() => {}));
mocks.deleteModelWithConfirm.mockResolvedValue(false);
await render();
expect(host.textContent).not.toContain("not found");
const button = deleteButton();
expect(button).toBeDefined();
await act(async () => button?.click());
expect(mocks.deleteModelWithConfirm).toHaveBeenCalledWith(workspace, { confirmName: "Broken" });
});
test("a missing meta is fetched, put in the store, and its settings rendered", async () => {
mocks.rpc.mockResolvedValue(workspaceMeta);
await render();
expect(mocks.rpc).toHaveBeenCalledWith("cmd_get_workspace_meta", { workspaceId: "wk_test" });
expect(mocks.mergeModelsInStore).toHaveBeenCalledWith("workspace_meta", [workspaceMeta]);
const settings = tab("settings");
expect(settings.querySelector('[data-testid="sync-setting"]')?.textContent).toBe("/sync/broken");
expect(settings.querySelector('[data-testid="encryption-setting"]')).not.toBeNull();
expect(host.querySelector('[role="alert"]')).toBeNull();
});
test("a meta that cannot be loaded shows the error only where sync and encryption go", async () => {
mocks.rpc.mockRejectedValue("database is locked");
await render();
// The error is the one banner, inside the Settings tab, in place of sync and encryption
const banners = host.querySelectorAll('[role="alert"]');
expect(banners).toHaveLength(1);
expect(tab("settings").contains(banners[0] ?? null)).toBe(true);
expect(banners[0]?.textContent).toContain("database is locked");
expect(host.querySelector('[data-testid="sync-setting"]')).toBeNull();
expect(host.querySelector('[data-testid="encryption-setting"]')).toBeNull();
expect(mocks.mergeModelsInStore).not.toHaveBeenCalled();
// The workspace's own settings and Delete still render
const general = tab("general");
expect(general.querySelector<HTMLInputElement>('input[aria-label="Name"]')?.value).toBe("Broken");
expect(general.contains(deleteButton() ?? null)).toBe(true);
});
@@ -1,22 +1,15 @@
import type { WorkspaceMeta } from "@yaakapp-internal/models"; import { patchModel, workspaceMetasAtom, workspacesAtom } from "@yaakapp-internal/models";
import { import { Banner, HStack, InlineCode } from "@yaakapp-internal/ui";
mergeModelsInStore,
patchModel,
workspaceMetasAtom,
workspacesAtom,
} from "@yaakapp-internal/models";
import { Banner, HStack, InlineCode, CountBadge } from "@yaakapp-internal/ui";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { useEffect, useState } from "react";
import { useAuthTab } from "../hooks/useAuthTab"; import { useAuthTab } from "../hooks/useAuthTab";
import { useHeadersTab } from "../hooks/useHeadersTab"; import { useHeadersTab } from "../hooks/useHeadersTab";
import { useInheritedHeaders } from "../hooks/useInheritedHeaders"; import { useInheritedHeaders } from "../hooks/useInheritedHeaders";
import { deleteModelWithConfirm } from "../lib/deleteModelWithConfirm"; import { deleteModelWithConfirm } from "../lib/deleteModelWithConfirm";
import { showDialog } from "../lib/dialog"; import { showDialog } from "../lib/dialog";
import { router } from "../lib/router"; import { router } from "../lib/router";
import { rpc } from "../lib/rpc";
import { CopyIconButton } from "./CopyIconButton"; import { CopyIconButton } from "./CopyIconButton";
import { Button } from "./core/Button"; import { Button } from "./core/Button";
import { CountBadge } from "./core/CountBadge";
import { PlainInput } from "./core/PlainInput"; import { PlainInput } from "./core/PlainInput";
import { SettingsList, SettingsSection } from "./core/SettingRow"; import { SettingsList, SettingsSection } from "./core/SettingRow";
import { TabContent, Tabs } from "./core/Tabs/Tabs"; import { TabContent, Tabs } from "./core/Tabs/Tabs";
@@ -32,8 +25,12 @@ interface Props {
workspaceId: string; workspaceId: string;
hide: () => void; hide: () => void;
tab?: WorkspaceSettingsTab; tab?: WorkspaceSettingsTab;
highlight?: WorkspaceSettingsHighlight;
} }
/** Settings rows that can be pointed out when the dialog opens */
export type WorkspaceSettingsHighlight = "sync_dir";
const TAB_AUTH = "auth"; const TAB_AUTH = "auth";
const TAB_DNS = "dns"; const TAB_DNS = "dns";
const TAB_HEADERS = "headers"; const TAB_HEADERS = "headers";
@@ -49,16 +46,12 @@ export type WorkspaceSettingsTab =
const DEFAULT_TAB: WorkspaceSettingsTab = TAB_GENERAL; const DEFAULT_TAB: WorkspaceSettingsTab = TAB_GENERAL;
export function WorkspaceSettingsDialog({ workspaceId, hide, tab }: Props) { export function WorkspaceSettingsDialog({ workspaceId, hide, tab, highlight }: Props) {
const workspace = useAtomValue(workspacesAtom).find((w) => w.id === workspaceId); const workspace = useAtomValue(workspacesAtom).find((w) => w.id === workspaceId);
const workspaceMeta = useAtomValue(workspaceMetasAtom).find((m) => m.workspaceId === workspaceId); const workspaceMeta = useAtomValue(workspaceMetasAtom).find((m) => m.workspaceId === workspaceId);
const authTab = useAuthTab(TAB_AUTH, workspace ?? null); const authTab = useAuthTab(TAB_AUTH, workspace ?? null);
const headersTab = useHeadersTab(TAB_HEADERS, workspace ?? null); const headersTab = useHeadersTab(TAB_HEADERS, workspace ?? null);
const inheritedHeaders = useInheritedHeaders(workspace ?? null); const inheritedHeaders = useInheritedHeaders(workspace ?? null);
const workspaceMetaError = useEnsureWorkspaceMeta(
workspaceId,
workspace != null && workspaceMeta == null,
);
if (workspace == null) { if (workspace == null) {
return ( return (
@@ -68,6 +61,13 @@ export function WorkspaceSettingsDialog({ workspaceId, hide, tab }: Props) {
); );
} }
if (workspaceMeta == null)
return (
<Banner color="danger">
<InlineCode>WorkspaceMeta</InlineCode> not found for workspace
</Banner>
);
return ( return (
<Tabs <Tabs
defaultValue={tab ?? DEFAULT_TAB} defaultValue={tab ?? DEFAULT_TAB}
@@ -108,28 +108,17 @@ export function WorkspaceSettingsDialog({ workspaceId, hide, tab }: Props) {
/> />
</TabContent> </TabContent>
<TabContent value={TAB_SETTINGS} className="overflow-y-auto h-full px-4"> <TabContent value={TAB_SETTINGS} className="overflow-y-auto h-full px-4">
<SettingsList className="space-y-8 pb-3"> <SettingsList className="space-y-8 pb-3" highlight={highlight}>
<SettingsSection title={null}> <SettingsSection title={null}>
{workspaceMeta != null ? ( <SyncToFilesystemSetting
<> layout="settings"
<SyncToFilesystemSetting value={{ filePath: workspaceMeta.settingSyncDir }}
layout="settings" onCreateNewWorkspace={hide}
value={{ filePath: workspaceMeta.settingSyncDir }} onChange={({ filePath }) => patchModel(workspaceMeta, { settingSyncDir: filePath })}
onCreateNewWorkspace={hide} />
onChange={({ filePath }) => <div className="mt-4">
patchModel(workspaceMeta, { settingSyncDir: filePath }) <WorkspaceEncryptionSetting layout="settings" size="xs" />
} </div>
/>
<div className="mt-4">
<WorkspaceEncryptionSetting layout="settings" size="xs" />
</div>
</>
) : workspaceMetaError != null ? (
<Banner color="danger">
Sync and encryption settings are unavailable because{" "}
<InlineCode>WorkspaceMeta</InlineCode> could not be loaded: {workspaceMetaError}
</Banner>
) : null}
</SettingsSection> </SettingsSection>
<ModelSettingsEditor model={workspace} showSectionTitles /> <ModelSettingsEditor model={workspace} showSectionTitles />
</SettingsList> </SettingsList>
@@ -193,42 +182,23 @@ export function WorkspaceSettingsDialog({ workspaceId, hide, tab }: Props) {
); );
} }
/** WorkspaceSettingsDialog.show = (
* The meta row normally reaches the store when the workspace loads, which also creates it if it workspaceId: string,
* is missing. If that load failed (for example on a corrupt row elsewhere in the workspace), the tab?: WorkspaceSettingsTab,
* store never gets it, so ask for it directly. Returns the error if that fails too. highlight?: WorkspaceSettingsHighlight,
*/ ) => {
function useEnsureWorkspaceMeta(workspaceId: string, missing: boolean): string | null {
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!missing) return;
let cancelled = false;
setError(null);
rpc<WorkspaceMeta>("cmd_get_workspace_meta", { workspaceId }).then(
(meta) => {
if (!cancelled) mergeModelsInStore("workspace_meta", [meta]);
},
(err) => {
if (!cancelled) setError(String(err));
},
);
return () => {
cancelled = true;
};
}, [workspaceId, missing]);
return error;
}
WorkspaceSettingsDialog.show = (workspaceId: string, tab?: WorkspaceSettingsTab) => {
showDialog({ showDialog({
id: "workspace-settings", id: "workspace-settings",
size: "lg", size: "lg",
className: "h-[calc(100vh-5rem)] max-h-200!", className: "h-[calc(100vh-5rem)] max-h-200!",
noPadding: true, noPadding: true,
render: ({ hide }) => ( render: ({ hide }) => (
<WorkspaceSettingsDialog workspaceId={workspaceId} hide={hide} tab={tab} /> <WorkspaceSettingsDialog
workspaceId={workspaceId}
hide={hide}
tab={tab}
highlight={highlight}
/>
), ),
}); });
}; };
@@ -1,9 +1,7 @@
import { useVirtualizer, type Virtualizer } from "@tanstack/react-virtual"; import { useVirtualizer, type Virtualizer } from "@tanstack/react-virtual";
import classNames from "classnames";
import type { ReactElement, ReactNode, UIEvent } from "react"; import type { ReactElement, ReactNode, UIEvent } from "react";
import { useCallback, useLayoutEffect, useRef, useState } from "react"; import { useCallback, useLayoutEffect, useRef, useState } from "react";
import { Icon } from "../Icon"; import { IconButton } from "./IconButton";
import { IconButton } from "../IconButton";
interface Props<T> { interface Props<T> {
data: T[]; data: T[];
@@ -13,14 +11,6 @@ interface Props<T> {
focusable?: boolean; focusable?: boolean;
/** Callback to expose the virtualizer for keyboard navigation */ /** Callback to expose the virtualizer for keyboard navigation */
onVirtualizerReady?: (virtualizer: Virtualizer<HTMLDivElement, Element>) => void; onVirtualizerReady?: (virtualizer: Virtualizer<HTMLDivElement, Element>) => void;
/**
* Holds and catches up as the proxy's flow list does: once scrolled away from the end (or
* `holdSignal` changes), new items wait under a pill counting them, which scrolls back down.
* Without it, a button locks the scroll to the bottom again.
*/
catchUp?: { label: (count: number) => string };
/** Holds the scroll where it is whenever this changes, as selecting an item does */
holdSignal?: unknown;
} }
export function AutoScroller<T>({ export function AutoScroller<T>({
@@ -29,15 +19,9 @@ export function AutoScroller<T>({
header, header,
focusable = false, focusable = false,
onVirtualizerReady, onVirtualizerReady,
catchUp,
holdSignal,
}: Props<T>) { }: Props<T>) {
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
const [autoScroll, setAutoScroll] = useState<boolean>(true); const [autoScroll, setAutoScroll] = useState<boolean>(true);
// How many items there were when the scroll was held, to count the new ones
const [heldAt, setHeldAt] = useState<number>(0);
const latestLength = useRef(data.length);
latestLength.current = data.length;
// The virtualizer // The virtualizer
const rowVirtualizer = useVirtualizer({ const rowVirtualizer = useVirtualizer({
@@ -51,11 +35,6 @@ export function AutoScroller<T>({
onVirtualizerReady?.(rowVirtualizer); onVirtualizerReady?.(rowVirtualizer);
}, [rowVirtualizer, onVirtualizerReady]); }, [rowVirtualizer, onVirtualizerReady]);
const hold = useCallback(() => {
setAutoScroll(false);
setHeldAt(latestLength.current);
}, []);
// Scroll to new items // Scroll to new items
const handleScroll = useCallback( const handleScroll = useCallback(
(e: UIEvent<HTMLDivElement>) => { (e: UIEvent<HTMLDivElement>) => {
@@ -65,21 +44,12 @@ export function AutoScroller<T>({
const pixelsFromBottom = el.scrollHeight - (el.scrollTop + el.clientHeight); const pixelsFromBottom = el.scrollHeight - (el.scrollTop + el.clientHeight);
const newAutoScroll = pixelsFromBottom <= 0; const newAutoScroll = pixelsFromBottom <= 0;
if (newAutoScroll !== autoScroll) { if (newAutoScroll !== autoScroll) {
if (newAutoScroll) setAutoScroll(true); setAutoScroll(newAutoScroll);
else hold();
} }
}, },
[autoScroll, hold], [autoScroll],
); );
// Selecting an item holds the list where it is
const lastHoldSignal = useRef(holdSignal);
useLayoutEffect(() => {
if (Object.is(lastHoldSignal.current, holdSignal)) return;
lastHoldSignal.current = holdSignal;
if (catchUp != null && autoScroll) hold();
}, [autoScroll, catchUp, hold, holdSignal]);
// Scroll to bottom on count change // Scroll to bottom on count change
useLayoutEffect(() => { useLayoutEffect(() => {
if (!autoScroll) return; if (!autoScroll) return;
@@ -92,11 +62,9 @@ export function AutoScroller<T>({
el.scrollTop = el.scrollHeight; el.scrollTop = el.scrollHeight;
}, [autoScroll, data.length]); }, [autoScroll, data.length]);
const newCount = data.length - heldAt;
return ( return (
<div className="h-full w-full relative grid grid-rows-[auto_minmax(0,1fr)]"> <div className="h-full w-full relative grid grid-rows-[auto_minmax(0,1fr)]">
{!autoScroll && catchUp == null && ( {!autoScroll && (
<div className="absolute bottom-0 right-0 m-2"> <div className="absolute bottom-0 right-0 m-2">
<IconButton <IconButton
title="Lock scroll to bottom" title="Lock scroll to bottom"
@@ -109,21 +77,6 @@ export function AutoScroller<T>({
/> />
</div> </div>
)} )}
{!autoScroll && catchUp != null && newCount > 0 && (
<button
type="button"
onClick={() => setAutoScroll(true)}
className={classNames(
"absolute bottom-3 left-1/2 -translate-x-1/2 z-10",
"flex items-center gap-1.5 h-6 px-3 rounded-full",
"bg-surface border border-border shadow-lg text-text text-xs tabular-nums",
"hover:bg-surface-highlight",
)}
>
<Icon icon="arrow_down_to_line" size="sm" color="primary" />
{catchUp.label(newCount)}
</button>
)}
{header ?? <span aria-hidden />} {header ?? <span aria-hidden />}
<div <div
ref={containerRef} ref={containerRef}
@@ -0,0 +1,36 @@
import { describe, expect, test } from "vite-plus/test";
import { parseBulkPairLine } from "./BulkPairEditor";
describe("parseBulkPairLine", () => {
test("parses colon-space pairs as name and value", () => {
expect(parseBulkPairLine("foo: bar")).toMatchObject({
enabled: true,
name: "foo",
value: "bar",
});
});
test("preserves colon-without-space lines as a name with an empty value", () => {
expect(parseBulkPairLine("foo:bar")).toMatchObject({
enabled: true,
name: "foo:bar",
value: "",
});
});
test("preserves malformed lines instead of dropping their contents", () => {
expect(parseBulkPairLine("not a pair")).toMatchObject({
enabled: true,
name: "not a pair",
value: "",
});
});
test("unescapes newlines in parsed values", () => {
expect(parseBulkPairLine("foo: bar\\nbaz")).toMatchObject({
enabled: true,
name: "foo",
value: "bar\nbaz",
});
});
});
@@ -0,0 +1,63 @@
import { useCallback, useMemo } from "react";
import { generateId } from "../../lib/generateId";
import { Editor } from "./Editor/LazyEditor";
import type { Pair, PairEditorProps, PairWithId } from "./PairEditor";
type Props = PairEditorProps;
export function BulkPairEditor({
pairs,
onChange,
namePlaceholder,
valuePlaceholder,
forceUpdateKey,
forcedEnvironmentId,
stateKey,
}: Props) {
const pairsText = useMemo(() => {
return pairs
.filter((p) => !(p.name.trim() === "" && p.value.trim() === ""))
.map(formatBulkPairLine)
.join("\n");
}, [pairs]);
const handleChange = useCallback(
(text: string) => {
const pairs = text
.split("\n")
.filter((l: string) => l.trim())
.map(parseBulkPairLine);
onChange(pairs);
},
[onChange],
);
return (
<Editor
autocompleteFunctions
autocompleteVariables
stateKey={`bulk_pair.${stateKey}`}
forcedEnvironmentId={forcedEnvironmentId}
forceUpdateKey={forceUpdateKey}
placeholder={`${namePlaceholder ?? "name"}: ${valuePlaceholder ?? "value"}`}
defaultValue={pairsText}
language="pairs"
onChange={handleChange}
/>
);
}
export function formatBulkPairLine(pair: Pair) {
const value = pair.value.replaceAll("\n", "\\n");
return `${pair.name}: ${value}`;
}
export function parseBulkPairLine(line: string): PairWithId {
const [, name, value] = line.match(/^([^:]+):\s+(.*)$/) ?? [];
return {
enabled: true,
name: (name ?? line).trim(),
value: (value ?? "").replaceAll("\\n", "\n").trim(),
id: generateId(),
};
}
+73 -2
View File
@@ -1,2 +1,73 @@
export type { CheckboxProps } from "@yaakapp-internal/ui"; import { HStack, Icon } from "@yaakapp-internal/ui";
export { Checkbox } from "@yaakapp-internal/ui"; import classNames from "classnames";
import type { ReactNode } from "react";
import { IconTooltip } from "./IconTooltip";
export interface CheckboxProps {
checked: boolean | "indeterminate";
title: ReactNode;
onChange: (checked: boolean) => void;
className?: string;
disabled?: boolean;
inputWrapperClassName?: string;
hideLabel?: boolean;
fullWidth?: boolean;
help?: ReactNode;
size?: "sm" | "md";
}
export function Checkbox({
checked,
onChange,
className,
inputWrapperClassName,
disabled,
title,
hideLabel,
fullWidth,
help,
size = "sm",
}: CheckboxProps) {
return (
<HStack
as="label"
alignItems="center"
space={2}
className={classNames(className, "text-text mr-auto")}
>
<div className={classNames(inputWrapperClassName, "x-theme-input", "relative flex mr-0.5")}>
<input
aria-hidden
className={classNames(
"appearance-none shrink-0 border border-border",
size === "sm" && "w-4 h-4",
size === "md" && "w-5 h-5",
"rounded-sm outline-hidden ring-0",
!disabled && "hocus:border-border-focus hocus:bg-focus/[5%]",
disabled && "border-dotted",
)}
type="checkbox"
disabled={disabled}
onChange={() => {
onChange(checked === "indeterminate" ? true : !checked);
}}
/>
<div className="absolute inset-0 flex items-center justify-center">
<Icon
size={size}
className={classNames(disabled && "opacity-disabled")}
icon={checked === "indeterminate" ? "minus" : checked ? "check" : "empty"}
/>
</div>
</div>
{!hideLabel && (
<div
className={classNames("text-sm", fullWidth && "w-full", disabled && "opacity-disabled")}
>
{title}
</div>
)}
{help && <IconTooltip content={help} />}
</HStack>
);
}
-32
View File
@@ -1,32 +0,0 @@
import type { Color } from "@yaakapp-internal/plugins";
import classNames from "classnames";
import type { ReactNode } from "react";
interface Props {
color?: Color | "default";
className?: string;
children: ReactNode;
}
/** A small tinted label, like a Gmail or Trello label */
export function Chip({ color = "default", className, children }: Props) {
return (
<span
className={classNames(
className,
"text-xs font-medium rounded-md px-2 py-0.5 bg-current/10 border border-current/10 shrink-0 whitespace-nowrap",
"inline-flex items-center gap-1",
color === "default" && "text-text-subtle",
color === "primary" && "text-primary",
color === "secondary" && "text-secondary",
color === "info" && "text-info",
color === "success" && "text-success",
color === "notice" && "text-notice",
color === "warning" && "text-warning",
color === "danger" && "text-danger",
)}
>
{children}
</span>
);
}
+12 -17
View File
@@ -1,8 +1,9 @@
import type { Color } from "@yaakapp-internal/plugins"; import type { Color } from "@yaakapp-internal/plugins";
import { HStack } from "@yaakapp-internal/ui";
import type { FormEvent } from "react"; import type { FormEvent } from "react";
import { useId, useState } from "react"; import { useState } from "react";
import { CopyIconButton } from "../CopyIconButton"; import { CopyIconButton } from "../CopyIconButton";
import { DialogFooter } from "./Dialog"; import { Button } from "./Button";
import { PlainInput } from "./PlainInput"; import { PlainInput } from "./PlainInput";
export interface ConfirmProps { export interface ConfirmProps {
@@ -21,7 +22,6 @@ export function Confirm({
color = "primary", color = "primary",
}: ConfirmProps) { }: ConfirmProps) {
const [confirm, setConfirm] = useState<string>(""); const [confirm, setConfirm] = useState<string>("");
const formId = useId();
const handleHide = () => { const handleHide = () => {
onResult(false); onResult(false);
onHide(); onHide();
@@ -38,7 +38,7 @@ export function Confirm({
}; };
return ( return (
<form id={formId} className="flex flex-col" onSubmit={handleSuccess}> <form className="flex flex-col" onSubmit={handleSuccess}>
{requireTyping && ( {requireTyping && (
<PlainInput <PlainInput
autoFocus autoFocus
@@ -61,19 +61,14 @@ export function Confirm({
} }
/> />
)} )}
<DialogFooter <HStack space={2} justifyContent="start" className="mt-2 mb-4 flex-row-reverse">
inline <Button type="submit" color={color} disabled={!didConfirm}>
actions={[ {confirmText ?? "Confirm"}
{ label: "Cancel", onClick: handleHide }, </Button>
{ <Button onClick={handleHide} variant="border">
label: confirmText ?? "Confirm", Cancel
color, </Button>
form: formId, </HStack>
disabled: !didConfirm,
autoFocus: !requireTyping,
},
]}
/>
</form> </form>
); );
} }
@@ -2,8 +2,7 @@ import type { Color } from "@yaakapp-internal/plugins";
import classNames from "classnames"; import classNames from "classnames";
interface Props { interface Props {
/** A number, a dot for `true`, or a short word such as a body's type */ count: number | true;
count: number | true | string;
count2?: number | true; count2?: number | true;
className?: string; className?: string;
color?: Color; color?: Color;
@@ -25,7 +24,6 @@ export function CountBadge({ count, count2, className, color, showZero }: Props)
color === "secondary" && "text-secondary", color === "secondary" && "text-secondary",
color === "success" && "text-success", color === "success" && "text-success",
color === "notice" && "text-notice", color === "notice" && "text-notice",
color === "info" && "text-info",
color === "warning" && "text-warning", color === "warning" && "text-warning",
color === "danger" && "text-danger", color === "danger" && "text-danger",
)} )}
@@ -1,27 +1,60 @@
import { import classNames from "classnames";
DetailsBanner as BaseDetailsBanner, import { atom, useAtom } from "jotai";
type DetailsBannerProps, import type { HTMLAttributes, ReactNode } from "react";
type StoredValue, import { useMemo } from "react";
} from "@yaakapp-internal/ui";
import { atom, useAtom, type WritableAtom } from "jotai";
import { type SetStateAction, useMemo } from "react";
import { atomWithKVStorage } from "../../lib/atoms/atomWithKVStorage"; import { atomWithKVStorage } from "../../lib/atoms/atomWithKVStorage";
import type { BannerProps } from "@yaakapp-internal/ui";
import { Banner } from "@yaakapp-internal/ui";
export function DetailsBanner(props: Omit<DetailsBannerProps, "useStoredValue">) { interface Props extends HTMLAttributes<HTMLDetailsElement> {
return <BaseDetailsBanner {...props} useStoredValue={useDetailsBannerStoredValue} />; summary: ReactNode;
color?: BannerProps["color"];
defaultOpen?: boolean;
storageKey?: string;
} }
export function useDetailsBannerStoredValue<T extends StoredValue>( export function DetailsBanner({
key: string | string[] | null, className,
fallback: T, color,
) { summary,
// oxlint-disable-next-line react-hooks/exhaustive-deps -- We only want to recompute the atom when the key changes children,
const valueAtom = useMemo<WritableAtom<T, [SetStateAction<T>], void>>( defaultOpen,
storageKey,
...extraProps
}: Props) {
// oxlint-disable-next-line react-hooks/exhaustive-deps -- We only want to recompute the atom when storageKey changes
const openAtom = useMemo(
() => () =>
key != null storageKey
? atomWithKVStorage<T>(["details_banner", ...[key].flat()], fallback) ? atomWithKVStorage<boolean>(["details_banner", storageKey], defaultOpen ?? false)
: atom(fallback), : atom(defaultOpen ?? false),
[key], [storageKey],
);
const [isOpen, setIsOpen] = useAtom(openAtom);
const handleToggle = (e: React.SyntheticEvent<HTMLDetailsElement>) => {
if (storageKey) {
setIsOpen(e.currentTarget.open);
}
};
return (
<Banner color={color} className={className}>
<details className="group list-none" open={isOpen} onToggle={handleToggle} {...extraProps}>
<summary className="cursor-default! select-none! list-none flex items-center gap-3 focus:outline-hidden opacity-70">
<div
className={classNames(
"transition-transform",
"group-open:rotate-90",
"w-0 h-0 border-t-[0.3em] border-b-[0.3em] border-l-[0.5em] border-r-0",
"border-t-transparent border-b-transparent border-l-text-subtle",
)}
/>
{summary}
</summary>
<div className="mt-1.5 pb-2">{children}</div>
</details>
</Banner>
); );
return useAtom(valueAtom);
} }
Loaded 100 of 976 files, more files were not shown because too many files have changed in this diff. Show more