mirror of
https://github.com/webstudio-is/webstudio.git
synced 2026-12-01 21:05:42 +09:00
feat: show session publish results and add CLI wait
This commit is contained in:
commit
fece298b28
2604 files changed
+313035
-51176
No files matched your search
@@ -0,0 +1,54 @@
|
||||
name: Build Builder E2E prerequisites
|
||||
|
||||
description: Build the Builder and package its E2E schema and dependencies.
|
||||
|
||||
inputs:
|
||||
submodules-ssh-key:
|
||||
description: SSH key for private E2E dependencies.
|
||||
required: false
|
||||
|
||||
outputs:
|
||||
shards:
|
||||
description: Filename-derived E2E shard matrix.
|
||||
value: ${{ steps.shards.outputs.value }}
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- uses: ./.github/actions/submodules-checkout
|
||||
with:
|
||||
submodules-ssh-key: ${{ inputs.submodules-ssh-key }}
|
||||
|
||||
- uses: ./.github/actions/ci-setup
|
||||
with:
|
||||
run-scripts: "true"
|
||||
|
||||
- name: Discover shards
|
||||
id: shards
|
||||
shell: bash
|
||||
run: |
|
||||
shards=$(pnpm --dir apps/builder exec tsx ./e2e/print-shards.ts)
|
||||
echo "value=$shards" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build Builder
|
||||
shell: bash
|
||||
run: pnpm --filter @webstudio-is/builder build
|
||||
|
||||
- name: Build generated React Router components
|
||||
shell: bash
|
||||
run: pnpm --filter @webstudio-is/sdk-components-react-router build
|
||||
|
||||
- name: Generate schema snapshot
|
||||
shell: bash
|
||||
run: pnpm --filter @webstudio-is/builder e2e:schema-cache
|
||||
|
||||
- name: Upload prerequisites
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: builder-e2e-build
|
||||
retention-days: 7
|
||||
path: |
|
||||
apps/builder/build/server
|
||||
apps/builder/build/client/assets
|
||||
packages/*/lib
|
||||
.cache/builder-e2e/schema-*.sql
|
||||
@@ -0,0 +1,72 @@
|
||||
name: Run Builder E2E shard
|
||||
|
||||
description: Run one Builder E2E shard and preserve diagnostics on failure.
|
||||
|
||||
inputs:
|
||||
submodules-ssh-key:
|
||||
description: SSH key for private E2E dependencies.
|
||||
required: false
|
||||
shard:
|
||||
description: Filename-derived shard name.
|
||||
required: true
|
||||
partition:
|
||||
description: Optional Playwright partition within the selected files.
|
||||
required: false
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- uses: ./.github/actions/submodules-checkout
|
||||
with:
|
||||
submodules-ssh-key: ${{ inputs.submodules-ssh-key }}
|
||||
|
||||
- uses: ./.github/actions/ci-setup
|
||||
with:
|
||||
run-scripts: "true"
|
||||
|
||||
- name: Cache Playwright Chromium
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
~/.cache/ms-playwright/chromium-*
|
||||
~/.cache/ms-playwright/chromium_headless_shell-*
|
||||
~/.cache/ms-playwright/ffmpeg-*
|
||||
key: playwright-chromium-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
|
||||
- name: Download Builder E2E build
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: builder-e2e-build
|
||||
path: .
|
||||
|
||||
- name: Run Builder E2E
|
||||
shell: bash
|
||||
env:
|
||||
E2E_TEST_SHARD: ${{ inputs.shard }}
|
||||
E2E_TEST_PARTITION: ${{ inputs.partition }}
|
||||
run: |
|
||||
args=(--workers=2)
|
||||
if [ -n "$E2E_TEST_PARTITION" ]; then
|
||||
args+=(--shard="$E2E_TEST_PARTITION")
|
||||
fi
|
||||
pnpm --filter @webstudio-is/builder e2e:ci:shard -- "${args[@]}"
|
||||
|
||||
- name: Upload report
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: builder-e2e-report-${{ inputs.shard }}
|
||||
retention-days: 7
|
||||
path: |
|
||||
apps/builder/playwright-report
|
||||
apps/builder/test-results/e2e
|
||||
|
||||
- name: Print service logs
|
||||
if: failure()
|
||||
shell: bash
|
||||
run: bash apps/builder/backend/run.sh snapshot logs
|
||||
|
||||
- name: Stop services
|
||||
if: always()
|
||||
shell: bash
|
||||
run: bash apps/builder/backend/run.sh snapshot down --volumes --remove-orphans
|
||||
@@ -0,0 +1,55 @@
|
||||
name: Test suite
|
||||
|
||||
description: Prepare browsers and run one repository test script.
|
||||
|
||||
inputs:
|
||||
submodules-ssh-key:
|
||||
description: SSH key for private test dependencies.
|
||||
required: false
|
||||
script:
|
||||
description: Root package script to run.
|
||||
required: true
|
||||
browsers:
|
||||
description: Browsers required by the test script.
|
||||
default: none
|
||||
required: false
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- uses: ./.github/actions/submodules-checkout
|
||||
with:
|
||||
submodules-ssh-key: ${{ inputs.submodules-ssh-key }}
|
||||
|
||||
- uses: ./.github/actions/ci-setup
|
||||
|
||||
- name: Cache Playwright Chromium
|
||||
if: inputs.browsers != 'none'
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
~/.cache/ms-playwright/chromium-*
|
||||
~/.cache/ms-playwright/chromium_headless_shell-*
|
||||
~/.cache/ms-playwright/ffmpeg-*
|
||||
key: playwright-chromium-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
|
||||
- name: Cache Playwright Firefox
|
||||
if: inputs.browsers == 'chromium-firefox'
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.cache/ms-playwright/firefox-*
|
||||
key: playwright-firefox-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
|
||||
- name: Install package test browsers
|
||||
if: inputs.browsers == 'chromium-firefox'
|
||||
shell: bash
|
||||
run: pnpm --filter @webstudio-is/sdk-components-animation exec playwright install chromium firefox
|
||||
|
||||
- name: Install Builder test browser
|
||||
if: inputs.browsers == 'chromium'
|
||||
shell: bash
|
||||
run: pnpm --filter @webstudio-is/builder exec playwright install chromium
|
||||
|
||||
- name: Run test suite
|
||||
shell: bash
|
||||
run: pnpm run "${{ inputs.script }}"
|
||||
@@ -134,6 +134,13 @@ runs:
|
||||
|
||||
shell: bash
|
||||
|
||||
- name: Verify published CLI contract against staged Builder
|
||||
if: ${{ inputs.production-staged == 'true' }}
|
||||
run: pnpm --filter webstudio check:published-cli-contract
|
||||
shell: bash
|
||||
env:
|
||||
WEBSTUDIO_CLI_CONTRACT_BUILDER_ORIGIN: ${{ steps.deploy.outputs.domain }}
|
||||
|
||||
- name: Set Alias
|
||||
id: alias
|
||||
run: |
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
name: Approved fork workflows
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
|
||||
jobs:
|
||||
main:
|
||||
uses: ./.github/workflows/main.yml
|
||||
secrets: inherit
|
||||
|
||||
vercel-deploy-staging:
|
||||
uses: ./.github/workflows/vercel-deploy-staging.yml
|
||||
secrets: inherit
|
||||
@@ -16,11 +16,11 @@ permissions:
|
||||
packages: write
|
||||
deployments: write
|
||||
|
||||
env:
|
||||
COMPATIBILITY_DATE: "2024-04-10"
|
||||
|
||||
jobs:
|
||||
build:
|
||||
env:
|
||||
COMPATIBILITY_DATE: 2024-04-10
|
||||
|
||||
environment:
|
||||
name: "staging"
|
||||
|
||||
@@ -124,7 +124,7 @@ jobs:
|
||||
run: |
|
||||
NODE_ENV=production pnpm wrangler deploy \
|
||||
--name build \
|
||||
--compatibility-date '${COMPATIBILITY_DATE}' \
|
||||
--compatibility-date "${COMPATIBILITY_DATE}" \
|
||||
--minify true \
|
||||
--logpush true \
|
||||
--dry-run \
|
||||
|
||||
@@ -38,6 +38,7 @@ jobs:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }}
|
||||
# Test that everything is working with submodules
|
||||
- uses: ./.github/actions/submodules-checkout
|
||||
with:
|
||||
@@ -57,7 +58,8 @@ jobs:
|
||||
shell: bash
|
||||
run: |
|
||||
set +e
|
||||
pnpm --filter='./fixtures/*' --sequential run fixtures:sync 2>&1 | tee fixtures-sync.log
|
||||
# Build webstudio-features from its checked-in snapshot; its remote data is mutable.
|
||||
pnpm --filter='./fixtures/*' --filter='!./fixtures/webstudio-features' --sequential run fixtures:sync 2>&1 | tee fixtures-sync.log
|
||||
sync_status=${PIPESTATUS[0]}
|
||||
if [ "$sync_status" -ne 0 ]; then
|
||||
message=$(tail -n 40 fixtures-sync.log | sed -e 's/%/%25/g' -e 's/\r/%0D/g' -e 's/$/%0A/' | tr -d '\n')
|
||||
@@ -74,12 +76,16 @@ jobs:
|
||||
find . -type f -path "./fixtures/*/.webstudio/data.json" -exec sed -i 's|"origin": ".*"|"origin": "https://main.development.webstudio.is"|g' {} +
|
||||
|
||||
- name: Test git diff
|
||||
# This command will fail if there are uncommitted changes, i.e something has broken
|
||||
run: git diff --name-only HEAD --exit-code
|
||||
# Submodule checkout can move the pinned commit to its current branch.
|
||||
run: |
|
||||
git diff --name-only HEAD --exit-code -- . ':(exclude)packages/sdk-components-animation/private-src'
|
||||
git -C packages/sdk-components-animation/private-src diff --name-only HEAD --exit-code
|
||||
|
||||
- name: Show changed files and diff
|
||||
if: ${{ failure() }}
|
||||
run: |
|
||||
echo "Changed files are:"
|
||||
git diff --name-only HEAD
|
||||
git diff HEAD | head -n 1000
|
||||
git diff --name-only HEAD -- . ':(exclude)packages/sdk-components-animation/private-src'
|
||||
git -C packages/sdk-components-animation/private-src diff --name-only HEAD
|
||||
git diff HEAD -- . ':(exclude)packages/sdk-components-animation/private-src' | head -n 1000
|
||||
git -C packages/sdk-components-animation/private-src diff HEAD | head -n 1000
|
||||
@@ -0,0 +1,19 @@
|
||||
name: Workflows for approved forks
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [labeled]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
deployments: write
|
||||
pull-requests: write
|
||||
statuses: write
|
||||
|
||||
jobs:
|
||||
approved-fork-workflows:
|
||||
# GitHub cannot filter labeled events by label name. Gate one workflow call
|
||||
# instead of adding skipped copies of every Main and Vercel workflow job.
|
||||
if: github.event.label.name == 'safe-to-deploy'
|
||||
uses: ./.github/workflows/approved-fork-workflows.yml
|
||||
secrets: inherit
|
||||
+73
-176
@@ -5,12 +5,10 @@ on:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
pull_request_target:
|
||||
types: [labeled]
|
||||
workflow_call:
|
||||
|
||||
# cancel in-progress runs on new commits to same PR (gitub.event.number)
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.number || github.sha }}
|
||||
group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.number || github.sha }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
@@ -19,11 +17,7 @@ permissions:
|
||||
jobs:
|
||||
ssg-artifact:
|
||||
name: Packaged SSG Assets build
|
||||
if: |
|
||||
github.event_name == 'push' ||
|
||||
github.event_name == 'pull_request' ||
|
||||
(github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy')
|
||||
timeout-minutes: 20
|
||||
timeout-minutes: 7
|
||||
runs-on: ubuntu-24.04-arm
|
||||
environment:
|
||||
name: development
|
||||
@@ -32,7 +26,7 @@ jobs:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy' }}
|
||||
allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }}
|
||||
|
||||
- uses: ./.github/actions/submodules-checkout
|
||||
with:
|
||||
@@ -43,23 +37,52 @@ jobs:
|
||||
- name: Build packaged SSG fixture
|
||||
run: pnpm --filter webstudio test:ssg-package
|
||||
|
||||
checks:
|
||||
# Run on push, regular PR (for repo branches), or labeled PR with safe-to-deploy (for forks)
|
||||
if: |
|
||||
github.event_name == 'push' ||
|
||||
github.event_name == 'pull_request' ||
|
||||
(github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy')
|
||||
|
||||
timeout-minutes: 20
|
||||
|
||||
tests:
|
||||
name: tests (${{ matrix.environment }}, ${{ matrix.suite.name }})
|
||||
timeout-minutes: ${{ (matrix.suite.name == 'builder-app' || matrix.suite.name == 'packages') && 12 || 7 }}
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
environment:
|
||||
- empty
|
||||
- development
|
||||
|
||||
suite:
|
||||
- name: packages
|
||||
script: test:packages
|
||||
browsers: chromium-firefox
|
||||
- name: cli
|
||||
script: test:cli
|
||||
browsers: none
|
||||
- name: builder-core
|
||||
script: test:builder:core
|
||||
browsers: chromium
|
||||
- name: builder-app
|
||||
script: test:builder:app
|
||||
browsers: chromium
|
||||
environment:
|
||||
name: ${{ matrix.environment }}
|
||||
env:
|
||||
DATABASE_URL: postgres://
|
||||
AUTH_SECRET: test
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }}
|
||||
|
||||
- uses: ./.github/actions/test-suite
|
||||
with:
|
||||
submodules-ssh-key: ${{ secrets.PRIVATE_GITHUB_DEPLOY_TOKEN }}
|
||||
script: ${{ matrix.suite.script }}
|
||||
browsers: ${{ matrix.suite.browsers }}
|
||||
|
||||
checks:
|
||||
timeout-minutes: 7
|
||||
|
||||
environment:
|
||||
name: empty
|
||||
|
||||
env:
|
||||
DATABASE_URL: postgres://
|
||||
@@ -71,12 +94,7 @@ jobs:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy' }}
|
||||
|
||||
# Will not checkout submodules on empty environment, and will on development
|
||||
- uses: ./.github/actions/submodules-checkout
|
||||
with:
|
||||
submodules-ssh-key: ${{ secrets.PRIVATE_GITHUB_DEPLOY_TOKEN }}
|
||||
allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }}
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
|
||||
@@ -89,8 +107,6 @@ jobs:
|
||||
run: |
|
||||
pnpm install
|
||||
|
||||
- run: echo ===SHA USED=== ${{ github.event.pull_request.head.sha || github.sha }} # todo: remove after check whats happening on main
|
||||
|
||||
- run: |
|
||||
pnpm oxfmt --check
|
||||
|
||||
@@ -110,33 +126,12 @@ jobs:
|
||||
run: |
|
||||
pnpm check:generated-docs
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: playwright-${{ runner.os }}-${{ hashFiles('**/package-lock.json') }}
|
||||
restore-keys: |
|
||||
playwright-${{ runner.os }}-
|
||||
|
||||
- name: Playwright init
|
||||
run: |
|
||||
pnpm playwright install
|
||||
working-directory: packages/sdk-components-animation
|
||||
|
||||
- name: Test
|
||||
run: |
|
||||
pnpm -r test
|
||||
|
||||
- name: Typecheck
|
||||
run: |
|
||||
pnpm -r typecheck
|
||||
|
||||
check-size:
|
||||
# Run on push, regular PR (for repo branches), or labeled PR with safe-to-deploy (for forks)
|
||||
if: |
|
||||
github.event_name == 'push' ||
|
||||
github.event_name == 'pull_request' ||
|
||||
(github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy')
|
||||
timeout-minutes: 7
|
||||
|
||||
runs-on: ubuntu-24.04-arm
|
||||
|
||||
@@ -147,7 +142,7 @@ jobs:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy' }}
|
||||
allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }}
|
||||
|
||||
- uses: ./.github/actions/submodules-checkout
|
||||
with:
|
||||
@@ -157,54 +152,11 @@ jobs:
|
||||
|
||||
- run: pnpm --filter "{./fixtures/*}..." build
|
||||
|
||||
- uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const assertSize = async (directory, maxSize) => {
|
||||
let result = ''
|
||||
await exec.exec('du', ['-sk', directory], {
|
||||
silent: true,
|
||||
listeners: {
|
||||
stdout: (data) => {
|
||||
result += data.toString()
|
||||
}
|
||||
}
|
||||
})
|
||||
const size = Number.parseInt(result, 10)
|
||||
return {
|
||||
passed: size <= maxSize,
|
||||
size,
|
||||
diff: size - maxSize,
|
||||
directory,
|
||||
}
|
||||
}
|
||||
const results = [
|
||||
await assertSize('./fixtures/ssg-cloudflare-pages/dist/client', 356),
|
||||
await assertSize('./fixtures/react-router-netlify/build/client', 376),
|
||||
await assertSize('./fixtures/webstudio-features/build/client', 3684),
|
||||
]
|
||||
for (const result of results) {
|
||||
if (result.passed) {
|
||||
console.info(`${result.directory}: ${result.size}kB (${result.diff}kB)`)
|
||||
} else {
|
||||
console.info('')
|
||||
console.error(`${result.directory}: ${result.size}kB (+${result.diff}kB)`)
|
||||
}
|
||||
}
|
||||
if (results.some(result => result.passed === false)) {
|
||||
console.error('Some fixtures exceeded limits')
|
||||
process.exit(1)
|
||||
}
|
||||
- run: pnpm check:fixture-sizes
|
||||
|
||||
builder-e2e-build:
|
||||
name: builder-e2e build
|
||||
# Run on push, regular PR (for repo branches), or labeled PR with safe-to-deploy (for forks)
|
||||
if: |
|
||||
github.event_name == 'push' ||
|
||||
github.event_name == 'pull_request' ||
|
||||
(github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy')
|
||||
|
||||
timeout-minutes: 20
|
||||
timeout-minutes: 7
|
||||
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
@@ -212,54 +164,42 @@ jobs:
|
||||
name: development
|
||||
|
||||
outputs:
|
||||
shards: ${{ steps.shards.outputs.value }}
|
||||
shards: ${{ steps.build.outputs.shards }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy' }}
|
||||
allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }}
|
||||
|
||||
- uses: ./.github/actions/submodules-checkout
|
||||
- id: build
|
||||
uses: ./.github/actions/builder-e2e-build
|
||||
with:
|
||||
submodules-ssh-key: ${{ secrets.PRIVATE_GITHUB_DEPLOY_TOKEN }}
|
||||
|
||||
supabase-migrations:
|
||||
name: Supabase migrations
|
||||
timeout-minutes: 7
|
||||
runs-on: ubuntu-24.04
|
||||
environment:
|
||||
name: empty
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }}
|
||||
|
||||
- uses: ./.github/actions/ci-setup
|
||||
with:
|
||||
run-scripts: "true"
|
||||
|
||||
- name: Discover builder e2e shards
|
||||
id: shards
|
||||
run: echo "value=$(pnpm --dir apps/builder exec tsx ./e2e/print-shards.ts)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build builder and generated preview dependencies
|
||||
run: pnpm e2e:builder:build
|
||||
|
||||
# Generate this from the current migrations for this workflow run only.
|
||||
# Shards consume the snapshot as a fast, disposable schema cache.
|
||||
- name: Generate builder e2e schema snapshot
|
||||
run: pnpm e2e:builder:refresh-schema-cache
|
||||
|
||||
- name: Upload builder e2e prerequisites
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: builder-e2e-build
|
||||
retention-days: 7
|
||||
path: |
|
||||
apps/builder/build/server
|
||||
apps/builder/build/client/assets
|
||||
packages/*/lib
|
||||
.cache/builder-e2e/schema-*.sql
|
||||
- name: Apply migrations to Supabase PostgreSQL
|
||||
run: pnpm --filter @webstudio-is/builder e2e:supabase-migrations
|
||||
|
||||
builder-e2e:
|
||||
name: builder-e2e (${{ matrix.shard }})
|
||||
# Run on push, regular PR (for repo branches), or labeled PR with safe-to-deploy (for forks)
|
||||
if: |
|
||||
github.event_name == 'push' ||
|
||||
github.event_name == 'pull_request' ||
|
||||
(github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy')
|
||||
|
||||
timeout-minutes: 40
|
||||
timeout-minutes: 12
|
||||
|
||||
needs: builder-e2e-build
|
||||
|
||||
@@ -267,62 +207,19 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: ${{ fromJSON(needs.builder-e2e-build.outputs.shards) }}
|
||||
include: ${{ fromJSON(needs.builder-e2e-build.outputs.shards) }}
|
||||
|
||||
environment:
|
||||
name: development
|
||||
|
||||
env:
|
||||
BUILDER_E2E_COMPOSE_ARGS: "--env-file apps/builder/.env -f apps/builder/docker-compose.yaml -f apps/builder/docker-compose.e2e.yaml"
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.label.name == 'safe-to-deploy' }}
|
||||
allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy' }}
|
||||
|
||||
- uses: ./.github/actions/submodules-checkout
|
||||
- uses: ./.github/actions/builder-e2e-shard
|
||||
with:
|
||||
submodules-ssh-key: ${{ secrets.PRIVATE_GITHUB_DEPLOY_TOKEN }}
|
||||
|
||||
- uses: ./.github/actions/ci-setup
|
||||
with:
|
||||
run-scripts: "true"
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: builder-e2e-playwright-${{ runner.os }}-${{ hashFiles('apps/builder/package.json', 'pnpm-lock.yaml') }}
|
||||
|
||||
- name: Download builder e2e build
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: builder-e2e-build
|
||||
path: .
|
||||
|
||||
- name: Run builder e2e
|
||||
env:
|
||||
E2E_SKIP_BUILDER_BUILD: true
|
||||
E2E_TEST_SHARD: ${{ matrix.shard }}
|
||||
run: |
|
||||
run_builder_e2e() {
|
||||
E2E_TEST_COMMAND_TIMEOUT_SECONDS=300 pnpm e2e:builder
|
||||
}
|
||||
|
||||
run_builder_e2e_keep_logs() {
|
||||
E2E_SKIP_CLEANUP=true E2E_TEST_COMMAND_TIMEOUT_SECONDS=300 pnpm e2e:builder
|
||||
}
|
||||
|
||||
run_builder_e2e || {
|
||||
echo "::warning::Builder e2e shard ${E2E_TEST_SHARD} failed; retrying once"
|
||||
run_builder_e2e_keep_logs
|
||||
}
|
||||
|
||||
- name: Print e2e service logs
|
||||
if: failure()
|
||||
run: docker compose $BUILDER_E2E_COMPOSE_ARGS logs
|
||||
|
||||
- name: Stop e2e services
|
||||
if: always()
|
||||
run: docker compose $BUILDER_E2E_COMPOSE_ARGS down --volumes --remove-orphans
|
||||
shard: ${{ matrix.shard }}
|
||||
partition: ${{ matrix.partition }}
|
||||
@@ -61,6 +61,9 @@ jobs:
|
||||
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
registry_baseline: ${{ steps.registry-baseline.outputs.value }}
|
||||
version: ${{ steps.version.outputs.value }}
|
||||
permissions:
|
||||
contents: write
|
||||
environment:
|
||||
@@ -119,15 +122,32 @@ jobs:
|
||||
echo "Exact registry artifact webstudio@$VERSION was not observable with integrity metadata." >&2
|
||||
exit 1
|
||||
|
||||
- name: Gate exact published CLI against baseline
|
||||
release-smoke:
|
||||
needs: publish
|
||||
timeout-minutes: 20
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: read
|
||||
environment:
|
||||
name: development
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.ref }} # tag name
|
||||
- uses: ./.github/actions/submodules-checkout
|
||||
with:
|
||||
submodules-ssh-key: ${{ secrets.PRIVATE_GITHUB_DEPLOY_TOKEN }}
|
||||
- uses: ./.github/actions/ci-setup
|
||||
|
||||
- name: Verify exact published CLI against baseline
|
||||
id: registry-smoke
|
||||
env:
|
||||
DATABASE_URL: postgres://
|
||||
AUTH_SECRET: test
|
||||
WEBSTUDIO_RELEASE_SMOKE_TOKEN_BUDGET: 6000
|
||||
WEBSTUDIO_RELEASE_SMOKE_CANDIDATE: webstudio@${{ steps.version.outputs.value }}
|
||||
WEBSTUDIO_RELEASE_SMOKE_BASELINE: webstudio@${{ steps.registry-baseline.outputs.value }}
|
||||
WEBSTUDIO_RELEASE_SMOKE_EXPECT_REGISTRY_VERSION: ${{ steps.version.outputs.value }}
|
||||
WEBSTUDIO_RELEASE_SMOKE_CANDIDATE: webstudio@${{ needs.publish.outputs.version }}
|
||||
WEBSTUDIO_RELEASE_SMOKE_BASELINE: webstudio@${{ needs.publish.outputs.registry_baseline }}
|
||||
WEBSTUDIO_RELEASE_SMOKE_EXPECT_REGISTRY_VERSION: ${{ needs.publish.outputs.version }}
|
||||
WEBSTUDIO_RELEASE_SMOKE_REPORT: ${{ github.workspace }}/artifacts/cli-release-smoke.json
|
||||
run: pnpm --filter webstudio test:release-smoke:registry
|
||||
|
||||
@@ -135,7 +155,7 @@ jobs:
|
||||
if: ${{ always() && (steps.registry-smoke.outcome == 'success' || steps.registry-smoke.outcome == 'failure') }}
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: cli-release-smoke-${{ steps.version.outputs.value }}
|
||||
name: cli-release-smoke-${{ needs.publish.outputs.version }}
|
||||
path: artifacts/cli-release-smoke.json
|
||||
if-no-files-found: error
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
name: Remove PR approvals
|
||||
|
||||
# Keep synchronization-only housekeeping out of label-triggered workflows.
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [synchronize]
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
remove-approvals:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Remove revision-specific approval labels
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const labels = new Set(
|
||||
context.payload.pull_request.labels.map(({ name }) => name)
|
||||
);
|
||||
for (const name of ['safe-to-deploy', 'visual-change-approved']) {
|
||||
if (labels.has(name) === false) {
|
||||
continue;
|
||||
}
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
name,
|
||||
});
|
||||
}
|
||||
@@ -2,8 +2,7 @@ name: Vercel Deploy Staging
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request_target:
|
||||
types: [labeled, synchronize]
|
||||
workflow_call:
|
||||
|
||||
# cancel in-progress runs on new commits to same PR (gitub.event.number)
|
||||
concurrency:
|
||||
@@ -17,29 +16,7 @@ permissions:
|
||||
pull-requests: write # needed to remove labels and comment
|
||||
|
||||
jobs:
|
||||
# Remove the safe-to-deploy label when new commits are pushed to a PR (requires re-review)
|
||||
remove-label-on-update:
|
||||
if: github.event_name == 'pull_request_target' && github.event.action == 'synchronize'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Remove safe-to-deploy label
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
name: 'safe-to-deploy'
|
||||
}).catch(() => {});
|
||||
console.log('Removed safe-to-deploy label due to new commits. Re-review required.');
|
||||
|
||||
deployment:
|
||||
# Run on push (for repo branches) OR on labeled event with safe-to-deploy label (for fork PRs)
|
||||
if: |
|
||||
github.event_name == 'push' ||
|
||||
(github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy')
|
||||
|
||||
# Execute development and staging on staging branches
|
||||
# Execute only development on all other branches
|
||||
strategy:
|
||||
@@ -125,11 +102,6 @@ jobs:
|
||||
builder-host: "${{ steps.vercel.outputs.alias }}.${{ matrix.environment }}.webstudio.is"
|
||||
|
||||
deployment-host:
|
||||
# Run on push (for repo branches) OR on labeled event with safe-to-deploy label (for fork PRs)
|
||||
if: |
|
||||
github.event_name == 'push' ||
|
||||
(github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name == 'safe-to-deploy')
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
development-builder-host: ${{ steps.host.outputs.value }}
|
||||
|
||||
@@ -7,11 +7,11 @@ on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, labeled]
|
||||
pull_request_target:
|
||||
types: [labeled, synchronize]
|
||||
types: [opened, synchronize, reopened, labeled]
|
||||
|
||||
concurrency:
|
||||
# A synchronize action emits both pull_request and pull_request_target. Keep
|
||||
# their runs separate so approval cleanup cannot cancel the visual check.
|
||||
# same-repository and fork runs separate.
|
||||
group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.number || github.sha }}
|
||||
cancel-in-progress: true
|
||||
|
||||
@@ -19,28 +19,9 @@ permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
remove-approval:
|
||||
if: github.event_name == 'pull_request_target' && github.event.action == 'synchronize'
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Remove visual change approval
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const labels = context.payload.pull_request.labels.map(({ name }) => name);
|
||||
if (labels.includes('visual-change-approved')) {
|
||||
await github.rest.issues.removeLabel({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
name: 'visual-change-approved',
|
||||
});
|
||||
}
|
||||
|
||||
visual-regression:
|
||||
# Same-repository PRs use the unprivileged event. Organization members'
|
||||
# fork PRs are trusted; every other fork revision needs safe-to-deploy.
|
||||
if: |
|
||||
github.event_name == 'push' ||
|
||||
(
|
||||
@@ -53,18 +34,29 @@ jobs:
|
||||
) ||
|
||||
(
|
||||
github.event_name == 'pull_request_target' &&
|
||||
github.event.action == 'labeled' &&
|
||||
github.event.pull_request.head.repo.full_name != github.repository &&
|
||||
(
|
||||
github.event.label.name == 'safe-to-deploy' ||
|
||||
(
|
||||
github.event.label.name == 'visual-change-approved' &&
|
||||
github.event.pull_request.head.repo.full_name != github.repository &&
|
||||
contains(github.event.pull_request.labels.*.name, 'safe-to-deploy')
|
||||
contains(fromJSON('["OWNER", "MEMBER"]'), github.event.pull_request.author_association) &&
|
||||
(
|
||||
github.event.action != 'labeled' ||
|
||||
github.event.label.name == 'visual-change-approved'
|
||||
)
|
||||
) ||
|
||||
(
|
||||
github.event.action == 'labeled' &&
|
||||
(
|
||||
github.event.label.name == 'safe-to-deploy' ||
|
||||
(
|
||||
github.event.label.name == 'visual-change-approved' &&
|
||||
contains(github.event.pull_request.labels.*.name, 'safe-to-deploy')
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
timeout-minutes: 30
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 7
|
||||
runs-on: ubuntu-24.04
|
||||
environment:
|
||||
name: development
|
||||
steps:
|
||||
@@ -72,6 +64,7 @@ jobs:
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' }}
|
||||
|
||||
- uses: ./.github/actions/submodules-checkout
|
||||
with:
|
||||
@@ -79,11 +72,14 @@ jobs:
|
||||
|
||||
- uses: ./.github/actions/ci-setup
|
||||
|
||||
- name: Cache pinned visual browser
|
||||
- name: Cache Playwright Chromium
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: visual-playwright-${{ runner.os }}-${{ hashFiles('packages/sdk-components-animation/package.json', 'pnpm-lock.yaml') }}
|
||||
path: |
|
||||
~/.cache/ms-playwright/chromium-*
|
||||
~/.cache/ms-playwright/chromium_headless_shell-*
|
||||
~/.cache/ms-playwright/ffmpeg-*
|
||||
key: playwright-chromium-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
|
||||
- name: Install pinned visual browser
|
||||
run: |
|
||||
|
||||
@@ -8,6 +8,8 @@ yarn.lock
|
||||
|
||||
# testing
|
||||
coverage
|
||||
playwright-report
|
||||
test-results
|
||||
|
||||
# remix
|
||||
build
|
||||
@@ -70,3 +72,7 @@ packages/prisma-client/src/__generated__
|
||||
|
||||
# copilot instructions
|
||||
.github/instructions
|
||||
|
||||
# local agent instructions
|
||||
AGENTS.md
|
||||
agents.md
|
||||
@@ -16,6 +16,7 @@ export default {
|
||||
"@storybook/addon-controls",
|
||||
"@storybook/addon-actions",
|
||||
"@storybook/addon-backgrounds",
|
||||
"@storybook/addon-toolbars",
|
||||
],
|
||||
async viteFinal(config) {
|
||||
return {
|
||||
|
||||
+174
-26
@@ -1,15 +1,128 @@
|
||||
import "./request-fixtures";
|
||||
import { updateCsrfToken } from "../apps/builder/app/shared/csrf.client";
|
||||
|
||||
// Use a synthetic CSRF value in the isolated Storybook environment.
|
||||
updateCsrfToken("storybook-fixture");
|
||||
import type { Preview } from "@storybook/react";
|
||||
import * as React from "react";
|
||||
import { useEffect } from "react";
|
||||
import { useEffect, useLayoutEffect, type ReactNode } from "react";
|
||||
import { TooltipProvider } from "@radix-ui/react-tooltip";
|
||||
import { setEnv } from "../packages/feature-flags/src/index";
|
||||
import { theme, globalCss } from "../packages/design-system/src/index";
|
||||
import { color } from "../packages/design-system/src/design-tokens";
|
||||
import {
|
||||
cssVar,
|
||||
type ThemeVariableName,
|
||||
} from "../packages/design-system/src/index";
|
||||
|
||||
// this adds <style> tags to the <head> of the document
|
||||
import "@fontsource-variable/inter";
|
||||
import "@fontsource-variable/manrope";
|
||||
import "@fontsource/roboto-mono";
|
||||
import "../packages/design-system/src/global.css";
|
||||
|
||||
const themeTestCases = {
|
||||
default: {},
|
||||
monochrome: {
|
||||
"--theme-color-neutral": "oklch(50% 0 0)",
|
||||
"--theme-color-accent": "oklch(50% 0 0)",
|
||||
"--theme-color-positive": "oklch(50% 0.14 152)",
|
||||
"--theme-color-negative": "oklch(50% 0.19 27)",
|
||||
"--theme-color-warning": "oklch(50% 0.14 75)",
|
||||
"--theme-color-informative": "oklch(50% 0.14 225)",
|
||||
"--theme-contrast-content": "100%",
|
||||
"--theme-contrast-surface": "70%",
|
||||
"--theme-contrast-border": "100%",
|
||||
},
|
||||
warm: {
|
||||
"--theme-color-neutral": "oklch(55% 0.02 70)",
|
||||
"--theme-color-accent": "oklch(60% 0.18 35)",
|
||||
"--theme-color-positive": "oklch(55% 0.14 135)",
|
||||
"--theme-color-negative": "oklch(55% 0.19 25)",
|
||||
"--theme-color-warning": "oklch(55% 0.14 85)",
|
||||
"--theme-color-informative": "oklch(55% 0.14 210)",
|
||||
"--theme-contrast-content": "15%",
|
||||
"--theme-contrast-surface": "0%",
|
||||
"--theme-contrast-border": "0%",
|
||||
},
|
||||
vivid: {
|
||||
"--theme-color-neutral": "oklch(45% 0.02 300)",
|
||||
"--theme-color-accent": "oklch(65% 0.3 300)",
|
||||
"--theme-color-positive": "oklch(60% 0.3 145)",
|
||||
"--theme-color-negative": "oklch(60% 0.3 20)",
|
||||
"--theme-color-warning": "oklch(65% 0.3 80)",
|
||||
"--theme-color-informative": "oklch(60% 0.3 225)",
|
||||
"--theme-contrast-content": "100%",
|
||||
"--theme-contrast-surface": "100%",
|
||||
"--theme-contrast-border": "100%",
|
||||
},
|
||||
} satisfies Record<string, Partial<Record<ThemeVariableName, string>>>;
|
||||
|
||||
const themeVariableNames = new Set(
|
||||
Object.values(themeTestCases).flatMap((testCase) => Object.keys(testCase))
|
||||
);
|
||||
|
||||
type ThemeTestCase = keyof typeof themeTestCases;
|
||||
type ColorScheme = "light" | "dark";
|
||||
|
||||
const isThemeTestCase = (value: unknown): value is ThemeTestCase =>
|
||||
typeof value === "string" && value in themeTestCases;
|
||||
|
||||
const ThemeGlobals = ({
|
||||
children,
|
||||
themeTestCase,
|
||||
colorScheme,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
themeTestCase: ThemeTestCase;
|
||||
colorScheme: ColorScheme;
|
||||
}) => {
|
||||
useLayoutEffect(() => {
|
||||
const root = document.documentElement;
|
||||
const previousScheme = root.getAttribute("data-color-scheme");
|
||||
const previousBodyBackground = document.body.style.backgroundColor;
|
||||
const previousBodyBackgroundPriority =
|
||||
document.body.style.getPropertyPriority("background-color");
|
||||
const previousTheme = new Map(
|
||||
Array.from(themeVariableNames, (name) => [
|
||||
name,
|
||||
root.style.getPropertyValue(name),
|
||||
])
|
||||
);
|
||||
|
||||
for (const name of themeVariableNames) {
|
||||
root.style.removeProperty(name);
|
||||
}
|
||||
for (const [name, value] of Object.entries(themeTestCases[themeTestCase])) {
|
||||
root.style.setProperty(name, value);
|
||||
}
|
||||
root.setAttribute("data-color-scheme", colorScheme);
|
||||
|
||||
if (themeTestCase !== "default" || colorScheme === "dark") {
|
||||
document.body.style.setProperty(
|
||||
"background-color",
|
||||
"var(--background-primary)",
|
||||
"important"
|
||||
);
|
||||
}
|
||||
|
||||
return () => {
|
||||
for (const [name, value] of previousTheme) {
|
||||
if (value === "") {
|
||||
root.style.removeProperty(name);
|
||||
} else {
|
||||
root.style.setProperty(name, value);
|
||||
}
|
||||
}
|
||||
if (previousScheme === null) {
|
||||
root.removeAttribute("data-color-scheme");
|
||||
} else {
|
||||
root.setAttribute("data-color-scheme", previousScheme);
|
||||
}
|
||||
document.body.style.setProperty(
|
||||
"background-color",
|
||||
previousBodyBackground,
|
||||
previousBodyBackgroundPriority
|
||||
);
|
||||
};
|
||||
}, [colorScheme, themeTestCase]);
|
||||
|
||||
return children;
|
||||
};
|
||||
|
||||
const WaitForFonts = ({ children }) => {
|
||||
const [isFontsLoaded, setIsFontsLoaded] = React.useState(false);
|
||||
@@ -38,28 +151,62 @@ const WaitForFonts = ({ children }) => {
|
||||
);
|
||||
};
|
||||
|
||||
const globalStyles = globalCss({
|
||||
body: {
|
||||
color: theme.colors.foregroundMain,
|
||||
fontFamily: theme.fonts.sans,
|
||||
},
|
||||
});
|
||||
|
||||
export const decorators: Preview["decorators"] = [
|
||||
(Story) => {
|
||||
globalStyles();
|
||||
const decorators: Preview["decorators"] = [
|
||||
(Story, { globals }) => {
|
||||
setEnv("*");
|
||||
const themeTestCase = isThemeTestCase(globals.themeTestCase)
|
||||
? globals.themeTestCase
|
||||
: "default";
|
||||
const colorScheme = globals.colorScheme === "dark" ? "dark" : "light";
|
||||
return (
|
||||
// waiting for fonts makes screenshot tests more stable
|
||||
<WaitForFonts>
|
||||
<TooltipProvider>
|
||||
<Story />
|
||||
</TooltipProvider>
|
||||
</WaitForFonts>
|
||||
<ThemeGlobals themeTestCase={themeTestCase} colorScheme={colorScheme}>
|
||||
<WaitForFonts>
|
||||
<TooltipProvider>
|
||||
<Story />
|
||||
</TooltipProvider>
|
||||
</WaitForFonts>
|
||||
</ThemeGlobals>
|
||||
);
|
||||
},
|
||||
];
|
||||
|
||||
const globalTypes: Preview["globalTypes"] = {
|
||||
themeTestCase: {
|
||||
name: "Theme test case",
|
||||
description: "Apply a bounded theme configuration to every story.",
|
||||
toolbar: {
|
||||
title: "Theme",
|
||||
icon: "paintbrush",
|
||||
items: [
|
||||
{ value: "default", title: "Default" },
|
||||
{ value: "monochrome", title: "Monochrome high contrast" },
|
||||
{ value: "warm", title: "Warm and soft" },
|
||||
{ value: "vivid", title: "Vivid and structured" },
|
||||
],
|
||||
dynamicTitle: true,
|
||||
},
|
||||
},
|
||||
colorScheme: {
|
||||
name: "Color scheme",
|
||||
description: "Render semantic colors in the light or dark scheme.",
|
||||
toolbar: {
|
||||
title: "Color scheme",
|
||||
icon: "mirror",
|
||||
items: [
|
||||
{ value: "light", title: "Light" },
|
||||
{ value: "dark", title: "Dark" },
|
||||
],
|
||||
dynamicTitle: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const initialGlobals: Preview["initialGlobals"] = {
|
||||
themeTestCase: "default",
|
||||
colorScheme: "light",
|
||||
};
|
||||
|
||||
const parameters: Preview["parameters"] = {
|
||||
actions: { argTypesRegex: "^on[A-Z].*" },
|
||||
controls: {
|
||||
@@ -71,17 +218,18 @@ const parameters: Preview["parameters"] = {
|
||||
backgrounds: {
|
||||
default: "White",
|
||||
values: [
|
||||
{ name: "Primary", value: cssVar("--background-primary") },
|
||||
{ name: "Secondary", value: cssVar("--background-secondary") },
|
||||
{ name: "Inverse", value: cssVar("--background-inverse") },
|
||||
{ name: "White", value: "#ffffff" },
|
||||
{ name: "Black", value: "#000000" },
|
||||
{ name: "Panel", value: color.backgroundPanel },
|
||||
{ name: "Maintenance Dark", value: color.maintenanceDark },
|
||||
{ name: "Maintenance Medium", value: color.maintenanceMedium },
|
||||
{ name: "Maintenance Light", value: color.maintenanceLight },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export default {
|
||||
decorators,
|
||||
globalTypes,
|
||||
initialGlobals,
|
||||
parameters,
|
||||
} satisfies Preview;
|
||||
@@ -0,0 +1,27 @@
|
||||
/** Story-only HTTP boundary. Install before stories import clients that capture fetch. */
|
||||
export type RequestFixture = (
|
||||
request: Request
|
||||
) => Response | Promise<Response> | undefined;
|
||||
|
||||
const originalFetch = globalThis.fetch;
|
||||
let fixture: RequestFixture | undefined;
|
||||
|
||||
globalThis.fetch = async (input, init) => {
|
||||
if (fixture === undefined) {
|
||||
return originalFetch(input, init);
|
||||
}
|
||||
const request = new Request(
|
||||
typeof input === "string" ? new URL(input, location.href) : input,
|
||||
init
|
||||
);
|
||||
const response = fixture(request);
|
||||
return response === undefined ? originalFetch(input, init) : response;
|
||||
};
|
||||
|
||||
export const setRequestFixture = (next: RequestFixture) => {
|
||||
const previous = fixture;
|
||||
fixture = next;
|
||||
return () => {
|
||||
fixture = previous;
|
||||
};
|
||||
};
|
||||
Vendored
+4
-1
@@ -725,7 +725,10 @@ declare module "css-tree" {
|
||||
// -------------------------------------------------
|
||||
export const tokenTypes: Record<string, number>;
|
||||
export const tokenNames: string[];
|
||||
export function tokenize(input: string): IterableIterator<any>;
|
||||
export function tokenize(
|
||||
input: string,
|
||||
onToken: (type: number, start: number, end: number) => void
|
||||
): void;
|
||||
|
||||
// Syntax factory and forking
|
||||
export function createSyntax(config: any): any;
|
||||
|
||||
@@ -10,8 +10,7 @@
|
||||
|
||||
- [Blog](https://webstudio.is/blog)
|
||||
- [Documentation](https://docs.webstudio.is/)
|
||||
- [Brand and Product Design](https://docs.webstudio.is/contributing/contributing-for-designers)
|
||||
- [Contributing Guide for Devs](https://docs.webstudio.is/contributing/contributing-for-developers)
|
||||
- [Contributing](https://docs.webstudio.is/contributing/contributions)
|
||||
- [Builder Issues Tracker](https://github.com/webstudio-is/webstudio/issues)
|
||||
- [Roadmap](https://github.com/orgs/webstudio-is/projects/11)
|
||||
|
||||
|
||||
+1
-5
@@ -30,8 +30,7 @@ POSTGREST_API_KEY=
|
||||
# S3_ACCESS_KEY_ID=
|
||||
# S3_SECRET_ACCESS_KEY=
|
||||
|
||||
# if using r2 this your worker url
|
||||
# ASSET_CDN_URL=https://assets.webstudio.is
|
||||
# Asset CDN origin used by published builds, without a trailing slash.
|
||||
|
||||
# Publisher config
|
||||
# PUBLISHER_HOST=wstd.io
|
||||
@@ -70,8 +69,6 @@ PLANS='[
|
||||
"allowContentMode": true,
|
||||
"allowStagingPublish": true,
|
||||
"allowAdvancedPublishDiagnostics": true,
|
||||
"publishLogRetentionDays": 1,
|
||||
"publishActivityRetentionDays": 30,
|
||||
"maxContactEmailsPerProject": 5,
|
||||
"maxDomainsAllowedPerUser": 200,
|
||||
"maxDailyPublishesPerUser": 100,
|
||||
@@ -83,7 +80,6 @@ PLANS='[
|
||||
"name": "Team",
|
||||
"extends": "Pro",
|
||||
"features": {
|
||||
"publishLogRetentionDays": 30,
|
||||
"maxWorkspaces": 20,
|
||||
"seatsIncluded": 4,
|
||||
"maxSeatsPerWorkspace": 20
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
/* Login alone locks the UI document; dashboard routes retain document scrolling. */
|
||||
body {
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -28,3 +28,19 @@ export const Auth: StoryFn<typeof LoginComponent> = () => {
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const Dark = Auth.bind({});
|
||||
Dark.globals = { colorScheme: "dark" };
|
||||
|
||||
export const Error = () => {
|
||||
const router = createRouter(
|
||||
<LoginComponent
|
||||
isGoogleEnabled
|
||||
isGithubEnabled={false}
|
||||
isSecretLoginEnabled
|
||||
errorMessage="Authentication failed"
|
||||
devPlanNames={["Free", "Pro"]}
|
||||
/>
|
||||
);
|
||||
return <RouterProvider router={router} />;
|
||||
};
|
||||
@@ -2,23 +2,16 @@ import { TooltipProvider } from "@radix-ui/react-tooltip";
|
||||
import {
|
||||
Button,
|
||||
Flex,
|
||||
globalCss,
|
||||
rawTheme,
|
||||
Text,
|
||||
theme,
|
||||
cssVar,
|
||||
webstudioBrand,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { GithubIcon, GoogleIcon, WebstudioIcon } from "@webstudio-is/icons";
|
||||
import { Form } from "@remix-run/react";
|
||||
import { authPath } from "~/shared/router-utils";
|
||||
import { SecretLogin } from "./secret-login";
|
||||
|
||||
const globalStyles = globalCss({
|
||||
body: {
|
||||
margin: 0,
|
||||
overflow: "hidden",
|
||||
},
|
||||
});
|
||||
|
||||
export type LoginProps = {
|
||||
errorMessage?: string;
|
||||
isGithubEnabled?: boolean;
|
||||
@@ -34,14 +27,14 @@ export const Login = ({
|
||||
isSecretLoginEnabled,
|
||||
devPlanNames,
|
||||
}: LoginProps) => {
|
||||
globalStyles();
|
||||
return (
|
||||
<Flex
|
||||
align="center"
|
||||
justify="center"
|
||||
css={{
|
||||
height: "100vh",
|
||||
background: theme.colors.brandBackgroundDashboard,
|
||||
color: cssVar("--foreground-primary"),
|
||||
background: webstudioBrand.backgroundGradient,
|
||||
}}
|
||||
>
|
||||
<Flex
|
||||
@@ -53,9 +46,7 @@ export const Login = ({
|
||||
minWidth: theme.spacing[20],
|
||||
padding: theme.spacing[17],
|
||||
borderRadius: theme.spacing[5],
|
||||
[`@media (min-width: ${rawTheme.spacing[35]})`]: {
|
||||
backgroundColor: `rgba(255, 255, 255, 0.5)`,
|
||||
},
|
||||
backgroundColor: `oklch(from ${cssVar("--background-primary")} l c h / 50%)`,
|
||||
}}
|
||||
>
|
||||
<WebstudioIcon size={48} />
|
||||
@@ -80,7 +71,7 @@ export const Login = ({
|
||||
prefix={<GithubIcon size={22} fill="currentColor" />}
|
||||
color="ghost"
|
||||
css={{
|
||||
border: `1px solid ${theme.colors.borderDark}`,
|
||||
border: `1px solid ${cssVar("--border-default")}`,
|
||||
height: theme.spacing[15],
|
||||
}}
|
||||
formAction={authPath({ provider: "github" })}
|
||||
|
||||
@@ -37,19 +37,19 @@ export const SecretLogin = ({ devPlanNames }: SecretLoginProps) => {
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Button type="submit">Login</Button>
|
||||
<Button color="primary" type="submit">
|
||||
Login
|
||||
</Button>
|
||||
</Flex>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
onClick={() => setShow(true)}
|
||||
color="neutral"
|
||||
css={{ height: theme.spacing[15] }}
|
||||
>
|
||||
<Button onClick={() => setShow(true)} css={{ height: theme.spacing[15] }}>
|
||||
Login with Secret
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
undefined;
|
||||
@@ -6,11 +6,7 @@ body {
|
||||
overflow: hidden;
|
||||
overscroll-behavior: contain;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
/*
|
||||
This is the top bar and loading screen color (--colors-backgroundTopbar).
|
||||
We are setting it to avoid a white screen flash when opening project from the dashboard.
|
||||
*/
|
||||
background-color: #2d2d2d;
|
||||
background-color: var(--background-primary);
|
||||
}
|
||||
|
||||
[data-radix-scroll-area-viewport] {
|
||||
@@ -25,5 +21,10 @@ body {
|
||||
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--colors-foregroundScrollBar) transparent;
|
||||
scrollbar-color: color-mix(
|
||||
in oklab,
|
||||
var(--foreground-secondary) 60%,
|
||||
transparent
|
||||
)
|
||||
transparent;
|
||||
}
|
||||
@@ -9,12 +9,14 @@ import {
|
||||
Flex,
|
||||
Grid,
|
||||
rawTheme,
|
||||
cssVar,
|
||||
} from "@webstudio-is/design-system";
|
||||
import type { AuthPermit } from "@webstudio-is/trpc-interface/index.server";
|
||||
import type { Role } from "@webstudio-is/project";
|
||||
import { initializeClientSync, getSyncClient } from "~/shared/sync/sync-client";
|
||||
import { usePreventUnload } from "~/shared/sync/project-queue";
|
||||
import { usePublish, $publisher } from "~/shared/pubsub";
|
||||
import { subscribePreviewFormRequests } from "~/shared/preview-form-parent";
|
||||
import { Inspector } from "./inspector";
|
||||
import { Topbar } from "./shared/topbar";
|
||||
import { Footer } from "./features/footer";
|
||||
@@ -42,6 +44,7 @@ import { $settings, type Settings } from "./shared/client-settings";
|
||||
import { builderUrl, getCanvasUrl } from "~/shared/router-utils";
|
||||
import { BlockingAlerts } from "./features/blocking-alerts";
|
||||
import { useSyncPageUrl } from "~/shared/pages";
|
||||
import { PreviewNavigationObserver } from "~/shared/pages/use-switch-page";
|
||||
import { useMount, useUnmount } from "~/shared/hook-utils/use-mount";
|
||||
import { subscribeCommands } from "~/builder/shared/commands";
|
||||
import { ProjectSettings } from "~/shared/project-settings";
|
||||
@@ -70,6 +73,7 @@ import { KeyboardShortcutsDialog } from "./features/keyboard-shortcuts-dialog";
|
||||
import { TokenConflictDialog } from "~/shared/token-conflict-dialog";
|
||||
import { RootStyleConflictDialog } from "~/shared/root-style-conflict-dialog";
|
||||
import { DesignTokenImportDialog } from "~/shared/design-token-import-dialog";
|
||||
import { TemplateNameConfirmationDialog } from "./features/template-name-confirmation-dialog";
|
||||
import type { User } from "~/shared/db/user.server";
|
||||
|
||||
import {
|
||||
@@ -120,7 +124,7 @@ const SidePanel = ({
|
||||
fg: 0,
|
||||
// Left sidebar tabs won't be able to pop out to the right if we set overflowX to auto.
|
||||
//overflowY: "auto",
|
||||
backgroundColor: theme.colors.backgroundPanel,
|
||||
backgroundColor: cssVar("--background-primary"),
|
||||
height: "100%",
|
||||
...css,
|
||||
}}
|
||||
@@ -333,6 +337,7 @@ export const Builder = (props: BuilderProps) => {
|
||||
useEffect(() => {
|
||||
$publisher.set({ publish });
|
||||
}, [publish]);
|
||||
useEffect(() => subscribePreviewFormRequests(publish), [publish]);
|
||||
|
||||
const project = useStore($project);
|
||||
|
||||
@@ -413,6 +418,7 @@ export const Builder = (props: BuilderProps) => {
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
{isPreviewMode && <PreviewNavigationObserver />}
|
||||
<div
|
||||
style={{ display: "contents" }}
|
||||
onPointerDown={inertHandlers.onPointerDown}
|
||||
@@ -474,15 +480,13 @@ export const Builder = (props: BuilderProps) => {
|
||||
left: 0,
|
||||
bottom: 0,
|
||||
width: 1,
|
||||
background: theme.colors.borderMain,
|
||||
background: cssVar("--border-default"),
|
||||
zIndex: 1,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Inspector navigatorLayout={navigatorLayout} />
|
||||
</SidePanel>
|
||||
<Main css={{ pointerEvents: "none" }}>
|
||||
<CanvasToolsContainer />
|
||||
</Main>
|
||||
{project ? (
|
||||
<Topbar
|
||||
project={project}
|
||||
@@ -529,6 +533,7 @@ export const Builder = (props: BuilderProps) => {
|
||||
<DesignTokenImportDialog />
|
||||
<TokenConflictDialog />
|
||||
<RootStyleConflictDialog />
|
||||
<TemplateNameConfirmationDialog />
|
||||
<RemoteDialog />
|
||||
<Toaster />
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useStore } from "@nanostores/react";
|
||||
import type { Meta, StoryFn } from "@storybook/react";
|
||||
import { StorySection, Text } from "@webstudio-is/design-system";
|
||||
import { ToolbarButton } from "@webstudio-is/design-system";
|
||||
import { WebstudioIcon } from "@webstudio-is/icons";
|
||||
import { IconButton, StorySection, Text } from "@webstudio-is/design-system";
|
||||
import { MenuIcon } from "@webstudio-is/icons";
|
||||
import { TopbarLayout } from "~/builder/shared/topbar";
|
||||
import { AddressBarPopover } from "./address-bar";
|
||||
import { $dataSources, $pages } from "~/shared/sync/data-stores";
|
||||
@@ -88,9 +87,9 @@ export const AddressBar: StoryFn = () => {
|
||||
<StorySection title="Address Bar">
|
||||
<TopbarLayout
|
||||
menu={
|
||||
<ToolbarButton aria-label="Menu">
|
||||
<WebstudioIcon size={22} />
|
||||
</ToolbarButton>
|
||||
<IconButton type="button" size="large" aria-label="Menu">
|
||||
<MenuIcon size={22} />
|
||||
</IconButton>
|
||||
}
|
||||
left={<AddressBarPopover />}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { userEvent } from "@vitest/browser/context";
|
||||
import { expect, test } from "vitest";
|
||||
import { TooltipProvider } from "@webstudio-is/design-system";
|
||||
import { $pages } from "~/shared/sync/data-stores";
|
||||
import { $selectedPageId } from "~/shared/nano-states";
|
||||
import { $currentSystem, $systemDataByPage } from "~/shared/system";
|
||||
import { registerContainers } from "~/shared/sync/sync-stores";
|
||||
import { AddressBarPopover } from "./address-bar";
|
||||
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
registerContainers();
|
||||
|
||||
test.each(["hover", "keyboard"])(
|
||||
"typing a new address clears a %s history suggestion",
|
||||
async (selection) => {
|
||||
const previousPages = $pages.get();
|
||||
const previousPageId = $selectedPageId.get();
|
||||
const previousSystem = $systemDataByPage.get();
|
||||
$systemDataByPage.set(new Map());
|
||||
$pages.set({
|
||||
homePageId: "home",
|
||||
rootFolderId: "root",
|
||||
folders: new Map([
|
||||
[
|
||||
"root",
|
||||
{ id: "root", name: "", slug: "", children: ["home", "dynamic"] },
|
||||
],
|
||||
]),
|
||||
pages: new Map([
|
||||
[
|
||||
"home",
|
||||
{
|
||||
id: "home",
|
||||
name: "Home",
|
||||
path: "",
|
||||
title: "",
|
||||
meta: {},
|
||||
rootInstanceId: "home-root",
|
||||
},
|
||||
],
|
||||
[
|
||||
"dynamic",
|
||||
{
|
||||
id: "dynamic",
|
||||
name: "Dynamic",
|
||||
path: "/blog/:slug",
|
||||
title: "",
|
||||
meta: {},
|
||||
rootInstanceId: "dynamic-root",
|
||||
history: ["/blog/previous", "/blog/older"],
|
||||
},
|
||||
],
|
||||
]),
|
||||
});
|
||||
$selectedPageId.set("dynamic");
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<AddressBarPopover />
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
await act(async () =>
|
||||
userEvent.click(container.querySelector("button")!)
|
||||
);
|
||||
const input =
|
||||
document.querySelector<HTMLInputElement>('input[name="slug"]')!;
|
||||
await act(async () => userEvent.click(input));
|
||||
if (selection === "hover") {
|
||||
const olderOption = Array.from(
|
||||
document.querySelectorAll<HTMLElement>('[role="option"]')
|
||||
).find((option) => option.textContent === "/blog/older")!;
|
||||
await act(async () => userEvent.hover(olderOption));
|
||||
} else {
|
||||
await act(async () => userEvent.keyboard("{ArrowDown}"));
|
||||
}
|
||||
expect(
|
||||
document.querySelector('[role="option"][aria-selected="true"]')
|
||||
).not.toBeNull();
|
||||
await act(async () => userEvent.fill(input, "new-address"));
|
||||
await act(async () => userEvent.keyboard("{Enter}"));
|
||||
expect($currentSystem.get().params.slug).toBe("new-address");
|
||||
await act(async () =>
|
||||
userEvent.click(container.querySelector("button")!)
|
||||
);
|
||||
expect(
|
||||
document.querySelector<HTMLInputElement>('input[name="slug"]')?.value
|
||||
).toBe("new-address");
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
$pages.set(previousPages);
|
||||
$selectedPageId.set(previousPageId);
|
||||
$systemDataByPage.set(previousSystem);
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
theme,
|
||||
textVariants,
|
||||
InputErrorsTooltip,
|
||||
ToolbarButton,
|
||||
Popover,
|
||||
PopoverTrigger,
|
||||
PopoverContent,
|
||||
@@ -30,9 +29,10 @@ import { CheckMarkIcon, CopyIcon, DynamicPageIcon } from "@webstudio-is/icons";
|
||||
import {
|
||||
compilePathnamePattern,
|
||||
isPathnamePattern,
|
||||
matchPathnamePattern,
|
||||
tokenizePathnamePattern,
|
||||
} from "@webstudio-is/project-build/runtime";
|
||||
import { matchPathnamePattern } from "@webstudio-is/wsauth";
|
||||
import { toWebstudioParams } from "@webstudio-is/react-sdk";
|
||||
import {
|
||||
$selectedPage,
|
||||
$selectedPagePath,
|
||||
@@ -145,6 +145,9 @@ const Suggestions = ({
|
||||
return;
|
||||
}
|
||||
const handleInput = () => {
|
||||
menuRef.current
|
||||
?.querySelector("[role=option][aria-selected=true]")
|
||||
?.removeAttribute("aria-selected");
|
||||
setIsListOpen(true);
|
||||
};
|
||||
let frameId: undefined | number;
|
||||
@@ -309,7 +312,9 @@ const AddressBar = forwardRef<
|
||||
options={history}
|
||||
onSelect={(option) => {
|
||||
flushSync(() => {
|
||||
setPathParams(matchPathnamePattern(path, option) ?? {});
|
||||
setPathParams(
|
||||
toWebstudioParams(path, matchPathnamePattern(path, option) ?? {})
|
||||
);
|
||||
});
|
||||
containerRef.current?.requestSubmit();
|
||||
}}
|
||||
@@ -369,11 +374,7 @@ export const AddressBarPopover = () => {
|
||||
if (isPathnamePattern(path) === false) {
|
||||
return (
|
||||
<Tooltip {...tooltipProps}>
|
||||
<ToolbarButton
|
||||
{...buttonProps}
|
||||
aria-label="Copy page URL"
|
||||
tabIndex={0}
|
||||
/>
|
||||
<IconButton {...buttonProps} type="button" aria-label="Copy page URL" />
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -387,11 +388,11 @@ export const AddressBarPopover = () => {
|
||||
}}
|
||||
>
|
||||
<PopoverTrigger asChild>
|
||||
<ToolbarButton aria-label="Toggle dynamic page address" tabIndex={0}>
|
||||
<IconButton type="button" aria-label="Toggle dynamic page address">
|
||||
<DynamicPageIcon />
|
||||
</ToolbarButton>
|
||||
</IconButton>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent sideOffset={0} collisionPadding={4} align="start">
|
||||
<PopoverContent collisionPadding={4} align="start">
|
||||
<AddressBar ref={formRef} onSubmit={() => setIsOpen(false)} />
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { Asset } from "@webstudio-is/sdk";
|
||||
import type { Project } from "@webstudio-is/project";
|
||||
import {
|
||||
createAssetFolderFixture,
|
||||
createAssetFoldersFixture,
|
||||
} from "@webstudio-is/sdk/testing";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { createDefaultCollectionConfig } from "@webstudio-is/content-engine";
|
||||
import {
|
||||
assetContentDescriptorHeader,
|
||||
serializeAssetContentDescriptor,
|
||||
} from "@webstudio-is/protocol/asset-resource-api";
|
||||
import {
|
||||
createAssetContentBridge,
|
||||
getAssetContentBridge,
|
||||
__testing__,
|
||||
} from "~/shared/asset-content-bridge.client";
|
||||
import {
|
||||
$assets,
|
||||
$assetFolders,
|
||||
$pages,
|
||||
$project,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { $authPermit, $builderMode } from "~/shared/nano-states";
|
||||
import { $settings } from "~/builder/shared/client-settings";
|
||||
import { AssetsPanel } from "./assets";
|
||||
const { initBridge, clearBridge } = __testing__;
|
||||
export default { title: "Assets/Collections", component: AssetsPanel };
|
||||
type State =
|
||||
| "ready"
|
||||
| "loading"
|
||||
| "invalid"
|
||||
| "missingTemplate"
|
||||
| "unavailable"
|
||||
| "entryWarning"
|
||||
| "readOnly";
|
||||
const CollectionStory = ({ state }: { state: State }) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
const previous = [
|
||||
$assets.get(),
|
||||
$assetFolders.get(),
|
||||
$pages.get(),
|
||||
$project.get(),
|
||||
$authPermit.get(),
|
||||
$builderMode.get(),
|
||||
$settings.get(),
|
||||
] as const;
|
||||
let previousBridge: ReturnType<typeof getAssetContentBridge> | undefined;
|
||||
try {
|
||||
previousBridge = getAssetContentBridge();
|
||||
} catch {}
|
||||
const projectId = `collection-story-${state}`;
|
||||
const sources = new Map([
|
||||
[
|
||||
"collection.json",
|
||||
state === "invalid" ? "{}" : createDefaultCollectionConfig(),
|
||||
],
|
||||
[
|
||||
"template.mdx",
|
||||
"---\ntitle: Article\nslug: article\ndraft: true\n---\n# Article",
|
||||
],
|
||||
[
|
||||
"post.mdx",
|
||||
state === "entryWarning"
|
||||
? "---\ntitle: \nslug: wrong\ndraft: yes\n---\nBody"
|
||||
: "---\ntitle: Post\nslug: post\ndraft: false\n---\nBody",
|
||||
],
|
||||
]);
|
||||
if (state === "missingTemplate") {
|
||||
sources.delete("template.mdx");
|
||||
}
|
||||
const files: Asset[] = Array.from(sources, ([name, source]) => ({
|
||||
id: name,
|
||||
name,
|
||||
projectId,
|
||||
folderId: "posts",
|
||||
type: "file",
|
||||
format: name.endsWith("json") ? "json" : "mdx",
|
||||
size: new TextEncoder().encode(source).length,
|
||||
meta: {},
|
||||
createdAt: "2026-11-01T00:00:00Z",
|
||||
}));
|
||||
initBridge(
|
||||
createAssetContentBridge({
|
||||
origin: location.origin,
|
||||
authorize: () => true,
|
||||
requireReload: () => {},
|
||||
request: async (url, init) => {
|
||||
if (state === "loading") {
|
||||
return new Promise<Response>(() => {});
|
||||
}
|
||||
if (state === "unavailable") {
|
||||
throw new Error("Example offline response");
|
||||
}
|
||||
if (init?.method && init.method !== "GET") {
|
||||
return new Response(undefined, { status: 403 });
|
||||
}
|
||||
const name = decodeURIComponent(new URL(url).pathname.split("/")[3]);
|
||||
const asset = files.find((file) => file.id === name);
|
||||
if (!asset) {
|
||||
return new Response(undefined, { status: 404 });
|
||||
}
|
||||
return new Response(sources.get(name), {
|
||||
// Each fixture fits in the initial frontmatter read range.
|
||||
status: new Headers(init?.headers).has("range") ? 206 : 200,
|
||||
headers: {
|
||||
[assetContentDescriptorHeader]:
|
||||
serializeAssetContentDescriptor(asset),
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
);
|
||||
$project.set({ id: projectId, title: "Collection example" } as Project);
|
||||
$assets.set(new Map(files.map((file) => [file.id, file])));
|
||||
$assetFolders.set(
|
||||
createAssetFoldersFixture(
|
||||
createAssetFolderFixture({ id: "posts", name: "Posts" })
|
||||
)
|
||||
);
|
||||
$pages.set(createDefaultPages({ rootInstanceId: "body" }));
|
||||
$authPermit.set(state === "readOnly" ? "view" : "own");
|
||||
$builderMode.set("design");
|
||||
$settings.set({
|
||||
...$settings.get(),
|
||||
lastAssetFolderIds: { [projectId]: "posts" },
|
||||
});
|
||||
setReady(true);
|
||||
return () => {
|
||||
setReady(false);
|
||||
$assets.set(previous[0]);
|
||||
$assetFolders.set(previous[1]);
|
||||
$pages.set(previous[2]);
|
||||
$project.set(previous[3]);
|
||||
$authPermit.set(previous[4]);
|
||||
$builderMode.set(previous[5]);
|
||||
$settings.set(previous[6]);
|
||||
if (previousBridge) {
|
||||
initBridge(previousBridge);
|
||||
} else {
|
||||
clearBridge();
|
||||
}
|
||||
};
|
||||
}, [state]);
|
||||
return ready ? (
|
||||
<div
|
||||
style={{
|
||||
width: 320,
|
||||
height: 800,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
}}
|
||||
>
|
||||
<AssetsPanel publish={() => {}} onClose={() => {}} />
|
||||
</div>
|
||||
) : null;
|
||||
};
|
||||
export const Ready = () => <CollectionStory state="ready" />;
|
||||
export const Loading = () => <CollectionStory state="loading" />;
|
||||
export const InvalidConfiguration = () => <CollectionStory state="invalid" />;
|
||||
export const MissingTemplate = () => (
|
||||
<CollectionStory state="missingTemplate" />
|
||||
);
|
||||
export const Unavailable = () => <CollectionStory state="unavailable" />;
|
||||
export const EntryWarning = () => <CollectionStory state="entryWarning" />;
|
||||
export const ReadOnly = () => <CollectionStory state="readOnly" />;
|
||||
@@ -1,44 +1,226 @@
|
||||
import {
|
||||
PanelContent,
|
||||
PanelBanner,
|
||||
Button,
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
Flex,
|
||||
IconButton,
|
||||
PanelTitle,
|
||||
Separator,
|
||||
Tooltip,
|
||||
Text,
|
||||
toast,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { BrushCleaningIcon, PlusIcon } from "@webstudio-is/icons";
|
||||
import { useRef, useState } from "react";
|
||||
import {
|
||||
AlertCircleIcon,
|
||||
BrushCleaningIcon,
|
||||
PlusIcon,
|
||||
SettingsIcon,
|
||||
} from "@webstudio-is/icons";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useStore } from "@nanostores/react";
|
||||
import { getAssetUrl, isTextFileAsset } from "@webstudio-is/sdk";
|
||||
import {
|
||||
formatAssetName,
|
||||
getAssetDisplayNameParts,
|
||||
getAssetUrl,
|
||||
isTextFileAsset,
|
||||
} from "@webstudio-is/sdk";
|
||||
import { AssetManager } from "~/builder/shared/asset-manager";
|
||||
import { AssetUpload, type AssetUploadHandle } from "~/builder/shared/assets";
|
||||
import { uploadSingleAsset } from "~/builder/shared/assets/upload-assets";
|
||||
import {
|
||||
canConfigureContentCollections,
|
||||
getCollectionReservedAssetIds,
|
||||
useContentCollections,
|
||||
type ContentCollection,
|
||||
} from "~/builder/shared/assets";
|
||||
import { openDeleteUnusedAssetsDialog } from "~/builder/shared/asset-manager/delete-unused-assets";
|
||||
import { CreateAssetFolderDialog } from "~/builder/shared/asset-manager/asset-folder-dialogs";
|
||||
import { $authPermit } from "~/shared/nano-states";
|
||||
import { $assets } from "~/shared/sync/data-stores";
|
||||
import {
|
||||
CreateAssetFolderDialog,
|
||||
type createContentCollectionFolder,
|
||||
} from "~/builder/shared/asset-manager/asset-folder-dialogs";
|
||||
import { $authPermit, $isContentMode } from "~/shared/nano-states";
|
||||
import { $assets, $pages, $project } from "~/shared/sync/data-stores";
|
||||
import {
|
||||
$settings,
|
||||
getSetting,
|
||||
setSetting,
|
||||
} from "~/builder/shared/client-settings";
|
||||
import type { Publish } from "~/shared/pubsub";
|
||||
import { useImageAssetCanvasDrag } from "./use-image-asset-canvas-drag";
|
||||
import { TextFileEditor } from "~/builder/features/text-file-editor/text-file-editor";
|
||||
import { CreateTextFileDialog } from "~/builder/features/text-file-editor/create-text-file-dialog";
|
||||
import { CreateCollectionEntryDialog } from "~/builder/shared/asset-manager/create-collection-entry-dialog";
|
||||
import {
|
||||
CollectionSettingsDialog,
|
||||
ConvertCollectionDialog,
|
||||
} from "~/builder/shared/asset-manager/collection-settings-dialog";
|
||||
import {
|
||||
CollectionRetryButton,
|
||||
CollectionUnavailableNotice,
|
||||
} from "./collection-unavailable-notice";
|
||||
import { useCollectionEntryValidation } from "~/builder/shared/assets/use-collection-entry-validation";
|
||||
import { CollectionEntrySettingsDialog } from "~/builder/shared/asset-manager/collection-entry-settings-dialog";
|
||||
import type { Asset } from "@webstudio-is/sdk";
|
||||
import { selectPage } from "~/shared/nano-states/pages";
|
||||
import { updateCurrentSystem } from "~/shared/system";
|
||||
import { getCollectionEntryCanvasTarget } from "~/builder/shared/asset-manager/collection-entry-navigation";
|
||||
|
||||
export const AssetsPanel = ({
|
||||
publish,
|
||||
createCollection,
|
||||
}: {
|
||||
publish: Publish;
|
||||
onClose: () => void;
|
||||
createCollection?: typeof createContentCollectionFolder;
|
||||
}) => {
|
||||
const [folderId, setFolderId] = useState<string>();
|
||||
const projectId = useStore($project)?.id;
|
||||
const pages = useStore($pages);
|
||||
const settings = useStore($settings);
|
||||
const folderId =
|
||||
projectId === undefined
|
||||
? undefined
|
||||
: settings.lastAssetFolderIds[projectId];
|
||||
const setFolderId = (folderId: string | undefined) => {
|
||||
if (projectId === undefined) {
|
||||
return;
|
||||
}
|
||||
const current = getSetting("lastAssetFolderIds");
|
||||
if (current[projectId] === folderId) {
|
||||
return;
|
||||
}
|
||||
const next = { ...current };
|
||||
if (folderId === undefined) {
|
||||
delete next[projectId];
|
||||
} else {
|
||||
next[projectId] = folderId;
|
||||
}
|
||||
setSetting("lastAssetFolderIds", next);
|
||||
};
|
||||
const [createFolderOpen, setCreateFolderOpen] = useState(false);
|
||||
const [createTextFileOpen, setCreateTextFileOpen] = useState(false);
|
||||
const [collectionRefreshKey, setCollectionRefreshKey] = useState(0);
|
||||
const [collectionToConfigure, setCollectionToConfigure] = useState<string>();
|
||||
const configureCollection = (folderId: string) => {
|
||||
setFolderId(folderId);
|
||||
setCollectionToConfigure(folderId);
|
||||
setCollectionRefreshKey((key) => key + 1);
|
||||
};
|
||||
const [collectionToConvert, setCollectionToConvert] =
|
||||
useState<ContentCollection>();
|
||||
const [repairingCollection, setRepairingCollection] = useState(false);
|
||||
const [entryCollection, setEntryCollection] =
|
||||
useState<Extract<ContentCollection, { status: "ready" }>>();
|
||||
const [settingsCollection, setSettingsCollection] =
|
||||
useState<Extract<ContentCollection, { status: "ready" }>>();
|
||||
const [openedTextAssetId, setOpenedTextAssetId] = useState<string>();
|
||||
const [entrySettings, setEntrySettings] = useState<{
|
||||
asset: Asset;
|
||||
collection: Extract<ContentCollection, { status: "ready" }>;
|
||||
}>();
|
||||
const uploadRef = useRef<AssetUploadHandle>(null);
|
||||
const authPermit = useStore($authPermit);
|
||||
const isContentMode = useStore($isContentMode);
|
||||
const canManageFolders = authPermit !== "view";
|
||||
const canConfigureCollections = canConfigureContentCollections(authPermit);
|
||||
const collections = useContentCollections(folderId, collectionRefreshKey);
|
||||
const collectionReservedAssetIds = getCollectionReservedAssetIds(
|
||||
collections,
|
||||
{ includeInvalid: true }
|
||||
);
|
||||
const currentCollection =
|
||||
folderId === undefined ? undefined : collections.get(folderId);
|
||||
const entryValidation = useCollectionEntryValidation(currentCollection);
|
||||
useEffect(() => {
|
||||
if (collectionToConfigure === undefined) {
|
||||
return;
|
||||
}
|
||||
const collection = collections.get(collectionToConfigure);
|
||||
if (collection?.status === "invalid") {
|
||||
setCollectionToConfigure(undefined);
|
||||
return;
|
||||
}
|
||||
if (collection?.status !== "ready") {
|
||||
return;
|
||||
}
|
||||
setCollectionToConfigure(undefined);
|
||||
setSettingsCollection(collection);
|
||||
}, [collectionToConfigure, collections]);
|
||||
const builderRepair =
|
||||
currentCollection?.status === "invalid" &&
|
||||
isContentMode === false &&
|
||||
canConfigureCollections
|
||||
? currentCollection
|
||||
: undefined;
|
||||
const repairAction = builderRepair?.repairAction;
|
||||
const repairAssetToOpen =
|
||||
repairAction === "edit" && builderRepair !== undefined
|
||||
? builderRepair.repairAsset
|
||||
: repairAction === undefined &&
|
||||
builderRepair !== undefined &&
|
||||
builderRepair.missingTemplateFilename === undefined &&
|
||||
builderRepair.forbiddenAsset === undefined &&
|
||||
isTextFileAsset(builderRepair.repairAsset)
|
||||
? builderRepair.repairAsset
|
||||
: undefined;
|
||||
const invalidCollectionMessage =
|
||||
currentCollection?.status !== "invalid"
|
||||
? undefined
|
||||
: builderRepair?.repairAction !== undefined
|
||||
? currentCollection.message
|
||||
: isContentMode
|
||||
? "New entries are unavailable until a builder repairs this collection."
|
||||
: canConfigureCollections
|
||||
? currentCollection.message
|
||||
: `${currentCollection.message} A builder must repair this collection.`;
|
||||
const addActions = {
|
||||
upload: () => uploadRef.current?.open(),
|
||||
createFile: () => setCreateTextFileOpen(true),
|
||||
createFolder: () => setCreateFolderOpen(true),
|
||||
createEntry: () => {
|
||||
if (currentCollection?.status === "ready") {
|
||||
setEntryCollection(currentCollection);
|
||||
}
|
||||
},
|
||||
};
|
||||
const createMissingTemplate = async () => {
|
||||
if (
|
||||
currentCollection?.status !== "invalid" ||
|
||||
currentCollection.missingTemplateFilename === undefined ||
|
||||
repairingCollection
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setRepairingCollection(true);
|
||||
try {
|
||||
const template = await uploadSingleAsset(
|
||||
"file",
|
||||
new File(
|
||||
["---\n---\n\nStart writing.\n"],
|
||||
currentCollection.missingTemplateFilename,
|
||||
{ type: "text/mdx" }
|
||||
),
|
||||
{ folderId: currentCollection.folderId, deduplicate: true }
|
||||
);
|
||||
if (template === undefined) {
|
||||
throw new Error(
|
||||
"The missing collection template could not be created."
|
||||
);
|
||||
}
|
||||
setCollectionRefreshKey((key) => key + 1);
|
||||
toast.success("Collection template created.");
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "The missing collection template could not be created."
|
||||
);
|
||||
} finally {
|
||||
setRepairingCollection(false);
|
||||
}
|
||||
};
|
||||
const openAsset = (assetId: string) => {
|
||||
const asset = $assets.get().get(assetId);
|
||||
@@ -55,6 +237,31 @@ export const AssetsPanel = ({
|
||||
"noopener,noreferrer"
|
||||
);
|
||||
};
|
||||
const openEntrySettings = (assetId: string) => {
|
||||
const asset = $assets.get().get(assetId);
|
||||
const collection = collections.get(asset?.folderId ?? "");
|
||||
if (asset !== undefined && collection?.status === "ready") {
|
||||
setEntrySettings({ asset, collection });
|
||||
}
|
||||
};
|
||||
const getEntryOpenOnCanvas = (asset: Asset) => {
|
||||
const collection = collections.get(asset.folderId ?? "");
|
||||
if (collection?.status !== "ready") {
|
||||
return;
|
||||
}
|
||||
const target = getCollectionEntryCanvasTarget({
|
||||
entryPageId: collection.config.entryPageId,
|
||||
entryBasename: getAssetDisplayNameParts(asset).basename,
|
||||
pages,
|
||||
});
|
||||
if (target !== undefined) {
|
||||
return () => {
|
||||
setEntrySettings(undefined);
|
||||
selectPage(target.pageId);
|
||||
updateCurrentSystem({ params: target.params });
|
||||
};
|
||||
}
|
||||
};
|
||||
useImageAssetCanvasDrag(publish);
|
||||
return (
|
||||
<>
|
||||
@@ -67,6 +274,42 @@ export const AssetsPanel = ({
|
||||
<PanelTitle
|
||||
suffix={
|
||||
<>
|
||||
{currentCollection?.status === "ready" &&
|
||||
isContentMode === false &&
|
||||
canConfigureCollections && (
|
||||
<Tooltip content="Collection settings">
|
||||
<IconButton
|
||||
aria-label="Collection settings"
|
||||
onClick={() => {
|
||||
setSettingsCollection(currentCollection);
|
||||
}}
|
||||
>
|
||||
<SettingsIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
{currentCollection?.status === "invalid" &&
|
||||
(builderRepair?.missingTemplateFilename !== undefined ||
|
||||
repairAssetToOpen !== undefined) && (
|
||||
<Tooltip content={currentCollection.message}>
|
||||
<IconButton
|
||||
aria-label="Repair invalid collection"
|
||||
onClick={() => {
|
||||
if (
|
||||
builderRepair?.missingTemplateFilename !== undefined
|
||||
) {
|
||||
void createMissingTemplate();
|
||||
return;
|
||||
}
|
||||
if (repairAssetToOpen !== undefined) {
|
||||
setOpenedTextAssetId(repairAssetToOpen.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<AlertCircleIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip content="Delete unused assets">
|
||||
<IconButton
|
||||
aria-label="Delete unused assets"
|
||||
@@ -87,41 +330,180 @@ export const AssetsPanel = ({
|
||||
</DropdownMenuTrigger>
|
||||
</Tooltip>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onSelect={addActions.upload}>
|
||||
Upload
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={addActions.createFile}>
|
||||
Create text file
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={addActions.createFolder}>
|
||||
Create folder
|
||||
</DropdownMenuItem>
|
||||
{(currentCollection === undefined ||
|
||||
currentCollection.status === "ready") && (
|
||||
<>
|
||||
<DropdownMenuItem onSelect={addActions.upload}>
|
||||
Upload
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={addActions.createFile}>
|
||||
Create text file
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
{currentCollection?.status === "ready" && (
|
||||
<DropdownMenuItem onSelect={addActions.createEntry}>
|
||||
New entry
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canManageFolders && (
|
||||
<DropdownMenuItem onSelect={addActions.createFolder}>
|
||||
Create folder
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</>
|
||||
}
|
||||
>
|
||||
Assets
|
||||
{currentCollection === undefined ? "Assets" : "Assets collection"}
|
||||
</PanelTitle>
|
||||
<Separator />
|
||||
<AssetManager
|
||||
entryIssues={entryValidation.issues}
|
||||
folderNotice={
|
||||
<>
|
||||
{currentCollection?.status === "ready" &&
|
||||
entryValidation.issues !== undefined &&
|
||||
entryValidation.issues.size > 0 && (
|
||||
<PanelBanner variant="warning" role="status">
|
||||
<Flex direction="column" gap={2}>
|
||||
<Text>
|
||||
{entryValidation.issues.size}{" "}
|
||||
{entryValidation.issues.size === 1
|
||||
? "entry has"
|
||||
: "entries have"}{" "}
|
||||
fields that do not match this collection. Review Entry
|
||||
settings to see and fix each field.
|
||||
</Text>
|
||||
<Flex gap={2} wrap="wrap">
|
||||
<Button
|
||||
onClick={() => {
|
||||
const firstAssetId = entryValidation.issues
|
||||
?.keys()
|
||||
.next().value;
|
||||
if (firstAssetId !== undefined) {
|
||||
openEntrySettings(firstAssetId);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Review first entry
|
||||
</Button>
|
||||
<Button onClick={entryValidation.retry}>
|
||||
Check again
|
||||
</Button>
|
||||
</Flex>
|
||||
</Flex>
|
||||
</PanelBanner>
|
||||
)}
|
||||
{currentCollection?.status === "loading" && (
|
||||
<PanelContent as={Flex} role="status" align="center">
|
||||
<Text variant="tiny">Loading collection settings…</Text>
|
||||
</PanelContent>
|
||||
)}
|
||||
{currentCollection?.status === "invalid" && (
|
||||
<PanelContent as={Flex} role="alert" direction="column" gap={2}>
|
||||
<Text color="destructive" variant="tiny">
|
||||
{invalidCollectionMessage}
|
||||
</Text>
|
||||
{builderRepair !== undefined && (
|
||||
<Flex gap={2} wrap="wrap">
|
||||
{builderRepair?.missingTemplateFilename !== undefined && (
|
||||
<Button
|
||||
disabled={repairingCollection}
|
||||
onClick={() => void createMissingTemplate()}
|
||||
>
|
||||
{repairingCollection
|
||||
? "Creating…"
|
||||
: "Create missing template"}
|
||||
</Button>
|
||||
)}
|
||||
{repairAssetToOpen !== undefined && (
|
||||
<Button
|
||||
onClick={() =>
|
||||
setOpenedTextAssetId(repairAssetToOpen.id)
|
||||
}
|
||||
>
|
||||
Open {formatAssetName(repairAssetToOpen)}
|
||||
</Button>
|
||||
)}
|
||||
<CollectionRetryButton
|
||||
collection={currentCollection}
|
||||
onCheckAgain={() =>
|
||||
setCollectionRefreshKey((key) => key + 1)
|
||||
}
|
||||
/>
|
||||
</Flex>
|
||||
)}
|
||||
</PanelContent>
|
||||
)}
|
||||
{currentCollection?.status === "unavailable" && (
|
||||
<CollectionUnavailableNotice
|
||||
collection={currentCollection}
|
||||
onCheckAgain={() => setCollectionRefreshKey((key) => key + 1)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
folderId={folderId}
|
||||
onFolderChange={setFolderId}
|
||||
onConfigureCollection={configureCollection}
|
||||
createCollection={createCollection}
|
||||
onOpen={openAsset}
|
||||
canManageFolders={authPermit !== "view"}
|
||||
onEntrySettings={openEntrySettings}
|
||||
getEntryOpenOnCanvas={getEntryOpenOnCanvas}
|
||||
canManageFolders={canManageFolders}
|
||||
panelActions={{
|
||||
...(authPermit === "view" ? {} : addActions),
|
||||
...(authPermit === "view"
|
||||
? {}
|
||||
: {
|
||||
...(currentCollection === undefined ||
|
||||
currentCollection.status === "ready"
|
||||
? {
|
||||
upload: addActions.upload,
|
||||
createFile: addActions.createFile,
|
||||
}
|
||||
: {}),
|
||||
...(currentCollection?.status === "ready"
|
||||
? { createEntry: addActions.createEntry }
|
||||
: {}),
|
||||
...(canManageFolders
|
||||
? { createFolder: addActions.createFolder }
|
||||
: {}),
|
||||
}),
|
||||
deleteUnusedAssets: openDeleteUnusedAssetsDialog,
|
||||
...(currentCollection !== undefined &&
|
||||
canConfigureCollections &&
|
||||
!isContentMode
|
||||
? {
|
||||
convertCollection: () =>
|
||||
setCollectionToConvert(currentCollection),
|
||||
}
|
||||
: {}),
|
||||
}}
|
||||
collections={collections}
|
||||
emptyMessage={
|
||||
currentCollection === undefined
|
||||
? undefined
|
||||
: currentCollection.status === "ready"
|
||||
? "No entries yet. Use New entry to create one."
|
||||
: "No collection entries are available."
|
||||
}
|
||||
/>
|
||||
<CreateAssetFolderDialog
|
||||
open={createFolderOpen}
|
||||
onOpenChange={setCreateFolderOpen}
|
||||
onConfigureCollection={configureCollection}
|
||||
createCollection={createCollection}
|
||||
currentFolderId={folderId}
|
||||
canCreateContentCollection={
|
||||
isContentMode === false && canConfigureCollections
|
||||
}
|
||||
/>
|
||||
<CreateTextFileDialog
|
||||
open={createTextFileOpen}
|
||||
folderId={folderId}
|
||||
canCreateCollectionConfig={canConfigureCollections}
|
||||
onOpenChange={setCreateTextFileOpen}
|
||||
onCreated={setOpenedTextAssetId}
|
||||
/>
|
||||
@@ -129,6 +511,10 @@ export const AssetsPanel = ({
|
||||
<TextFileEditor
|
||||
key={openedTextAssetId}
|
||||
assetId={openedTextAssetId}
|
||||
readOnly={
|
||||
canConfigureCollections === false &&
|
||||
collectionReservedAssetIds.has(openedTextAssetId)
|
||||
}
|
||||
onOpenChange={(open) => {
|
||||
if (open === false) {
|
||||
setOpenedTextAssetId(undefined);
|
||||
@@ -136,6 +522,47 @@ export const AssetsPanel = ({
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{entryCollection !== undefined && (
|
||||
<CreateCollectionEntryDialog
|
||||
collection={entryCollection}
|
||||
open
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (nextOpen === false) {
|
||||
setEntryCollection(undefined);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{entrySettings !== undefined && (
|
||||
<CollectionEntrySettingsDialog
|
||||
key={entrySettings.asset.id}
|
||||
{...entrySettings}
|
||||
onClose={() => setEntrySettings(undefined)}
|
||||
onOpenFile={() => openAsset(entrySettings.asset.id)}
|
||||
onOpenCanvas={getEntryOpenOnCanvas(entrySettings.asset)}
|
||||
/>
|
||||
)}
|
||||
{settingsCollection !== undefined &&
|
||||
isContentMode === false &&
|
||||
canConfigureCollections && (
|
||||
<CollectionSettingsDialog
|
||||
collection={settingsCollection}
|
||||
open
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (nextOpen === false) {
|
||||
setSettingsCollection(undefined);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{collectionToConvert !== undefined &&
|
||||
canConfigureCollections &&
|
||||
!isContentMode && (
|
||||
<ConvertCollectionDialog
|
||||
configAsset={collectionToConvert.configAsset}
|
||||
onClose={() => setCollectionToConvert(undefined)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,126 @@
|
||||
import { useState } from "react";
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
import type { Asset } from "@webstudio-is/sdk";
|
||||
import type { ContentCollection } from "~/builder/shared/assets";
|
||||
import { createAssetManagerTestRenderer } from "~/builder/shared/asset-manager/test-utils";
|
||||
import {
|
||||
CollectionRetryButton,
|
||||
CollectionUnavailableNotice,
|
||||
} from "./collection-unavailable-notice";
|
||||
|
||||
const renderer = createAssetManagerTestRenderer();
|
||||
|
||||
const configAsset: Asset = {
|
||||
id: "config",
|
||||
projectId: "project",
|
||||
name: "collection.json",
|
||||
filename: "collection",
|
||||
folderId: "posts",
|
||||
type: "file",
|
||||
format: "json",
|
||||
size: 1,
|
||||
createdAt: "2026-09-06T00:00:00.000Z",
|
||||
meta: {},
|
||||
};
|
||||
|
||||
const createUnavailableCollection = (): Extract<
|
||||
ContentCollection,
|
||||
{ status: "unavailable" }
|
||||
> => ({
|
||||
status: "unavailable",
|
||||
folderId: "posts",
|
||||
configAsset,
|
||||
reservedAssets: [configAsset],
|
||||
siblingAssets: [configAsset],
|
||||
message: "Collection files could not be loaded: Request timed out",
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
renderer.cleanup();
|
||||
});
|
||||
|
||||
test("shows retry progress until collection discovery finishes", () => {
|
||||
const onCheckAgain = vi.fn();
|
||||
let finishCheck: () => void = () => undefined;
|
||||
const Notice = () => {
|
||||
const [collection, setCollection] = useState(createUnavailableCollection);
|
||||
finishCheck = () => setCollection(createUnavailableCollection());
|
||||
return (
|
||||
<CollectionUnavailableNotice
|
||||
collection={collection}
|
||||
onCheckAgain={onCheckAgain}
|
||||
/>
|
||||
);
|
||||
};
|
||||
renderer.render(<Notice />);
|
||||
|
||||
const alert = document.querySelector<HTMLElement>("[role=alert]");
|
||||
expect(alert).not.toBeNull();
|
||||
// Transport diagnostics are not user-facing copy.
|
||||
expect(alert?.textContent).not.toContain("Request timed out");
|
||||
const retry = Array.from(
|
||||
document.querySelectorAll<HTMLButtonElement>("button")
|
||||
).find((button) => button.textContent === "Retry");
|
||||
if (retry === undefined) {
|
||||
throw new Error("Expected collection retry button");
|
||||
}
|
||||
|
||||
act(() => retry.click());
|
||||
|
||||
expect(onCheckAgain).toHaveBeenCalledOnce();
|
||||
expect(retry).toBeDisabled();
|
||||
expect(retry.textContent).toBe("Retrying…");
|
||||
|
||||
act(finishCheck);
|
||||
|
||||
expect(retry).toBeEnabled();
|
||||
expect(retry.textContent).toBe("Retry");
|
||||
});
|
||||
|
||||
test("shows the same retry progress for an invalid collection", () => {
|
||||
const onCheckAgain = vi.fn();
|
||||
let finishCheck: () => void = () => void 0;
|
||||
const InvalidRetry = () => {
|
||||
const [collection, setCollection] = useState<
|
||||
Extract<ContentCollection, { status: "invalid" }>
|
||||
>({
|
||||
status: "invalid",
|
||||
folderId: "posts",
|
||||
configAsset,
|
||||
reservedAssets: [configAsset],
|
||||
siblingAssets: [configAsset],
|
||||
repairAsset: configAsset,
|
||||
message: "Collection configuration is invalid",
|
||||
});
|
||||
finishCheck = () =>
|
||||
setCollection((current) => ({
|
||||
...current,
|
||||
reservedAssets: [...current.reservedAssets],
|
||||
}));
|
||||
return (
|
||||
<CollectionRetryButton
|
||||
collection={collection}
|
||||
onCheckAgain={onCheckAgain}
|
||||
/>
|
||||
);
|
||||
};
|
||||
renderer.render(<InvalidRetry />);
|
||||
const retry = Array.from(
|
||||
document.querySelectorAll<HTMLButtonElement>("button")
|
||||
).find((button) => button.textContent === "Retry");
|
||||
if (retry === undefined) {
|
||||
throw new Error("Expected collection retry button");
|
||||
}
|
||||
|
||||
act(() => retry.click());
|
||||
|
||||
expect(onCheckAgain).toHaveBeenCalledOnce();
|
||||
expect(retry).toBeDisabled();
|
||||
expect(retry.textContent).toBe("Retrying…");
|
||||
|
||||
act(finishCheck);
|
||||
|
||||
expect(retry).toBeEnabled();
|
||||
expect(retry.textContent).toBe("Retry");
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useState } from "react";
|
||||
import { PanelBanner, Button, Flex, Text } from "@webstudio-is/design-system";
|
||||
import type { ContentCollection } from "~/builder/shared/assets";
|
||||
|
||||
type UnavailableCollection = Extract<
|
||||
ContentCollection,
|
||||
{ status: "unavailable" }
|
||||
>;
|
||||
type RetryableCollection = Extract<
|
||||
ContentCollection,
|
||||
{ status: "invalid" | "unavailable" }
|
||||
>;
|
||||
|
||||
export const CollectionRetryButton = ({
|
||||
collection,
|
||||
onCheckAgain,
|
||||
}: {
|
||||
collection: RetryableCollection;
|
||||
onCheckAgain: () => void;
|
||||
}) => {
|
||||
const [checkingCollection, setCheckingCollection] = useState<
|
||||
RetryableCollection | undefined
|
||||
>();
|
||||
const checking = checkingCollection === collection;
|
||||
|
||||
return (
|
||||
<Button
|
||||
disabled={checking}
|
||||
onClick={() => {
|
||||
setCheckingCollection(collection);
|
||||
onCheckAgain();
|
||||
}}
|
||||
>
|
||||
{checking ? "Retrying…" : "Retry"}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
export const CollectionUnavailableNotice = ({
|
||||
collection,
|
||||
onCheckAgain,
|
||||
}: {
|
||||
collection: UnavailableCollection;
|
||||
onCheckAgain: () => void;
|
||||
}) => {
|
||||
return (
|
||||
<PanelBanner role="alert" variant="error" css={{ flexShrink: 0 }}>
|
||||
<Flex align="center" justify="between" gap={2}>
|
||||
<Text>
|
||||
Couldn’t load collection settings. Retry to use collection actions.
|
||||
</Text>
|
||||
<Flex>
|
||||
<CollectionRetryButton
|
||||
collection={collection}
|
||||
onCheckAgain={onCheckAgain}
|
||||
/>
|
||||
</Flex>
|
||||
</Flex>
|
||||
</PanelBanner>
|
||||
);
|
||||
};
|
||||
@@ -1,5 +1,6 @@
|
||||
import { StorySection } from "@webstudio-is/design-system";
|
||||
import { Alert } from "./alert";
|
||||
import { UnsupportedBrowserDialog } from "./blocking-alerts";
|
||||
|
||||
export default { title: "Blocking Alerts", component: Alert };
|
||||
|
||||
@@ -12,3 +13,9 @@ export const BlockingAlerts = () => (
|
||||
/>
|
||||
</StorySection>
|
||||
);
|
||||
|
||||
export const UnsupportedBrowser = () => (
|
||||
<StorySection title="Unsupported browser">
|
||||
<UnsupportedBrowserDialog onDismiss={() => {}} />
|
||||
</StorySection>
|
||||
);
|
||||
@@ -1,9 +1,7 @@
|
||||
import { atom } from "nanostores";
|
||||
import { useStore } from "@nanostores/react";
|
||||
import type { ReactNode } from "react";
|
||||
import {
|
||||
Button,
|
||||
css,
|
||||
cssVar,
|
||||
Flex,
|
||||
Popover,
|
||||
PopoverContent,
|
||||
@@ -18,27 +16,20 @@ const containerStyle = css({
|
||||
left: 0,
|
||||
width: "100vw",
|
||||
height: "100vh",
|
||||
background: "rgba(0, 0, 0, 0.9)",
|
||||
background: `oklch(from ${cssVar("--overlay-scrim")} l c h / 90%)`,
|
||||
});
|
||||
|
||||
const contentStyle = css({
|
||||
width: theme.spacing[33],
|
||||
color: theme.colors.foregroundDestructive,
|
||||
color: cssVar("--foreground-negative"),
|
||||
});
|
||||
|
||||
const $isAlertDismissed = atom(false);
|
||||
const scrimForeground = `light-dark(
|
||||
${cssVar("--foreground-on-inverse")},
|
||||
${cssVar("--foreground-primary")}
|
||||
)`;
|
||||
|
||||
export const Alert = ({
|
||||
message,
|
||||
isDismissable,
|
||||
}: {
|
||||
message: string | ReactNode;
|
||||
isDismissable?: boolean;
|
||||
}) => {
|
||||
const isAlertDismissed = useStore($isAlertDismissed);
|
||||
if (isAlertDismissed) {
|
||||
return;
|
||||
}
|
||||
export const Alert = ({ message }: { message: string | ReactNode }) => {
|
||||
return (
|
||||
<Popover open>
|
||||
<PopoverContent css={{ zIndex: theme.zIndices.max }}>
|
||||
@@ -50,17 +41,9 @@ export const Alert = ({
|
||||
className={contentStyle()}
|
||||
>
|
||||
<AlertIcon size={22} />
|
||||
<Text color="contrast" align="center">
|
||||
<Text align="center" css={{ color: scrimForeground }}>
|
||||
{message}
|
||||
</Text>
|
||||
{isDismissable && (
|
||||
<Button
|
||||
color="destructive"
|
||||
onClick={() => $isAlertDismissed.set(true)}
|
||||
>
|
||||
Dismiss
|
||||
</Button>
|
||||
)}
|
||||
</Flex>
|
||||
</Flex>
|
||||
</PopoverContent>
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Alert } from "./alert";
|
||||
import { useWindowResizeDebounced } from "~/shared/dom-hooks";
|
||||
import { isFeatureEnabled } from "@webstudio-is/feature-flags";
|
||||
import { Link } from "@webstudio-is/design-system";
|
||||
import {
|
||||
PanelContent,
|
||||
Button,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogTitle,
|
||||
Link,
|
||||
Text,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { $isPreviewMode } from "~/shared/nano-states";
|
||||
import { useStore } from "@nanostores/react";
|
||||
import { $loadingState } from "~/builder/shared/nano-states";
|
||||
@@ -24,83 +34,113 @@ const useTooSmallMessage = () => {
|
||||
return message;
|
||||
};
|
||||
|
||||
const useUnsupportedBrowser = () => {
|
||||
const [message, setMessage] = useState<ReactNode>();
|
||||
export const isChromiumBrowser = (userAgent: string) =>
|
||||
/(?:Chrome|Chromium)\//.test(userAgent);
|
||||
|
||||
const useIsUnsupportedBrowser = () => {
|
||||
const [isUnsupportedBrowser, setIsUnsupportedBrowser] = useState(false);
|
||||
useEffect(() => {
|
||||
if ("chrome" in window || isFeatureEnabled("unsupportedBrowsers")) {
|
||||
if (
|
||||
isChromiumBrowser(navigator.userAgent) ||
|
||||
isFeatureEnabled("unsupportedBrowsers")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
setMessage(
|
||||
<>
|
||||
The Webstudio Builder UI currently supports any{" "}
|
||||
<Link
|
||||
href="https://en.wikipedia.org/wiki/Chromium_(web_browser)"
|
||||
target="_blank"
|
||||
color="inherit"
|
||||
variant="inherit"
|
||||
>
|
||||
Chromium-based
|
||||
</Link>{" "}
|
||||
browsers such as{" "}
|
||||
<Link
|
||||
href="https://www.google.com/chrome"
|
||||
target="_blank"
|
||||
color="inherit"
|
||||
variant="inherit"
|
||||
>
|
||||
Google Chrome
|
||||
</Link>
|
||||
,{" "}
|
||||
<Link
|
||||
href="https://www.microsoft.com/en-us/edge"
|
||||
target="_blank"
|
||||
color="inherit"
|
||||
variant="inherit"
|
||||
>
|
||||
Microsoft Edge
|
||||
</Link>
|
||||
,{" "}
|
||||
<Link
|
||||
href="https://brave.com/"
|
||||
target="_blank"
|
||||
color="inherit"
|
||||
variant="inherit"
|
||||
>
|
||||
Brave
|
||||
</Link>
|
||||
,{" "}
|
||||
<Link
|
||||
href="https://arc.net/"
|
||||
target="_blank"
|
||||
color="inherit"
|
||||
variant="inherit"
|
||||
>
|
||||
Arc
|
||||
</Link>{" "}
|
||||
and many more. We plan to support Firefox and Safari in the near future.
|
||||
<br />
|
||||
<br />
|
||||
The website you're building should function correctly across all
|
||||
browsers!
|
||||
</>
|
||||
);
|
||||
setIsUnsupportedBrowser(true);
|
||||
}, []);
|
||||
return message;
|
||||
return isUnsupportedBrowser;
|
||||
};
|
||||
|
||||
export const UnsupportedBrowserDialog = ({
|
||||
onDismiss,
|
||||
}: {
|
||||
onDismiss: () => void;
|
||||
}) => (
|
||||
<Dialog
|
||||
open
|
||||
modal
|
||||
onOpenChange={(open) => {
|
||||
if (open === false) {
|
||||
onDismiss();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent width={480}>
|
||||
<DialogTitle>Unsupported browser</DialogTitle>
|
||||
<DialogDescription asChild>
|
||||
<PanelContent as={Text}>
|
||||
The Webstudio Builder UI currently supports any{" "}
|
||||
<Link
|
||||
href="https://en.wikipedia.org/wiki/Chromium_(web_browser)"
|
||||
target="_blank"
|
||||
color="inherit"
|
||||
variant="inherit"
|
||||
>
|
||||
Chromium-based
|
||||
</Link>{" "}
|
||||
browsers such as{" "}
|
||||
<Link
|
||||
href="https://www.google.com/chrome"
|
||||
target="_blank"
|
||||
color="inherit"
|
||||
variant="inherit"
|
||||
>
|
||||
Google Chrome
|
||||
</Link>
|
||||
,{" "}
|
||||
<Link
|
||||
href="https://www.microsoft.com/en-us/edge"
|
||||
target="_blank"
|
||||
color="inherit"
|
||||
variant="inherit"
|
||||
>
|
||||
Microsoft Edge
|
||||
</Link>
|
||||
,{" "}
|
||||
<Link
|
||||
href="https://brave.com/"
|
||||
target="_blank"
|
||||
color="inherit"
|
||||
variant="inherit"
|
||||
>
|
||||
Brave
|
||||
</Link>
|
||||
,{" "}
|
||||
<Link
|
||||
href="https://arc.net/"
|
||||
target="_blank"
|
||||
color="inherit"
|
||||
variant="inherit"
|
||||
>
|
||||
Arc
|
||||
</Link>{" "}
|
||||
and many more. We plan to support Firefox and Safari in the near
|
||||
future.
|
||||
<br />
|
||||
<br />
|
||||
The website you're building should function correctly across all
|
||||
browsers!
|
||||
</PanelContent>
|
||||
</DialogDescription>
|
||||
<DialogActions>
|
||||
<Button autoFocus onClick={onDismiss}>
|
||||
Continue
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
export const BlockingAlerts = () => {
|
||||
const isPreviewMode = useStore($isPreviewMode);
|
||||
const loadingState = useStore($loadingState);
|
||||
|
||||
const unsupportedBrowsersMessage = useUnsupportedBrowser();
|
||||
// Takes the latest message, order matters
|
||||
const message = [useTooSmallMessage(), unsupportedBrowsersMessage]
|
||||
.filter(Boolean)
|
||||
.pop();
|
||||
const [isUnsupportedBrowserDialogDismissed, setIsDialogDismissed] =
|
||||
useState(false);
|
||||
const isUnsupportedBrowser = useIsUnsupportedBrowser();
|
||||
const tooSmallMessage = useTooSmallMessage();
|
||||
|
||||
if (
|
||||
message === undefined ||
|
||||
// We want user to be able to test in unsupported browsers in preview mode.
|
||||
isPreviewMode ||
|
||||
loadingState.state !== "ready"
|
||||
@@ -108,10 +148,13 @@ export const BlockingAlerts = () => {
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<Alert
|
||||
message={message}
|
||||
isDismissable={unsupportedBrowsersMessage !== undefined}
|
||||
/>
|
||||
);
|
||||
if (tooSmallMessage !== undefined) {
|
||||
return <Alert message={tooSmallMessage} />;
|
||||
}
|
||||
|
||||
if (isUnsupportedBrowser && isUnsupportedBrowserDialogDismissed === false) {
|
||||
return (
|
||||
<UnsupportedBrowserDialog onDismiss={() => setIsDialogDismissed(true)} />
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,75 @@
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, expect, test, vi } from "vitest";
|
||||
import { isChromiumBrowser, UnsupportedBrowserDialog } from "./blocking-alerts";
|
||||
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal(
|
||||
"ResizeObserver",
|
||||
class {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
);
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
document.body.innerHTML = "";
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
test("shows an accessible modal dialog and lets the user continue", () => {
|
||||
const onDismiss = vi.fn();
|
||||
|
||||
act(() => {
|
||||
root.render(<UnsupportedBrowserDialog onDismiss={onDismiss} />);
|
||||
});
|
||||
|
||||
const dialog = document.body.querySelector('[role="dialog"]');
|
||||
expect(dialog).not.toBeNull();
|
||||
expect(dialog?.getAttribute("aria-labelledby")).toBeTruthy();
|
||||
expect(document.body.style.pointerEvents).toBe("none");
|
||||
expect(dialog?.textContent).toContain("Unsupported browser");
|
||||
expect(dialog?.textContent).toContain("Chromium-based");
|
||||
|
||||
act(() => {
|
||||
Array.from(dialog?.querySelectorAll("button") ?? [])
|
||||
.find((button) => button.textContent === "Continue")
|
||||
?.click();
|
||||
});
|
||||
|
||||
expect(onDismiss).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test("recognizes Chromium from its user agent without window.chrome", () => {
|
||||
expect(
|
||||
isChromiumBrowser(
|
||||
"Mozilla/5.0 Chrome/131.0.0.0 Safari/537.36 HeadlessChrome/131.0.0.0"
|
||||
)
|
||||
).toBe(true);
|
||||
expect(
|
||||
isChromiumBrowser(
|
||||
"Mozilla/5.0 Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0"
|
||||
)
|
||||
).toBe(true);
|
||||
expect(
|
||||
isChromiumBrowser("Mozilla/5.0 Firefox/132.0 Gecko/20100101 Firefox/132.0")
|
||||
).toBe(false);
|
||||
expect(
|
||||
isChromiumBrowser(
|
||||
"Mozilla/5.0 AppleWebKit/605.1.15 Version/18.0 Safari/605.1.15"
|
||||
)
|
||||
).toBe(false);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from "react";
|
||||
import { useStore } from "@nanostores/react";
|
||||
import { Flex } from "@webstudio-is/design-system";
|
||||
import { Flex, rawTheme, theme } from "@webstudio-is/design-system";
|
||||
import { $breakpoints } from "~/shared/sync/data-stores";
|
||||
import {
|
||||
$selectedBreakpoint,
|
||||
@@ -57,31 +57,33 @@ export const BreakpointsContainer = () => {
|
||||
};
|
||||
|
||||
return (
|
||||
<Flex>
|
||||
<Flex justify="end" css={hideOnMobile}>
|
||||
<CanvasSettingsPopover />
|
||||
<Flex align="center">
|
||||
<Flex align="center" css={{ gap: theme.spacing[5] }}>
|
||||
<Flex justify="end" css={hideOnMobile}>
|
||||
<CanvasSettingsPopover />
|
||||
</Flex>
|
||||
<Flex align="center" justify="center" css={hideOnMobile}>
|
||||
<BreakpointsSelector />
|
||||
</Flex>
|
||||
{selectedBreakpoint && (
|
||||
<BreakpointsMenu
|
||||
breakpoints={breakpoints}
|
||||
selectedBreakpoint={selectedBreakpoint}
|
||||
open={breakpointsMenuView === "initial"}
|
||||
triggerOpen={breakpointsMenuView !== undefined}
|
||||
onOpenChange={(open) => {
|
||||
if (open) {
|
||||
$breakpointsMenuView.set("initial");
|
||||
return;
|
||||
}
|
||||
if ($breakpointsMenuView.get() === "initial") {
|
||||
$breakpointsMenuView.set(undefined);
|
||||
}
|
||||
}}
|
||||
onEditClick={() => $breakpointsMenuView.set("editor")}
|
||||
/>
|
||||
)}
|
||||
</Flex>
|
||||
<Flex align="center" justify="center" css={hideOnMobile}>
|
||||
<BreakpointsSelector />
|
||||
</Flex>
|
||||
{selectedBreakpoint && (
|
||||
<BreakpointsMenu
|
||||
breakpoints={breakpoints}
|
||||
selectedBreakpoint={selectedBreakpoint}
|
||||
open={breakpointsMenuView === "initial"}
|
||||
triggerOpen={breakpointsMenuView !== undefined}
|
||||
onOpenChange={(open) => {
|
||||
if (open) {
|
||||
$breakpointsMenuView.set("initial");
|
||||
return;
|
||||
}
|
||||
if ($breakpointsMenuView.get() === "initial") {
|
||||
$breakpointsMenuView.set(undefined);
|
||||
}
|
||||
}}
|
||||
onEditClick={() => $breakpointsMenuView.set("editor")}
|
||||
/>
|
||||
)}
|
||||
<BreakpointsEditor
|
||||
open={breakpointsMenuView === "editor"}
|
||||
onOpenChange={(open) => {
|
||||
@@ -92,7 +94,7 @@ export const BreakpointsContainer = () => {
|
||||
$breakpointsMenuView.set("confirmation");
|
||||
}}
|
||||
>
|
||||
<div style={{ height: "100%", width: 0 }} />
|
||||
<div style={{ height: rawTheme.sizes.controlHeight, width: 0 }} />
|
||||
</BreakpointsEditor>
|
||||
{breakpointToDelete && (
|
||||
<ConfirmationDialog
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button, StorySection } from "@webstudio-is/design-system";
|
||||
import type { Breakpoint } from "@webstudio-is/sdk";
|
||||
import { $breakpoints } from "~/shared/sync/data-stores";
|
||||
import { BreakpointsEditor } from "./breakpoints-editor";
|
||||
import { ConfirmationDialog } from "./confirmation-dialog";
|
||||
|
||||
const desktop: Breakpoint = {
|
||||
id: "desktop",
|
||||
label: "Desktop",
|
||||
minWidth: 1280,
|
||||
};
|
||||
|
||||
export default {
|
||||
title: "Builder/Breakpoints editor",
|
||||
component: BreakpointsEditor,
|
||||
};
|
||||
|
||||
const BreakpointsStory = ({ empty = false }: { empty?: boolean }) => {
|
||||
const [open, setOpen] = useState(true);
|
||||
const [toDelete, setToDelete] = useState<Breakpoint>();
|
||||
useEffect(() => {
|
||||
const previous = $breakpoints.get();
|
||||
$breakpoints.set(
|
||||
new Map(
|
||||
empty
|
||||
? []
|
||||
: [
|
||||
["base", { id: "base", label: "" }],
|
||||
[desktop.id, desktop],
|
||||
["mobile", { id: "mobile", label: "Mobile", maxWidth: 767 }],
|
||||
]
|
||||
)
|
||||
);
|
||||
return () => $breakpoints.set(previous);
|
||||
}, [empty]);
|
||||
return (
|
||||
<StorySection title="Breakpoints">
|
||||
<BreakpointsEditor
|
||||
open={open && toDelete === undefined}
|
||||
onOpenChange={setOpen}
|
||||
onDelete={(breakpoint) => setToDelete(breakpoint)}
|
||||
>
|
||||
<Button>Breakpoints</Button>
|
||||
</BreakpointsEditor>
|
||||
{toDelete && (
|
||||
<ConfirmationDialog
|
||||
open
|
||||
breakpoint={toDelete}
|
||||
onAbort={() => setToDelete(undefined)}
|
||||
onConfirm={() => setToDelete(undefined)}
|
||||
/>
|
||||
)}
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const Populated = () => <BreakpointsStory />;
|
||||
export const Empty = () => <BreakpointsStory empty />;
|
||||
export const DeleteConfirmation = () => (
|
||||
<ConfirmationDialog
|
||||
open
|
||||
breakpoint={desktop}
|
||||
onAbort={() => {}}
|
||||
onConfirm={() => {}}
|
||||
/>
|
||||
);
|
||||
@@ -0,0 +1,111 @@
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { userEvent } from "@vitest/browser/context";
|
||||
import { TooltipProvider } from "@webstudio-is/design-system";
|
||||
import { __testing__ } from "./breakpoints-editor";
|
||||
|
||||
const { BreakpointEditorItem } = __testing__;
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
test.each(["enter", "tab", "click"])(
|
||||
"keeps the breakpoint draft until %s commits it",
|
||||
async (commit) => {
|
||||
const onChangeComplete = vi.fn();
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
act(() =>
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<BreakpointEditorItem
|
||||
breakpoint={{ id: "tablet", label: "Tablet", maxWidth: 991 }}
|
||||
onChangeComplete={onChangeComplete}
|
||||
onDelete={() => {}}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
const input = container.querySelector<HTMLInputElement>(
|
||||
'[aria-label="Breakpoint width"]'
|
||||
)!;
|
||||
await act(async () => {
|
||||
await userEvent.fill(input, "8");
|
||||
});
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 650));
|
||||
});
|
||||
expect(onChangeComplete).not.toHaveBeenCalled();
|
||||
expect(document.activeElement).toBe(input);
|
||||
await act(async () => {
|
||||
await userEvent.fill(input, "899");
|
||||
});
|
||||
await act(async () => {
|
||||
if (commit === "click") {
|
||||
await userEvent.click(
|
||||
container.querySelector<HTMLInputElement>(
|
||||
'input[placeholder="Breakpoint name"]'
|
||||
)!
|
||||
);
|
||||
} else {
|
||||
await userEvent.keyboard(commit === "enter" ? "{Enter}" : "{Tab}");
|
||||
}
|
||||
});
|
||||
expect(onChangeComplete).toHaveBeenLastCalledWith({
|
||||
id: "tablet",
|
||||
label: "Tablet",
|
||||
maxWidth: 899,
|
||||
});
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
test.each([
|
||||
["Max width", { minWidth: 768 }, { maxWidth: 768 }],
|
||||
["Min width", { maxWidth: 991 }, { minWidth: 991 }],
|
||||
] as const)(
|
||||
"saves a breakpoint when switching to %s",
|
||||
async (option, original, expected) => {
|
||||
const onChangeComplete = vi.fn();
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
act(() =>
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<BreakpointEditorItem
|
||||
breakpoint={{ id: "tablet", label: "Tablet", ...original }}
|
||||
onChangeComplete={onChangeComplete}
|
||||
onDelete={() => {}}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
await act(async () => {
|
||||
await userEvent.click(container.querySelector('[role="combobox"]')!);
|
||||
});
|
||||
await act(async () => {
|
||||
await userEvent.click(
|
||||
Array.from(
|
||||
document.querySelectorAll<HTMLElement>('[role="option"]')
|
||||
).find((element) => element.textContent === option)!
|
||||
);
|
||||
});
|
||||
expect(onChangeComplete).toHaveBeenLastCalledWith({
|
||||
id: "tablet",
|
||||
label: "Tablet",
|
||||
...expected,
|
||||
});
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Fragment, useState, useMemo } from "react";
|
||||
import { nanoid } from "nanoid";
|
||||
import type { Breakpoint } from "@webstudio-is/sdk";
|
||||
import { createId, type Breakpoint } from "@webstudio-is/sdk";
|
||||
import {
|
||||
PanelContent,
|
||||
theme,
|
||||
Flex,
|
||||
PanelTitle,
|
||||
@@ -46,15 +46,14 @@ const BreakpointEditorItem = ({
|
||||
onChangeComplete,
|
||||
onDelete,
|
||||
}: BreakpointEditorItemProps) => {
|
||||
const [type, setType] = useState<"minWidth" | "maxWidth">(
|
||||
breakpoint.maxWidth !== undefined ? "maxWidth" : "minWidth"
|
||||
);
|
||||
|
||||
const initialValue = useMemo(
|
||||
() => ({
|
||||
label: breakpoint.label,
|
||||
condition: breakpoint.condition ?? "",
|
||||
width: breakpoint.minWidth ?? breakpoint.maxWidth ?? 0,
|
||||
type: (breakpoint.maxWidth !== undefined ? "maxWidth" : "minWidth") as
|
||||
| "minWidth"
|
||||
| "maxWidth",
|
||||
}),
|
||||
[
|
||||
breakpoint.label,
|
||||
@@ -71,7 +70,7 @@ const BreakpointEditorItem = ({
|
||||
breakpoint.id,
|
||||
value.label,
|
||||
value.condition,
|
||||
type,
|
||||
value.type,
|
||||
value.width,
|
||||
breakpoint
|
||||
);
|
||||
@@ -80,7 +79,7 @@ const BreakpointEditorItem = ({
|
||||
onChangeComplete(newBreakpoint);
|
||||
}
|
||||
},
|
||||
{ autoSave: true }
|
||||
{ autoSave: false }
|
||||
);
|
||||
|
||||
const hasCondition = localValue.value.condition.trim() !== "";
|
||||
@@ -121,7 +120,7 @@ const BreakpointEditorItem = ({
|
||||
breakpoint.id,
|
||||
localValue.value.label,
|
||||
localValue.value.condition,
|
||||
type,
|
||||
localValue.value.type,
|
||||
localValue.value.width,
|
||||
breakpoint
|
||||
);
|
||||
@@ -140,11 +139,14 @@ const BreakpointEditorItem = ({
|
||||
css={{ width: theme.spacing[28] }}
|
||||
options={["maxWidth", "minWidth"]}
|
||||
getLabel={(option) =>
|
||||
option === "maxWidth" ? "Max Width" : "Min Width"
|
||||
option === "maxWidth" ? "Max width" : "Min width"
|
||||
}
|
||||
value={type}
|
||||
value={localValue.value.type}
|
||||
onChange={(value) => {
|
||||
setType(value as "minWidth" | "maxWidth");
|
||||
localValue.set({
|
||||
...localValue.value,
|
||||
type: value as "minWidth" | "maxWidth",
|
||||
});
|
||||
localValue.save();
|
||||
}}
|
||||
disabled={hasCondition}
|
||||
@@ -159,7 +161,11 @@ const BreakpointEditorItem = ({
|
||||
value: localValue.value.width,
|
||||
unit: "px",
|
||||
}}
|
||||
intermediateValue={undefined}
|
||||
intermediateValue={{
|
||||
type: "unit",
|
||||
value: localValue.value.width,
|
||||
unit: "px",
|
||||
}}
|
||||
disabled={hasCondition}
|
||||
getOptions={() => []}
|
||||
onChange={(value) => {
|
||||
@@ -300,7 +306,7 @@ export const BreakpointsEditor = ({
|
||||
return;
|
||||
}
|
||||
const newBreakpoint: Breakpoint = {
|
||||
id: nanoid(),
|
||||
id: createId("nano"),
|
||||
label: "",
|
||||
minWidth: 0,
|
||||
};
|
||||
@@ -319,14 +325,14 @@ export const BreakpointsEditor = ({
|
||||
{allBreakpoints.map((breakpoint, index, all) => {
|
||||
return (
|
||||
<Fragment key={breakpoint.id}>
|
||||
<Box css={{ p: theme.panel.padding }}>
|
||||
<PanelContent as={Box}>
|
||||
<BreakpointEditorItem
|
||||
breakpoint={breakpoint}
|
||||
onChangeComplete={handleChangeComplete}
|
||||
onDelete={onDelete}
|
||||
autoFocus={index === 0}
|
||||
/>
|
||||
</Box>
|
||||
</PanelContent>
|
||||
{index < all.length - 1 && <PopoverSeparator />}
|
||||
</Fragment>
|
||||
);
|
||||
@@ -343,3 +349,5 @@ export const BreakpointsEditor = ({
|
||||
</Popover>
|
||||
);
|
||||
};
|
||||
|
||||
export const __testing__ = { BreakpointEditorItem };
|
||||
@@ -1,15 +1,15 @@
|
||||
import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";
|
||||
import {
|
||||
PanelContent,
|
||||
Flex,
|
||||
Button,
|
||||
Text,
|
||||
ToolbarButton,
|
||||
theme,
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuSeparator,
|
||||
Button,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { EllipsesIcon } from "@webstudio-is/icons";
|
||||
import { groupBreakpoints } from "@webstudio-is/project-build/runtime";
|
||||
@@ -41,17 +41,21 @@ export const BreakpointsMenu = ({
|
||||
return (
|
||||
<DropdownMenu open={open} onOpenChange={onOpenChange}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<ToolbarButton
|
||||
variant="subtle"
|
||||
<Button
|
||||
type="button"
|
||||
color="ghost"
|
||||
aria-label="Breakpoints with custom conditions"
|
||||
data-state={triggerOpen ? "open" : selectedCustom ? "on" : "off"}
|
||||
state={
|
||||
triggerOpen || selectedCustom !== undefined ? "pressed" : "auto"
|
||||
}
|
||||
prefix={selectedCustom ? undefined : <EllipsesIcon />}
|
||||
>
|
||||
{selectedCustom ? selectedCustom.label : <EllipsesIcon />}
|
||||
</ToolbarButton>
|
||||
{selectedCustom?.label}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent sideOffset={4} css={{ width: theme.spacing[30] }}>
|
||||
<DropdownMenuContent css={{ width: theme.spacing[30] }}>
|
||||
{grouped.widthBased.map((breakpoint) => {
|
||||
let description = "All Sizes";
|
||||
let description = "All sizes";
|
||||
if (breakpoint.minWidth !== undefined) {
|
||||
description = `≥ ${breakpoint.minWidth} PX`;
|
||||
} else if (breakpoint.maxWidth !== undefined) {
|
||||
@@ -103,13 +107,8 @@ export const BreakpointsMenu = ({
|
||||
<DropdownMenuSeparator />
|
||||
)}
|
||||
|
||||
<Flex
|
||||
align="center"
|
||||
justify="center"
|
||||
css={{ padding: theme.panel.padding }}
|
||||
>
|
||||
<PanelContent as={Flex} align="center" justify="center">
|
||||
<Button
|
||||
color="neutral"
|
||||
onClick={() => {
|
||||
onEditClick();
|
||||
}}
|
||||
@@ -117,8 +116,10 @@ export const BreakpointsMenu = ({
|
||||
>
|
||||
Edit breakpoints
|
||||
</Button>
|
||||
</Flex>
|
||||
</PanelContent>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
};
|
||||
|
||||
undefined;
|
||||
@@ -3,10 +3,10 @@ import type { Breakpoint } from "@webstudio-is/sdk";
|
||||
import {
|
||||
Flex,
|
||||
Text,
|
||||
Toolbar,
|
||||
ToolbarToggleGroup,
|
||||
ToolbarToggleItem,
|
||||
ToggleGroup,
|
||||
ToggleGroupButton,
|
||||
Tooltip,
|
||||
cssVar,
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { AlertIcon, AsteriskIcon } from "@webstudio-is/icons";
|
||||
@@ -143,7 +143,7 @@ const ZoomWarning = () => {
|
||||
css={{
|
||||
px: theme.spacing[5],
|
||||
height: "100%",
|
||||
color: theme.colors.backgroundAlertMain,
|
||||
color: cssVar("--foreground-warning"),
|
||||
}}
|
||||
>
|
||||
<AlertIcon />
|
||||
@@ -163,20 +163,24 @@ export const BreakpointsSelector = () => {
|
||||
}
|
||||
|
||||
return (
|
||||
<Toolbar>
|
||||
<ToolbarToggleGroup
|
||||
<Flex align="center" css={{ height: theme.spacing[15] }}>
|
||||
<ToggleGroup
|
||||
variant="frameless"
|
||||
type="single"
|
||||
value={selectedBreakpoint.id}
|
||||
onValueChange={(breakpointId: string) => {
|
||||
// onValueChange gives empty string when unselected
|
||||
// which is not part of breakpoints so do nothing in this case
|
||||
if (breakpoints.has(breakpointId) === false) {
|
||||
return;
|
||||
}
|
||||
$selectedBreakpointId.set(breakpointId);
|
||||
setCanvasWidth(breakpointId);
|
||||
}}
|
||||
css={{ position: "relative" }}
|
||||
aria-label="Breakpoints"
|
||||
css={{
|
||||
position: "relative",
|
||||
alignSelf: "stretch",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
{(() => {
|
||||
const grouped = groupBreakpoints(Array.from(breakpoints.values()));
|
||||
@@ -189,8 +193,24 @@ export const BreakpointsSelector = () => {
|
||||
variant="wrapped"
|
||||
disableHoverableContent
|
||||
>
|
||||
<ToolbarToggleItem
|
||||
variant="subtle"
|
||||
<ToggleGroupButton
|
||||
value={breakpoint.id}
|
||||
css={{
|
||||
color: cssVar("--foreground-secondary"),
|
||||
fontWeight: 500,
|
||||
"&:hover": {
|
||||
color: cssVar("--foreground-primary"),
|
||||
backgroundColor: cssVar("--overlay-interaction-hover"),
|
||||
},
|
||||
"&[aria-checked=true]": {
|
||||
color: cssVar("--foreground-primary"),
|
||||
fontWeight: 600,
|
||||
backgroundColor: "transparent",
|
||||
"&:hover": {
|
||||
backgroundColor: cssVar("--overlay-interaction-hover"),
|
||||
},
|
||||
},
|
||||
}}
|
||||
ref={(node) => {
|
||||
if (node) {
|
||||
refs.current.set(breakpoint.id, node);
|
||||
@@ -198,12 +218,11 @@ export const BreakpointsSelector = () => {
|
||||
}
|
||||
refs.current.delete(breakpoint.id);
|
||||
}}
|
||||
value={breakpoint.id}
|
||||
>
|
||||
{breakpoint.minWidth ?? breakpoint.maxWidth ?? (
|
||||
<AsteriskIcon size={22} />
|
||||
<AsteriskIcon size={19} />
|
||||
)}
|
||||
</ToolbarToggleItem>
|
||||
</ToggleGroupButton>
|
||||
</Tooltip>
|
||||
));
|
||||
})()}
|
||||
@@ -214,8 +233,8 @@ export const BreakpointsSelector = () => {
|
||||
breakpoints={breakpoints}
|
||||
/>
|
||||
)}
|
||||
</ToolbarToggleGroup>
|
||||
</ToggleGroup>
|
||||
<ZoomWarning />
|
||||
</Toolbar>
|
||||
</Flex>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useEffect } from "react";
|
||||
import { $breakpoints } from "~/shared/sync/data-stores";
|
||||
import { $selectedBreakpointId } from "~/shared/nano-states";
|
||||
import { $canvasWidth } from "~/builder/shared/nano-states";
|
||||
import { CanvasSettingsPopover } from "./canvas-settings-popover";
|
||||
|
||||
export default { title: "Canvas settings", component: CanvasSettingsPopover };
|
||||
export const CanvasSettings = () => {
|
||||
useEffect(() => {
|
||||
const previous = [
|
||||
$breakpoints.get(),
|
||||
$selectedBreakpointId.get(),
|
||||
$canvasWidth.get(),
|
||||
] as const;
|
||||
$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));
|
||||
$selectedBreakpointId.set("base");
|
||||
$canvasWidth.set(1280);
|
||||
return () => {
|
||||
$breakpoints.set(previous[0]);
|
||||
$selectedBreakpointId.set(previous[1]);
|
||||
$canvasWidth.set(previous[2]);
|
||||
};
|
||||
}, []);
|
||||
return <CanvasSettingsPopover />;
|
||||
};
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useStore } from "@nanostores/react";
|
||||
import {
|
||||
PanelContent,
|
||||
theme,
|
||||
Flex,
|
||||
Label,
|
||||
@@ -7,7 +8,7 @@ import {
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
InputField,
|
||||
ToolbarButton,
|
||||
Button,
|
||||
Text,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { WidthInput } from "./width-input";
|
||||
@@ -29,28 +30,28 @@ export const CanvasSettingsPopover = () => {
|
||||
|
||||
return (
|
||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||
<PopoverTrigger aria-label="Canvas Settings" asChild>
|
||||
<ToolbarButton>
|
||||
<PopoverTrigger aria-label="Canvas settings" asChild>
|
||||
<Button type="button" color="ghost">
|
||||
<Text
|
||||
css={{
|
||||
display: "flex",
|
||||
gap: "1ch",
|
||||
fontVariantNumeric: "tabular-nums",
|
||||
}}
|
||||
color={isOpen ? "contrast" : "moreSubtle"}
|
||||
color={isOpen ? "main" : "subtle"}
|
||||
>
|
||||
{Math.round(canvasWidth)}px
|
||||
{roundedScale !== 100 && <span>{`${roundedScale}%`}</span>}
|
||||
<ChevronDownIcon />
|
||||
</Text>
|
||||
</ToolbarButton>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
collisionPadding={4}
|
||||
align="start"
|
||||
css={{ width: theme.spacing[30] }}
|
||||
>
|
||||
<Flex css={{ padding: theme.panel.padding }} gap="3">
|
||||
<PanelContent as={Flex} gap="3">
|
||||
<WidthInput min={minCanvasWidth} />
|
||||
<Flex align="center" gap="2">
|
||||
<Label>Scale</Label>
|
||||
@@ -60,7 +61,7 @@ export const CanvasSettingsPopover = () => {
|
||||
readOnly
|
||||
/>
|
||||
</Flex>
|
||||
</Flex>
|
||||
</PanelContent>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useStore } from "@nanostores/react";
|
||||
import { css, theme } from "@webstudio-is/design-system";
|
||||
import { css } from "@webstudio-is/design-system";
|
||||
import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";
|
||||
import { $breakpoints } from "~/shared/sync/data-stores";
|
||||
import { isBaseBreakpoint } from "@webstudio-is/project-build/runtime";
|
||||
|
||||
// Fixed Webstudio visualization, intentionally independent of the UI theme.
|
||||
const gradientLeft = "linear-gradient(90deg, #4a4efa 0%, #bd2fdb 100%)";
|
||||
const gradientRight = "linear-gradient(90deg, #bd2fdb 0%, #4a4efa 100%)";
|
||||
|
||||
const cascadeIndicatorStyle = css({
|
||||
position: "absolute",
|
||||
bottom: 0,
|
||||
@@ -12,10 +16,10 @@ const cascadeIndicatorStyle = css({
|
||||
borderRadius: 2,
|
||||
transition: "150ms width, 150ms left, 150ms right",
|
||||
'&[data-direction="left"]': {
|
||||
background: theme.colors.backgroundGradientHorizontal,
|
||||
background: gradientLeft,
|
||||
},
|
||||
'&[data-direction="right"]': {
|
||||
background: theme.colors.backgroundGradientHorizontalReverse,
|
||||
background: gradientRight,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -38,9 +38,7 @@ export const ConfirmationDialog = ({
|
||||
<Button autoFocus onClick={onConfirm} color="destructive">
|
||||
Delete
|
||||
</Button>
|
||||
<Button color="neutral" onClick={onAbort}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={onAbort}>Cancel</Button>
|
||||
</DialogActions>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { StorySection, Toolbar } from "@webstudio-is/design-system";
|
||||
import { Flex, StorySection } from "@webstudio-is/design-system";
|
||||
import { BuilderModeDropDown } from "./builder-mode";
|
||||
import {
|
||||
$builderMode,
|
||||
@@ -11,8 +11,8 @@ export default {
|
||||
title: "Builder mode",
|
||||
};
|
||||
|
||||
export const BuilderMode = () => {
|
||||
$builderMode.set("design");
|
||||
const renderBuilderMode = (mode: "design" | "preview") => {
|
||||
$builderMode.set(mode);
|
||||
$authPermit.set("own");
|
||||
$authToken.set(undefined);
|
||||
$planFeatures.set({
|
||||
@@ -20,19 +20,17 @@ export const BuilderMode = () => {
|
||||
allowContentMode: true,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<StorySection title="Design mode">
|
||||
<Toolbar>
|
||||
<BuilderModeDropDown />
|
||||
</Toolbar>
|
||||
</StorySection>
|
||||
|
||||
<StorySection title="Preview mode">
|
||||
<Toolbar>
|
||||
<BuilderModeDropDown />
|
||||
</Toolbar>
|
||||
</StorySection>
|
||||
</>
|
||||
);
|
||||
return <BuilderModeDropDown />;
|
||||
};
|
||||
|
||||
export const DesignMode = () => (
|
||||
<StorySection title="Design mode">
|
||||
<Flex align="center">{renderBuilderMode("design")}</Flex>
|
||||
</StorySection>
|
||||
);
|
||||
|
||||
export const PreviewMode = () => (
|
||||
<StorySection title="Preview mode">
|
||||
<Flex align="center">{renderBuilderMode("preview")}</Flex>
|
||||
</StorySection>
|
||||
);
|
||||
@@ -0,0 +1,105 @@
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { userEvent } from "@vitest/browser/context";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { TooltipProvider } from "@webstudio-is/design-system";
|
||||
import { defaultPlanFeatures } from "@webstudio-is/plans";
|
||||
import {
|
||||
$authPermit,
|
||||
$builderMode,
|
||||
$planFeatures,
|
||||
setBuilderMode,
|
||||
} from "~/shared/nano-states";
|
||||
import { BuilderModeDropDown } from "./builder-mode";
|
||||
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
let root: Root | undefined;
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
root = undefined;
|
||||
document.body.innerHTML = "";
|
||||
$authPermit.set("view");
|
||||
$planFeatures.set(defaultPlanFeatures);
|
||||
});
|
||||
|
||||
const openModeMenu = async () => {
|
||||
$builderMode.set("design");
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
await act(async () =>
|
||||
root?.render(
|
||||
<TooltipProvider>
|
||||
<BuilderModeDropDown />
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
await act(async () =>
|
||||
userEvent.click(
|
||||
container.querySelector('button[aria-label="Choose mode"]')!
|
||||
)
|
||||
);
|
||||
return Array.from(
|
||||
document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')
|
||||
).find((item) => item.textContent?.includes("Content"));
|
||||
};
|
||||
|
||||
test("shows the Content shortcut for an owned free project", async () => {
|
||||
$authPermit.set("own");
|
||||
$planFeatures.set(defaultPlanFeatures);
|
||||
|
||||
const contentItem = await openModeMenu();
|
||||
|
||||
expect(contentItem).toBeDefined();
|
||||
expect(contentItem?.hasAttribute("data-disabled")).toBe(false);
|
||||
expect(contentItem?.textContent).not.toContain("Pro");
|
||||
expect(contentItem?.querySelector("kbd")).not.toBeNull();
|
||||
});
|
||||
|
||||
test("shows the shortcut without the Pro badge when Content is allowed", async () => {
|
||||
$authPermit.set("own");
|
||||
$planFeatures.set({ ...defaultPlanFeatures, allowContentMode: true });
|
||||
|
||||
const contentItem = await openModeMenu();
|
||||
|
||||
expect(contentItem).toBeDefined();
|
||||
expect(contentItem?.hasAttribute("data-disabled")).toBe(false);
|
||||
expect(contentItem?.querySelector("kbd")).not.toBeNull();
|
||||
expect(contentItem?.textContent).not.toContain("Pro");
|
||||
});
|
||||
|
||||
test("shows Content as a disabled Pro option on a shared free project", async () => {
|
||||
$authPermit.set("build");
|
||||
$planFeatures.set(defaultPlanFeatures);
|
||||
|
||||
const contentItem = await openModeMenu();
|
||||
|
||||
expect(contentItem).toBeDefined();
|
||||
expect(contentItem?.hasAttribute("data-disabled")).toBe(true);
|
||||
expect(contentItem?.textContent).toContain("Pro");
|
||||
expect(contentItem?.querySelector("kbd")).toBeNull();
|
||||
});
|
||||
|
||||
test("shows the shortcut on a shared Pro project", async () => {
|
||||
$authPermit.set("build");
|
||||
$planFeatures.set({ ...defaultPlanFeatures, allowContentMode: true });
|
||||
|
||||
const contentItem = await openModeMenu();
|
||||
|
||||
expect(contentItem).toBeDefined();
|
||||
expect(contentItem?.hasAttribute("data-disabled")).toBe(false);
|
||||
expect(contentItem?.querySelector("kbd")).not.toBeNull();
|
||||
});
|
||||
|
||||
test("opens a free Content-only share link in Preview mode", () => {
|
||||
$authPermit.set("edit");
|
||||
$planFeatures.set(defaultPlanFeatures);
|
||||
|
||||
setBuilderMode("content");
|
||||
|
||||
expect($builderMode.get()).toBe("preview");
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from "@webstudio-is/icons";
|
||||
import {
|
||||
Box,
|
||||
Chip,
|
||||
DropdownMenuItemRightSlot,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
@@ -17,9 +18,9 @@ import {
|
||||
MenuCheckedIcon,
|
||||
menuItemCss,
|
||||
theme,
|
||||
ToolbarButton,
|
||||
ToolbarToggleGroup,
|
||||
ToolbarToggleItem,
|
||||
IconToggleButton,
|
||||
SplitButton,
|
||||
SplitButtonMenuButton,
|
||||
Tooltip,
|
||||
Text,
|
||||
DropdownMenu,
|
||||
@@ -70,7 +71,7 @@ export const BuilderModeDropDown = () => {
|
||||
};
|
||||
|
||||
return (
|
||||
<Flex align="center">
|
||||
<SplitButton>
|
||||
<Tooltip
|
||||
content={
|
||||
<Flex gap="1">
|
||||
@@ -79,36 +80,25 @@ export const BuilderModeDropDown = () => {
|
||||
</Flex>
|
||||
}
|
||||
>
|
||||
<ToolbarToggleGroup
|
||||
type="single"
|
||||
value={builderMode}
|
||||
onValueChange={() => {
|
||||
<IconToggleButton
|
||||
aria-label="Toggle preview"
|
||||
pressed={builderMode === "preview"}
|
||||
onPressedChange={() => {
|
||||
emitCommand("togglePreviewMode");
|
||||
}}
|
||||
>
|
||||
<ToolbarToggleItem variant="preview" value="preview">
|
||||
<PlayIcon />
|
||||
</ToolbarToggleItem>
|
||||
</ToolbarToggleGroup>
|
||||
<PlayIcon />
|
||||
</IconToggleButton>
|
||||
</Tooltip>
|
||||
<DropdownMenu>
|
||||
<Tooltip content={"Choose mode"}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<ToolbarButton
|
||||
tabIndex={0}
|
||||
aria-label="Choose mode"
|
||||
variant="chevron"
|
||||
>
|
||||
<SplitButtonMenuButton type="button" aria-label="Choose mode">
|
||||
<ChevronDownIcon />
|
||||
</ToolbarButton>
|
||||
</SplitButtonMenuButton>
|
||||
</DropdownMenuTrigger>
|
||||
</Tooltip>
|
||||
<DropdownMenuContent
|
||||
sideOffset={4}
|
||||
collisionPadding={16}
|
||||
side="bottom"
|
||||
loop
|
||||
>
|
||||
<DropdownMenuContent collisionPadding={16} side="bottom" loop>
|
||||
<DropdownMenuRadioGroup
|
||||
value={builderMode}
|
||||
onValueChange={(value) => {
|
||||
@@ -118,11 +108,12 @@ export const BuilderModeDropDown = () => {
|
||||
}}
|
||||
>
|
||||
{Object.entries(menuItems)
|
||||
.filter(([_, { enabled }]) => enabled)
|
||||
.map(([mode, { icon, title, shortcut }]) => (
|
||||
.filter(([mode, { enabled }]) => mode === "content" || enabled)
|
||||
.map(([mode, { icon, title, shortcut, enabled }]) => (
|
||||
<DropdownMenuRadioItem
|
||||
key={mode}
|
||||
value={mode}
|
||||
disabled={!enabled}
|
||||
onFocus={handleFocus(mode as keyof typeof menuItems)}
|
||||
onBlur={handleBlur}
|
||||
icon={<MenuCheckedIcon />}
|
||||
@@ -132,7 +123,7 @@ export const BuilderModeDropDown = () => {
|
||||
<Box>{title}</Box>
|
||||
</Flex>
|
||||
<DropdownMenuItemRightSlot>
|
||||
<Kbd value={shortcut} />
|
||||
{enabled ? <Kbd value={shortcut} /> : <Chip>Pro</Chip>}
|
||||
</DropdownMenuItemRightSlot>
|
||||
|
||||
</DropdownMenuRadioItem>
|
||||
@@ -149,6 +140,6 @@ export const BuilderModeDropDown = () => {
|
||||
</div>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</Flex>
|
||||
</SplitButton>
|
||||
);
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useStore } from "@nanostores/react";
|
||||
import { buttonStyle, Link } from "@webstudio-is/design-system";
|
||||
import { LinkButton } from "@webstudio-is/design-system";
|
||||
import { $authToken, $authTokenPermissions } from "~/shared/nano-states";
|
||||
import { cloneProjectUrl } from "~/shared/router-utils/path-utils";
|
||||
|
||||
@@ -12,19 +12,15 @@ export const CloneButton = () => {
|
||||
}
|
||||
|
||||
return (
|
||||
<Link
|
||||
data-state="auto"
|
||||
className={buttonStyle({
|
||||
color: "positive",
|
||||
})}
|
||||
color="contrast"
|
||||
<LinkButton
|
||||
href={cloneProjectUrl({
|
||||
origin: window.origin,
|
||||
sourceAuthToken: authToken,
|
||||
})}
|
||||
underline="none"
|
||||
>
|
||||
Clone
|
||||
</Link>
|
||||
</LinkButton>
|
||||
);
|
||||
};
|
||||
|
||||
undefined;
|
||||
@@ -68,7 +68,7 @@ const getBreakpointLabel = (breakpoint: Breakpoint) => {
|
||||
return `${breakpoint.label}: ${breakpoint.condition}`;
|
||||
}
|
||||
|
||||
let label = "All Sizes";
|
||||
let label = "All sizes";
|
||||
if (breakpoint.minWidth !== undefined) {
|
||||
label = `≥ ${breakpoint.minWidth} PX`;
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ export const CssVariablesGroup = ({
|
||||
name="cssVariable"
|
||||
heading={
|
||||
<CommandGroupHeading>
|
||||
CSS Variables ({options.length})
|
||||
CSS variables ({options.length})
|
||||
</CommandGroupHeading>
|
||||
}
|
||||
actions={[
|
||||
|
||||
@@ -127,7 +127,7 @@ export const DataVariablesGroup = ({
|
||||
name="dataVariable"
|
||||
heading={
|
||||
<CommandGroupHeading>
|
||||
Data variables ({options.length})
|
||||
Variables ({options.length})
|
||||
</CommandGroupHeading>
|
||||
}
|
||||
actions={[
|
||||
|
||||
@@ -3,7 +3,10 @@ import { coreMetas, elementComponent } from "@webstudio-is/sdk";
|
||||
import * as baseMetas from "@webstudio-is/sdk-components-react/metas";
|
||||
import * as animationMetas from "@webstudio-is/sdk-components-animation/metas";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { $, renderData } from "@webstudio-is/template";
|
||||
import {
|
||||
createTemplateComponentFixture,
|
||||
renderData,
|
||||
} from "@webstudio-is/template";
|
||||
import { $registeredComponentMetas } from "~/shared/nano-states";
|
||||
import { $instances } from "~/shared/sync/data-stores";
|
||||
import { $pages, $props } from "~/shared/sync/data-stores";
|
||||
@@ -12,6 +15,11 @@ import { $selectedPageId } from "~/shared/nano-states";
|
||||
import { selectInstance } from "~/shared/nano-states";
|
||||
import { canWrapInstance } from "@webstudio-is/project-build/runtime";
|
||||
|
||||
const Body = createTemplateComponentFixture("Body");
|
||||
const Box = createTemplateComponentFixture("Box");
|
||||
const ListItem = createTemplateComponentFixture("ListItem");
|
||||
const Text = createTemplateComponentFixture("Text");
|
||||
|
||||
registerContainers();
|
||||
|
||||
const metas = new Map(
|
||||
@@ -28,9 +36,9 @@ describe("canWrapInstance for components", () => {
|
||||
test("should allow wrapping text in a Link", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.Text ws:id="text">Hello</$.Text>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<Text ws:id="text">Hello</Text>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["text", "body"]);
|
||||
@@ -51,9 +59,9 @@ describe("canWrapInstance for components", () => {
|
||||
test("should allow wrapping text in a Heading", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.Text ws:id="text">Hello</$.Text>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<Text ws:id="text">Hello</Text>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["text", "body"]);
|
||||
@@ -74,9 +82,9 @@ describe("canWrapInstance for components", () => {
|
||||
test("should allow wrapping box in a Form", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.Box ws:id="box"></$.Box>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<Box ws:id="box"></Box>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["box", "body"]);
|
||||
@@ -85,7 +93,7 @@ describe("canWrapInstance for components", () => {
|
||||
"box",
|
||||
["box", "body"],
|
||||
"body",
|
||||
"Form",
|
||||
"ResourceForm",
|
||||
undefined,
|
||||
$instances.get(),
|
||||
$props.get(),
|
||||
@@ -94,12 +102,12 @@ describe("canWrapInstance for components", () => {
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
test("should allow wrapping text in a legacy CodeText", () => {
|
||||
test("should prevent wrapping an instance in CodeText", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.Text ws:id="text">Hello</$.Text>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<Text ws:id="text">Hello</Text>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["text", "body"]);
|
||||
@@ -114,7 +122,7 @@ describe("canWrapInstance for components", () => {
|
||||
$props.get(),
|
||||
$registeredComponentMetas.get()
|
||||
);
|
||||
expect(result).toBe(true);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -122,9 +130,9 @@ describe("canWrapInstance for HTML elements", () => {
|
||||
test("should allow wrapping text in a span", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.Text ws:id="text">Hello</$.Text>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<Text ws:id="text">Hello</Text>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["text", "body"]);
|
||||
@@ -145,9 +153,9 @@ describe("canWrapInstance for HTML elements", () => {
|
||||
test("should allow wrapping box in a div", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.Box ws:id="box"></$.Box>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<Box ws:id="box"></Box>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["box", "body"]);
|
||||
@@ -168,9 +176,9 @@ describe("canWrapInstance for HTML elements", () => {
|
||||
test("should allow wrapping box in span (content model allows it)", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.Box ws:id="box"></$.Box>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<Box ws:id="box"></Box>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["box", "body"]);
|
||||
@@ -193,9 +201,9 @@ describe("canWrapInstance for HTML elements", () => {
|
||||
test("should allow wrapping list item in ul", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.ListItem ws:id="li">Item</$.ListItem>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<ListItem ws:id="li">Item</ListItem>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["li", "body"]);
|
||||
@@ -216,9 +224,9 @@ describe("canWrapInstance for HTML elements", () => {
|
||||
test("should reject wrapping box in ul (ul requires li children)", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.Box ws:id="box"></$.Box>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<Box ws:id="box"></Box>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["box", "body"]);
|
||||
@@ -242,9 +250,9 @@ describe("canWrapInstance edge cases", () => {
|
||||
test("should handle wrapping with Slot", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.Box ws:id="box"></$.Box>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<Box ws:id="box"></Box>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["box", "body"]);
|
||||
@@ -265,9 +273,9 @@ describe("canWrapInstance edge cases", () => {
|
||||
test("should allow wrapping with Collection", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.Box ws:id="box"></$.Box>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<Box ws:id="box"></Box>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["box", "body"]);
|
||||
@@ -288,9 +296,9 @@ describe("canWrapInstance edge cases", () => {
|
||||
test("should allow wrapping with AnimateChildren", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.Box ws:id="box"></$.Box>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<Box ws:id="box"></Box>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["box", "body"]);
|
||||
@@ -311,9 +319,9 @@ describe("canWrapInstance edge cases", () => {
|
||||
test("should allow wrapping with AnimateText", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.Box ws:id="box"></$.Box>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<Box ws:id="box"></Box>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["box", "body"]);
|
||||
@@ -334,9 +342,9 @@ describe("canWrapInstance edge cases", () => {
|
||||
test("should allow wrapping with StaggerAnimation", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.Box ws:id="box"></$.Box>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<Box ws:id="box"></Box>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["box", "body"]);
|
||||
@@ -357,9 +365,9 @@ describe("canWrapInstance edge cases", () => {
|
||||
test("should allow wrapping with VideoAnimation", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.Box ws:id="box"></$.Box>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<Box ws:id="box"></Box>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["box", "body"]);
|
||||
@@ -380,12 +388,12 @@ describe("canWrapInstance edge cases", () => {
|
||||
test("should handle wrapping multiple elements", () => {
|
||||
$instances.set(
|
||||
renderData(
|
||||
<$.Body ws:id="body">
|
||||
<$.Box ws:id="parent">
|
||||
<$.Box ws:id="child1"></$.Box>
|
||||
<$.Box ws:id="child2"></$.Box>
|
||||
</$.Box>
|
||||
</$.Body>
|
||||
<Body ws:id="body">
|
||||
<Box ws:id="parent">
|
||||
<Box ws:id="child1"></Box>
|
||||
<Box ws:id="child2"></Box>
|
||||
</Box>
|
||||
</Body>
|
||||
).instances
|
||||
);
|
||||
selectInstance(["child1", "parent", "body"]);
|
||||
|
||||
@@ -54,7 +54,7 @@ const wrapperComponentNames = [
|
||||
"AnimateText",
|
||||
"StaggerAnimation",
|
||||
"VideoAnimation",
|
||||
"Form",
|
||||
"ResourceForm",
|
||||
];
|
||||
|
||||
const $wrapOptions = computed(
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
listComponentCatalogAvailableComponents,
|
||||
} from "@webstudio-is/project-build/runtime";
|
||||
import {
|
||||
PanelContent,
|
||||
theme,
|
||||
Flex,
|
||||
ComponentCard,
|
||||
@@ -46,6 +47,7 @@ const $metas = computed(
|
||||
const metasByCategory = listBuilderComponentPanelItems({
|
||||
metas: componentMetas,
|
||||
templates,
|
||||
showDeprecatedSection: isFeatureEnabled("deprecatedComponents"),
|
||||
documentType: selectedPage?.meta.documentType ?? "html",
|
||||
showInternal: isFeatureEnabled("internalComponents"),
|
||||
getFallbackLabel: (component) => getInstanceLabel({ component }),
|
||||
@@ -172,13 +174,13 @@ export const ComponentsPanel = ({
|
||||
<PanelTitle>Components</PanelTitle>
|
||||
<Separator />
|
||||
|
||||
<Box css={{ padding: theme.panel.padding }}>
|
||||
<PanelContent as={Box}>
|
||||
<SearchField
|
||||
{...searchFieldProps}
|
||||
autoFocus
|
||||
placeholder="Find components"
|
||||
/>
|
||||
</Box>
|
||||
</PanelContent>
|
||||
<Separator />
|
||||
|
||||
<ScrollArea ref={draggableContainerRef}>
|
||||
|
||||
@@ -22,8 +22,7 @@ export const Breadcrumbs = () => {
|
||||
return (
|
||||
<Fragment key={index}>
|
||||
<Button
|
||||
color="dark-ghost"
|
||||
css={{ color: "inherit" }}
|
||||
color="ghost"
|
||||
key={instance.id}
|
||||
onClick={() => {
|
||||
selectInstance(instanceSelector);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Flex, theme } from "@webstudio-is/design-system";
|
||||
import { cssVar, Flex, theme } from "@webstudio-is/design-system";
|
||||
import { Breadcrumbs } from "./breadcrumbs";
|
||||
|
||||
export const Footer = () => {
|
||||
@@ -10,8 +10,9 @@ export const Footer = () => {
|
||||
isolation: "isolate",
|
||||
gridArea: "footer",
|
||||
height: theme.spacing[11],
|
||||
background: theme.colors.backgroundTopbar,
|
||||
color: theme.colors.foregroundContrastMain,
|
||||
background: cssVar("--background-primary"),
|
||||
borderTop: `1px solid ${cssVar("--border-default")}`,
|
||||
color: cssVar("--foreground-primary"),
|
||||
}}
|
||||
>
|
||||
<Breadcrumbs />
|
||||
|
||||
+6
-3
@@ -1,5 +1,6 @@
|
||||
import { useStore } from "@nanostores/react";
|
||||
import {
|
||||
PanelContent,
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
@@ -10,6 +11,7 @@ import {
|
||||
ScrollArea,
|
||||
theme,
|
||||
Box,
|
||||
cssVar,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { atom } from "nanostores";
|
||||
import { Fragment } from "react";
|
||||
@@ -203,6 +205,7 @@ export const KeyboardShortcutsDialog = () => {
|
||||
"focusStyleSources",
|
||||
"toggleStylePanelFocusMode",
|
||||
"toggleStylePanelAdvancedMode",
|
||||
"openStyleBlockEditor",
|
||||
],
|
||||
};
|
||||
|
||||
@@ -286,7 +289,7 @@ export const KeyboardShortcutsDialog = () => {
|
||||
as="span"
|
||||
css={{
|
||||
paddingInline: 4,
|
||||
border: `1px solid ${theme.colors.borderNeutral}`,
|
||||
border: `1px solid ${cssVar("--border-default")}`,
|
||||
borderRadius: theme.borderRadius[2],
|
||||
}}
|
||||
>
|
||||
@@ -323,10 +326,10 @@ export const KeyboardShortcutsDialog = () => {
|
||||
>
|
||||
<DialogTitle>Keyboard shortcuts</DialogTitle>
|
||||
<ScrollArea>
|
||||
<Grid columns={2} gap={3} css={{ padding: theme.panel.padding }}>
|
||||
<PanelContent as={Grid} columns={2} gap={3}>
|
||||
<Grid gap={5}>{leftCategories.map(renderCategory)}</Grid>
|
||||
<Grid gap={5}>{rightCategories.map(renderCategory)}</Grid>
|
||||
</Grid>
|
||||
</PanelContent>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -2,11 +2,11 @@ import {
|
||||
DialogClose,
|
||||
Flex,
|
||||
Link,
|
||||
LinkButton,
|
||||
PanelTitle,
|
||||
Separator,
|
||||
Text,
|
||||
Tooltip,
|
||||
buttonStyle,
|
||||
theme,
|
||||
truncate,
|
||||
} from "@webstudio-is/design-system";
|
||||
@@ -50,7 +50,7 @@ export const About = ({ item }: { item?: MarketplaceOverviewItem }) => {
|
||||
</Flex>
|
||||
{item.issues && (
|
||||
<Flex gap="1">
|
||||
<Text css={{ flexShrink: 0 }}>Issues Tracker:</Text>
|
||||
<Text css={{ flexShrink: 0 }}>Issues tracker:</Text>
|
||||
<Link href={item.issues} target="_blank" css={truncate()}>
|
||||
{item.issues}
|
||||
</Link>
|
||||
@@ -68,14 +68,8 @@ export const About = ({ item }: { item?: MarketplaceOverviewItem }) => {
|
||||
: 'The project does not have a shared link with "View" permission.'
|
||||
}
|
||||
>
|
||||
<Link
|
||||
className={buttonStyle({
|
||||
color: "neutral",
|
||||
css: {
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
})}
|
||||
underline="none"
|
||||
<LinkButton
|
||||
css={{ gap: theme.spacing[3] }}
|
||||
href={
|
||||
hasAuthToken
|
||||
? builderUrl({
|
||||
@@ -89,9 +83,11 @@ export const About = ({ item }: { item?: MarketplaceOverviewItem }) => {
|
||||
aria-disabled={hasAuthToken ? undefined : "true"}
|
||||
>
|
||||
<ExternalLinkIcon aria-hidden /> Open project
|
||||
</Link>
|
||||
</LinkButton>
|
||||
</Tooltip>
|
||||
</Flex>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
undefined;
|
||||
@@ -14,7 +14,7 @@ export default {
|
||||
|
||||
const placeholderImage = `data:image/svg+xml,${encodeURIComponent(
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="400" height="210">
|
||||
<rect width="400" height="210" fill="#c0d0e0"/>
|
||||
<rect width="400" height="210" fill="transparent"/>
|
||||
<text x="200" y="105" text-anchor="middle" dominant-baseline="central"
|
||||
font-family="sans-serif" font-size="24" fill="#4a6a8a">400 × 210</text>
|
||||
</svg>`
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { forwardRef } from "react";
|
||||
import {
|
||||
PanelContent,
|
||||
Flex,
|
||||
Text,
|
||||
theme,
|
||||
focusRingStyle,
|
||||
css,
|
||||
cssVar,
|
||||
rawTheme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { getImageAttributes, wsImageLoader } from "@webstudio-is/image";
|
||||
@@ -25,7 +27,7 @@ const spinnerStyle = css({
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
backgroundColor: "rgba(255, 255, 255, 0.5)",
|
||||
backgroundColor: `color-mix(in oklab, ${cssVar("--background-primary")} 50%, transparent)`,
|
||||
backdropFilter: "blur(8px)",
|
||||
});
|
||||
|
||||
@@ -44,7 +46,7 @@ const imageStyle = css({
|
||||
objectFit: "cover",
|
||||
},
|
||||
false: {
|
||||
background: theme.colors.white,
|
||||
background: cssVar("--background-primary"),
|
||||
padding: rawTheme.spacing[5],
|
||||
},
|
||||
},
|
||||
@@ -105,13 +107,13 @@ export const Card = forwardRef<HTMLDivElement, CardProps>(
|
||||
ref
|
||||
) => {
|
||||
return (
|
||||
<Flex
|
||||
<PanelContent
|
||||
as={Flex}
|
||||
{...props}
|
||||
ref={ref}
|
||||
direction="column"
|
||||
data-state={state}
|
||||
css={{
|
||||
padding: theme.panel.padding,
|
||||
position: "relative",
|
||||
overflow: "hidden",
|
||||
outline: "none",
|
||||
@@ -130,7 +132,7 @@ export const Card = forwardRef<HTMLDivElement, CardProps>(
|
||||
</Text>
|
||||
{suffix}
|
||||
</Flex>
|
||||
</Flex>
|
||||
</PanelContent>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useState } from "react";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import type { WebstudioData } from "@webstudio-is/sdk";
|
||||
import type { MarketplaceOverviewItem } from "~/shared/marketplace/types";
|
||||
import { Overview } from "./overview";
|
||||
import { Templates } from "./templates";
|
||||
export default { title: "Builder/Marketplace/Gallery", component: Overview };
|
||||
const items: MarketplaceOverviewItem[] = [
|
||||
{
|
||||
projectId: "section",
|
||||
category: "sectionTemplates",
|
||||
name: "Sections",
|
||||
author: "Webstudio team",
|
||||
thumbnailAssetId: "",
|
||||
email: "team@example.com",
|
||||
description: "Section templates",
|
||||
},
|
||||
{
|
||||
projectId: "pages",
|
||||
category: "pageTemplates",
|
||||
name: "Pages",
|
||||
author: "Webstudio team",
|
||||
thumbnailAssetId: "",
|
||||
email: "team@example.com",
|
||||
description: "Page templates",
|
||||
},
|
||||
];
|
||||
const GalleryStory = ({
|
||||
loading = false,
|
||||
selected = false,
|
||||
empty = false,
|
||||
}: {
|
||||
loading?: boolean;
|
||||
selected?: boolean;
|
||||
empty?: boolean;
|
||||
}) => {
|
||||
const [active, setActive] = useState<string | undefined>(
|
||||
loading ? "section" : undefined
|
||||
);
|
||||
const [about, setAbout] = useState<string | undefined>(
|
||||
selected ? "section" : undefined
|
||||
);
|
||||
return (
|
||||
<div style={{ width: 320, height: 700 }}>
|
||||
<Overview
|
||||
items={empty ? [] : items}
|
||||
activeProjectId={active}
|
||||
openAbout={about}
|
||||
onOpenAbout={setAbout}
|
||||
onSelect={(item) => setActive(item.projectId)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
export const Default = () => <GalleryStory />;
|
||||
export const Loading = () => <GalleryStory loading />;
|
||||
export const Selected = () => <GalleryStory selected />;
|
||||
export const Empty = () => <GalleryStory empty />;
|
||||
const pages = createDefaultPages({ rootInstanceId: "body" });
|
||||
pages.pages.get(pages.homePageId)!.marketplace = {
|
||||
include: true,
|
||||
category: "Sections",
|
||||
};
|
||||
const data: WebstudioData = {
|
||||
pages,
|
||||
assets: new Map(),
|
||||
breakpoints: new Map(),
|
||||
dataSources: new Map(),
|
||||
instances: new Map([
|
||||
["body", { id: "body", type: "instance", component: "Body", children: [] }],
|
||||
]),
|
||||
props: new Map(),
|
||||
resources: new Map(),
|
||||
styles: new Map(),
|
||||
styleSources: new Map(),
|
||||
styleSourceSelections: new Map(),
|
||||
};
|
||||
const TemplatesStory = ({ authorized = false }: { authorized?: boolean }) => (
|
||||
<div style={{ width: 320, height: 700 }}>
|
||||
<Templates
|
||||
name="Sections"
|
||||
projectId="example-project"
|
||||
productCategory="sectionTemplates"
|
||||
authorizationToken={authorized ? "storybook-example" : undefined}
|
||||
data={data}
|
||||
onOpenChange={() => {}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
export const TemplatesAvailable = () => <TemplatesStory authorized />;
|
||||
export const TemplatesWithoutShareLink = () => <TemplatesStory />;
|
||||
@@ -47,7 +47,11 @@ const GalleryOverviewItem = ({
|
||||
state={isOpen ? "selected" : isLoading ? "loading" : undefined}
|
||||
suffix={
|
||||
<Flex shrink={false} align="center">
|
||||
<IconButton {...pressProps} state={isOpen ? "open" : undefined}>
|
||||
<IconButton
|
||||
{...pressProps}
|
||||
state={isOpen ? "open" : undefined}
|
||||
aria-label={`More actions for ${item.name}`}
|
||||
>
|
||||
<EllipsesIcon />
|
||||
</IconButton>
|
||||
</Flex>
|
||||
|
||||
@@ -7,13 +7,13 @@ import {
|
||||
import { executeRuntimeMutation } from "~/shared/instance-utils/data";
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
PanelContent,
|
||||
Button,
|
||||
Flex,
|
||||
List,
|
||||
ListItem,
|
||||
ScrollArea,
|
||||
Separator,
|
||||
theme,
|
||||
Link,
|
||||
Tooltip,
|
||||
} from "@webstudio-is/design-system";
|
||||
@@ -190,11 +190,11 @@ export const Templates = ({
|
||||
|
||||
return (
|
||||
<Flex direction="column" css={{ height: "100%" }}>
|
||||
<Flex
|
||||
<PanelContent
|
||||
as={Flex}
|
||||
align="center"
|
||||
shrink="false"
|
||||
justify="between"
|
||||
css={{ padding: theme.panel.padding }}
|
||||
gap="3"
|
||||
>
|
||||
<Button
|
||||
@@ -202,7 +202,6 @@ export const Templates = ({
|
||||
onClick={() => {
|
||||
onOpenChange(false);
|
||||
}}
|
||||
color="neutral"
|
||||
>
|
||||
{name}
|
||||
</Button>
|
||||
@@ -231,7 +230,7 @@ export const Templates = ({
|
||||
<ExternalLinkIcon />
|
||||
</Link>
|
||||
</Tooltip>
|
||||
</Flex>
|
||||
</PanelContent>
|
||||
<Separator />
|
||||
<ScrollArea>
|
||||
{Array.from(templatesDataByCategory.keys())
|
||||
@@ -287,3 +286,5 @@ export const Templates = ({
|
||||
</Flex>
|
||||
);
|
||||
};
|
||||
|
||||
undefined;
|
||||
@@ -1,65 +1,12 @@
|
||||
import {
|
||||
css,
|
||||
DropdownMenuTrigger,
|
||||
rawTheme,
|
||||
ToolbarButton,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { MenuIcon, WebstudioIcon } from "@webstudio-is/icons";
|
||||
|
||||
const size = rawTheme.spacing[9];
|
||||
|
||||
const containerTransformVar = "--ws-menu-button-container-transform";
|
||||
|
||||
const triggerStyle = css({
|
||||
position: "relative",
|
||||
[containerTransformVar]: `translateZ(-${size}) rotateY(0deg)`,
|
||||
"&[data-state=open], &:hover": {
|
||||
[containerTransformVar]: `translateZ(-${size}) rotateY(-90deg)`,
|
||||
},
|
||||
});
|
||||
|
||||
const innerContainerStyle = css({
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
transformStyle: "preserve-3d",
|
||||
transition: "transform 200ms",
|
||||
transform: `var(${containerTransformVar})`,
|
||||
});
|
||||
|
||||
const faceStyle = css({
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
position: "absolute",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
variants: {
|
||||
front: {
|
||||
true: {
|
||||
transform: `rotateY(0deg) translateZ(${size})`,
|
||||
},
|
||||
},
|
||||
back: {
|
||||
true: {
|
||||
transform: `rotateY(90deg) translateZ(${size})`,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
import { DropdownMenuTrigger, IconButton } from "@webstudio-is/design-system";
|
||||
import { MenuIcon } from "@webstudio-is/icons";
|
||||
|
||||
export const MenuButton = () => {
|
||||
return (
|
||||
<ToolbarButton asChild className={triggerStyle()} aria-label="Menu Button">
|
||||
<DropdownMenuTrigger>
|
||||
<span className={innerContainerStyle()}>
|
||||
<span className={faceStyle({ front: true })}>
|
||||
<WebstudioIcon size={22} />
|
||||
</span>
|
||||
<span className={faceStyle({ back: true })}>
|
||||
<MenuIcon size={22} />
|
||||
</span>
|
||||
</span>
|
||||
</DropdownMenuTrigger>
|
||||
</ToolbarButton>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<IconButton type="button" aria-label="Menu" size="large">
|
||||
<MenuIcon size={22} />
|
||||
</IconButton>
|
||||
</DropdownMenuTrigger>
|
||||
);
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Flex, StorySection, Text, Toolbar } from "@webstudio-is/design-system";
|
||||
import { Flex, StorySection, Text } from "@webstudio-is/design-system";
|
||||
import { Menu } from "./menu";
|
||||
import {
|
||||
$authPermit,
|
||||
@@ -28,9 +28,9 @@ const OwnerDesignModeVariant = () => {
|
||||
});
|
||||
$purchases.set([{ planName: "Pro" }]);
|
||||
return (
|
||||
<Toolbar>
|
||||
<Flex align="center">
|
||||
<Menu defaultOpen />
|
||||
</Toolbar>
|
||||
</Flex>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -44,9 +44,9 @@ const ViewerFreePlanVariant = () => {
|
||||
canPublish: false,
|
||||
});
|
||||
return (
|
||||
<Toolbar>
|
||||
<Flex align="center">
|
||||
<Menu defaultOpen />
|
||||
</Toolbar>
|
||||
</Flex>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -65,9 +65,9 @@ const AdminContentModeVariant = () => {
|
||||
});
|
||||
$purchases.set([{ planName: "Pro" }]);
|
||||
return (
|
||||
<Toolbar>
|
||||
<Flex align="center">
|
||||
<Menu defaultOpen />
|
||||
</Toolbar>
|
||||
</Flex>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -33,11 +33,12 @@ import { emitCommand } from "~/builder/shared/commands";
|
||||
import { MenuButton } from "./menu-button";
|
||||
import { $openProjectSettings } from "~/shared/nano-states/project-settings";
|
||||
import { UpgradeIcon } from "@webstudio-is/icons";
|
||||
import { getSetting, setSetting } from "~/builder/shared/client-settings";
|
||||
import { $settings, setSetting } from "~/builder/shared/client-settings";
|
||||
import { help } from "~/shared/help";
|
||||
import { ColorSchemeMenu } from "~/shared/color-scheme-menu";
|
||||
|
||||
const ViewMenuItem = () => {
|
||||
const navigatorLayout = getSetting("navigatorLayout");
|
||||
const { navigatorLayout } = useStore($settings);
|
||||
const isUiHidden = useStore($isUiHidden);
|
||||
|
||||
return (
|
||||
@@ -63,6 +64,8 @@ const ViewMenuItem = () => {
|
||||
>
|
||||
Undock navigator
|
||||
</DropdownMenuCheckboxItem>
|
||||
<DropdownMenuSeparator />
|
||||
<ColorSchemeMenu withIndicator />
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
);
|
||||
@@ -93,7 +96,7 @@ export const Menu = ({ defaultOpen }: { defaultOpen?: boolean } = {}) => {
|
||||
return (
|
||||
<DropdownMenu modal={false} defaultOpen={defaultOpen}>
|
||||
<MenuButton />
|
||||
<DropdownMenuContent sideOffset={4} collisionPadding={4} width="regular">
|
||||
<DropdownMenuContent collisionPadding={4} width="regular">
|
||||
<DropdownMenuItem
|
||||
onSelect={() => {
|
||||
window.location.href = dashboardUrl({ origin: window.origin });
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
import { computed } from "nanostores";
|
||||
import { useStore } from "@nanostores/react";
|
||||
import {
|
||||
ScrollArea,
|
||||
css,
|
||||
textVariants,
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { generateStyleMap, mergeStyles } from "@webstudio-is/css-engine";
|
||||
import type { StyleMap } from "@webstudio-is/css-engine";
|
||||
import { CollapsibleSection } from "~/builder/shared/collapsible-section";
|
||||
import { highlightCss } from "~/shared/code-highlight";
|
||||
import type { ComputedStyleDecl } from "~/shared/style-object-model";
|
||||
import { $computedStyleDeclarations } from "~/builder/features/style-panel/shared/model";
|
||||
import { $selectedInstance } from "~/shared/nano-states";
|
||||
|
||||
const preStyle = css(textVariants.mono, {
|
||||
margin: 0,
|
||||
height: theme.spacing[24],
|
||||
userSelect: "text",
|
||||
cursor: "text",
|
||||
});
|
||||
|
||||
// - Compiles a CSS string from the style engine
|
||||
// - Groups by category and separates categories with comments
|
||||
const getCssText = (
|
||||
definedComputedStyles: ComputedStyleDecl[],
|
||||
instanceId: string
|
||||
) => {
|
||||
const sourceStyles: StyleMap = new Map();
|
||||
const cascadedStyles: StyleMap = new Map();
|
||||
const presetStyles: StyleMap = new Map();
|
||||
|
||||
// Aggregate styles by category so we can group them when rendering.
|
||||
for (const styleDecl of definedComputedStyles) {
|
||||
let group;
|
||||
if (
|
||||
styleDecl.source.name === "local" ||
|
||||
styleDecl.source.name === "overwritten"
|
||||
) {
|
||||
group = sourceStyles;
|
||||
}
|
||||
if (styleDecl.source.name === "remote") {
|
||||
group = cascadedStyles;
|
||||
}
|
||||
if (styleDecl.source.name === "preset") {
|
||||
group = presetStyles;
|
||||
}
|
||||
if (group) {
|
||||
if (styleDecl.source.instanceId === instanceId) {
|
||||
group.set(styleDecl.property, styleDecl.cascadedValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result: Array<string> = [];
|
||||
|
||||
const add = (comment: string, style: StyleMap) => {
|
||||
if (style.size === 0) {
|
||||
return;
|
||||
}
|
||||
result.push(`/* ${comment} */`);
|
||||
result.push(generateStyleMap(mergeStyles(style)));
|
||||
};
|
||||
|
||||
add("Style sources", sourceStyles);
|
||||
add("Cascaded", cascadedStyles);
|
||||
add("Preset", presetStyles);
|
||||
|
||||
return result.join("\n");
|
||||
};
|
||||
|
||||
const $highlightedCss = computed(
|
||||
[$selectedInstance, $computedStyleDeclarations],
|
||||
(instance, computedStyleDeclarations) => {
|
||||
if (instance === undefined) {
|
||||
return;
|
||||
}
|
||||
const cssText = getCssText(computedStyleDeclarations, instance.id);
|
||||
return highlightCss(cssText);
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Will be deleted soon in favor of advanced panel as soon as it has ability to select.
|
||||
* @deprecated
|
||||
*/
|
||||
export const CssPreview = () => {
|
||||
const code = useStore($highlightedCss);
|
||||
if (code === undefined) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<CollapsibleSection label="CSS preview" fullWidth>
|
||||
<ScrollArea css={{ padding: theme.panel.padding }}>
|
||||
<pre tabIndex={0} className={preStyle()}>
|
||||
<div
|
||||
style={{ whiteSpace: "break-spaces" }}
|
||||
dangerouslySetInnerHTML={{ __html: code }}
|
||||
></div>
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</CollapsibleSection>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,104 @@
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { blockComponent, coreMetas } from "@webstudio-is/sdk";
|
||||
import { TooltipProvider } from "@webstudio-is/design-system";
|
||||
import {
|
||||
$builderMode,
|
||||
$registeredComponentMetas,
|
||||
$selectedPageId,
|
||||
} from "~/shared/nano-states";
|
||||
import { $instances, $pages } from "~/shared/sync/data-stores";
|
||||
import { NavigatorTree } from "./navigator-tree";
|
||||
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
let root: Root | undefined;
|
||||
let container: HTMLDivElement | undefined;
|
||||
const previousMetas = $registeredComponentMetas.get();
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
container?.remove();
|
||||
root = undefined;
|
||||
container = undefined;
|
||||
$builderMode.set("design");
|
||||
$selectedPageId.set(undefined);
|
||||
$pages.set(undefined);
|
||||
$instances.set(new Map());
|
||||
$registeredComponentMetas.set(previousMetas);
|
||||
});
|
||||
|
||||
test("explains an empty Content mode Navigator only for a selected page", () => {
|
||||
$registeredComponentMetas.set(new Map(Object.entries(coreMetas)));
|
||||
$pages.set(
|
||||
createDefaultPages({ rootInstanceId: "body", homePageId: "home" })
|
||||
);
|
||||
$instances.set(
|
||||
new Map([
|
||||
[
|
||||
"body",
|
||||
{
|
||||
type: "instance",
|
||||
id: "body",
|
||||
component: "Body",
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
[
|
||||
"block",
|
||||
{
|
||||
type: "instance",
|
||||
id: "block",
|
||||
component: blockComponent,
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
])
|
||||
);
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
$builderMode.set("content");
|
||||
root?.render(
|
||||
<TooltipProvider>
|
||||
<NavigatorTree />
|
||||
</TooltipProvider>
|
||||
);
|
||||
});
|
||||
expect(container.querySelector('[role="status"]')).toBeNull();
|
||||
|
||||
act(() => $selectedPageId.set("home"));
|
||||
expect(container.querySelector('[role="status"]')).not.toBeNull();
|
||||
|
||||
act(() => {
|
||||
$instances.set(
|
||||
new Map([
|
||||
[
|
||||
"body",
|
||||
{
|
||||
...$instances.get().get("body")!,
|
||||
children: [{ type: "id", value: "block" }],
|
||||
},
|
||||
],
|
||||
["block", $instances.get().get("block")!],
|
||||
])
|
||||
);
|
||||
});
|
||||
expect(container.querySelector('[role="status"]')).toBeNull();
|
||||
|
||||
act(() => $builderMode.set("design"));
|
||||
expect(container.querySelector('[role="status"]')).toBeNull();
|
||||
|
||||
act(() => {
|
||||
const instances = new Map($instances.get());
|
||||
instances.set("body", { ...instances.get("body")!, children: [] });
|
||||
$instances.set(instances);
|
||||
});
|
||||
expect(container.querySelector('[role="status"]')).toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Box, StorySection, theme } from "@webstudio-is/design-system";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import {
|
||||
blockBodyComponent,
|
||||
blockComponent,
|
||||
contentBlockSourceProp,
|
||||
coreMetas,
|
||||
elementComponent,
|
||||
type Instance,
|
||||
} from "@webstudio-is/sdk";
|
||||
import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$builderMode,
|
||||
$editingItemSelector,
|
||||
$registeredComponentMetas,
|
||||
$selectedPageId,
|
||||
selectInstance,
|
||||
selectInstances,
|
||||
} from "~/shared/nano-states";
|
||||
import { $instances, $pages, $props } from "~/shared/sync/data-stores";
|
||||
import { $externalContentRoots } from "~/shared/external-content-mutations";
|
||||
import { NavigatorPanel } from "./navigator";
|
||||
|
||||
type State =
|
||||
| "design"
|
||||
| "no-content"
|
||||
| "content"
|
||||
| "mdx"
|
||||
| "multi"
|
||||
| "menu"
|
||||
| "rename";
|
||||
|
||||
export default { title: "Navigator/Panel", component: NavigatorPanel };
|
||||
|
||||
const NavigatorStory = ({ state }: { state: State }) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
const previous = {
|
||||
builderMode: $builderMode.get(),
|
||||
metas: $registeredComponentMetas.get(),
|
||||
instances: $instances.get(),
|
||||
pages: $pages.get(),
|
||||
props: $props.get(),
|
||||
selectedPageId: $selectedPageId.get(),
|
||||
selectedInstances: $allSelectedInstanceSelectors.get(),
|
||||
editingItem: $editingItemSelector.get(),
|
||||
externalRoots: $externalContentRoots.get(),
|
||||
};
|
||||
const isContent =
|
||||
state === "no-content" || state === "content" || state === "mdx";
|
||||
const bodyChildren =
|
||||
state === "no-content"
|
||||
? []
|
||||
: isContent
|
||||
? [{ type: "id" as const, value: "block" }]
|
||||
: ["first", "second", "third"].map((value) => ({
|
||||
type: "id" as const,
|
||||
value,
|
||||
}));
|
||||
const instances: Instance[] = [
|
||||
{
|
||||
type: "instance",
|
||||
id: "body",
|
||||
component: "Body",
|
||||
children: bodyChildren,
|
||||
},
|
||||
...(isContent && state !== "no-content"
|
||||
? [
|
||||
{
|
||||
type: "instance" as const,
|
||||
id: "block",
|
||||
component: blockComponent,
|
||||
label: "Article",
|
||||
children: [
|
||||
{
|
||||
type: "id" as const,
|
||||
value: state === "mdx" ? "mdx" : "heading",
|
||||
},
|
||||
],
|
||||
},
|
||||
state === "mdx"
|
||||
? {
|
||||
type: "instance" as const,
|
||||
id: "mdx",
|
||||
component: blockBodyComponent,
|
||||
children: [],
|
||||
}
|
||||
: {
|
||||
type: "instance" as const,
|
||||
id: "heading",
|
||||
component: elementComponent,
|
||||
tag: "h1",
|
||||
label: "Article heading",
|
||||
children: [
|
||||
{ type: "text" as const, value: "Article heading" },
|
||||
],
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(!isContent
|
||||
? ["first", "second", "third"].map(
|
||||
(id): Instance => ({
|
||||
type: "instance",
|
||||
id,
|
||||
component: elementComponent,
|
||||
tag: "div",
|
||||
label: `${id[0].toUpperCase()}${id.slice(1)} box`,
|
||||
children: [],
|
||||
})
|
||||
)
|
||||
: []),
|
||||
];
|
||||
$registeredComponentMetas.set(
|
||||
new Map(Object.entries({ ...coreMetas, ...baseComponentMetas }))
|
||||
);
|
||||
$instances.set(
|
||||
new Map(instances.map((instance) => [instance.id, instance]))
|
||||
);
|
||||
$pages.set(
|
||||
createDefaultPages({ rootInstanceId: "body", homePageId: "home" })
|
||||
);
|
||||
$props.set(
|
||||
state === "mdx"
|
||||
? new Map([
|
||||
[
|
||||
"source",
|
||||
{
|
||||
id: "source",
|
||||
instanceId: "block",
|
||||
name: contentBlockSourceProp,
|
||||
type: "asset" as const,
|
||||
value: "article",
|
||||
},
|
||||
],
|
||||
])
|
||||
: new Map()
|
||||
);
|
||||
$externalContentRoots.set(new Map());
|
||||
$selectedPageId.set("home");
|
||||
$builderMode.set(isContent ? "content" : "design");
|
||||
if (state === "multi") {
|
||||
selectInstances([
|
||||
["first", "body"],
|
||||
["second", "body"],
|
||||
]);
|
||||
} else if (state === "rename") {
|
||||
selectInstance(["first", "body"]);
|
||||
$editingItemSelector.set(["first", "body"]);
|
||||
} else if (state === "mdx") {
|
||||
selectInstance(["mdx", "block", "body"]);
|
||||
} else if (state === "content") {
|
||||
selectInstance(["heading", "block", "body"]);
|
||||
} else {
|
||||
selectInstance(["first", "body"]);
|
||||
}
|
||||
setReady(true);
|
||||
return () => {
|
||||
$builderMode.set(previous.builderMode);
|
||||
$registeredComponentMetas.set(previous.metas);
|
||||
$instances.set(previous.instances);
|
||||
$pages.set(previous.pages);
|
||||
$props.set(previous.props);
|
||||
$selectedPageId.set(previous.selectedPageId);
|
||||
$allSelectedInstanceSelectors.set(previous.selectedInstances);
|
||||
$editingItemSelector.set(previous.editingItem);
|
||||
$externalContentRoots.set(previous.externalRoots);
|
||||
};
|
||||
}, [state]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ready || state !== "menu") {
|
||||
return;
|
||||
}
|
||||
const showMenu = () => {
|
||||
const row = Array.from(
|
||||
document.querySelectorAll<HTMLButtonElement>("[data-tree-button]")
|
||||
).find((item) => item.textContent?.includes("First box"));
|
||||
if (row) {
|
||||
observer.disconnect();
|
||||
row.dispatchEvent(
|
||||
new MouseEvent("contextmenu", {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
button: 2,
|
||||
})
|
||||
);
|
||||
}
|
||||
};
|
||||
const observer = new MutationObserver(showMenu);
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
showMenu();
|
||||
return () => observer.disconnect();
|
||||
}, [ready, state]);
|
||||
|
||||
return (
|
||||
<StorySection title="Navigator">
|
||||
<Box
|
||||
css={{
|
||||
width: theme.sizes.sidebarWidth,
|
||||
height: 480,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
}}
|
||||
>
|
||||
{ready && <NavigatorPanel onClose={() => {}} />}
|
||||
</Box>
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
|
||||
export const Design = () => <NavigatorStory state="design" />;
|
||||
export const NoEditableContent = () => <NavigatorStory state="no-content" />;
|
||||
export const EditableContent = () => <NavigatorStory state="content" />;
|
||||
export const MdxContent = () => <NavigatorStory state="mdx" />;
|
||||
export const MultiSelection = () => <NavigatorStory state="multi" />;
|
||||
export const ContextMenu = () => <NavigatorStory state="menu" />;
|
||||
export const Rename = () => <NavigatorStory state="rename" />;
|
||||
@@ -0,0 +1,230 @@
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { expect, test } from "vitest";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { coreMetas, elementComponent, type Instance } from "@webstudio-is/sdk";
|
||||
import { TooltipProvider } from "@webstudio-is/design-system";
|
||||
import { showAttribute } from "@webstudio-is/react-sdk";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$dragAndDropState,
|
||||
$propValuesByInstanceSelector,
|
||||
$selectedPageId,
|
||||
$registeredComponentMetas,
|
||||
getInstanceKey,
|
||||
selectInstance,
|
||||
} from "~/shared/nano-states";
|
||||
import { $instances, $pages } from "~/shared/sync/data-stores";
|
||||
import { $flatTree, NavigatorTree } from "./navigator-tree";
|
||||
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
test("large Navigator selection and reorder leave unchanged labels alone", async () => {
|
||||
const count = 2000;
|
||||
let labelReads = 0;
|
||||
const previousMetas = $registeredComponentMetas.get();
|
||||
$registeredComponentMetas.set(new Map(Object.entries(coreMetas)));
|
||||
const children = Array.from({ length: count }, (_, index) => ({
|
||||
type: "id" as const,
|
||||
value: `child-${index}`,
|
||||
}));
|
||||
$pages.set(
|
||||
createDefaultPages({ rootInstanceId: "body", homePageId: "home" })
|
||||
);
|
||||
$instances.set(
|
||||
new Map<string, Instance>([
|
||||
[
|
||||
"body",
|
||||
{
|
||||
type: "instance",
|
||||
id: "body",
|
||||
component: elementComponent,
|
||||
tag: "body",
|
||||
children,
|
||||
},
|
||||
],
|
||||
...children.map(({ value }): [string, Instance] => [
|
||||
value,
|
||||
{
|
||||
type: "instance",
|
||||
id: value,
|
||||
component: elementComponent,
|
||||
tag: "div",
|
||||
children: [],
|
||||
get label() {
|
||||
labelReads += 1;
|
||||
return value;
|
||||
},
|
||||
},
|
||||
]),
|
||||
])
|
||||
);
|
||||
$selectedPageId.set("home");
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
const startRender = performance.now();
|
||||
act(() =>
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<NavigatorTree />
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
const renderMs = performance.now() - startRender;
|
||||
expect(
|
||||
container.querySelectorAll("[data-tree-button]").length
|
||||
).toBeGreaterThan(count);
|
||||
labelReads = 0;
|
||||
const treeBeforeSelection = $flatTree.get();
|
||||
const startSelect = performance.now();
|
||||
act(() => selectInstance(["child-1000", "body"]));
|
||||
const selectMs = performance.now() - startSelect;
|
||||
expect($flatTree.get()).toBe(treeBeforeSelection);
|
||||
const selectionLabelReads = labelReads;
|
||||
labelReads = 0;
|
||||
const startReorder = performance.now();
|
||||
act(() => {
|
||||
$instances.set(
|
||||
new Map($instances.get()).set("body", {
|
||||
...$instances.get().get("body")!,
|
||||
children: [children.at(-1)!, ...children.slice(0, -1)],
|
||||
})
|
||||
);
|
||||
});
|
||||
const reorderMs = performance.now() - startReorder;
|
||||
console.info({
|
||||
count,
|
||||
renderMs,
|
||||
selectMs,
|
||||
reorderMs,
|
||||
selectionLabelReads,
|
||||
reorderLabelReads: labelReads,
|
||||
});
|
||||
expect.soft(selectionLabelReads).toBeLessThan(10);
|
||||
expect.soft(labelReads).toBe(0);
|
||||
|
||||
const buttons = Array.from(
|
||||
container.querySelectorAll<HTMLButtonElement>("[data-tree-button]")
|
||||
);
|
||||
const selected = buttons.find(
|
||||
(button) => button.getAttribute("aria-selected") === "true"
|
||||
)!;
|
||||
expect(selected.textContent).toBe("child-1000");
|
||||
expect(buttons[2].textContent).toBe("child-1999");
|
||||
|
||||
const sibling = buttons.find(
|
||||
(button) => button.textContent === "child-1001"
|
||||
)!;
|
||||
act(() => {
|
||||
sibling.dispatchEvent(
|
||||
new PointerEvent("pointerdown", {
|
||||
bubbles: true,
|
||||
button: 0,
|
||||
ctrlKey: true,
|
||||
})
|
||||
);
|
||||
});
|
||||
expect($allSelectedInstanceSelectors.get()).toEqual([
|
||||
["child-1000", "body"],
|
||||
["child-1001", "body"],
|
||||
]);
|
||||
expect(sibling.getAttribute("aria-selected")).toBe("true");
|
||||
act(() => {
|
||||
sibling.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
bubbles: true,
|
||||
key: "ArrowDown",
|
||||
shiftKey: true,
|
||||
})
|
||||
);
|
||||
});
|
||||
expect($allSelectedInstanceSelectors.get()).toHaveLength(3);
|
||||
expect(document.activeElement?.textContent).toBe("child-1002");
|
||||
|
||||
// A prop evaluation refresh also recreates the flat tree.
|
||||
act(() => selectInstance(["child-1000", "body"]));
|
||||
labelReads = 0;
|
||||
act(() => $propValuesByInstanceSelector.set(new Map()));
|
||||
expect.soft(labelReads).toBe(0);
|
||||
|
||||
// Native drag targeting must use the new sibling index after a reorder.
|
||||
const target = buttons[2].closest<HTMLElement>(
|
||||
"[data-tree-sortable-item]"
|
||||
)!;
|
||||
const source = sibling.closest<HTMLElement>("[data-tree-sortable-item]")!;
|
||||
const dataTransfer = new DataTransfer();
|
||||
const rect = target.getBoundingClientRect();
|
||||
act(() => {
|
||||
source.dispatchEvent(
|
||||
new DragEvent("dragstart", { bubbles: true, dataTransfer })
|
||||
);
|
||||
target.dispatchEvent(
|
||||
new DragEvent("dragover", {
|
||||
bubbles: true,
|
||||
dataTransfer,
|
||||
clientX: rect.left + 1,
|
||||
clientY: rect.top + 1,
|
||||
})
|
||||
);
|
||||
});
|
||||
await act(
|
||||
async () =>
|
||||
new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
|
||||
);
|
||||
act(() => {
|
||||
target.dispatchEvent(
|
||||
new DragEvent("dragover", {
|
||||
bubbles: true,
|
||||
dataTransfer,
|
||||
clientX: rect.left + 1,
|
||||
clientY: rect.top + 1,
|
||||
})
|
||||
);
|
||||
});
|
||||
await act(
|
||||
async () =>
|
||||
new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
|
||||
);
|
||||
expect($dragAndDropState.get().dropTarget?.indexWithinChildren).toBe(0);
|
||||
act(() =>
|
||||
source.dispatchEvent(
|
||||
new DragEvent("dragend", { bubbles: true, dataTransfer })
|
||||
)
|
||||
);
|
||||
|
||||
// Row content must still update when its instance or visibility changes.
|
||||
act(() => {
|
||||
const instances = new Map($instances.get());
|
||||
instances.set("child-1001", {
|
||||
...instances.get("child-1001")!,
|
||||
label: "Renamed child",
|
||||
});
|
||||
$instances.set(instances);
|
||||
});
|
||||
expect(sibling.textContent).toBe("Renamed child");
|
||||
act(() =>
|
||||
$propValuesByInstanceSelector.set(
|
||||
new Map([
|
||||
[
|
||||
getInstanceKey(["child-1001", "body"]),
|
||||
new Map([[showAttribute, false]]),
|
||||
],
|
||||
])
|
||||
)
|
||||
);
|
||||
expect(sibling.parentElement?.style.opacity).toBe("0.4");
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
selectInstance(undefined);
|
||||
$selectedPageId.set(undefined);
|
||||
$pages.set(undefined);
|
||||
$instances.set(new Map());
|
||||
$registeredComponentMetas.set(previousMetas);
|
||||
$dragAndDropState.set({ isDragging: false });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { expect, test } from "vitest";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { coreMetas, elementComponent, type Instance } from "@webstudio-is/sdk";
|
||||
import { TooltipProvider } from "@webstudio-is/design-system";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$dragAndDropState,
|
||||
$hoveredInstanceSelector,
|
||||
$registeredComponentMetas,
|
||||
$selectedPageId,
|
||||
selectInstance,
|
||||
selectInstances,
|
||||
} from "~/shared/nano-states";
|
||||
import { $instances, $pages } from "~/shared/sync/data-stores";
|
||||
import { NavigatorTree } from "./navigator-tree";
|
||||
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
test("reuses unrelated rows while selection and hover handlers stay current", () => {
|
||||
const previousMetas = $registeredComponentMetas.get();
|
||||
const reads = new Map<string, number>();
|
||||
const ids = ["first", "second", "third"];
|
||||
const metas = new Map(Object.entries(coreMetas));
|
||||
for (const id of ids) {
|
||||
metas.set(id, {
|
||||
...coreMetas[elementComponent],
|
||||
// Count real row-content renders at the metadata boundary, without replacing modules.
|
||||
get label() {
|
||||
reads.set(id, (reads.get(id) ?? 0) + 1);
|
||||
return id;
|
||||
},
|
||||
});
|
||||
}
|
||||
$registeredComponentMetas.set(metas);
|
||||
$pages.set(
|
||||
createDefaultPages({ rootInstanceId: "body", homePageId: "home" })
|
||||
);
|
||||
$instances.set(
|
||||
new Map<string, Instance>([
|
||||
[
|
||||
"body",
|
||||
{
|
||||
type: "instance",
|
||||
id: "body",
|
||||
component: elementComponent,
|
||||
children: ids.map((value) => ({ type: "id", value })),
|
||||
},
|
||||
],
|
||||
...ids.map((id): [string, Instance] => [
|
||||
id,
|
||||
{ type: "instance", id, component: id, children: [] },
|
||||
]),
|
||||
])
|
||||
);
|
||||
$selectedPageId.set("home");
|
||||
const container = document.createElement("div");
|
||||
container.style.width = "32px";
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
act(() =>
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<NavigatorTree />
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
expect(
|
||||
container.querySelector("[data-radix-scroll-area-viewport]")
|
||||
).toBeNull();
|
||||
const sortableRow = container.querySelector<HTMLElement>(
|
||||
"[data-tree-sortable-item]"
|
||||
);
|
||||
expect(sortableRow).not.toBeNull();
|
||||
expect(getComputedStyle(sortableRow!).contentVisibility).toBe("auto");
|
||||
const tree = container.querySelector<HTMLElement>("[data-navigator-tree]")!;
|
||||
const scroller = tree.parentElement?.parentElement as HTMLElement;
|
||||
expect(getComputedStyle(scroller).overflowX).toBe("auto");
|
||||
expect(scroller.scrollWidth).toBeGreaterThan(scroller.clientWidth);
|
||||
scroller.scrollLeft = 100;
|
||||
expect(scroller.scrollLeft).toBeGreaterThan(0);
|
||||
act(() => selectInstance(["first", "body"]));
|
||||
reads.clear();
|
||||
act(() => selectInstance(["second", "body"]));
|
||||
expect(reads.get("third") ?? 0).toBe(0);
|
||||
expect(reads.get("second")).toBeGreaterThan(0);
|
||||
reads.clear();
|
||||
act(() => $hoveredInstanceSelector.set(["first", "body"]));
|
||||
expect(reads.get("third") ?? 0).toBe(0);
|
||||
expect(reads.get("first")).toBeGreaterThan(0);
|
||||
|
||||
const buttons = Array.from(
|
||||
container.querySelectorAll<HTMLButtonElement>("[data-tree-button]")
|
||||
);
|
||||
const third = buttons.find((button) => button.textContent === "third")!;
|
||||
act(() =>
|
||||
third.dispatchEvent(
|
||||
new MouseEvent("click", { bubbles: true, ctrlKey: true })
|
||||
)
|
||||
);
|
||||
expect($allSelectedInstanceSelectors.get()).toEqual([
|
||||
["second", "body"],
|
||||
["third", "body"],
|
||||
]);
|
||||
const first = buttons.find((button) => button.textContent === "first")!;
|
||||
act(() =>
|
||||
first.dispatchEvent(
|
||||
new MouseEvent("click", { bubbles: true, shiftKey: true })
|
||||
)
|
||||
);
|
||||
expect($allSelectedInstanceSelectors.get()).toEqual(
|
||||
ids.map((id) => [id, "body"])
|
||||
);
|
||||
act(() => {
|
||||
const nextMetas = new Map($registeredComponentMetas.get());
|
||||
nextMetas.set("third", {
|
||||
...nextMetas.get("third")!,
|
||||
label: "Updated component",
|
||||
});
|
||||
$registeredComponentMetas.set(nextMetas);
|
||||
});
|
||||
expect(third.textContent).toBe("Updated component");
|
||||
|
||||
// The drop marker crosses the row edge, so this row must not clip it.
|
||||
const firstRow = first.closest<HTMLElement>("[data-tree-sortable-item]")!;
|
||||
act(() =>
|
||||
$dragAndDropState.set({
|
||||
isDragging: true,
|
||||
dropTarget: {
|
||||
itemSelector: ["body"],
|
||||
indexWithinChildren: 0,
|
||||
placement: {
|
||||
closestChildIndex: 0,
|
||||
indexAdjustment: 0,
|
||||
childrenOrientation: { type: "vertical", reverse: false },
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(getComputedStyle(firstRow).contentVisibility).toBe("visible");
|
||||
expect(
|
||||
getComputedStyle(third.closest<HTMLElement>("[data-tree-sortable-item]")!)
|
||||
.contentVisibility
|
||||
).toBe("auto");
|
||||
act(() => $dragAndDropState.set({ isDragging: false }));
|
||||
expect(getComputedStyle(firstRow).contentVisibility).toBe("auto");
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
selectInstances([]);
|
||||
$hoveredInstanceSelector.set(undefined);
|
||||
$dragAndDropState.set({ isDragging: false });
|
||||
$selectedPageId.set(undefined);
|
||||
$pages.set(undefined);
|
||||
$instances.set(new Map());
|
||||
$registeredComponentMetas.set(previousMetas);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react";
|
||||
import {
|
||||
Box,
|
||||
Flex,
|
||||
StorySection,
|
||||
cssVar,
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { coreMetas } from "@webstudio-is/sdk";
|
||||
import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";
|
||||
import { $registeredComponentMetas } from "~/shared/nano-states";
|
||||
import { $instances, $pages, $props } from "~/shared/sync/data-stores";
|
||||
import { $selectedPageId } from "~/shared/nano-states";
|
||||
import { Label } from "~/builder/features/workspace/canvas-tools/outline/label";
|
||||
import { Outline } from "~/builder/features/workspace/canvas-tools/outline/outline";
|
||||
import { NavigatorTree } from "./navigator-tree";
|
||||
|
||||
const meta = {
|
||||
title: "Navigator/Navigator tree",
|
||||
} satisfies Meta;
|
||||
|
||||
export default meta;
|
||||
|
||||
$registeredComponentMetas.set(
|
||||
new Map(Object.entries({ ...coreMetas, ...baseComponentMetas }))
|
||||
);
|
||||
$instances.set(
|
||||
new Map([
|
||||
[
|
||||
"body",
|
||||
{
|
||||
type: "instance",
|
||||
id: "body",
|
||||
component: "Body",
|
||||
children: [{ type: "id", value: "slot" }],
|
||||
},
|
||||
],
|
||||
[
|
||||
"slot",
|
||||
{
|
||||
type: "instance",
|
||||
id: "slot",
|
||||
component: "Slot",
|
||||
label: "Reusable Slot",
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
])
|
||||
);
|
||||
$props.set(new Map());
|
||||
$pages.set(createDefaultPages({ rootInstanceId: "body", homePageId: "home" }));
|
||||
$selectedPageId.set("home");
|
||||
|
||||
const instanceRect = new DOMRect(24, 48, 192, 80);
|
||||
const clampingRect = new DOMRect(0, 0, 240, 160);
|
||||
|
||||
export const ReusableInstance: StoryObj = {
|
||||
render: () => (
|
||||
<StorySection title="Reusable instance color">
|
||||
<Flex gap={5} align="start">
|
||||
<Box
|
||||
css={{
|
||||
width: theme.sizes.sidebarWidth,
|
||||
height: 160,
|
||||
backgroundColor: cssVar("--background-primary"),
|
||||
}}
|
||||
>
|
||||
<NavigatorTree />
|
||||
</Box>
|
||||
<Box
|
||||
css={{
|
||||
position: "relative",
|
||||
width: clampingRect.width,
|
||||
height: clampingRect.height,
|
||||
backgroundColor: cssVar("--background-primary"),
|
||||
}}
|
||||
>
|
||||
<Outline
|
||||
rect={instanceRect}
|
||||
clampingRect={clampingRect}
|
||||
variant="slot"
|
||||
>
|
||||
<Label
|
||||
instance={{ component: "Slot", label: "Reusable Slot" }}
|
||||
instanceRect={instanceRect}
|
||||
variant="slot"
|
||||
/>
|
||||
</Outline>
|
||||
</Box>
|
||||
</Flex>
|
||||
</StorySection>
|
||||
),
|
||||
};
|
||||
|
||||
export const ReusableInstanceDark: StoryObj = {
|
||||
...ReusableInstance,
|
||||
globals: { colorScheme: "dark" },
|
||||
};
|
||||
@@ -1,13 +1,22 @@
|
||||
import { beforeEach, describe, expect, test } from "vitest";
|
||||
import { blockComponent } from "@webstudio-is/sdk";
|
||||
import { __testing__ } from "./navigator-tree";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
import {
|
||||
blockBodyComponent,
|
||||
blockComponent,
|
||||
elementComponent,
|
||||
contentBlockSourceProp,
|
||||
} from "@webstudio-is/sdk";
|
||||
import { $flatTree, __testing__ } from "./navigator-tree";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
$builderMode,
|
||||
$selectedPageId,
|
||||
selectInstances,
|
||||
} from "~/shared/nano-states";
|
||||
import { $instances } from "~/shared/sync/data-stores";
|
||||
import { $instances, $pages, $props } from "~/shared/sync/data-stores";
|
||||
import { $externalContentRoots } from "~/shared/external-content-mutations";
|
||||
|
||||
const {
|
||||
getMdxContentSource,
|
||||
commitNavigatorDrop,
|
||||
getFocusSelectionSkipCountAfterPointerDown,
|
||||
getBuilderDropTarget,
|
||||
@@ -19,6 +28,102 @@ const {
|
||||
shouldSelectOnPointerDown,
|
||||
} = __testing__;
|
||||
|
||||
test("identifies only the connected MDX Body, including an empty Body", () => {
|
||||
const previousRoots = $externalContentRoots.get();
|
||||
$instances.set(
|
||||
new Map([
|
||||
[
|
||||
"block",
|
||||
{
|
||||
id: "block",
|
||||
type: "instance",
|
||||
component: blockComponent,
|
||||
children: [
|
||||
{ type: "id", value: "body" },
|
||||
{ type: "id", value: "shell" },
|
||||
],
|
||||
},
|
||||
],
|
||||
[
|
||||
"body",
|
||||
{
|
||||
id: "body",
|
||||
type: "instance",
|
||||
component: blockBodyComponent,
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
[
|
||||
"shell",
|
||||
{
|
||||
id: "shell",
|
||||
type: "instance",
|
||||
component: elementComponent,
|
||||
tag: "div",
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
])
|
||||
);
|
||||
$props.set(new Map());
|
||||
expect(getMdxContentSource(["body", "block"])).toBeUndefined();
|
||||
$props.set(
|
||||
new Map([
|
||||
[
|
||||
"source",
|
||||
{
|
||||
id: "source",
|
||||
instanceId: "block",
|
||||
name: contentBlockSourceProp,
|
||||
type: "asset",
|
||||
value: "article",
|
||||
},
|
||||
],
|
||||
])
|
||||
);
|
||||
try {
|
||||
expect(getMdxContentSource(["body", "block"])).toEqual({
|
||||
assetId: "article",
|
||||
});
|
||||
expect(getMdxContentSource(["shell", "block"])).toBeUndefined();
|
||||
expect(getMdxContentSource(["block"])).toBeUndefined();
|
||||
$props.set(
|
||||
new Map([
|
||||
[
|
||||
"source",
|
||||
{
|
||||
id: "source",
|
||||
instanceId: "block",
|
||||
name: contentBlockSourceProp,
|
||||
type: "expression",
|
||||
value: "collection.data._id",
|
||||
},
|
||||
],
|
||||
])
|
||||
);
|
||||
$externalContentRoots.set(
|
||||
new Map([
|
||||
[
|
||||
"root",
|
||||
{
|
||||
blockInstanceId: "block",
|
||||
contentInstanceId: "body",
|
||||
assetId: "article",
|
||||
instanceIds: new Set(),
|
||||
mutationRevision: 0,
|
||||
},
|
||||
],
|
||||
])
|
||||
);
|
||||
expect(getMdxContentSource(["body", "block"])).toEqual({
|
||||
assetId: "article",
|
||||
});
|
||||
} finally {
|
||||
$props.set(new Map());
|
||||
$externalContentRoots.set(previousRoots);
|
||||
}
|
||||
});
|
||||
|
||||
const createTreeItem = ({
|
||||
parentComponent = "Box",
|
||||
}: { parentComponent?: string } = {}): Parameters<
|
||||
@@ -87,6 +192,181 @@ const createTreeItem = ({
|
||||
};
|
||||
};
|
||||
|
||||
test("shows connected Content Block instances in Content mode", () => {
|
||||
$pages.set({
|
||||
homePageId: "home",
|
||||
rootFolderId: "root",
|
||||
pages: new Map([
|
||||
[
|
||||
"home",
|
||||
{
|
||||
id: "home",
|
||||
name: "Home",
|
||||
path: "",
|
||||
title: "Home",
|
||||
meta: {},
|
||||
rootInstanceId: "body",
|
||||
},
|
||||
],
|
||||
]),
|
||||
folders: new Map([
|
||||
["root", { id: "root", name: "Root", slug: "", children: ["home"] }],
|
||||
]),
|
||||
});
|
||||
$instances.set(
|
||||
new Map([
|
||||
[
|
||||
"body",
|
||||
{
|
||||
type: "instance",
|
||||
id: "body",
|
||||
component: "Body",
|
||||
children: [{ type: "id", value: "block" }],
|
||||
},
|
||||
],
|
||||
[
|
||||
"block",
|
||||
{
|
||||
type: "instance",
|
||||
id: "block",
|
||||
component: blockComponent,
|
||||
children: [{ type: "id", value: "heading" }],
|
||||
},
|
||||
],
|
||||
[
|
||||
"heading",
|
||||
{
|
||||
type: "instance",
|
||||
id: "heading",
|
||||
component: elementComponent,
|
||||
tag: "h1",
|
||||
children: [{ type: "text", value: "MDX heading" }],
|
||||
},
|
||||
],
|
||||
])
|
||||
);
|
||||
$selectedPageId.set("home");
|
||||
$builderMode.set("content");
|
||||
expect($flatTree.get().map(({ instance }) => instance.id)).toEqual([
|
||||
"block",
|
||||
"heading",
|
||||
]);
|
||||
});
|
||||
|
||||
test("shows the scoped Content Block occurrence in Content mode", () => {
|
||||
$pages.set({
|
||||
homePageId: "home",
|
||||
rootFolderId: "root",
|
||||
pages: new Map([
|
||||
[
|
||||
"home",
|
||||
{
|
||||
id: "home",
|
||||
name: "Home",
|
||||
path: "",
|
||||
title: "Home",
|
||||
meta: {},
|
||||
rootInstanceId: "body",
|
||||
},
|
||||
],
|
||||
]),
|
||||
folders: new Map([
|
||||
["root", { id: "root", name: "Root", slug: "", children: ["home"] }],
|
||||
]),
|
||||
});
|
||||
$instances.set(
|
||||
new Map([
|
||||
[
|
||||
"body",
|
||||
{
|
||||
type: "instance",
|
||||
id: "body",
|
||||
component: "Body",
|
||||
children: [{ type: "id", value: "block" }],
|
||||
},
|
||||
],
|
||||
[
|
||||
"block",
|
||||
{
|
||||
type: "instance",
|
||||
id: "block",
|
||||
component: blockComponent,
|
||||
children: [{ type: "id", value: "content" }],
|
||||
},
|
||||
],
|
||||
[
|
||||
"content",
|
||||
{
|
||||
type: "instance",
|
||||
id: "content",
|
||||
component: blockBodyComponent,
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
[
|
||||
"scoped-block",
|
||||
{
|
||||
type: "instance",
|
||||
id: "scoped-block",
|
||||
component: blockComponent,
|
||||
children: [{ type: "id", value: "content" }],
|
||||
},
|
||||
],
|
||||
[
|
||||
"scoped-content",
|
||||
{
|
||||
type: "instance",
|
||||
id: "scoped-content",
|
||||
component: blockBodyComponent,
|
||||
children: [{ type: "id", value: "scoped-heading" }],
|
||||
},
|
||||
],
|
||||
[
|
||||
"scoped-heading",
|
||||
{
|
||||
type: "instance",
|
||||
id: "scoped-heading",
|
||||
component: elementComponent,
|
||||
tag: "h1",
|
||||
children: [{ type: "text", value: "Scoped MDX heading" }],
|
||||
},
|
||||
],
|
||||
])
|
||||
);
|
||||
$selectedPageId.set("home");
|
||||
$builderMode.set("content");
|
||||
$externalContentRoots.set(
|
||||
new Map([
|
||||
[
|
||||
"root",
|
||||
{
|
||||
sourceBlockInstanceId: "block",
|
||||
sourceRenderScope: '["block","body"]',
|
||||
blockInstanceId: "scoped-block",
|
||||
sourceContentInstanceId: "content",
|
||||
contentInstanceId: "scoped-content",
|
||||
renderScope: '["scoped-block","body"]',
|
||||
instanceIds: new Set(["scoped-heading"]),
|
||||
mutationRevision: 0,
|
||||
},
|
||||
],
|
||||
])
|
||||
);
|
||||
|
||||
expect($flatTree.get().map(({ instance }) => instance.id)).toEqual([
|
||||
"scoped-block",
|
||||
"scoped-content",
|
||||
]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
$builderMode.set("design");
|
||||
$selectedPageId.set(undefined);
|
||||
$pages.set(undefined);
|
||||
$instances.set(new Map());
|
||||
$externalContentRoots.set(new Map());
|
||||
});
|
||||
|
||||
describe("getNavigatorSelectionUpdate", () => {
|
||||
beforeEach(() => {
|
||||
selectInstances([]);
|
||||
|
||||
@@ -2,15 +2,29 @@ import {
|
||||
reparentInstance,
|
||||
toggleInstanceShow,
|
||||
} from "~/shared/instance-utils/mutation";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import {
|
||||
memo,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ComponentProps,
|
||||
} from "react";
|
||||
import { shallowEqual } from "shallow-equal";
|
||||
import { atom, computed } from "nanostores";
|
||||
import { mergeRefs } from "@react-aria/utils";
|
||||
import { useStore } from "@nanostores/react";
|
||||
import {
|
||||
Box,
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
InfoTooltip,
|
||||
PanelBanner,
|
||||
cssVar,
|
||||
keyframes,
|
||||
rawTheme,
|
||||
ScrollArea,
|
||||
ScrollAreaNative,
|
||||
SmallIconButton,
|
||||
styled,
|
||||
Text,
|
||||
@@ -27,18 +41,23 @@ import { showAttribute, getCollectionEntries } from "@webstudio-is/react-sdk";
|
||||
import {
|
||||
ROOT_INSTANCE_ID,
|
||||
collectionComponent,
|
||||
blockBodyComponent,
|
||||
contentBlockSourceProp,
|
||||
getContentBlockSource,
|
||||
blockComponent,
|
||||
rootComponent,
|
||||
blockTemplateComponent,
|
||||
descendantComponent,
|
||||
type Instance,
|
||||
type WsComponentMeta,
|
||||
} from "@webstudio-is/sdk";
|
||||
import { animationCanPlayOnCanvasProperty } from "@webstudio-is/sdk/runtime";
|
||||
import { showAttributeMeta } from "@webstudio-is/project-build/runtime";
|
||||
import {
|
||||
EyeClosedIcon,
|
||||
EyeOpenIcon,
|
||||
InfoCircleIcon,
|
||||
MarkdownEmbedIcon,
|
||||
SettingsIcon,
|
||||
} from "@webstudio-is/icons";
|
||||
import {
|
||||
$allSelectedInstanceSelectors,
|
||||
@@ -74,13 +93,98 @@ import {
|
||||
} from "@webstudio-is/project-build/runtime";
|
||||
import { emitCommand } from "~/builder/shared/commands";
|
||||
import { useContentEditable } from "~/shared/dom-hooks";
|
||||
import { executeRuntimeMutation } from "~/shared/instance-utils/data";
|
||||
import {
|
||||
executeRuntimeMutation,
|
||||
getDuplicateTemplateNameMessage,
|
||||
} from "~/shared/instance-utils/data";
|
||||
import { isRichTextContent } from "@webstudio-is/project-build/runtime";
|
||||
import {
|
||||
$externalContentRoots,
|
||||
externalContentInstanceNameMessage,
|
||||
isExternalContentInstance,
|
||||
resolveExternalContentOccurrence,
|
||||
findExternalContentRoot,
|
||||
} from "~/shared/external-content-mutations";
|
||||
import {
|
||||
getInstanceLabel,
|
||||
InstanceIcon,
|
||||
} from "~/builder/shared/instance-label";
|
||||
import { InstanceContextMenu } from "~/builder/shared/instance-context-menu";
|
||||
import { TextFileEditor } from "../text-file-editor/text-file-editor";
|
||||
import { useEffectEvent } from "~/shared/hook-utils/effect-event";
|
||||
|
||||
const getMdxContentSource = (selector: InstanceSelector) => {
|
||||
const instances = $instances.get();
|
||||
if (instances.get(selector[0])?.component !== blockBodyComponent) {
|
||||
return;
|
||||
}
|
||||
const blockIndex = selector.findIndex(
|
||||
(id) => instances.get(id)?.component === blockComponent
|
||||
);
|
||||
if (blockIndex === -1) {
|
||||
return;
|
||||
}
|
||||
const blockSelector = selector.slice(blockIndex);
|
||||
const root =
|
||||
Array.from($externalContentRoots.get().values()).find(
|
||||
(root) =>
|
||||
root.contentInstanceId === selector[0] &&
|
||||
root.blockInstanceId === blockSelector[0]
|
||||
) ??
|
||||
findExternalContentRoot(
|
||||
$externalContentRoots.get(),
|
||||
blockSelector[0],
|
||||
JSON.stringify(blockSelector)
|
||||
);
|
||||
const source = getContentBlockSource({
|
||||
blockInstanceId: root?.sourceBlockInstanceId ?? blockSelector[0],
|
||||
props: $props.get().values(),
|
||||
});
|
||||
if (source === undefined) {
|
||||
return;
|
||||
}
|
||||
const value = $propValuesByInstanceSelector
|
||||
.get()
|
||||
.get(getInstanceKey(blockSelector))
|
||||
?.get(contentBlockSourceProp);
|
||||
return {
|
||||
assetId:
|
||||
source.type === "asset"
|
||||
? source.assetId
|
||||
: (root?.assetId ??
|
||||
(typeof value === "string" && value !== "" ? value : undefined)),
|
||||
};
|
||||
};
|
||||
|
||||
const MdxContentMenu = ({ assetId }: { assetId?: string }) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<SmallIconButton
|
||||
aria-label="MDX content settings"
|
||||
icon={<SettingsIcon />}
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
onCloseAutoFocus={(event) => {
|
||||
if (open) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DropdownMenuItem disabled={!assetId} onSelect={() => setOpen(true)}>
|
||||
Open MDX file
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
{open && assetId && (
|
||||
<TextFileEditor assetId={assetId} onOpenChange={setOpen} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
type TreeItemAncestor =
|
||||
| undefined
|
||||
@@ -224,6 +328,7 @@ export const $flatTree = computed(
|
||||
$propValuesByInstanceSelector,
|
||||
$dropTarget,
|
||||
$isContentMode,
|
||||
$externalContentRoots,
|
||||
],
|
||||
(
|
||||
page,
|
||||
@@ -231,7 +336,8 @@ export const $flatTree = computed(
|
||||
expandedItems,
|
||||
propValuesByInstanceSelector,
|
||||
dropTarget,
|
||||
isContentMode
|
||||
isContentMode,
|
||||
externalContentRoots
|
||||
) => {
|
||||
const flatTree: TreeItem[] = [];
|
||||
if (page === undefined) {
|
||||
@@ -246,12 +352,28 @@ export const $flatTree = computed(
|
||||
isLastChild = false,
|
||||
indexWithinChildren = 0
|
||||
) => {
|
||||
const instance = instances.get(instanceId);
|
||||
let instance = instances.get(instanceId);
|
||||
if (instance === undefined) {
|
||||
// log instead of failing navigator tree
|
||||
console.error(`Unknown instance ${instanceId}`);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
isContentMode &&
|
||||
(instance.component === blockComponent ||
|
||||
instance.component === blockBodyComponent)
|
||||
) {
|
||||
const occurrence = resolveExternalContentOccurrence({
|
||||
sourceInstance: instance,
|
||||
sourceSelector: selector,
|
||||
instances,
|
||||
roots: externalContentRoots,
|
||||
});
|
||||
if (occurrence !== undefined) {
|
||||
instance = occurrence.instance;
|
||||
selector = occurrence.selector;
|
||||
}
|
||||
}
|
||||
const propValues = propValuesByInstanceSelector.get(
|
||||
getInstanceKey(selector)
|
||||
);
|
||||
@@ -457,7 +579,7 @@ const ShowToggle = ({
|
||||
{isAnimating && value && (
|
||||
<>
|
||||
<br />
|
||||
<Text css={{ color: theme.colors.foregroundPrimary }}>
|
||||
<Text css={{ color: cssVar("--foreground-accent") }}>
|
||||
Animation is running on canvas.
|
||||
</Text>
|
||||
</>
|
||||
@@ -471,9 +593,9 @@ const ShowToggle = ({
|
||||
css={
|
||||
value && isAnimating
|
||||
? {
|
||||
color: theme.colors.foregroundPrimary,
|
||||
color: cssVar("--foreground-accent"),
|
||||
"&:hover": {
|
||||
color: theme.colors.foregroundPrimary,
|
||||
color: cssVar("--foreground-accent"),
|
||||
filter: "brightness(80%)",
|
||||
},
|
||||
}
|
||||
@@ -492,54 +614,95 @@ const EditableTreeNodeLabel = styled("div", {
|
||||
variants: {
|
||||
isEditing: {
|
||||
true: {
|
||||
background: theme.colors.backgroundControls,
|
||||
background: cssVar("--background-secondary"),
|
||||
padding: theme.spacing[3],
|
||||
borderRadius: theme.spacing[3],
|
||||
color: theme.colors.foregroundMain,
|
||||
color: cssVar("--foreground-primary"),
|
||||
outline: "none",
|
||||
cursor: "auto",
|
||||
textOverflow: "clip",
|
||||
userSelect: "text",
|
||||
},
|
||||
},
|
||||
hasError: {
|
||||
true: {
|
||||
outline: `1px solid ${cssVar("--border-negative")}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const TreeNodeContent = ({
|
||||
instance,
|
||||
mdx = false,
|
||||
isEditing,
|
||||
isNameEditable,
|
||||
onIsEditingChange,
|
||||
}: {
|
||||
instance: Instance;
|
||||
mdx?: boolean;
|
||||
isEditing: boolean;
|
||||
isNameEditable: boolean;
|
||||
onIsEditingChange: (isEditing: boolean) => void;
|
||||
}) => {
|
||||
const editableRef = useRef<HTMLDivElement | null>(null);
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
const label = getInstanceLabel(instance);
|
||||
const label = mdx ? "MDX content" : getInstanceLabel(instance);
|
||||
const { ref, handlers } = useContentEditable({
|
||||
value: label,
|
||||
isEditable: true,
|
||||
isEditing,
|
||||
isEditable: isNameEditable,
|
||||
isEditing: isNameEditable && isEditing,
|
||||
onChangeValue: (value: string) => {
|
||||
executeRuntimeMutation({
|
||||
id: "instances.setLabel",
|
||||
input: { instanceId: instance.id, label: value },
|
||||
});
|
||||
editableRef.current?.closest("button")?.focus();
|
||||
if (isExternalContentInstance($externalContentRoots.get(), instance.id)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
executeRuntimeMutation({
|
||||
id: "instances.setLabel",
|
||||
input: { instanceId: instance.id, label: value },
|
||||
});
|
||||
setError(undefined);
|
||||
editableRef.current?.closest("button")?.focus();
|
||||
} catch (error) {
|
||||
const message = getDuplicateTemplateNameMessage(error);
|
||||
if (message === undefined) {
|
||||
throw error;
|
||||
}
|
||||
setError(message);
|
||||
onIsEditingChange(true);
|
||||
}
|
||||
},
|
||||
onChangeEditing: onIsEditingChange,
|
||||
});
|
||||
|
||||
return (
|
||||
<TreeNodeLabel prefix={<InstanceIcon instance={instance} />}>
|
||||
<EditableTreeNodeLabel
|
||||
ref={mergeRefs(editableRef, ref)}
|
||||
{...handlers}
|
||||
isEditing={isEditing}
|
||||
<TreeNodeLabel
|
||||
prefix={
|
||||
mdx ? <MarkdownEmbedIcon /> : <InstanceIcon instance={instance} />
|
||||
}
|
||||
>
|
||||
<Tooltip
|
||||
content={
|
||||
mdx
|
||||
? "Content inside this region is saved to the connected MDX file. Other instances in this Content Block are saved in the project."
|
||||
: isNameEditable
|
||||
? error
|
||||
: externalContentInstanceNameMessage
|
||||
}
|
||||
delayDuration={0}
|
||||
>
|
||||
{label}
|
||||
</EditableTreeNodeLabel>
|
||||
<EditableTreeNodeLabel
|
||||
ref={mergeRefs(editableRef, ref)}
|
||||
{...handlers}
|
||||
isEditing={isEditing}
|
||||
hasError={error !== undefined}
|
||||
aria-invalid={error === undefined ? undefined : true}
|
||||
onInput={() => setError(undefined)}
|
||||
>
|
||||
{label}
|
||||
</EditableTreeNodeLabel>
|
||||
</Tooltip>
|
||||
</TreeNodeLabel>
|
||||
);
|
||||
};
|
||||
@@ -701,9 +864,166 @@ const commitNavigatorDrop = ({
|
||||
return true;
|
||||
};
|
||||
|
||||
const NavigatorRow = memo(
|
||||
({
|
||||
item,
|
||||
isSelected,
|
||||
isSelectedDescendant,
|
||||
isHighlighted,
|
||||
isEditing,
|
||||
isNameEditable,
|
||||
show,
|
||||
isAnimating,
|
||||
isMdx,
|
||||
mdxAssetId,
|
||||
onPointerDown,
|
||||
onClick,
|
||||
onFocus,
|
||||
onKeyDown,
|
||||
onKeyUp,
|
||||
}: {
|
||||
item: TreeItem;
|
||||
// Invalidate labels when registered component metadata changes.
|
||||
meta: WsComponentMeta;
|
||||
isSelected: boolean;
|
||||
isSelectedDescendant: boolean;
|
||||
isHighlighted: boolean;
|
||||
isEditing: boolean;
|
||||
isNameEditable: boolean;
|
||||
show: boolean;
|
||||
isAnimating: boolean;
|
||||
isMdx: boolean;
|
||||
mdxAssetId?: string;
|
||||
onPointerDown: (
|
||||
selector: InstanceSelector,
|
||||
event: React.PointerEvent
|
||||
) => void;
|
||||
onClick: (selector: InstanceSelector, event: React.MouseEvent) => void;
|
||||
onFocus: (selector: InstanceSelector, event: React.FocusEvent) => void;
|
||||
onKeyDown: (
|
||||
selector: InstanceSelector,
|
||||
event: React.KeyboardEvent<HTMLButtonElement>
|
||||
) => void;
|
||||
onKeyUp: (event: React.KeyboardEvent<HTMLButtonElement>) => void;
|
||||
}) => {
|
||||
const level = item.visibleAncestors.length - 1;
|
||||
return (
|
||||
<InstanceContextMenu>
|
||||
<TreeNode
|
||||
level={level}
|
||||
isSelected={isSelected}
|
||||
isSelectedDescendant={isSelectedDescendant}
|
||||
isHighlighted={isHighlighted}
|
||||
isExpanded={item.isExpanded}
|
||||
isActionVisible={isAnimating || isMdx}
|
||||
onExpand={(isExpanded, all) => handleExpand(item, isExpanded, all)}
|
||||
nodeProps={{
|
||||
style: {
|
||||
opacity: item.isHidden ? 0.4 : undefined,
|
||||
color: item.isReusable
|
||||
? cssVar("--foreground-accent-secondary")
|
||||
: undefined,
|
||||
},
|
||||
}}
|
||||
buttonProps={{
|
||||
onPointerDown: (event) => onPointerDown(item.selector, event),
|
||||
onMouseEnter: () => {
|
||||
$hoveredInstanceSelector.set(item.selector);
|
||||
$blockChildOutline.set(undefined);
|
||||
},
|
||||
onMouseLeave: () => $hoveredInstanceSelector.set(undefined),
|
||||
onClick: (event) => onClick(item.selector, event),
|
||||
onFocus: (event) => onFocus(item.selector, event),
|
||||
onKeyDown: (event) => {
|
||||
onKeyDown(item.selector, event);
|
||||
if (event.defaultPrevented) {
|
||||
return;
|
||||
}
|
||||
if (event.key === "Enter") {
|
||||
emitCommand("editInstanceText");
|
||||
}
|
||||
},
|
||||
onKeyUp,
|
||||
}}
|
||||
action={
|
||||
isMdx ? (
|
||||
<MdxContentMenu assetId={mdxAssetId} />
|
||||
) : (
|
||||
<ShowToggle
|
||||
instance={item.instance}
|
||||
value={show}
|
||||
isAnimating={isAnimating}
|
||||
/>
|
||||
)
|
||||
}
|
||||
>
|
||||
<TreeNodeContent
|
||||
instance={item.instance}
|
||||
mdx={isMdx}
|
||||
isNameEditable={isNameEditable}
|
||||
isEditing={isEditing}
|
||||
onIsEditingChange={(isEditing) => {
|
||||
$editingItemSelector.set(
|
||||
isEditing === true ? item.selector : undefined
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</TreeNode>
|
||||
</InstanceContextMenu>
|
||||
);
|
||||
},
|
||||
// Position changes belong to the sortable wrapper. Row handlers only need
|
||||
// the instance and selector, so unchanged controls can keep their render.
|
||||
({ item: previous, ...previousProps }, { item: next, ...nextProps }) =>
|
||||
shallowEqual(previousProps, nextProps) &&
|
||||
previous.instance === next.instance &&
|
||||
areInstanceSelectorsEqual(previous.selector, next.selector) &&
|
||||
previous.visibleAncestors.length === next.visibleAncestors.length &&
|
||||
previous.isExpanded === next.isExpanded &&
|
||||
previous.isHidden === next.isHidden &&
|
||||
previous.isReusable === next.isReusable
|
||||
);
|
||||
|
||||
const NavigatorSortableRow = memo(
|
||||
({ item, ...props }: ComponentProps<typeof NavigatorRow>) => (
|
||||
<TreeSortableItem
|
||||
level={item.visibleAncestors.length - 1}
|
||||
isExpanded={item.isExpanded}
|
||||
isLastChild={item.isLastChild}
|
||||
data={item}
|
||||
canDrag={() => canDrag(item.instance, item.selector)}
|
||||
dropTarget={item.dropTarget}
|
||||
onDropTargetChange={(dropTarget, draggingItem) => {
|
||||
$dragAndDropState.set({
|
||||
...$dragAndDropState.get(),
|
||||
...getNavigatorDragState({
|
||||
item,
|
||||
dropTarget,
|
||||
draggingItem,
|
||||
canDropTarget: canDrop,
|
||||
}),
|
||||
});
|
||||
}}
|
||||
onDrop={(data) => {
|
||||
commitNavigatorDrop({
|
||||
item: data,
|
||||
dropTarget: $dragAndDropState.get().dropTarget,
|
||||
reparent: reparentInstance,
|
||||
});
|
||||
$dragAndDropState.set({ isDragging: false });
|
||||
}}
|
||||
onExpand={(isExpanded) => handleExpand(item, isExpanded, false)}
|
||||
>
|
||||
<NavigatorRow item={item} {...props} />
|
||||
</TreeSortableItem>
|
||||
)
|
||||
);
|
||||
|
||||
export const NavigatorTree = () => {
|
||||
const isContentMode = useStore($isContentMode);
|
||||
const selectedPage = useStore($selectedPage);
|
||||
const flatTree = useStore($flatTree);
|
||||
const externalContentRoots = useStore($externalContentRoots);
|
||||
const selectedInstanceSelectors = useStore($allSelectedInstanceSelectors);
|
||||
const selectedInstanceSelector = useStore($selectedInstanceSelector);
|
||||
const selectedKeys = useMemo(
|
||||
@@ -741,8 +1061,12 @@ export const NavigatorTree = () => {
|
||||
if (selectedInstanceSelector) {
|
||||
const newExpandedItems = new Set($expandedItems.get());
|
||||
let expanded = 0;
|
||||
// do not expand the selected instance itself, start with parent
|
||||
for (let index = 1; index < selectedInstanceSelector.length; index += 1) {
|
||||
// Expand ancestors except the root, which is always expanded.
|
||||
for (
|
||||
let index = 1;
|
||||
index < selectedInstanceSelector.length - 1;
|
||||
index += 1
|
||||
) {
|
||||
const key = getSelectorKey(selectedInstanceSelector.slice(index));
|
||||
if (newExpandedItems.has(key) === false) {
|
||||
newExpandedItems.add(key);
|
||||
@@ -782,21 +1106,23 @@ export const NavigatorTree = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const selectInstanceOnFocus = (
|
||||
instanceSelector: undefined | Instance["id"][],
|
||||
event: React.MouseEvent | React.FocusEvent
|
||||
) => {
|
||||
if (suppressFocusSelectionRef.current) {
|
||||
return;
|
||||
const selectInstanceOnFocus = useEffectEvent(
|
||||
(
|
||||
instanceSelector: undefined | Instance["id"][],
|
||||
event: React.MouseEvent | React.FocusEvent
|
||||
) => {
|
||||
if (suppressFocusSelectionRef.current) {
|
||||
return;
|
||||
}
|
||||
if (skipFocusSelectionCountRef.current > 0) {
|
||||
skipFocusSelectionCountRef.current -= 1;
|
||||
return;
|
||||
}
|
||||
clearTextSelection(event);
|
||||
selectInstance(instanceSelector);
|
||||
rangeAnchorSelectorRef.current = instanceSelector;
|
||||
}
|
||||
if (skipFocusSelectionCountRef.current > 0) {
|
||||
skipFocusSelectionCountRef.current -= 1;
|
||||
return;
|
||||
}
|
||||
clearTextSelection(event);
|
||||
selectInstance(instanceSelector);
|
||||
rangeAnchorSelectorRef.current = instanceSelector;
|
||||
};
|
||||
);
|
||||
|
||||
const selectNavigatorInstance = (
|
||||
instanceSelector: InstanceSelector,
|
||||
@@ -816,145 +1142,162 @@ export const NavigatorTree = () => {
|
||||
rangeAnchorSelectorRef.current = nextSelection.anchorSelector;
|
||||
};
|
||||
|
||||
const handlePointerDown = (
|
||||
instanceSelector: InstanceSelector,
|
||||
event: React.PointerEvent
|
||||
) => {
|
||||
skipFocusSelectionCountRef.current =
|
||||
getFocusSelectionSkipCountAfterPointerDown(event);
|
||||
if (shouldSelectOnPointerDown(event)) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
selectNavigatorInstance(instanceSelector, event);
|
||||
const handlePointerDown = useEffectEvent(
|
||||
(instanceSelector: InstanceSelector, event: React.PointerEvent) => {
|
||||
skipFocusSelectionCountRef.current =
|
||||
getFocusSelectionSkipCountAfterPointerDown(event);
|
||||
if (shouldSelectOnPointerDown(event)) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
selectNavigatorInstance(instanceSelector, event);
|
||||
skipNextClickSelectionRef.current = true;
|
||||
return;
|
||||
}
|
||||
if (event.button !== 2) {
|
||||
return;
|
||||
}
|
||||
skipNextClickSelectionRef.current = true;
|
||||
return;
|
||||
if (selectedKeys.has(getSelectorKey(instanceSelector))) {
|
||||
return;
|
||||
}
|
||||
clearTextSelection(event);
|
||||
suppressFocusSelectionRef.current = false;
|
||||
selectInstances(
|
||||
getContextMenuSelectedInstanceSelectors({
|
||||
selectedSelectors: selectedInstanceSelectors,
|
||||
clickedSelector: instanceSelector,
|
||||
})
|
||||
);
|
||||
rangeAnchorSelectorRef.current = instanceSelector;
|
||||
}
|
||||
if (event.button !== 2) {
|
||||
return;
|
||||
}
|
||||
skipNextClickSelectionRef.current = true;
|
||||
if (selectedKeys.has(getSelectorKey(instanceSelector))) {
|
||||
return;
|
||||
}
|
||||
clearTextSelection(event);
|
||||
suppressFocusSelectionRef.current = false;
|
||||
selectInstances(
|
||||
getContextMenuSelectedInstanceSelectors({
|
||||
selectedSelectors: selectedInstanceSelectors,
|
||||
clickedSelector: instanceSelector,
|
||||
})
|
||||
);
|
||||
rangeAnchorSelectorRef.current = instanceSelector;
|
||||
};
|
||||
);
|
||||
|
||||
const handleClick = (
|
||||
instanceSelector: InstanceSelector,
|
||||
event: React.MouseEvent
|
||||
) => {
|
||||
if (skipNextClickSelectionRef.current) {
|
||||
skipNextClickSelectionRef.current = false;
|
||||
return;
|
||||
const handleClick = useEffectEvent(
|
||||
(instanceSelector: InstanceSelector, event: React.MouseEvent) => {
|
||||
if (skipNextClickSelectionRef.current) {
|
||||
skipNextClickSelectionRef.current = false;
|
||||
return;
|
||||
}
|
||||
selectNavigatorInstance(instanceSelector, event);
|
||||
}
|
||||
selectNavigatorInstance(instanceSelector, event);
|
||||
};
|
||||
);
|
||||
|
||||
const handleKeyDown = (
|
||||
instanceSelector: InstanceSelector,
|
||||
event: React.KeyboardEvent<HTMLButtonElement>
|
||||
) => {
|
||||
if (
|
||||
shouldClearNavigatorMultiSelectionOnEscape({
|
||||
key: event.key,
|
||||
selectedSelectors: selectedInstanceSelectors,
|
||||
})
|
||||
) {
|
||||
const handleKeyDown = useEffectEvent(
|
||||
(
|
||||
instanceSelector: InstanceSelector,
|
||||
event: React.KeyboardEvent<HTMLButtonElement>
|
||||
) => {
|
||||
if (
|
||||
shouldClearNavigatorMultiSelectionOnEscape({
|
||||
key: event.key,
|
||||
selectedSelectors: selectedInstanceSelectors,
|
||||
})
|
||||
) {
|
||||
suppressCommandsForEvent(event.nativeEvent);
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
suppressFocusSelectionRef.current = false;
|
||||
clearInstanceSelection();
|
||||
rangeAnchorSelectorRef.current = undefined;
|
||||
return;
|
||||
}
|
||||
|
||||
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "a") {
|
||||
suppressCommandsForEvent(event.nativeEvent);
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
suppressFocusSelectionRef.current = false;
|
||||
const nextSelection = getNavigatorSiblingSelectionUpdate({
|
||||
focusedSelector: instanceSelector,
|
||||
flatSelectors,
|
||||
});
|
||||
if (nextSelection === undefined) {
|
||||
return;
|
||||
}
|
||||
selectInstances(nextSelection.selectedSelectors);
|
||||
rangeAnchorSelectorRef.current = nextSelection.anchorSelector;
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.shiftKey === false) {
|
||||
suppressFocusSelectionRef.current = false;
|
||||
return;
|
||||
}
|
||||
const direction =
|
||||
event.key === "ArrowUp"
|
||||
? "previous"
|
||||
: event.key === "ArrowDown"
|
||||
? "next"
|
||||
: undefined;
|
||||
if (direction === undefined) {
|
||||
return;
|
||||
}
|
||||
suppressCommandsForEvent(event.nativeEvent);
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
suppressFocusSelectionRef.current = false;
|
||||
clearInstanceSelection();
|
||||
rangeAnchorSelectorRef.current = undefined;
|
||||
return;
|
||||
}
|
||||
|
||||
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "a") {
|
||||
suppressCommandsForEvent(event.nativeEvent);
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
suppressFocusSelectionRef.current = false;
|
||||
const nextSelection = getNavigatorSiblingSelectionUpdate({
|
||||
const nextSelection = getNavigatorKeyboardSelectionUpdate({
|
||||
selectedSelectors: selectedInstanceSelectors,
|
||||
focusedSelector: instanceSelector,
|
||||
flatSelectors,
|
||||
anchorSelector: rangeAnchorSelectorRef.current,
|
||||
direction,
|
||||
});
|
||||
if (nextSelection === undefined) {
|
||||
return;
|
||||
}
|
||||
suppressFocusSelectionRef.current = true;
|
||||
selectInstances(nextSelection.selectedSelectors);
|
||||
rangeAnchorSelectorRef.current = nextSelection.anchorSelector;
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.shiftKey === false) {
|
||||
suppressFocusSelectionRef.current = false;
|
||||
return;
|
||||
const treeButtons = Array.from(
|
||||
event.currentTarget
|
||||
.closest("[data-navigator-tree]")
|
||||
?.querySelectorAll<HTMLButtonElement>("[data-tree-button]") ?? []
|
||||
);
|
||||
const buttonIndex = treeButtons.indexOf(event.currentTarget);
|
||||
const nextFocusedButton =
|
||||
direction === "previous" ? buttonIndex - 1 : buttonIndex + 1;
|
||||
if (treeButtons[nextFocusedButton] !== undefined) {
|
||||
treeButtons[nextFocusedButton]?.focus({ preventScroll: true });
|
||||
}
|
||||
}
|
||||
const direction =
|
||||
event.key === "ArrowUp"
|
||||
? "previous"
|
||||
: event.key === "ArrowDown"
|
||||
? "next"
|
||||
: undefined;
|
||||
if (direction === undefined) {
|
||||
return;
|
||||
}
|
||||
suppressCommandsForEvent(event.nativeEvent);
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const nextSelection = getNavigatorKeyboardSelectionUpdate({
|
||||
selectedSelectors: selectedInstanceSelectors,
|
||||
focusedSelector: instanceSelector,
|
||||
flatSelectors,
|
||||
anchorSelector: rangeAnchorSelectorRef.current,
|
||||
direction,
|
||||
});
|
||||
if (nextSelection === undefined) {
|
||||
return;
|
||||
}
|
||||
suppressFocusSelectionRef.current = true;
|
||||
selectInstances(nextSelection.selectedSelectors);
|
||||
rangeAnchorSelectorRef.current = nextSelection.anchorSelector;
|
||||
);
|
||||
|
||||
const treeButtons = Array.from(
|
||||
event.currentTarget
|
||||
.closest("[data-navigator-tree]")
|
||||
?.querySelectorAll<HTMLButtonElement>("[data-tree-button]") ?? []
|
||||
);
|
||||
const buttonIndex = treeButtons.indexOf(event.currentTarget);
|
||||
const nextFocusedButton =
|
||||
direction === "previous" ? buttonIndex - 1 : buttonIndex + 1;
|
||||
if (treeButtons[nextFocusedButton] !== undefined) {
|
||||
treeButtons[nextFocusedButton]?.focus({ preventScroll: true });
|
||||
const handleKeyUp = useEffectEvent(
|
||||
(event: React.KeyboardEvent<HTMLButtonElement>) => {
|
||||
if (event.key === "Shift" || event.shiftKey === false) {
|
||||
suppressFocusSelectionRef.current = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyUp = (event: React.KeyboardEvent<HTMLButtonElement>) => {
|
||||
if (event.key === "Shift" || event.shiftKey === false) {
|
||||
suppressFocusSelectionRef.current = false;
|
||||
}
|
||||
};
|
||||
);
|
||||
|
||||
// oxlint-disable react-hooks/rules-of-hooks -- our useEffectEvent supplies stable callbacks with current state
|
||||
return (
|
||||
<ScrollArea
|
||||
direction="both"
|
||||
<ScrollAreaNative
|
||||
css={{
|
||||
width: "100%",
|
||||
overflow: "hidden",
|
||||
flexBasis: 0,
|
||||
flexGrow: 1,
|
||||
minHeight: 0,
|
||||
"& [data-tree-sortable-item]:not([data-has-drop-target])": {
|
||||
contentVisibility: "auto",
|
||||
containIntrinsicSize: `auto ${theme.sizes.controlHeight}`,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<TreeRoot>
|
||||
<Box data-navigator-tree>
|
||||
<Box data-navigator-tree css={{ minWidth: "max-content" }}>
|
||||
{isContentMode &&
|
||||
selectedPage !== undefined &&
|
||||
flatTree.length === 0 && (
|
||||
<PanelBanner variant="warning" role="status">
|
||||
<Text>
|
||||
This page has no editable content. To make areas editable in
|
||||
content mode, wrap them in a Content block component in design
|
||||
mode.
|
||||
</Text>
|
||||
</PanelBanner>
|
||||
)}
|
||||
{rootMeta && isContentMode === false && (
|
||||
<TreeNode
|
||||
level={0}
|
||||
@@ -969,8 +1312,8 @@ export const NavigatorTree = () => {
|
||||
selectInstanceOnFocus([ROOT_INSTANCE_ID], event),
|
||||
}}
|
||||
action={
|
||||
<Tooltip
|
||||
variant="wrapped"
|
||||
<InfoTooltip
|
||||
label="About Global root variables"
|
||||
side="bottom"
|
||||
disableHoverableContent={true}
|
||||
content={
|
||||
@@ -979,9 +1322,7 @@ export const NavigatorTree = () => {
|
||||
instance on every page.
|
||||
</Text>
|
||||
}
|
||||
>
|
||||
<InfoCircleIcon />
|
||||
</Tooltip>
|
||||
/>
|
||||
}
|
||||
>
|
||||
<TreeNodeLabel
|
||||
@@ -995,7 +1336,6 @@ export const NavigatorTree = () => {
|
||||
)}
|
||||
|
||||
{flatTree.map((item) => {
|
||||
const level = item.visibleAncestors.length - 1;
|
||||
const key = getSelectorKey(item.selector);
|
||||
const propValues = propValuesByInstanceSelectorWithMemoryProps.get(
|
||||
getInstanceKey(item.selector)
|
||||
@@ -1023,118 +1363,55 @@ export const NavigatorTree = () => {
|
||||
const isAnimating = isAnimationSelected || isAnimationPinned;
|
||||
|
||||
const meta = metas.get(item.instance.component);
|
||||
const mdxSource = getMdxContentSource(item.selector);
|
||||
|
||||
if (meta === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<TreeSortableItem
|
||||
<NavigatorSortableRow
|
||||
key={key}
|
||||
level={level}
|
||||
isExpanded={item.isExpanded}
|
||||
isLastChild={item.isLastChild}
|
||||
data={item}
|
||||
canDrag={() => canDrag(item.instance, item.selector)}
|
||||
dropTarget={item.dropTarget}
|
||||
onDropTargetChange={(dropTarget, draggingItem) => {
|
||||
$dragAndDropState.set({
|
||||
...$dragAndDropState.get(),
|
||||
...getNavigatorDragState({
|
||||
item,
|
||||
dropTarget,
|
||||
draggingItem,
|
||||
canDropTarget: canDrop,
|
||||
}),
|
||||
});
|
||||
}}
|
||||
onDrop={(data) => {
|
||||
const builderDropTarget = $dragAndDropState.get().dropTarget;
|
||||
commitNavigatorDrop({
|
||||
item: data,
|
||||
dropTarget: builderDropTarget,
|
||||
reparent: reparentInstance,
|
||||
});
|
||||
$dragAndDropState.set({ isDragging: false });
|
||||
}}
|
||||
onExpand={(isExpanded) => handleExpand(item, isExpanded, false)}
|
||||
>
|
||||
<InstanceContextMenu>
|
||||
<TreeNode
|
||||
level={level}
|
||||
isSelected={selectedKeys.has(getSelectorKey(item.selector))}
|
||||
isSelectedDescendant={isSelectedDescendantItem}
|
||||
isHighlighted={hoveredKey === key || dropTargetKey === key}
|
||||
isExpanded={item.isExpanded}
|
||||
isActionVisible={isAnimating}
|
||||
onExpand={(isExpanded, all) =>
|
||||
handleExpand(item, isExpanded, all)
|
||||
}
|
||||
nodeProps={{
|
||||
style: {
|
||||
opacity: item.isHidden ? 0.4 : undefined,
|
||||
color: item.isReusable
|
||||
? rawTheme.colors.foregroundReusable
|
||||
: undefined,
|
||||
},
|
||||
}}
|
||||
buttonProps={{
|
||||
onPointerDown: (event) =>
|
||||
handlePointerDown(item.selector, event),
|
||||
onMouseEnter: () => {
|
||||
$hoveredInstanceSelector.set(item.selector);
|
||||
$blockChildOutline.set(undefined);
|
||||
},
|
||||
onMouseLeave: () =>
|
||||
$hoveredInstanceSelector.set(undefined),
|
||||
onClick: (event) => handleClick(item.selector, event),
|
||||
onFocus: (event) =>
|
||||
selectInstanceOnFocus(item.selector, event),
|
||||
onKeyDown: (event) => {
|
||||
handleKeyDown(item.selector, event);
|
||||
if (event.defaultPrevented) {
|
||||
return;
|
||||
}
|
||||
if (event.key === "Enter") {
|
||||
emitCommand("editInstanceText");
|
||||
}
|
||||
},
|
||||
onKeyUp: handleKeyUp,
|
||||
}}
|
||||
action={
|
||||
<ShowToggle
|
||||
instance={item.instance}
|
||||
value={show}
|
||||
isAnimating={isAnimating}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<TreeNodeContent
|
||||
instance={item.instance}
|
||||
isEditing={areInstanceSelectorsEqual(
|
||||
item.selector,
|
||||
editingItemSelector
|
||||
)}
|
||||
onIsEditingChange={(isEditing) => {
|
||||
$editingItemSelector.set(
|
||||
isEditing === true ? item.selector : undefined
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</TreeNode>
|
||||
</InstanceContextMenu>
|
||||
</TreeSortableItem>
|
||||
item={item}
|
||||
meta={meta}
|
||||
isSelected={selectedKeys.has(key)}
|
||||
isSelectedDescendant={isSelectedDescendantItem}
|
||||
isHighlighted={hoveredKey === key || dropTargetKey === key}
|
||||
isEditing={areInstanceSelectorsEqual(
|
||||
item.selector,
|
||||
editingItemSelector
|
||||
)}
|
||||
isNameEditable={
|
||||
mdxSource === undefined &&
|
||||
isExternalContentInstance(
|
||||
externalContentRoots,
|
||||
item.instance.id
|
||||
) === false
|
||||
}
|
||||
show={show}
|
||||
isAnimating={isAnimating}
|
||||
isMdx={mdxSource !== undefined}
|
||||
mdxAssetId={mdxSource?.assetId}
|
||||
onPointerDown={handlePointerDown}
|
||||
onClick={handleClick}
|
||||
onFocus={selectInstanceOnFocus}
|
||||
onKeyDown={handleKeyDown}
|
||||
onKeyUp={handleKeyUp}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
</TreeRoot>
|
||||
{/* space in the end of scroll area */}
|
||||
<Box css={{ height: theme.spacing[9] }}></Box>
|
||||
</ScrollArea>
|
||||
</ScrollAreaNative>
|
||||
);
|
||||
// oxlint-enable react-hooks/rules-of-hooks
|
||||
};
|
||||
|
||||
export const __testing__ = {
|
||||
MdxContentMenu,
|
||||
getMdxContentSource,
|
||||
commitNavigatorDrop,
|
||||
getFocusSelectionSkipCountAfterPointerDown,
|
||||
getBuilderDropTarget,
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
import { Flex, PanelTitle, Separator } from "@webstudio-is/design-system";
|
||||
import { CssPreview } from "./css-preview";
|
||||
import { NavigatorTree } from "./navigator-tree";
|
||||
import { $isDesignMode } from "~/shared/nano-states";
|
||||
import { useStore } from "@nanostores/react";
|
||||
import { InstanceContextMenu } from "~/builder/shared/instance-context-menu";
|
||||
|
||||
export const NavigatorPanel = (_props: { onClose: () => void }) => {
|
||||
const isDesignMode = useStore($isDesignMode);
|
||||
return (
|
||||
<>
|
||||
<PanelTitle>Navigator</PanelTitle>
|
||||
@@ -16,8 +12,6 @@ export const NavigatorPanel = (_props: { onClose: () => void }) => {
|
||||
<NavigatorTree />
|
||||
</Flex>
|
||||
</InstanceContextMenu>
|
||||
<Separator />
|
||||
{isDesignMode && <CssPreview />}
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
PanelContent,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
@@ -7,7 +8,6 @@ import {
|
||||
Flex,
|
||||
Text,
|
||||
Button,
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import type { Page, Folder, PageTemplate } from "@webstudio-is/sdk";
|
||||
import { getPageDisplayName } from "./page-utils";
|
||||
@@ -34,13 +34,13 @@ export const DeletePageConfirmationDialog = ({
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogTitle>Delete page</DialogTitle>
|
||||
<Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>
|
||||
<PanelContent as={Flex} gap="3" direction="column">
|
||||
<Text>{`Are you sure you want to delete "${getPageDisplayName(page)}"?`}</Text>
|
||||
<Text>
|
||||
You can undo it even if you delete the page as long as you don't
|
||||
reload.
|
||||
</Text>
|
||||
</Flex>
|
||||
</PanelContent>
|
||||
<DialogActions>
|
||||
<Button
|
||||
autoFocus
|
||||
@@ -82,9 +82,9 @@ export const DeleteFolderConfirmationDialog = ({
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogTitle>Delete confirmation</DialogTitle>
|
||||
<Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>
|
||||
<PanelContent as={Flex} gap="3" direction="column">
|
||||
<Text>{`Delete folder "${folder.name}" including all of its pages?`}</Text>
|
||||
</Flex>
|
||||
</PanelContent>
|
||||
<DialogActions>
|
||||
<Button
|
||||
autoFocus
|
||||
@@ -126,13 +126,13 @@ export const DeleteTemplateConfirmationDialog = ({
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogTitle>Delete template</DialogTitle>
|
||||
<Flex gap="3" direction="column" css={{ padding: theme.panel.padding }}>
|
||||
<PanelContent as={Flex} gap="3" direction="column">
|
||||
<Text>{`Are you sure you want to delete the template "${template.name}"?`}</Text>
|
||||
<Text>
|
||||
You can undo it even if you delete the template as long as you don't
|
||||
reload.
|
||||
</Text>
|
||||
</Flex>
|
||||
</PanelContent>
|
||||
<DialogActions>
|
||||
<Button
|
||||
autoFocus
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
Label,
|
||||
SmallIconButton,
|
||||
Text,
|
||||
cssVar,
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { TrashIcon, PlusIcon } from "@webstudio-is/icons";
|
||||
@@ -15,6 +16,7 @@ import { isLiteralExpression } from "@webstudio-is/expression";
|
||||
import { computeExpression } from "@webstudio-is/project-build/runtime";
|
||||
import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
|
||||
import { $pageRootScope } from "./page-utils";
|
||||
import { useAsyncValue } from "~/shared/use-async-value";
|
||||
|
||||
type Meta = {
|
||||
property: string;
|
||||
@@ -40,7 +42,11 @@ const MetadataItem = (props: {
|
||||
const contentId = useId();
|
||||
const { variableValues, scope, aliases } = useStore($pageRootScope);
|
||||
|
||||
const content = computeExpression(props.content, variableValues);
|
||||
const content = useAsyncValue(
|
||||
() => computeExpression(props.content, variableValues),
|
||||
[props.content, variableValues],
|
||||
undefined
|
||||
);
|
||||
|
||||
return (
|
||||
<Grid
|
||||
@@ -105,7 +111,7 @@ const MetadataItem = (props: {
|
||||
gridArea: "button",
|
||||
justifyItems: "center",
|
||||
gap: "2px",
|
||||
color: theme.colors.foregroundIconSecondary,
|
||||
color: cssVar("--foreground-secondary"),
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
@@ -182,7 +188,6 @@ export const CustomMetadata = (props: CustomMetadataProps) => {
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
color="neutral"
|
||||
css={{
|
||||
justifySelf: "center",
|
||||
}}
|
||||
@@ -202,3 +207,5 @@ export const CustomMetadata = (props: CustomMetadataProps) => {
|
||||
</Grid>
|
||||
);
|
||||
};
|
||||
|
||||
undefined;
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useStore } from "@nanostores/react";
|
||||
import {
|
||||
PanelContent,
|
||||
Button,
|
||||
DialogClose,
|
||||
DialogTitle,
|
||||
@@ -7,15 +8,15 @@ import {
|
||||
Grid,
|
||||
InputErrorsTooltip,
|
||||
InputField,
|
||||
InfoTooltip,
|
||||
Label,
|
||||
DialogTitleActions,
|
||||
ScrollArea,
|
||||
TitleSuffixSpacer,
|
||||
Tooltip,
|
||||
rawTheme,
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { InfoCircleIcon, TrashIcon } from "@webstudio-is/icons";
|
||||
import { TrashIcon } from "@webstudio-is/icons";
|
||||
import { type Folder, getFolderById } from "@webstudio-is/sdk";
|
||||
import {
|
||||
folderSettingsDefaultValues,
|
||||
@@ -80,7 +81,7 @@ const FormFields = ({
|
||||
return (
|
||||
<Grid css={{ height: "100%" }}>
|
||||
<ScrollArea>
|
||||
<Grid gap={3} css={{ padding: theme.panel.padding }}>
|
||||
<PanelContent as={Grid} gap={3}>
|
||||
<Grid gap={1}>
|
||||
<Label htmlFor={fieldIds.name}>Folder name</Label>
|
||||
<InputErrorsTooltip errors={errors.name}>
|
||||
@@ -104,15 +105,10 @@ const FormFields = ({
|
||||
<Grid gap={1}>
|
||||
<Flex align="center" css={{ gap: theme.spacing[3] }}>
|
||||
<Label htmlFor={fieldIds.slug}>Slug</Label>
|
||||
<Tooltip
|
||||
content={"Slug will be used as part of the path to the page"}
|
||||
variant="wrapped"
|
||||
>
|
||||
<InfoCircleIcon
|
||||
color={rawTheme.colors.foregroundSubtle}
|
||||
tabIndex={0}
|
||||
/>
|
||||
</Tooltip>
|
||||
<InfoTooltip
|
||||
label="About folder slug"
|
||||
content="Slug will be used as part of the path to the page"
|
||||
/>
|
||||
</Flex>
|
||||
<InputErrorsTooltip errors={errors.slug}>
|
||||
<InputField
|
||||
@@ -132,7 +128,7 @@ const FormFields = ({
|
||||
/>
|
||||
</InputErrorsTooltip>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</PanelContent>
|
||||
</ScrollArea>
|
||||
</Grid>
|
||||
);
|
||||
@@ -193,6 +189,7 @@ export const NewFolderSettings = ({
|
||||
)}
|
||||
<TitleSuffixSpacer />
|
||||
<Button
|
||||
color="primary"
|
||||
state={isSubmitting ? "pending" : "auto"}
|
||||
onClick={handleSubmit}
|
||||
tabIndex={2}
|
||||
|
||||
@@ -19,7 +19,9 @@ export const Form = () => (
|
||||
<Flex direction="column" gap="3" css={{ padding: 16 }}>
|
||||
<Text variant="labels">Page name</Text>
|
||||
<InputField defaultValue="Home" />
|
||||
<Button type="submit">Save</Button>
|
||||
<Button color="primary" type="submit">
|
||||
Save
|
||||
</Button>
|
||||
</Flex>
|
||||
</FormComponent>
|
||||
</Flex>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import {
|
||||
PanelContent,
|
||||
cssVar,
|
||||
IconButton,
|
||||
Text,
|
||||
Grid,
|
||||
@@ -35,16 +37,17 @@ export const ImageInfo = ({
|
||||
justify={"start"}
|
||||
css={{
|
||||
borderRadius: theme.borderRadius[4],
|
||||
border: `1px solid ${theme.colors.borderMain}`,
|
||||
backgroundColor: theme.colors.white,
|
||||
border: `1px solid ${cssVar("--border-default")}`,
|
||||
backgroundColor: cssVar("--background-primary"),
|
||||
padding: theme.spacing[4],
|
||||
justifySelf: "start",
|
||||
pr: theme.spacing[5],
|
||||
}}
|
||||
>
|
||||
<Grid
|
||||
<PanelContent
|
||||
as={Grid}
|
||||
columns={1}
|
||||
css={{ padding: theme.panel.padding, width: theme.spacing[34] }}
|
||||
css={{ width: theme.spacing[34] }}
|
||||
gap={2}
|
||||
align={"center"}
|
||||
>
|
||||
@@ -72,7 +75,7 @@ export const ImageInfo = ({
|
||||
</Text>
|
||||
</Flex>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</PanelContent>
|
||||
</Grid>
|
||||
<IconButton onClick={onDelete} disabled={disabled}>
|
||||
<TrashIcon />
|
||||
|
||||
@@ -2,6 +2,7 @@ import { $pages } from "~/shared/sync/data-stores";
|
||||
import { PageSettings as PageSettingsComponent } from "./page-settings/page-settings";
|
||||
import {
|
||||
Grid,
|
||||
cssVar,
|
||||
theme,
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -91,9 +92,9 @@ export const PageSettings = () => {
|
||||
css={{
|
||||
width: theme.spacing[35],
|
||||
margin: "auto",
|
||||
border: `1px solid ${theme.colors.borderMain}`,
|
||||
border: `1px solid ${cssVar("--border-default")}`,
|
||||
boxShadow: theme.shadows.menuDropShadow,
|
||||
background: theme.colors.backgroundPanel,
|
||||
background: cssVar("--background-primary"),
|
||||
borderRadius: theme.borderRadius[4],
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useState, useEffect, type JSX } from "react";
|
||||
import { useState, useEffect, useMemo, useRef, type JSX } from "react";
|
||||
import { useStore } from "@nanostores/react";
|
||||
import {
|
||||
type Page,
|
||||
type Pages,
|
||||
findPageByIdOrPath,
|
||||
getPageDraftabilityError,
|
||||
isPageDraft,
|
||||
@@ -295,6 +296,34 @@ export const FormFields = ({
|
||||
);
|
||||
};
|
||||
|
||||
export const usePageSettingsErrors = ({
|
||||
pages,
|
||||
pageId,
|
||||
values,
|
||||
variableValues,
|
||||
}: {
|
||||
pages: Pages | undefined;
|
||||
pageId: Page["id"] | undefined;
|
||||
values: PageSettingsValues;
|
||||
variableValues: Map<string, unknown>;
|
||||
}) => {
|
||||
const [errors, setErrors] = useState<PageSettingsErrors>({});
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
validatePageSettings({ pages, pageId, values, variableValues }).then(
|
||||
(nextErrors) => {
|
||||
if (active) {
|
||||
setErrors(nextErrors);
|
||||
}
|
||||
}
|
||||
);
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [pageId, pages, values, variableValues]);
|
||||
return errors;
|
||||
};
|
||||
|
||||
export const NewPageSettings = ({
|
||||
onSuccess,
|
||||
}: {
|
||||
@@ -310,7 +339,7 @@ export const NewPageSettings = ({
|
||||
});
|
||||
const [isSubmitAttempted, setIsSubmitAttempted] = useState(false);
|
||||
const { variableValues } = useStore($pageRootScope);
|
||||
const errors = validatePageSettings({
|
||||
const errors = usePageSettingsErrors({
|
||||
pages,
|
||||
pageId: undefined,
|
||||
values,
|
||||
@@ -372,6 +401,7 @@ const NewPageSettingsView = ({
|
||||
<DialogTitleActions>
|
||||
<TitleSuffixSpacer />
|
||||
<Button
|
||||
color="primary"
|
||||
state={isSubmitting ? "pending" : "auto"}
|
||||
onClick={onSubmit}
|
||||
tabIndex={2}
|
||||
@@ -438,7 +468,7 @@ export const PageSettings = ({
|
||||
}) === undefined;
|
||||
|
||||
const [refreshDebounce, setRefreshDebounce] = useState(0);
|
||||
let errors: PageSettingsErrors = {};
|
||||
const errorsRef = useRef<PageSettingsErrors>({});
|
||||
const {
|
||||
value: unsavedValues,
|
||||
set: setUnsavedValues,
|
||||
@@ -450,7 +480,7 @@ export const PageSettings = ({
|
||||
},
|
||||
{
|
||||
resetOnSave: true,
|
||||
shouldSave: () => Object.keys(errors).length === 0,
|
||||
shouldSave: () => Object.keys(errorsRef.current).length === 0,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -471,15 +501,23 @@ export const PageSettings = ({
|
||||
}
|
||||
};
|
||||
|
||||
const values: PageSettingsValues = {
|
||||
...(page
|
||||
? getPageSettingsValues({ page, pages, isHomePage })
|
||||
: pageSettingsDefaultValues),
|
||||
...unsavedValues,
|
||||
};
|
||||
const values = useMemo<PageSettingsValues>(
|
||||
() => ({
|
||||
...(page
|
||||
? getPageSettingsValues({ page, pages, isHomePage })
|
||||
: pageSettingsDefaultValues),
|
||||
...unsavedValues,
|
||||
}),
|
||||
[page, pages, isHomePage, unsavedValues]
|
||||
);
|
||||
|
||||
const { variableValues } = useStore($pageRootScope);
|
||||
errors = validatePageSettings({ pages, pageId, values, variableValues });
|
||||
const errors = usePageSettingsErrors({
|
||||
pages,
|
||||
pageId,
|
||||
values,
|
||||
variableValues,
|
||||
});
|
||||
if (unsavedValues.path !== undefined) {
|
||||
addContentModePathError({
|
||||
errors,
|
||||
@@ -487,6 +525,7 @@ export const PageSettings = ({
|
||||
path: unsavedValues.path,
|
||||
});
|
||||
}
|
||||
errorsRef.current = errors;
|
||||
|
||||
useEffect(() => {
|
||||
// we can't flush immediately as setState haven't propagated at that time
|
||||
|
||||
@@ -2,16 +2,15 @@ import { useId, useState } from "react";
|
||||
import {
|
||||
Checkbox,
|
||||
CheckboxAndLabel,
|
||||
cssVar,
|
||||
Grid,
|
||||
InputErrorsTooltip,
|
||||
InputField,
|
||||
Label,
|
||||
Link,
|
||||
LinkButton,
|
||||
ProChip,
|
||||
Text,
|
||||
Tooltip,
|
||||
buttonStyle,
|
||||
rawTheme,
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { InfoCircleIcon } from "@webstudio-is/icons";
|
||||
@@ -85,16 +84,14 @@ export const AuthSection = ({
|
||||
staging for free; upgrade to Pro to publish to custom
|
||||
domains.
|
||||
</Text>
|
||||
<Link
|
||||
className={buttonStyle({ color: "gradient" })}
|
||||
<LinkButton
|
||||
color="primary"
|
||||
css={{ marginTop: theme.spacing[5], width: "100%" }}
|
||||
color="contrast"
|
||||
underline="none"
|
||||
target="_blank"
|
||||
href="https://webstudio.is/pricing"
|
||||
>
|
||||
Upgrade
|
||||
</Link>
|
||||
</LinkButton>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
@@ -102,7 +99,7 @@ export const AuthSection = ({
|
||||
variant="wrapped"
|
||||
>
|
||||
<InfoCircleIcon
|
||||
color={rawTheme.colors.foregroundSubtle}
|
||||
color={cssVar("--foreground-secondary")}
|
||||
tabIndex={-1}
|
||||
/>
|
||||
</Tooltip>
|
||||
|
||||
@@ -2,32 +2,31 @@ import { type FocusEventHandler, useId } from "react";
|
||||
import { useStore } from "@nanostores/react";
|
||||
import {
|
||||
Checkbox,
|
||||
cssVar,
|
||||
Flex,
|
||||
Grid,
|
||||
InputErrorsTooltip,
|
||||
InputField,
|
||||
Label,
|
||||
Link,
|
||||
LinkButton,
|
||||
ProChip,
|
||||
Select,
|
||||
Text,
|
||||
Tooltip,
|
||||
buttonStyle,
|
||||
rawTheme,
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { isLiteralExpression } from "@webstudio-is/expression";
|
||||
import { documentTypes, type Pages } from "@webstudio-is/sdk";
|
||||
import { HomeIcon, InfoCircleIcon } from "@webstudio-is/icons";
|
||||
import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
|
||||
import { computeExpression } from "@webstudio-is/project-build/runtime";
|
||||
import { $permissions } from "~/shared/nano-states";
|
||||
import { $pageRootScope } from "../page-utils";
|
||||
import type {
|
||||
PageSettingsErrors,
|
||||
PageSettingsValues,
|
||||
} from "@webstudio-is/project-build/runtime";
|
||||
import { computePageSettingsText, type OnChange } from "./shared";
|
||||
import { usePageSettingsText, type OnChange } from "./shared";
|
||||
|
||||
const autoSelectHandler: FocusEventHandler<HTMLInputElement> = (event) =>
|
||||
event.target.select();
|
||||
@@ -66,16 +65,14 @@ const PathField = ({
|
||||
parameters and other features. You can publish to staging
|
||||
for free; upgrade to Pro to publish to custom domains.
|
||||
</Text>
|
||||
<Link
|
||||
className={buttonStyle({ color: "gradient" })}
|
||||
<LinkButton
|
||||
color="primary"
|
||||
css={{ marginTop: theme.spacing[5], width: "100%" }}
|
||||
color="contrast"
|
||||
underline="none"
|
||||
target="_blank"
|
||||
href="https://webstudio.is/pricing"
|
||||
>
|
||||
Upgrade
|
||||
</Link>
|
||||
</LinkButton>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
@@ -83,7 +80,7 @@ const PathField = ({
|
||||
variant="wrapped"
|
||||
>
|
||||
<InfoCircleIcon
|
||||
color={rawTheme.colors.foregroundSubtle}
|
||||
color={cssVar("--foreground-secondary")}
|
||||
tabIndex={-1}
|
||||
/>
|
||||
</Tooltip>
|
||||
@@ -146,14 +143,14 @@ const StatusField = ({
|
||||
variant="wrapped"
|
||||
>
|
||||
<InfoCircleIcon
|
||||
color={rawTheme.colors.foregroundSubtle}
|
||||
color={cssVar("--foreground-secondary")}
|
||||
tabIndex={-1}
|
||||
/>
|
||||
</Tooltip>
|
||||
</Flex>
|
||||
<BindableExpressionControl
|
||||
expression={value ?? ""}
|
||||
value={String(computeExpression(value, variableValues) ?? "")}
|
||||
value={usePageSettingsText(value, variableValues)}
|
||||
bound={value !== undefined && isLiteralExpression(value) === false}
|
||||
showBinding={showBindingControls}
|
||||
scope={scope}
|
||||
@@ -222,16 +219,14 @@ const RedirectField = ({
|
||||
staging for free; upgrade to Pro to publish to custom
|
||||
domains.
|
||||
</Text>
|
||||
<Link
|
||||
className={buttonStyle({ color: "gradient" })}
|
||||
<LinkButton
|
||||
color="primary"
|
||||
css={{ marginTop: theme.spacing[5], width: "100%" }}
|
||||
color="contrast"
|
||||
underline="none"
|
||||
target="_blank"
|
||||
href="https://webstudio.is/pricing"
|
||||
>
|
||||
Upgrade
|
||||
</Link>
|
||||
</LinkButton>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
@@ -239,7 +234,7 @@ const RedirectField = ({
|
||||
variant="wrapped"
|
||||
>
|
||||
<InfoCircleIcon
|
||||
color={rawTheme.colors.foregroundSubtle}
|
||||
color={cssVar("--foreground-secondary")}
|
||||
tabIndex={-1}
|
||||
/>
|
||||
</Tooltip>
|
||||
@@ -247,7 +242,7 @@ const RedirectField = ({
|
||||
|
||||
<BindableExpressionControl
|
||||
expression={value ?? ""}
|
||||
value={computePageSettingsText(value, variableValues)}
|
||||
value={usePageSettingsText(value, variableValues)}
|
||||
bound={value !== undefined && isLiteralExpression(value) === false}
|
||||
showBinding={showBindingControls}
|
||||
scope={scope}
|
||||
@@ -347,14 +342,14 @@ export const GeneralSection = ({
|
||||
</>
|
||||
) : canSetHomePage === false ? (
|
||||
<>
|
||||
<HomeIcon color={rawTheme.colors.foregroundSubtle} />
|
||||
<HomeIcon color={cssVar("--foreground-secondary")} />
|
||||
<Text color="subtle">
|
||||
Stage this page for publish before setting it as the home page
|
||||
</Text>
|
||||
</>
|
||||
) : values.parentFolderId !== pages.rootFolderId ? (
|
||||
<>
|
||||
<HomeIcon color={rawTheme.colors.foregroundSubtle} />
|
||||
<HomeIcon color={cssVar("--foreground-secondary")} />
|
||||
<Text
|
||||
css={{
|
||||
overflowWrap: "anywhere",
|
||||
@@ -369,7 +364,7 @@ export const GeneralSection = ({
|
||||
</>
|
||||
) : values.documentType !== "html" ? (
|
||||
<>
|
||||
<HomeIcon color={rawTheme.colors.foregroundSubtle} />
|
||||
<HomeIcon color={cssVar("--foreground-secondary")} />
|
||||
<Text
|
||||
css={{
|
||||
overflowWrap: "anywhere",
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useId } from "react";
|
||||
import { useStore } from "@nanostores/react";
|
||||
import {
|
||||
PanelContent,
|
||||
Box,
|
||||
Button,
|
||||
cssVar,
|
||||
Grid,
|
||||
InputField,
|
||||
Label,
|
||||
@@ -14,7 +16,7 @@ import { $assets } from "~/shared/sync/data-stores";
|
||||
import { Card } from "../../marketplace/card";
|
||||
import { ImageInfo } from "../image-info";
|
||||
import type { PageSettingsValues } from "@webstudio-is/project-build/runtime";
|
||||
import { computePageSettingsText, type OnChange } from "./shared";
|
||||
import { usePageSettingsText, type OnChange } from "./shared";
|
||||
|
||||
export const MarketplaceSection = ({
|
||||
values,
|
||||
@@ -29,7 +31,7 @@ export const MarketplaceSection = ({
|
||||
({ property }) => property === "ws:category"
|
||||
);
|
||||
// @todo remove after all stores are migrated
|
||||
const categoryFallback = computePageSettingsText(
|
||||
const categoryFallback = usePageSettingsText(
|
||||
categoryMeta?.content ?? `""`,
|
||||
new Map()
|
||||
);
|
||||
@@ -38,7 +40,7 @@ export const MarketplaceSection = ({
|
||||
const thumbnailAsset = assets.get(values.marketplace.thumbnailAssetId);
|
||||
const thumnailFallbackAsset = assets.get(values.socialImageAssetId);
|
||||
return (
|
||||
<Grid gap={2} css={{ padding: theme.panel.padding }}>
|
||||
<PanelContent as={Grid} gap={2}>
|
||||
<Grid
|
||||
flow="column"
|
||||
gap={1}
|
||||
@@ -81,7 +83,7 @@ export const MarketplaceSection = ({
|
||||
})
|
||||
}
|
||||
>
|
||||
<Button color="neutral" css={{ justifySelf: "start" }}>
|
||||
<Button css={{ justifySelf: "start" }}>
|
||||
Choose thumbnail from assets
|
||||
</Button>
|
||||
</ImageControl>
|
||||
@@ -103,7 +105,7 @@ export const MarketplaceSection = ({
|
||||
css={{
|
||||
padding: theme.spacing[5],
|
||||
borderRadius: theme.borderRadius[4],
|
||||
border: `1px solid ${theme.colors.borderMain}`,
|
||||
border: `1px solid ${cssVar("--border-default")}`,
|
||||
justifySelf: "start",
|
||||
}}
|
||||
>
|
||||
@@ -116,6 +118,6 @@ export const MarketplaceSection = ({
|
||||
</Grid>
|
||||
</Box>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</PanelContent>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { pageSettingsDefaultValues } from "@webstudio-is/project-build/runtime";
|
||||
import { SearchSection } from "./section-search";
|
||||
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
test("search exclusion preserves false and can be toggled in both directions", async () => {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const onChange = vi.fn();
|
||||
const render = async (expression: string) => {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<SearchSection
|
||||
values={{
|
||||
...pageSettingsDefaultValues,
|
||||
excludePageFromSearch: expression,
|
||||
}}
|
||||
errors={{}}
|
||||
onChange={onChange}
|
||||
showBindingControls={false}
|
||||
/>
|
||||
);
|
||||
});
|
||||
};
|
||||
try {
|
||||
await render("false");
|
||||
const checkbox =
|
||||
container.querySelector<HTMLButtonElement>('[role="checkbox"]')!;
|
||||
expect(checkbox.getAttribute("aria-checked")).toBe("false");
|
||||
await act(async () => checkbox.click());
|
||||
expect(onChange).toHaveBeenLastCalledWith({
|
||||
field: "excludePageFromSearch",
|
||||
value: "true",
|
||||
});
|
||||
await render("true");
|
||||
expect(checkbox.getAttribute("aria-checked")).toBe("true");
|
||||
await act(async () => checkbox.click());
|
||||
expect(onChange).toHaveBeenLastCalledWith({
|
||||
field: "excludePageFromSearch",
|
||||
value: "false",
|
||||
});
|
||||
await render("false");
|
||||
expect(checkbox.getAttribute("aria-checked")).toBe("false");
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
@@ -11,8 +11,9 @@ import {
|
||||
theme,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { isLiteralExpression } from "@webstudio-is/expression";
|
||||
import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
|
||||
import { computeExpression } from "@webstudio-is/project-build/runtime";
|
||||
import { useAsyncValue } from "~/shared/use-async-value";
|
||||
import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
|
||||
import type {
|
||||
PageSettingsErrors,
|
||||
PageSettingsValues,
|
||||
@@ -21,7 +22,11 @@ import { useStore } from "@nanostores/react";
|
||||
import { $assets, $projectSettings } from "~/shared/sync/data-stores";
|
||||
import { $pageRootScope } from "../page-utils";
|
||||
import { SearchPreview } from "../search-preview";
|
||||
import { computePageSettingsText, usePageUrl, type OnChange } from "./shared";
|
||||
import { usePageSettingsText, usePageUrl, type OnChange } from "./shared";
|
||||
|
||||
// Search-engine previews represent an external light surface, not Builder UI.
|
||||
const searchPreviewBackground = "#ffffff";
|
||||
const searchPreviewBorder = "#e6e6e6";
|
||||
|
||||
const LanguageField = ({
|
||||
errors,
|
||||
@@ -43,7 +48,7 @@ const LanguageField = ({
|
||||
<Label htmlFor={id}>Language</Label>
|
||||
<BindableExpressionControl
|
||||
expression={value}
|
||||
value={computePageSettingsText(value, variableValues)}
|
||||
value={usePageSettingsText(value, variableValues)}
|
||||
bound={isLiteralExpression(value) === false}
|
||||
showBinding={showBindingControls}
|
||||
scope={scope}
|
||||
@@ -96,13 +101,14 @@ export const SearchSection = ({
|
||||
const pageUrl = usePageUrl(values);
|
||||
const faviconAsset = assets.get(projectSettings?.meta.faviconAssetId ?? "");
|
||||
const faviconUrl = faviconAsset?.type === "image" ? faviconAsset.name : "";
|
||||
const title = computePageSettingsText(values.title, variableValues);
|
||||
const description = computePageSettingsText(
|
||||
values.description,
|
||||
variableValues
|
||||
);
|
||||
const title = usePageSettingsText(values.title, variableValues);
|
||||
const description = usePageSettingsText(values.description, variableValues);
|
||||
const excludePageFromSearch = Boolean(
|
||||
computeExpression(values.excludePageFromSearch, variableValues)
|
||||
useAsyncValue(
|
||||
() => computeExpression(values.excludePageFromSearch, variableValues),
|
||||
[values.excludePageFromSearch, variableValues],
|
||||
undefined
|
||||
)
|
||||
);
|
||||
return (
|
||||
<Grid gap={2}>
|
||||
@@ -115,9 +121,9 @@ export const SearchSection = ({
|
||||
<Box
|
||||
css={{
|
||||
padding: theme.spacing[5],
|
||||
background: theme.colors.white,
|
||||
background: searchPreviewBackground,
|
||||
borderRadius: theme.borderRadius[4],
|
||||
border: `1px solid ${theme.colors.borderMain}`,
|
||||
border: `1px solid ${searchPreviewBorder}`,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
|
||||
@@ -18,7 +18,7 @@ import { isLiteralExpression } from "@webstudio-is/expression";
|
||||
import { $pageRootScope } from "../page-utils";
|
||||
import { ImageInfo } from "../image-info";
|
||||
import { SocialPreview } from "../social-preview";
|
||||
import { computePageSettingsText, usePageUrl, type OnChange } from "./shared";
|
||||
import { usePageSettingsText, usePageUrl, type OnChange } from "./shared";
|
||||
|
||||
export const SocialImageSection = ({
|
||||
values,
|
||||
@@ -37,16 +37,13 @@ export const SocialImageSection = ({
|
||||
const assets = useStore($assets);
|
||||
const socialImageAsset = assets.get(values.socialImageAssetId);
|
||||
const { variableValues, scope, aliases } = useStore($pageRootScope);
|
||||
const socialImageUrl = computePageSettingsText(
|
||||
const socialImageUrl = usePageSettingsText(
|
||||
values.socialImageUrl,
|
||||
variableValues
|
||||
);
|
||||
const pageUrl = usePageUrl(values);
|
||||
const title = computePageSettingsText(values.title, variableValues);
|
||||
const description = computePageSettingsText(
|
||||
values.description,
|
||||
variableValues
|
||||
);
|
||||
const title = usePageSettingsText(values.title, variableValues);
|
||||
const description = usePageSettingsText(values.description, variableValues);
|
||||
return (
|
||||
<Grid gap={2}>
|
||||
<Text color="subtle">
|
||||
@@ -100,7 +97,6 @@ export const SocialImageSection = ({
|
||||
<Button
|
||||
id={socialImageAssetButtonId}
|
||||
css={{ justifySelf: "start" }}
|
||||
color="neutral"
|
||||
disabled={disabled}
|
||||
>
|
||||
Choose image from assets
|
||||
@@ -134,3 +130,5 @@ export const SocialImageSection = ({
|
||||
</Grid>
|
||||
);
|
||||
};
|
||||
|
||||
undefined;
|
||||
@@ -3,13 +3,13 @@ import { useStore } from "@nanostores/react";
|
||||
import { Grid, Label, Text, TextArea } from "@webstudio-is/design-system";
|
||||
import { isLiteralExpression } from "@webstudio-is/expression";
|
||||
import { BindableExpressionControl } from "~/builder/shared/bindable-expression";
|
||||
import { computeExpression } from "@webstudio-is/project-build/runtime";
|
||||
import type {
|
||||
PageSettingsErrors,
|
||||
PageSettingsValues,
|
||||
} from "@webstudio-is/project-build/runtime";
|
||||
import { $pageRootScope } from "../page-utils";
|
||||
import type { OnChange } from "./shared";
|
||||
import { usePageSettingsText } from "./shared";
|
||||
|
||||
export const TextContentSection = ({
|
||||
values,
|
||||
@@ -30,9 +30,7 @@ export const TextContentSection = ({
|
||||
<Label htmlFor={contentId}>Text</Label>
|
||||
<BindableExpressionControl
|
||||
expression={values.content}
|
||||
value={String(
|
||||
computeExpression(values.content, variableValues) ?? ""
|
||||
)}
|
||||
value={usePageSettingsText(values.content, variableValues)}
|
||||
bound={isLiteralExpression(values.content) === false}
|
||||
scope={scope}
|
||||
aliases={aliases}
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { computePageSettingsText } from "./shared";
|
||||
import { computeExpression } from "@webstudio-is/project-build/runtime";
|
||||
|
||||
describe("computePageSettingsText", () => {
|
||||
test("renders literal and computed values as text", () => {
|
||||
expect(computePageSettingsText(`"Page title"`, new Map())).toBe(
|
||||
describe("page settings expression values", () => {
|
||||
test("renders literal and computed values as text", async () => {
|
||||
await expect(computeExpression(`"Page title"`, new Map())).resolves.toBe(
|
||||
"Page title"
|
||||
);
|
||||
expect(computePageSettingsText("42", new Map())).toBe("42");
|
||||
await expect(computeExpression("42", new Map())).resolves.toBe(42);
|
||||
});
|
||||
|
||||
test("does not expose missing expression values as text", () => {
|
||||
expect(computePageSettingsText("missingVariable", new Map())).toBe("");
|
||||
expect(computePageSettingsText("null", new Map())).toBe("");
|
||||
test("does not expose missing expression values as text", async () => {
|
||||
await expect(computeExpression("missingVariable", new Map())).resolves.toBe(
|
||||
undefined
|
||||
);
|
||||
await expect(computeExpression("null", new Map())).resolves.toBe(null);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { useStore } from "@nanostores/react";
|
||||
import { getPagePath } from "@webstudio-is/sdk";
|
||||
import type { PageSettingsValues } from "@webstudio-is/project-build/runtime";
|
||||
import { computeExpression } from "@webstudio-is/project-build/runtime";
|
||||
import { useAsyncValue } from "~/shared/use-async-value";
|
||||
import {
|
||||
compilePathnamePattern,
|
||||
tokenizePathnamePattern,
|
||||
@@ -19,11 +20,15 @@ export type OnChange = (
|
||||
}[keyof PageSettingsValues]
|
||||
) => void;
|
||||
|
||||
export const computePageSettingsText = (
|
||||
export const usePageSettingsText = (
|
||||
expression: string,
|
||||
variables: Map<string, unknown>
|
||||
) => {
|
||||
const value = computeExpression(expression, variables);
|
||||
const value = useAsyncValue(
|
||||
() => computeExpression(expression, variables),
|
||||
[expression, variables],
|
||||
undefined
|
||||
);
|
||||
return value === undefined || value === null ? "" : String(value);
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { Project } from "@webstudio-is/project";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import { Dialog, DialogContent } from "@webstudio-is/design-system";
|
||||
import { $pages, $project } from "~/shared/sync/data-stores";
|
||||
import {
|
||||
$authPermit,
|
||||
$builderMode,
|
||||
$selectedPageId,
|
||||
} from "~/shared/nano-states";
|
||||
import { FolderSettings, NewFolderSettings } from "./folder-settings";
|
||||
import {
|
||||
TemplateSettings,
|
||||
NewTemplateSettings,
|
||||
CreatePageFromTemplateSettings,
|
||||
} from "./template-settings";
|
||||
import { PageSettings, NewPageSettings } from "./page-settings/page-settings";
|
||||
import { PagesPanel } from "./pages";
|
||||
|
||||
export default { title: "Pages/States", component: PagesPanel };
|
||||
|
||||
type State =
|
||||
| "tree"
|
||||
| "folder"
|
||||
| "newFolder"
|
||||
| "template"
|
||||
| "newTemplate"
|
||||
| "fromTemplate"
|
||||
| "newPage"
|
||||
| "home"
|
||||
| "draft"
|
||||
| "text"
|
||||
| "redirect"
|
||||
| "marketplace"
|
||||
| "bound";
|
||||
const PageStory = ({
|
||||
state,
|
||||
contentMode = false,
|
||||
}: {
|
||||
state: State;
|
||||
contentMode?: boolean;
|
||||
}) => {
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
const previous = [
|
||||
$pages.get(),
|
||||
$project.get(),
|
||||
$authPermit.get(),
|
||||
$builderMode.get(),
|
||||
$selectedPageId.get(),
|
||||
] as const;
|
||||
const pages = createDefaultPages({ rootInstanceId: "page-root" });
|
||||
const page = {
|
||||
id: "example-page",
|
||||
name: "Example page",
|
||||
title: '"Example page"',
|
||||
path: "/example",
|
||||
rootInstanceId: "page-root",
|
||||
meta: {},
|
||||
isDraft: state === "draft",
|
||||
};
|
||||
pages.pages.set(page.id, {
|
||||
...page,
|
||||
meta:
|
||||
state === "text"
|
||||
? { documentType: "text", content: '"User-agent: *\\nAllow: /"' }
|
||||
: state === "bound"
|
||||
? { description: "page.description", language: "page.language" }
|
||||
: {},
|
||||
});
|
||||
pages.folders.set("example-folder", {
|
||||
id: "example-folder",
|
||||
name: "Blog",
|
||||
slug: "blog",
|
||||
children: [page.id],
|
||||
});
|
||||
pages.folders.get(pages.rootFolderId)?.children.push("example-folder");
|
||||
pages.pageTemplates = new Map([
|
||||
[
|
||||
"example-template",
|
||||
{
|
||||
id: "example-template",
|
||||
name: "Article",
|
||||
title: '"Article"',
|
||||
rootInstanceId: "template-root",
|
||||
meta: { description: '"Article description"' },
|
||||
},
|
||||
],
|
||||
]);
|
||||
if (state === "redirect") {
|
||||
pages.redirects = [{ old: "/blog/example", new: "/", status: "301" }];
|
||||
}
|
||||
$pages.set(pages);
|
||||
$project.set({
|
||||
id: "storybook-project",
|
||||
title: "My Project",
|
||||
marketplaceApprovalStatus:
|
||||
state === "marketplace" ? "APPROVED" : "UNLISTED",
|
||||
} as Project);
|
||||
$authPermit.set("own");
|
||||
$builderMode.set(contentMode ? "content" : "design");
|
||||
$selectedPageId.set(state === "home" ? pages.homePageId : page.id);
|
||||
setReady(true);
|
||||
return () => {
|
||||
setReady(false);
|
||||
$pages.set(previous[0]);
|
||||
$project.set(previous[1]);
|
||||
$authPermit.set(previous[2]);
|
||||
$builderMode.set(previous[3]);
|
||||
$selectedPageId.set(previous[4]);
|
||||
};
|
||||
}, [state, contentMode]);
|
||||
if (!ready) {
|
||||
return;
|
||||
}
|
||||
if (state === "tree") {
|
||||
return (
|
||||
<div style={{ width: 280, height: 780 }}>
|
||||
<PagesPanel onClose={() => {}} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const content =
|
||||
state === "folder" ? (
|
||||
<FolderSettings
|
||||
folderId="example-folder"
|
||||
onClose={() => {}}
|
||||
onRequestDelete={() => {}}
|
||||
onDuplicate={() => {}}
|
||||
/>
|
||||
) : state === "newFolder" ? (
|
||||
<NewFolderSettings onClose={() => {}} onSuccess={() => {}} />
|
||||
) : state === "template" ? (
|
||||
<TemplateSettings
|
||||
templateId="example-template"
|
||||
onClose={() => {}}
|
||||
onDuplicate={() => {}}
|
||||
onDelete={() => {}}
|
||||
/>
|
||||
) : state === "newTemplate" ? (
|
||||
<NewTemplateSettings onSuccess={() => {}} />
|
||||
) : state === "fromTemplate" ? (
|
||||
<CreatePageFromTemplateSettings
|
||||
templateId="example-template"
|
||||
onSuccess={() => {}}
|
||||
/>
|
||||
) : state === "newPage" ? (
|
||||
<NewPageSettings onSuccess={() => {}} />
|
||||
) : (
|
||||
<PageSettings
|
||||
pageId={$selectedPageId.get()!}
|
||||
onClose={() => {}}
|
||||
onDelete={() => {}}
|
||||
onDuplicate={() => {}}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<Dialog open>
|
||||
<DialogContent css={{ width: 320, height: 800 }}>{content}</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
export const Tree = () => <PageStory state="tree" />;
|
||||
export const ContentTree = () => <PageStory state="tree" contentMode />;
|
||||
export const Folder = () => <PageStory state="folder" />;
|
||||
export const NewFolder = () => <PageStory state="newFolder" />;
|
||||
export const Template = () => <PageStory state="template" />;
|
||||
export const TemplateReadOnly = () => (
|
||||
<PageStory state="template" contentMode />
|
||||
);
|
||||
export const NewTemplate = () => <PageStory state="newTemplate" />;
|
||||
export const FromTemplate = () => <PageStory state="fromTemplate" />;
|
||||
export const FromTemplateContentMode = () => (
|
||||
<PageStory state="fromTemplate" contentMode />
|
||||
);
|
||||
export const NewPage = () => <PageStory state="newPage" />;
|
||||
export const Home = () => <PageStory state="home" />;
|
||||
export const Draft = () => <PageStory state="draft" />;
|
||||
export const TextDocument = () => <PageStory state="text" />;
|
||||
export const RedirectConflict = () => <PageStory state="redirect" />;
|
||||
export const Marketplace = () => <PageStory state="marketplace" />;
|
||||
export const BoundContent = () => <PageStory state="bound" contentMode />;
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
import { setEnv } from "@webstudio-is/feature-flags";
|
||||
import { createDefaultPages } from "@webstudio-is/project-build";
|
||||
import type { Project } from "@webstudio-is/project";
|
||||
@@ -37,7 +37,12 @@ import {
|
||||
import { registerContainers } from "~/shared/sync/sync-stores";
|
||||
import { $selectedPageId } from "~/shared/nano-states";
|
||||
import { updateCurrentSystem } from "~/shared/system";
|
||||
import { $resourcesCache, getResourceKey } from "~/shared/resources";
|
||||
import {
|
||||
$resourcesCache,
|
||||
computeResourceRequest,
|
||||
getResourceKey,
|
||||
} from "~/shared/resources";
|
||||
import { subscribeResourceRequestPlan } from "~/shared/nano-states/props";
|
||||
|
||||
setEnv("*");
|
||||
registerContainers();
|
||||
@@ -129,7 +134,7 @@ const createPages = () => {
|
||||
const toMap = <T extends { id: string }>(list: T[]) =>
|
||||
new Map(list.map((item) => [item.id, item]));
|
||||
|
||||
test("page root scope should rely on selected page", () => {
|
||||
test("page root scope should rely on selected page", async () => {
|
||||
const pages = createDefaultPages({
|
||||
rootInstanceId: "homeRootId",
|
||||
homePageId: "homePageId",
|
||||
@@ -162,90 +167,99 @@ test("page root scope should rely on selected page", () => {
|
||||
},
|
||||
])
|
||||
);
|
||||
expect($pageRootScope.get()).toEqual({
|
||||
aliases: new Map([
|
||||
["$ws$system", "system"],
|
||||
["$ws$dataSource$2", "page variable"],
|
||||
]),
|
||||
scope: {
|
||||
$ws$system: initialSystem,
|
||||
$ws$dataSource$2: "",
|
||||
},
|
||||
variableValues: new Map<string, unknown>([
|
||||
[SYSTEM_VARIABLE_ID, initialSystem],
|
||||
["2", ""],
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
test("page root scope should use variable and resource values", () => {
|
||||
$pages.set(
|
||||
createDefaultPages({
|
||||
rootInstanceId: "homeRootId",
|
||||
homePageId: "homePageId",
|
||||
await vi.waitFor(() =>
|
||||
expect($pageRootScope.get()).toEqual({
|
||||
aliases: new Map([
|
||||
["$ws$system", "system"],
|
||||
["$ws$dataSource$2", "page variable"],
|
||||
]),
|
||||
scope: {
|
||||
$ws$system: initialSystem,
|
||||
$ws$dataSource$2: "",
|
||||
},
|
||||
variableValues: new Map<string, unknown>([
|
||||
[SYSTEM_VARIABLE_ID, initialSystem],
|
||||
["2", ""],
|
||||
]),
|
||||
})
|
||||
);
|
||||
$selectedPageId.set("homePageId");
|
||||
$dataSources.set(
|
||||
toMap([
|
||||
{
|
||||
id: "valueVariableId",
|
||||
scopeInstanceId: "homeRootId",
|
||||
name: "value variable",
|
||||
type: "variable",
|
||||
value: { type: "string", value: "" },
|
||||
},
|
||||
{
|
||||
id: "resourceVariableId",
|
||||
scopeInstanceId: "homeRootId",
|
||||
name: "resource variable",
|
||||
type: "resource",
|
||||
resourceId: "resourceId",
|
||||
},
|
||||
])
|
||||
);
|
||||
$dataSourceVariables.set(
|
||||
new Map([["valueVariableId", "value variable value"]])
|
||||
);
|
||||
const resourceKey = getResourceKey({
|
||||
name: "my-resource",
|
||||
url: "",
|
||||
searchParams: [],
|
||||
method: "get",
|
||||
headers: [],
|
||||
});
|
||||
$resources.set(
|
||||
toMap<Resource>([
|
||||
{
|
||||
id: "resourceId",
|
||||
name: "my-resource",
|
||||
url: `""`,
|
||||
method: "get",
|
||||
headers: [],
|
||||
},
|
||||
])
|
||||
);
|
||||
$resourcesCache.set(new Map([[resourceKey, "resource variable value"]]));
|
||||
expect($pageRootScope.get()).toEqual({
|
||||
aliases: new Map([
|
||||
["$ws$system", "system"],
|
||||
["$ws$dataSource$valueVariableId", "value variable"],
|
||||
["$ws$dataSource$resourceVariableId", "resource variable"],
|
||||
]),
|
||||
scope: {
|
||||
$ws$system: initialSystem,
|
||||
$ws$dataSource$resourceVariableId: "resource variable value",
|
||||
$ws$dataSource$valueVariableId: "value variable value",
|
||||
},
|
||||
variableValues: new Map<string, unknown>([
|
||||
[SYSTEM_VARIABLE_ID, initialSystem],
|
||||
["valueVariableId", "value variable value"],
|
||||
["resourceVariableId", "resource variable value"],
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
test("page root scope should provide page system variable value", () => {
|
||||
test("page root scope should use a resource value consumed by the page", async () => {
|
||||
const unsubscribeResourceRequestPlan = subscribeResourceRequestPlan(() => {});
|
||||
try {
|
||||
const pages = createDefaultPages({
|
||||
rootInstanceId: "homeRootId",
|
||||
homePageId: "homePageId",
|
||||
});
|
||||
const homePage = pages.pages.get("homePageId");
|
||||
if (homePage === undefined) {
|
||||
throw new Error("Home page is missing");
|
||||
}
|
||||
pages.pages.set("homePageId", {
|
||||
...homePage,
|
||||
title: "$ws$dataSource$resourceVariableId",
|
||||
});
|
||||
$pages.set(pages);
|
||||
$selectedPageId.set("homePageId");
|
||||
$dataSources.set(
|
||||
toMap([
|
||||
{
|
||||
id: "valueVariableId",
|
||||
scopeInstanceId: "homeRootId",
|
||||
name: "value variable",
|
||||
type: "variable",
|
||||
value: { type: "string", value: "" },
|
||||
},
|
||||
{
|
||||
id: "resourceVariableId",
|
||||
scopeInstanceId: "homeRootId",
|
||||
name: "resource variable",
|
||||
type: "resource",
|
||||
resourceId: "resourceId",
|
||||
},
|
||||
])
|
||||
);
|
||||
$dataSourceVariables.set(
|
||||
new Map([["valueVariableId", "value variable value"]])
|
||||
);
|
||||
const resource = {
|
||||
id: "resourceId",
|
||||
name: "my-resource",
|
||||
url: `""`,
|
||||
method: "get",
|
||||
headers: [],
|
||||
} satisfies Resource;
|
||||
$resources.set(toMap([resource]));
|
||||
const resourceKey = getResourceKey(
|
||||
await computeResourceRequest(resource, new Map())
|
||||
);
|
||||
$resourcesCache.set(new Map([[resourceKey, "resource variable value"]]));
|
||||
await vi.waitFor(() =>
|
||||
expect($pageRootScope.get()).toEqual({
|
||||
aliases: new Map([
|
||||
["$ws$system", "system"],
|
||||
["$ws$dataSource$valueVariableId", "value variable"],
|
||||
["$ws$dataSource$resourceVariableId", "resource variable"],
|
||||
]),
|
||||
scope: {
|
||||
$ws$system: initialSystem,
|
||||
$ws$dataSource$resourceVariableId: "resource variable value",
|
||||
$ws$dataSource$valueVariableId: "value variable value",
|
||||
},
|
||||
variableValues: new Map<string, unknown>([
|
||||
[SYSTEM_VARIABLE_ID, initialSystem],
|
||||
["valueVariableId", "value variable value"],
|
||||
["resourceVariableId", "resource variable value"],
|
||||
]),
|
||||
})
|
||||
);
|
||||
} finally {
|
||||
unsubscribeResourceRequestPlan();
|
||||
}
|
||||
});
|
||||
|
||||
test("page root scope should provide page system variable value", async () => {
|
||||
$pages.set(
|
||||
createDefaultPages({
|
||||
rootInstanceId: "homeRootId",
|
||||
@@ -264,53 +278,37 @@ test("page root scope should provide page system variable value", () => {
|
||||
},
|
||||
])
|
||||
);
|
||||
expect($pageRootScope.get()).toEqual({
|
||||
aliases: new Map([["$ws$dataSource$systemId", "system"]]),
|
||||
scope: {
|
||||
$ws$dataSource$systemId: {
|
||||
origin: "https://undefined.wstd.work",
|
||||
params: {},
|
||||
pathname: "/",
|
||||
search: {},
|
||||
await vi.waitFor(() =>
|
||||
expect($pageRootScope.get()).toEqual({
|
||||
aliases: new Map([["$ws$dataSource$systemId", "system"]]),
|
||||
scope: {
|
||||
$ws$dataSource$systemId: initialSystem,
|
||||
},
|
||||
},
|
||||
variableValues: new Map([
|
||||
[
|
||||
"systemId",
|
||||
{
|
||||
params: {},
|
||||
pathname: "/",
|
||||
search: {},
|
||||
origin: "https://undefined.wstd.work",
|
||||
},
|
||||
],
|
||||
]),
|
||||
});
|
||||
updateCurrentSystem({
|
||||
variableValues: new Map([
|
||||
[SYSTEM_VARIABLE_ID, initialSystem],
|
||||
["systemId", initialSystem],
|
||||
]),
|
||||
})
|
||||
);
|
||||
const updatedSystem = {
|
||||
...initialSystem,
|
||||
params: { slug: "my-post" },
|
||||
};
|
||||
updateCurrentSystem({
|
||||
params: updatedSystem.params,
|
||||
});
|
||||
expect($pageRootScope.get()).toEqual({
|
||||
aliases: new Map([["$ws$dataSource$systemId", "system"]]),
|
||||
scope: {
|
||||
$ws$dataSource$systemId: {
|
||||
params: { slug: "my-post" },
|
||||
pathname: "/",
|
||||
search: {},
|
||||
origin: "https://undefined.wstd.work",
|
||||
await vi.waitFor(() =>
|
||||
expect($pageRootScope.get()).toEqual({
|
||||
aliases: new Map([["$ws$dataSource$systemId", "system"]]),
|
||||
scope: {
|
||||
$ws$dataSource$systemId: updatedSystem,
|
||||
},
|
||||
},
|
||||
variableValues: new Map([
|
||||
[
|
||||
"systemId",
|
||||
{
|
||||
params: { slug: "my-post" },
|
||||
pathname: "/",
|
||||
search: {},
|
||||
origin: "https://undefined.wstd.work",
|
||||
},
|
||||
],
|
||||
]),
|
||||
});
|
||||
variableValues: new Map([
|
||||
[SYSTEM_VARIABLE_ID, updatedSystem],
|
||||
["systemId", updatedSystem],
|
||||
]),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
describe("isFolder", () => {
|
||||
|
||||
@@ -35,7 +35,8 @@ export const $pageRootScope = computed(
|
||||
variableValuesByInstanceSelector.get(
|
||||
getInstanceKey([page.rootInstanceId, ROOT_INSTANCE_ID])
|
||||
) ?? new Map<string, unknown>();
|
||||
for (const [dataSourceId, value] of values) {
|
||||
const visibleDataSourceIdByName = new Map<string, string>();
|
||||
for (const dataSourceId of values.keys()) {
|
||||
let dataSource = dataSources.get(dataSourceId);
|
||||
if (dataSourceId === SYSTEM_VARIABLE_ID) {
|
||||
dataSource = systemParameter;
|
||||
@@ -43,6 +44,17 @@ export const $pageRootScope = computed(
|
||||
if (dataSource === undefined) {
|
||||
continue;
|
||||
}
|
||||
visibleDataSourceIdByName.set(dataSource.name, dataSourceId);
|
||||
}
|
||||
for (const dataSourceId of visibleDataSourceIdByName.values()) {
|
||||
const value = values.get(dataSourceId);
|
||||
const dataSource =
|
||||
dataSourceId === SYSTEM_VARIABLE_ID
|
||||
? systemParameter
|
||||
: dataSources.get(dataSourceId);
|
||||
if (dataSource === undefined) {
|
||||
continue;
|
||||
}
|
||||
const name = encodeDataSourceVariable(dataSourceId);
|
||||
scope[name] = value;
|
||||
aliases.set(name, dataSource.name);
|
||||
|
||||
@@ -16,7 +16,7 @@ const faviconDataUrl = `data:image/svg+xml,${encodeURIComponent(
|
||||
|
||||
export const SearchPreview = () => (
|
||||
<StorySection title="Search Preview">
|
||||
<Box css={{ width: 600, margin: 20 }}>
|
||||
<Box css={{ width: 600, margin: 20, background: "#fff" }}>
|
||||
<SearchPreviewComponent
|
||||
pageUrl="https://webstudio.is/blog-webstudios-architecture-an-overview"
|
||||
titleLink="Blog: Webstudio's Architecture - an overview"
|
||||
|
||||
@@ -2,6 +2,15 @@ import { Box, Flex, Grid } from "@webstudio-is/design-system";
|
||||
import { getImageAttributes, wsImageLoader } from "@webstudio-is/image";
|
||||
import { formatUrl, truncateByWords, truncate } from "./social-utils";
|
||||
|
||||
// Search previews reproduce Google's light result surface rather than Builder UI.
|
||||
const searchPreviewColors = {
|
||||
faviconBackground: "#f1f3f4",
|
||||
faviconBorder: "#ecedef",
|
||||
foreground: "#202124",
|
||||
foregroundSecondary: "#4d5156",
|
||||
link: "#1a0dab",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Full description with links https://developers.google.com/search/docs/appearance/visual-elements-gallery
|
||||
*/
|
||||
@@ -86,8 +95,8 @@ export const SearchPreview = (props: SearchPreviewProps) => {
|
||||
width: 28,
|
||||
height: 28,
|
||||
borderRadius: "50%",
|
||||
backgroundColor: "#f1f3f4",
|
||||
border: "1px solid #ecedef",
|
||||
backgroundColor: searchPreviewColors.faviconBackground,
|
||||
border: `1px solid ${searchPreviewColors.faviconBorder}`,
|
||||
}}
|
||||
justify={"center"}
|
||||
align={"center"}
|
||||
@@ -104,7 +113,7 @@ export const SearchPreview = (props: SearchPreviewProps) => {
|
||||
<Grid>
|
||||
<Flex
|
||||
css={{
|
||||
color: "#202124",
|
||||
color: searchPreviewColors.foreground,
|
||||
fontSize: "14px",
|
||||
lineHeight: "20px",
|
||||
whiteSpace: "nowrap",
|
||||
@@ -116,7 +125,7 @@ export const SearchPreview = (props: SearchPreviewProps) => {
|
||||
css={{
|
||||
fontSize: "12px",
|
||||
lineHeight: "18px",
|
||||
color: "#4d5156",
|
||||
color: searchPreviewColors.foregroundSecondary,
|
||||
gap: 8,
|
||||
}}
|
||||
align={"center"}
|
||||
@@ -131,7 +140,7 @@ export const SearchPreview = (props: SearchPreviewProps) => {
|
||||
css={{
|
||||
fontSize: "20px",
|
||||
fontWeight: 400,
|
||||
color: "#1a0dab",
|
||||
color: searchPreviewColors.link,
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
whiteSpace: "nowrap",
|
||||
@@ -144,7 +153,7 @@ export const SearchPreview = (props: SearchPreviewProps) => {
|
||||
css={{
|
||||
lineHeight: 1.58,
|
||||
fontSize: 14,
|
||||
color: "#4d5156",
|
||||
color: searchPreviewColors.foregroundSecondary,
|
||||
"-webkit-line-clamp": 2,
|
||||
display: "-webkit-box",
|
||||
"-webkit-box-orient": "vertical",
|
||||
|
||||
@@ -9,13 +9,22 @@ type SocialPreviewProps = {
|
||||
ogDescription: string;
|
||||
};
|
||||
|
||||
// Social previews represent an external light surface, not Builder UI.
|
||||
const socialPreviewColors = {
|
||||
background: "#fff",
|
||||
imagePlaceholder: "#dfe3e6",
|
||||
border: "#e6e6e6",
|
||||
foreground: "#18283e",
|
||||
foregroundSecondary: "#4d5156",
|
||||
} as const;
|
||||
|
||||
const imgStyle = css({
|
||||
borderTopLeftRadius: theme.borderRadius[4],
|
||||
borderTopRightRadius: theme.borderRadius[4],
|
||||
width: "100%",
|
||||
aspectRatio: "1.91",
|
||||
background: "#DFE3E6",
|
||||
borderBottom: `1px solid ${theme.colors.borderMain}`,
|
||||
background: socialPreviewColors.imagePlaceholder,
|
||||
borderBottom: `1px solid ${socialPreviewColors.border}`,
|
||||
variants: {
|
||||
hasImage: {
|
||||
true: {
|
||||
@@ -39,8 +48,8 @@ export const SocialPreview = ({
|
||||
gap={1}
|
||||
css={{
|
||||
borderRadius: theme.borderRadius[4],
|
||||
border: `1px solid ${theme.colors.borderMain}`,
|
||||
backgroundColor: theme.colors.white,
|
||||
border: `1px solid ${socialPreviewColors.border}`,
|
||||
backgroundColor: socialPreviewColors.background,
|
||||
}}
|
||||
>
|
||||
<img
|
||||
@@ -63,7 +72,7 @@ export const SocialPreview = ({
|
||||
>
|
||||
<Box
|
||||
css={{
|
||||
color: "#4D5156",
|
||||
color: socialPreviewColors.foregroundSecondary,
|
||||
fontFamily: "Arial",
|
||||
fontSize: "12px",
|
||||
lineHeight: "16px",
|
||||
@@ -73,7 +82,7 @@ export const SocialPreview = ({
|
||||
</Box>
|
||||
<Box
|
||||
css={{
|
||||
color: "#18283E",
|
||||
color: socialPreviewColors.foreground,
|
||||
fontFamily: "Arial",
|
||||
fontSize: "14px",
|
||||
fontWeight: 700,
|
||||
@@ -87,7 +96,7 @@ export const SocialPreview = ({
|
||||
</Box>
|
||||
<Box
|
||||
css={{
|
||||
color: "#4D5156",
|
||||
color: socialPreviewColors.foregroundSecondary,
|
||||
fontFamily: "Arial",
|
||||
fontSize: "12px",
|
||||
fontWeight: 400,
|
||||
|
||||
Loaded 100 of 2604 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user