mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-05 06:36:34 +00:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22c84c59f6 | ||
|
|
d6512537f4 | ||
|
|
59afa917b2 | ||
|
|
75f8a2597d | ||
|
|
6e6ef71913 | ||
|
|
5f8f3c3a44 | ||
|
|
9859997f9c | ||
|
|
7526bf1260 | ||
|
|
360c2b0b3c | ||
|
|
c7fdc1d3ba | ||
|
|
279a152c20 | ||
|
|
7e4617279b | ||
|
|
2c8afcf4bd | ||
|
|
7924d86621 |
@@ -0,0 +1,14 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: npm
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
cooldown:
|
||||
default-days: 7
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
cooldown:
|
||||
default-days: 7
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
sparse-checkout: scripts
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref }}
|
||||
@@ -70,7 +70,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref }}
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
@@ -93,7 +93,7 @@ jobs:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Setup Expo and EAS
|
||||
uses: expo/expo-github-action@v8
|
||||
uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8
|
||||
with:
|
||||
eas-version: latest
|
||||
token: ${{ secrets.EXPO_TOKEN }}
|
||||
|
||||
+31
-28
@@ -24,6 +24,9 @@ env:
|
||||
NPM_CONFIG_AUDIT: "false"
|
||||
NPM_CONFIG_FUND: "false"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
changes:
|
||||
name: changes
|
||||
@@ -49,7 +52,7 @@ jobs:
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
|
||||
@@ -60,7 +63,7 @@ jobs:
|
||||
filters: .github/ci-paths.yml
|
||||
|
||||
- name: Validate CI contracts
|
||||
run: node --test scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs scripts/precompress-assets.test.mjs
|
||||
run: node --test packages/react-native-enriched-markdown/vendor-grammars.test.mjs scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs scripts/precompress-assets.test.mjs
|
||||
|
||||
quality:
|
||||
name: quality
|
||||
@@ -68,9 +71,9 @@ jobs:
|
||||
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.format != 'false' || needs.changes.outputs.quality != 'false' || needs.changes.outputs.relay != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
@@ -87,7 +90,7 @@ jobs:
|
||||
|
||||
- name: Lint lockfile
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
|
||||
run: npx --yes lockfile-lint --path package-lock.json --type npm --allowed-hosts npm --validate-https --validate-integrity
|
||||
run: npm exec --no -- lockfile-lint --path package-lock.json --type npm --allowed-hosts npm --validate-https --validate-integrity
|
||||
|
||||
- name: Lint
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
|
||||
@@ -148,9 +151,9 @@ jobs:
|
||||
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
@@ -170,9 +173,9 @@ jobs:
|
||||
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
@@ -208,9 +211,9 @@ jobs:
|
||||
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.website != 'false') }}
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
@@ -228,7 +231,7 @@ jobs:
|
||||
# sometimes serves them at under 100 kB/s, which turns a 1-minute step into 25 minutes.
|
||||
# Keep the downloaded .deb files in the Actions cache so apt installs them without the mirror.
|
||||
- name: Restore website browser system packages
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4
|
||||
with:
|
||||
path: ~/website-browser-debs
|
||||
key: website-browser-debs-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
|
||||
@@ -252,7 +255,7 @@ jobs:
|
||||
run: npm run test:e2e --workspace=@getpaseo/website
|
||||
|
||||
- name: Upload website test artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
if: failure()
|
||||
with:
|
||||
name: website-playwright-results
|
||||
@@ -274,12 +277,12 @@ jobs:
|
||||
node -e "const os = require('node:os'); console.log(JSON.stringify({cpus: os.cpus().length, model: os.cpus()[0].model, ramGiB: os.totalmem() / 2 ** 30}))"
|
||||
|
||||
- &server_checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- &server_node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
@@ -368,9 +371,9 @@ jobs:
|
||||
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.server != 'false') }}
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
@@ -418,9 +421,9 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
steps: &desktop_test_steps
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
@@ -453,7 +456,7 @@ jobs:
|
||||
PASEO_DESKTOP_LIFECYCLE_ARTIFACT_DIR: ${{ runner.temp }}/desktop-lifecycle
|
||||
|
||||
- name: Upload desktop lifecycle screenshots
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
if: ${{ !cancelled() && runner.os == 'Linux' }}
|
||||
with:
|
||||
name: desktop-lifecycle
|
||||
@@ -476,7 +479,7 @@ jobs:
|
||||
PASEO_DESKTOP_BROWSER_E2E_ARTIFACT_DIR: ${{ runner.temp }}/desktop-browser-e2e
|
||||
|
||||
- name: Upload desktop browser diagnostics
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
if: ${{ failure() && runner.os == 'Linux' }}
|
||||
with:
|
||||
name: desktop-browser-e2e
|
||||
@@ -500,9 +503,9 @@ jobs:
|
||||
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.app != 'false') }}
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
@@ -533,9 +536,9 @@ jobs:
|
||||
run: |
|
||||
node -e "const os = require('node:os'); console.log(JSON.stringify({cpus: os.cpus().length, model: os.cpus()[0].model, ramGiB: os.totalmem() / 2 ** 30}))"
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
@@ -567,7 +570,7 @@ jobs:
|
||||
PWTEST_SHARD_WEIGHTS: "90:114:100:104:108:112:112:90"
|
||||
|
||||
- name: Upload test artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
if: failure()
|
||||
with:
|
||||
name: playwright-results-${{ env.PLAYWRIGHT_ARTIFACT }}
|
||||
@@ -658,9 +661,9 @@ jobs:
|
||||
PASEO_CLI_TEST_SHARD: "1"
|
||||
PASEO_CLI_TEST_SHARD_TOTAL: "3"
|
||||
steps: &cli_test_steps
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
@@ -14,9 +14,9 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
@@ -10,9 +10,9 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
@@ -22,9 +22,9 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
@@ -61,7 +61,7 @@ jobs:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
sparse-checkout: scripts
|
||||
ref: ${{ env.CHECKOUT_REF }}
|
||||
@@ -113,7 +113,7 @@ jobs:
|
||||
runs-on: ${{ matrix.runner }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ env.CHECKOUT_REF }}
|
||||
@@ -123,7 +123,7 @@ jobs:
|
||||
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
@@ -183,7 +183,7 @@ jobs:
|
||||
|
||||
- name: Upload packaged smoke diagnostics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: desktop-smoke-macos-${{ matrix.electron_arch }}
|
||||
path: ${{ runner.temp }}/desktop-smoke
|
||||
@@ -203,7 +203,7 @@ jobs:
|
||||
|
||||
- name: Upload desktop artifacts to workflow
|
||||
if: env.SHOULD_PUBLISH != 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: desktop-macos-${{ matrix.electron_arch }}
|
||||
path: ${{ env.DESKTOP_PACKAGE_PATH }}/release/*.dmg
|
||||
@@ -211,7 +211,7 @@ jobs:
|
||||
|
||||
- name: Upload manifest artifact
|
||||
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: mac-manifest-${{ matrix.electron_arch }}
|
||||
path: ${{ env.DESKTOP_PACKAGE_PATH }}/release/${{ env.RELEASE_CHANNEL }}-mac.yml
|
||||
@@ -226,7 +226,7 @@ jobs:
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ env.CHECKOUT_REF }}
|
||||
@@ -236,7 +236,7 @@ jobs:
|
||||
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
@@ -284,7 +284,7 @@ jobs:
|
||||
|
||||
- name: Upload packaged smoke diagnostics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: desktop-smoke-linux-x64
|
||||
path: ${{ runner.temp }}/desktop-smoke
|
||||
@@ -304,7 +304,7 @@ jobs:
|
||||
|
||||
- name: Upload desktop artifacts to workflow
|
||||
if: env.SHOULD_PUBLISH != 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: desktop-linux
|
||||
path: ${{ env.DESKTOP_PACKAGE_PATH }}/release/*
|
||||
@@ -312,7 +312,7 @@ jobs:
|
||||
|
||||
- name: Upload manifest artifact
|
||||
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: linux-manifest
|
||||
path: ${{ env.DESKTOP_PACKAGE_PATH }}/release/${{ env.RELEASE_CHANNEL }}-linux.yml
|
||||
@@ -327,7 +327,7 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ env.CHECKOUT_REF }}
|
||||
@@ -337,7 +337,7 @@ jobs:
|
||||
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
@@ -382,7 +382,7 @@ jobs:
|
||||
|
||||
- name: Upload packaged smoke diagnostics
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: desktop-smoke-windows-x64
|
||||
path: ${{ runner.temp }}/desktop-smoke
|
||||
@@ -402,7 +402,7 @@ jobs:
|
||||
|
||||
- name: Upload desktop artifacts to workflow
|
||||
if: env.SHOULD_PUBLISH != 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: desktop-windows
|
||||
path: ${{ env.DESKTOP_PACKAGE_PATH }}/release/*
|
||||
@@ -410,7 +410,7 @@ jobs:
|
||||
|
||||
- name: Upload manifest artifact
|
||||
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: windows-manifest
|
||||
path: ${{ env.DESKTOP_PACKAGE_PATH }}/release/${{ env.RELEASE_CHANNEL }}.yml
|
||||
@@ -427,7 +427,7 @@ jobs:
|
||||
cancel-in-progress: false
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
sparse-checkout: |
|
||||
package.json
|
||||
@@ -440,7 +440,7 @@ jobs:
|
||||
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
@@ -455,21 +455,21 @@ jobs:
|
||||
|
||||
- name: Download mac manifest artifacts
|
||||
if: env.IS_SMOKE_TAG != 'true' && needs.publish-macos.result == 'success'
|
||||
uses: actions/download-artifact@v4
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
|
||||
with:
|
||||
pattern: mac-manifest-*
|
||||
path: release-manifests
|
||||
|
||||
- name: Download Linux manifest artifact
|
||||
if: env.IS_SMOKE_TAG != 'true' && needs.publish-linux.result == 'success'
|
||||
uses: actions/download-artifact@v4
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
|
||||
with:
|
||||
name: linux-manifest
|
||||
path: release-manifests/linux-manifest
|
||||
|
||||
- name: Download Windows manifest artifact
|
||||
if: env.IS_SMOKE_TAG != 'true' && needs.publish-windows.result == 'success'
|
||||
uses: actions/download-artifact@v4
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
|
||||
with:
|
||||
name: windows-manifest
|
||||
path: release-manifests/windows-manifest
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
sparse-checkout: |
|
||||
package.json
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
@@ -48,7 +48,7 @@ jobs:
|
||||
check_tag: ${{ steps.values.outputs.check_tag }}
|
||||
publish_tags: ${{ steps.values.outputs.publish_tags }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
|
||||
|
||||
- id: values
|
||||
env:
|
||||
@@ -119,12 +119,12 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
|
||||
|
||||
- uses: docker/setup-qemu-action@v4
|
||||
- uses: docker/setup-buildx-action@v4
|
||||
- uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4
|
||||
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4
|
||||
|
||||
- uses: docker/build-push-action@v7
|
||||
- uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
|
||||
with:
|
||||
context: .
|
||||
file: docker/base/Dockerfile
|
||||
@@ -133,7 +133,8 @@ jobs:
|
||||
PASEO_VERSION=${{ needs.setup.outputs.install_version }}
|
||||
tags: ${{ needs.setup.outputs.check_tag }}
|
||||
push: false
|
||||
provenance: false
|
||||
# The check build does not export an image to attach attestations to.
|
||||
provenance: mode=max
|
||||
cache-from: type=gha,scope=paseo
|
||||
cache-to: type=gha,scope=paseo,mode=max
|
||||
|
||||
@@ -145,19 +146,19 @@ jobs:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
|
||||
|
||||
- uses: docker/setup-qemu-action@v4
|
||||
- uses: docker/setup-buildx-action@v4
|
||||
- uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4
|
||||
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4
|
||||
|
||||
- name: Log in to GHCR
|
||||
uses: docker/login-action@v4
|
||||
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- uses: docker/build-push-action@v7
|
||||
- uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
|
||||
with:
|
||||
context: .
|
||||
file: docker/base/Dockerfile
|
||||
@@ -166,6 +167,6 @@ jobs:
|
||||
PASEO_VERSION=${{ needs.setup.outputs.install_version }}
|
||||
tags: ${{ needs.setup.outputs.publish_tags }}
|
||||
push: true
|
||||
provenance: false
|
||||
provenance: mode=max
|
||||
cache-from: type=gha,scope=paseo
|
||||
cache-to: type=gha,scope=paseo,mode=max
|
||||
|
||||
@@ -25,23 +25,23 @@ jobs:
|
||||
update-hash:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/create-github-app-token@v1
|
||||
- uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1
|
||||
id: app-token
|
||||
with:
|
||||
app-id: ${{ secrets.PASEO_BOT_APP_ID }}
|
||||
private-key: ${{ secrets.PASEO_BOT_APP_PRIVATE_KEY }}
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
ref: ${{ github.ref }}
|
||||
token: ${{ steps.app-token.outputs.token }}
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
- uses: cachix/install-nix-action@v31
|
||||
- uses: cachix/install-nix-action@3dc140bfc76c49fbd4dd958429132e3746bcb086 # v31
|
||||
with:
|
||||
nix_path: nixpkgs=channel:nixos-unstable
|
||||
|
||||
|
||||
@@ -41,14 +41,14 @@ jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
- uses: cachix/install-nix-action@v31
|
||||
- uses: cachix/install-nix-action@3dc140bfc76c49fbd4dd958429132e3746bcb086 # v31
|
||||
with:
|
||||
nix_path: nixpkgs=channel:nixos-unstable
|
||||
|
||||
@@ -134,9 +134,9 @@ jobs:
|
||||
if: ${{ github.event_name != 'pull_request' }}
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
|
||||
- uses: cachix/install-nix-action@v31
|
||||
- uses: cachix/install-nix-action@3dc140bfc76c49fbd4dd958429132e3746bcb086 # v31
|
||||
with:
|
||||
nix_path: nixpkgs=channel:nixos-unstable
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
ARG NODE_IMAGE=node:22-bookworm-slim
|
||||
ARG NODE_IMAGE=node:22-bookworm-slim@sha256:be979e5523c76fa4d5ca4ebd3099078f220aa47ec39c48ad5b5df9314debd6eb
|
||||
FROM --platform=$BUILDPLATFORM ${NODE_IMAGE} AS source-pack
|
||||
|
||||
ARG PASEO_VERSION
|
||||
|
||||
+3
-2
@@ -216,16 +216,17 @@ not change the shipped scroll view. Keep this behavior in the app's compiled nat
|
||||
|
||||
## F-Droid / source-only Android builds
|
||||
|
||||
F-Droid builds should set `PASEO_FDROID_BUILD=1` when running Expo prebuild:
|
||||
F-Droid builds should set `PASEO_FDROID_BUILD=1` for `npm ci` (or `npm install`), Expo prebuild, and Gradle:
|
||||
|
||||
```bash
|
||||
PASEO_FDROID_BUILD=1 npm ci
|
||||
cd packages/app
|
||||
PASEO_FDROID_BUILD=1 APP_VARIANT=production npx expo prebuild --platform android --clean --non-interactive
|
||||
cd android
|
||||
PASEO_FDROID_BUILD=1 ./gradlew assembleRelease --no-daemon --max-workers=1 -Dorg.gradle.parallel=false
|
||||
```
|
||||
|
||||
The flag must be present for both prebuild and Gradle because Gradle starts Metro for the release bundle. Keep the source build serial and daemon-free as shown above: compiling every Expo module can exhaust memory when Gradle workers run in parallel. The profile enables source-built Expo modules, excludes the proprietary camera, Firebase notification, and Expo development-client native modules, disables Gradle dependency metadata, and substitutes JavaScript stubs for camera and notifications. The resulting app supports direct and pasted-link pairing but not QR scanning or push notifications.
|
||||
Setting `PASEO_FDROID_BUILD=1` during install makes `packages/react-native-enriched-markdown/postinstall.mjs` skip downloading the prebuilt iOS RaTeX XCFramework into the source tree. The flag must also be present for both prebuild and Gradle because Gradle starts Metro for the release bundle. Keep the source build serial and daemon-free as shown above: compiling every Expo module can exhaust memory when Gradle workers run in parallel. The profile enables source-built Expo modules, excludes the proprietary camera, Firebase notification, and Expo development-client native modules, disables Gradle dependency metadata, and substitutes JavaScript stubs for camera and notifications. The resulting app supports direct and pasted-link pairing but not QR scanning or push notifications. Setting `PASEO_FDROID_BUILD=1` also disables native RaTeX math in `react-native-enriched-markdown` and falls back to raw LaTeX text without requiring a Rust toolchain.
|
||||
|
||||
For a single-ABI APK, pass React Native's architecture property to Gradle:
|
||||
|
||||
|
||||
+2
-2
@@ -78,7 +78,7 @@ In the composer, the first glyph's ink starts on the text column's edge, and the
|
||||
|
||||
One gate, `resolveControlSizing`, picks touch or pointer sizing: touch when the layout is compact or touch is the primary input. An iPad with the sidebar docked is wide and touch-sized; a desktop is pointer-sized; a phone is both compact and touch. The primary input comes from `(pointer: coarse)` (`hasTouchPrimaryPointer` in `hooks/pointer-capabilities.ts`), not from whether a touch screen exists: WebKit keeps touch primary on an iPad with a trackpad attached, and Chromium reports a fine primary pointer for a laptop with a touch screen that its trackpad drives. The fact is read once at startup: attaching a pointer to a tablet does not shrink its controls, and a 2-in-1 launched with a pointer keeps pointer sizes after it switches to tablet mode until the app reloads. Stylesheets take sizes from `bySizing({ touch, pointer })`, which resolves to a breakpoint value, so a caller never sees which sizing it got. Rows, icon buttons and icon slots take theirs from `styles/density.ts`, which uses the same gate. An `{ xs, md }` literal for a hit target or glyph is wrong: on an iPad it yields the pointer size.
|
||||
|
||||
Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `<Switch>` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 where controls are touch-sized, and it takes presses over its size's control height without adding that height to its row. Buttons, text fields, dropdown triggers, and `<SegmentedControl>` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. The selected segment is a `surface3` fill with `foreground` text, not an inverted one — inverting it inside thin chrome puts a white slab in the toolbar. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use.
|
||||
Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `<Switch>` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 where controls are touch-sized, and it takes presses over its size's control height without adding that height to its row. Buttons, text fields, dropdown triggers, and `<SegmentedControl>` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. `<SegmentedControl>` sits in a recessed `surface2` pill track with an elevated active thumb (`surface3` on dark themes, `surface0` with a subtle shadow on light themes) and `foreground` text, never an inverted fill inside thin chrome. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use.
|
||||
|
||||
A `<Pressable>` wrapping a `<Text>` is a sixth variant. It is wrong. `<Button>` accepts `style`, `textStyle`, `leftIcon`, `disabled`, `size`, and `variant`.
|
||||
|
||||
@@ -96,7 +96,7 @@ A list that is itself the page content — sidebar items in `sidebar-workspace-l
|
||||
|
||||
Pane chrome — the workspace pane header, the file-explorer header, the diff pane header — uses a single bottom border to separate the header from the content (`packages/app/src/components/git-diff-pane.tsx:2328-2331`). One border, no shadow.
|
||||
|
||||
`borderAccent` is reserved for the outline button. Inputs use `border`. Single-thing borders are wrong; a single bordered element is either a card with one row (use the card) or it does not need a border.
|
||||
`borderAccent` is reserved for the outline button and resting frames like the composer. Inputs rest at `border` and step to `borderFocus` on focus. Single-thing borders are wrong; a single bordered element is either a card with one row (use the card) or it does not need a border.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ The package keeps the npm tarball's layout, including its build output:
|
||||
- `android/generated` and `ios/generated` are checked-in codegen output (`includesGeneratedCode`). A change to a native component spec regenerates both; `scripts/postinstall-patches.test.mjs` compares them against the specs.
|
||||
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`, `cpp/parser` and `cpp/wasm`. A parser change rebuilds both, or web keeps the old behavior while iOS and Android change. Run `cpp/wasm/build.sh` with `OUT_DIR` set to `src/web/wasm`, in `emscripten/emsdk:4.0.10` with the `-s GROWABLE_ARRAYBUFFERS=0` line removed. That version reproduces the committed JavaScript glue and has no such setting. The `lib/module` copy is the Babel output of the new file.
|
||||
- Upstream's Gradle, CMake and CocoaPods scripts detect upstream's own monorepo by the paths `packages/core` and a root `vendor/`. Do not add either path to this repository.
|
||||
- `postinstall.mjs` downloads the tree-sitter grammars into the ignored `cpp/highlight/vendor/grammars` and `vendor/tree-sitter`. The `enriched-markdown` block in `packages/app/package.json` chooses the languages.
|
||||
- `postinstall.mjs` downloads the tree-sitter grammars into the ignored `cpp/highlight/vendor/grammars` and `vendor/tree-sitter`, and downloads RaTeX into `ios/vendor` when `enableMath` is true (unless `PASEO_FDROID_BUILD=1`). The `enriched-markdown` block in `packages/app/package.json` chooses the languages and enables native math.
|
||||
|
||||
CI does not build native code or run the fork's Robolectric suites. Run `npm run test:android --workspace=@getpaseo/app` for Android changes. Native changes require a client rebuild; JavaScript refresh cannot enable compiled grammars.
|
||||
|
||||
@@ -46,7 +46,17 @@ Some fork changes are backports. A sync past the upstream version drops them in
|
||||
|
||||
## Engine constraints
|
||||
|
||||
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded. `<br>` becomes a Markdown hard break, except inside a table, where a newline would end the row. There it becomes U+2028, and `cpp/parser/MD4CParser.cpp` turns U+2028 back into a line break in table cell text, never in code.
|
||||
Built-in LaTeX math is enabled by default, and video is disabled. Task lists and admonitions are enabled, and task checkboxes stay read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing, and details show their summary and body expanded. `<br>` becomes a Markdown hard break, except inside a table, where a newline would end the row. There it becomes U+2028, and `cpp/parser/MD4CParser.cpp` turns U+2028 back into a line break in table cell text, never in code.
|
||||
|
||||
### LaTeX math
|
||||
|
||||
`components/markdown/math.ts` accepts `$...$`, `$$...$$`, `\(...\)`, `\[...\]`, and closed `math` fences (` ```math ` or `~~~math`). Inline `$...$` requires non-alphanumeric outer boundaries, no inner edge spaces, and no leading currency number or shell prose. Escaped `\[1, 2\]` citations, `$PATH`, regexes, and `latex` or `tex` code fences stay literal. Non-math messages skip scanning with a fast character check and do not trigger an `mdast` parse. Adapted expressions canonicalize to `$...$` or `$$...$$` for `md4c`, escape table pipes inside table rows, and flank adjacent CJK characters with hair spaces.
|
||||
|
||||
On web and Electron, `react-native-enriched-markdown` loads KaTeX (`htmlAndMathml` output with `.woff2` fonts) lazily when a document contains a math node. It caches rendered HTML in a 256-entry LRU and skips root-font overrides on `.katex` elements. Selection copy restores `[data-math-source]` to `$...$` or `$$\n...\n$$` without hidden `.katex-mathml` or `annotation` nodes. Chat Find ignores `.katex-mathml`, `annotation`, and `annotation-xml` nodes as well.
|
||||
|
||||
On iOS and Android, native views render with RaTeX (`enableMath: true` in `packages/app/package.json`). F-Droid builds (`PASEO_FDROID_BUILD=1`) disable native RaTeX in Gradle and `postinstall.mjs`, falling back to raw LaTeX. On 32-bit `x86` Android devices without `libratex_ffi.so`, the math views catch `Throwable` and render raw LaTeX text.
|
||||
|
||||
While streaming, `streaming.ts` keeps open `$$`, `\[`, and `math` fences in the unsealed tail so equations never split across blocks. Incomplete inline and display math stays withheld or literal until its closing delimiter arrives.
|
||||
|
||||
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
|
||||
|
||||
|
||||
+19
-3
@@ -433,7 +433,9 @@ query cache. Explicit SDK targets follow the [host API contract](../public-docs/
|
||||
|
||||
Workspace panels, Command Center items, and client slash commands are client contributions. The
|
||||
daemon transports their compiled bundle without interpreting placement or callbacks. Panel props
|
||||
contain workspace and agent IDs. Required-selector hooks read normalized client state synchronously
|
||||
carry `workspaceId`, validated read-only `params` (with host-enforced `agentId` on agent panels),
|
||||
`revision`, and `tab`; optional `identity(params)` sets the coalescing key on the persisted
|
||||
`plugin` target. Required-selector hooks read normalized client state synchronously
|
||||
and use shallow equality, so a panel does not subscribe to fields it does not render. Command
|
||||
callbacks materialize their snapshots only when invoked. Contribution discovery and panel opening
|
||||
never fetch active context through plugin RPC. Snapshot DTOs are deeply readonly and frozen at
|
||||
@@ -442,8 +444,8 @@ runtime so plugin code cannot mutate normalized app state or a memoized selectio
|
||||
current installed-plugin catalog. A missing contribution renders unavailable inside the tab.
|
||||
Panels declare `locations: ["workspace", "explorer"]` to opt into Explorer hosting; omission means
|
||||
workspace only. Location controls hosting, not context. An agent panel target keeps its `agentId`
|
||||
when moved between hosts. Explorer configuration can create workspace-context panels and remove
|
||||
existing agent-context instances, but it cannot create an agent panel without an agent-aware command.
|
||||
and `params` when moved between hosts. UI launchers only offer workspace-context panels whose
|
||||
`params` schema accepts `{}`.
|
||||
|
||||
`AgentChat` renders the agent tab's own chain (`AgentPanelContent` in
|
||||
`packages/app/src/panels/agent-panel.tsx`) through `packages/app/src/agent-embed`. The chain takes
|
||||
@@ -802,6 +804,20 @@ read. See the [public file panel reference](../public-docs/plugins/reference.md#
|
||||
the author API, selection, `DocumentFrame`, and the version requirement. The examples live in
|
||||
`plugin-examples/pdf-panel` and `plugin-examples/markdown-panel`.
|
||||
|
||||
## HtmlFrame
|
||||
|
||||
`HtmlFrame` (`packages/app/src/html-frame`) runs HTML in a sandboxed frame for plugins; the
|
||||
[public reference](../public-docs/plugins/reference.md#htmlframe) owns the author API. It reuses the
|
||||
file preview hardening: `file-panels/html-preview-csp.ts` builds the policy,
|
||||
`html-preview-navigation.ts` guards the native WebView. Web uses a `sandbox="allow-scripts"`
|
||||
`srcdoc` iframe verified with a per-mount bootstrap token before flushing queued host messages,
|
||||
native wraps the WebView in a sized `View` so inline auto-height frames work inside scrolling lists,
|
||||
and one bootstrap script (`bootstrap.ts`) gives the page the same `window.parent.postMessage`
|
||||
contract on both. A `srcdoc` iframe inherits its embedder's CSP. Neither the daemon's web UI
|
||||
(`web-ui.ts`), nor the desktop `paseo://` protocol handler, nor `index.html` sets one, so allowed
|
||||
CDN scripts load; a reverse proxy that adds a `Content-Security-Policy` header to the app page would
|
||||
also bind the frame and block them.
|
||||
|
||||
## Contribute buttons
|
||||
|
||||
Header buttons and composer pills share the client-only descriptor and registration lifecycle in
|
||||
|
||||
Generated
+111
-3
@@ -38,6 +38,7 @@
|
||||
"js-yaml": "^4.1.1",
|
||||
"knip": "^5.82.1",
|
||||
"lefthook": "^2.1.6",
|
||||
"lockfile-lint": "5.1.1",
|
||||
"oxfmt": "0.46.0",
|
||||
"oxlint": "1.61.0",
|
||||
"oxlint-tsgolint": "^0.22.1",
|
||||
@@ -14792,6 +14793,20 @@
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/@yarnpkg/parsers": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@yarnpkg/parsers/-/parsers-3.1.0.tgz",
|
||||
"integrity": "sha512-WoxUM/Be4hfsX06FxsvpGgfYqwgivMV7/Ol7aFuSfSmY6rRaiju4QxOEe9RUS0iYcSHWl5i9AhB1cMoE0p+XiA==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"js-yaml": "^4.3.0",
|
||||
"tslib": "^2.4.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/abab": {
|
||||
"version": "2.0.6",
|
||||
"resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz",
|
||||
@@ -17348,6 +17363,43 @@
|
||||
"layout-base": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/cosmiconfig": {
|
||||
"version": "9.0.2",
|
||||
"resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.2.tgz",
|
||||
"integrity": "sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"env-paths": "^2.2.1",
|
||||
"import-fresh": "^3.3.0",
|
||||
"js-yaml": "^4.1.0",
|
||||
"parse-json": "^5.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/d-fischer"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": ">=4.9.5"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"typescript": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/cosmiconfig/node_modules/env-paths": {
|
||||
"version": "2.2.1",
|
||||
"resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz",
|
||||
"integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/create-jest": {
|
||||
"version": "29.7.0",
|
||||
"resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz",
|
||||
@@ -25817,9 +25869,19 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/js-yaml": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
|
||||
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz",
|
||||
"integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/puzrin"
|
||||
},
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/nodeca"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"argparse": "^2.0.1"
|
||||
@@ -26810,6 +26872,41 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/lockfile-lint": {
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/lockfile-lint/-/lockfile-lint-5.1.1.tgz",
|
||||
"integrity": "sha512-GqzPAe/DvCR23Rg6vu0be+ZvpDgeri4TkTFWAQJ0MTACvWwQXah5f9kSuKyPY9Y1JRdKpQI6QOLwfdRoQezTpg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"cosmiconfig": "^9.0.0",
|
||||
"debug": "^4.3.4",
|
||||
"lockfile-lint-api": "^5.10.2",
|
||||
"tinyglobby": "^0.2.15",
|
||||
"yargs": "^17.7.2"
|
||||
},
|
||||
"bin": {
|
||||
"lockfile-lint": "bin/lockfile-lint.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lockfile-lint-api": {
|
||||
"version": "5.10.2",
|
||||
"resolved": "https://registry.npmjs.org/lockfile-lint-api/-/lockfile-lint-api-5.10.2.tgz",
|
||||
"integrity": "sha512-m3bo4ScHsfyRzysYjhtGcyaoutbg9Xe8ttR6vtGrgOSJ6qj4ryi8vWPCYy8SeG4FxvHuFM5Mfcubz/REMzaUOw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@yarnpkg/parsers": "^3.0.0-rc.48.1",
|
||||
"debug": "^4.3.4",
|
||||
"object-hash": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash": {
|
||||
"version": "4.17.23",
|
||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz",
|
||||
@@ -29965,6 +30062,16 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/object-hash": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz",
|
||||
"integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/object-inspect": {
|
||||
"version": "1.13.4",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
|
||||
@@ -37620,6 +37727,7 @@
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"htmlparser2": "^12.0.0",
|
||||
"i18next": "^26.3.0",
|
||||
"katex": "^0.16.47",
|
||||
"lucide-react-native": "^1.50.0",
|
||||
"markdown-it": "^10.0.0",
|
||||
"mdast-util-from-markdown": "2.0.3",
|
||||
|
||||
@@ -144,6 +144,7 @@
|
||||
"js-yaml": "^4.1.1",
|
||||
"knip": "^5.82.1",
|
||||
"lefthook": "^2.1.6",
|
||||
"lockfile-lint": "5.1.1",
|
||||
"oxfmt": "0.46.0",
|
||||
"oxlint": "1.61.0",
|
||||
"oxlint-tsgolint": "^0.22.1",
|
||||
|
||||
@@ -173,6 +173,29 @@ test("command center tabs rotate with Tab and never move the header", async ({ p
|
||||
await expectCommandCenterTabs(panel, ["All", "Workspaces", "Files", "Actions"]);
|
||||
});
|
||||
|
||||
await test.step("overflowing filter tabs scroll into view on narrow viewports", async () => {
|
||||
const originalViewport = page.viewportSize() ?? { width: 1280, height: 720 };
|
||||
await page.setViewportSize({ width: 280, height: 640 });
|
||||
try {
|
||||
const tabsBar = panel.getByTestId("command-center-tabs");
|
||||
const metrics = await tabsBar.evaluate((el) => ({
|
||||
scrollWidth: el.scrollWidth,
|
||||
clientWidth: el.clientWidth,
|
||||
}));
|
||||
expect(metrics.scrollWidth).toBeGreaterThan(metrics.clientWidth);
|
||||
await page.keyboard.press("Shift+Tab");
|
||||
await expectCommandCenterTab(panel, "Actions");
|
||||
const actionsTab = panel.getByTestId("command-center-tab-actions");
|
||||
await expect(actionsTab).toBeInViewport({ ratio: 1 });
|
||||
await page.keyboard.press("Tab");
|
||||
await expectCommandCenterTab(panel, "All");
|
||||
const scrollLeft = await tabsBar.evaluate((el) => el.scrollLeft);
|
||||
expect(scrollLeft).toBe(0);
|
||||
} finally {
|
||||
await page.setViewportSize(originalViewport);
|
||||
}
|
||||
});
|
||||
|
||||
await test.step("outside a workspace there is no Files tab, and Tab skips it", async () => {
|
||||
const outside = { workspaceOpen: false };
|
||||
await closeCommandCenter(page);
|
||||
|
||||
@@ -248,10 +248,10 @@ async function readSettledFrameBorder(page: Page): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
// `borderAccent` at rest, `surface4` while focused: greys in both themes, never the accent.
|
||||
// `borderAccent` at rest, `borderFocus` while focused: greys in both themes, never the accent.
|
||||
const FRAME_BORDERS = {
|
||||
dark: { rest: "rgb(47, 53, 52)", focus: "rgb(89, 91, 91)" },
|
||||
light: { rest: "rgb(236, 236, 241)", focus: "rgb(212, 212, 216)" },
|
||||
dark: { rest: "rgb(47, 53, 52)", focus: "rgb(66, 70, 69)" },
|
||||
light: { rest: "rgb(236, 236, 241)", focus: "rgb(208, 208, 213)" },
|
||||
} as const;
|
||||
|
||||
for (const colorScheme of ["dark", "light"] as const) {
|
||||
|
||||
@@ -19,7 +19,7 @@ function pluginSource(workspaceId: string, agentId: string): string {
|
||||
return `import React from "react";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
import { useWorkspace } from "@getpaseo/plugin/client";
|
||||
import { ComposerPill } from "@getpaseo/plugin/client/ui";
|
||||
import { ComposerPill, ScrollView } from "@getpaseo/plugin/client/ui";
|
||||
|
||||
function InboxScreen({ theme, params }) {
|
||||
return (
|
||||
@@ -32,7 +32,7 @@ function InboxScreen({ theme, params }) {
|
||||
function InboxPopover({ theme, layout, close, openScreen }) {
|
||||
const workspaceName = useWorkspace(${JSON.stringify(workspaceId)}, (w) => w.name);
|
||||
return (
|
||||
<View style={{ gap: 10 }}>
|
||||
<View style={{ padding: 12, gap: 10 }}>
|
||||
<Text style={{ color: theme.colors.foreground, fontSize: 16 }}>Inbox decisions</Text>
|
||||
<Text style={{ color: theme.colors.foregroundMuted }}>Workspace: {workspaceName}</Text>
|
||||
<Text style={{ color: theme.colors.foregroundMuted }}>
|
||||
@@ -56,9 +56,218 @@ function InboxPopover({ theme, layout, close, openScreen }) {
|
||||
);
|
||||
}
|
||||
|
||||
function TallDecisionsPopover({ theme, close }) {
|
||||
return (
|
||||
<View style={{ flex: 1, minHeight: 0 }}>
|
||||
<View
|
||||
testID="tall-popover-header"
|
||||
style={{
|
||||
paddingHorizontal: 14,
|
||||
paddingVertical: 12,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: theme.colors.border,
|
||||
}}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground, fontWeight: "600" }}>Open decisions</Text>
|
||||
</View>
|
||||
<ScrollView testID="tall-popover-scroll" style={{ flex: 1 }}>
|
||||
{Array.from({ length: 24 }, (_, index) => (
|
||||
<View
|
||||
key={index}
|
||||
style={{
|
||||
paddingHorizontal: 14,
|
||||
paddingVertical: 10,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: theme.colors.border,
|
||||
}}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground }}>{"Decision item " + index}</Text>
|
||||
</View>
|
||||
))}
|
||||
</ScrollView>
|
||||
<View
|
||||
testID="tall-popover-footer"
|
||||
style={{
|
||||
paddingHorizontal: 14,
|
||||
paddingVertical: 12,
|
||||
borderTopWidth: 1,
|
||||
borderTopColor: theme.colors.border,
|
||||
}}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Submit decisions"
|
||||
onPress={close}
|
||||
style={{
|
||||
paddingVertical: 8,
|
||||
paddingHorizontal: 12,
|
||||
borderRadius: 6,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground }}>Submit</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function TallDecisionsPill({ openPopover }) {
|
||||
return (
|
||||
<ComposerPill
|
||||
icon="ListChecks"
|
||||
label="All decisions"
|
||||
onPress={() => openPopover(TallDecisionsPopover)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function RevealResultsPopover({ theme, close }) {
|
||||
const [clicks, setClicks] = React.useState(0);
|
||||
const [revealed, setRevealed] = React.useState(false);
|
||||
return (
|
||||
<View style={revealed ? { flex: 1, minHeight: 0 } : { padding: 12, gap: 8 }}>
|
||||
<View
|
||||
testID="reveal-popover-header"
|
||||
style={{
|
||||
paddingHorizontal: revealed ? 14 : 0,
|
||||
paddingVertical: revealed ? 10 : 0,
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={"Reveal count: " + clicks}
|
||||
onPress={() => setClicks((count) => count + 1)}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground }}>{"Reveal count: " + clicks}</Text>
|
||||
</Pressable>
|
||||
{revealed ? null : (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Show results"
|
||||
onPress={() => setRevealed(true)}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground }}>Show results</Text>
|
||||
</Pressable>
|
||||
)}
|
||||
</View>
|
||||
{revealed ? (
|
||||
<ScrollView testID="reveal-popover-scroll" style={{ flex: 1 }}>
|
||||
{Array.from({ length: 24 }, (_, index) => (
|
||||
<View
|
||||
key={index}
|
||||
style={{
|
||||
paddingHorizontal: 14,
|
||||
paddingVertical: 10,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: theme.colors.border,
|
||||
}}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground }}>{"Result item " + index}</Text>
|
||||
</View>
|
||||
))}
|
||||
</ScrollView>
|
||||
) : null}
|
||||
<View style={{ paddingHorizontal: revealed ? 14 : 0, paddingVertical: revealed ? 10 : 0 }}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Close reveal popover"
|
||||
onPress={close}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground }}>Close results</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function RevealResultsPill({ openPopover }) {
|
||||
return (
|
||||
<ComposerPill
|
||||
icon="Search"
|
||||
label="Lazy results"
|
||||
onPress={() => openPopover(RevealResultsPopover)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FixedScrollPopover({ theme, close }) {
|
||||
const [expanded, setExpanded] = React.useState(false);
|
||||
const [extraFooterAction, setExtraFooterAction] = React.useState(false);
|
||||
const [filtered, setFiltered] = React.useState(false);
|
||||
return (
|
||||
<View style={expanded ? { flex: 1, minHeight: 0 } : undefined}>
|
||||
<View testID="fixed-scroll-header" style={{ paddingHorizontal: 14, paddingVertical: 10 }}>
|
||||
<Text style={{ color: theme.colors.foreground, fontWeight: "600" }}>Fixed viewport</Text>
|
||||
</View>
|
||||
<ScrollView testID="fixed-scroll-body" style={expanded ? { flex: 1 } : { height: 120 }}>
|
||||
{Array.from({ length: filtered ? 1 : 16 }, (_, index) => (
|
||||
<View key={index} style={{ height: 28, justifyContent: "center", paddingHorizontal: 14 }}>
|
||||
<Text style={{ color: theme.colors.foreground }}>{"Fixed row " + index}</Text>
|
||||
</View>
|
||||
))}
|
||||
</ScrollView>
|
||||
<View
|
||||
testID="fixed-scroll-footer"
|
||||
style={{ gap: 8, paddingHorizontal: 14, paddingVertical: 10 }}
|
||||
>
|
||||
<View style={{ flexDirection: "row", flexWrap: "wrap", gap: 12 }}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Filter fixed rows"
|
||||
onPress={() => setFiltered((value) => !value)}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground }}>Filter rows</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Add footer action"
|
||||
onPress={() => setExtraFooterAction((value) => !value)}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground }}>Add footer action</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Expand fixed viewport"
|
||||
onPress={() => setExpanded((value) => !value)}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground }}>
|
||||
{expanded ? "Collapse fixed" : "Expand fixed"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Close fixed viewport"
|
||||
onPress={close}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground }}>Close fixed</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
{extraFooterAction ? (
|
||||
<View testID="fixed-scroll-extra-action" style={{ height: 48, justifyContent: "center" }}>
|
||||
<Text style={{ color: theme.colors.foreground }}>Secondary footer action</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function FixedScrollPill({ openPopover }) {
|
||||
return (
|
||||
<ComposerPill
|
||||
icon="PanelTop"
|
||||
label="Fixed scroll"
|
||||
onPress={() => openPopover(FixedScrollPopover)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function LivePopover({ theme, close }) {
|
||||
return (
|
||||
<View style={{ gap: 8 }}>
|
||||
<View style={{ padding: 12, gap: 8 }}>
|
||||
<Text style={{ color: theme.colors.foreground }}>Live popover content</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
@@ -125,6 +334,9 @@ export default function contribute(client) {
|
||||
const removeQuiet = client.addComposerPillItem({ id: "quiet", title: "Quiet", Component: QuietPill });
|
||||
const removeAction = client.addComposerPillItem({ id: "action", title: "Run check", Component: ActionPill });
|
||||
const removeInbox = client.addComposerPillItem({ id: "inbox", title: "Inbox decisions", Component: InboxPill });
|
||||
const removeTall = client.addComposerPillItem({ id: "tall", title: "All decisions", Component: TallDecisionsPill });
|
||||
const removeReveal = client.addComposerPillItem({ id: "reveal", title: "Reveal results", Component: RevealResultsPill });
|
||||
const removeFixed = client.addComposerPillItem({ id: "fixed", title: "Fixed viewport", Component: FixedScrollPill });
|
||||
|
||||
const live = client.addComposerPill({
|
||||
id: "live-popover",
|
||||
@@ -183,6 +395,9 @@ export default function contribute(client) {
|
||||
removeQuiet();
|
||||
removeAction();
|
||||
removeInbox();
|
||||
removeTall();
|
||||
removeReveal();
|
||||
removeFixed();
|
||||
live.remove();
|
||||
dynamicMenu.remove();
|
||||
};
|
||||
@@ -198,13 +413,27 @@ async function runCommand(page: Page, title: string) {
|
||||
}
|
||||
|
||||
async function expectStill(subject: Locator) {
|
||||
let previous: Buffer | null = null;
|
||||
let previous: {
|
||||
buffer: Buffer;
|
||||
box: { x: number; y: number; width: number; height: number };
|
||||
} | null = null;
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const current = await subject.screenshot();
|
||||
const still = previous !== null && current.equals(previous);
|
||||
previous = current;
|
||||
const box = await subject.boundingBox();
|
||||
if (!box || box.width <= 0 || box.height <= 0) {
|
||||
previous = null;
|
||||
return false;
|
||||
}
|
||||
const buffer = await subject.screenshot();
|
||||
const still =
|
||||
previous !== null &&
|
||||
Math.abs(box.x - previous.box.x) < 0.5 &&
|
||||
Math.abs(box.y - previous.box.y) < 0.5 &&
|
||||
Math.abs(box.width - previous.box.width) < 0.5 &&
|
||||
Math.abs(box.height - previous.box.height) < 0.5 &&
|
||||
buffer.equals(previous.buffer);
|
||||
previous = { buffer, box };
|
||||
return still;
|
||||
},
|
||||
{ intervals: [150] },
|
||||
@@ -219,6 +448,173 @@ async function qaScreenshot(page: Page, name: string) {
|
||||
await page.screenshot({ path: path.join(directory, `${name}.png`) });
|
||||
}
|
||||
|
||||
async function scrollToEndAndExpectPinned(options: {
|
||||
page: Page;
|
||||
header: Locator;
|
||||
footer: Locator;
|
||||
scroll: Locator;
|
||||
bottomItemLabel: string;
|
||||
}) {
|
||||
const { page, header, footer, scroll, bottomItemLabel } = options;
|
||||
const initialHeaderY = (await header.boundingBox())!.y;
|
||||
const initialFooterY = (await footer.boundingBox())!.y;
|
||||
const canScroll = await scroll.evaluate((node) => node.scrollHeight > node.clientHeight + 1);
|
||||
expect(canScroll).toBe(true);
|
||||
await scroll.evaluate((node) => {
|
||||
node.scrollTop = node.scrollHeight;
|
||||
});
|
||||
await expect(page.getByText(bottomItemLabel, { exact: true })).toBeVisible();
|
||||
expect((await header.boundingBox())!.y).toBe(initialHeaderY);
|
||||
expect((await footer.boundingBox())!.y).toBe(initialFooterY);
|
||||
}
|
||||
|
||||
async function expectPinnedScrollableDesktopPopover(page: Page, pluginId: string) {
|
||||
const surface = page.getByTestId(`plugin-composer-pill-${pluginId}-tall-popover`);
|
||||
const header = page.getByTestId("tall-popover-header");
|
||||
const footer = page.getByTestId("tall-popover-footer");
|
||||
const scroll = page.getByTestId("tall-popover-scroll");
|
||||
|
||||
await expect(header).toBeVisible();
|
||||
await expect(footer).toBeVisible();
|
||||
await expectStill(header);
|
||||
|
||||
const surfaceBox = (await surface.boundingBox())!;
|
||||
const headerBox = (await header.boundingBox())!;
|
||||
const footerBox = (await footer.boundingBox())!;
|
||||
expect(surfaceBox.height).toBeLessThanOrEqual(441);
|
||||
// 0px outer padding (1px surface border only).
|
||||
expect(Math.abs(headerBox.y - surfaceBox.y - 1)).toBeLessThanOrEqual(1);
|
||||
expect(
|
||||
Math.abs(surfaceBox.y + surfaceBox.height - (footerBox.y + footerBox.height) - 1),
|
||||
).toBeLessThanOrEqual(1);
|
||||
|
||||
await scrollToEndAndExpectPinned({
|
||||
page,
|
||||
header,
|
||||
footer,
|
||||
scroll,
|
||||
bottomItemLabel: "Decision item 23",
|
||||
});
|
||||
}
|
||||
|
||||
async function expectPinnedScrollableCompactSheet(page: Page, pluginId: string) {
|
||||
const sheetContent = page.getByTestId(`plugin-composer-pill-${pluginId}-tall-popover-content`);
|
||||
const header = page.getByTestId("tall-popover-header");
|
||||
const footer = page.getByTestId("tall-popover-footer");
|
||||
const scroll = page.getByTestId("tall-popover-scroll");
|
||||
|
||||
await expect(sheetContent).toBeVisible();
|
||||
await expect(footer).toBeInViewport();
|
||||
await expectStill(sheetContent);
|
||||
|
||||
const sheetBox = (await sheetContent.boundingBox())!;
|
||||
const footerBox = (await footer.boundingBox())!;
|
||||
expect(sheetBox.height).toBeLessThanOrEqual(COMPACT.height * 0.8 + 1);
|
||||
expect(footerBox.y + footerBox.height).toBeLessThanOrEqual(COMPACT.height + 1);
|
||||
|
||||
await scrollToEndAndExpectPinned({
|
||||
page,
|
||||
header,
|
||||
footer,
|
||||
scroll,
|
||||
bottomItemLabel: "Decision item 23",
|
||||
});
|
||||
}
|
||||
|
||||
async function expectRevealedScrollerPreservesCompactState(page: Page, pluginId: string) {
|
||||
const revealPill = page.getByRole("button", { name: "Lazy results", exact: true });
|
||||
await expect(revealPill).toBeVisible();
|
||||
await revealPill.click();
|
||||
|
||||
const sheetContent = page.getByTestId(`plugin-composer-pill-${pluginId}-reveal-popover-content`);
|
||||
await expect(sheetContent).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Reveal count: 0", exact: true })).toBeInViewport();
|
||||
await expectStill(sheetContent);
|
||||
|
||||
await page.getByRole("button", { name: "Reveal count: 0", exact: true }).click();
|
||||
await expect(page.getByRole("button", { name: "Reveal count: 1", exact: true })).toBeVisible();
|
||||
await page.getByRole("button", { name: "Show results", exact: true }).click();
|
||||
|
||||
const scroll = page.getByTestId("reveal-popover-scroll");
|
||||
await expect(scroll).toBeVisible();
|
||||
await expectStill(sheetContent);
|
||||
// Revealing a ScrollView in an open sheet must keep plugin state mounted and cap sheet height.
|
||||
await expect(page.getByRole("button", { name: "Reveal count: 1", exact: true })).toBeVisible();
|
||||
expect((await sheetContent.boundingBox())!.height).toBeLessThanOrEqual(COMPACT.height * 0.8 + 1);
|
||||
await scroll.evaluate((node) => {
|
||||
node.scrollTop = node.scrollHeight;
|
||||
});
|
||||
await expect(page.getByText("Result item 23", { exact: true })).toBeVisible();
|
||||
|
||||
await page.getByRole("button", { name: "Close reveal popover", exact: true }).click();
|
||||
await expect(scroll).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function expectCompactSheetHugsFixedScrollPopover(page: Page, pluginId: string) {
|
||||
const fixedPill = page.getByRole("button", { name: "Fixed scroll", exact: true });
|
||||
await expect(fixedPill).toBeVisible();
|
||||
await fixedPill.click();
|
||||
|
||||
const sheetContent = page.getByTestId(`plugin-composer-pill-${pluginId}-fixed-popover-content`);
|
||||
const scroll = page.getByTestId("fixed-scroll-body");
|
||||
await expect(sheetContent).toBeVisible();
|
||||
await expect(page.getByTestId("fixed-scroll-footer")).toBeInViewport();
|
||||
await expectStill(sheetContent);
|
||||
|
||||
const sheetBox = (await sheetContent.boundingBox())!;
|
||||
const footerBox = (await page.getByTestId("fixed-scroll-footer").boundingBox())!;
|
||||
// A 120px fixed-height ScrollView with short header/footer must hug its own ~200-260px height
|
||||
// rather than expanding to the 80% sheet cap (675px).
|
||||
expect(sheetBox.height).toBeLessThan(340);
|
||||
expect(
|
||||
Math.abs(sheetBox.y + sheetBox.height - (footerBox.y + footerBox.height)),
|
||||
).toBeLessThanOrEqual(2);
|
||||
await scroll.evaluate((node) => {
|
||||
node.scrollTop = node.scrollHeight;
|
||||
});
|
||||
await expect(page.getByText("Fixed row 15", { exact: true })).toBeVisible();
|
||||
|
||||
await page.getByRole("button", { name: "Add footer action", exact: true }).click();
|
||||
await expectStill(sheetContent);
|
||||
const grownSheetBox = (await sheetContent.boundingBox())!;
|
||||
const extraActionBox = (await page.getByTestId("fixed-scroll-extra-action").boundingBox())!;
|
||||
expect(grownSheetBox.height).toBeGreaterThanOrEqual(sheetBox.height + 40);
|
||||
expect(extraActionBox.y + extraActionBox.height).toBeLessThanOrEqual(
|
||||
grownSheetBox.y + grownSheetBox.height + 2,
|
||||
);
|
||||
|
||||
await page.getByRole("button", { name: "Add footer action", exact: true }).click();
|
||||
await expectStill(sheetContent);
|
||||
|
||||
await page.getByRole("button", { name: "Filter fixed rows", exact: true }).click();
|
||||
await expectStill(sheetContent);
|
||||
const filteredBox = (await sheetContent.boundingBox())!;
|
||||
const filteredFooterBox = (await page.getByTestId("fixed-scroll-footer").boundingBox())!;
|
||||
expect(Math.abs(filteredBox.height - sheetBox.height)).toBeLessThanOrEqual(2);
|
||||
expect(
|
||||
Math.abs(filteredBox.y + filteredBox.height - (filteredFooterBox.y + filteredFooterBox.height)),
|
||||
).toBeLessThanOrEqual(2);
|
||||
|
||||
await page.getByRole("button", { name: "Filter fixed rows", exact: true }).click();
|
||||
await expectStill(sheetContent);
|
||||
|
||||
await page.getByRole("button", { name: "Expand fixed viewport", exact: true }).click();
|
||||
await expectStill(sheetContent);
|
||||
const expandedBox = (await sheetContent.boundingBox())!;
|
||||
const expandedScrollBox = (await scroll.boundingBox())!;
|
||||
expect(expandedBox.height).toBeGreaterThan(450);
|
||||
expect(expandedBox.height).toBeLessThanOrEqual(COMPACT.height * 0.8 + 2);
|
||||
expect(expandedScrollBox.height).toBeGreaterThan(300);
|
||||
|
||||
await page.getByRole("button", { name: "Expand fixed viewport", exact: true }).click();
|
||||
await expectStill(sheetContent);
|
||||
const collapsedBox = (await sheetContent.boundingBox())!;
|
||||
expect(collapsedBox.height).toBeLessThan(340);
|
||||
|
||||
await page.getByRole("button", { name: "Close fixed viewport", exact: true }).click();
|
||||
await expect(scroll).toHaveCount(0);
|
||||
}
|
||||
|
||||
test("declarative addComposerPillItem + ComposerPill and imperative pill fixes work end-to-end", async ({
|
||||
page,
|
||||
}) => {
|
||||
@@ -340,6 +736,35 @@ test("declarative addComposerPillItem + ComposerPill and imperative pill fixes w
|
||||
await page.getByRole("button", { name: "Close inbox popover", exact: true }).click();
|
||||
await expect(compactLabel).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("tall raw-canvas popover caps at <= 440px on desktop and <= 80% on compact sheet with pinned header/footer and scrolling body", async () => {
|
||||
const tallPill = page.getByRole("button", { name: "All decisions", exact: true });
|
||||
await page.setViewportSize(WIDE);
|
||||
await expect(tallPill).toBeVisible();
|
||||
await tallPill.click();
|
||||
|
||||
await expectPinnedScrollableDesktopPopover(page, PLUGIN_ID);
|
||||
await qaScreenshot(page, "05-desktop-tall-popover");
|
||||
await page.getByRole("button", { name: "Submit decisions", exact: true }).click();
|
||||
await expect(page.getByTestId("tall-popover-header")).toHaveCount(0);
|
||||
|
||||
await page.setViewportSize(COMPACT);
|
||||
await tallPill.click();
|
||||
await expectPinnedScrollableCompactSheet(page, PLUGIN_ID);
|
||||
await qaScreenshot(page, "06-compact-tall-sheet");
|
||||
await page.getByRole("button", { name: "Submit decisions", exact: true }).click();
|
||||
await expect(page.getByTestId("tall-popover-header")).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("compact raw-canvas sheet preserves plugin state when revealing a ScrollView via user action", async () => {
|
||||
await page.setViewportSize(COMPACT);
|
||||
await expectRevealedScrollerPreservesCompactState(page, PLUGIN_ID);
|
||||
});
|
||||
|
||||
await test.step("compact raw-canvas sheet hugs a fixed-height ScrollView without expanding to 80%", async () => {
|
||||
await page.setViewportSize(COMPACT);
|
||||
await expectCompactSheetHugsFixedScrollPopover(page, PLUGIN_ID);
|
||||
});
|
||||
} finally {
|
||||
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: config.config.pluginsEnabled });
|
||||
|
||||
@@ -326,3 +326,537 @@ test("a file a plugin opens in another workspace waits there on a phone", async
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const PARAMS_AND_IDENTITY_ENTRY = `import {
|
||||
type PluginClientContext,
|
||||
type PluginWorkspacePanelProps,
|
||||
useTabState,
|
||||
useWorkspaceLayout,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
import { z } from "zod";
|
||||
|
||||
const decisionParams = z.object({ decisionId: z.string() });
|
||||
const decisionStateSchema = z.object({ note: z.string() });
|
||||
|
||||
function DecisionsPanel({
|
||||
params,
|
||||
revision,
|
||||
tab,
|
||||
theme,
|
||||
}: PluginWorkspacePanelProps<z.infer<typeof decisionParams>>) {
|
||||
const [state, setState] = useTabState(tab, decisionStateSchema, { note: "initial" });
|
||||
return (
|
||||
<View style={{ flex: 1, padding: 16, gap: 8 }}>
|
||||
<Text style={{ color: theme.colors.foreground }}>
|
||||
{\`decision:\${params.decisionId}|rev:\${revision}|state:\${state.note}\`}
|
||||
</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={() => setState({ note: "pinned" })}
|
||||
>
|
||||
<Text style={{ color: theme.colors.foreground }}>Pin decision state</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const prParams = z.object({
|
||||
prNumber: z.number(),
|
||||
commentId: z.string().optional(),
|
||||
});
|
||||
|
||||
function PrPanel({
|
||||
workspaceId,
|
||||
params,
|
||||
revision,
|
||||
theme,
|
||||
}: PluginWorkspacePanelProps<z.infer<typeof prParams>>) {
|
||||
const readBack = useWorkspaceLayout(workspaceId, (layout) => {
|
||||
const found = layout.tabs.find((entry) => entry.panelId === "workspace-layout/pr" && entry.params.prNumber === params.prNumber);
|
||||
return found ? JSON.stringify(found.params) : "missing";
|
||||
});
|
||||
return (
|
||||
<View style={{ flex: 1, padding: 16, gap: 8 }}>
|
||||
<Text style={{ color: theme.colors.foreground }}>
|
||||
{\`pr:\${params.prNumber}|comment:\${params.commentId ?? "none"}|rev:\${revision}\`}
|
||||
</Text>
|
||||
<Text style={{ color: theme.colors.foregroundMuted }}>
|
||||
{\`readback:\${params.prNumber}:\${readBack}\`}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function StaticPanel({ theme }: PluginWorkspacePanelProps) {
|
||||
return (
|
||||
<View style={{ flex: 1, padding: 16 }}>
|
||||
<Text style={{ color: theme.colors.foreground }}>Static parameterless panel</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
client.addWorkspacePanel({
|
||||
id: "decisions",
|
||||
title: "Decisions",
|
||||
icon: "ListChecks",
|
||||
locations: ["explorer"],
|
||||
params: decisionParams,
|
||||
Component: DecisionsPanel,
|
||||
});
|
||||
client.addWorkspacePanel({
|
||||
id: "pr",
|
||||
title: "PR",
|
||||
icon: "GitPullRequest",
|
||||
params: prParams,
|
||||
identity: (p) => String(p.prNumber),
|
||||
Component: PrPanel,
|
||||
});
|
||||
client.addWorkspacePanel({
|
||||
id: "static",
|
||||
title: "Static",
|
||||
icon: "Square",
|
||||
locations: ["workspace", "explorer"],
|
||||
Component: StaticPanel,
|
||||
});
|
||||
|
||||
client.addCommandCenterItem({
|
||||
id: "open-decision-d1",
|
||||
title: "Open decision D1",
|
||||
icon: "ListChecks",
|
||||
context: "workspace",
|
||||
onSelect({ workspaceLayout }) {
|
||||
workspaceLayout.open({ panelId: "decisions", params: { decisionId: "D1" } });
|
||||
},
|
||||
});
|
||||
client.addCommandCenterItem({
|
||||
id: "open-decision-d2",
|
||||
title: "Open decision D2",
|
||||
icon: "ListChecks",
|
||||
context: "workspace",
|
||||
onSelect({ workspaceLayout }) {
|
||||
workspaceLayout.open({ panelId: "decisions", params: { decisionId: "D2" } });
|
||||
},
|
||||
});
|
||||
client.addCommandCenterItem({
|
||||
id: "open-pr-1a",
|
||||
title: "Open PR 1 comment a",
|
||||
icon: "GitPullRequest",
|
||||
context: "workspace",
|
||||
onSelect({ workspaceLayout }) {
|
||||
workspaceLayout.open({ panelId: "pr", params: { prNumber: 1, commentId: "a" } });
|
||||
},
|
||||
});
|
||||
client.addCommandCenterItem({
|
||||
id: "open-pr-2x",
|
||||
title: "Open PR 2 comment x",
|
||||
icon: "GitPullRequest",
|
||||
context: "workspace",
|
||||
onSelect({ workspaceLayout }) {
|
||||
workspaceLayout.open({ panelId: "pr", params: { prNumber: 2, commentId: "x" } });
|
||||
},
|
||||
});
|
||||
client.addCommandCenterItem({
|
||||
id: "open-pr-1b",
|
||||
title: "Open PR 1 comment b",
|
||||
icon: "GitPullRequest",
|
||||
context: "workspace",
|
||||
onSelect({ workspaceLayout }) {
|
||||
workspaceLayout.open({ panelId: "pr", params: { prNumber: 1, commentId: "b" } });
|
||||
},
|
||||
});
|
||||
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
async function expectNewTabLauncherPanelAvailability(
|
||||
page: Page,
|
||||
input: { present: readonly string[]; absent: readonly string[] },
|
||||
): Promise<void> {
|
||||
await mainPanes(page).first().getByTestId("workspace-new-tab-button").click();
|
||||
const menu = page.getByTestId("workspace-new-tab-menu").filter({ visible: true });
|
||||
for (const label of input.present) {
|
||||
await expect(menu.getByText(label, { exact: true })).toBeVisible();
|
||||
}
|
||||
for (const label of input.absent) {
|
||||
await expect(menu.getByText(label, { exact: true })).toHaveCount(0);
|
||||
}
|
||||
await page.keyboard.press("Escape");
|
||||
}
|
||||
|
||||
async function expectDecisionsPanel(
|
||||
page: Page,
|
||||
input: { tabs: number; decisionId: string; revision: number; stateNote: string },
|
||||
): Promise<void> {
|
||||
await expect(
|
||||
explorer(page)
|
||||
.getByTestId("workspace-tabs-row")
|
||||
.getByRole("button", { name: "Decisions", exact: true }),
|
||||
).toHaveCount(input.tabs);
|
||||
await expect(
|
||||
explorer(page).getByText(
|
||||
`decision:${input.decisionId}|rev:${input.revision}|state:${input.stateNote}`,
|
||||
{ exact: true },
|
||||
),
|
||||
).toBeVisible();
|
||||
}
|
||||
|
||||
async function pinDecisionState(page: Page): Promise<void> {
|
||||
await explorer(page).getByRole("button", { name: "Pin decision state" }).click();
|
||||
}
|
||||
|
||||
async function expectPrPanel(
|
||||
page: Page,
|
||||
input: {
|
||||
tabs: number;
|
||||
prNumber: number;
|
||||
commentId: string;
|
||||
revision: number;
|
||||
persistedParams?: { prNumber: number; commentId: string };
|
||||
},
|
||||
): Promise<void> {
|
||||
await expect(
|
||||
mainPanes(page)
|
||||
.first()
|
||||
.getByTestId("workspace-tabs-row")
|
||||
.getByRole("button", { name: "PR", exact: true }),
|
||||
).toHaveCount(input.tabs);
|
||||
await expect(
|
||||
page.getByText(`pr:${input.prNumber}|comment:${input.commentId}|rev:${input.revision}`, {
|
||||
exact: true,
|
||||
}),
|
||||
).toBeVisible();
|
||||
if (input.persistedParams) {
|
||||
await expect(
|
||||
page.getByText(`readback:${input.prNumber}:${JSON.stringify(input.persistedParams)}`, {
|
||||
exact: true,
|
||||
}),
|
||||
).toBeVisible();
|
||||
}
|
||||
}
|
||||
|
||||
test("reused Explorer panels and keyed workspace panels deliver params, identity, revision, and tab state", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
const example = await copyPluginExample("workspace-layout");
|
||||
await writeFile(path.join(example.directory, "index.client.tsx"), PARAMS_AND_IDENTITY_ENTRY);
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "plugin-params-identity-",
|
||||
title: AGENT_TITLE,
|
||||
repo: { files: REPO_FILES },
|
||||
});
|
||||
try {
|
||||
await withPluginInstalled(example.directory, async () => {
|
||||
await page.setViewportSize(WIDE);
|
||||
await openAgentRoute(page, workspace);
|
||||
await approveClientPluginsInUi(page, ["workspace-layout"]);
|
||||
|
||||
await test.step("parameterless launcher hides panels with required params and keeps parameterless ones", async () => {
|
||||
await expectNewTabLauncherPanelAvailability(page, {
|
||||
present: ["Static"],
|
||||
absent: ["PR", "Decisions"],
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("reused Explorer panel updates params in place, bumps revision, and preserves tab.state", async () => {
|
||||
await runCommand(page, "Open decision D1");
|
||||
await expectDecisionsPanel(page, {
|
||||
tabs: 1,
|
||||
decisionId: "D1",
|
||||
revision: 1,
|
||||
stateNote: "initial",
|
||||
});
|
||||
|
||||
await pinDecisionState(page);
|
||||
await expectDecisionsPanel(page, {
|
||||
tabs: 1,
|
||||
decisionId: "D1",
|
||||
revision: 1,
|
||||
stateNote: "pinned",
|
||||
});
|
||||
|
||||
await runCommand(page, "Open decision D2");
|
||||
await expectDecisionsPanel(page, {
|
||||
tabs: 1,
|
||||
decisionId: "D2",
|
||||
revision: 2,
|
||||
stateNote: "pinned",
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("keyed panel opens separate tabs per identity key and updates hint params on reveal", async () => {
|
||||
await runCommand(page, "Open PR 1 comment a");
|
||||
await expectPrPanel(page, { tabs: 1, prNumber: 1, commentId: "a", revision: 1 });
|
||||
|
||||
await runCommand(page, "Open PR 2 comment x");
|
||||
await expectPrPanel(page, { tabs: 2, prNumber: 2, commentId: "x", revision: 1 });
|
||||
|
||||
await runCommand(page, "Open PR 1 comment b");
|
||||
await expectPrPanel(page, {
|
||||
tabs: 2,
|
||||
prNumber: 1,
|
||||
commentId: "b",
|
||||
revision: 2,
|
||||
persistedParams: { prNumber: 1, commentId: "b" },
|
||||
});
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await example.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
const MIN_WIDTH_ENTRY = `import type {
|
||||
PluginAgentPanelProps,
|
||||
PluginClientContext,
|
||||
PluginFilePanelProps,
|
||||
PluginWorkspacePanelProps,
|
||||
} from "@getpaseo/plugin/client";
|
||||
import { Text, View } from "react-native";
|
||||
|
||||
function WideWorkspacePanel({ theme }: PluginWorkspacePanelProps) {
|
||||
return (
|
||||
<View style={{ flex: 1, padding: 16, backgroundColor: theme.colors.surface0 }}>
|
||||
<Text style={{ color: theme.colors.foreground }}>Wide workspace panel content</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function WideAgentPanel({ theme, params }: PluginAgentPanelProps) {
|
||||
return (
|
||||
<View style={{ flex: 1, padding: 16, backgroundColor: theme.colors.surface0 }}>
|
||||
<Text style={{ color: theme.colors.foreground }}>{\`Wide agent panel \${params.agentId}\`}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function WideSpecFilePanel({ theme, file }: PluginFilePanelProps) {
|
||||
return (
|
||||
<View style={{ flex: 1, padding: 16, backgroundColor: theme.colors.surface0 }}>
|
||||
<Text style={{ color: theme.colors.foreground }}>{\`Wide spec file \${file.name}\`}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
client.addWorkspacePanel({
|
||||
id: "wide-board",
|
||||
title: "Wide board",
|
||||
icon: "PanelsTopLeft",
|
||||
locations: ["explorer"],
|
||||
minWidth: 480,
|
||||
Component: WideWorkspacePanel,
|
||||
});
|
||||
client.addAgentPanel({
|
||||
id: "wide-review",
|
||||
title: "Wide review",
|
||||
icon: "Scan",
|
||||
locations: ["explorer"],
|
||||
minWidth: 520,
|
||||
Component: WideAgentPanel,
|
||||
});
|
||||
client.addFilePanel({
|
||||
id: "wide-spec",
|
||||
title: "Wide spec",
|
||||
icon: "FileText",
|
||||
files: { extensions: ["specfile"] },
|
||||
minWidth: 600,
|
||||
Component: WideSpecFilePanel,
|
||||
});
|
||||
|
||||
client.addCommandCenterItem({
|
||||
id: "open-wide-board",
|
||||
title: "Open wide board",
|
||||
icon: "PanelsTopLeft",
|
||||
context: "workspace",
|
||||
onSelect({ workspaceLayout }) {
|
||||
workspaceLayout.open({ panelId: "wide-board" }, { placement: { type: "explorer" } });
|
||||
},
|
||||
});
|
||||
client.addCommandCenterItem({
|
||||
id: "open-wide-review",
|
||||
title: "Open wide review",
|
||||
icon: "Scan",
|
||||
context: "agent",
|
||||
onSelect({ workspaceLayout, agent }) {
|
||||
workspaceLayout.open(
|
||||
{ panelId: "wide-review", params: { agentId: agent.id } },
|
||||
{ placement: { type: "explorer" } },
|
||||
);
|
||||
},
|
||||
});
|
||||
client.addCommandCenterItem({
|
||||
id: "open-wide-spec",
|
||||
title: "Open wide spec",
|
||||
icon: "FileText",
|
||||
context: "workspace",
|
||||
onSelect({ workspaceLayout }) {
|
||||
workspaceLayout.open(
|
||||
{ panelId: "paseo/file", params: { path: "sample.specfile" } },
|
||||
{ placement: { type: "explorer" } },
|
||||
);
|
||||
},
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
|
||||
async function expectExplorerWidth(page: Page, expected: number): Promise<void> {
|
||||
await expect
|
||||
.poll(async () => (await explorer(page).boundingBox())?.width)
|
||||
.toBeCloseTo(expected, 0);
|
||||
}
|
||||
|
||||
async function expectExplorerWidthAtMost(page: Page, max: number): Promise<void> {
|
||||
await expect
|
||||
.poll(async () => (await explorer(page).boundingBox())?.width)
|
||||
.toBeLessThanOrEqual(max);
|
||||
}
|
||||
|
||||
async function dragExplorerHandle(page: Page, deltaX: number): Promise<void> {
|
||||
const handle = page
|
||||
.getByTestId("workspace-explorer-sidebar-resize-handle")
|
||||
.getByRole("separator");
|
||||
const bounds = await handle.boundingBox();
|
||||
if (!bounds) throw new Error("Explorer resize handle is missing");
|
||||
const startX = bounds.x + bounds.width / 2;
|
||||
const startY = bounds.y + Math.min(100, bounds.height / 2);
|
||||
await page.mouse.move(startX, startY);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(startX + deltaX, startY, { steps: 10 });
|
||||
await page.mouse.up();
|
||||
}
|
||||
|
||||
test("plugin panel minWidth widens desktop Explorer non-destructively, respects body minimum, and is ignored on compact", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
const example = await copyPluginExample("workspace-layout");
|
||||
await writeFile(path.join(example.directory, "index.client.tsx"), MIN_WIDTH_ENTRY);
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "plugin-min-width-",
|
||||
title: AGENT_TITLE,
|
||||
repo: {
|
||||
files: [...REPO_FILES, { path: "sample.specfile", content: "spec v1\n" }],
|
||||
},
|
||||
});
|
||||
try {
|
||||
await withPluginInstalled(example.directory, async () => {
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await openAgentRoute(page, workspace);
|
||||
await approveClientPluginsInUi(page, ["workspace-layout"]);
|
||||
|
||||
await test.step("workspace panel minWidth: 480 widens Explorer and restores 320px on Files", async () => {
|
||||
await runCommand(page, "Open wide board");
|
||||
await expect(
|
||||
explorer(page).getByText("Wide workspace panel content", { exact: true }),
|
||||
).toBeVisible();
|
||||
await expectExplorerWidth(page, 480);
|
||||
|
||||
await explorer(page)
|
||||
.getByRole("button", { name: "Browse workspace files", exact: true })
|
||||
.click();
|
||||
await expectExplorerWidth(page, 320);
|
||||
});
|
||||
|
||||
await test.step("agent panel minWidth: 520 and file panel minWidth: 600 widen Explorer and restore 320px", async () => {
|
||||
await runCommand(page, "Open wide review");
|
||||
await expect(
|
||||
explorer(page).getByText(`Wide agent panel ${workspace.agentId}`, { exact: true }),
|
||||
).toBeVisible();
|
||||
await expectExplorerWidth(page, 520);
|
||||
|
||||
await explorer(page)
|
||||
.getByRole("button", { name: "Browse workspace files", exact: true })
|
||||
.click();
|
||||
await expectExplorerWidth(page, 320);
|
||||
|
||||
await runCommand(page, "Open wide spec");
|
||||
await page.getByRole("button", { name: "Use", exact: true }).click();
|
||||
await expect(
|
||||
explorer(page).getByText("Wide spec file sample.specfile", { exact: true }),
|
||||
).toBeVisible();
|
||||
await expectExplorerWidth(page, 600);
|
||||
|
||||
await explorer(page)
|
||||
.getByRole("button", { name: "Browse workspace files", exact: true })
|
||||
.click();
|
||||
await expectExplorerWidth(page, 320);
|
||||
});
|
||||
|
||||
await test.step("live drag clamps at minWidth and preserves dragged wider width across tabs", async () => {
|
||||
await runCommand(page, "Open wide board");
|
||||
await expectExplorerWidth(page, 480);
|
||||
|
||||
// Drag narrower -> clamps at 480 and does not overwrite default 320 on Files.
|
||||
await dragExplorerHandle(page, 120);
|
||||
await expectExplorerWidth(page, 480);
|
||||
await explorer(page)
|
||||
.getByRole("button", { name: "Browse workspace files", exact: true })
|
||||
.click();
|
||||
await expectExplorerWidth(page, 320);
|
||||
|
||||
// Drag wider to 560 -> persists 560 across Files, and minWidth: 600 still widens to 600.
|
||||
await runCommand(page, "Open wide board");
|
||||
await expectExplorerWidth(page, 480);
|
||||
await dragExplorerHandle(page, -80);
|
||||
await expectExplorerWidth(page, 560);
|
||||
await explorer(page)
|
||||
.getByRole("button", { name: "Browse workspace files", exact: true })
|
||||
.click();
|
||||
await expectExplorerWidth(page, 560);
|
||||
await explorer(page)
|
||||
.getByTestId("workspace-tabs-row")
|
||||
.getByRole("button", { name: "sample.specfile", exact: true })
|
||||
.click();
|
||||
await expectExplorerWidth(page, 600);
|
||||
await explorer(page)
|
||||
.getByRole("button", { name: "Browse workspace files", exact: true })
|
||||
.click();
|
||||
await expectExplorerWidth(page, 560);
|
||||
});
|
||||
|
||||
await test.step("narrow desktop viewport keeps at least 360px for the workspace body", async () => {
|
||||
await explorer(page)
|
||||
.getByTestId("workspace-tabs-row")
|
||||
.getByRole("button", { name: "sample.specfile", exact: true })
|
||||
.click();
|
||||
await expectExplorerWidth(page, 600);
|
||||
|
||||
await page.setViewportSize({ width: 750, height: 900 });
|
||||
await expectExplorerWidthAtMost(page, 390);
|
||||
const mainBox = await mainPanes(page).first().boundingBox();
|
||||
expect(mainBox?.width ?? 0).toBeGreaterThanOrEqual(360);
|
||||
});
|
||||
|
||||
await test.step("compact/mobile viewport ignores minWidth and renders full-width Explorer overlay", async () => {
|
||||
await page.setViewportSize(COMPACT);
|
||||
await expect(page.getByTestId("compact-shell")).toBeVisible();
|
||||
await expectMobileExplorerHidden(page);
|
||||
await page
|
||||
.getByTestId("workspace-explorer-toggle")
|
||||
.filter({ visible: true })
|
||||
.first()
|
||||
.click();
|
||||
await expectMobileExplorerVisible(page);
|
||||
await explorer(page)
|
||||
.getByTestId("workspace-tabs-row")
|
||||
.getByRole("button", { name: "Wide board", exact: true })
|
||||
.click();
|
||||
await expect(
|
||||
explorer(page).getByText("Wide workspace panel content", { exact: true }),
|
||||
).toBeVisible();
|
||||
await expectExplorerWidth(page, COMPACT.width);
|
||||
await closeMobileExplorer(page);
|
||||
await expectMobileExplorerHidden(page);
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await example.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -41,6 +41,9 @@ import {
|
||||
connectDirectHost,
|
||||
connectDirectHostExpectingPassword,
|
||||
pasteIntoDirectHost,
|
||||
pasteClipboardIntoDirectField,
|
||||
pasteIntoMiddleOfDirectHost,
|
||||
typeDirectHostCharacters,
|
||||
fillDirectHostPromptPassword,
|
||||
openCompactSettings,
|
||||
expectCompactSettingsList,
|
||||
@@ -56,6 +59,7 @@ import {
|
||||
fillDirectHostUri,
|
||||
expectDirectHostFormValues,
|
||||
expectDirectHostSslEnabled,
|
||||
expectDirectHostSslDisabled,
|
||||
fillDirectHostAddress,
|
||||
toggleDirectHostSsl,
|
||||
expectDirectHostUriValue,
|
||||
@@ -373,6 +377,110 @@ test.describe("Settings sidebar navigation", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("direct connection form smart-fills on paste without disrupting manual typing", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openAddHostFlow(page);
|
||||
await selectHostConnectionType(page, "direct");
|
||||
await expectDirectConnectionMode(page, "Form");
|
||||
|
||||
await test.step("pasting localhost:port splits Host and Port", async () => {
|
||||
await pasteClipboardIntoDirectField(page, "Host", "localhost:6768");
|
||||
await expectDirectHostFormValues(page, { host: "localhost", port: "6768", password: "" });
|
||||
await expectDirectHostSslDisabled(page);
|
||||
});
|
||||
|
||||
await test.step("pasting an https URI populates Host, Port, and Use SSL", async () => {
|
||||
await pasteClipboardIntoDirectField(page, "Host", "https://myhost.ts.net:7443/");
|
||||
await expectDirectHostFormValues(page, { host: "myhost.ts.net", port: "7443", password: "" });
|
||||
await expectDirectHostSslEnabled(page);
|
||||
});
|
||||
|
||||
await test.step("pasting a full Paseo URI populates Host, Port, Use SSL, and Password", async () => {
|
||||
await pasteClipboardIntoDirectField(
|
||||
page,
|
||||
"Host",
|
||||
"tcp://100.91.42.18:6769?ssl=false&password=my%20secret",
|
||||
);
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "100.91.42.18",
|
||||
port: "6769",
|
||||
password: "my secret",
|
||||
});
|
||||
await expectDirectHostSslDisabled(page);
|
||||
});
|
||||
|
||||
await test.step("pasting https without a port defaults Port to 443", async () => {
|
||||
await pasteClipboardIntoDirectField(page, "Host", "https://tunnel.example.test");
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "tunnel.example.test",
|
||||
port: "443",
|
||||
password: "my secret",
|
||||
});
|
||||
await expectDirectHostSslEnabled(page);
|
||||
});
|
||||
|
||||
await test.step("typing bare IPv6 and pasting into the middle of Host stay literal", async () => {
|
||||
await typeDirectHostCharacters(page, "2001:1234::1");
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "2001:1234::1",
|
||||
port: "443",
|
||||
password: "my secret",
|
||||
});
|
||||
|
||||
await pasteIntoMiddleOfDirectHost(page, "example.com", 2, "sub:9000");
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "exsub:9000ample.com",
|
||||
port: "443",
|
||||
password: "my secret",
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("pasting a tcp URI without password clears a previous host password", async () => {
|
||||
await pasteClipboardIntoDirectField(page, "Host", "tcp://second.example.test:7443");
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "second.example.test",
|
||||
port: "7443",
|
||||
password: "",
|
||||
});
|
||||
await expectDirectHostSslDisabled(page);
|
||||
});
|
||||
|
||||
await test.step("clicking Use SSL after typing an https URL keeps SSL enabled", async () => {
|
||||
await expectDirectHostSslDisabled(page);
|
||||
await typeDirectHostCharacters(page, "https://typed.example.test:7443");
|
||||
await toggleDirectHostSsl(page);
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "typed.example.test",
|
||||
port: "7443",
|
||||
password: "",
|
||||
});
|
||||
await expectDirectHostSslEnabled(page);
|
||||
});
|
||||
|
||||
await test.step("pasting a host:port into Port fills Host and Port", async () => {
|
||||
await pasteClipboardIntoDirectField(page, "Port", "hetzner.tail8a2f.ts.net:6768");
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "hetzner.tail8a2f.ts.net",
|
||||
port: "6768",
|
||||
password: "",
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("pasting a live daemon address connects cleanly", async () => {
|
||||
await pasteClipboardIntoDirectField(page, "Host", `http://127.0.0.1:${getE2EDaemonPort()}/`);
|
||||
await expectDirectHostFormValues(page, {
|
||||
host: "127.0.0.1",
|
||||
port: String(getE2EDaemonPort()),
|
||||
password: "",
|
||||
});
|
||||
await expectDirectHostSslDisabled(page);
|
||||
await connectDirectHost(page);
|
||||
});
|
||||
});
|
||||
|
||||
test("direct connection connects to a URI with Host blank", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { mkdir, mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import type { Locator, Page } from "@playwright/test";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { connectSeedClient } from "../support/helpers/seed-client";
|
||||
import {
|
||||
closeSidebarDisplayPreferences,
|
||||
openSidebarProjectFilter,
|
||||
} from "../support/helpers/sidebar";
|
||||
|
||||
const PROJECT_COUNT = 36;
|
||||
const LAST_PROJECT_NAME = `Project ${String(PROJECT_COUNT - 1).padStart(2, "0")}`;
|
||||
|
||||
interface SeededProjects {
|
||||
cleanup(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds enough projects to overflow the display-preferences popover. Each project
|
||||
* owns its own directory under one temporary parent, removed with the daemon
|
||||
* records in `cleanup`.
|
||||
*/
|
||||
async function seedManyProjects(): Promise<SeededProjects> {
|
||||
const parentDirectory = await mkdtemp(path.join(tmpdir(), "paseo-e2e-project-filter-"));
|
||||
const client = await connectSeedClient();
|
||||
try {
|
||||
const directoryPaths = Array.from({ length: PROJECT_COUNT }, (_, index) =>
|
||||
path.join(parentDirectory, `Project ${String(index).padStart(2, "0")}`),
|
||||
);
|
||||
await Promise.all(directoryPaths.map((directoryPath) => mkdir(directoryPath)));
|
||||
const addedProjectIds = await Promise.all(
|
||||
directoryPaths.map(async (directoryPath) => {
|
||||
const added = await client.addProject(directoryPath);
|
||||
if (!added.project) throw new Error(`The daemon did not add ${directoryPath}`);
|
||||
return added.project.projectId;
|
||||
}),
|
||||
);
|
||||
return {
|
||||
cleanup: async () => {
|
||||
await Promise.all(
|
||||
addedProjectIds.map((projectId) =>
|
||||
client.removeProject(projectId).catch(() => undefined),
|
||||
),
|
||||
);
|
||||
await client.close().catch(() => undefined);
|
||||
await rm(parentDirectory, { recursive: true, force: true }).catch(() => undefined);
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await client.close().catch(() => undefined);
|
||||
await rm(parentDirectory, { recursive: true, force: true }).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function projectFilterFlyout(page: Page): Locator {
|
||||
return page.getByTestId("sidebar-display-preferences-content-projectFilter");
|
||||
}
|
||||
|
||||
function viewportHeight(page: Page): number {
|
||||
const viewport = page.viewportSize();
|
||||
if (!viewport) throw new Error("The page has no viewport");
|
||||
return viewport.height;
|
||||
}
|
||||
|
||||
async function openProjectFilter(page: Page): Promise<Locator> {
|
||||
await gotoAppShell(page);
|
||||
await expect(page.getByTestId("sidebar-display-preferences-menu")).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await openSidebarProjectFilter(page);
|
||||
|
||||
const flyout = projectFilterFlyout(page);
|
||||
await expect(flyout).toBeVisible();
|
||||
// The flyout paints off-screen until it has measured its anchor and content.
|
||||
await expect.poll(async () => (await flyout.boundingBox())?.y ?? -9999).toBeGreaterThan(0);
|
||||
return flyout;
|
||||
}
|
||||
|
||||
async function requireBox(locator: Locator): Promise<{ y: number; height: number }> {
|
||||
const box = await locator.boundingBox();
|
||||
if (!box) throw new Error(`${locator.toString()} has no box`);
|
||||
return box;
|
||||
}
|
||||
|
||||
/** The flyout must sit entirely inside the window, not run past its bottom edge. */
|
||||
async function expectProjectFilterInsideWindow(flyout: Locator, height: number): Promise<void> {
|
||||
await expect(async () => {
|
||||
const box = await requireBox(flyout);
|
||||
expect(box.y).toBeGreaterThanOrEqual(0);
|
||||
expect(box.y + box.height).toBeLessThanOrEqual(height);
|
||||
expect(box.height).toBeLessThan(height);
|
||||
}).toPass({ timeout: 10_000 });
|
||||
}
|
||||
|
||||
/** The row exists in the list but starts below the visible window. */
|
||||
async function expectBelowWindow(row: Locator, height: number): Promise<void> {
|
||||
const box = await requireBox(row);
|
||||
expect(box.y).toBeGreaterThan(height);
|
||||
}
|
||||
|
||||
/** The row is reachable inside the flyout's viewport after scrolling. */
|
||||
async function expectInsideFlyout(flyout: Locator, row: Locator): Promise<void> {
|
||||
const surface = await requireBox(flyout);
|
||||
const box = await requireBox(row);
|
||||
expect(box.y).toBeGreaterThanOrEqual(surface.y);
|
||||
expect(box.y + box.height).toBeLessThanOrEqual(surface.y + surface.height + 1);
|
||||
}
|
||||
|
||||
function scrollTopOf(flyout: Locator): Promise<number | null> {
|
||||
return flyout.evaluate((root) => {
|
||||
const candidates = [root, ...Array.from(root.querySelectorAll<HTMLElement>("*"))];
|
||||
const found = candidates.find((candidate) => {
|
||||
const overflowY = getComputedStyle(candidate).overflowY;
|
||||
return (
|
||||
(overflowY === "auto" || overflowY === "scroll") &&
|
||||
candidate.scrollHeight > candidate.clientHeight + 1
|
||||
);
|
||||
});
|
||||
return found ? found.scrollTop : null;
|
||||
});
|
||||
}
|
||||
|
||||
/** Drives the flyout with the mouse wheel until the target row lands inside its viewport. */
|
||||
async function scrollToLastProject(page: Page, flyout: Locator, lastRow: Locator): Promise<void> {
|
||||
await flyout.hover();
|
||||
await expect(async () => {
|
||||
await page.mouse.wheel(0, 2_000);
|
||||
const surface = await requireBox(flyout);
|
||||
const row = await requireBox(lastRow);
|
||||
expect(row.y).toBeGreaterThanOrEqual(surface.y);
|
||||
expect(row.y + row.height).toBeLessThanOrEqual(surface.y + surface.height + 1);
|
||||
expect(await scrollTopOf(flyout)).toBeGreaterThan(0);
|
||||
}).toPass({ timeout: 10_000 });
|
||||
}
|
||||
|
||||
// #9182: with more projects than fit in the window, the project filter grew past
|
||||
// the bottom edge and had no scroll container, so the rows below the fold could
|
||||
// not be reached or toggled.
|
||||
test("the project filter stays inside the window and scrolls to its last row", async ({ page }) => {
|
||||
const projects = await seedManyProjects();
|
||||
|
||||
try {
|
||||
await page.setViewportSize({ width: 1280, height: 720 });
|
||||
const flyout = await openProjectFilter(page);
|
||||
const lastRow = flyout.getByText(LAST_PROJECT_NAME, { exact: true });
|
||||
|
||||
await test.step("the flyout fits inside the window while the last project starts below it", async () => {
|
||||
const height = viewportHeight(page);
|
||||
await expectProjectFilterInsideWindow(flyout, height);
|
||||
await expectBelowWindow(lastRow, height);
|
||||
});
|
||||
|
||||
await test.step("mouse wheel scrolling reaches the last project inside the flyout", async () => {
|
||||
await scrollToLastProject(page, flyout, lastRow);
|
||||
await expectInsideFlyout(flyout, lastRow);
|
||||
});
|
||||
|
||||
await test.step("shrinking the window keeps the flyout inside the viewport and scrollable", async () => {
|
||||
await page.setViewportSize({ width: 1280, height: 540 });
|
||||
await expectProjectFilterInsideWindow(flyout, viewportHeight(page));
|
||||
await scrollToLastProject(page, flyout, lastRow);
|
||||
await expectInsideFlyout(flyout, lastRow);
|
||||
await closeSidebarDisplayPreferences(page);
|
||||
});
|
||||
} finally {
|
||||
await projects.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -52,7 +52,7 @@ function Details({ workspaceId, theme, layout, close }) {
|
||||
const rpc = useRpc(summary);
|
||||
const query = useQuery({ queryKey: ["summary"], queryFn: () => rpc({}) });
|
||||
if (failed) throw new Error("Button content failed");
|
||||
return <View style={{ gap: 12 }}>
|
||||
return <View style={{ padding: 12, gap: 12 }}>
|
||||
<Text accessibilityLabel="Content observation" style={{ color: theme.colors.foreground }}>{ownerId}</Text>
|
||||
<Text style={{ color: theme.colors.foreground }}>Observed updates: {updates}</Text>
|
||||
<Pressable accessibilityRole="button" accessibilityLabel="Fail button content" onPress={() => setFailed(true)}><Text style={{ color: theme.colors.foreground }}>Fail content</Text></Pressable>
|
||||
|
||||
@@ -500,12 +500,11 @@ async function sampleFramesDuring(
|
||||
}
|
||||
return match;
|
||||
};
|
||||
const findOverviewCard = (tabsEl: Element | null, stacked: boolean): Element | null => {
|
||||
const findOverviewCard = (tabsEl: Element | null): Element | null => {
|
||||
if (!tabsEl) return null;
|
||||
const container = stacked
|
||||
? (tabsEl.closest('[style*="overflow"]')?.parentElement ??
|
||||
tabsEl.parentElement?.parentElement?.parentElement)
|
||||
: tabsEl.parentElement?.parentElement;
|
||||
const container =
|
||||
tabsEl.closest('[style*="overflow"]')?.parentElement ??
|
||||
tabsEl.parentElement?.parentElement?.parentElement;
|
||||
if (!container) return null;
|
||||
const visibleChildren = Array.from(container.children).filter(isVisible);
|
||||
return visibleChildren[visibleChildren.length - 1] ?? null;
|
||||
@@ -519,7 +518,7 @@ async function sampleFramesDuring(
|
||||
const skeletonEl = queryVisible('[data-testid="plugin-overview-skeleton"]');
|
||||
const licenseRect = roundRect(findVisibleText("License"));
|
||||
const relatedRect = roundRect(findVisibleText("Related plugins"));
|
||||
const overviewCard = findOverviewCard(tabsEl, stacked);
|
||||
const overviewCard = findOverviewCard(tabsEl);
|
||||
const overviewRect = roundRect(overviewCard);
|
||||
|
||||
samples.push({
|
||||
|
||||
@@ -59,7 +59,7 @@ function DeploysItem({ theme, currentScreen, openScreen }) {
|
||||
|
||||
function SyncDetails({ theme, layout, close, openScreen }) {
|
||||
return (
|
||||
<View style={{ gap: 8 }}>
|
||||
<View style={{ padding: 12, gap: 8 }}>
|
||||
<Text style={{ color: theme.colors.foreground }}>Sync details</Text>
|
||||
<Text style={{ color: theme.colors.foregroundMuted }}>Presentation: {layout.compact ? "compact" : "wide"}</Text>
|
||||
<Pressable accessibilityRole="button" accessibilityLabel="Open deploys from popover" onPress={() => openScreen({ screenId: "deploys" })}><Text style={{ color: theme.colors.foreground }}>Open deploys</Text></Pressable>
|
||||
@@ -124,7 +124,7 @@ const botMenus = {};
|
||||
function botMenu(bot) {
|
||||
botMenus[bot.id] ??= function BotMenu({ theme, close }) {
|
||||
return (
|
||||
<View style={{ gap: 8 }}>
|
||||
<View style={{ padding: 12, gap: 8 }}>
|
||||
<Text style={{ color: theme.colors.foreground }}>{bot.name + " options"}</Text>
|
||||
<Pressable accessibilityRole="button" accessibilityLabel={"Close " + bot.name + " options"} onPress={close}><Text style={{ color: theme.colors.foreground }}>Done</Text></Pressable>
|
||||
</View>
|
||||
@@ -143,7 +143,7 @@ function MoreButton({ theme, bot, onPress }) {
|
||||
|
||||
function BotStatus({ theme, close }) {
|
||||
return (
|
||||
<View style={{ gap: 8 }}>
|
||||
<View style={{ padding: 12, gap: 8 }}>
|
||||
<Text style={{ color: theme.colors.foreground }}>Bot status details</Text>
|
||||
<Pressable accessibilityRole="button" accessibilityLabel="Close bot status" onPress={close}><Text style={{ color: theme.colors.foreground }}>Done</Text></Pressable>
|
||||
</View>
|
||||
|
||||
@@ -455,6 +455,46 @@ export async function pasteIntoDirectHost(page: Page, text: string): Promise<voi
|
||||
await page.getByRole("textbox", { name: "Host", exact: true }).fill(text);
|
||||
}
|
||||
|
||||
export async function pasteClipboardIntoDirectField(
|
||||
page: Page,
|
||||
field: "Host" | "Port",
|
||||
text: string,
|
||||
options?: { replace?: boolean },
|
||||
): Promise<void> {
|
||||
const input = page.getByRole("textbox", { name: field, exact: true });
|
||||
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await page.evaluate((value) => navigator.clipboard.writeText(value), text);
|
||||
await input.click();
|
||||
if (options?.replace ?? true) {
|
||||
await page.keyboard.press("ControlOrMeta+a");
|
||||
}
|
||||
await page.keyboard.press("ControlOrMeta+v");
|
||||
}
|
||||
|
||||
export async function typeDirectHostCharacters(page: Page, text: string): Promise<void> {
|
||||
const input = page.getByRole("textbox", { name: "Host", exact: true });
|
||||
await input.click();
|
||||
await page.keyboard.press("ControlOrMeta+a");
|
||||
await page.keyboard.press("Backspace");
|
||||
await input.pressSequentially(text);
|
||||
}
|
||||
|
||||
export async function pasteIntoMiddleOfDirectHost(
|
||||
page: Page,
|
||||
initialHost: string,
|
||||
offset: number,
|
||||
pastedText: string,
|
||||
): Promise<void> {
|
||||
await typeDirectHostCharacters(page, initialHost);
|
||||
await page.keyboard.press("Home");
|
||||
for (let index = 0; index < offset; index += 1) {
|
||||
await page.keyboard.press("ArrowRight");
|
||||
}
|
||||
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await page.evaluate((value) => navigator.clipboard.writeText(value), pastedText);
|
||||
await page.keyboard.press("ControlOrMeta+v");
|
||||
}
|
||||
|
||||
export async function toggleDirectHostSsl(page: Page): Promise<void> {
|
||||
await page.getByRole("checkbox", { name: "Use SSL", exact: true }).click();
|
||||
}
|
||||
|
||||
Vendored
+4
@@ -1 +1,5 @@
|
||||
declare module "*.css";
|
||||
declare module "*.woff2" {
|
||||
const src: string;
|
||||
export default src;
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ const customWebPlatform = (process.env.PASEO_WEB_PLATFORM ?? "")
|
||||
.toLowerCase();
|
||||
|
||||
const config = getDefaultConfig(projectRoot);
|
||||
if (!config.resolver.assetExts.includes("woff2")) {
|
||||
config.resolver.assetExts.push("woff2");
|
||||
}
|
||||
config.cacheVersion = isWatchdogBuild ? "watchdog" : "standard";
|
||||
const defaultResolveRequest = config.resolver.resolveRequest ?? resolve;
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@
|
||||
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
|
||||
"build:apk": "npm --prefix ../.. run build:apk",
|
||||
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :expo-modules-core:testReleaseUnitTest --tests expo.modules.kotlin.activityresult.AppContextActivityResultRegistryRecreationTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*CodeBlockCopyButtonConstructionTest' --tests '*LongPressSelectionInterceptTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :expo-modules-core:testReleaseUnitTest --tests expo.modules.kotlin.activityresult.AppContextActivityResultRegistryRecreationTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*CodeBlockCopyButtonConstructionTest' --tests '*LongPressSelectionInterceptTest' --tests '*MathRenderingFallbackTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
@@ -110,6 +110,7 @@
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"htmlparser2": "^12.0.0",
|
||||
"i18next": "^26.3.0",
|
||||
"katex": "^0.16.47",
|
||||
"lucide-react-native": "^1.50.0",
|
||||
"markdown-it": "^10.0.0",
|
||||
"mdast-util-from-markdown": "2.0.3",
|
||||
@@ -178,7 +179,7 @@
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"enriched-markdown": {
|
||||
"enableMath": false,
|
||||
"enableMath": true,
|
||||
"enableCodeHighlight": true,
|
||||
"codeHighlightLanguages": [
|
||||
"json",
|
||||
|
||||
@@ -111,6 +111,7 @@ function ThinkingField({
|
||||
value={state.thinkingOptionId || null}
|
||||
onValueChange={onSegmentChange}
|
||||
size={controlSize}
|
||||
style={styles.thinkingControl}
|
||||
testID="agent-profile-thinking-trigger"
|
||||
/>
|
||||
</Field>
|
||||
@@ -574,6 +575,9 @@ const styles = StyleSheet.create((theme) => ({
|
||||
padding: theme.spacing[4],
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
thinkingControl: {
|
||||
alignSelf: "flex-start",
|
||||
},
|
||||
featureCardPending: {
|
||||
opacity: theme.opacity[50],
|
||||
},
|
||||
|
||||
@@ -122,3 +122,26 @@ it("keeps text around nested plugin blocks in separate occurrences", () => {
|
||||
expect(findRenderedMatches(row, "details").map((range) => range.toString())).toEqual(["details"]);
|
||||
expect(findRenderedMatches(row, "beta").map((range) => range.toString())).toEqual(["beta"]);
|
||||
});
|
||||
|
||||
it("ignores KaTeX MathML and annotations while keeping block math as a boundary", () => {
|
||||
const row = content(
|
||||
[
|
||||
"<p>Before ",
|
||||
'<span role="math" aria-label="alpha" data-display="inline" data-math-source="$alpha$">',
|
||||
'<span class="katex">',
|
||||
'<span class="katex-mathml"><math><semantics><mrow><mi>alpha</mi></mrow><annotation encoding="application/x-tex">alpha</annotation><annotation-xml encoding="MathML-Content"><ci>alpha</ci></annotation-xml></semantics></math></span>',
|
||||
'<span class="katex-html" aria-hidden="true"><span>alpha</span></span>',
|
||||
"</span>",
|
||||
"</span>",
|
||||
" after</p>",
|
||||
'<span role="math" aria-label="x^2" data-display="block" data-math-source="$$\nx^2\n$$">block fallback</span>',
|
||||
"<p>next</p>",
|
||||
].join(""),
|
||||
);
|
||||
|
||||
expect(findRenderedMatches(row, "alpha")).toEqual([]);
|
||||
expect(findRenderedMatches(row, "Before").map((range) => range.toString())).toEqual(["Before"]);
|
||||
expect(findRenderedMatches(row, "after").map((range) => range.toString())).toEqual(["after"]);
|
||||
expect(findRenderedMatches(row, "fallbacknext")).toEqual([]);
|
||||
expect(findRenderedMatches(row, "after fallbacknext")).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
const BLOCKS = ["p", "pre", "li", "td", "th", "h1", "h2", "h3", "h4", "h5", "h6"]
|
||||
.flatMap((tag) => [tag, `[data-paseo-markdown-tag="${tag}"]`])
|
||||
.join(",");
|
||||
const BLOCKS = [
|
||||
...["p", "pre", "li", "td", "th", "h1", "h2", "h3", "h4", "h5", "h6"].flatMap((tag) => [
|
||||
tag,
|
||||
`[data-paseo-markdown-tag="${tag}"]`,
|
||||
]),
|
||||
'[role="math"][data-display="block"]',
|
||||
].join(",");
|
||||
const IGNORED =
|
||||
'[data-paseo-markdown-ignore="true"], [aria-hidden="true"], button, [role="button"], svg, script, style';
|
||||
'[data-paseo-markdown-ignore="true"], [aria-hidden="true"], .katex-mathml, annotation, annotation-xml, button, [role="button"], svg, script, style';
|
||||
|
||||
/** Rendered rows carrying a source message identity, in reading order. */
|
||||
export function findMessageRows(root: HTMLElement | null, messageId: string): HTMLElement[] {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { applyRootUiFont } from "./apply-root-font.web";
|
||||
|
||||
describe("applyRootUiFont", () => {
|
||||
afterEach(() => {
|
||||
document.getElementById("paseo-ui-font")?.remove();
|
||||
document.documentElement.style.removeProperty("--paseo-ui-font");
|
||||
document.body.replaceChildren();
|
||||
});
|
||||
|
||||
it("applies the UI font to prose while excluding monospace, role=math, and KaTeX subtrees", () => {
|
||||
applyRootUiFont("'Custom UI Font', sans-serif");
|
||||
|
||||
const root = document.createElement("div");
|
||||
root.id = "root";
|
||||
root.innerHTML = `
|
||||
<p id="prose">Prose</p>
|
||||
<code data-pmono="true" style="font-family: monospace"><span id="mono">code</span></code>
|
||||
<span id="math-host" role="math" style="font-family: KaTeX_Main"><span id="katex-root" class="katex"><span id="katex-glyph">x</span></span></span>
|
||||
`;
|
||||
document.body.append(root);
|
||||
|
||||
expect(getComputedStyle(document.getElementById("prose")!).fontFamily).toContain(
|
||||
"Custom UI Font",
|
||||
);
|
||||
expect(getComputedStyle(document.getElementById("mono")!).fontFamily).not.toContain(
|
||||
"Custom UI Font",
|
||||
);
|
||||
expect(getComputedStyle(document.getElementById("math-host")!).fontFamily).not.toContain(
|
||||
"Custom UI Font",
|
||||
);
|
||||
expect(getComputedStyle(document.getElementById("katex-root")!).fontFamily).not.toContain(
|
||||
"Custom UI Font",
|
||||
);
|
||||
expect(getComputedStyle(document.getElementById("katex-glyph")!).fontFamily).not.toContain(
|
||||
"Custom UI Font",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -7,9 +7,10 @@
|
||||
// beats both RN-web's base font and Unistyles' generated classes (0,1,0) — no reliance
|
||||
// on stylesheet order. Code/diff/terminal surfaces carry `data-pmono` (and have their
|
||||
// subtree excluded via `:not([data-pmono] *)`) so they keep their monospace font.
|
||||
// KaTeX math containers carry `role="math"` and `.katex` and keep KaTeX font faces.
|
||||
const STYLE_ID = "paseo-ui-font";
|
||||
const RULE =
|
||||
":is(#root, #overlay-root) *:not([data-pmono]):not([data-pmono] *){font-family:var(--paseo-ui-font);}";
|
||||
':is(#root, #overlay-root) *:not([data-pmono]):not([data-pmono] *):not([role="math"]):not([role="math"] *):not(.katex):not(.katex *){font-family:var(--paseo-ui-font);}';
|
||||
|
||||
export function applyRootUiFont(uiFontStack: string): void {
|
||||
if (typeof document === "undefined") return;
|
||||
|
||||
@@ -997,7 +997,11 @@ describe("quote copy", () => {
|
||||
});
|
||||
|
||||
/** Renders Markdown through the web engine with the app's renderers, as a message does. */
|
||||
async function renderMarkdown(markdown: string, lastText: string): Promise<HTMLElement> {
|
||||
async function renderMarkdown(
|
||||
markdown: string,
|
||||
lastText: string,
|
||||
latexMath = false,
|
||||
): Promise<HTMLElement> {
|
||||
if (!host || !root) {
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
@@ -1017,7 +1021,7 @@ describe("quote copy", () => {
|
||||
children: h(EnrichedMarkdownText, {
|
||||
markdown,
|
||||
flavor: "github",
|
||||
md4cFlags: { latexMath: false, admonitions: true },
|
||||
md4cFlags: { latexMath, admonitions: true },
|
||||
renderers: WEB_RENDERERS,
|
||||
}),
|
||||
}),
|
||||
@@ -1135,4 +1139,102 @@ describe("quote copy", () => {
|
||||
|
||||
expect(createElementClipboardContent(quote)).toBeNull();
|
||||
});
|
||||
|
||||
it("copies rendered inline and display math inside a quote as LaTeX", async () => {
|
||||
const rendered = await renderMarkdown(
|
||||
"> Inline $E = mc^2$ and:\n>\n> $$\nx^2\n$$",
|
||||
"Inline",
|
||||
true,
|
||||
);
|
||||
await vi.waitFor(() =>
|
||||
expect(rendered.querySelectorAll(".katex").length).toBeGreaterThanOrEqual(2),
|
||||
);
|
||||
|
||||
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
|
||||
|
||||
expect(content?.plainText).toBe("Inline $E = mc^2$ and:\n\n$$\nx^2\n$$");
|
||||
});
|
||||
});
|
||||
|
||||
describe("math selection copy", () => {
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement | undefined;
|
||||
const toast: ToastApi = { show: () => () => {}, copied: () => {}, error: () => {} };
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
afterEach(() => {
|
||||
const mounted = root;
|
||||
if (mounted) flushSync(() => mounted.unmount());
|
||||
root = undefined;
|
||||
host?.remove();
|
||||
host = undefined;
|
||||
});
|
||||
|
||||
async function renderMathMarkdown(markdown: string): Promise<HTMLElement> {
|
||||
host = document.createElement("div");
|
||||
host.setAttribute("data-testid", "assistant-message");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
flushSync(() =>
|
||||
root!.render(
|
||||
h(
|
||||
QueryClientProvider,
|
||||
{ client: queryClient },
|
||||
h(
|
||||
I18nextProvider,
|
||||
{ i18n },
|
||||
h(ToastApiProvider, {
|
||||
api: toast,
|
||||
children: h(EnrichedMarkdownText, {
|
||||
markdown,
|
||||
flavor: "github",
|
||||
md4cFlags: { latexMath: true, admonitions: true },
|
||||
renderers: WEB_RENDERERS,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const rendered = host;
|
||||
await vi.waitFor(() => expect(rendered.querySelector(".katex")).not.toBeNull());
|
||||
return rendered;
|
||||
}
|
||||
|
||||
it("copies inline math as $tex$ and display math as $$\\ntex\\n$$ without leaking MathML", async () => {
|
||||
const rendered = await renderMathMarkdown(
|
||||
"Before $a_i < b_j$ after.\n\n$$\n\\frac{1}{2}\n$$\n\nEnd.",
|
||||
);
|
||||
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(rendered));
|
||||
expect(content?.plainText).toBe("Before $a_i < b_j$ after.\n\n$$\n\\frac{1}{2}\n$$\n\nEnd.");
|
||||
expect(content?.html).not.toContain("<em>");
|
||||
expect(content?.html).toContain("$a_i < b_j$");
|
||||
});
|
||||
|
||||
it("copies a standalone selected math formula as its LaTeX source", async () => {
|
||||
const rendered = await renderMathMarkdown("Equation $E = mc^2$ here.");
|
||||
const mathEl = fixtureElement(rendered, '[role="math"]');
|
||||
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(mathEl));
|
||||
expect(content?.plainText).toBe("$E = mc^2$");
|
||||
});
|
||||
|
||||
it("strips .katex-mathml, annotation, and annotation-xml on partial math selection", async () => {
|
||||
const rendered = await renderMathMarkdown("Formula $a + b + c$ end.");
|
||||
const mathmlAnnotation = fixtureElement(rendered, ".katex-mathml annotation");
|
||||
const katexHtml = fixtureElement(rendered, ".katex-html");
|
||||
const firstLeaf = tokenText(katexHtml, "a");
|
||||
const secondLeaf = tokenText(katexHtml, "b");
|
||||
|
||||
// Partial selection inside .katex-html
|
||||
const partial = copyBetween([firstLeaf, 0], [secondLeaf, 1]);
|
||||
expect(partial?.plainText).toBe("a+b");
|
||||
expect(partial?.plainText).not.toContain("a + b + c");
|
||||
|
||||
// Selection starting inside .katex-mathml annotation and ending inside .katex-html
|
||||
const crossing = copyBetween([textNode(mathmlAnnotation), 0], [secondLeaf, 1]);
|
||||
expect(crossing?.plainText).toBe("a+b");
|
||||
expect(crossing?.plainText).not.toContain("a + b + c");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type MarkdownClipboardContent,
|
||||
} from "@/utils/rich-clipboard";
|
||||
import {
|
||||
KATEX_MATHML_SELECTOR,
|
||||
MARKDOWN_ADMONITION_TITLE_ATTRIBUTE,
|
||||
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_IMAGE_SOURCES_ATTRIBUTE,
|
||||
@@ -20,6 +21,8 @@ import {
|
||||
MARKDOWN_COPY_TAG_ATTRIBUTE,
|
||||
MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE,
|
||||
MARKDOWN_COPY_UNWRAP_ATTRIBUTE,
|
||||
MARKDOWN_MATH_DISPLAY_ATTRIBUTE,
|
||||
MARKDOWN_MATH_SOURCE_ATTRIBUTE,
|
||||
TRAILING_CODE_LINE_BREAKS,
|
||||
} from "./markup";
|
||||
|
||||
@@ -106,6 +109,17 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
|
||||
return `\n\n${`[!${type}]\n${body}`.replace(/^/gm, "> ")}\n\n`;
|
||||
},
|
||||
});
|
||||
// Rendered math copies back as `$tex$` (inline) or `$$\ntex\n$$` (block).
|
||||
turndown.addRule("mathSource", {
|
||||
filter: (node) => node.hasAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE),
|
||||
replacement: (_content, node) => {
|
||||
const element = node as Element;
|
||||
const source = element.getAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE) ?? "";
|
||||
const isBlock = element.getAttribute(MARKDOWN_MATH_DISPLAY_ATTRIBUTE) === "block";
|
||||
const formatted = flavor === "markdown" ? turndown.escape(source) : source;
|
||||
return isBlock ? `\n\n${formatted}\n\n` : formatted;
|
||||
},
|
||||
});
|
||||
turndown.addRule("gfmStrikethrough", {
|
||||
filter: ["del", "s"],
|
||||
replacement: (content) => `~~${content}~~`,
|
||||
@@ -411,12 +425,19 @@ function nodeAtPath(root: Node, path: number[]): Node {
|
||||
}
|
||||
|
||||
function removeUnselectedSemantics(range: Range, source: Element, clone: Element): void {
|
||||
const selector = `[${MARKDOWN_COPY_TAG_ATTRIBUTE}], a, ${SEMANTIC_TAGS}`;
|
||||
const selector = `[${MARKDOWN_COPY_TAG_ATTRIBUTE}], [${MARKDOWN_MATH_SOURCE_ATTRIBUTE}], a, ${SEMANTIC_TAGS}`;
|
||||
const originals = Array.from(source.querySelectorAll(selector));
|
||||
const copies = Array.from(clone.querySelectorAll(selector));
|
||||
|
||||
originals.forEach((original, index) => {
|
||||
const copy = copies[index];
|
||||
if (original.hasAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE)) {
|
||||
if (copy && (!range.intersectsNode(original) || !hasSelectedAllContents(range, original))) {
|
||||
copy.removeAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE);
|
||||
copy.removeAttribute(MARKDOWN_MATH_DISPLAY_ATTRIBUTE);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (copy) copySemanticAttributes(original, copy);
|
||||
if (!copy || shouldPreserveSemanticElement(range, original)) {
|
||||
if (copy) {
|
||||
@@ -440,6 +461,9 @@ function shouldPreserveSemanticElement(range: Range, element: Element): boolean
|
||||
if (!range.intersectsNode(element)) {
|
||||
return false;
|
||||
}
|
||||
if (element.hasAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE)) {
|
||||
return hasSelectedAllContents(range, element);
|
||||
}
|
||||
const tag = semanticTag(element);
|
||||
// An image has no part to select, so touching it selects all of it.
|
||||
if (tag === "p" || tag === "img" || isTableStructure(tag)) {
|
||||
@@ -590,7 +614,9 @@ function selectsNothingOutside(range: Range, element: Element): boolean {
|
||||
|
||||
function hasMarkdownContent(fragment: DocumentFragment, includeIgnored: boolean): boolean {
|
||||
if (!includeIgnored) {
|
||||
for (const ignored of fragment.querySelectorAll(`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}]`)) {
|
||||
for (const ignored of fragment.querySelectorAll(
|
||||
`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}], ${KATEX_MATHML_SELECTOR}`,
|
||||
)) {
|
||||
ignored.remove();
|
||||
}
|
||||
}
|
||||
@@ -681,8 +707,19 @@ function selectedMessageParts(range: Range): SelectedMessagePart[] | null {
|
||||
});
|
||||
}
|
||||
|
||||
function restoreMathSources(container: HTMLElement): void {
|
||||
for (const math of container.querySelectorAll(`[${MARKDOWN_MATH_SOURCE_ATTRIBUTE}]`)) {
|
||||
const source = math.getAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE);
|
||||
if (source !== null) {
|
||||
math.textContent = source;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function restoreMarkdownElements(container: HTMLElement): void {
|
||||
for (const ignored of container.querySelectorAll(`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}]`)) {
|
||||
for (const ignored of container.querySelectorAll(
|
||||
`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}], ${KATEX_MATHML_SELECTOR}`,
|
||||
)) {
|
||||
ignored.remove();
|
||||
}
|
||||
|
||||
@@ -732,7 +769,11 @@ function restoreMarkdownElements(container: HTMLElement): void {
|
||||
element.replaceWith(...element.childNodes);
|
||||
}
|
||||
|
||||
const presentational = Array.from(container.querySelectorAll("div, span"));
|
||||
restoreMathSources(container);
|
||||
|
||||
const presentational = Array.from(
|
||||
container.querySelectorAll(`div, span:not([${MARKDOWN_MATH_SOURCE_ATTRIBUTE}])`),
|
||||
);
|
||||
for (const element of presentational.toReversed()) {
|
||||
element.replaceWith(...element.childNodes);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,10 @@ export const MARKDOWN_COPY_ALT_ATTRIBUTE = "data-paseo-markdown-alt";
|
||||
/** Set by the Markdown library's web admonition renderer on the box and on its generated title. */
|
||||
export const MARKDOWN_ADMONITION_TYPE_ATTRIBUTE = "data-enrm-admonition-type";
|
||||
export const MARKDOWN_ADMONITION_TITLE_ATTRIBUTE = "data-enrm-admonition-title";
|
||||
/** Set by the Markdown library's web KaTeX renderer on rendered math elements. */
|
||||
export const MARKDOWN_MATH_SOURCE_ATTRIBUTE = "data-math-source";
|
||||
export const MARKDOWN_MATH_DISPLAY_ATTRIBUTE = "data-display";
|
||||
export const KATEX_MATHML_SELECTOR = ".katex-mathml, annotation, annotation-xml";
|
||||
|
||||
/**
|
||||
* Trailing line breaks, with any indentation that followed the last one.
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import type { UploadedFileAttachment } from "@getpaseo/protocol/messages";
|
||||
import { collectRetainedAttachmentIds } from "@/attachments/gc-retention";
|
||||
import {
|
||||
collectRetainedAttachmentIds,
|
||||
retainAttachmentForGarbageCollection,
|
||||
} from "@/attachments/gc-retention";
|
||||
import { getAttachmentStore } from "@/attachments/store";
|
||||
import type { AttachmentMetadata, SaveAttachmentInput } from "@/attachments/types";
|
||||
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
|
||||
@@ -95,6 +98,25 @@ export async function persistAttachmentFromFileUri(input: {
|
||||
});
|
||||
}
|
||||
|
||||
export async function withRetainedAttachments<T>(
|
||||
attachments: readonly AttachmentMetadata[] | undefined,
|
||||
run: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
if (!attachments || attachments.length === 0) {
|
||||
return await run();
|
||||
}
|
||||
const releases = attachments.map((attachment) =>
|
||||
retainAttachmentForGarbageCollection(attachment.id),
|
||||
);
|
||||
try {
|
||||
return await run();
|
||||
} finally {
|
||||
for (const release of releases) {
|
||||
release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function encodeAttachmentsForSend(
|
||||
attachments: readonly AttachmentMetadata[] | undefined,
|
||||
): Promise<Array<{ data: string; mimeType: string }> | undefined> {
|
||||
@@ -102,29 +124,31 @@ export async function encodeAttachmentsForSend(
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const store = await getAttachmentStore();
|
||||
const encoded = await Promise.all(
|
||||
attachments.map(async (attachment) => {
|
||||
try {
|
||||
const data = await store.encodeBase64({ attachment });
|
||||
return {
|
||||
data,
|
||||
mimeType: attachment.mimeType,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("[attachments] Failed to encode attachment for send", {
|
||||
id: attachment.id,
|
||||
error,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return await withRetainedAttachments(attachments, async () => {
|
||||
const store = await getAttachmentStore();
|
||||
const encoded = await Promise.all(
|
||||
attachments.map(async (attachment) => {
|
||||
try {
|
||||
const data = await store.encodeBase64({ attachment });
|
||||
return {
|
||||
data,
|
||||
mimeType: attachment.mimeType,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("[attachments] Failed to encode attachment for send", {
|
||||
id: attachment.id,
|
||||
error,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const valid = encoded.filter(
|
||||
(entry): entry is { data: string; mimeType: string } => entry !== null,
|
||||
);
|
||||
return valid.length > 0 ? valid : undefined;
|
||||
const valid = encoded.filter(
|
||||
(entry): entry is { data: string; mimeType: string } => entry !== null,
|
||||
);
|
||||
return valid.length > 0 ? valid : undefined;
|
||||
});
|
||||
}
|
||||
|
||||
const DEFAULT_UPLOAD_EXTENSION_BY_MIME: Record<string, string> = {
|
||||
@@ -180,28 +204,30 @@ export async function uploadImageAttachments(input: {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const uploaded: UploadedFileAttachment[] = [];
|
||||
for (const attachment of input.images) {
|
||||
const fileName = resolveUploadedImageFileName(attachment);
|
||||
const bytes = await readAttachmentBytes(attachment);
|
||||
if (bytes.byteLength > FILE_UPLOAD_MAX_BYTES) {
|
||||
throw new Error(i18n.t("composer.errors.fileTooLarge", { size: "50MB", fileName }));
|
||||
return await withRetainedAttachments(input.images, async () => {
|
||||
const uploaded: UploadedFileAttachment[] = [];
|
||||
for (const attachment of input.images ?? []) {
|
||||
const fileName = resolveUploadedImageFileName(attachment);
|
||||
const bytes = await readAttachmentBytes(attachment);
|
||||
if (bytes.byteLength > FILE_UPLOAD_MAX_BYTES) {
|
||||
throw new Error(i18n.t("composer.errors.fileTooLarge", { size: "50MB", fileName }));
|
||||
}
|
||||
const response = await input.client.uploadFile({
|
||||
fileName,
|
||||
mimeType: attachment.mimeType,
|
||||
bytes,
|
||||
});
|
||||
if (response.error || !response.file) {
|
||||
throw new Error(response.error ?? "Upload failed.");
|
||||
}
|
||||
uploaded.push({
|
||||
...response.file,
|
||||
role: "image",
|
||||
});
|
||||
}
|
||||
const response = await input.client.uploadFile({
|
||||
fileName,
|
||||
mimeType: attachment.mimeType,
|
||||
bytes,
|
||||
});
|
||||
if (response.error || !response.file) {
|
||||
throw new Error(response.error ?? "Upload failed.");
|
||||
}
|
||||
uploaded.push({
|
||||
...response.file,
|
||||
role: "image",
|
||||
});
|
||||
}
|
||||
|
||||
return uploaded;
|
||||
return uploaded;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
type NativeScrollEvent,
|
||||
type NativeSyntheticEvent,
|
||||
type PressableStateCallbackType,
|
||||
type ScrollView as NativeScrollView,
|
||||
} from "react-native";
|
||||
import {
|
||||
memo,
|
||||
@@ -33,7 +34,7 @@ import { ArchivedBadge } from "@/components/archived-badge";
|
||||
import { StatusIcon } from "@/components/status-icon";
|
||||
import { useWorkspaceStatus } from "@/workspace-status";
|
||||
import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { SPACING, type Theme } from "@/styles/theme";
|
||||
import { HighlightedText, type HighlightedTextProps } from "@/components/ui/highlighted-text";
|
||||
import { findHighlightRanges } from "@/components/ui/highlighted-text-segments";
|
||||
import { MaterialFileIcon } from "@/components/material-file-icon";
|
||||
@@ -44,7 +45,9 @@ import {
|
||||
EditingTextInput as TextInput,
|
||||
type EditingTextInputHandle,
|
||||
} from "@/components/ui/text-input";
|
||||
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { getScrollOffsetToRevealItem } from "@/components/ui/scroll-reveal";
|
||||
import { ScrollView } from "@/components/ui/scroll-view";
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import {
|
||||
IsolatedBottomSheetModal,
|
||||
@@ -602,7 +605,7 @@ const ResultRow = memo(function ResultRow({
|
||||
active ||
|
||||
state.pressed ||
|
||||
Boolean((state as PressableStateCallbackType & { hovered?: boolean }).hovered)
|
||||
? "surface1"
|
||||
? "surfaceSelected"
|
||||
: "surface0"
|
||||
}
|
||||
/>
|
||||
@@ -1025,7 +1028,7 @@ export function CommandCenter() {
|
||||
onKeyDown: handleOverlayKeyDown,
|
||||
});
|
||||
|
||||
const tabOptions = useMemo<SegmentedControlOption<CommandCenterTab>[]>(
|
||||
const tabOptions = useMemo<CommandCenterTabOption[]>(
|
||||
() =>
|
||||
state.tabs.map((tab) => ({
|
||||
value: tab,
|
||||
@@ -1035,13 +1038,7 @@ export function CommandCenter() {
|
||||
[state.tabs, t],
|
||||
);
|
||||
const tabs = (
|
||||
<SegmentedControl
|
||||
options={tabOptions}
|
||||
value={state.tab}
|
||||
onValueChange={state.selectTab}
|
||||
size="sm"
|
||||
testID="command-center-tabs"
|
||||
/>
|
||||
<CommandCenterTabPills options={tabOptions} value={state.tab} onValueChange={state.selectTab} />
|
||||
);
|
||||
const placeholder = t(placeholderKey(state.tab, state.tabs));
|
||||
|
||||
@@ -1128,6 +1125,136 @@ export function CommandCenter() {
|
||||
);
|
||||
}
|
||||
|
||||
interface CommandCenterTabOption {
|
||||
value: CommandCenterTab;
|
||||
label: string;
|
||||
testID: string;
|
||||
}
|
||||
|
||||
function CommandCenterTabPill({
|
||||
option,
|
||||
selected,
|
||||
onSelect,
|
||||
onLayoutPill,
|
||||
}: {
|
||||
option: CommandCenterTabOption;
|
||||
selected: boolean;
|
||||
onSelect(tab: CommandCenterTab): void;
|
||||
onLayoutPill(tab: CommandCenterTab, event: LayoutChangeEvent): void;
|
||||
}) {
|
||||
const handlePress = useCallback(() => {
|
||||
if (!selected) onSelect(option.value);
|
||||
}, [onSelect, option.value, selected]);
|
||||
const handleLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => onLayoutPill(option.value, event),
|
||||
[onLayoutPill, option.value],
|
||||
);
|
||||
const accessibilityState = useMemo(() => ({ selected }), [selected]);
|
||||
return (
|
||||
<Button
|
||||
variant={selected ? "secondary" : "ghost"}
|
||||
size="sm"
|
||||
numberOfLines={1}
|
||||
accessibilityState={accessibilityState}
|
||||
aria-selected={selected}
|
||||
testID={option.testID}
|
||||
onPress={handlePress}
|
||||
onLayout={handleLayout}
|
||||
style={styles.tabPill}
|
||||
>
|
||||
{option.label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function CommandCenterTabPills({
|
||||
options,
|
||||
value,
|
||||
onValueChange,
|
||||
}: {
|
||||
options: readonly CommandCenterTabOption[];
|
||||
value: CommandCenterTab;
|
||||
onValueChange(tab: CommandCenterTab): void;
|
||||
}) {
|
||||
const scrollRef = useRef<NativeScrollView>(null);
|
||||
const viewportWidthRef = useRef(0);
|
||||
const scrollOffsetRef = useRef(0);
|
||||
const pillLayoutsRef = useRef<Partial<Record<CommandCenterTab, { x: number; width: number }>>>(
|
||||
{},
|
||||
);
|
||||
|
||||
const revealTab = useCallback((tab: CommandCenterTab) => {
|
||||
const layout = pillLayoutsRef.current[tab];
|
||||
const scroll = scrollRef.current;
|
||||
const viewportWidth = viewportWidthRef.current;
|
||||
if (!layout || !scroll || viewportWidth <= 0) return;
|
||||
const edgeMargin = SPACING[4];
|
||||
const nextOffset = getScrollOffsetToRevealItem({
|
||||
currentOffset: scrollOffsetRef.current,
|
||||
viewportHeight: Math.floor(viewportWidth),
|
||||
itemTop: Math.max(0, Math.floor(layout.x) - edgeMargin),
|
||||
itemHeight: Math.ceil(layout.width) + edgeMargin * 2,
|
||||
});
|
||||
const clampedOffset = Math.ceil(nextOffset);
|
||||
if (Math.abs(clampedOffset - scrollOffsetRef.current) < 1) return;
|
||||
scrollOffsetRef.current = clampedOffset;
|
||||
scroll.scrollTo({ x: clampedOffset, animated: false });
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
revealTab(value);
|
||||
}, [revealTab, value]);
|
||||
|
||||
const handleViewportLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
viewportWidthRef.current = event.nativeEvent.layout.width;
|
||||
revealTab(value);
|
||||
},
|
||||
[revealTab, value],
|
||||
);
|
||||
|
||||
const handlePillLayout = useCallback(
|
||||
(tab: CommandCenterTab, event: LayoutChangeEvent) => {
|
||||
const { x, width } = event.nativeEvent.layout;
|
||||
pillLayoutsRef.current[tab] = { x, width };
|
||||
if (tab === value) {
|
||||
revealTab(tab);
|
||||
}
|
||||
},
|
||||
[revealTab, value],
|
||||
);
|
||||
|
||||
const handleScroll = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
scrollOffsetRef.current = event.nativeEvent.contentOffset.x;
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
ref={scrollRef}
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
keyboardShouldPersistTaps={KEYBOARD_SHOULD_PERSIST_TAPS}
|
||||
scrollEventThrottle={16}
|
||||
onLayout={handleViewportLayout}
|
||||
onScroll={handleScroll}
|
||||
style={styles.tabScroll}
|
||||
testID="command-center-tabs"
|
||||
>
|
||||
<View style={styles.tabList}>
|
||||
{options.map((option) => (
|
||||
<CommandCenterTabPill
|
||||
key={option.value}
|
||||
option={option}
|
||||
selected={option.value === value}
|
||||
onSelect={onValueChange}
|
||||
onLayoutPill={handlePillLayout}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
function FileSearchLoadingIndicator({ loading, label }: { loading: boolean; label: string }) {
|
||||
return (
|
||||
<View style={styles.fileSearchStatus} testID="command-center-file-search-status">
|
||||
@@ -1170,12 +1297,25 @@ const styles = StyleSheet.create((theme) => ({
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: theme.colors.border,
|
||||
},
|
||||
// Below the divider, above the list. The first section label brings its own top gap, so the
|
||||
// pills sit with equal space above and below. A fixed bar, so switching tabs never moves the
|
||||
// field or the list.
|
||||
// Below the divider, above the list. Adds subtle bottom room so pills never sit glued onto
|
||||
// the first row or section header while keeping the bar fixed across tab switches.
|
||||
tabBar: {
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingTop: COMMAND_CENTER_SECTION_GAP,
|
||||
paddingBottom: theme.spacing[3],
|
||||
},
|
||||
tabScroll: {
|
||||
flexGrow: 0,
|
||||
flexShrink: 0,
|
||||
},
|
||||
tabList: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
flexShrink: 0,
|
||||
gap: theme.spacing[1],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
},
|
||||
tabPill: {
|
||||
flexShrink: 0,
|
||||
},
|
||||
input: {
|
||||
fontSize: theme.fontSize.base,
|
||||
@@ -1202,7 +1342,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: theme.colors.border,
|
||||
},
|
||||
row: { paddingHorizontal: theme.spacing[4], justifyContent: "center" },
|
||||
activeRow: { backgroundColor: theme.colors.surface1 },
|
||||
activeRow: { backgroundColor: theme.colors.surfaceSelected },
|
||||
rowContent: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
} from "@/components/ui/isolated-bottom-sheet-modal";
|
||||
import { ScrollView } from "@/components/ui/scroll-view";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { BottomSafeAreaInset } from "@/components/ui/bottom-safe-area-inset";
|
||||
import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
import { AdaptiveTextInput } from "@/components/adaptive-text-input";
|
||||
import { useDismissibleOverlay } from "@/components/ui/overlay-dismissal";
|
||||
@@ -336,17 +336,8 @@ export function SheetDragArea({ children }: { children: ReactNode }) {
|
||||
* navigation inset: it pads it once and tells its content none is left, so content that pads the
|
||||
* inset itself, like the composer dock, sits the same in a sheet as in a tab.
|
||||
*/
|
||||
export function SheetBottomInset({ style, children, ...props }: ViewProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const contentInsets = useMemo(() => ({ ...insets, bottom: 0 }), [insets]);
|
||||
const insetStyle = useMemo(() => [style, { paddingBottom: insets.bottom }], [style, insets]);
|
||||
return (
|
||||
<View {...props} style={insetStyle}>
|
||||
<SafeAreaInsetsContext.Provider value={contentInsets}>
|
||||
{children}
|
||||
</SafeAreaInsetsContext.Provider>
|
||||
</View>
|
||||
);
|
||||
export function SheetBottomInset(props: ViewProps) {
|
||||
return <BottomSafeAreaInset {...props} />;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -623,13 +623,13 @@ const styles = StyleSheet.create((theme) => ({
|
||||
marginLeft: theme.spacing[2],
|
||||
},
|
||||
rowSelected: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSelected,
|
||||
},
|
||||
rowHovered: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
backgroundColor: theme.colors.surfaceHover,
|
||||
},
|
||||
rowPressed: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSelected,
|
||||
},
|
||||
sessionTitle: {
|
||||
flexShrink: 1,
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildDirectConnectionUri, normalizeDirectConnectionHost } from "./direct-connection-host";
|
||||
import {
|
||||
buildDirectConnectionUri,
|
||||
normalizeDirectConnectionHost,
|
||||
parseDirectConnectionPaste,
|
||||
} from "./direct-connection-host";
|
||||
|
||||
const labels = {
|
||||
hostRequired: "host required",
|
||||
@@ -57,6 +61,26 @@ describe("buildDirectConnectionUri", () => {
|
||||
).toBe("tcp://example.test:443?ssl=true&password=secret");
|
||||
});
|
||||
|
||||
it("honors scheme, ssl, and password from a typed URI in Host", () => {
|
||||
expect(
|
||||
buildDirectConnectionUri(
|
||||
{
|
||||
host: "tcp://secure.example.test:7443?ssl=true&password=example",
|
||||
port: "6767",
|
||||
useTls: false,
|
||||
password: "",
|
||||
},
|
||||
labels,
|
||||
),
|
||||
).toBe("tcp://secure.example.test:7443?ssl=true&password=example");
|
||||
expect(
|
||||
buildDirectConnectionUri(
|
||||
{ host: "https://myhost.ts.net", port: "6767", useTls: false, password: "" },
|
||||
labels,
|
||||
),
|
||||
).toBe("tcp://myhost.ts.net:443?ssl=true");
|
||||
});
|
||||
|
||||
it.each(["", " ", "tcp://", "http:///path"])("requires a host for %j", (host) => {
|
||||
expect(() => buildUri(host)).toThrow("host required");
|
||||
});
|
||||
@@ -64,5 +88,102 @@ describe("buildDirectConnectionUri", () => {
|
||||
it("rejects an invalid port", () => {
|
||||
expect(() => buildUri("100.66.69.36", "70000")).toThrow("invalid port");
|
||||
expect(() => buildUri("100.66.69.36:0")).toThrow("invalid port");
|
||||
expect(() => buildUri("[::1]:0x10")).toThrow("invalid port");
|
||||
expect(() => buildUri("100.66.69.36", "0x10")).toThrow("invalid port");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseDirectConnectionPaste", () => {
|
||||
it.each([
|
||||
["localhost:6768", { host: "localhost", port: "6768" }],
|
||||
[" localhost:6768\n", { host: "localhost", port: "6768" }],
|
||||
["100.91.42.18:6767", { host: "100.91.42.18", port: "6767" }],
|
||||
["hetzner.tail8a2f.ts.net:6768", { host: "hetzner.tail8a2f.ts.net", port: "6768" }],
|
||||
["localhost:6768/", { host: "localhost", port: "6768" }],
|
||||
["localhost:6768/ws", { host: "localhost", port: "6768" }],
|
||||
["[::1]:6768", { host: "::1", port: "6768" }],
|
||||
["[fe80::1]:7000/", { host: "fe80::1", port: "7000" }],
|
||||
["[::1]", { host: "::1" }],
|
||||
["localhost/", { host: "localhost" }],
|
||||
["http://localhost:6768", { host: "localhost", port: "6768", useTls: false }],
|
||||
["http://localhost:6768/", { host: "localhost", port: "6768", useTls: false }],
|
||||
["http://myhost.ts.net", { host: "myhost.ts.net", port: "80", useTls: false }],
|
||||
["https://myhost.ts.net:6767", { host: "myhost.ts.net", port: "6767", useTls: true }],
|
||||
["https://myhost.ts.net:6767/", { host: "myhost.ts.net", port: "6767", useTls: true }],
|
||||
["HTTPS://MyHost.ts.net", { host: "MyHost.ts.net", port: "443", useTls: true }],
|
||||
["https://myhost.ts.net/", { host: "myhost.ts.net", port: "443", useTls: true }],
|
||||
["ws://localhost:6768/ws", { host: "localhost", port: "6768", useTls: false }],
|
||||
["ws://myhost.ts.net/ws", { host: "myhost.ts.net", port: "80", useTls: false }],
|
||||
["wss://myhost.ts.net:6767/ws", { host: "myhost.ts.net", port: "6767", useTls: true }],
|
||||
["wss://myhost.ts.net/ws", { host: "myhost.ts.net", port: "443", useTls: true }],
|
||||
["wss://[2001:db8::1]:7443/ws", { host: "2001:db8::1", port: "7443", useTls: true }],
|
||||
["tcp://localhost:6768", { host: "localhost", port: "6768", useTls: false, password: "" }],
|
||||
[
|
||||
"tcp://myhost.ts.net:6767?ssl=true",
|
||||
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "" },
|
||||
],
|
||||
[
|
||||
"tcp://myhost.ts.net:6767?ssl=true&password=a%26b%3Dc+d",
|
||||
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "a&b=c d" },
|
||||
],
|
||||
[
|
||||
"tcp://[::1]:7000?ssl=true&password=secret",
|
||||
{ host: "::1", port: "7000", useTls: true, password: "secret" },
|
||||
],
|
||||
["tcp://myhost.ts.net", { host: "myhost.ts.net", useTls: false, password: "" }],
|
||||
["tcp://myhost.ts.net?ssl=true", { host: "myhost.ts.net", useTls: true, password: "" }],
|
||||
[
|
||||
"https://myhost.ts.net:6767?password=pw",
|
||||
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "pw" },
|
||||
],
|
||||
[
|
||||
"https://:my%20pass@myhost.ts.net:6767",
|
||||
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "my pass" },
|
||||
],
|
||||
[
|
||||
"localhost:6768?ssl=true&password=pw",
|
||||
{ host: "localhost", port: "6768", useTls: true, password: "pw" },
|
||||
],
|
||||
])("extracts fields from %j", (input, expected) => {
|
||||
expect(parseDirectConnectionPaste(input)).toEqual(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"",
|
||||
" ",
|
||||
"localhost",
|
||||
"100.91.42.18",
|
||||
"::1",
|
||||
"fe80::1",
|
||||
"2001:db8::1",
|
||||
"localhost:0",
|
||||
"localhost:65536",
|
||||
"localhost:70000",
|
||||
"localhost:abc",
|
||||
"localhost:",
|
||||
"http://localhost:0",
|
||||
"http://localhost:70000",
|
||||
"http://localhost:abc",
|
||||
"http://localhost:",
|
||||
"tcp://localhost:abc",
|
||||
"http://",
|
||||
"https://",
|
||||
"tcp://",
|
||||
"http:///path",
|
||||
":6768",
|
||||
"[]:6768",
|
||||
"ftp://example.com:21",
|
||||
"ssh://user@host:22",
|
||||
"fe80:abcd",
|
||||
"my host:6768",
|
||||
"line1\nlocalhost:6768",
|
||||
"getpaseo/paseo",
|
||||
"alice@example.com",
|
||||
"alice@example.com/",
|
||||
"relay://relay.paseo.test:443/srv_abc?key=k",
|
||||
"https://app.paseo.sh/#connect=abc",
|
||||
"https://app.paseo.sh/#offer=abc",
|
||||
])("returns null for %j", (input) => {
|
||||
expect(parseDirectConnectionPaste(input)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,52 +19,297 @@ export interface NormalizedDirectConnectionHost {
|
||||
isIpv6: boolean;
|
||||
}
|
||||
|
||||
const SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
|
||||
const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(\d*))?$/;
|
||||
const HOST_WITH_PORT_PATTERN = /^([^:]+):(\d+)$/;
|
||||
export interface ParsedDirectConnectionAddress {
|
||||
/** Lowercased scheme without `://`, if present (e.g. "tcp", "http", "https", "ws", "wss"). */
|
||||
scheme: string | null;
|
||||
host: string;
|
||||
/** Explicit port text after `:`, if present (`""` when a trailing `:` had no port). */
|
||||
port: string | null;
|
||||
isIpv6: boolean;
|
||||
/** Path suffix starting with `/`, or empty string when omitted. */
|
||||
path: string;
|
||||
/** Password from `?password=` (or URL userinfo when query password is absent), if present. */
|
||||
password: string | null;
|
||||
/** Explicit `ssl` query flag (`"true"` / `"false"`), or null when omitted. */
|
||||
sslParam: boolean | null;
|
||||
}
|
||||
|
||||
export interface DirectConnectionPasteFields {
|
||||
host: string;
|
||||
port?: string;
|
||||
useTls?: boolean;
|
||||
password?: string;
|
||||
}
|
||||
|
||||
const SCHEME_PATTERN = /^([a-z][a-z0-9+.-]*):\/\//i;
|
||||
const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(.*))?$/;
|
||||
const DIGITS_ONLY_PATTERN = /^\d+$/;
|
||||
const DIRECT_CONNECTION_SCHEMES = new Set(["tcp", "http", "https", "ws", "wss"]);
|
||||
|
||||
export function defaultPortForDirectScheme(scheme: string | null): string | null {
|
||||
if (scheme === "https" || scheme === "wss") return "443";
|
||||
if (scheme === "http" || scheme === "ws") return "80";
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveDirectSchemeTls(
|
||||
scheme: string | null,
|
||||
sslParam: boolean | null,
|
||||
): boolean | undefined {
|
||||
if (scheme === "https" || scheme === "wss") return true;
|
||||
if (scheme === "http" || scheme === "ws") return false;
|
||||
if (scheme === "tcp") return sslParam === true;
|
||||
return sslParam ?? undefined;
|
||||
}
|
||||
|
||||
function decodeUserinfoComponent(value: string): string {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function parseSslParam(value: string | null): boolean | null {
|
||||
if (value === "true") return true;
|
||||
if (value === "false") return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseValidPortNumber(raw: string): number | null {
|
||||
if (!DIGITS_ONLY_PATTERN.test(raw)) return null;
|
||||
const port = Number(raw);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
|
||||
return port;
|
||||
}
|
||||
|
||||
function parseValidPort(raw: string): string | null {
|
||||
const port = parseValidPortNumber(raw);
|
||||
return port === null ? null : String(port);
|
||||
}
|
||||
|
||||
function stripUserinfo(
|
||||
authority: string,
|
||||
hasScheme: boolean,
|
||||
): { authority: string; password: string | null } {
|
||||
const atIndex = hasScheme ? authority.lastIndexOf("@") : -1;
|
||||
if (atIndex === -1) return { authority, password: null };
|
||||
const userinfo = authority.slice(0, atIndex);
|
||||
const hostPort = authority.slice(atIndex + 1);
|
||||
const colonIndex = userinfo.indexOf(":");
|
||||
if (colonIndex === -1) return { authority: hostPort, password: null };
|
||||
const decoded = decodeUserinfoComponent(userinfo.slice(colonIndex + 1));
|
||||
return { authority: hostPort, password: decoded || null };
|
||||
}
|
||||
|
||||
function splitAuthorityHostPort(authority: string): {
|
||||
host: string;
|
||||
port: string | null;
|
||||
isIpv6: boolean;
|
||||
} {
|
||||
const bracketed = BRACKETED_IPV6_PATTERN.exec(authority);
|
||||
if (bracketed) {
|
||||
return {
|
||||
host: bracketed[1] ?? "",
|
||||
port: bracketed[2] ?? null,
|
||||
isIpv6: true,
|
||||
};
|
||||
}
|
||||
const parts = authority.split(":");
|
||||
if (parts.length === 2) {
|
||||
return { host: parts[0] ?? "", port: parts[1] ?? "", isIpv6: false };
|
||||
}
|
||||
return { host: authority, port: null, isIpv6: parts.length > 2 };
|
||||
}
|
||||
|
||||
function hasInvalidPasteHost(host: string): boolean {
|
||||
return !host || /[\s[\]@]/.test(host);
|
||||
}
|
||||
|
||||
function resolvePastePort(address: ParsedDirectConnectionAddress): string | null | undefined {
|
||||
if (address.port !== null) return parseValidPort(address.port);
|
||||
return defaultPortForDirectScheme(address.scheme) ?? undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lenient split of a direct-connection address or URI into host, port, scheme, and credentials.
|
||||
* Keeps invalid port text intact so callers can decide whether to carry it as text or reject it.
|
||||
*/
|
||||
export function parseDirectConnectionAddress(input: string): ParsedDirectConnectionAddress {
|
||||
const trimmed = input.trim();
|
||||
if (!trimmed) {
|
||||
return {
|
||||
scheme: null,
|
||||
host: "",
|
||||
port: null,
|
||||
isIpv6: false,
|
||||
path: "",
|
||||
password: null,
|
||||
sslParam: null,
|
||||
};
|
||||
}
|
||||
|
||||
const schemeMatch = SCHEME_PATTERN.exec(trimmed);
|
||||
const scheme = schemeMatch ? (schemeMatch[1] ?? "").toLowerCase() : null;
|
||||
const rest = schemeMatch ? trimmed.slice(schemeMatch[0].length) : trimmed;
|
||||
|
||||
const hashIndex = rest.indexOf("#");
|
||||
const beforeHash = hashIndex === -1 ? rest : rest.slice(0, hashIndex);
|
||||
const queryIndex = beforeHash.indexOf("?");
|
||||
const beforeQuery = queryIndex === -1 ? beforeHash : beforeHash.slice(0, queryIndex);
|
||||
const query = new URLSearchParams(queryIndex === -1 ? "" : beforeHash.slice(queryIndex + 1));
|
||||
|
||||
const slashIndex = beforeQuery.indexOf("/");
|
||||
const rawAuthority = slashIndex === -1 ? beforeQuery : beforeQuery.slice(0, slashIndex);
|
||||
const path = slashIndex === -1 ? "" : beforeQuery.slice(slashIndex);
|
||||
|
||||
const { authority, password: userinfoPassword } = stripUserinfo(rawAuthority, scheme !== null);
|
||||
const { host, port, isIpv6 } = splitAuthorityHostPort(authority);
|
||||
|
||||
return {
|
||||
scheme,
|
||||
host,
|
||||
port,
|
||||
isIpv6,
|
||||
path,
|
||||
password: query.get("password") || userinfoPassword || null,
|
||||
sslParam: parseSslParam(query.get("ssl")),
|
||||
};
|
||||
}
|
||||
|
||||
/** The three link formats a daemon prints for pairing: `relay://`, `#connect=`, and `#offer=`. */
|
||||
export function isPairingLink(input: string): boolean {
|
||||
const trimmed = input.trim();
|
||||
return (
|
||||
trimmed.toLowerCase().startsWith("relay://") ||
|
||||
trimmed.includes("#connect=") ||
|
||||
trimmed.includes("#offer=")
|
||||
);
|
||||
}
|
||||
|
||||
function shouldNormalizeBareHostPaste(
|
||||
trimmed: string,
|
||||
address: ParsedDirectConnectionAddress,
|
||||
): boolean {
|
||||
const hasOnlyTrailingSlashes = address.path.length > 0 && /^\/+$/.test(address.path);
|
||||
if (address.path.length > 0 && !hasOnlyTrailingSlashes) return false;
|
||||
return hasOnlyTrailingSlashes || (address.isIpv6 && trimmed.startsWith("["));
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts structured Direct connection form fields from a pasted `host:port`, bracketed IPv6,
|
||||
* or supported URI (`http`, `https`, `ws`, `wss`, `tcp`). Returns `null` when the text is a plain
|
||||
* host, bare IPv6, pairing link, unsupported scheme, or contains an invalid explicit port.
|
||||
*/
|
||||
export function parseDirectConnectionPaste(input: string): DirectConnectionPasteFields | null {
|
||||
const trimmed = input.trim();
|
||||
if (!trimmed || /[\r\n]/.test(trimmed) || isPairingLink(trimmed)) return null;
|
||||
|
||||
const address = parseDirectConnectionAddress(trimmed);
|
||||
if (address.scheme !== null && !DIRECT_CONNECTION_SCHEMES.has(address.scheme)) return null;
|
||||
if (hasInvalidPasteHost(address.host)) return null;
|
||||
|
||||
const port = resolvePastePort(address);
|
||||
if (port === null) return null;
|
||||
|
||||
const useTls = resolveDirectSchemeTls(address.scheme, address.sslParam);
|
||||
// A pasted `tcp://` URI is a complete Paseo connection string: omitting `?password=` means no
|
||||
// password and clears any credential left over from a previous host.
|
||||
const password =
|
||||
address.scheme === "tcp" ? (address.password ?? "") : (address.password ?? undefined);
|
||||
|
||||
if (
|
||||
port === undefined &&
|
||||
useTls === undefined &&
|
||||
password === undefined &&
|
||||
!shouldNormalizeBareHostPaste(trimmed, address)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
host: address.host,
|
||||
...(port !== undefined ? { port } : {}),
|
||||
...(useTls !== undefined ? { useTls } : {}),
|
||||
...(password !== undefined ? { password } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export interface ResolvedDirectHostDraft {
|
||||
host: string;
|
||||
port: string;
|
||||
isIpv6: boolean;
|
||||
useTls: boolean;
|
||||
password: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a Form draft where Host may still contain a manually typed `host:port` or URI.
|
||||
* Honors explicit scheme, port, `ssl`, and `password` settings from Host while preserving
|
||||
* separate form fields for anything Host did not specify.
|
||||
*/
|
||||
export function resolveDirectHostDraft(draft: DirectConnectionHostInput): ResolvedDirectHostDraft {
|
||||
const address = parseDirectConnectionAddress(draft.host);
|
||||
const explicitPort = address.port !== null && address.port.length > 0 ? address.port : null;
|
||||
const port = (explicitPort ?? defaultPortForDirectScheme(address.scheme) ?? draft.port).trim();
|
||||
|
||||
let useTls = draft.useTls;
|
||||
if (address.scheme === "https" || address.scheme === "wss") {
|
||||
useTls = true;
|
||||
} else if (address.scheme === "http" || address.scheme === "ws") {
|
||||
useTls = false;
|
||||
} else if (address.sslParam !== null) {
|
||||
useTls = address.sslParam;
|
||||
}
|
||||
|
||||
return {
|
||||
host: address.host,
|
||||
port,
|
||||
isIpv6: address.isIpv6,
|
||||
useTls,
|
||||
password: address.password ?? draft.password,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Users often paste `host:port` or a full URL into the host field.
|
||||
* Reduce it to a bare host (plus an optional port) before building the URI.
|
||||
*/
|
||||
export function normalizeDirectConnectionHost(input: string): NormalizedDirectConnectionHost {
|
||||
let host = input.trim().replace(SCHEME_PATTERN, "");
|
||||
const suffixIndex = host.search(/[/?#]/);
|
||||
if (suffixIndex !== -1) {
|
||||
host = host.slice(0, suffixIndex);
|
||||
const address = parseDirectConnectionAddress(input);
|
||||
if (address.port !== null && !DIGITS_ONLY_PATTERN.test(address.port)) {
|
||||
if (address.isIpv6 && address.port === "") {
|
||||
return { host: address.host, port: null, isIpv6: true };
|
||||
}
|
||||
if (!address.isIpv6) {
|
||||
return { host: `${address.host}:${address.port}`, port: null, isIpv6: false };
|
||||
}
|
||||
}
|
||||
|
||||
const bracketed = BRACKETED_IPV6_PATTERN.exec(host);
|
||||
if (bracketed) {
|
||||
return { host: bracketed[1] ?? "", port: bracketed[2] || null, isIpv6: true };
|
||||
}
|
||||
|
||||
const hostWithPort = HOST_WITH_PORT_PATTERN.exec(host);
|
||||
if (hostWithPort) {
|
||||
return { host: hostWithPort[1] ?? "", port: hostWithPort[2] ?? null, isIpv6: false };
|
||||
}
|
||||
|
||||
return { host, port: null, isIpv6: host.split(":").length > 2 };
|
||||
return {
|
||||
host: address.host,
|
||||
port: address.port || null,
|
||||
isIpv6: address.isIpv6,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildDirectConnectionUri(
|
||||
draft: DirectConnectionHostInput,
|
||||
labels: DirectConnectionHostLabels,
|
||||
): string {
|
||||
const normalized = normalizeDirectConnectionHost(draft.host);
|
||||
const port = Number((normalized.port ?? draft.port).trim());
|
||||
if (!normalized.host) {
|
||||
const resolved = resolveDirectHostDraft(draft);
|
||||
if (!resolved.host) {
|
||||
throw new Error(labels.hostRequired);
|
||||
}
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
const port = parseValidPortNumber(resolved.port);
|
||||
if (port === null) {
|
||||
throw new Error(labels.invalidPort);
|
||||
}
|
||||
|
||||
return serializeConnectionUriForStorage({
|
||||
host: normalized.host,
|
||||
host: resolved.host,
|
||||
port,
|
||||
isIpv6: normalized.isIpv6,
|
||||
useTls: draft.useTls,
|
||||
...(draft.password ? { password: draft.password } : {}),
|
||||
isIpv6: resolved.isIpv6,
|
||||
useTls: resolved.useTls,
|
||||
...(resolved.password ? { password: resolved.password } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -25,6 +25,43 @@ describe("Explorer sidebar layout", () => {
|
||||
expect(resolveExplorerSidebarWidth({ requestedWidth: 600, containerWidth: 750 })).toBe(390);
|
||||
});
|
||||
|
||||
it("applies panel minWidth as a non-destructive floor capped by workspace body minimum", () => {
|
||||
// Widens default 320px to 480px
|
||||
expect(resolveExplorerSidebarWidth({ containerWidth: 1200, minWidth: 480 })).toBe(480);
|
||||
expect(
|
||||
resolveExplorerSidebarWidth({ requestedWidth: 320, containerWidth: 1200, minWidth: 480 }),
|
||||
).toBe(480);
|
||||
// Preserves wider user-saved width
|
||||
expect(
|
||||
resolveExplorerSidebarWidth({ requestedWidth: 560, containerWidth: 1200, minWidth: 480 }),
|
||||
).toBe(560);
|
||||
// Caps at containerWidth - 360 on narrow windows
|
||||
expect(
|
||||
resolveExplorerSidebarWidth({ requestedWidth: 320, containerWidth: 750, minWidth: 480 }),
|
||||
).toBe(390);
|
||||
expect(
|
||||
resolveExplorerSidebarWidth({ requestedWidth: 320, containerWidth: 500, minWidth: 480 }),
|
||||
).toBe(240);
|
||||
// Omitted or <= 240 leaves behavior identical
|
||||
expect(
|
||||
resolveExplorerSidebarWidth({
|
||||
requestedWidth: 320,
|
||||
containerWidth: 1200,
|
||||
minWidth: undefined,
|
||||
}),
|
||||
).toBe(320);
|
||||
expect(
|
||||
resolveExplorerSidebarWidth({ requestedWidth: 320, containerWidth: 1200, minWidth: 200 }),
|
||||
).toBe(320);
|
||||
expect(
|
||||
resolveExplorerSidebarWidth({ requestedWidth: 100, containerWidth: 1200, minWidth: 240 }),
|
||||
).toBe(240);
|
||||
// Dock sizes honor minWidth
|
||||
const dockSizes = resolveExplorerSidebarDockSizes({ containerWidth: 1200, minWidth: 480 });
|
||||
expect(dockSizes[1] * 1200).toBeCloseTo(480);
|
||||
expect(dockSizes[0] * 1200).toBeCloseTo(720);
|
||||
});
|
||||
|
||||
describe("native resize ownership", () => {
|
||||
const allocation = {
|
||||
width: 320,
|
||||
|
||||
@@ -6,14 +6,20 @@ export const EXPLORER_WORKSPACE_MIN_WIDTH = MIN_EXPLORER_SIDEBAR_WIDTH + MIN_WOR
|
||||
export function resolveExplorerSidebarWidth(input: {
|
||||
requestedWidth?: number;
|
||||
containerWidth: number;
|
||||
minWidth?: number;
|
||||
}): number {
|
||||
"worklet";
|
||||
const requestedWidth = input.requestedWidth ?? DEFAULT_EXPLORER_SIDEBAR_WIDTH;
|
||||
const effectiveMinWidth =
|
||||
input.minWidth !== undefined && Number.isFinite(input.minWidth) && input.minWidth > 0
|
||||
? Math.max(MIN_EXPLORER_SIDEBAR_WIDTH, input.minWidth)
|
||||
: MIN_EXPLORER_SIDEBAR_WIDTH;
|
||||
const maximumVisibleWidth =
|
||||
input.containerWidth > 0
|
||||
? Math.max(MIN_EXPLORER_SIDEBAR_WIDTH, input.containerWidth - MIN_WORKSPACE_BODY_WIDTH)
|
||||
: requestedWidth;
|
||||
return Math.max(MIN_EXPLORER_SIDEBAR_WIDTH, Math.min(maximumVisibleWidth, requestedWidth));
|
||||
: Math.max(effectiveMinWidth, requestedWidth);
|
||||
const clampedMinWidth = Math.min(maximumVisibleWidth, effectiveMinWidth);
|
||||
return Math.max(clampedMinWidth, Math.min(maximumVisibleWidth, requestedWidth));
|
||||
}
|
||||
|
||||
// A release keeps its UI width until React acknowledges it or replaces its allocation.
|
||||
@@ -98,6 +104,7 @@ export function resolveExplorerSidebarFrameWidth(
|
||||
export function resolveExplorerSidebarDockSizes(input: {
|
||||
requestedWidth?: number;
|
||||
containerWidth: number;
|
||||
minWidth?: number;
|
||||
}): number[] {
|
||||
if (input.containerWidth <= 0) {
|
||||
return [1, 0];
|
||||
|
||||
@@ -429,7 +429,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
borderRadius: theme.borderRadius.md,
|
||||
},
|
||||
rowHighlighted: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
backgroundColor: theme.colors.surfaceSelected,
|
||||
},
|
||||
hostBody: {
|
||||
flex: 1,
|
||||
|
||||
@@ -1052,10 +1052,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
},
|
||||
rowHovered: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
backgroundColor: theme.colors.surfaceHover,
|
||||
},
|
||||
rowPressed: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSelected,
|
||||
},
|
||||
rowIconWrap: {
|
||||
width: theme.iconSize.md,
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
export interface LineEnd {
|
||||
contentEnd: number;
|
||||
nextLineStart: number;
|
||||
}
|
||||
|
||||
export interface BlockquoteStrip {
|
||||
quoteDepth: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
export interface IndentMeasure {
|
||||
spaces: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
export interface ListMarkerMatch {
|
||||
markerEnd: number;
|
||||
contentIndent: number;
|
||||
markerChar: string;
|
||||
}
|
||||
|
||||
export interface FenceOpenerMatch {
|
||||
char: "`" | "~";
|
||||
length: number;
|
||||
fenceOffset: number;
|
||||
indent: number;
|
||||
info: string;
|
||||
}
|
||||
|
||||
export interface BlockScanState {
|
||||
listIndents: number[];
|
||||
listQuoteDepth: number;
|
||||
inParagraph: boolean;
|
||||
prevQuoteDepth: number;
|
||||
inIndentedCode: boolean;
|
||||
indentedCodeQuoteDepth: number;
|
||||
indentedCodeMinIndent: number;
|
||||
}
|
||||
|
||||
export type BlockLine =
|
||||
| { kind: "blank"; quoteDepth: number; afterQuotes: number }
|
||||
| { kind: "indented-code"; quoteDepth: number; afterQuotes: number }
|
||||
| {
|
||||
kind: "fence";
|
||||
quoteDepth: number;
|
||||
afterQuotes: number;
|
||||
fenceOffset: number;
|
||||
char: "`" | "~";
|
||||
length: number;
|
||||
info: string;
|
||||
maxCloseIndent: number;
|
||||
contentStripIndent: number;
|
||||
inList: boolean;
|
||||
listMinIndent: number;
|
||||
firstLinePrefix: string;
|
||||
continuationPrefix: string;
|
||||
}
|
||||
| { kind: "text"; quoteDepth: number; afterQuotes: number; containerIndent: number };
|
||||
|
||||
export function isWhitespaceChar(ch: string | undefined): boolean {
|
||||
return ch === " " || ch === "\t" || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v";
|
||||
}
|
||||
|
||||
export function isAsciiPunctuation(ch: string | undefined): boolean {
|
||||
if (!ch) return false;
|
||||
const code = ch.charCodeAt(0);
|
||||
return (
|
||||
(code >= 0x21 && code <= 0x2f) ||
|
||||
(code >= 0x3a && code <= 0x40) ||
|
||||
(code >= 0x5b && code <= 0x60) ||
|
||||
(code >= 0x7b && code <= 0x7e)
|
||||
);
|
||||
}
|
||||
|
||||
export function isAsciiAlnum(ch: string | undefined): boolean {
|
||||
if (!ch) return false;
|
||||
const code = ch.charCodeAt(0);
|
||||
return (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
|
||||
}
|
||||
|
||||
export function findLineEnd(source: string, from: number): LineEnd {
|
||||
let i = from;
|
||||
while (i < source.length) {
|
||||
const code = source.charCodeAt(i);
|
||||
if (code === 10) return { contentEnd: i, nextLineStart: i + 1 };
|
||||
if (code === 13) {
|
||||
const next = i + 1 < source.length && source.charCodeAt(i + 1) === 10 ? i + 2 : i + 1;
|
||||
return { contentEnd: i, nextLineStart: next };
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return { contentEnd: source.length, nextLineStart: source.length };
|
||||
}
|
||||
|
||||
export function stripBlockquotesAt(source: string, from: number, limit: number): BlockquoteStrip {
|
||||
let offset = from;
|
||||
let quoteDepth = 0;
|
||||
while (offset < limit) {
|
||||
let spaces = 0;
|
||||
let cursor = offset;
|
||||
while (cursor < limit && source[cursor] === " " && spaces < 3) {
|
||||
cursor++;
|
||||
spaces++;
|
||||
}
|
||||
if (cursor >= limit || source[cursor] !== ">") break;
|
||||
quoteDepth++;
|
||||
cursor++;
|
||||
if (cursor < limit && (source[cursor] === " " || source[cursor] === "\t")) cursor++;
|
||||
offset = cursor;
|
||||
}
|
||||
return { quoteDepth, offset };
|
||||
}
|
||||
|
||||
export function measureIndentAt(source: string, from: number, limit: number): IndentMeasure {
|
||||
let spaces = 0;
|
||||
let offset = from;
|
||||
while (offset < limit) {
|
||||
const ch = source[offset];
|
||||
if (ch === " ") {
|
||||
spaces++;
|
||||
offset++;
|
||||
} else if (ch === "\t") {
|
||||
spaces += 4 - (spaces % 4);
|
||||
offset++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { spaces, offset };
|
||||
}
|
||||
|
||||
export function isBlankRange(source: string, from: number, limit: number): boolean {
|
||||
for (let i = from; i < limit; i++) {
|
||||
if (source[i] !== " " && source[i] !== "\t") return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function isThematicBreakText(trimmed: string): boolean {
|
||||
return /^(?:([-*_])(?:[ \t]*\1){2,})[ \t]*$/.test(trimmed);
|
||||
}
|
||||
|
||||
function parseListMarkerPrefix(
|
||||
source: string,
|
||||
offset: number,
|
||||
limit: number,
|
||||
disallowOrderedNonOne: boolean,
|
||||
): { markerChars: number; after: number; markerChar: string } | null {
|
||||
const ch = source[offset];
|
||||
if (ch === "-" || ch === "*" || ch === "+") {
|
||||
if ((ch === "-" || ch === "*") && isThematicBreakText(source.slice(offset, limit))) {
|
||||
return null;
|
||||
}
|
||||
return { markerChars: 1, after: offset + 1, markerChar: ch };
|
||||
}
|
||||
if (ch < "0" || ch > "9") return null;
|
||||
let cursor = offset;
|
||||
while (cursor < limit && source[cursor] >= "0" && source[cursor] <= "9" && cursor - offset < 9) {
|
||||
cursor++;
|
||||
}
|
||||
if (cursor >= limit || (source[cursor] !== "." && source[cursor] !== ")")) return null;
|
||||
if (disallowOrderedNonOne && Number(source.slice(offset, cursor)) !== 1) return null;
|
||||
return { markerChars: cursor + 1 - offset, after: cursor + 1, markerChar: ch };
|
||||
}
|
||||
|
||||
function measureMarkerSeparator(
|
||||
source: string,
|
||||
after: number,
|
||||
limit: number,
|
||||
startColumn: number,
|
||||
): { extraSpaces: number; endPos: number } {
|
||||
let col = startColumn;
|
||||
let extraSpaces = 0;
|
||||
let pos = after;
|
||||
while (pos < limit) {
|
||||
const ws = source[pos];
|
||||
if (ws === " ") {
|
||||
extraSpaces += 1;
|
||||
col += 1;
|
||||
pos++;
|
||||
} else if (ws === "\t") {
|
||||
const tabWidth = 4 - (col % 4);
|
||||
extraSpaces += tabWidth;
|
||||
col += tabWidth;
|
||||
pos++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { extraSpaces, endPos: pos };
|
||||
}
|
||||
|
||||
export function matchListMarkerAt(
|
||||
source: string,
|
||||
from: number,
|
||||
limit: number,
|
||||
maxIndent = 3,
|
||||
options?: { allowEmpty?: boolean; disallowOrderedNonOne?: boolean },
|
||||
): ListMarkerMatch | null {
|
||||
const { spaces, offset } = measureIndentAt(source, from, limit);
|
||||
if (spaces > maxIndent || offset >= limit) return null;
|
||||
|
||||
const prefix = parseListMarkerPrefix(
|
||||
source,
|
||||
offset,
|
||||
limit,
|
||||
options?.disallowOrderedNonOne ?? false,
|
||||
);
|
||||
if (!prefix) return null;
|
||||
|
||||
const { extraSpaces, endPos } = measureMarkerSeparator(
|
||||
source,
|
||||
prefix.after,
|
||||
limit,
|
||||
spaces + prefix.markerChars,
|
||||
);
|
||||
|
||||
if (extraSpaces === 0) {
|
||||
if (endPos === limit && options?.allowEmpty) {
|
||||
return {
|
||||
markerEnd: endPos,
|
||||
contentIndent: spaces + prefix.markerChars + 1,
|
||||
markerChar: prefix.markerChar,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// CommonMark §5.2: >=5 spaces after a marker keeps 4+ spaces as an indented code block.
|
||||
const consumed = extraSpaces >= 5 ? 1 : extraSpaces;
|
||||
const markerEnd = extraSpaces >= 5 ? prefix.after + 1 : endPos;
|
||||
return {
|
||||
markerEnd,
|
||||
contentIndent: spaces + prefix.markerChars + consumed,
|
||||
markerChar: prefix.markerChar,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseFenceOpenerAt(
|
||||
source: string,
|
||||
from: number,
|
||||
limit: number,
|
||||
maxIndent: number,
|
||||
): FenceOpenerMatch | null {
|
||||
const { spaces, offset } = measureIndentAt(source, from, limit);
|
||||
if (spaces > maxIndent || offset >= limit) return null;
|
||||
const ch = source[offset];
|
||||
if (ch !== "`" && ch !== "~") return null;
|
||||
let cursor = offset;
|
||||
while (cursor < limit && source[cursor] === ch) cursor++;
|
||||
const length = cursor - offset;
|
||||
if (length < 3) return null;
|
||||
const info = source.slice(cursor, limit);
|
||||
if (ch === "`" && info.includes("`")) return null;
|
||||
return { char: ch, length, fenceOffset: offset, indent: spaces, info };
|
||||
}
|
||||
|
||||
export function isClosingFenceAt(
|
||||
source: string,
|
||||
from: number,
|
||||
limit: number,
|
||||
maxIndent: number,
|
||||
char: "`" | "~",
|
||||
minLength: number,
|
||||
): boolean {
|
||||
const { spaces, offset } = measureIndentAt(source, from, limit);
|
||||
if (spaces > maxIndent || offset >= limit || source[offset] !== char) return false;
|
||||
let cursor = offset;
|
||||
while (cursor < limit && source[cursor] === char) cursor++;
|
||||
if (cursor - offset < minLength) return false;
|
||||
while (cursor < limit) {
|
||||
if (source[cursor] !== " " && source[cursor] !== "\t") return false;
|
||||
cursor++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function checkFenceContainerExit(
|
||||
source: string,
|
||||
lineStart: number,
|
||||
contentEnd: number,
|
||||
openQuoteDepth: number,
|
||||
listMinIndent: number,
|
||||
): { exited: boolean; quoteDepth: number; afterQuotes: number } {
|
||||
const { quoteDepth, offset: afterQuotes } = stripBlockquotesAt(source, lineStart, contentEnd);
|
||||
if (quoteDepth < openQuoteDepth) {
|
||||
return { exited: true, quoteDepth, afterQuotes };
|
||||
}
|
||||
if (
|
||||
listMinIndent > 0 &&
|
||||
quoteDepth === openQuoteDepth &&
|
||||
!isBlankRange(source, afterQuotes, contentEnd) &&
|
||||
measureIndentAt(source, afterQuotes, contentEnd).spaces < listMinIndent
|
||||
) {
|
||||
return { exited: true, quoteDepth, afterQuotes };
|
||||
}
|
||||
return { exited: false, quoteDepth, afterQuotes };
|
||||
}
|
||||
|
||||
export function createBlockScanState(): BlockScanState {
|
||||
return {
|
||||
listIndents: [],
|
||||
listQuoteDepth: 0,
|
||||
inParagraph: false,
|
||||
prevQuoteDepth: 0,
|
||||
inIndentedCode: false,
|
||||
indentedCodeQuoteDepth: 0,
|
||||
indentedCodeMinIndent: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function syncListContainer(state: BlockScanState, quoteDepth: number, spaces: number): number {
|
||||
if (quoteDepth < state.listQuoteDepth) {
|
||||
state.listIndents.length = 0;
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
}
|
||||
if (quoteDepth !== state.listQuoteDepth) return 0;
|
||||
while (state.listIndents.length > 0 && spaces < state.listIndents[state.listIndents.length - 1]) {
|
||||
state.listIndents.pop();
|
||||
}
|
||||
return state.listIndents.length > 0 ? state.listIndents[state.listIndents.length - 1] : 0;
|
||||
}
|
||||
|
||||
function peelLineListMarkers(
|
||||
state: BlockScanState,
|
||||
source: string,
|
||||
afterQuotes: number,
|
||||
contentEnd: number,
|
||||
quoteDepth: number,
|
||||
initialIndent: number,
|
||||
): { cursor: number; containerIndent: number; peeledList: boolean } {
|
||||
let cursor = afterQuotes;
|
||||
let containerIndent = initialIndent;
|
||||
let peeledList = false;
|
||||
let marker = matchListMarkerAt(source, cursor, contentEnd, containerIndent + 3, {
|
||||
allowEmpty: !state.inParagraph,
|
||||
disallowOrderedNonOne: state.inParagraph,
|
||||
});
|
||||
while (marker) {
|
||||
const markerBase = cursor === afterQuotes ? 0 : containerIndent;
|
||||
const totalIndent = markerBase + marker.contentIndent;
|
||||
state.listIndents.push(totalIndent);
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
containerIndent = totalIndent;
|
||||
cursor = marker.markerEnd;
|
||||
peeledList = true;
|
||||
marker = matchListMarkerAt(source, cursor, contentEnd, 3, { allowEmpty: true });
|
||||
}
|
||||
return { cursor, containerIndent, peeledList };
|
||||
}
|
||||
|
||||
function startIndentedCode(
|
||||
state: BlockScanState,
|
||||
quoteDepth: number,
|
||||
afterQuotes: number,
|
||||
containerIndent: number,
|
||||
): BlockLine {
|
||||
state.inIndentedCode = true;
|
||||
state.indentedCodeQuoteDepth = quoteDepth;
|
||||
state.indentedCodeMinIndent = containerIndent + 4;
|
||||
state.prevQuoteDepth = quoteDepth;
|
||||
return { kind: "indented-code", quoteDepth, afterQuotes };
|
||||
}
|
||||
|
||||
function isContinuationIndentedCode(
|
||||
state: BlockScanState,
|
||||
quoteDepth: number,
|
||||
spaces: number,
|
||||
): boolean {
|
||||
if (!state.inIndentedCode) return false;
|
||||
if (quoteDepth === state.indentedCodeQuoteDepth && spaces >= state.indentedCodeMinIndent) {
|
||||
return true;
|
||||
}
|
||||
state.inIndentedCode = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
function classifyBlankBlockLine(
|
||||
state: BlockScanState,
|
||||
quoteDepth: number,
|
||||
afterQuotes: number,
|
||||
): BlockLine {
|
||||
state.inParagraph = false;
|
||||
if (quoteDepth < state.listQuoteDepth) {
|
||||
state.listIndents.length = 0;
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
}
|
||||
if (state.inIndentedCode && quoteDepth < state.indentedCodeQuoteDepth) {
|
||||
state.inIndentedCode = false;
|
||||
}
|
||||
return { kind: "blank", quoteDepth, afterQuotes };
|
||||
}
|
||||
|
||||
function classifyTextBlockLine(
|
||||
state: BlockScanState,
|
||||
source: string,
|
||||
cursor: number,
|
||||
contentEnd: number,
|
||||
quoteDepth: number,
|
||||
afterQuotes: number,
|
||||
containerIndent: number,
|
||||
peeledList: boolean,
|
||||
): BlockLine {
|
||||
const { spaces: trimmedSpaces, offset: trimmedOffset } = measureIndentAt(
|
||||
source,
|
||||
cursor,
|
||||
contentEnd,
|
||||
);
|
||||
const relSpaces = peeledList ? trimmedSpaces : trimmedSpaces - containerIndent;
|
||||
const trimmed = source.slice(trimmedOffset, contentEnd);
|
||||
const endsParagraph =
|
||||
relSpaces <= 3 &&
|
||||
(/^#{1,6}(?:[ \t]|$)/.test(trimmed) ||
|
||||
isThematicBreakText(trimmed) ||
|
||||
(state.inParagraph && !peeledList && /^(?:-+|=+)[ \t]*$/.test(trimmed)));
|
||||
state.inParagraph = !endsParagraph;
|
||||
state.prevQuoteDepth = quoteDepth;
|
||||
return { kind: "text", quoteDepth, afterQuotes, containerIndent };
|
||||
}
|
||||
|
||||
function buildFenceBlockLine(
|
||||
state: BlockScanState,
|
||||
source: string,
|
||||
lineStart: number,
|
||||
afterQuotes: number,
|
||||
quoteDepth: number,
|
||||
containerIndent: number,
|
||||
peeledList: boolean,
|
||||
opener: FenceOpenerMatch,
|
||||
): BlockLine {
|
||||
state.inParagraph = false;
|
||||
state.prevQuoteDepth = quoteDepth;
|
||||
const quotePrefix = source.slice(lineStart, afterQuotes);
|
||||
const contentStripIndent = peeledList ? containerIndent + opener.indent : opener.indent;
|
||||
const inList = quoteDepth === state.listQuoteDepth && state.listIndents.length > 0;
|
||||
return {
|
||||
kind: "fence",
|
||||
quoteDepth,
|
||||
afterQuotes,
|
||||
fenceOffset: opener.fenceOffset,
|
||||
char: opener.char,
|
||||
length: opener.length,
|
||||
info: opener.info,
|
||||
maxCloseIndent: containerIndent + 3,
|
||||
contentStripIndent,
|
||||
inList,
|
||||
listMinIndent: inList ? containerIndent : 0,
|
||||
firstLinePrefix: source.slice(lineStart, opener.fenceOffset),
|
||||
continuationPrefix: `${quotePrefix}${" ".repeat(contentStripIndent)}`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify one line in CommonMark block order (quotes -> blank -> indented code ->
|
||||
* list markers -> fenced code -> ATX/Setext/thematic-break -> paragraph text) so math
|
||||
* scanners skip nested-list code fences and indented code blocks identically to md4c.
|
||||
*/
|
||||
export function classifyBlockLine(
|
||||
state: BlockScanState,
|
||||
source: string,
|
||||
lineStart: number,
|
||||
contentEnd: number,
|
||||
): BlockLine {
|
||||
const { quoteDepth, offset: afterQuotes } = stripBlockquotesAt(source, lineStart, contentEnd);
|
||||
|
||||
if (isBlankRange(source, afterQuotes, contentEnd)) {
|
||||
return classifyBlankBlockLine(state, quoteDepth, afterQuotes);
|
||||
}
|
||||
|
||||
if (quoteDepth > state.prevQuoteDepth) {
|
||||
state.inParagraph = false;
|
||||
state.inIndentedCode = false;
|
||||
}
|
||||
|
||||
const { spaces } = measureIndentAt(source, afterQuotes, contentEnd);
|
||||
if (isContinuationIndentedCode(state, quoteDepth, spaces)) {
|
||||
state.prevQuoteDepth = quoteDepth;
|
||||
return { kind: "indented-code", quoteDepth, afterQuotes };
|
||||
}
|
||||
|
||||
const baseIndent = syncListContainer(state, quoteDepth, spaces);
|
||||
if (!state.inParagraph && spaces >= baseIndent + 4) {
|
||||
return startIndentedCode(state, quoteDepth, afterQuotes, baseIndent);
|
||||
}
|
||||
|
||||
const { cursor, containerIndent, peeledList } = peelLineListMarkers(
|
||||
state,
|
||||
source,
|
||||
afterQuotes,
|
||||
contentEnd,
|
||||
quoteDepth,
|
||||
baseIndent,
|
||||
);
|
||||
if (peeledList) {
|
||||
state.inParagraph = false;
|
||||
const afterMarker = measureIndentAt(source, cursor, contentEnd);
|
||||
if (afterMarker.offset < contentEnd && afterMarker.spaces >= 4) {
|
||||
return startIndentedCode(state, quoteDepth, afterQuotes, containerIndent);
|
||||
}
|
||||
if (isBlankRange(source, cursor, contentEnd)) {
|
||||
state.prevQuoteDepth = quoteDepth;
|
||||
return { kind: "text", quoteDepth, afterQuotes: cursor, containerIndent };
|
||||
}
|
||||
}
|
||||
|
||||
const opener = parseFenceOpenerAt(
|
||||
source,
|
||||
cursor,
|
||||
contentEnd,
|
||||
peeledList ? 3 : containerIndent + 3,
|
||||
);
|
||||
if (opener) {
|
||||
return buildFenceBlockLine(
|
||||
state,
|
||||
source,
|
||||
lineStart,
|
||||
afterQuotes,
|
||||
quoteDepth,
|
||||
containerIndent,
|
||||
peeledList,
|
||||
opener,
|
||||
);
|
||||
}
|
||||
|
||||
return classifyTextBlockLine(
|
||||
state,
|
||||
source,
|
||||
cursor,
|
||||
contentEnd,
|
||||
quoteDepth,
|
||||
afterQuotes,
|
||||
containerIndent,
|
||||
peeledList,
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { decodeString } from "micromark-util-decode-string";
|
||||
import type { Nodes } from "mdast";
|
||||
import { isOffsetInRanges, scanMarkdownMath, type MathRange } from "./math";
|
||||
|
||||
const ATTRIBUTE = String.raw`\s+[A-Za-z_:][\w.:-]*(?:\s*=\s*(?:[^\s"'=<>\x60]+|'[^']*'|"[^"]*"))?`;
|
||||
const TAG = String.raw`<(?:[A-Za-z][A-Za-z0-9-]*(?:${ATTRIBUTE})*\s*\/?|\/[A-Za-z][A-Za-z0-9-]*\s*)>`;
|
||||
@@ -55,12 +56,14 @@ export function normalizeMarkdownHtml(source: string): string {
|
||||
} else if ("children" in node) node.children.forEach(protectCode);
|
||||
}
|
||||
protectCode(tree);
|
||||
const mathRanges = scanMarkdownMath(source);
|
||||
const protectedRanges = mergeRanges(codeRanges, mathRanges);
|
||||
// Only `<br>` reads these, so a source without one skips the extra parse.
|
||||
const tableRanges = /<br/i.test(source) ? collectTableRanges(source, codeRanges) : [];
|
||||
const tableRanges = /<br/i.test(source) ? collectTableRanges(source, protectedRanges) : [];
|
||||
const links: (string | undefined)[] = [];
|
||||
let previousTag: { name: string; end: number } | null = null;
|
||||
const convert = (raw: string, offset: number): string => {
|
||||
if (codeRanges.some(({ start, end }) => offset >= start && offset < end)) return raw;
|
||||
if (isOffsetInRanges(offset, protectedRanges)) return raw;
|
||||
if (raw.startsWith("<!--")) return "";
|
||||
const summary = /^<summary\b[^>]*>([\s\S]*?)<\/summary\s*>$/i.exec(raw);
|
||||
if (summary) {
|
||||
@@ -261,3 +264,19 @@ function collectTableRanges(
|
||||
);
|
||||
return tableRanges;
|
||||
}
|
||||
|
||||
function mergeRanges(a: readonly MathRange[], b: readonly MathRange[]): MathRange[] {
|
||||
if (a.length === 0 && b.length === 0) return [];
|
||||
const sorted = [...a, ...b].sort((left, right) => left.start - right.start);
|
||||
const merged: MathRange[] = [{ ...sorted[0] }];
|
||||
for (let i = 1; i < sorted.length; i++) {
|
||||
const current = sorted[i];
|
||||
const last = merged[merged.length - 1];
|
||||
if (current.start <= last.end) {
|
||||
if (current.end > last.end) last.end = current.end;
|
||||
} else {
|
||||
merged.push({ ...current });
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,277 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import {
|
||||
EnrichedMarkdownText,
|
||||
getLoadedKaTeX,
|
||||
preloadMarkdownParser,
|
||||
registerKaTeXStyleLoader,
|
||||
} from "react-native-enriched-markdown";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { applyRootUiFont } from "@/appearance/apply-root-font.web";
|
||||
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { darkTheme, lightTheme } from "@/styles/theme";
|
||||
import { ensureKaTeXStyles } from "./katex-styles.web";
|
||||
import { MarkdownRenderer } from "./renderer";
|
||||
import { createMarkdownStyles } from "./styles";
|
||||
import { WEB_RENDERERS } from "./renderers.web";
|
||||
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
const toast = { show: () => () => {}, copied: () => {}, error: () => {} };
|
||||
const queryClient = new QueryClient();
|
||||
const MATH_FLAGS = { latexMath: true, admonitions: true };
|
||||
|
||||
function wrapProviders(node: React.ReactNode) {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<ToastApiProvider api={toast}>{node}</ToastApiProvider>
|
||||
</I18nextProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await i18n.changeLanguage("en");
|
||||
await preloadMarkdownParser();
|
||||
container = document.createElement("div");
|
||||
container.id = "root";
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
container.remove();
|
||||
document.getElementById("paseo-ui-font")?.remove();
|
||||
document.documentElement.style.removeProperty("--paseo-ui-font");
|
||||
});
|
||||
|
||||
describe("web KaTeX math rendering", () => {
|
||||
it("does not load KaTeX when rendering prose without math", async () => {
|
||||
expect(getLoadedKaTeX()).toBeNull();
|
||||
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
wrapProviders(
|
||||
<MarkdownRenderer text="Costs $5 and $10, or $100/mo, with $PATH and \[1, 2\]." />,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
|
||||
expect(getLoadedKaTeX()).toBeNull();
|
||||
expect(container.querySelector('[role="math"]')).toBeNull();
|
||||
expect(container.textContent).toContain("Costs $5 and $10, or $100/mo");
|
||||
expect(container.textContent).toContain("$PATH");
|
||||
});
|
||||
|
||||
it("falls back to raw LaTeX when stylesheet loading fails and recovers on retry", async () => {
|
||||
let shouldFail = true;
|
||||
registerKaTeXStyleLoader(async () => {
|
||||
if (shouldFail) throw new Error("Simulated KaTeX CSS chunk failure");
|
||||
ensureKaTeXStyles();
|
||||
});
|
||||
|
||||
try {
|
||||
flushSync(() => {
|
||||
root.render(wrapProviders(<MarkdownRenderer text="Inline $x^2 + 1$ and $$y^2$$" />));
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const mathNodes = container.querySelectorAll('[role="math"]');
|
||||
expect(mathNodes.length).toBe(2);
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
|
||||
expect(getLoadedKaTeX()).toBeNull();
|
||||
expect(container.querySelector('[role="math"] .katex')).toBeNull();
|
||||
expect(container.textContent).toContain("$x^2 + 1$");
|
||||
expect(container.textContent).toContain("$$y^2$$");
|
||||
|
||||
shouldFail = false;
|
||||
flushSync(() => {
|
||||
root.render(wrapProviders(<MarkdownRenderer text="Recovered $x^2 + 1$ and $$y^2$$" />));
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(container.querySelectorAll('[role="math"] .katex-html').length).toBe(2);
|
||||
});
|
||||
expect(getLoadedKaTeX()).not.toBeNull();
|
||||
expect(document.getElementById("paseo-katex-css")).not.toBeNull();
|
||||
} finally {
|
||||
registerKaTeXStyleLoader(() => {
|
||||
ensureKaTeXStyles();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("lazily loads KaTeX and .woff2-only CSS for math, renders all 5 syntaxes, and renders synchronously on second mount", async () => {
|
||||
applyRootUiFont("'Custom UI Font', sans-serif");
|
||||
|
||||
const markdown = [
|
||||
"Inline $E = mc^2$ and \\(a^2 + b^2 = c^2\\).",
|
||||
"",
|
||||
"$$x^2 + y^2 = z^2$$",
|
||||
"",
|
||||
"\\[\\int_0^1 x^2\\,dx\\]",
|
||||
"",
|
||||
"```math",
|
||||
"\\sum_{i=1}^n i",
|
||||
"```",
|
||||
].join("\n");
|
||||
|
||||
flushSync(() => {
|
||||
root.render(wrapProviders(<MarkdownRenderer text={markdown} />));
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(container.querySelectorAll('[role="math"] .katex').length).toBe(5);
|
||||
});
|
||||
|
||||
expect(getLoadedKaTeX()).not.toBeNull();
|
||||
|
||||
const styleEl = document.getElementById("paseo-katex-css");
|
||||
expect(styleEl).not.toBeNull();
|
||||
const css = styleEl?.textContent ?? "";
|
||||
expect(css).toContain(".woff2");
|
||||
expect(css).not.toContain('.woff")');
|
||||
expect(css).not.toContain('.ttf")');
|
||||
|
||||
const mathNodes = Array.from(container.querySelectorAll<HTMLElement>('[role="math"]'));
|
||||
expect(mathNodes.map((el) => el.dataset.display)).toEqual([
|
||||
"inline",
|
||||
"inline",
|
||||
"block",
|
||||
"block",
|
||||
"block",
|
||||
]);
|
||||
expect(mathNodes[0]?.dataset.mathSource).toBe("$E = mc^2$");
|
||||
expect(mathNodes[2]?.dataset.mathSource).toBe("$$\nx^2 + y^2 = z^2\n$$");
|
||||
expect(mathNodes[0]?.querySelector(".katex-mathml")).not.toBeNull();
|
||||
expect(mathNodes[0]?.querySelector(".katex-html")).not.toBeNull();
|
||||
|
||||
// KaTeX font is preserved even when applyRootUiFont is active on #root.
|
||||
const mathInner = mathNodes[0]!.querySelector<HTMLElement>(".katex")!;
|
||||
expect(getComputedStyle(mathInner).fontFamily).toContain("KaTeX_Main");
|
||||
|
||||
// Second mount renders synchronously from module cache without raw-TeX flash.
|
||||
const secondHost = document.createElement("div");
|
||||
document.body.append(secondHost);
|
||||
const secondRoot = createRoot(secondHost);
|
||||
try {
|
||||
flushSync(() => {
|
||||
secondRoot.render(
|
||||
wrapProviders(
|
||||
<EnrichedMarkdownText
|
||||
markdown="Instant $x + 1$"
|
||||
flavor="github"
|
||||
md4cFlags={MATH_FLAGS}
|
||||
renderers={WEB_RENDERERS}
|
||||
/>,
|
||||
),
|
||||
);
|
||||
});
|
||||
// Immediately available after synchronous flushSync without waiting for timers.
|
||||
expect(secondHost.querySelector('[role="math"] .katex')).not.toBeNull();
|
||||
} finally {
|
||||
flushSync(() => secondRoot.unmount());
|
||||
secondHost.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["light", lightTheme],
|
||||
["dark", darkTheme],
|
||||
] as const)(
|
||||
"renders display and inline math cleanly in %s theme with horizontal scroll",
|
||||
async (_name, theme) => {
|
||||
const { markdownStyle } = createMarkdownStyles(theme, { blockGap: 16 });
|
||||
const wideEquation = `$$${Array.from({ length: 12 }, (_, i) => `x_{${i}}`).join(" + ")}$$`;
|
||||
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
wrapProviders(
|
||||
<EnrichedMarkdownText
|
||||
markdown={`Inline $x$ and:\n\n${wideEquation}`}
|
||||
markdownStyle={markdownStyle}
|
||||
flavor="github"
|
||||
md4cFlags={MATH_FLAGS}
|
||||
renderers={WEB_RENDERERS}
|
||||
/>,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(container.querySelectorAll('[role="math"] .katex').length).toBe(2);
|
||||
});
|
||||
|
||||
const blockMath = container.querySelector<HTMLElement>(
|
||||
'[role="math"][data-display="block"]',
|
||||
)!;
|
||||
expect(blockMath.style.backgroundColor).toBe("transparent");
|
||||
expect(blockMath.style.overflowX).toBe("auto");
|
||||
expect(blockMath.style.textAlign).toBe("center");
|
||||
},
|
||||
);
|
||||
|
||||
it("renders accurate formula output across inline/display mode and repeated renders past cache turnover", async () => {
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
wrapProviders(
|
||||
<MarkdownRenderer text={"Inline $x_0$ vs display:\n\n$$x_0$$\n\nRepeated $x_0$."} />,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(container.querySelectorAll('[role="math"] .katex-html').length).toBe(3);
|
||||
});
|
||||
|
||||
const htmlText = (el: HTMLElement | undefined) =>
|
||||
el?.querySelector(".katex-html")?.textContent?.replace(/\u200B/g, "");
|
||||
const annotationText = (el: HTMLElement | undefined) =>
|
||||
el?.querySelector(".katex-mathml annotation")?.textContent;
|
||||
|
||||
const initialMath = Array.from(container.querySelectorAll<HTMLElement>('[role="math"]'));
|
||||
expect(initialMath.map((el) => el.dataset.display)).toEqual(["inline", "block", "inline"]);
|
||||
expect(initialMath[0]?.querySelector(".katex-display")).toBeNull();
|
||||
expect(initialMath[1]?.querySelector(".katex-display")).not.toBeNull();
|
||||
expect(htmlText(initialMath[0])).toBe("x0");
|
||||
expect(htmlText(initialMath[1])).toBe("x0");
|
||||
expect(htmlText(initialMath[2])).toBe("x0");
|
||||
expect(annotationText(initialMath[0])).toBe("x_0");
|
||||
expect(annotationText(initialMath[1])).toBe("x_0");
|
||||
|
||||
// Exceed the 256-entry render cache and re-render earlier formulas to verify evicted entries stay accurate.
|
||||
const manyFormulas = Array.from({ length: 265 }, (_, i) => `$a_{${i}}$`).join(" ");
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
wrapProviders(<MarkdownRenderer text={`${manyFormulas} $x_0$ $$x_0$$ $a_{0}$`} />),
|
||||
);
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(container.querySelectorAll('[role="math"] .katex-html').length).toBe(268);
|
||||
});
|
||||
|
||||
const rendered = Array.from(container.querySelectorAll<HTMLElement>('[role="math"]'));
|
||||
expect(htmlText(rendered[0])).toBe("a0");
|
||||
expect(annotationText(rendered[0])).toBe("a_{0}");
|
||||
expect(htmlText(rendered[264])).toBe("a264");
|
||||
expect(annotationText(rendered[264])).toBe("a_{264}");
|
||||
expect(rendered[265]?.dataset.display).toBe("inline");
|
||||
expect(htmlText(rendered[265])).toBe("x0");
|
||||
expect(rendered[266]?.dataset.display).toBe("block");
|
||||
expect(htmlText(rendered[266])).toBe("x0");
|
||||
expect(rendered[267]?.dataset.mathSource).toBe("$a_{0}$");
|
||||
expect(htmlText(rendered[267])).toBe("a0");
|
||||
expect(annotationText(rendered[267])).toBe("a_{0}");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,437 @@
|
||||
import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown";
|
||||
import type { ASTNode } from "react-native-enriched-markdown/src/web/types";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { normalizeMarkdownHtml } from "./html";
|
||||
import { adaptMarkdownMath, findBlockMathSpans, scanMarkdownMath } from "./math";
|
||||
import { prepareMarkdownSource } from "./source";
|
||||
|
||||
const MATH_FLAGS = { latexMath: true, hardSoftBreaks: true, admonitions: true };
|
||||
const NO_MATH_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true };
|
||||
|
||||
function collectNodes(node: ASTNode, result: ASTNode[] = []): ASTNode[] {
|
||||
result.push(node);
|
||||
node.children?.forEach((child) => collectNodes(child, result));
|
||||
return result;
|
||||
}
|
||||
|
||||
function collectMathNodes(ast: ASTNode): { type: string; content: string }[] {
|
||||
return collectNodes(ast)
|
||||
.filter((node) => node.type === "LatexMathInline" || node.type === "LatexMathDisplay")
|
||||
.map((node) => ({
|
||||
type: node.type,
|
||||
content: (node.children ?? []).map((child) => child.content ?? "").join(""),
|
||||
}));
|
||||
}
|
||||
|
||||
function collectText(node: ASTNode): string {
|
||||
if (node.type === "LatexMathInline" || node.type === "LatexMathDisplay") return "";
|
||||
if (node.type === "Text") return node.content ?? "";
|
||||
return (node.children ?? []).map(collectText).join("");
|
||||
}
|
||||
|
||||
describe("math source adaptation — currency, shell, regex, and literal prose", () => {
|
||||
it.each([
|
||||
["Costs $5 and $10.", "Costs $5 and $10."],
|
||||
["Costs $5 and 10$", "Costs $5 and 10$"],
|
||||
["From $100/mo to $200/mo", "From $100/mo to $200/mo"],
|
||||
["Costs $100/mo (or 200$)", "Costs $100/mo (or 200$)"],
|
||||
["Total: $5 ($)", "Total: $5 ($)"],
|
||||
["Costs $5. Run $ ls", "Costs $5. Run $ ls"],
|
||||
["Pay $10 and get $ back", "Pay $10 and get $ back"],
|
||||
["I have $ 5 and $ 10", "I have $ 5 and $ 10"],
|
||||
["Price is US$5 or CA$10", "Price is US$5 or CA$10"],
|
||||
["Set $PATH and $HOME", "Set $PATH and $HOME"],
|
||||
["Use $PATH with /^foo$/", "Use $PATH with /^foo$/"],
|
||||
["Save $5 with sed s/foo$/bar/", "Save $5 with sed s/foo$/bar/"],
|
||||
["Check $HOME then foo$", "Check $HOME then foo$"],
|
||||
["$3$4", "$3$4"],
|
||||
["Costs $50k or $10M or $2B today", "Costs $50k or $10M or $2B today"],
|
||||
["Costs $5! Or $10)?", "Costs $5! Or $10)?"],
|
||||
["Escaped \\$x\\$", "Escaped $x$"],
|
||||
["See citation \\[1, 2\\]", "See citation [1, 2]"],
|
||||
])(
|
||||
"keeps %s literal when parsed with latexMath: true and latexMath: false",
|
||||
async (source, expectedText) => {
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
for (const flags of [MATH_FLAGS, NO_MATH_FLAGS]) {
|
||||
const ast = await parseMarkdown(rendered, flags);
|
||||
expect(collectMathNodes(ast)).toEqual([]);
|
||||
expect(collectText(ast)).toBe(expectedText);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("leaves inline code and latex/tex code fences literal", async () => {
|
||||
const inlineCode = "Use `$x$` and ``$$y$$`` and `\\(z\\)`";
|
||||
const preparedInline = prepareMarkdownSource(inlineCode).render();
|
||||
expect(preparedInline).toBe(inlineCode);
|
||||
const inlineAst = await parseMarkdown(preparedInline, MATH_FLAGS);
|
||||
expect(collectMathNodes(inlineAst)).toEqual([]);
|
||||
|
||||
for (const lang of ["latex", "tex"]) {
|
||||
const fence = `\`\`\`${lang}\n\\documentclass{article}\n$x = 1$\n\`\`\``;
|
||||
const preparedFence = prepareMarkdownSource(fence).render();
|
||||
expect(preparedFence).toBe(fence);
|
||||
const fenceAst = await parseMarkdown(preparedFence, MATH_FLAGS);
|
||||
expect(collectMathNodes(fenceAst)).toEqual([]);
|
||||
expect(collectNodes(fenceAst).some((node) => node.type === "CodeBlock")).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves list-nested fenced code blocks containing blank lines, $, \\(, and $$ verbatim", async () => {
|
||||
const nested = [
|
||||
"1. Install:",
|
||||
" - Run this:",
|
||||
"",
|
||||
" ```bash",
|
||||
' export PATH="$HOME/bin:$PATH"',
|
||||
"",
|
||||
" grep -E '\\(foo\\)' log.txt",
|
||||
" ```",
|
||||
].join("\n");
|
||||
const renderedNested = prepareMarkdownSource(nested).render();
|
||||
expect(renderedNested).toBe(nested);
|
||||
const nestedAst = await parseMarkdown(renderedNested, MATH_FLAGS);
|
||||
expect(collectMathNodes(nestedAst)).toEqual([]);
|
||||
const nestedCodeBlock = collectNodes(nestedAst).find((node) => node.type === "CodeBlock");
|
||||
expect(nestedCodeBlock).toBeDefined();
|
||||
expect(collectText(nestedCodeBlock!)).toBe(
|
||||
"export PATH=\"$HOME/bin:$PATH\"\n\ngrep -E '\\(foo\\)' log.txt\n",
|
||||
);
|
||||
|
||||
const deepNested = [
|
||||
"1. Outer:",
|
||||
" 1. Inner:",
|
||||
" - Leaf:",
|
||||
"",
|
||||
" ```sh",
|
||||
" echo $HOME",
|
||||
"",
|
||||
" printf '%s\\n' '\\(a+b\\)' '$$x^2$$'",
|
||||
" ```",
|
||||
].join("\n");
|
||||
const renderedDeep = prepareMarkdownSource(deepNested).render();
|
||||
expect(renderedDeep).toBe(deepNested);
|
||||
const deepAst = await parseMarkdown(renderedDeep, MATH_FLAGS);
|
||||
expect(collectMathNodes(deepAst)).toEqual([]);
|
||||
const deepCodeBlock = collectNodes(deepAst).find((node) => node.type === "CodeBlock");
|
||||
expect(deepCodeBlock).toBeDefined();
|
||||
expect(collectText(deepCodeBlock!)).toBe(
|
||||
"echo $HOME\n\nprintf '%s\\n' '\\(a+b\\)' '$$x^2$$'\n",
|
||||
);
|
||||
expect(scanMarkdownMath(deepNested)).toEqual([]);
|
||||
expect(findBlockMathSpans(deepNested)).toEqual([]);
|
||||
});
|
||||
|
||||
it("preserves CommonMark 4-space and tab indented code blocks verbatim", async () => {
|
||||
const atStart = [
|
||||
' export PATH="$HOME/bin:$PATH"',
|
||||
" grep -E '\\(foo\\)' log.txt",
|
||||
" echo $$x^2$$",
|
||||
].join("\n");
|
||||
const renderedStart = prepareMarkdownSource(atStart).render();
|
||||
expect(renderedStart).toBe(atStart);
|
||||
const startAst = await parseMarkdown(renderedStart, MATH_FLAGS);
|
||||
expect(collectMathNodes(startAst)).toEqual([]);
|
||||
const startCode = collectNodes(startAst).find((node) => node.type === "CodeBlock");
|
||||
expect(startCode).toBeDefined();
|
||||
expect(collectText(startCode!)).toBe(
|
||||
"export PATH=\"$HOME/bin:$PATH\"\ngrep -E '\\(foo\\)' log.txt\necho $$x^2$$\n",
|
||||
);
|
||||
|
||||
const afterBlank = [
|
||||
"Run this:",
|
||||
"",
|
||||
" echo $HOME",
|
||||
" echo \\(foo\\)",
|
||||
" echo $$x^2$$",
|
||||
"",
|
||||
"\techo $USER",
|
||||
].join("\n");
|
||||
const renderedAfterBlank = prepareMarkdownSource(afterBlank).render();
|
||||
expect(renderedAfterBlank).toBe(afterBlank);
|
||||
const afterBlankAst = await parseMarkdown(renderedAfterBlank, MATH_FLAGS);
|
||||
expect(collectMathNodes(afterBlankAst)).toEqual([]);
|
||||
const afterBlankCodes = collectNodes(afterBlankAst).filter((node) => node.type === "CodeBlock");
|
||||
expect(afterBlankCodes).toHaveLength(1);
|
||||
expect(collectText(afterBlankCodes[0]!)).toBe(
|
||||
"echo $HOME\necho \\(foo\\)\necho $$x^2$$\n\necho $USER\n",
|
||||
);
|
||||
expect(scanMarkdownMath(afterBlank)).toEqual([]);
|
||||
expect(findBlockMathSpans(afterBlank)).toEqual([]);
|
||||
});
|
||||
|
||||
it("preserves later non-math fences after prose", async () => {
|
||||
const source = "Intro.\n\n~~~sh\necho $PATH\n~~~";
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
expect(rendered).toBe(source);
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
expect(collectMathNodes(ast)).toEqual([]);
|
||||
const codeBlock = collectNodes(ast).find((node) => node.type === "CodeBlock");
|
||||
expect(collectText(codeBlock!)).toBe("echo $PATH\n");
|
||||
});
|
||||
|
||||
it("exits an unclosed list-nested fence when the enclosing list ends and adapts later math", async () => {
|
||||
const withBlank = "- ~~~sh\n echo ok\n\nOutside \\(x+1\\).";
|
||||
const renderedWithBlank = prepareMarkdownSource(withBlank).render();
|
||||
expect(renderedWithBlank).toBe("- ~~~sh\n echo ok\n\nOutside $x+1$.");
|
||||
const astWithBlank = await parseMarkdown(renderedWithBlank, MATH_FLAGS);
|
||||
expect(collectMathNodes(astWithBlank)).toEqual([{ type: "LatexMathInline", content: "x+1" }]);
|
||||
|
||||
const noBlank = "- ~~~sh\n echo ok\nOutside \\(x+1\\).";
|
||||
const astRaw = await parseMarkdown(noBlank, MATH_FLAGS);
|
||||
// Verify md4c closes the list fence immediately on unindented non-blank lines too.
|
||||
expect(collectNodes(astRaw).some((node) => node.type === "CodeBlock")).toBe(true);
|
||||
const renderedNoBlank = prepareMarkdownSource(noBlank).render();
|
||||
const astNoBlank = await parseMarkdown(renderedNoBlank, MATH_FLAGS);
|
||||
expect(collectMathNodes(astNoBlank)).toEqual([{ type: "LatexMathInline", content: "x+1" }]);
|
||||
});
|
||||
|
||||
it("ignores escaped \\\\( and \\\\[ and HTML comments", async () => {
|
||||
const source = "Literal \\\\(x\\\\) and \\\\[y\\\\] and <!-- $hidden$ -->";
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
expect(collectMathNodes(ast)).toEqual([]);
|
||||
expect(collectText(ast)).toContain("\\(x\\)");
|
||||
expect(collectText(ast)).toContain("\\[y\\]");
|
||||
});
|
||||
|
||||
it("protects <autolinks> containing dollar signs", async () => {
|
||||
const source = "Visit <https://example.com/$5> and pay $10";
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
expect(rendered).toContain("<https://example.com/$5>");
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
expect(collectMathNodes(ast)).toEqual([]);
|
||||
const link = collectNodes(ast).find((node) => node.type === "Link");
|
||||
expect(link?.attributes?.url).toBe("https://example.com/$5");
|
||||
});
|
||||
});
|
||||
|
||||
describe("math source adaptation — valid inline and display math", () => {
|
||||
it.each([
|
||||
["$x$", "x"],
|
||||
["$a_i$", "a_i"],
|
||||
["$E = mc^2$", "E = mc^2"],
|
||||
["$2^k$", "2^k"],
|
||||
["$3x + 1$", "3x + 1"],
|
||||
["$0.5\\theta$", "0.5\\theta"],
|
||||
["$1/2$", "1/2"],
|
||||
["$5+2$", "5+2"],
|
||||
["$10 \\times 20$", "10 \\times 20"],
|
||||
["$\\theta \\in [0.5, 1.0]$", "\\theta \\in [0.5, 1.0]"],
|
||||
["$k$-means", "k"],
|
||||
["公式$x=1$的值", "x=1"],
|
||||
["\\(a^2 + b^2 = c^2\\)", "a^2 + b^2 = c^2"],
|
||||
["$x < y$ and $a > b$", "x < y"],
|
||||
["$a < b > c$", "a < b > c"],
|
||||
["Paragraph line\n with 4-space indented continuation $x$", "x"],
|
||||
])("parses inline math %s through md4c", async (source, firstContent) => {
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
const mathNodes = collectMathNodes(ast);
|
||||
expect(mathNodes.length).toBeGreaterThanOrEqual(1);
|
||||
expect(mathNodes[0]).toMatchObject({
|
||||
type: "LatexMathInline",
|
||||
content: firstContent,
|
||||
});
|
||||
});
|
||||
|
||||
it("parses both $x < y$ and $a > b$ without HTML mangling", async () => {
|
||||
const source = "$x < y$ and $a > b$";
|
||||
const ast = await parseMarkdown(prepareMarkdownSource(source).render(), MATH_FLAGS);
|
||||
expect(collectMathNodes(ast)).toEqual([
|
||||
{ type: "LatexMathInline", content: "x < y" },
|
||||
{ type: "LatexMathInline", content: "a > b" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("inserts hair space around CJK-flanked math and preserves surrounding CJK text", async () => {
|
||||
const source = "公式$x=1$的值";
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
expect(rendered).toBe("公式\u200A$x=1$\u200A的值");
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
expect(collectMathNodes(ast)).toEqual([{ type: "LatexMathInline", content: "x=1" }]);
|
||||
expect(collectText(ast)).toBe("公式\u200A\u200A的值");
|
||||
});
|
||||
|
||||
it("escapes GFM table pipes inside math without splitting columns", async () => {
|
||||
const source = [
|
||||
"| Metric | Formula | Norm |",
|
||||
"| --- | --- | --- |",
|
||||
"| Cond | $P(A|B)$ | $\\|x\\|$ |",
|
||||
].join("\n");
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
const table = collectNodes(ast).find((node) => node.type === "Table");
|
||||
const bodyRow = table?.children?.find((node) => node.type === "TableBody")?.children?.[0];
|
||||
expect(bodyRow?.children).toHaveLength(3);
|
||||
expect(collectMathNodes(bodyRow!)).toEqual([
|
||||
{ type: "LatexMathInline", content: "P(A\\vert B)" },
|
||||
{ type: "LatexMathInline", content: "\\Vert x\\Vert " },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps matrix & and || intact inside math when mdast runs", async () => {
|
||||
const source = [
|
||||
"Before & ||spoiler||",
|
||||
"",
|
||||
"$$",
|
||||
"\\begin{pmatrix}",
|
||||
"a & b \\\\",
|
||||
"c & d",
|
||||
"\\end{pmatrix}",
|
||||
"$$",
|
||||
"",
|
||||
"Norm $\\|x\\| + ||y||$ and <end>.",
|
||||
].join("\n");
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
const mathNodes = collectMathNodes(ast);
|
||||
expect(mathNodes).toHaveLength(2);
|
||||
expect(mathNodes[0].type).toBe("LatexMathDisplay");
|
||||
expect(mathNodes[0].content).toContain("a & b \\\\");
|
||||
expect(mathNodes[1]).toEqual({
|
||||
type: "LatexMathInline",
|
||||
content: "\\|x\\| + ||y||",
|
||||
});
|
||||
const text = collectText(ast);
|
||||
expect(text).toContain("Before & ||spoiler||");
|
||||
expect(text).toContain("<end>.");
|
||||
});
|
||||
|
||||
it("parses display math syntaxes: $$, multiline $$ with blank lines/comments, \\[...\\], and ```math", async () => {
|
||||
const single = await parseMarkdown(prepareMarkdownSource("$$E = mc^2$$").render(), MATH_FLAGS);
|
||||
expect(collectMathNodes(single)).toEqual([{ type: "LatexMathDisplay", content: "E = mc^2" }]);
|
||||
|
||||
const multilineBlank = [
|
||||
"$$",
|
||||
"x = 1 % first variable",
|
||||
"% whole line comment",
|
||||
"",
|
||||
"y = 50\\% + 2 % trailing comment",
|
||||
"$$",
|
||||
].join("\n");
|
||||
const multiAst = await parseMarkdown(
|
||||
prepareMarkdownSource(multilineBlank).render(),
|
||||
MATH_FLAGS,
|
||||
);
|
||||
const multiMath = collectMathNodes(multiAst);
|
||||
expect(multiMath).toHaveLength(1);
|
||||
expect(multiMath[0].type).toBe("LatexMathDisplay");
|
||||
expect(multiMath[0].content).toContain("x = 1");
|
||||
expect(multiMath[0].content).toContain("y = 50\\% + 2");
|
||||
expect(multiMath[0].content).not.toContain("first variable");
|
||||
expect(multiMath[0].content).not.toContain("whole line comment");
|
||||
expect(multiMath[0].content).not.toContain("trailing comment");
|
||||
|
||||
const bracketSource = "\\[ \\int_0^1 x^2\\,dx \\]";
|
||||
const bracketAst = await parseMarkdown(
|
||||
prepareMarkdownSource(bracketSource).render(),
|
||||
MATH_FLAGS,
|
||||
);
|
||||
expect(collectMathNodes(bracketAst)).toEqual([
|
||||
{ type: "LatexMathDisplay", content: " \\int_0^1 x^2\\,dx " },
|
||||
]);
|
||||
|
||||
const fencedMath = "```math\n\\sum_{i=1}^n i\n```";
|
||||
const fencedAst = await parseMarkdown(prepareMarkdownSource(fencedMath).render(), MATH_FLAGS);
|
||||
expect(collectMathNodes(fencedAst)).toHaveLength(1);
|
||||
expect(collectMathNodes(fencedAst)[0].type).toBe("LatexMathDisplay");
|
||||
expect(collectMathNodes(fencedAst)[0].content?.trim()).toBe("\\sum_{i=1}^n i");
|
||||
|
||||
const tildeMath = "~~~math\na^2 + b^2 = c^2\n~~~";
|
||||
const tildeAst = await parseMarkdown(prepareMarkdownSource(tildeMath).render(), MATH_FLAGS);
|
||||
expect(collectMathNodes(tildeAst)).toHaveLength(1);
|
||||
expect(collectMathNodes(tildeAst)[0].type).toBe("LatexMathDisplay");
|
||||
expect(collectMathNodes(tildeAst)[0].content?.trim()).toBe("a^2 + b^2 = c^2");
|
||||
|
||||
const proseThenMath = "Intro.\n\n~~~math\nx=1\n~~~";
|
||||
const proseThenMathAst = await parseMarkdown(
|
||||
prepareMarkdownSource(proseThenMath).render(),
|
||||
MATH_FLAGS,
|
||||
);
|
||||
expect(collectMathNodes(proseThenMathAst)).toHaveLength(1);
|
||||
expect(collectMathNodes(proseThenMathAst)[0].type).toBe("LatexMathDisplay");
|
||||
expect(collectMathNodes(proseThenMathAst)[0].content?.trim()).toBe("x=1");
|
||||
|
||||
const listMathFence = "1. Compute:\n\n ```math\n x = 1\n ```";
|
||||
const listMathAst = await parseMarkdown(
|
||||
prepareMarkdownSource(listMathFence).render(),
|
||||
MATH_FLAGS,
|
||||
);
|
||||
expect(collectMathNodes(listMathAst)).toHaveLength(1);
|
||||
expect(collectMathNodes(listMathAst)[0].type).toBe("LatexMathDisplay");
|
||||
expect(collectMathNodes(listMathAst)[0].content?.trim()).toBe("x = 1");
|
||||
expect(collectNodes(listMathAst).some((node) => node.type === "OrderedList")).toBe(true);
|
||||
|
||||
const nestedListMathFence = "1. Outer:\n - Inner:\n\n ```math\n y = 2\n ```";
|
||||
const nestedListMathAst = await parseMarkdown(
|
||||
prepareMarkdownSource(nestedListMathFence).render(),
|
||||
MATH_FLAGS,
|
||||
);
|
||||
expect(collectMathNodes(nestedListMathAst)).toHaveLength(1);
|
||||
expect(collectMathNodes(nestedListMathAst)[0].type).toBe("LatexMathDisplay");
|
||||
expect(collectMathNodes(nestedListMathAst)[0].content?.trim()).toBe("y = 2");
|
||||
expect(collectNodes(nestedListMathAst).some((node) => node.type === "UnorderedList")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("escapes internal unescaped $ inside \\(...\\), \\[...\\], and ```math", async () => {
|
||||
const paren = prepareMarkdownSource("\\(\\text{cost } $5\\)").render();
|
||||
expect(paren).toBe("$\\text{cost } \\$5$");
|
||||
const parenAst = await parseMarkdown(paren, MATH_FLAGS);
|
||||
expect(collectMathNodes(parenAst)).toEqual([
|
||||
{ type: "LatexMathInline", content: "\\text{cost } \\$5" },
|
||||
]);
|
||||
|
||||
const bracket = prepareMarkdownSource("\\[\\text{cost } $5\\]").render();
|
||||
const bracketAst = await parseMarkdown(bracket, MATH_FLAGS);
|
||||
expect(collectMathNodes(bracketAst)).toEqual([
|
||||
{ type: "LatexMathDisplay", content: "\\text{cost } \\$5" },
|
||||
]);
|
||||
|
||||
const fenced = prepareMarkdownSource("```math\n\\text{cost } $5\n```").render();
|
||||
const fencedAst = await parseMarkdown(fenced, MATH_FLAGS);
|
||||
expect(collectMathNodes(fencedAst)[0].content?.trim()).toBe("\\text{cost } \\$5");
|
||||
});
|
||||
|
||||
it("keeps unclosed ```math, $$, \\[, \\(, and $ literal", () => {
|
||||
expect(adaptMarkdownMath("```math\n\\frac{a}{").source).toBe("```math\n\\frac{a}{");
|
||||
expect(adaptMarkdownMath("$$\n\\frac{a}{").source).toBe("\\$\\$\n\\frac{a}{");
|
||||
expect(adaptMarkdownMath("\\[\n\\frac{a}{").source).toBe("\\[\n\\frac{a}{");
|
||||
expect(adaptMarkdownMath("$\\alpha +").source).toBe("\\$\\alpha +");
|
||||
expect(adaptMarkdownMath("\\(\\alpha +").source).toBe("\\(\\alpha +");
|
||||
});
|
||||
|
||||
it("protects math ranges in normalizeMarkdownHtml", () => {
|
||||
expect(normalizeMarkdownHtml("$a < b > c$ and <b>bold</b>")).toBe("$a < b > c$ and **bold**");
|
||||
expect(normalizeMarkdownHtml("$$\n<div>x</div>\n$$")).toBe("$$\n<div>x</div>\n$$");
|
||||
expect(
|
||||
normalizeMarkdownHtml("<details><summary>Proof</summary>\n\n$a < b > c$\n</details>"),
|
||||
).toBe("**Proof**\n\n\n\n$a < b > c$\n");
|
||||
});
|
||||
});
|
||||
|
||||
describe("math fast path invariants", () => {
|
||||
it("bails out immediately on plain prose without math triggers", () => {
|
||||
const prose = "Plain markdown with **bold**, `code`, and [link](https://example.com).";
|
||||
expect(scanMarkdownMath(prose)).toEqual([]);
|
||||
const adapted = adaptMarkdownMath(prose);
|
||||
expect(adapted.source).toBe(prose);
|
||||
expect(adapted.mathRanges).toEqual([]);
|
||||
});
|
||||
|
||||
it("preserves plain prose and canonicalizes math-only prose synchronously through prepareMarkdownSource", () => {
|
||||
const plain = "Plain prose without special triggers.";
|
||||
expect(prepareMarkdownSource(plain).render()).toBe(plain);
|
||||
|
||||
const mathSource =
|
||||
"Inline $E = mc^2$, paren \\(a+b\\), display $$x^2 + y^2$$.\n\n```math\nz = 1\n```";
|
||||
const rendered = prepareMarkdownSource(mathSource).render();
|
||||
expect(rendered).toContain("$E = mc^2$");
|
||||
expect(rendered).toContain("$a+b$");
|
||||
expect(rendered).toContain("$$\nz = 1\n$$");
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -806,9 +806,37 @@ it.each([
|
||||
color: theme.colors.accentBright,
|
||||
});
|
||||
expect(style.thematicBreak?.color).toBe(theme.colors.border);
|
||||
expect(style.math).toMatchObject({
|
||||
color: theme.colors.foreground,
|
||||
backgroundColor: "transparent",
|
||||
padding: 8,
|
||||
marginTop: 0,
|
||||
marginBottom: 16,
|
||||
textAlign: "center",
|
||||
});
|
||||
expect(style.inlineMath).toMatchObject({
|
||||
color: theme.colors.foreground,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("uses muted text colour for math when compact and muted", () => {
|
||||
const { markdownStyle: style } = createMarkdownStyles(darkTheme, {
|
||||
compact: true,
|
||||
muted: true,
|
||||
blockGap: 12,
|
||||
});
|
||||
expect(style.math).toMatchObject({
|
||||
color: darkTheme.colors.foregroundMuted,
|
||||
backgroundColor: "transparent",
|
||||
padding: 8,
|
||||
marginTop: 0,
|
||||
marginBottom: 12,
|
||||
textAlign: "center",
|
||||
});
|
||||
expect(style.inlineMath).toEqual({ color: darkTheme.colors.foregroundMuted });
|
||||
});
|
||||
|
||||
it.each([darkTheme, lightTheme])("supplies the theme selection colour to the renderer", (theme) => {
|
||||
expect(createMarkdownStyles(theme, { blockGap: 16 })).toHaveProperty(
|
||||
"selectionColor",
|
||||
@@ -1442,3 +1470,69 @@ describe("web Markdown parser preload", () => {
|
||||
expect(ast?.children?.map((node) => node.type)).toEqual(["Heading", "Paragraph"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("math preparation compatibility with latexMath false and true", () => {
|
||||
it("renders currency literally with latexMath: false while enabling math with latexMath: true", async () => {
|
||||
const source =
|
||||
"Costs $5 and $10; inline $E = mc^2$, \\(a+b\\), \\[c+d\\], and:\n\n```math\nx^2\n```";
|
||||
const prepared = prepareMarkdownSource(source).render();
|
||||
|
||||
const noMathAst = await parseMarkdown(prepared, {
|
||||
latexMath: false,
|
||||
hardSoftBreaks: true,
|
||||
admonitions: true,
|
||||
});
|
||||
const noMathText = JSON.stringify(noMathAst);
|
||||
expect(noMathText).toContain("Costs $5 and $10");
|
||||
expect(noMathText).not.toContain("LatexMath");
|
||||
|
||||
const mathAst = await parseMarkdown(prepared, {
|
||||
latexMath: true,
|
||||
hardSoftBreaks: true,
|
||||
admonitions: true,
|
||||
});
|
||||
const mathNodes: { type: string; content: string }[] = [];
|
||||
const walk = (node: ASTNode) => {
|
||||
if (node.type === "LatexMathInline" || node.type === "LatexMathDisplay") {
|
||||
mathNodes.push({
|
||||
type: node.type,
|
||||
content: (node.children ?? []).map((child) => child.content ?? "").join(""),
|
||||
});
|
||||
}
|
||||
node.children?.forEach(walk);
|
||||
};
|
||||
walk(mathAst);
|
||||
expect(mathNodes.map((n) => [n.type, n.content.trim()])).toEqual([
|
||||
["LatexMathInline", "E = mc^2"],
|
||||
["LatexMathInline", "a+b"],
|
||||
["LatexMathDisplay", "c+d"],
|
||||
["LatexMathDisplay", "x^2"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("web KaTeX .woff2-only stylesheet sync", () => {
|
||||
it("includes all 20 .woff2 fonts from katex and drops .woff/.ttf fallbacks", async () => {
|
||||
const fs = await import("node:fs");
|
||||
const path = await import("node:path");
|
||||
const katexCssPath = require.resolve("katex/dist/katex.min.css");
|
||||
const katexFontsDir = path.join(path.dirname(katexCssPath), "fonts");
|
||||
const woff2Files = fs
|
||||
.readdirSync(katexFontsDir)
|
||||
.filter((name) => name.endsWith(".woff2"))
|
||||
.sort();
|
||||
expect(woff2Files).toHaveLength(20);
|
||||
|
||||
const katexStylesSource = fs.readFileSync(
|
||||
path.resolve(__dirname, "katex-styles.web.ts"),
|
||||
"utf8",
|
||||
);
|
||||
for (const fontFile of woff2Files) {
|
||||
expect(katexStylesSource).toContain(`katex/dist/fonts/${fontFile}`);
|
||||
}
|
||||
expect(katexStylesSource).not.toContain('.woff")');
|
||||
expect(katexStylesSource).not.toContain('.ttf")');
|
||||
expect(katexStylesSource).toContain(".katex{");
|
||||
expect(katexStylesSource).toContain(".enrm-text .katex-display{margin:0}");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -35,7 +35,7 @@ export type { MarkdownDestinations };
|
||||
export type MarkdownSoftBreaks = "break" | "join";
|
||||
|
||||
const ThemedMarkdown = withUnistyles(EnrichedMarkdownText);
|
||||
const MD4C_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true };
|
||||
const MD4C_FLAGS = { latexMath: true, hardSoftBreaks: true, admonitions: true };
|
||||
const JOINED_SOFT_BREAKS_MD4C_FLAGS = { ...MD4C_FLAGS, hardSoftBreaks: false };
|
||||
|
||||
// Reading the breakpoint here makes Unistyles restyle the text when the layout crosses it.
|
||||
|
||||
@@ -8,10 +8,11 @@ import {
|
||||
type ComponentProps,
|
||||
type MouseEvent,
|
||||
} from "react";
|
||||
import type {
|
||||
CodeBlockRendererProps,
|
||||
LinkRendererProps,
|
||||
MarkdownRenderers,
|
||||
import {
|
||||
registerKaTeXStyleLoader,
|
||||
type CodeBlockRendererProps,
|
||||
type LinkRendererProps,
|
||||
type MarkdownRenderers,
|
||||
} from "react-native-enriched-markdown";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { useFileLink } from "@/assistant-file-links";
|
||||
@@ -151,6 +152,11 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
registerKaTeXStyleLoader(async () => {
|
||||
const mod = await import("./katex-styles.web");
|
||||
mod.ensureKaTeXStyles();
|
||||
});
|
||||
|
||||
export const WEB_RENDERERS: MarkdownRenderers = {
|
||||
codeBlock: WebCodeBlock,
|
||||
link: WebLink,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { pluginOverviewUrl } from "@getpaseo/protocol/plugin-overview";
|
||||
import { classifyAssistantFileLink } from "@/assistant-file-links";
|
||||
import { ASSISTANT_FILE_EXTENSIONS } from "@/assistant-file-links/extensions";
|
||||
import { normalizeMarkdownHtml } from "./html";
|
||||
import { adaptMarkdownMath, isOffsetInRanges } from "./math";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import type { AssistantFileLinkSource } from "@/assistant-file-links";
|
||||
@@ -231,6 +232,8 @@ export function prepareMarkdownSource(
|
||||
} = {},
|
||||
) {
|
||||
source = normalizeMarkdownHtml(source);
|
||||
const { source: adaptedSource, mathRanges } = adaptMarkdownMath(source);
|
||||
source = adaptedSource;
|
||||
const images: MarkdownImage[] = [];
|
||||
let tree: Root | undefined;
|
||||
const getTree = () =>
|
||||
@@ -351,53 +354,59 @@ export function prepareMarkdownSource(
|
||||
edits.push({ start, end: labelStart, text: "" });
|
||||
edits.push({ start: labelEnd, end, text: "" });
|
||||
}
|
||||
function adaptTableHeaderGap(start: number, previous?: Nodes, line?: number) {
|
||||
if (previous?.type !== "paragraph" || previous.position?.end.line !== (line ?? -1) - 1) return;
|
||||
// MD4C only recognizes a table header on the first line of a paragraph.
|
||||
const lineStart =
|
||||
Math.max(source.lastIndexOf("\n", start - 1), source.lastIndexOf("\r", start - 1)) + 1;
|
||||
const newline = source.slice(lineStart - 2, lineStart).replace(/[^\r\n]/g, "");
|
||||
const blank = source.slice(lineStart, start).replace(/[^>]/g, " ").trimEnd();
|
||||
const boundary = lineStart - newline.length;
|
||||
edits.push({ start: boundary, end: lineStart, text: `${newline}${blank}${newline}` });
|
||||
}
|
||||
function adaptTableRow(start: number, end: number) {
|
||||
// MD4C's always-enabled spoiler extension otherwise consumes adjacent cell
|
||||
// delimiters. Spaces keep empty GFM cells empty without producing spoilers.
|
||||
const row = source.slice(start, end);
|
||||
for (const match of row.matchAll(/(?<!\\)\|(?=\|)/g)) {
|
||||
if (isOffsetInRanges(start + match.index, mathRanges)) continue;
|
||||
edits.push({ start: start + match.index + 1, end: start + match.index + 1, text: " " });
|
||||
}
|
||||
}
|
||||
function adaptTextNode(start: number, end: number) {
|
||||
const slice = source.slice(start, end);
|
||||
const text = slice.replace(
|
||||
/(?<!\\)(?:(&(?:#(?:[xX][\da-fA-F]+|\d+)|[a-zA-Z][a-zA-Z\d]+);)|(\|\|))/g,
|
||||
(match, entity: string | undefined, _bars: string | undefined, offset: number) => {
|
||||
if (isOffsetInRanges(start + offset, mathRanges)) return match;
|
||||
if (entity) return decodeString(entity).replace(/[!-/:-@[-`{-~]/g, "\\$&");
|
||||
return "\\|\\|";
|
||||
},
|
||||
);
|
||||
if (text !== slice) edits.push({ start, end, text });
|
||||
}
|
||||
function visit(node: Nodes, previous?: Nodes) {
|
||||
const position = node.position;
|
||||
if (position?.start.offset !== undefined && position.end.offset !== undefined) {
|
||||
const start = position.start.offset;
|
||||
const end = position.end.offset;
|
||||
if (node.type === "paragraph") splitStandaloneImages(node, start, end);
|
||||
if (
|
||||
node.type === "table" &&
|
||||
previous?.type === "paragraph" &&
|
||||
previous.position?.end.line === position.start.line - 1
|
||||
) {
|
||||
// MD4C only recognizes a table header on the first line of a paragraph.
|
||||
const lineStart =
|
||||
Math.max(source.lastIndexOf("\n", start - 1), source.lastIndexOf("\r", start - 1)) + 1;
|
||||
const newline = source.slice(lineStart - 2, lineStart).replace(/[^\r\n]/g, "");
|
||||
const blank = source.slice(lineStart, start).replace(/[^>]/g, " ").trimEnd();
|
||||
const boundary = lineStart - newline.length;
|
||||
edits.push({ start: boundary, end: lineStart, text: `${newline}${blank}${newline}` });
|
||||
}
|
||||
if (httpsOnly) {
|
||||
dropUnsafeDestination(node, start, end);
|
||||
} else if (node.type === "link") {
|
||||
const title = workspaceHoverTitle(node, source.slice(start, end), workspaceRoot);
|
||||
if (title !== null)
|
||||
edits.push({ start: end - 1, end: end - 1, text: ` ${JSON.stringify(title)}` });
|
||||
}
|
||||
if (node.type === "tableRow") {
|
||||
// MD4C's always-enabled spoiler extension otherwise consumes adjacent cell
|
||||
// delimiters. Spaces keep empty GFM cells empty without producing spoilers.
|
||||
const row = source.slice(start, end);
|
||||
for (const match of row.matchAll(/(?<!\\)\|(?=\|)/g)) {
|
||||
edits.push({ start: start + match.index + 1, end: start + match.index + 1, text: " " });
|
||||
if (node.type === "table") adaptTableHeaderGap(start, previous, position.start.line);
|
||||
if (!isOffsetInRanges(start, mathRanges)) {
|
||||
if (httpsOnly) {
|
||||
dropUnsafeDestination(node, start, end);
|
||||
} else if (node.type === "link") {
|
||||
const title = workspaceHoverTitle(node, source.slice(start, end), workspaceRoot);
|
||||
if (title !== null)
|
||||
edits.push({ start: end - 1, end: end - 1, text: ` ${JSON.stringify(title)}` });
|
||||
}
|
||||
}
|
||||
if (node.type === "tableRow") adaptTableRow(start, end);
|
||||
if (node.type === "image" || node.type === "imageReference") {
|
||||
collectImage(node, start, end);
|
||||
if (!isOffsetInRanges(start, mathRanges)) collectImage(node, start, end);
|
||||
return;
|
||||
}
|
||||
if (node.type === "text") {
|
||||
const text = source
|
||||
.slice(start, end)
|
||||
.replace(/(?<!\\)&(?:#(?:[xX][\da-fA-F]+|\d+)|[a-zA-Z][a-zA-Z\d]+);/g, (entity) =>
|
||||
decodeString(entity).replace(/[!-/:-@[-`{-~]/g, "\\$&"),
|
||||
)
|
||||
.replace(/(?<!\\)\|\|/g, "\\|\\|");
|
||||
if (text !== source.slice(start, end)) edits.push({ start, end, text });
|
||||
}
|
||||
if (node.type === "text") adaptTextNode(start, end);
|
||||
}
|
||||
if ("children" in node)
|
||||
node.children.forEach((child, index) => visit(child, node.children[index - 1]));
|
||||
|
||||
@@ -1,3 +1,22 @@
|
||||
import {
|
||||
checkFenceContainerExit,
|
||||
isAsciiAlnum,
|
||||
isAsciiPunctuation,
|
||||
isBlankRange,
|
||||
isClosingFenceAt,
|
||||
matchListMarkerAt,
|
||||
measureIndentAt,
|
||||
parseFenceOpenerAt,
|
||||
stripBlockquotesAt,
|
||||
} from "./block-scan";
|
||||
import {
|
||||
isUnclosedInlineMathCandidate,
|
||||
matchClosedBracketMath,
|
||||
matchClosedDollarDisplayMath,
|
||||
matchClosedInlineMath,
|
||||
matchClosedParenMath,
|
||||
} from "./math";
|
||||
|
||||
/**
|
||||
* Sentinel destination for incomplete links while streaming. Web renders it as a
|
||||
* non-interactive link-styled span; native styles it as a link and ignores taps.
|
||||
@@ -15,8 +34,17 @@ interface OpenFence {
|
||||
char: "`" | "~";
|
||||
length: number;
|
||||
lineStart: number;
|
||||
lastLineStart: number;
|
||||
quoteDepth: number;
|
||||
maxCloseIndent: number;
|
||||
listMinIndent: number;
|
||||
hasContent: boolean;
|
||||
}
|
||||
|
||||
interface OpenDisplayMath {
|
||||
kind: "$$" | "\\[";
|
||||
withholdFrom: number;
|
||||
quoteDepth: number;
|
||||
hasContent: boolean;
|
||||
}
|
||||
|
||||
@@ -24,7 +52,9 @@ interface FenceScanCheckpoint {
|
||||
/** Exact prefix of completed lines already scanned (ends at `\n` or `\r`, or is `""`). */
|
||||
scannedPrefix: string;
|
||||
openFence: OpenFence | null;
|
||||
openDisplayMath: OpenDisplayMath | null;
|
||||
listContentIndent: number;
|
||||
listQuoteDepth: number;
|
||||
/** Start offset of the most recent closing fence line, or -1 if none. */
|
||||
lastClosedFenceLineStart: number;
|
||||
}
|
||||
@@ -110,76 +140,20 @@ function lastCompletedLineEnd(source: string): number {
|
||||
return lastBreak === -1 ? 0 : lastBreak + 1;
|
||||
}
|
||||
|
||||
/** Strip leading CommonMark blockquote markers (`> `) and return quote depth + content offset. */
|
||||
function stripBlockquotes(text: string): { quoteDepth: number; offset: number } {
|
||||
let offset = 0;
|
||||
let quoteDepth = 0;
|
||||
while (offset < text.length) {
|
||||
let spaces = 0;
|
||||
let cursor = offset;
|
||||
while (cursor < text.length && text[cursor] === " " && spaces < 3) {
|
||||
cursor++;
|
||||
spaces++;
|
||||
}
|
||||
if (text[cursor] !== ">") break;
|
||||
quoteDepth++;
|
||||
cursor++;
|
||||
if (text[cursor] === " " || text[cursor] === "\t") cursor++;
|
||||
offset = cursor;
|
||||
}
|
||||
return { quoteDepth, offset };
|
||||
return stripBlockquotesAt(text, 0, text.length);
|
||||
}
|
||||
|
||||
function measureIndent(text: string, from: number): { spaces: number; offset: number } {
|
||||
let spaces = 0;
|
||||
let offset = from;
|
||||
while (offset < text.length) {
|
||||
const ch = text[offset];
|
||||
if (ch === " ") {
|
||||
spaces++;
|
||||
offset++;
|
||||
} else if (ch === "\t") {
|
||||
spaces += 4 - (spaces % 4);
|
||||
offset++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { spaces, offset };
|
||||
return measureIndentAt(text, from, text.length);
|
||||
}
|
||||
|
||||
function matchListMarker(
|
||||
text: string,
|
||||
from: number,
|
||||
maxIndent = Number.POSITIVE_INFINITY,
|
||||
): { markerEnd: number; contentIndent: number } | null {
|
||||
const { spaces, offset } = measureIndent(text, from);
|
||||
if (offset >= text.length) return null;
|
||||
const ch = text[offset];
|
||||
if (ch === "-" || ch === "*" || ch === "+") {
|
||||
const after = offset + 1;
|
||||
if (after < text.length && (text[after] === " " || text[after] === "\t")) {
|
||||
return { markerEnd: after + 1, contentIndent: spaces + 2 };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (ch >= "0" && ch <= "9") {
|
||||
let cursor = offset;
|
||||
while (
|
||||
cursor < text.length &&
|
||||
text[cursor] >= "0" &&
|
||||
text[cursor] <= "9" &&
|
||||
cursor - offset < 9
|
||||
) {
|
||||
cursor++;
|
||||
}
|
||||
if (cursor < text.length && (text[cursor] === "." || text[cursor] === ")")) {
|
||||
const after = cursor + 1;
|
||||
if (after < text.length && (text[after] === " " || text[after] === "\t")) {
|
||||
return { markerEnd: after + 1, contentIndent: spaces + (after - offset) + 1 };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
return matchListMarkerAt(text, from, text.length, maxIndent);
|
||||
}
|
||||
|
||||
function parseFenceOpener(
|
||||
@@ -187,17 +161,7 @@ function parseFenceOpener(
|
||||
from: number,
|
||||
maxIndent: number,
|
||||
): { char: "`" | "~"; length: number; info: string } | null {
|
||||
const { spaces, offset } = measureIndent(text, from);
|
||||
if (spaces > maxIndent || offset >= text.length) return null;
|
||||
const ch = text[offset];
|
||||
if (ch !== "`" && ch !== "~") return null;
|
||||
let cursor = offset;
|
||||
while (cursor < text.length && text[cursor] === ch) cursor++;
|
||||
const length = cursor - offset;
|
||||
if (length < 3) return null;
|
||||
const info = text.slice(cursor);
|
||||
if (ch === "`" && info.includes("`")) return null;
|
||||
return { char: ch, length, info };
|
||||
return parseFenceOpenerAt(text, from, text.length, maxIndent);
|
||||
}
|
||||
|
||||
function isClosingFence(
|
||||
@@ -207,16 +171,7 @@ function isClosingFence(
|
||||
char: "`" | "~",
|
||||
minLength: number,
|
||||
): boolean {
|
||||
const { spaces, offset } = measureIndent(text, from);
|
||||
if (spaces > maxIndent || offset >= text.length || text[offset] !== char) return false;
|
||||
let cursor = offset;
|
||||
while (cursor < text.length && text[cursor] === char) cursor++;
|
||||
if (cursor - offset < minLength) return false;
|
||||
while (cursor < text.length) {
|
||||
if (text[cursor] !== " " && text[cursor] !== "\t") return false;
|
||||
cursor++;
|
||||
}
|
||||
return true;
|
||||
return isClosingFenceAt(text, from, text.length, maxIndent, char, minLength);
|
||||
}
|
||||
|
||||
function isPartialClosingFence(
|
||||
@@ -237,18 +192,191 @@ function isPartialClosingFence(
|
||||
}
|
||||
|
||||
function isBlankRest(text: string, from: number): boolean {
|
||||
for (let i = from; i < text.length; i++) {
|
||||
if (text[i] !== " " && text[i] !== "\t") return false;
|
||||
}
|
||||
return true;
|
||||
return isBlankRange(text, from, text.length);
|
||||
}
|
||||
|
||||
interface FenceStepState {
|
||||
openFence: OpenFence | null;
|
||||
openDisplayMath: OpenDisplayMath | null;
|
||||
listContentIndent: number;
|
||||
listQuoteDepth: number;
|
||||
lastClosedFenceLineStart: number;
|
||||
}
|
||||
|
||||
function hasTrailingOddBackslash(text: string): boolean {
|
||||
let backslashes = 0;
|
||||
for (let i = text.length - 1; i >= 0 && text[i] === "\\"; i--) backslashes++;
|
||||
return backslashes % 2 === 1;
|
||||
}
|
||||
|
||||
function hasTrailingPartialDoubleDollarCloser(text: string): boolean {
|
||||
if (!text.endsWith("$")) return false;
|
||||
if (text.length >= 2 && text[text.length - 2] === "$") return false;
|
||||
return !hasTrailingOddBackslash(text.slice(0, -1));
|
||||
}
|
||||
|
||||
function findSameLineBracketClose(text: string, from: number): number {
|
||||
let j = from;
|
||||
while (j < text.length) {
|
||||
if (text[j] === "\\" && text[j + 1] === "]") return j + 2;
|
||||
if (text[j] === "\\" && j + 1 < text.length) {
|
||||
j += 2;
|
||||
continue;
|
||||
}
|
||||
j++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function findSameLineDoubleDollarClose(text: string, from: number): number {
|
||||
let j = from;
|
||||
while (j < text.length) {
|
||||
if (text[j] === "\\" && j + 1 < text.length) {
|
||||
j += 2;
|
||||
continue;
|
||||
}
|
||||
if (text[j] === "$" && text[j + 1] === "$") {
|
||||
let closeEnd = j;
|
||||
while (closeEnd < text.length && text[closeEnd] === "$") closeEnd++;
|
||||
if (closeEnd - j === 2) return closeEnd;
|
||||
j = closeEnd;
|
||||
continue;
|
||||
}
|
||||
j++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function openDisplayMathFromLine(
|
||||
kind: "$$" | "\\[",
|
||||
text: string,
|
||||
from: number,
|
||||
openIndex: number,
|
||||
restStart: number,
|
||||
lineStart: number,
|
||||
quoteDepth: number,
|
||||
isTrailingPartialLine: boolean,
|
||||
): OpenDisplayMath {
|
||||
const withholdFrom = isBlankRest(text.slice(from, openIndex), 0)
|
||||
? lineStart
|
||||
: lineStart + openIndex;
|
||||
const rest = text.slice(restStart);
|
||||
const effectiveRest =
|
||||
kind === "\\[" && isTrailingPartialLine && hasTrailingOddBackslash(rest)
|
||||
? rest.slice(0, -1)
|
||||
: rest;
|
||||
return {
|
||||
kind,
|
||||
withholdFrom,
|
||||
quoteDepth,
|
||||
hasContent: !isBlankRest(effectiveRest, 0),
|
||||
};
|
||||
}
|
||||
|
||||
function scanLineForDisplayMath(
|
||||
text: string,
|
||||
from: number,
|
||||
lineStart: number,
|
||||
quoteDepth: number,
|
||||
isTrailingPartialLine: boolean,
|
||||
state: FenceStepState,
|
||||
): void {
|
||||
let k = from;
|
||||
while (k < text.length) {
|
||||
const ch = text[k];
|
||||
if (ch === "\\") {
|
||||
if (text[k + 1] === "[") {
|
||||
const closeEnd = findSameLineBracketClose(text, k + 2);
|
||||
if (closeEnd !== -1) {
|
||||
k = closeEnd;
|
||||
continue;
|
||||
}
|
||||
state.openDisplayMath = openDisplayMathFromLine(
|
||||
"\\[",
|
||||
text,
|
||||
from,
|
||||
k,
|
||||
k + 2,
|
||||
lineStart,
|
||||
quoteDepth,
|
||||
isTrailingPartialLine,
|
||||
);
|
||||
return;
|
||||
}
|
||||
k += k + 1 < text.length && isAsciiPunctuation(text[k + 1]) ? 2 : 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "`") {
|
||||
let runEnd = k;
|
||||
while (runEnd < text.length && text[runEnd] === "`") runEnd++;
|
||||
const closePos = findMatchingBacktickRun(text, runEnd, runEnd - k);
|
||||
k = closePos !== -1 ? closePos + (runEnd - k) : runEnd;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$") {
|
||||
let runEnd = k;
|
||||
while (runEnd < text.length && text[runEnd] === "$") runEnd++;
|
||||
if (runEnd - k === 2) {
|
||||
const closeEnd = findSameLineDoubleDollarClose(text, runEnd);
|
||||
if (closeEnd !== -1) {
|
||||
k = closeEnd;
|
||||
continue;
|
||||
}
|
||||
state.openDisplayMath = openDisplayMathFromLine(
|
||||
"$$",
|
||||
text,
|
||||
from,
|
||||
k,
|
||||
runEnd,
|
||||
lineStart,
|
||||
quoteDepth,
|
||||
isTrailingPartialLine,
|
||||
);
|
||||
return;
|
||||
}
|
||||
k = runEnd;
|
||||
continue;
|
||||
}
|
||||
k++;
|
||||
}
|
||||
}
|
||||
|
||||
function stepOpenDisplayMathLine(
|
||||
text: string,
|
||||
offset: number,
|
||||
lineStart: number,
|
||||
quoteDepth: number,
|
||||
isTrailingPartialLine: boolean,
|
||||
state: FenceStepState,
|
||||
): boolean {
|
||||
const open = state.openDisplayMath!;
|
||||
if (quoteDepth < open.quoteDepth) {
|
||||
state.openDisplayMath = null;
|
||||
return false;
|
||||
}
|
||||
const closeEnd =
|
||||
open.kind === "$$"
|
||||
? findSameLineDoubleDollarClose(text, offset)
|
||||
: findSameLineBracketClose(text, offset);
|
||||
if (closeEnd !== -1) {
|
||||
state.openDisplayMath = null;
|
||||
state.lastClosedFenceLineStart = lineStart;
|
||||
scanLineForDisplayMath(text, closeEnd, lineStart, quoteDepth, isTrailingPartialLine, state);
|
||||
return true;
|
||||
}
|
||||
const rest = text.slice(offset);
|
||||
let effectiveRest = rest;
|
||||
if (isTrailingPartialLine) {
|
||||
if (open.kind === "$$" && hasTrailingPartialDoubleDollarCloser(rest)) {
|
||||
effectiveRest = rest.slice(0, -1);
|
||||
} else if (open.kind === "\\[" && hasTrailingOddBackslash(rest)) {
|
||||
effectiveRest = rest.slice(0, -1);
|
||||
}
|
||||
}
|
||||
if (!isBlankRest(effectiveRest, 0)) open.hasContent = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
function stepFenceLine(
|
||||
text: string,
|
||||
lineStart: number,
|
||||
@@ -258,8 +386,17 @@ function stepFenceLine(
|
||||
const { quoteDepth, offset } = stripBlockquotes(text);
|
||||
|
||||
if (state.openFence !== null) {
|
||||
if (quoteDepth < state.openFence.quoteDepth) {
|
||||
// Leaving the blockquote closes any fence opened inside it.
|
||||
if (
|
||||
checkFenceContainerExit(
|
||||
text,
|
||||
0,
|
||||
text.length,
|
||||
state.openFence.quoteDepth,
|
||||
state.openFence.listMinIndent,
|
||||
).exited
|
||||
) {
|
||||
// Leaving the blockquote or enclosing list closes any fence opened inside it.
|
||||
state.lastClosedFenceLineStart = state.openFence.lastLineStart;
|
||||
state.openFence = null;
|
||||
} else if (
|
||||
isClosingFence(
|
||||
@@ -274,6 +411,7 @@ function stepFenceLine(
|
||||
state.openFence = null;
|
||||
return;
|
||||
} else {
|
||||
state.openFence.lastLineStart = lineStart;
|
||||
const partialCloser =
|
||||
isTrailingPartialLine &&
|
||||
quoteDepth === state.openFence.quoteDepth &&
|
||||
@@ -289,34 +427,62 @@ function stepFenceLine(
|
||||
}
|
||||
}
|
||||
|
||||
if (isBlankRest(text, offset)) return;
|
||||
if (
|
||||
state.openDisplayMath !== null &&
|
||||
stepOpenDisplayMathLine(text, offset, lineStart, quoteDepth, isTrailingPartialLine, state)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isBlankRest(text, offset)) {
|
||||
if (quoteDepth < state.listQuoteDepth) {
|
||||
state.listContentIndent = 0;
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (quoteDepth < state.listQuoteDepth) {
|
||||
state.listContentIndent = 0;
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
}
|
||||
|
||||
let cursor = offset;
|
||||
let lineIndentBase = state.listContentIndent;
|
||||
let lineIndentBase = quoteDepth === state.listQuoteDepth ? state.listContentIndent : 0;
|
||||
const { spaces: firstSpaces } = measureIndent(text, cursor);
|
||||
if (firstSpaces < state.listContentIndent) {
|
||||
if (quoteDepth === state.listQuoteDepth && firstSpaces < state.listContentIndent) {
|
||||
state.listContentIndent = 0;
|
||||
lineIndentBase = 0;
|
||||
}
|
||||
let marker = matchListMarker(text, cursor);
|
||||
let peeledList = false;
|
||||
let marker = matchListMarker(text, cursor, lineIndentBase + 3);
|
||||
while (marker) {
|
||||
state.listContentIndent = marker.contentIndent;
|
||||
lineIndentBase = marker.contentIndent;
|
||||
const markerBase = cursor === offset ? 0 : lineIndentBase;
|
||||
const totalIndent = markerBase + marker.contentIndent;
|
||||
state.listContentIndent = totalIndent;
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
lineIndentBase = totalIndent;
|
||||
cursor = marker.markerEnd;
|
||||
marker = matchListMarker(text, cursor);
|
||||
peeledList = true;
|
||||
marker = matchListMarker(text, cursor, 3);
|
||||
}
|
||||
|
||||
const opener = parseFenceOpener(text, cursor, lineIndentBase + 3);
|
||||
const opener = parseFenceOpener(text, cursor, peeledList ? 3 : lineIndentBase + 3);
|
||||
if (opener) {
|
||||
state.openFence = {
|
||||
char: opener.char,
|
||||
length: opener.length,
|
||||
lineStart,
|
||||
lastLineStart: lineStart,
|
||||
quoteDepth,
|
||||
maxCloseIndent: lineIndentBase + 3,
|
||||
listMinIndent: lineIndentBase,
|
||||
hasContent: false,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
scanLineForDisplayMath(text, offset, lineStart, quoteDepth, isTrailingPartialLine, state);
|
||||
}
|
||||
|
||||
function advanceFenceRange(source: string, from: number, to: number, state: FenceStepState): void {
|
||||
@@ -339,18 +505,28 @@ function cloneOpenFence(fence: OpenFence | null): OpenFence | null {
|
||||
return fence ? { ...fence } : null;
|
||||
}
|
||||
|
||||
function cloneOpenDisplayMath(math: OpenDisplayMath | null): OpenDisplayMath | null {
|
||||
return math ? { ...math } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Incrementally advance fence tracking across completed lines so steady-state
|
||||
* Incrementally advance fence and display-math tracking across completed lines so steady-state
|
||||
* streaming frames within a line scan 0 prior lines, and each newline scans 1 line.
|
||||
*/
|
||||
function resolveFenceState(
|
||||
source: string,
|
||||
checkpoint: FenceScanCheckpoint | null,
|
||||
): { openFence: OpenFence | null; lastClosedFenceLineStart: number } {
|
||||
): {
|
||||
openFence: OpenFence | null;
|
||||
openDisplayMath: OpenDisplayMath | null;
|
||||
lastClosedFenceLineStart: number;
|
||||
} {
|
||||
const completedEnd = lastCompletedLineEnd(source);
|
||||
const state: FenceStepState = {
|
||||
openFence: null,
|
||||
openDisplayMath: null,
|
||||
listContentIndent: 0,
|
||||
listQuoteDepth: 0,
|
||||
lastClosedFenceLineStart: -1,
|
||||
};
|
||||
|
||||
@@ -361,7 +537,9 @@ function resolveFenceState(
|
||||
source.startsWith(checkpoint.scannedPrefix);
|
||||
if (matchedPrefix && checkpoint) {
|
||||
state.openFence = cloneOpenFence(checkpoint.openFence);
|
||||
state.openDisplayMath = cloneOpenDisplayMath(checkpoint.openDisplayMath);
|
||||
state.listContentIndent = checkpoint.listContentIndent;
|
||||
state.listQuoteDepth = checkpoint.listQuoteDepth;
|
||||
state.lastClosedFenceLineStart = checkpoint.lastClosedFenceLineStart;
|
||||
scanFrom = checkpoint.scannedPrefix.length;
|
||||
}
|
||||
@@ -373,7 +551,9 @@ function resolveFenceState(
|
||||
if (checkpoint && (!matchedPrefix || completedEnd !== checkpoint.scannedPrefix.length)) {
|
||||
checkpoint.scannedPrefix = source.slice(0, completedEnd);
|
||||
checkpoint.openFence = cloneOpenFence(state.openFence);
|
||||
checkpoint.openDisplayMath = cloneOpenDisplayMath(state.openDisplayMath);
|
||||
checkpoint.listContentIndent = state.listContentIndent;
|
||||
checkpoint.listQuoteDepth = state.listQuoteDepth;
|
||||
checkpoint.lastClosedFenceLineStart = state.lastClosedFenceLineStart;
|
||||
}
|
||||
|
||||
@@ -383,6 +563,7 @@ function resolveFenceState(
|
||||
|
||||
return {
|
||||
openFence: state.openFence,
|
||||
openDisplayMath: state.openDisplayMath,
|
||||
lastClosedFenceLineStart: state.lastClosedFenceLineStart,
|
||||
};
|
||||
}
|
||||
@@ -663,17 +844,6 @@ function isWhitespaceChar(ch: string | undefined): boolean {
|
||||
return ch === undefined || ch === " " || ch === "\t" || ch === "\n" || ch === "\r";
|
||||
}
|
||||
|
||||
function isAsciiPunctuation(ch: string | undefined): boolean {
|
||||
if (!ch) return false;
|
||||
const code = ch.charCodeAt(0);
|
||||
return (
|
||||
(code >= 0x21 && code <= 0x2f) ||
|
||||
(code >= 0x3a && code <= 0x40) ||
|
||||
(code >= 0x5b && code <= 0x60) ||
|
||||
(code >= 0x7b && code <= 0x7e)
|
||||
);
|
||||
}
|
||||
|
||||
function isUnicodePunctuation(ch: string | undefined): boolean {
|
||||
if (!ch) return false;
|
||||
if (isAsciiPunctuation(ch)) return true;
|
||||
@@ -861,6 +1031,7 @@ interface InlineScanState {
|
||||
stack: InlineStackEntry[];
|
||||
openCode: { pos: number; length: number; contentStart: number } | null;
|
||||
openHtmlPos: number | null;
|
||||
openInlineMathPos: number | null;
|
||||
trailingBackslash: boolean;
|
||||
}
|
||||
|
||||
@@ -1153,7 +1324,7 @@ function stripPartialEmphCloser(output: string, entry: EmphEntry): string {
|
||||
|
||||
function unwindInlineState(source: string, state: InlineScanState): string {
|
||||
let output = source;
|
||||
const { openCode, openHtmlPos, trailingBackslash, stack } = state;
|
||||
const { openCode, openHtmlPos, openInlineMathPos, trailingBackslash, stack } = state;
|
||||
|
||||
if (openCode) {
|
||||
let codeContent = output.slice(openCode.contentStart);
|
||||
@@ -1167,6 +1338,8 @@ function unwindInlineState(source: string, state: InlineScanState): string {
|
||||
: output.slice(0, openCode.contentStart) + codeContent + "`".repeat(openCode.length);
|
||||
} else if (openHtmlPos !== null) {
|
||||
output = output.slice(0, openHtmlPos);
|
||||
} else if (openInlineMathPos !== null) {
|
||||
output = output.slice(0, openInlineMathPos);
|
||||
} else if (trailingBackslash) {
|
||||
output = output.slice(0, -1);
|
||||
}
|
||||
@@ -1210,6 +1383,56 @@ function scanBacktickToken(source: string, i: number, state: InlineScanState): n
|
||||
return null;
|
||||
}
|
||||
|
||||
function isOnTrailingLine(source: string, from: number): boolean {
|
||||
return source.indexOf("\n", from) === -1 && source.indexOf("\r", from) === -1;
|
||||
}
|
||||
|
||||
function scanInlineBackslashToken(
|
||||
source: string,
|
||||
i: number,
|
||||
state: InlineScanState,
|
||||
): number | null {
|
||||
if (source[i + 1] === "(") {
|
||||
const closedParen = matchClosedParenMath(source, i);
|
||||
if (closedParen !== -1) return closedParen;
|
||||
if (isOnTrailingLine(source, i + 2)) {
|
||||
if (i + 2 === source.length) state.openInlineMathPos = i;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (source[i + 1] === "[") {
|
||||
const closedBracket = matchClosedBracketMath(source, i);
|
||||
if (closedBracket !== -1) return closedBracket;
|
||||
}
|
||||
if (i + 1 === source.length) {
|
||||
state.trailingBackslash = true;
|
||||
return null;
|
||||
}
|
||||
return i + (isAsciiPunctuation(source[i + 1]) ? 2 : 1);
|
||||
}
|
||||
|
||||
function scanInlineDollarToken(source: string, i: number, state: InlineScanState): number | null {
|
||||
if (source[i + 1] === "$") {
|
||||
const closedDisplay = matchClosedDollarDisplayMath(source, i);
|
||||
if (closedDisplay !== -1) return closedDisplay;
|
||||
let runEnd = i;
|
||||
while (runEnd < source.length && source[runEnd] === "$") runEnd++;
|
||||
return runEnd;
|
||||
}
|
||||
const closedInline = matchClosedInlineMath(source, i);
|
||||
if (closedInline !== -1) return closedInline;
|
||||
if (isOnTrailingLine(source, i + 1)) {
|
||||
const charBefore = i > 0 ? source[i - 1] : undefined;
|
||||
const validOpenerFlank = charBefore !== "\\" && charBefore !== "$" && !isAsciiAlnum(charBefore);
|
||||
if (i + 1 === source.length && validOpenerFlank) {
|
||||
state.openInlineMathPos = i;
|
||||
return null;
|
||||
}
|
||||
if (isUnclosedInlineMathCandidate(source, i)) return null;
|
||||
}
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
function stepInlineScanner(
|
||||
source: string,
|
||||
i: number,
|
||||
@@ -1219,13 +1442,8 @@ function stepInlineScanner(
|
||||
): number | null {
|
||||
const ch = source[i];
|
||||
if (ch === "\n") return lineContentStarts.get(i + 1) ?? i + 1;
|
||||
if (ch === "\\") {
|
||||
if (i + 1 === source.length) {
|
||||
state.trailingBackslash = true;
|
||||
return null;
|
||||
}
|
||||
return i + (isAsciiPunctuation(source[i + 1]) ? 2 : 1);
|
||||
}
|
||||
if (ch === "\\") return scanInlineBackslashToken(source, i, state);
|
||||
if (ch === "$") return scanInlineDollarToken(source, i, state);
|
||||
if (ch === "`") return scanBacktickToken(source, i, state);
|
||||
if (ch === "<") return scanHtmlToken(source, i, state);
|
||||
if (ch === "[" || (ch === "!" && source[i + 1] === "[")) {
|
||||
@@ -1248,6 +1466,7 @@ function stabilizeInlineBlock(
|
||||
stack: [],
|
||||
openCode: null,
|
||||
openHtmlPos: null,
|
||||
openInlineMathPos: null,
|
||||
trailingBackslash: false,
|
||||
};
|
||||
|
||||
@@ -1259,42 +1478,74 @@ function stabilizeInlineBlock(
|
||||
const hasOpenState =
|
||||
state.openCode !== null ||
|
||||
state.openHtmlPos !== null ||
|
||||
state.openInlineMathPos !== null ||
|
||||
state.stack.length > 0 ||
|
||||
state.trailingBackslash;
|
||||
return hasOpenState ? unwindInlineState(source, state) : source;
|
||||
}
|
||||
|
||||
function stabilizeOpenFence(
|
||||
source: string,
|
||||
openFence: OpenFence,
|
||||
endsWithNewline: boolean,
|
||||
): string {
|
||||
if (!openFence.hasContent) {
|
||||
return source.slice(0, openFence.lineStart);
|
||||
}
|
||||
if (!endsWithNewline) {
|
||||
const last = prevLineSlice(source, source.length);
|
||||
if (last) {
|
||||
const lastText = lineText(source, last);
|
||||
const lastQ = stripBlockquotes(lastText);
|
||||
if (
|
||||
lastQ.quoteDepth === openFence.quoteDepth &&
|
||||
(isPartialClosingFence(
|
||||
lastText,
|
||||
lastQ.offset,
|
||||
openFence.maxCloseIndent,
|
||||
openFence.char,
|
||||
openFence.length,
|
||||
) ||
|
||||
(openFence.quoteDepth > 0 && isBlankRest(lastText, lastQ.offset)))
|
||||
) {
|
||||
return source.slice(0, last.start);
|
||||
}
|
||||
}
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
function stabilizeOpenDisplayMath(
|
||||
source: string,
|
||||
openDisplayMath: OpenDisplayMath,
|
||||
endsWithNewline: boolean,
|
||||
): string {
|
||||
if (!openDisplayMath.hasContent) {
|
||||
return source.slice(0, openDisplayMath.withholdFrom);
|
||||
}
|
||||
if (!endsWithNewline) {
|
||||
if (openDisplayMath.kind === "$$" && hasTrailingPartialDoubleDollarCloser(source)) {
|
||||
return source.slice(0, -1);
|
||||
}
|
||||
if (openDisplayMath.kind === "\\[" && hasTrailingOddBackslash(source)) {
|
||||
return source.slice(0, -1);
|
||||
}
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
function stabilizeWithCheckpoint(source: string, checkpoint: FenceScanCheckpoint | null): string {
|
||||
if (source.length === 0) return source;
|
||||
const endsWithNewline = sourceEndsWithNewline(source);
|
||||
|
||||
// 1. Fenced code blocks (top-level, quoted, or inside lists) — O(new lines) when incremental.
|
||||
const { openFence, lastClosedFenceLineStart } = resolveFenceState(source, checkpoint);
|
||||
if (openFence !== null) {
|
||||
if (!openFence.hasContent) {
|
||||
return source.slice(0, openFence.lineStart);
|
||||
}
|
||||
if (!endsWithNewline) {
|
||||
const last = prevLineSlice(source, source.length);
|
||||
if (last) {
|
||||
const lastText = lineText(source, last);
|
||||
const lastQ = stripBlockquotes(lastText);
|
||||
if (
|
||||
lastQ.quoteDepth === openFence.quoteDepth &&
|
||||
(isPartialClosingFence(
|
||||
lastText,
|
||||
lastQ.offset,
|
||||
openFence.maxCloseIndent,
|
||||
openFence.char,
|
||||
openFence.length,
|
||||
) ||
|
||||
(openFence.quoteDepth > 0 && isBlankRest(lastText, lastQ.offset)))
|
||||
) {
|
||||
return source.slice(0, last.start);
|
||||
}
|
||||
}
|
||||
}
|
||||
return source;
|
||||
// 1. Fenced code blocks & display math blocks — O(new lines) when incremental.
|
||||
const { openFence, openDisplayMath, lastClosedFenceLineStart } = resolveFenceState(
|
||||
source,
|
||||
checkpoint,
|
||||
);
|
||||
if (openFence !== null) return stabilizeOpenFence(source, openFence, endsWithNewline);
|
||||
if (openDisplayMath !== null) {
|
||||
return stabilizeOpenDisplayMath(source, openDisplayMath, endsWithNewline);
|
||||
}
|
||||
|
||||
// 2. Trailing GFM table — O(table rows) backwards from EOF.
|
||||
@@ -1330,7 +1581,9 @@ export function createStreamingMarkdownStabilizer(): StreamingMarkdownStabilizer
|
||||
const checkpoint: FenceScanCheckpoint = {
|
||||
scannedPrefix: "",
|
||||
openFence: null,
|
||||
openDisplayMath: null,
|
||||
listContentIndent: 0,
|
||||
listQuoteDepth: 0,
|
||||
lastClosedFenceLineStart: -1,
|
||||
};
|
||||
return {
|
||||
|
||||
@@ -544,3 +544,119 @@ describe("stabilizeStreamingMarkdown — fences, tables, HTML, and full prefix s
|
||||
expect(incremental.stabilize("Plain\nCheck `inline")).toBe("Plain\nCheck `inline`");
|
||||
}, 20000);
|
||||
});
|
||||
|
||||
describe("streaming Markdown math safety", () => {
|
||||
it("keeps open multiline $$, \\[, and ```math blocks in the tail without splitting mid-equation", () => {
|
||||
const blocks = ["$$\na = 1\n\nb = 2\n", "\\[\na = 1\n\nb = 2\n", "```math\na = 1\n\nb = 2\n"];
|
||||
for (const openMath of blocks) {
|
||||
const source = `Intro.\n\n${openMath}`;
|
||||
const split = splitOnce(source);
|
||||
expect(split.head).toBe("Intro.\n\n");
|
||||
expect(split.tail).toBe(openMath);
|
||||
}
|
||||
|
||||
// Even after a blank-line $$ or \[ block closes, it stays together until a following block arrives.
|
||||
const closedDollar = "Intro.\n\n$$\na = 1\n\nb = 2\n$$\n";
|
||||
expect(splitOnce(closedDollar)).toEqual({
|
||||
head: "Intro.\n\n",
|
||||
tail: "$$\na = 1\n\nb = 2\n$$\n",
|
||||
});
|
||||
expect(splitOnce(`${closedDollar}\nAfter.\n`)).toEqual({
|
||||
head: closedDollar + "\n",
|
||||
tail: "After.\n",
|
||||
});
|
||||
|
||||
const closedBracket = "Intro.\n\n\\[\na = 1\n\nb = 2\n\\]\n";
|
||||
expect(splitOnce(closedBracket)).toEqual({
|
||||
head: "Intro.\n\n",
|
||||
tail: "Intro.\n\n\\[\na = 1\n\nb = 2\n\\]\n".slice("Intro.\n\n".length),
|
||||
});
|
||||
expect(splitOnce(`${closedBracket}\nAfter.\n`)).toEqual({
|
||||
head: closedBracket + "\n",
|
||||
tail: "After.\n",
|
||||
});
|
||||
});
|
||||
|
||||
it("withholds dangling math openers and partial closers without auto-closing partial TeX", () => {
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n$$")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n$$\n")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n\\[")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n\\[\n")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n```math")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n```math\n")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Formula: $")).toBe("Formula: ");
|
||||
expect(stabilizeStreamingMarkdown("Formula: \\(")).toBe("Formula: ");
|
||||
// Currency/escaped trailing dollars are not math openers.
|
||||
expect(stabilizeStreamingMarkdown("Price is US$")).toBe("Price is US$");
|
||||
expect(stabilizeStreamingMarkdown("Escaped \\$")).toBe("Escaped \\$");
|
||||
|
||||
// Partial TeX content stays literal and is never auto-closed or mangled by inline emphasis/links.
|
||||
expect(stabilizeStreamingMarkdown("$$\n\\frac{a}{")).toBe("$$\n\\frac{a}{");
|
||||
expect(stabilizeStreamingMarkdown("\\[\n\\frac{a}{")).toBe("\\[\n\\frac{a}{");
|
||||
expect(stabilizeStreamingMarkdown("```math\n\\frac{a}{")).toBe("```math\n\\frac{a}{");
|
||||
expect(stabilizeStreamingMarkdown("Compute $\\alpha + *x")).toBe("Compute $\\alpha + *x");
|
||||
expect(stabilizeStreamingMarkdown("Compute \\(\\alpha + [a")).toBe("Compute \\(\\alpha + [a");
|
||||
|
||||
// Partial closing markers inside open display math are withheld until completed.
|
||||
expect(stabilizeStreamingMarkdown("$$\n\\frac{a}{b}\n$")).toBe("$$\n\\frac{a}{b}\n");
|
||||
expect(stabilizeStreamingMarkdown("\\[\n\\frac{a}{b}\n\\")).toBe("\\[\n\\frac{a}{b}\n");
|
||||
|
||||
// Currency dollars do not suppress emphasis stabilization later on the line.
|
||||
expect(stabilizeStreamingMarkdown("Costs $5 and **bold")).toBe("Costs $5 and **bold**");
|
||||
// Closed inline math protects internal * / _ from emphasis stabilization.
|
||||
expect(stabilizeStreamingMarkdown("Compute $a * b$ and **bold")).toBe(
|
||||
"Compute $a * b$ and **bold**",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("Compute \\(a * b\\) and **bold")).toBe(
|
||||
"Compute \\(a * b\\) and **bold**",
|
||||
);
|
||||
|
||||
// An unclosed list-nested fence ends once a non-blank line exits the list container.
|
||||
expect(stabilizeStreamingMarkdown("- ~~~sh\n echo ok\nOutside\n$$")).toBe(
|
||||
"- ~~~sh\n echo ok\nOutside\n",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("- ~~~sh\n echo ok\nOutside **bo")).toBe(
|
||||
"- ~~~sh\n echo ok\nOutside **bo**",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("- ```sh\n echo ok\nOutside **bo")).toBe(
|
||||
"- ```sh\n echo ok\nOutside **bo**",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("- item\n - ```\n code\n back **bo")).toBe(
|
||||
"- item\n - ```\n code\n back **bo**",
|
||||
);
|
||||
// Exiting a deeper quote clears stale list indent so outer quoted code stays open.
|
||||
expect(stabilizeStreamingMarkdown("> > - item\n>\n> ~~~sh\n> echo **bo")).toBe(
|
||||
"> > - item\n>\n> ~~~sh\n> echo **bo",
|
||||
);
|
||||
});
|
||||
|
||||
it("maintains incremental stabilizer parity and idempotence across math streaming prefixes", () => {
|
||||
const sample = [
|
||||
"Inline $a * b$ and \\(c_1 + d_2\\).",
|
||||
"",
|
||||
"$$",
|
||||
"x = 1",
|
||||
"",
|
||||
"y = 2",
|
||||
"$$",
|
||||
"",
|
||||
"\\[",
|
||||
"\\int_0^1 x^2\\,dx",
|
||||
"\\]",
|
||||
"",
|
||||
"```math",
|
||||
"\\sum_{i=1}^n i",
|
||||
"```",
|
||||
"",
|
||||
"Done.",
|
||||
].join("\n");
|
||||
|
||||
const incremental = createStreamingMarkdownStabilizer();
|
||||
for (let end = 0; end <= sample.length; end++) {
|
||||
const prefix = sample.slice(0, end);
|
||||
const stabilized = stabilizeStreamingMarkdown(prefix);
|
||||
expect(incremental.stabilize(prefix), `incremental parity at ${end}`).toBe(stabilized);
|
||||
expect(stabilizeStreamingMarkdown(stabilized), `idempotent at ${end}`).toBe(stabilized);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import type { Nodes, Root } from "mdast";
|
||||
import { findBlockMathSpans } from "./math";
|
||||
|
||||
export {
|
||||
createStreamingMarkdownStabilizer,
|
||||
@@ -80,12 +81,24 @@ export function createStreamingMarkdownSplitter(
|
||||
partStarts = [0];
|
||||
return;
|
||||
}
|
||||
const mathSpans = findBlockMathSpans(open);
|
||||
let settled = 0;
|
||||
for (let index = 0; index < tree.children.length - 1; index++) {
|
||||
if (needsDocumentContext(tree.children[index])) break;
|
||||
// mdast starts some nodes after their indentation; the next parser needs it too.
|
||||
const nextStart = tree.children[index + 1].position!.start.offset!;
|
||||
settled = open.lastIndexOf("\n", nextStart - 1) + 1;
|
||||
const splitAt = open.lastIndexOf("\n", nextStart - 1) + 1;
|
||||
let crossesMath = false;
|
||||
let insideUnclosedMath = false;
|
||||
for (const span of mathSpans) {
|
||||
if (splitAt > span.start && splitAt < span.end) {
|
||||
crossesMath = true;
|
||||
if (span.end === Number.POSITIVE_INFINITY) insideUnclosedMath = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (insideUnclosedMath) break;
|
||||
if (!crossesMath) settled = splitAt;
|
||||
}
|
||||
if (settled === 0) return;
|
||||
if (boundary - partStarts[partStarts.length - 1] >= HEAD_PART_LENGTH) partStarts.push(boundary);
|
||||
|
||||
@@ -103,6 +103,17 @@ export function createMarkdownStyles(
|
||||
inlineImage: { size: paragraph.lineHeight },
|
||||
image: { ...block, height: 320, resizeMode: "contain", borderRadius: 8 },
|
||||
thematicBreak: { ...block, color: theme.colors.border, height: 1 },
|
||||
math: {
|
||||
fontSize,
|
||||
color: paragraph.color,
|
||||
backgroundColor: "transparent",
|
||||
padding: 8,
|
||||
...block,
|
||||
textAlign: "center",
|
||||
},
|
||||
inlineMath: {
|
||||
color: paragraph.color,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1072,7 +1072,7 @@ const expandableBadgeStylesheet = StyleSheet.create((theme) => ({
|
||||
...(isWeb ? { cursor: "auto" as const, userSelect: "text" as const } : {}),
|
||||
},
|
||||
pressableExpanded: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
backgroundColor: theme.colors.surfaceHover,
|
||||
},
|
||||
pressableExpandedAttached: {
|
||||
borderColor: theme.colors.border,
|
||||
|
||||
@@ -2051,13 +2051,13 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
browserModelRow: {},
|
||||
browserRowHovered: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
backgroundColor: theme.colors.surfaceSelected,
|
||||
},
|
||||
browserRowHoveredElevated: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
browserRowPressed: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
backgroundColor: theme.colors.surfaceSelected,
|
||||
},
|
||||
browserRowPressedElevated: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
|
||||
@@ -86,20 +86,20 @@ const styles = StyleSheet.create((theme) => ({
|
||||
width: 14,
|
||||
height: 14,
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
},
|
||||
projectIcon: {
|
||||
width: PROJECT_ICON_SIZE,
|
||||
height: PROJECT_ICON_SIZE,
|
||||
// Matches the real icon it stands in for, so the skeleton doesn't change shape on load.
|
||||
borderRadius: projectIconRadius(PROJECT_ICON_SIZE),
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
},
|
||||
sectionTitle: {
|
||||
width: "45%",
|
||||
height: 12,
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
},
|
||||
rows: {
|
||||
gap: theme.spacing[1],
|
||||
@@ -116,18 +116,18 @@ const styles = StyleSheet.create((theme) => ({
|
||||
width: 8,
|
||||
height: 8,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
},
|
||||
rowTitle: {
|
||||
flex: 1,
|
||||
height: 12,
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
},
|
||||
rowBadge: {
|
||||
width: 40,
|
||||
height: 20,
|
||||
borderRadius: theme.borderRadius.md,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -2748,7 +2748,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: theme.colors.surfaceSidebarHover,
|
||||
},
|
||||
newWorkspaceGhostRowPressed: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
},
|
||||
// The width of a workspace row's status slot, so the label lands on the same rail as the
|
||||
// titles above it.
|
||||
@@ -2788,10 +2788,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: theme.colors.surfaceSidebarHover,
|
||||
},
|
||||
projectRowPressed: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
},
|
||||
projectRowDragging: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
transform: [{ scale: 1.02 }],
|
||||
@@ -2874,7 +2874,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
opacity: 0,
|
||||
},
|
||||
projectKebabButtonHovered: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.interactionHighlight,
|
||||
},
|
||||
projectTrailingControlSlot: {
|
||||
width: 24,
|
||||
@@ -2935,10 +2935,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: theme.colors.surfaceSidebarHover,
|
||||
},
|
||||
workspaceRowPressed: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
},
|
||||
workspaceRowDragging: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
transform: [{ scale: 1.02 }],
|
||||
@@ -3007,6 +3007,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
marginLeft: 2,
|
||||
},
|
||||
kebabButtonHovered: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.interactionHighlight,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -308,9 +308,13 @@ export function SidebarDisplayPreferencesMenu(): ReactElement {
|
||||
>
|
||||
<ThemedSettings2 size={14} uniProps={mutedIconMapping} />
|
||||
</MenuTrigger>
|
||||
{/* Host, project, and label pages grow with the host's data, so the popover has to
|
||||
scroll once they outgrow the window. A sheet already scrolls; without this the wide
|
||||
presentation clipped every row past the bottom edge. */}
|
||||
<MenuSurface
|
||||
align="end"
|
||||
width={MENU_WIDTH}
|
||||
scrollable
|
||||
pages={pages}
|
||||
sheetTitle={t("sidebar.display.heading")}
|
||||
testID="sidebar-display-preferences-content"
|
||||
|
||||
@@ -88,7 +88,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: theme.colors.surfaceSidebarHover,
|
||||
},
|
||||
rowPressed: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
},
|
||||
// The width of a workspace row's status slot, so the label lands on the same rail as the
|
||||
// titles above it rather than two points to their left.
|
||||
|
||||
@@ -152,7 +152,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
// The workspace rows' pressed fill.
|
||||
rowPressed: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
},
|
||||
button: {
|
||||
flex: 1,
|
||||
|
||||
@@ -11,4 +11,9 @@ describe("getSidebarRowBackdrop", () => {
|
||||
it("uses the hover surface for an unselected hovered row", () => {
|
||||
expect(getSidebarRowBackdrop({ isHovered: true })).toBe("surfaceSidebarHover");
|
||||
});
|
||||
|
||||
it("uses the selected sidebar surface when pressed or dragging", () => {
|
||||
expect(getSidebarRowBackdrop({ isHighlighted: true })).toBe("surfaceSidebarSelected");
|
||||
expect(getSidebarRowBackdrop({ isDragging: true })).toBe("surfaceSidebarSelected");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -22,8 +22,7 @@ export function getSidebarRowBackdrop({
|
||||
selected?: boolean;
|
||||
isHovered?: boolean;
|
||||
}): SidebarSurfaceBackdrop {
|
||||
if (isDragging || isHighlighted) return "surface2";
|
||||
if (selected) return "surfaceSidebarSelected";
|
||||
if (isDragging || isHighlighted || selected) return "surfaceSidebarSelected";
|
||||
if (isHovered) return "surfaceSidebarHover";
|
||||
return "surfaceSidebar";
|
||||
}
|
||||
|
||||
@@ -1235,7 +1235,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: theme.colors.surfaceSidebarHover,
|
||||
},
|
||||
statusGroupRowPressed: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
},
|
||||
statusGroupRowLeft: {
|
||||
flexDirection: "row",
|
||||
@@ -1286,10 +1286,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: theme.colors.surfaceSidebarHover,
|
||||
},
|
||||
workspaceRowPressed: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
},
|
||||
workspaceRowDragging: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.surfaceSidebarSelected,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
transform: [{ scale: 1.02 }],
|
||||
|
||||
@@ -539,7 +539,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
marginRight: bySizing({ touch: -14, pointer: -7 }),
|
||||
},
|
||||
triggerHovered: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.interactionHighlight,
|
||||
},
|
||||
// The kebab's box without its offsets: the archive glyph fills its view box, so it needs
|
||||
// none of the nudging the three dots do.
|
||||
|
||||
@@ -102,6 +102,8 @@ const styles = StyleSheet.create((theme) => ({
|
||||
surface0: { borderColor: theme.colors.surface0 },
|
||||
surface1: { borderColor: theme.colors.surface1 },
|
||||
surface2: { borderColor: theme.colors.surface2 },
|
||||
surfaceHover: { borderColor: theme.colors.surfaceHover },
|
||||
surfaceSelected: { borderColor: theme.colors.surfaceSelected },
|
||||
surfaceSidebar: { borderColor: theme.colors.surfaceSidebar },
|
||||
surfaceSidebarHover: { borderColor: theme.colors.surfaceSidebarHover },
|
||||
surfaceSidebarSelected: { borderColor: theme.colors.surfaceSidebarSelected },
|
||||
|
||||
@@ -46,6 +46,10 @@ function getBackdropStyle(backdrop: SurfaceBackdrop | null | undefined) {
|
||||
return styles.backdropSurface0;
|
||||
case "surface1":
|
||||
return styles.backdropSurface1;
|
||||
case "surfaceHover":
|
||||
return styles.backdropSurfaceHover;
|
||||
case "surfaceSelected":
|
||||
return styles.backdropSurfaceSelected;
|
||||
case "surfaceSidebar":
|
||||
return styles.backdropSurfaceSidebar;
|
||||
case "surfaceSidebarHover":
|
||||
@@ -90,6 +94,8 @@ export const styles = StyleSheet.create((theme) => {
|
||||
},
|
||||
backdropSurface0: { backgroundColor: theme.colors.surface0 },
|
||||
backdropSurface1: { backgroundColor: theme.colors.surface1 },
|
||||
backdropSurfaceHover: { backgroundColor: theme.colors.surfaceHover },
|
||||
backdropSurfaceSelected: { backgroundColor: theme.colors.surfaceSelected },
|
||||
backdropSurfaceSidebar: { backgroundColor: theme.colors.surfaceSidebar },
|
||||
backdropSurfaceSidebarHover: { backgroundColor: theme.colors.surfaceSidebarHover },
|
||||
backdropSurfaceSidebarSelected: { backgroundColor: theme.colors.surfaceSidebarSelected },
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
import {
|
||||
SafeAreaInsetsContext,
|
||||
useSafeAreaInsets,
|
||||
type EdgeInsets,
|
||||
} from "react-native-safe-area-context";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { SheetBottomInset } from "@/components/adaptive-modal-sheet";
|
||||
import { BottomSafeAreaInset } from "./bottom-safe-area-inset";
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
beforeEach(() => vi.stubGlobal("React", React));
|
||||
|
||||
const FRAME_HEIGHT = 600;
|
||||
const FILL_STYLE = { flex: 1, minHeight: 0 };
|
||||
const BOTTOM_BAR_STYLE = { padding: 12 };
|
||||
const INSETS_48: EdgeInsets = { top: 24, right: 0, bottom: 48, left: 0 };
|
||||
const INSETS_0: EdgeInsets = { top: 0, right: 0, bottom: 0, left: 0 };
|
||||
const NON_ZERO_CASES = [
|
||||
{ bottom: 48, insets: { top: 24, right: 8, bottom: 48, left: 4 } },
|
||||
{ bottom: 34, insets: { top: 24, right: 8, bottom: 34, left: 4 } },
|
||||
] as const;
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
container?.remove();
|
||||
root = null;
|
||||
container = null;
|
||||
});
|
||||
|
||||
function BottomPinnedSurface() {
|
||||
const insets = useSafeAreaInsets();
|
||||
return (
|
||||
<View style={FILL_STYLE}>
|
||||
<View style={FILL_STYLE}>
|
||||
<Text testID="descendant-insets">
|
||||
{`${insets.top}|${insets.right}|${insets.bottom}|${insets.left}`}
|
||||
</Text>
|
||||
</View>
|
||||
<View testID="bottom-bar" style={BOTTOM_BAR_STYLE}>
|
||||
<Pressable accessibilityRole="button">
|
||||
<Text>Submit</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function mount(node: React.ReactNode) {
|
||||
container = document.createElement("div");
|
||||
container.style.width = "390px";
|
||||
container.style.height = `${FRAME_HEIGHT}px`;
|
||||
container.style.display = "flex";
|
||||
container.style.flexDirection = "column";
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => root?.render(node));
|
||||
return container;
|
||||
}
|
||||
|
||||
function queryEl(host: HTMLElement, testID: string): HTMLElement {
|
||||
const el = host.querySelector(`[data-testid="${testID}"]`);
|
||||
if (!(el instanceof HTMLElement)) throw new Error(`Missing element ${testID}`);
|
||||
return el;
|
||||
}
|
||||
|
||||
describe("BottomSafeAreaInset", () => {
|
||||
it.each(NON_ZERO_CASES)(
|
||||
"clears bottom=$bottom in Chromium layout and zeroes descendant bottom inset",
|
||||
({ bottom, insets }) => {
|
||||
const host = mount(
|
||||
<SafeAreaInsetsContext.Provider value={insets}>
|
||||
<BottomSafeAreaInset style={FILL_STYLE} testID="host-boundary">
|
||||
<BottomPinnedSurface />
|
||||
</BottomSafeAreaInset>
|
||||
</SafeAreaInsetsContext.Provider>,
|
||||
);
|
||||
|
||||
const frameRect = host.getBoundingClientRect();
|
||||
const boundary = queryEl(host, "host-boundary");
|
||||
const bottomBarRect = queryEl(host, "bottom-bar").getBoundingClientRect();
|
||||
|
||||
expect(getComputedStyle(boundary).paddingBottom).toBe(`${bottom}px`);
|
||||
expect(bottomBarRect.bottom).toBeLessThanOrEqual(frameRect.bottom - bottom + 1);
|
||||
expect(bottomBarRect.bottom).toBeGreaterThanOrEqual(frameRect.bottom - bottom - 1);
|
||||
expect(queryEl(host, "descendant-insets").textContent).toBe("24|8|0|4");
|
||||
},
|
||||
);
|
||||
|
||||
it("does not double-pad when nested inside SheetBottomInset", () => {
|
||||
const host = mount(
|
||||
<SafeAreaInsetsContext.Provider value={INSETS_48}>
|
||||
<SheetBottomInset style={FILL_STYLE} testID="sheet-boundary">
|
||||
<BottomSafeAreaInset style={FILL_STYLE} testID="host-boundary">
|
||||
<BottomPinnedSurface />
|
||||
</BottomSafeAreaInset>
|
||||
</SheetBottomInset>
|
||||
</SafeAreaInsetsContext.Provider>,
|
||||
);
|
||||
|
||||
const frameRect = host.getBoundingClientRect();
|
||||
const sheet = queryEl(host, "sheet-boundary");
|
||||
const boundary = queryEl(host, "host-boundary");
|
||||
const bottomBarRect = queryEl(host, "bottom-bar").getBoundingClientRect();
|
||||
|
||||
expect(getComputedStyle(sheet).paddingBottom).toBe("48px");
|
||||
expect(getComputedStyle(boundary).paddingBottom).toBe("0px");
|
||||
expect(bottomBarRect.bottom).toBeLessThanOrEqual(frameRect.bottom - 48 + 1);
|
||||
expect(bottomBarRect.bottom).toBeGreaterThanOrEqual(frameRect.bottom - 48 - 1);
|
||||
expect(queryEl(host, "descendant-insets").textContent).toBe("24|0|0|0");
|
||||
});
|
||||
|
||||
it("adds no bottom padding when insets.bottom is 0", () => {
|
||||
const host = mount(
|
||||
<SafeAreaInsetsContext.Provider value={INSETS_0}>
|
||||
<BottomSafeAreaInset style={FILL_STYLE} testID="host-boundary">
|
||||
<BottomPinnedSurface />
|
||||
</BottomSafeAreaInset>
|
||||
</SafeAreaInsetsContext.Provider>,
|
||||
);
|
||||
|
||||
const frameRect = host.getBoundingClientRect();
|
||||
const boundary = queryEl(host, "host-boundary");
|
||||
const bottomBarRect = queryEl(host, "bottom-bar").getBoundingClientRect();
|
||||
|
||||
expect(getComputedStyle(boundary).paddingBottom).toBe("0px");
|
||||
expect(bottomBarRect.bottom).toBeLessThanOrEqual(frameRect.bottom + 1);
|
||||
expect(bottomBarRect.bottom).toBeGreaterThanOrEqual(frameRect.bottom - 1);
|
||||
expect(queryEl(host, "descendant-insets").textContent).toBe("0|0|0|0");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useMemo } from "react";
|
||||
import { View, type ViewProps } from "react-native";
|
||||
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
/**
|
||||
* Owns the remaining bottom safe-area inset at a host boundary: pads `insets.bottom` once
|
||||
* (when positive) and publishes `SafeAreaInsetsContext` with `bottom: 0` to descendants so nested
|
||||
* inset-aware views (such as `ComposerDock` or nested host containers) never double-pad.
|
||||
*/
|
||||
export function BottomSafeAreaInset({ style, children, ...props }: ViewProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const contentInsets = useMemo(
|
||||
() => (insets.bottom > 0 ? { ...insets, bottom: 0 } : insets),
|
||||
[insets],
|
||||
);
|
||||
const insetStyle = useMemo(
|
||||
() => (insets.bottom > 0 ? [style, { paddingBottom: insets.bottom }] : style),
|
||||
[insets.bottom, style],
|
||||
);
|
||||
return (
|
||||
<View {...props} style={insetStyle}>
|
||||
<SafeAreaInsetsContext.Provider value={contentInsets}>
|
||||
{children}
|
||||
</SafeAreaInsetsContext.Provider>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
import React, {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
type MutableRefObject,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { StyleSheet, type StyleProp, type ViewStyle } from "react-native";
|
||||
import type { GestureType } from "react-native-gesture-handler";
|
||||
|
||||
/**
|
||||
@@ -22,17 +26,29 @@ export type SheetContentDragGesture = MutableRefObject<GestureType | undefined>;
|
||||
*/
|
||||
export type AttachSheetContentDrag = (gesture: SheetContentDragGesture) => () => void;
|
||||
|
||||
export interface SheetScrollMetricsReporter {
|
||||
registerScroll: () => () => void;
|
||||
reportLayoutHeight: (height: number) => void;
|
||||
reportContentHeight: (height: number) => void;
|
||||
remeasure?: () => void;
|
||||
}
|
||||
|
||||
interface BottomSheetScopeValue {
|
||||
attachContentDrag: AttachSheetContentDrag;
|
||||
reportScrollMetrics?: SheetScrollMetricsReporter;
|
||||
}
|
||||
|
||||
const BottomSheetScopeContext = createContext<BottomSheetScopeValue | null>(null);
|
||||
|
||||
export function BottomSheetScope({
|
||||
attachContentDrag,
|
||||
reportScrollMetrics,
|
||||
children,
|
||||
}: BottomSheetScopeValue & { children: ReactNode }) {
|
||||
const value = useMemo(() => ({ attachContentDrag }), [attachContentDrag]);
|
||||
const value = useMemo(
|
||||
() => ({ attachContentDrag, reportScrollMetrics }),
|
||||
[attachContentDrag, reportScrollMetrics],
|
||||
);
|
||||
return (
|
||||
<BottomSheetScopeContext.Provider value={value}>{children}</BottomSheetScopeContext.Provider>
|
||||
);
|
||||
@@ -45,3 +61,75 @@ export function useIsInsideBottomSheet(): boolean {
|
||||
export function useAttachSheetContentDrag(): AttachSheetContentDrag | undefined {
|
||||
return useContext(BottomSheetScopeContext)?.attachContentDrag;
|
||||
}
|
||||
|
||||
type ScrollStyleMode = "fixed" | "flex" | "auto";
|
||||
|
||||
function getScrollStyleMode(style: StyleProp<ViewStyle>): ScrollStyleMode {
|
||||
const flat = StyleSheet.flatten(style);
|
||||
if (
|
||||
(typeof flat?.flex === "number" && flat.flex > 0) ||
|
||||
(typeof flat?.flexGrow === "number" && flat.flexGrow > 0)
|
||||
) {
|
||||
return "flex";
|
||||
}
|
||||
if (typeof flat?.height === "number" || typeof flat?.maxHeight === "number") {
|
||||
return "fixed";
|
||||
}
|
||||
return "auto";
|
||||
}
|
||||
|
||||
export function useSheetScrollMetricsProps<
|
||||
L extends { nativeEvent: { layout: { height: number } } },
|
||||
>(
|
||||
enabled: boolean,
|
||||
onLayout: ((event: L) => void) | undefined,
|
||||
onContentSizeChange: ((width: number, height: number) => void) | undefined,
|
||||
style?: StyleProp<ViewStyle>,
|
||||
): {
|
||||
onLayout: ((event: L) => void) | undefined;
|
||||
onContentSizeChange: ((width: number, height: number) => void) | undefined;
|
||||
} {
|
||||
const reporter = useContext(BottomSheetScopeContext)?.reportScrollMetrics;
|
||||
const active = enabled && reporter !== undefined;
|
||||
const styleMode = getScrollStyleMode(style);
|
||||
const prevStyleModeRef = useRef<ScrollStyleMode | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
if (!active || !reporter) {
|
||||
prevStyleModeRef.current = null;
|
||||
return undefined;
|
||||
}
|
||||
return reporter.registerScroll();
|
||||
}, [active, reporter]);
|
||||
useLayoutEffect(() => {
|
||||
if (!active || !reporter) {
|
||||
prevStyleModeRef.current = null;
|
||||
return;
|
||||
}
|
||||
const previous = prevStyleModeRef.current;
|
||||
prevStyleModeRef.current = styleMode;
|
||||
if (previous !== null && previous !== styleMode) {
|
||||
reporter.remeasure?.();
|
||||
}
|
||||
}, [active, reporter, styleMode]);
|
||||
const handleLayout = useCallback(
|
||||
(event: L) => {
|
||||
if (active && reporter) {
|
||||
reporter.reportLayoutHeight(event.nativeEvent.layout.height);
|
||||
}
|
||||
onLayout?.(event);
|
||||
},
|
||||
[active, onLayout, reporter],
|
||||
);
|
||||
const handleContentSizeChange = useCallback(
|
||||
(width: number, height: number) => {
|
||||
if (active && reporter) {
|
||||
reporter.reportContentHeight(height);
|
||||
}
|
||||
onContentSizeChange?.(width, height);
|
||||
},
|
||||
[active, onContentSizeChange, reporter],
|
||||
);
|
||||
return active
|
||||
? { onLayout: handleLayout, onContentSizeChange: handleContentSizeChange }
|
||||
: { onLayout, onContentSizeChange };
|
||||
}
|
||||
|
||||
@@ -1930,19 +1930,19 @@ const styles = StyleSheet.create((theme) => ({
|
||||
alignSelf: "stretch",
|
||||
},
|
||||
comboboxItemHovered: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
backgroundColor: theme.colors.surfaceHover,
|
||||
},
|
||||
comboboxItemHoveredElevated: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
comboboxItemPressed: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
backgroundColor: theme.colors.surfaceSelected,
|
||||
},
|
||||
comboboxItemPressedElevated: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
comboboxItemActive: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
backgroundColor: theme.colors.surfaceSelected,
|
||||
},
|
||||
comboboxItemDisabled: {
|
||||
opacity: 0.55,
|
||||
|
||||
@@ -251,11 +251,15 @@ describe("control geometry", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps segmented controls ghost with button-radius segments in a button-sized track", () => {
|
||||
it("keeps segmented controls in an inset pill track sized to match buttons", () => {
|
||||
const geometry = createControlGeometry(theme);
|
||||
|
||||
expect(geometry.segmentedContainerSm.padding).toBe(0);
|
||||
expect(geometry.segmentedContainerMd.padding).toBe(0);
|
||||
expect(geometry.segmentedContainerSm.padding).toBe(2);
|
||||
expect(geometry.segmentedContainerMd.padding).toBe(2);
|
||||
expect(geometry.segmentedContainerSm.gap).toBe(2);
|
||||
expect(geometry.segmentedContainerMd.gap).toBe(2);
|
||||
expect(geometry.segmentedContainerSm.borderRadius).toBe(geometry.buttonSm.borderRadius);
|
||||
expect(geometry.segmentedContainerMd.borderRadius).toBe(geometry.buttonMd.borderRadius);
|
||||
expect(geometry.segmentedSegmentSm.borderRadius).toBe(geometry.buttonSm.borderRadius);
|
||||
expect(geometry.segmentedSegmentMd.borderRadius).toBe(geometry.buttonMd.borderRadius);
|
||||
expect(geometry.segmentedContainerSm.minHeight).toEqual(geometry.buttonSm.minHeight);
|
||||
|
||||
@@ -462,11 +462,15 @@ export function createControlGeometry(theme: Theme) {
|
||||
},
|
||||
segmentedContainerSm: {
|
||||
minHeight: CONTROL_HEIGHTS.sm,
|
||||
padding: 0,
|
||||
padding: SEGMENTED_INSET,
|
||||
gap: SEGMENTED_INSET,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
},
|
||||
segmentedContainerMd: {
|
||||
minHeight: CONTROL_HEIGHTS.md,
|
||||
padding: 0,
|
||||
padding: SEGMENTED_INSET,
|
||||
gap: SEGMENTED_INSET,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
},
|
||||
segmentedSegmentSm: {
|
||||
minHeight: mapLayout(CONTROL_HEIGHTS.sm, (height) => height - SEGMENTED_INSET * 2),
|
||||
|
||||
@@ -263,5 +263,6 @@ export function useIsolatedBottomSheetVisibility({
|
||||
}
|
||||
|
||||
export { SheetVisibleFrame, useBottomSheetSafeAreaPaddingStyle } from "./visible-frame";
|
||||
export { getBottomSheetVisibleContentHeight } from "./visible-frame-layout";
|
||||
export { systemBackPress } from "./back-press";
|
||||
export { SheetHostScope } from "./host-scope";
|
||||
|
||||
@@ -5,11 +5,13 @@ import {
|
||||
type PropsWithChildren,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
type RefObject,
|
||||
} from "react";
|
||||
import {
|
||||
Pressable,
|
||||
Text,
|
||||
View,
|
||||
type LayoutChangeEvent,
|
||||
type PressableStateCallbackType,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
@@ -72,10 +74,36 @@ export type ActionStatus = "idle" | "pending" | "success";
|
||||
*
|
||||
* It also carries the page's depth, so the two presentations cannot disagree about what a page is.
|
||||
*/
|
||||
export function MenuPage({ depth, children }: PropsWithChildren<{ depth: number }>): ReactElement {
|
||||
function resolveMenuPageStyle(raw: boolean | "fill") {
|
||||
if (raw === "fill") return styles.rawFillPage;
|
||||
return raw ? styles.rawPage : styles.page;
|
||||
}
|
||||
|
||||
export function MenuPage({
|
||||
depth,
|
||||
raw = false,
|
||||
onContentEndLayout,
|
||||
contentEndRef,
|
||||
children,
|
||||
}: PropsWithChildren<{
|
||||
depth: number;
|
||||
raw?: boolean | "fill";
|
||||
onContentEndLayout?: (event: LayoutChangeEvent) => void;
|
||||
contentEndRef?: RefObject<View | null>;
|
||||
}>): ReactElement {
|
||||
return (
|
||||
<MenuDepthProvider value={depth}>
|
||||
<View style={styles.page}>{children}</View>
|
||||
<View style={resolveMenuPageStyle(raw)}>
|
||||
{children}
|
||||
{onContentEndLayout ? (
|
||||
<View
|
||||
ref={contentEndRef}
|
||||
pointerEvents="none"
|
||||
style={styles.rawEndMarker}
|
||||
onLayout={onContentEndLayout}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
</MenuDepthProvider>
|
||||
);
|
||||
}
|
||||
@@ -451,6 +479,19 @@ const styles = StyleSheet.create((theme) => ({
|
||||
paddingVertical: theme.spacing[1],
|
||||
gap: MENU_ROW_GAP,
|
||||
},
|
||||
rawPage: {
|
||||
flexGrow: 1,
|
||||
flexShrink: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
rawFillPage: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
rawEndMarker: {
|
||||
height: 0,
|
||||
flexShrink: 0,
|
||||
},
|
||||
labelContainer: {
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
paddingTop: theme.spacing[2],
|
||||
@@ -533,7 +574,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
fieldFocused: {
|
||||
borderColor: theme.colors.borderAccent,
|
||||
borderColor: theme.colors.borderFocus,
|
||||
},
|
||||
fieldInput: {
|
||||
flex: 1,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { act, useEffect, useState, type ReactNode } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { Text, View } from "react-native";
|
||||
import { ScrollView, Text, View, type ViewStyle } from "react-native";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { page } from "vitest/browser";
|
||||
import {
|
||||
@@ -271,3 +271,219 @@ describe("submenu flyout side", () => {
|
||||
expect(flyout.left).toBeGreaterThanOrEqual(panel.right - MAX_OVERLAP);
|
||||
});
|
||||
});
|
||||
|
||||
function scrollerInside(root: HTMLElement): HTMLElement {
|
||||
const candidates = [root, ...Array.from(root.querySelectorAll<HTMLElement>("*"))];
|
||||
const scroller = candidates.find((candidate) => {
|
||||
const overflowY = getComputedStyle(candidate).overflowY;
|
||||
return (
|
||||
(overflowY === "auto" || overflowY === "scroll") &&
|
||||
candidate.scrollHeight > candidate.clientHeight + 1
|
||||
);
|
||||
});
|
||||
if (!scroller) throw new Error("The scrollable menu surface has no scroll viewport");
|
||||
return scroller;
|
||||
}
|
||||
|
||||
describe("scrollable menu surface on window resize", () => {
|
||||
const ITEM_COUNT = 40;
|
||||
|
||||
beforeEach(async () => {
|
||||
await page.viewport(1280, 720);
|
||||
});
|
||||
|
||||
it("stays inside the window when shrunk and scrolls to the last item", async () => {
|
||||
mount(
|
||||
<View style={AWAY_FROM_EDGE}>
|
||||
<MenuRoot>
|
||||
<MenuTrigger testID="pill" accessibilityLabel="Open menu">
|
||||
<Text>Open menu</Text>
|
||||
</MenuTrigger>
|
||||
<MenuSurface scrollable width={232} testID="panel">
|
||||
{Array.from({ length: ITEM_COUNT }, (_, index) => (
|
||||
<MenuItem key={index} testID={`scroll-item-${index}`} closeOnSelect={false}>
|
||||
{`Item ${index}`}
|
||||
</MenuItem>
|
||||
))}
|
||||
</MenuSurface>
|
||||
</MenuRoot>
|
||||
</View>,
|
||||
);
|
||||
act(() => element("pill").click());
|
||||
|
||||
await expect
|
||||
.poll(() => {
|
||||
const found = document.querySelector('[data-testid="panel"]');
|
||||
return found instanceof HTMLElement ? found.getBoundingClientRect().top : -9999;
|
||||
})
|
||||
.toBeGreaterThan(0);
|
||||
|
||||
const panel = element("panel");
|
||||
const initialRect = panel.getBoundingClientRect();
|
||||
expect(initialRect.top).toBeGreaterThanOrEqual(0);
|
||||
expect(initialRect.bottom).toBeLessThanOrEqual(window.innerHeight);
|
||||
expect(initialRect.height).toBeLessThan(window.innerHeight);
|
||||
|
||||
// Wait for initial item focus so it does not reset scroll position right after scrolling.
|
||||
await expect
|
||||
.poll(() => document.activeElement?.getAttribute("data-testid"))
|
||||
.toBe("scroll-item-0");
|
||||
|
||||
const lastItem = element(`scroll-item-${ITEM_COUNT - 1}`);
|
||||
expect(lastItem.getBoundingClientRect().bottom).toBeGreaterThan(window.innerHeight);
|
||||
|
||||
await page.viewport(1280, 540);
|
||||
await expect.poll(() => panel.getBoundingClientRect().bottom).toBeLessThanOrEqual(540);
|
||||
|
||||
const scroller = scrollerInside(panel);
|
||||
act(() => {
|
||||
scroller.scrollTop = scroller.scrollHeight;
|
||||
});
|
||||
await expect
|
||||
.poll(() => {
|
||||
const row = lastItem.getBoundingClientRect();
|
||||
const surface = panel.getBoundingClientRect();
|
||||
return row.top >= surface.top && row.bottom <= surface.bottom + 1;
|
||||
})
|
||||
.toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
const BOUNDED_MAX_HEIGHT = 440;
|
||||
const RAW_ROOT_STYLE: ViewStyle = { flex: 1, minHeight: 0 };
|
||||
const RAW_SCROLL_STYLE: ViewStyle = { flex: 1 };
|
||||
const RAW_HEADER_STYLE: ViewStyle = { height: 48, justifyContent: "center" };
|
||||
const RAW_FOOTER_STYLE: ViewStyle = { height: 48, justifyContent: "center" };
|
||||
const RAW_ROW_STYLE: ViewStyle = { height: 40, justifyContent: "center" };
|
||||
const RAW_SHORT_STYLE: ViewStyle = { height: 96, justifyContent: "center" };
|
||||
const RAW_OVERFLOW_STYLE: ViewStyle = { height: 900 };
|
||||
|
||||
function mountBoundedRawCanvas(body: ReactNode): void {
|
||||
mount(
|
||||
<View style={AWAY_FROM_EDGE}>
|
||||
<MenuRoot>
|
||||
<MenuTrigger testID="pill" accessibilityLabel="Open panel">
|
||||
<Text>Open panel</Text>
|
||||
</MenuTrigger>
|
||||
<MenuSurface
|
||||
scrollable={false}
|
||||
minWidth={280}
|
||||
maxWidth={420}
|
||||
maxHeight={BOUNDED_MAX_HEIGHT}
|
||||
testID="panel"
|
||||
>
|
||||
{body}
|
||||
</MenuSurface>
|
||||
</MenuRoot>
|
||||
</View>,
|
||||
);
|
||||
act(() => element("pill").click());
|
||||
}
|
||||
|
||||
describe("bounded non-scrollable menu surface (raw canvas)", () => {
|
||||
beforeEach(async () => {
|
||||
await page.viewport(1280, 900);
|
||||
});
|
||||
|
||||
it("hugs short content with 0px outer padding", async () => {
|
||||
mountBoundedRawCanvas(
|
||||
<View testID="raw-short" style={RAW_SHORT_STYLE}>
|
||||
<Text>Short</Text>
|
||||
</View>,
|
||||
);
|
||||
|
||||
await expect
|
||||
.poll(() => {
|
||||
const found = document.querySelector('[data-testid="panel"]');
|
||||
return found instanceof HTMLElement ? found.getBoundingClientRect().top : -9999;
|
||||
})
|
||||
.toBeGreaterThan(0);
|
||||
|
||||
const panel = element("panel").getBoundingClientRect();
|
||||
const shortBox = element("raw-short").getBoundingClientRect();
|
||||
// 1px border on each side, 0px outer padding.
|
||||
expect(panel.height).toBeLessThan(150);
|
||||
expect(Math.abs(shortBox.top - panel.top - 1)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(panel.bottom - shortBox.bottom - 1)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(shortBox.left - panel.left - 1)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(panel.right - shortBox.right - 1)).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("caps tall header + ScrollView + footer at maxHeight, pins header/footer, and scrolls body", async () => {
|
||||
mountBoundedRawCanvas(
|
||||
<View style={RAW_ROOT_STYLE}>
|
||||
<View testID="raw-header" style={RAW_HEADER_STYLE}>
|
||||
<Text>Fixed Header</Text>
|
||||
</View>
|
||||
<ScrollView testID="raw-scroll" style={RAW_SCROLL_STYLE}>
|
||||
{Array.from({ length: 30 }, (_, index) => (
|
||||
<View key={index} testID={`raw-row-${index}`} style={RAW_ROW_STYLE}>
|
||||
<Text>{`Row ${index}`}</Text>
|
||||
</View>
|
||||
))}
|
||||
</ScrollView>
|
||||
<View testID="raw-footer" style={RAW_FOOTER_STYLE}>
|
||||
<Text>Fixed Footer</Text>
|
||||
</View>
|
||||
</View>,
|
||||
);
|
||||
|
||||
await expect
|
||||
.poll(() => {
|
||||
const found = document.querySelector('[data-testid="panel"]');
|
||||
return found instanceof HTMLElement ? found.getBoundingClientRect().top : -9999;
|
||||
})
|
||||
.toBeGreaterThan(0);
|
||||
|
||||
const panel = element("panel");
|
||||
const panelRect = panel.getBoundingClientRect();
|
||||
const headerBefore = element("raw-header").getBoundingClientRect();
|
||||
const footerBefore = element("raw-footer").getBoundingClientRect();
|
||||
expect(panelRect.height).toBeLessThanOrEqual(BOUNDED_MAX_HEIGHT + 1);
|
||||
expect(panelRect.height).toBeGreaterThan(400);
|
||||
expect(Math.abs(headerBefore.top - panelRect.top - 1)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(panelRect.bottom - footerBefore.bottom - 1)).toBeLessThanOrEqual(1);
|
||||
|
||||
const scroller = scrollerInside(panel);
|
||||
const lastRow = element("raw-row-29");
|
||||
expect(lastRow.getBoundingClientRect().bottom).toBeGreaterThan(footerBefore.top);
|
||||
|
||||
act(() => {
|
||||
scroller.scrollTop = scroller.scrollHeight;
|
||||
});
|
||||
|
||||
await expect
|
||||
.poll(() => {
|
||||
const row = lastRow.getBoundingClientRect();
|
||||
const scrollerRect = scroller.getBoundingClientRect();
|
||||
return row.top >= scrollerRect.top - 1 && row.bottom <= scrollerRect.bottom + 1;
|
||||
})
|
||||
.toBe(true);
|
||||
|
||||
// Header and footer remain pinned in place after scrolling.
|
||||
expect(element("raw-header").getBoundingClientRect().top).toBe(headerBefore.top);
|
||||
expect(element("raw-footer").getBoundingClientRect().bottom).toBe(footerBefore.bottom);
|
||||
});
|
||||
|
||||
it("clips tall non-scrolling content at maxHeight and respects shorter viewports", async () => {
|
||||
mountBoundedRawCanvas(
|
||||
<View testID="raw-overflow" style={RAW_OVERFLOW_STYLE}>
|
||||
<Text>Tall static</Text>
|
||||
</View>,
|
||||
);
|
||||
|
||||
await expect
|
||||
.poll(() => {
|
||||
const found = document.querySelector('[data-testid="panel"]');
|
||||
return found instanceof HTMLElement ? found.getBoundingClientRect().top : -9999;
|
||||
})
|
||||
.toBeGreaterThan(0);
|
||||
|
||||
const panel = element("panel");
|
||||
expect(panel.getBoundingClientRect().height).toBeLessThanOrEqual(BOUNDED_MAX_HEIGHT + 1);
|
||||
expect(getComputedStyle(panel).overflowY).toBe("hidden");
|
||||
|
||||
await page.viewport(1280, 360);
|
||||
await expect.poll(() => panel.getBoundingClientRect().height).toBeLessThanOrEqual(360 - 16 + 1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,9 +15,9 @@ import {
|
||||
import { createPortal } from "react-dom";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Dimensions,
|
||||
Platform,
|
||||
Pressable,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
type PointerEvent,
|
||||
type StyleProp,
|
||||
@@ -119,26 +119,26 @@ export function useAnchoredPosition({
|
||||
*/
|
||||
flipHorizontal?: boolean;
|
||||
}) {
|
||||
const { width: screenWidth, height: screenHeight } = useWindowDimensions();
|
||||
const [triggerRect, setTriggerRect] = useState<Rect | null>(null);
|
||||
const [contentSize, setContentSize] = useState<Size | null>(null);
|
||||
const [position, setPosition] = useState<SurfacePosition | null>(null);
|
||||
const [actualPlacement, setActualPlacement] = useState<Placement>(side);
|
||||
const heldSideRef = useRef<Placement | null>(null);
|
||||
|
||||
const viewportMaxHeight = Math.max(screenHeight - 16, 0);
|
||||
const resolvedMaxHeight =
|
||||
typeof maxHeight === "number" ? Math.min(maxHeight, viewportMaxHeight) : viewportMaxHeight;
|
||||
|
||||
const visibleContentSize = useMemo(() => {
|
||||
if (!contentSize) return null;
|
||||
if (!scrollable) return contentSize;
|
||||
|
||||
const { height: screenHeight } = Dimensions.get("window");
|
||||
const viewportMaxHeight = Math.max(screenHeight - 16, 0);
|
||||
const resolvedMaxHeight =
|
||||
typeof maxHeight === "number" ? Math.min(maxHeight, viewportMaxHeight) : viewportMaxHeight;
|
||||
if (!scrollable && typeof maxHeight !== "number") return contentSize;
|
||||
|
||||
return {
|
||||
width: contentSize.width,
|
||||
height: Math.min(contentSize.height, resolvedMaxHeight),
|
||||
};
|
||||
}, [contentSize, scrollable, maxHeight]);
|
||||
}, [contentSize, scrollable, maxHeight, resolvedMaxHeight]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
@@ -172,12 +172,12 @@ export function useAnchoredPosition({
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [anchorRect, anchorRef, open]);
|
||||
// A resize moves the anchor and changes the display area, so both measurements repeat.
|
||||
}, [anchorRect, anchorRef, open, screenWidth, screenHeight]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!triggerRect || !visibleContentSize) return;
|
||||
|
||||
const { width: screenWidth, height: screenHeight } = Dimensions.get("window");
|
||||
// measureInWindow and Modal both use full-screen coordinates, so the display area starts at 0.
|
||||
const heldSide = heldSideRef.current;
|
||||
const result = computePosition({
|
||||
@@ -193,7 +193,16 @@ export function useAnchoredPosition({
|
||||
|
||||
setPosition(holdSurfaceEdge(result, visibleContentSize.height));
|
||||
setActualPlacement(result.actualPlacement);
|
||||
}, [triggerRect, visibleContentSize, side, align, offset, flipHorizontal]);
|
||||
}, [
|
||||
triggerRect,
|
||||
visibleContentSize,
|
||||
screenWidth,
|
||||
screenHeight,
|
||||
side,
|
||||
align,
|
||||
offset,
|
||||
flipHorizontal,
|
||||
]);
|
||||
|
||||
const onContentLayout = useCallback(
|
||||
(event: { nativeEvent: { layout: { width: number; height: number } } }) => {
|
||||
@@ -206,7 +215,15 @@ export function useAnchoredPosition({
|
||||
[],
|
||||
);
|
||||
|
||||
return { position, actualPlacement, contentSize, visibleContentSize, onContentLayout };
|
||||
return {
|
||||
position,
|
||||
actualPlacement,
|
||||
contentSize,
|
||||
visibleContentSize,
|
||||
resolvedMaxHeight,
|
||||
onContentLayout,
|
||||
screenWidth,
|
||||
};
|
||||
}
|
||||
|
||||
export interface AnchoredSurfaceProps {
|
||||
@@ -240,6 +257,76 @@ export interface AnchoredSurfaceProps {
|
||||
children: ReactElement;
|
||||
}
|
||||
|
||||
function buildAnchoredFrameStyle({
|
||||
fullWidth,
|
||||
horizontalPadding,
|
||||
width,
|
||||
minWidth,
|
||||
maxWidth,
|
||||
screenWidth,
|
||||
hasBoundedHeight,
|
||||
resolvedMaxHeight,
|
||||
surfacePositionStyle,
|
||||
actualPlacement,
|
||||
align,
|
||||
}: {
|
||||
fullWidth: boolean;
|
||||
horizontalPadding: number;
|
||||
width?: number;
|
||||
minWidth: number;
|
||||
maxWidth?: number;
|
||||
screenWidth: number;
|
||||
hasBoundedHeight: boolean;
|
||||
resolvedMaxHeight: number | undefined;
|
||||
surfacePositionStyle: ViewStyle;
|
||||
actualPlacement: Placement;
|
||||
align: Alignment;
|
||||
}): StyleProp<ViewStyle> {
|
||||
const resolvedWidthStyle: ViewStyle = fullWidth
|
||||
? { width: screenWidth - horizontalPadding * 2 }
|
||||
: fitSurfaceWidth({ width, minWidth, maxWidth }, screenWidth);
|
||||
return [
|
||||
resolvedWidthStyle,
|
||||
hasBoundedHeight ? { maxHeight: resolvedMaxHeight } : null,
|
||||
surfacePositionStyle,
|
||||
{
|
||||
...(fullWidth ? { left: horizontalPadding } : null),
|
||||
transformOrigin: getTransformOrigin(actualPlacement, align),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function buildSurfaceExiting(placed: boolean, onExited?: () => void) {
|
||||
if (!placed || isWeb || !onExited) return undefined;
|
||||
return contentExiting.withCallback((finished) => {
|
||||
"worklet";
|
||||
if (finished) {
|
||||
runOnJS(onExited)();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function useFocusFirstMenuItemOnPlace({
|
||||
open,
|
||||
placed,
|
||||
surfaceNativeID,
|
||||
}: {
|
||||
open: boolean;
|
||||
placed: boolean;
|
||||
surfaceNativeID: string;
|
||||
}): void {
|
||||
useEffect(() => {
|
||||
if (!isWeb || !open || !placed || typeof document === "undefined") return undefined;
|
||||
const frame = requestAnimationFrame(() => {
|
||||
document
|
||||
.getElementById(surfaceNativeID)
|
||||
?.querySelector<HTMLElement>('[data-menu-item="true"]:not([data-menu-disabled="true"])')
|
||||
?.focus();
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [open, placed, surfaceNativeID]);
|
||||
}
|
||||
|
||||
/**
|
||||
* One floating menu surface, positioned against an anchor. The root menu renders one of these
|
||||
* against its trigger; every open submenu renders another against the row that opened it.
|
||||
@@ -270,7 +357,14 @@ export function AnchoredSurface({
|
||||
}: AnchoredSurfaceProps): ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
const surfaceNativeID = useId();
|
||||
const { position, actualPlacement, visibleContentSize, onContentLayout } = useAnchoredPosition({
|
||||
const {
|
||||
position,
|
||||
actualPlacement,
|
||||
visibleContentSize,
|
||||
resolvedMaxHeight,
|
||||
onContentLayout,
|
||||
screenWidth,
|
||||
} = useAnchoredPosition({
|
||||
open,
|
||||
anchorRect,
|
||||
anchorRef,
|
||||
@@ -281,6 +375,7 @@ export function AnchoredSurface({
|
||||
maxHeight,
|
||||
flipHorizontal,
|
||||
});
|
||||
const hasBoundedHeight = !scrollable && typeof maxHeight === "number";
|
||||
|
||||
// The surface is placed once both measurements land. Until then it sits off-screen so it can
|
||||
// be measured, and it must not animate: an entering animation that ran there would be over
|
||||
@@ -292,42 +387,38 @@ export function AnchoredSurface({
|
||||
const surfaceKey = isWeb || placed ? "placed" : "measuring";
|
||||
|
||||
useWebContentEntering({ placed, surfaceNativeID });
|
||||
|
||||
useEffect(() => {
|
||||
if (!isWeb || !open || !placed || typeof document === "undefined") return undefined;
|
||||
const frame = requestAnimationFrame(() => {
|
||||
document
|
||||
.getElementById(surfaceNativeID)
|
||||
?.querySelector<HTMLElement>('[data-menu-item="true"]:not([data-menu-disabled="true"])')
|
||||
?.focus();
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [open, placed, surfaceNativeID]);
|
||||
useFocusFirstMenuItemOnPlace({ open, placed, surfaceNativeID });
|
||||
|
||||
const frame = useMemo(() => surfaceFrameStyles(position), [position]);
|
||||
const frameStyle = useMemo<StyleProp<ViewStyle>>(() => {
|
||||
const { width: screenWidth } = Dimensions.get("window");
|
||||
const resolvedWidthStyle: ViewStyle = fullWidth
|
||||
? { width: screenWidth - horizontalPadding * 2 }
|
||||
: fitSurfaceWidth({ width, minWidth, maxWidth }, screenWidth);
|
||||
return [
|
||||
resolvedWidthStyle,
|
||||
const frameStyle = useMemo(
|
||||
() =>
|
||||
buildAnchoredFrameStyle({
|
||||
fullWidth,
|
||||
horizontalPadding,
|
||||
width,
|
||||
minWidth,
|
||||
maxWidth,
|
||||
screenWidth,
|
||||
hasBoundedHeight,
|
||||
resolvedMaxHeight,
|
||||
surfacePositionStyle: frame.surface,
|
||||
actualPlacement,
|
||||
align,
|
||||
}),
|
||||
[
|
||||
fullWidth,
|
||||
horizontalPadding,
|
||||
width,
|
||||
minWidth,
|
||||
maxWidth,
|
||||
screenWidth,
|
||||
hasBoundedHeight,
|
||||
resolvedMaxHeight,
|
||||
frame.surface,
|
||||
{
|
||||
...(fullWidth ? { left: horizontalPadding } : null),
|
||||
transformOrigin: getTransformOrigin(actualPlacement, align),
|
||||
},
|
||||
];
|
||||
}, [
|
||||
fullWidth,
|
||||
horizontalPadding,
|
||||
width,
|
||||
minWidth,
|
||||
maxWidth,
|
||||
frame.surface,
|
||||
actualPlacement,
|
||||
align,
|
||||
]);
|
||||
actualPlacement,
|
||||
align,
|
||||
],
|
||||
);
|
||||
|
||||
const scrollViewportStyle = useMemo(
|
||||
() => [visibleContentSize ? { height: visibleContentSize.height } : null],
|
||||
@@ -349,6 +440,7 @@ export function AnchoredSurface({
|
||||
onLayout={onContentLayout}
|
||||
onPointerEnter={onPointerEnter}
|
||||
onPointerLeave={onPointerLeave}
|
||||
style={hasBoundedHeight ? styles.boundedContent : undefined}
|
||||
>
|
||||
{children}
|
||||
</View>
|
||||
@@ -377,16 +469,7 @@ export function AnchoredSurface({
|
||||
style={styles.content}
|
||||
frameStyle={frameStyle}
|
||||
entering={placed ? nativeContentEntering : undefined}
|
||||
exiting={
|
||||
!placed || isWeb || !onExited
|
||||
? undefined
|
||||
: contentExiting.withCallback((finished) => {
|
||||
"worklet";
|
||||
if (finished) {
|
||||
runOnJS(onExited)();
|
||||
}
|
||||
})
|
||||
}
|
||||
exiting={buildSurfaceExiting(placed, onExited)}
|
||||
>
|
||||
{scrollable ? (
|
||||
<FloatingScrollView
|
||||
@@ -506,4 +589,9 @@ const styles = StyleSheet.create((theme) => ({
|
||||
overflow: "hidden",
|
||||
...theme.shadow.md,
|
||||
},
|
||||
boundedContent: {
|
||||
flexGrow: 1,
|
||||
flexShrink: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getMenuSheetBottomPadding } from "./menu-sheet-layout";
|
||||
import {
|
||||
getMenuSheetBottomPadding,
|
||||
resolveSheetCanvasScrollContentHeight,
|
||||
resolveSheetCanvasStaticContentHeight,
|
||||
} from "./menu-sheet-layout";
|
||||
|
||||
describe("getMenuSheetBottomPadding", () => {
|
||||
it("keeps breathing room below the last row when there is no system inset", () => {
|
||||
@@ -20,3 +24,80 @@ describe("getMenuSheetBottomPadding", () => {
|
||||
).toBe(52);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSheetCanvasScrollContentHeight", () => {
|
||||
it("adds non-scroll chrome (header, footer, safe area) to scroll content height for flex scrollers", () => {
|
||||
expect(
|
||||
resolveSheetCanvasScrollContentHeight({
|
||||
frameHeight: 600,
|
||||
bodyHeight: 500,
|
||||
contentEndY: 500,
|
||||
scrollLayoutHeight: 400,
|
||||
scrollContentHeight: 1100,
|
||||
intrinsicScrollHeight: false,
|
||||
}),
|
||||
).toEqual({ height: 1300, intrinsicScrollHeight: false });
|
||||
});
|
||||
|
||||
it("shrinks smoothly for short flex lists without clipping fixed chrome", () => {
|
||||
expect(
|
||||
resolveSheetCanvasScrollContentHeight({
|
||||
frameHeight: 600,
|
||||
bodyHeight: 500,
|
||||
contentEndY: 500,
|
||||
scrollLayoutHeight: 400,
|
||||
scrollContentHeight: 90,
|
||||
intrinsicScrollHeight: false,
|
||||
}),
|
||||
).toEqual({ height: 290, intrinsicScrollHeight: false });
|
||||
});
|
||||
|
||||
it("hugs fixed-height scrollers without counting unused maxHeight space", () => {
|
||||
const initial = resolveSheetCanvasScrollContentHeight({
|
||||
frameHeight: 675,
|
||||
bodyHeight: 675,
|
||||
contentEndY: 200,
|
||||
scrollLayoutHeight: 120,
|
||||
scrollContentHeight: 400,
|
||||
intrinsicScrollHeight: false,
|
||||
});
|
||||
expect(initial).toEqual({ height: 200, intrinsicScrollHeight: true });
|
||||
|
||||
// Once settled at 200px, bodyHeight equals contentEndY and must keep hugging 200px.
|
||||
const settled = resolveSheetCanvasScrollContentHeight({
|
||||
frameHeight: 200,
|
||||
bodyHeight: 200,
|
||||
contentEndY: 200,
|
||||
scrollLayoutHeight: 120,
|
||||
scrollContentHeight: 400,
|
||||
intrinsicScrollHeight: initial.intrinsicScrollHeight,
|
||||
});
|
||||
expect(settled).toEqual({ height: 200, intrinsicScrollHeight: true });
|
||||
|
||||
// If the same mounted scroller switches from fixed-height to flex during a re-measure at
|
||||
// maxHeight, clear the intrinsic latch so the sheet grows with the expanded flex body.
|
||||
expect(
|
||||
resolveSheetCanvasScrollContentHeight({
|
||||
frameHeight: 675,
|
||||
bodyHeight: 675,
|
||||
contentEndY: 675,
|
||||
scrollLayoutHeight: 595,
|
||||
scrollContentHeight: 400,
|
||||
intrinsicScrollHeight: settled.intrinsicScrollHeight,
|
||||
measuring: true,
|
||||
}),
|
||||
).toEqual({ height: 480, intrinsicScrollHeight: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSheetCanvasStaticContentHeight", () => {
|
||||
it("sums sheet header, static content height, and bottom safe area", () => {
|
||||
expect(
|
||||
resolveSheetCanvasStaticContentHeight({
|
||||
headerHeight: 44,
|
||||
staticHeight: 120,
|
||||
safeAreaBottom: 48,
|
||||
}),
|
||||
).toBe(212);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,3 +4,45 @@ export function getMenuSheetBottomPadding(input: {
|
||||
}): number {
|
||||
return input.safeAreaBottom + input.breathingRoom;
|
||||
}
|
||||
|
||||
export function resolveSheetCanvasScrollContentHeight(input: {
|
||||
frameHeight: number;
|
||||
bodyHeight: number;
|
||||
contentEndY: number;
|
||||
scrollLayoutHeight: number;
|
||||
scrollContentHeight: number;
|
||||
intrinsicScrollHeight: boolean;
|
||||
measuring?: boolean;
|
||||
}): { height: number; intrinsicScrollHeight: boolean } {
|
||||
const hostChrome = Math.max(0, input.frameHeight - input.bodyHeight);
|
||||
// Measure at maxHeight first: when the plugin tree stops short of the host body (for example a
|
||||
// fixed-height ScrollView), its laid-out height (`contentEndY`) already includes the exact
|
||||
// viewport height it chose, so adding scrollContentHeight would create dead space below it.
|
||||
// When `measuring` is true (initial mount or sizing-mode flip), re-evaluate from `bodyHeight`
|
||||
// rather than keeping an old intrinsic latch.
|
||||
const bodyTruncated = input.contentEndY > 0 && input.bodyHeight - input.contentEndY > 1;
|
||||
const intrinsic = input.measuring ? bodyTruncated : input.intrinsicScrollHeight || bodyTruncated;
|
||||
if (intrinsic) {
|
||||
return {
|
||||
height: hostChrome + Math.max(0, input.contentEndY),
|
||||
intrinsicScrollHeight: true,
|
||||
};
|
||||
}
|
||||
const nonScrollHeight = Math.max(0, input.frameHeight - input.scrollLayoutHeight);
|
||||
return {
|
||||
height: nonScrollHeight + Math.max(0, input.scrollContentHeight),
|
||||
intrinsicScrollHeight: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveSheetCanvasStaticContentHeight(input: {
|
||||
headerHeight: number;
|
||||
staticHeight: number;
|
||||
safeAreaBottom: number;
|
||||
}): number {
|
||||
return (
|
||||
Math.max(0, input.headerHeight) +
|
||||
Math.max(0, input.staticHeight) +
|
||||
Math.max(0, input.safeAreaBottom)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,16 +5,40 @@ import {
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Pressable, Text, View, useWindowDimensions, type PointerEvent } from "react-native";
|
||||
import {
|
||||
Pressable,
|
||||
Text,
|
||||
View,
|
||||
useWindowDimensions,
|
||||
type LayoutChangeEvent,
|
||||
type PointerEvent,
|
||||
} from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { BottomSheetScrollView } from "@gorhom/bottom-sheet";
|
||||
import {
|
||||
BottomSheetScrollView,
|
||||
KEYBOARD_STATUS,
|
||||
useBottomSheetInternal,
|
||||
} from "@gorhom/bottom-sheet";
|
||||
import Animated, {
|
||||
useAnimatedReaction,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import { ChevronLeft } from "lucide-react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { BottomSafeAreaInset } from "@/components/ui/bottom-safe-area-inset";
|
||||
import {
|
||||
BottomSheetScope,
|
||||
useAttachSheetContentDrag,
|
||||
type SheetScrollMetricsReporter,
|
||||
} from "@/components/ui/bottom-sheet-scope";
|
||||
import {
|
||||
getBottomSheetVisibleContentHeight,
|
||||
IsolatedBottomSheetModal,
|
||||
useIsolatedBottomSheetVisibility,
|
||||
type ContextBridge,
|
||||
@@ -31,7 +55,11 @@ import { MenuPage } from "./menu-item";
|
||||
import { currentPageId, isSubPageOpen } from "./menu-navigation";
|
||||
import { AnchoredSurface, MenuOverlay } from "./menu-overlay";
|
||||
import { isHoverPointer } from "./menu-pointer";
|
||||
import { getMenuSheetBottomPadding } from "./menu-sheet-layout";
|
||||
import {
|
||||
getMenuSheetBottomPadding,
|
||||
resolveSheetCanvasScrollContentHeight,
|
||||
resolveSheetCanvasStaticContentHeight,
|
||||
} from "./menu-sheet-layout";
|
||||
import type { Alignment, Placement } from "../anchor";
|
||||
import type { KeyboardFocusScope } from "@/keyboard/actions";
|
||||
|
||||
@@ -66,6 +94,8 @@ export interface MenuListPageDefinition {
|
||||
* surface stops closing on hover, since its parent leads back to the same dismissal.
|
||||
*/
|
||||
hoverIntent?: boolean;
|
||||
/** Overrides the surface's `scrollable` mode for this page when provided. */
|
||||
scrollable?: boolean;
|
||||
fill?: false;
|
||||
}
|
||||
|
||||
@@ -223,7 +253,7 @@ function MenuPopoverSurface({
|
||||
maxHeight,
|
||||
fullWidth = false,
|
||||
horizontalPadding = 16,
|
||||
scrollable = false,
|
||||
scrollable,
|
||||
testID,
|
||||
keyboardFocusScope,
|
||||
}: MenuSurfaceProps): ReactElement | null {
|
||||
@@ -279,11 +309,13 @@ function MenuPopoverSurface({
|
||||
maxHeight={maxHeight}
|
||||
fullWidth={fullWidth}
|
||||
horizontalPadding={horizontalPadding}
|
||||
scrollable={scrollable}
|
||||
scrollable={Boolean(scrollable)}
|
||||
testID={testID}
|
||||
keyboardFocusScope={keyboardFocusScope}
|
||||
>
|
||||
<MenuPage depth={0}>{children}</MenuPage>
|
||||
<MenuPage depth={0} raw={scrollable === false}>
|
||||
{children}
|
||||
</MenuPage>
|
||||
</AnchoredSurface>
|
||||
{openPages.map(({ page, depth }) => (
|
||||
<MenuFlyout
|
||||
@@ -344,6 +376,8 @@ function MenuFlyout({
|
||||
|
||||
if (!anchorRef) return null;
|
||||
|
||||
const pageScrollable = page.fill === true ? false : (page.scrollable ?? scrollable);
|
||||
|
||||
return (
|
||||
<AnchoredSurface
|
||||
open
|
||||
@@ -356,13 +390,15 @@ function MenuFlyout({
|
||||
offset={-SUBMENU_OVERLAP}
|
||||
minWidth={minWidth}
|
||||
maxHeight={maxHeight}
|
||||
scrollable={scrollable}
|
||||
scrollable={Boolean(pageScrollable)}
|
||||
backdrop={false}
|
||||
onPointerEnter={handleHoverIn}
|
||||
onPointerLeave={handleHoverOut}
|
||||
testID={testID}
|
||||
>
|
||||
<MenuPage depth={depth + 1}>{page.content}</MenuPage>
|
||||
<MenuPage depth={depth + 1} raw={pageScrollable === false}>
|
||||
{page.content}
|
||||
</MenuPage>
|
||||
</AnchoredSurface>
|
||||
);
|
||||
}
|
||||
@@ -372,6 +408,7 @@ function MenuSheetSurface({
|
||||
pages = [],
|
||||
sheetTitle,
|
||||
sheetTrailing,
|
||||
scrollable,
|
||||
testID,
|
||||
keyboardFocusScope,
|
||||
}: MenuSurfaceProps): ReactElement | null {
|
||||
@@ -397,6 +434,12 @@ function MenuSheetSurface({
|
||||
const depth = menu.path.length;
|
||||
const fillPage = openPage?.fill === true ? openPage : null;
|
||||
const listPage = openPage?.fill === true ? null : openPage;
|
||||
const pageScrollable = listPage ? (listPage.scrollable ?? scrollable) : scrollable;
|
||||
const isRawCanvas = !fillPage && pageScrollable === false;
|
||||
const maxDynamicContentSize = windowHeight * 0.8;
|
||||
const headerTitle = listPage ? listPage.title : sheetTitle;
|
||||
const onHeaderBack = listPage ? menu.goBack : null;
|
||||
const headerTrailing = listPage ? undefined : sheetTrailing;
|
||||
|
||||
// The sheet's content is teleported out of this subtree, so both menu contexts have to be
|
||||
// rebuilt on the other side. Providing them around the modal instead would put them on the
|
||||
@@ -410,6 +453,44 @@ function MenuSheetSurface({
|
||||
[menu, surfaceValue],
|
||||
);
|
||||
|
||||
const renderSheetBody = () => {
|
||||
const activeChildren = listPage ? listPage.content : children;
|
||||
const activeDepth = listPage ? depth : 0;
|
||||
|
||||
if (fillPage) {
|
||||
return (
|
||||
<View style={styles.fillPage} testID={testID ? `${testID}-${fillPage.id}` : undefined}>
|
||||
{fillPage.content}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (isRawCanvas) {
|
||||
return (
|
||||
<MenuSheetCanvasBody
|
||||
headerTitle={headerTitle}
|
||||
onHeaderBack={onHeaderBack}
|
||||
headerTrailing={headerTrailing}
|
||||
depth={activeDepth}
|
||||
maxHeight={maxDynamicContentSize}
|
||||
dataSet={sheetDataSet}
|
||||
testID={testID}
|
||||
>
|
||||
{activeChildren}
|
||||
</MenuSheetCanvasBody>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<MenuSheetScrollView dataSet={sheetDataSet} testID={testID}>
|
||||
{headerTitle ? (
|
||||
<MenuSheetHeader title={headerTitle} onBack={onHeaderBack} trailing={headerTrailing} />
|
||||
) : null}
|
||||
<MenuPage depth={activeDepth}>{activeChildren}</MenuPage>
|
||||
</MenuSheetScrollView>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<IsolatedBottomSheetModal
|
||||
ref={sheetRef}
|
||||
@@ -423,7 +504,7 @@ function MenuSheetSurface({
|
||||
enableDynamicSizing={!fillPage}
|
||||
snapPoints={fillPage ? FULL_SHEET_SNAP_POINTS : undefined}
|
||||
enableContentPanningGesture={!fillPage}
|
||||
maxDynamicContentSize={windowHeight * 0.8}
|
||||
maxDynamicContentSize={maxDynamicContentSize}
|
||||
onChange={handleSheetChange}
|
||||
onDismiss={handleSheetDismiss}
|
||||
backdropOpacity={0.45}
|
||||
@@ -436,31 +517,394 @@ function MenuSheetSurface({
|
||||
keyboardBehavior="interactive"
|
||||
keyboardBlurBehavior="restore"
|
||||
>
|
||||
{fillPage ? (
|
||||
<View style={styles.fillPage} testID={testID ? `${testID}-${fillPage.id}` : undefined}>
|
||||
{fillPage.content}
|
||||
</View>
|
||||
) : (
|
||||
<MenuSheetScrollView dataSet={sheetDataSet} testID={testID}>
|
||||
{listPage ? (
|
||||
<>
|
||||
<MenuSheetHeader title={listPage.title} onBack={menu.goBack} />
|
||||
<MenuPage depth={depth}>{listPage.content}</MenuPage>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{sheetTitle ? (
|
||||
<MenuSheetHeader title={sheetTitle} onBack={null} trailing={sheetTrailing} />
|
||||
) : null}
|
||||
<MenuPage depth={0}>{children}</MenuPage>
|
||||
</>
|
||||
)}
|
||||
</MenuSheetScrollView>
|
||||
)}
|
||||
{renderSheetBody()}
|
||||
</IsolatedBottomSheetModal>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw bounded canvas inside a dynamic sheet (`scrollable={false}`). Hands scroll and padding
|
||||
* ownership to the content while keeping `BottomSheetScope` (so plugin `<ScrollView>` / `<FlatList>`
|
||||
* use Gorhom's gesture-integrated scrollers), `BottomSafeAreaInset` (clearing Android 3-button nav
|
||||
* and iOS home indicator once), and `MenuSheetHeader` fixed at the top.
|
||||
*/
|
||||
function MenuSheetCanvasBody({
|
||||
headerTitle,
|
||||
onHeaderBack,
|
||||
headerTrailing,
|
||||
depth,
|
||||
maxHeight,
|
||||
dataSet,
|
||||
testID,
|
||||
children,
|
||||
}: {
|
||||
headerTitle?: string;
|
||||
onHeaderBack: (() => void) | null;
|
||||
headerTrailing?: ReactNode;
|
||||
depth: number;
|
||||
maxHeight: number;
|
||||
dataSet: { keyboardScope: KeyboardFocusScope } | undefined;
|
||||
testID?: string;
|
||||
children: ReactNode;
|
||||
}): ReactElement {
|
||||
const {
|
||||
animatedDetentsState,
|
||||
animatedKeyboardState,
|
||||
animatedLayoutState,
|
||||
animatedPosition,
|
||||
enableDynamicSizing,
|
||||
} = useBottomSheetInternal();
|
||||
const attachContentDrag = useAttachSheetContentDrag();
|
||||
const safeAreaInsets = useSafeAreaInsets();
|
||||
const [scrollCount, setScrollCount] = useState(0);
|
||||
const [intrinsicScrollMode, setIntrinsicScrollMode] = useState(false);
|
||||
const scrollCountRef = useRef(0);
|
||||
const scrollMeasuring = useSharedValue(false);
|
||||
const hasScrollView = scrollCount > 0;
|
||||
const hasHeader = Boolean(headerTitle);
|
||||
const metricsRef = useRef({
|
||||
frameHeight: null as number | null,
|
||||
bodyHeight: null as number | null,
|
||||
contentEndY: null as number | null,
|
||||
scrollLayoutHeight: null as number | null,
|
||||
scrollContentHeight: null as number | null,
|
||||
headerHeight: hasHeader ? (null as number | null) : 0,
|
||||
staticHeight: null as number | null,
|
||||
intrinsicScrollHeight: false,
|
||||
measuring: false,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasHeader) {
|
||||
metricsRef.current.headerHeight = 0;
|
||||
} else {
|
||||
metricsRef.current.headerHeight = null;
|
||||
}
|
||||
}, [hasHeader]);
|
||||
|
||||
const canvasContentHeight = useSharedValue(0);
|
||||
|
||||
const commitContentHeight = useCallback(
|
||||
(height: number) => {
|
||||
if (!enableDynamicSizing || !(height > 0)) return;
|
||||
canvasContentHeight.value = height;
|
||||
animatedLayoutState.modify((state) => {
|
||||
"worklet";
|
||||
state.contentHeight = height;
|
||||
return state;
|
||||
});
|
||||
metricsRef.current.measuring = false;
|
||||
scrollMeasuring.value = false;
|
||||
},
|
||||
[animatedLayoutState, canvasContentHeight, enableDynamicSizing, scrollMeasuring],
|
||||
);
|
||||
|
||||
// MenuSheetCanvasBody owns animatedLayoutState.contentHeight for both static and scrollable
|
||||
// raw-canvas sheets. Guard against Gorhom BottomSheetScrollView's internal onContentSizeChange
|
||||
// setter writing raw row height without header/footer/viewport framing.
|
||||
useAnimatedReaction(
|
||||
() => animatedLayoutState.get().contentHeight,
|
||||
(layoutHeight) => {
|
||||
const owned = canvasContentHeight.value;
|
||||
if (enableDynamicSizing && owned > 0 && layoutHeight !== owned) {
|
||||
animatedLayoutState.modify((state) => {
|
||||
"worklet";
|
||||
state.contentHeight = owned;
|
||||
return state;
|
||||
});
|
||||
}
|
||||
},
|
||||
[animatedLayoutState, canvasContentHeight, enableDynamicSizing],
|
||||
);
|
||||
|
||||
const tryCommitStatic = useCallback(() => {
|
||||
if (
|
||||
scrollCountRef.current > 0 &&
|
||||
(!metricsRef.current.intrinsicScrollHeight || metricsRef.current.measuring)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const { headerHeight, staticHeight } = metricsRef.current;
|
||||
if (headerHeight === null || staticHeight === null) return;
|
||||
commitContentHeight(
|
||||
Math.min(
|
||||
maxHeight,
|
||||
resolveSheetCanvasStaticContentHeight({
|
||||
headerHeight,
|
||||
staticHeight,
|
||||
safeAreaBottom: safeAreaInsets.bottom,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}, [commitContentHeight, maxHeight, safeAreaInsets.bottom]);
|
||||
|
||||
const tryCommitScroll = useCallback(() => {
|
||||
const {
|
||||
frameHeight,
|
||||
bodyHeight,
|
||||
contentEndY,
|
||||
scrollLayoutHeight,
|
||||
scrollContentHeight,
|
||||
intrinsicScrollHeight,
|
||||
measuring,
|
||||
} = metricsRef.current;
|
||||
// Once intrinsic mode settles, handleStaticLayout owns size changes (such as a growing
|
||||
// footer beside a fixed-height scroller) until the next remeasure pass. Re-assert canvas
|
||||
// height on scroller callbacks so Gorhom's content-size setter never takes over the sheet.
|
||||
if (intrinsicScrollHeight && !measuring) {
|
||||
tryCommitStatic();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
frameHeight === null ||
|
||||
bodyHeight === null ||
|
||||
contentEndY === null ||
|
||||
scrollLayoutHeight === null ||
|
||||
scrollContentHeight === null
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const resolved = resolveSheetCanvasScrollContentHeight({
|
||||
frameHeight,
|
||||
bodyHeight,
|
||||
contentEndY,
|
||||
scrollLayoutHeight,
|
||||
scrollContentHeight,
|
||||
intrinsicScrollHeight,
|
||||
measuring,
|
||||
});
|
||||
if (resolved.intrinsicScrollHeight && !metricsRef.current.intrinsicScrollHeight) {
|
||||
metricsRef.current.staticHeight = null;
|
||||
}
|
||||
metricsRef.current.intrinsicScrollHeight = resolved.intrinsicScrollHeight;
|
||||
setIntrinsicScrollMode(resolved.intrinsicScrollHeight);
|
||||
commitContentHeight(resolved.height);
|
||||
}, [commitContentHeight, tryCommitStatic]);
|
||||
|
||||
const measureEpochRef = useRef(0);
|
||||
const bodyRef = useRef<View | null>(null);
|
||||
const contentEndRef = useRef<View | null>(null);
|
||||
|
||||
const measureContentEnd = useCallback(() => {
|
||||
if (scrollCountRef.current === 0) return;
|
||||
if (metricsRef.current.intrinsicScrollHeight && !metricsRef.current.measuring) return;
|
||||
const body = bodyRef.current;
|
||||
const marker = contentEndRef.current;
|
||||
if (!body || !marker) return;
|
||||
const epoch = measureEpochRef.current;
|
||||
marker.measureLayout(body, (_left, top) => {
|
||||
if (epoch !== measureEpochRef.current || scrollCountRef.current === 0) return;
|
||||
metricsRef.current.contentEndY = top;
|
||||
tryCommitScroll();
|
||||
});
|
||||
}, [tryCommitScroll]);
|
||||
|
||||
const reportScrollMetrics = useMemo<SheetScrollMetricsReporter>(
|
||||
() => ({
|
||||
registerScroll() {
|
||||
scrollCountRef.current += 1;
|
||||
if (scrollCountRef.current === 1) {
|
||||
measureEpochRef.current += 1;
|
||||
metricsRef.current.intrinsicScrollHeight = false;
|
||||
metricsRef.current.staticHeight = null;
|
||||
metricsRef.current.measuring = true;
|
||||
scrollMeasuring.value = true;
|
||||
setIntrinsicScrollMode(false);
|
||||
}
|
||||
setScrollCount(scrollCountRef.current);
|
||||
return () => {
|
||||
scrollCountRef.current = Math.max(0, scrollCountRef.current - 1);
|
||||
if (scrollCountRef.current === 0) {
|
||||
measureEpochRef.current += 1;
|
||||
metricsRef.current.intrinsicScrollHeight = false;
|
||||
metricsRef.current.measuring = false;
|
||||
scrollMeasuring.value = false;
|
||||
setIntrinsicScrollMode(false);
|
||||
}
|
||||
setScrollCount(scrollCountRef.current);
|
||||
};
|
||||
},
|
||||
reportLayoutHeight(height: number) {
|
||||
metricsRef.current.scrollLayoutHeight = height;
|
||||
measureContentEnd();
|
||||
tryCommitScroll();
|
||||
},
|
||||
reportContentHeight(height: number) {
|
||||
metricsRef.current.scrollContentHeight = height;
|
||||
tryCommitScroll();
|
||||
},
|
||||
remeasure() {
|
||||
if (scrollCountRef.current === 0) return;
|
||||
measureEpochRef.current += 1;
|
||||
metricsRef.current.intrinsicScrollHeight = false;
|
||||
metricsRef.current.staticHeight = null;
|
||||
metricsRef.current.measuring = true;
|
||||
setIntrinsicScrollMode(false);
|
||||
if ((metricsRef.current.frameHeight ?? 0) < maxHeight - 1) {
|
||||
metricsRef.current.frameHeight = null;
|
||||
metricsRef.current.bodyHeight = null;
|
||||
metricsRef.current.contentEndY = null;
|
||||
// Retain the previous scrollLayoutHeight until reportLayoutHeight fires so switching to
|
||||
// automatic sizing at the same pixel height never leaves tryCommitScroll blocked.
|
||||
scrollMeasuring.value = true;
|
||||
return;
|
||||
}
|
||||
scrollMeasuring.value = true;
|
||||
measureContentEnd();
|
||||
},
|
||||
}),
|
||||
[maxHeight, measureContentEnd, scrollMeasuring, tryCommitScroll],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasScrollView && scrollCountRef.current === 0) {
|
||||
metricsRef.current.intrinsicScrollHeight = false;
|
||||
metricsRef.current.measuring = false;
|
||||
metricsRef.current.scrollLayoutHeight = null;
|
||||
metricsRef.current.scrollContentHeight = null;
|
||||
setIntrinsicScrollMode(false);
|
||||
tryCommitStatic();
|
||||
}
|
||||
}, [hasScrollView, tryCommitStatic]);
|
||||
|
||||
const handleFrameLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
metricsRef.current.frameHeight = event.nativeEvent.layout.height;
|
||||
if (hasScrollView) tryCommitScroll();
|
||||
},
|
||||
[hasScrollView, tryCommitScroll],
|
||||
);
|
||||
|
||||
const handleBodyLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
metricsRef.current.bodyHeight = event.nativeEvent.layout.height;
|
||||
if (hasScrollView) {
|
||||
measureContentEnd();
|
||||
tryCommitScroll();
|
||||
}
|
||||
},
|
||||
[hasScrollView, measureContentEnd, tryCommitScroll],
|
||||
);
|
||||
|
||||
const handleContentEndLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
metricsRef.current.contentEndY = event.nativeEvent.layout.y;
|
||||
if (hasScrollView) tryCommitScroll();
|
||||
},
|
||||
[hasScrollView, tryCommitScroll],
|
||||
);
|
||||
|
||||
const handleHeaderLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
metricsRef.current.headerHeight = event.nativeEvent.layout.height;
|
||||
tryCommitStatic();
|
||||
},
|
||||
[tryCommitStatic],
|
||||
);
|
||||
|
||||
const handleStaticLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
metricsRef.current.staticHeight = event.nativeEvent.layout.height;
|
||||
tryCommitStatic();
|
||||
},
|
||||
[tryCommitStatic],
|
||||
);
|
||||
|
||||
const scrollFrameAnimatedStyle = useAnimatedStyle(() => {
|
||||
if (!hasScrollView) return { height: undefined };
|
||||
const { containerHeight, handleHeight } = animatedLayoutState.get();
|
||||
const lowestDetentPosition = animatedDetentsState.get().detents?.[0];
|
||||
if (
|
||||
containerHeight <= 0 ||
|
||||
handleHeight < 0 ||
|
||||
lowestDetentPosition === undefined ||
|
||||
scrollMeasuring.value
|
||||
) {
|
||||
return { height: maxHeight };
|
||||
}
|
||||
const keyboard = animatedKeyboardState.get();
|
||||
return {
|
||||
height: getBottomSheetVisibleContentHeight({
|
||||
containerHeight,
|
||||
handleHeight,
|
||||
contentPosition: animatedPosition.get(),
|
||||
lowestDetentPosition,
|
||||
keyboardHeight: keyboard.heightWithinContainer,
|
||||
isKeyboardVisible: keyboard.status === KEYBOARD_STATUS.SHOWN,
|
||||
}),
|
||||
};
|
||||
}, [
|
||||
animatedDetentsState,
|
||||
animatedKeyboardState,
|
||||
animatedLayoutState,
|
||||
animatedPosition,
|
||||
hasScrollView,
|
||||
maxHeight,
|
||||
scrollMeasuring,
|
||||
]);
|
||||
|
||||
const frameStyle = useMemo(
|
||||
() => [
|
||||
hasScrollView ? styles.rawSheetScrollFrame : styles.rawSheetFrameAuto,
|
||||
{ maxHeight },
|
||||
hasScrollView ? { height: maxHeight } : undefined,
|
||||
scrollFrameAnimatedStyle,
|
||||
],
|
||||
[hasScrollView, maxHeight, scrollFrameAnimatedStyle],
|
||||
);
|
||||
const useIntrinsicMeasure = !hasScrollView || intrinsicScrollMode;
|
||||
const insetStyle = hasScrollView ? styles.rawSheetFrameFilled : styles.rawSheetFrameAuto;
|
||||
const bodyContainerStyle = hasScrollView ? styles.rawSheetBodyFilled : styles.rawSheetBodyClipped;
|
||||
const staticMeasureStyle = useIntrinsicMeasure
|
||||
? styles.rawStaticMeasure
|
||||
: styles.rawSheetBodyFilled;
|
||||
|
||||
// Keep the same React element tree mounted across !hasScrollView <-> hasScrollView so lazily
|
||||
// revealing a ScrollView/FlatList inside an open popover never remounts plugin state.
|
||||
const content = (
|
||||
<Animated.View style={frameStyle}>
|
||||
<BottomSafeAreaInset
|
||||
dataSet={dataSet}
|
||||
onLayout={handleFrameLayout}
|
||||
style={insetStyle}
|
||||
testID={testID ? `${testID}-content` : undefined}
|
||||
>
|
||||
{headerTitle ? (
|
||||
<View onLayout={handleHeaderLayout}>
|
||||
<MenuSheetHeader title={headerTitle} onBack={onHeaderBack} trailing={headerTrailing} />
|
||||
</View>
|
||||
) : null}
|
||||
<View ref={bodyRef} onLayout={handleBodyLayout} style={bodyContainerStyle}>
|
||||
<View
|
||||
onLayout={useIntrinsicMeasure ? handleStaticLayout : undefined}
|
||||
style={staticMeasureStyle}
|
||||
>
|
||||
<MenuPage
|
||||
depth={depth}
|
||||
raw={useIntrinsicMeasure ? true : "fill"}
|
||||
contentEndRef={contentEndRef}
|
||||
onContentEndLayout={handleContentEndLayout}
|
||||
>
|
||||
{children}
|
||||
</MenuPage>
|
||||
</View>
|
||||
</View>
|
||||
</BottomSafeAreaInset>
|
||||
</Animated.View>
|
||||
);
|
||||
|
||||
if (!attachContentDrag) return content;
|
||||
|
||||
return (
|
||||
<BottomSheetScope
|
||||
attachContentDrag={attachContentDrag}
|
||||
reportScrollMetrics={reportScrollMetrics}
|
||||
>
|
||||
{content}
|
||||
</BottomSheetScope>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rendered on the far side of the sheet's portal so it clears the screen's bottom inset, not the
|
||||
* one left where the menu was opened: inside a sheet tab, none is.
|
||||
@@ -534,6 +978,30 @@ const styles = StyleSheet.create((theme) => ({
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
rawSheetFrameAuto: {
|
||||
flexShrink: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
rawSheetScrollFrame: {
|
||||
minHeight: 0,
|
||||
overflow: "hidden",
|
||||
},
|
||||
rawSheetFrameFilled: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
rawSheetBodyFilled: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
},
|
||||
rawSheetBodyClipped: {
|
||||
flexShrink: 1,
|
||||
minHeight: 0,
|
||||
overflow: "hidden",
|
||||
},
|
||||
rawStaticMeasure: {
|
||||
flexShrink: 0,
|
||||
},
|
||||
sheetHeader: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
|
||||
@@ -8,7 +8,11 @@ import {
|
||||
import { BottomSheetScrollView, BottomSheetFlatList } from "@gorhom/bottom-sheet";
|
||||
import { GestureDetector } from "react-native-gesture-handler";
|
||||
import { usePanelAwareHorizontalScrollGesture } from "@/mobile-panels/gestures";
|
||||
import { useAttachSheetContentDrag, useIsInsideBottomSheet } from "./bottom-sheet-scope";
|
||||
import {
|
||||
useAttachSheetContentDrag,
|
||||
useIsInsideBottomSheet,
|
||||
useSheetScrollMetricsProps,
|
||||
} from "./bottom-sheet-scope";
|
||||
import { withContentDrag } from "./content-drag";
|
||||
|
||||
// Gorhom forwards to the RN FlatList and ScrollView instances. Its published ref types disagree
|
||||
@@ -20,6 +24,12 @@ const SheetFlatList = BottomSheetFlatList as unknown as typeof NativeFlatList;
|
||||
export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
|
||||
function ScrollView(props, ref) {
|
||||
const inSheet = useIsInsideBottomSheet();
|
||||
const metricsProps = useSheetScrollMetricsProps(
|
||||
inSheet && !props.horizontal,
|
||||
props.onLayout,
|
||||
props.onContentSizeChange,
|
||||
props.style,
|
||||
);
|
||||
if (props.horizontal) {
|
||||
return (
|
||||
<HorizontalScrollGesture>
|
||||
@@ -27,7 +37,7 @@ export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
|
||||
</HorizontalScrollGesture>
|
||||
);
|
||||
}
|
||||
if (inSheet) return <SheetScrollView {...props} ref={ref} />;
|
||||
if (inSheet) return <SheetScrollView {...props} {...metricsProps} ref={ref} />;
|
||||
return <PageScrollView {...props} ref={ref} />;
|
||||
},
|
||||
);
|
||||
@@ -47,6 +57,12 @@ const SheetScrollView = withContentDrag<ScrollViewProps, NativeScrollView>(
|
||||
|
||||
function PresentationFlatList<Item>(props: FlatListProps<Item>, ref: Ref<NativeFlatList<Item>>) {
|
||||
const inSheet = useIsInsideBottomSheet();
|
||||
const metricsProps = useSheetScrollMetricsProps(
|
||||
inSheet && !props.horizontal,
|
||||
props.onLayout,
|
||||
props.onContentSizeChange,
|
||||
props.style,
|
||||
);
|
||||
if (props.horizontal) {
|
||||
return (
|
||||
<HorizontalScrollGesture>
|
||||
@@ -54,7 +70,7 @@ function PresentationFlatList<Item>(props: FlatListProps<Item>, ref: Ref<NativeF
|
||||
</HorizontalScrollGesture>
|
||||
);
|
||||
}
|
||||
if (inSheet) return <SheetFlatList {...props} ref={ref} />;
|
||||
if (inSheet) return <SheetFlatList {...props} {...metricsProps} ref={ref} />;
|
||||
return <NativeFlatList {...props} ref={ref} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,38 @@
|
||||
// Web dialogs use ordinary scrolling at every breakpoint. Keep native gesture
|
||||
// dependencies out of this module's import graph.
|
||||
export { ScrollView, FlatList } from "react-native";
|
||||
import { forwardRef, type ReactElement, type Ref } from "react";
|
||||
import {
|
||||
FlatList as NativeFlatList,
|
||||
ScrollView as NativeScrollView,
|
||||
type FlatListProps,
|
||||
type ScrollViewProps,
|
||||
} from "react-native";
|
||||
import { useIsInsideBottomSheet, useSheetScrollMetricsProps } from "./bottom-sheet-scope";
|
||||
|
||||
export const ScrollView = forwardRef<NativeScrollView, ScrollViewProps>(
|
||||
function ScrollView(props, ref) {
|
||||
const inSheet = useIsInsideBottomSheet();
|
||||
const metricsProps = useSheetScrollMetricsProps(
|
||||
inSheet && !props.horizontal,
|
||||
props.onLayout,
|
||||
props.onContentSizeChange,
|
||||
props.style,
|
||||
);
|
||||
return <NativeScrollView {...props} {...metricsProps} ref={ref} />;
|
||||
},
|
||||
);
|
||||
|
||||
function WebFlatList<Item>(props: FlatListProps<Item>, ref: Ref<NativeFlatList<Item>>) {
|
||||
const inSheet = useIsInsideBottomSheet();
|
||||
const metricsProps = useSheetScrollMetricsProps(
|
||||
inSheet && !props.horizontal,
|
||||
props.onLayout,
|
||||
props.onContentSizeChange,
|
||||
props.style,
|
||||
);
|
||||
return <NativeFlatList {...props} {...metricsProps} ref={ref} />;
|
||||
}
|
||||
|
||||
export const FlatList = forwardRef(WebFlatList) as <Item>(
|
||||
props: FlatListProps<Item> & { ref?: Ref<NativeFlatList<Item>> },
|
||||
) => ReactElement;
|
||||
|
||||
@@ -176,7 +176,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
maxWidth: "100%",
|
||||
},
|
||||
fieldFocused: {
|
||||
borderColor: theme.colors.borderAccent,
|
||||
borderColor: theme.colors.borderFocus,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
input: {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import React from "react";
|
||||
import { cleanup, fireEvent, render } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { SegmentedControl } from "./segmented-control";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe("SegmentedControl", () => {
|
||||
it("renders a recessed surface2 pill track with an elevated surface0 selected thumb in light theme", () => {
|
||||
const { getByTestId } = render(
|
||||
<SegmentedControl
|
||||
testID="mode-picker"
|
||||
value="form"
|
||||
onValueChange={vi.fn()}
|
||||
options={[
|
||||
{ value: "form", label: "Form", testID: "mode-form" },
|
||||
{ value: "uri", label: "URI", testID: "mode-uri" },
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
const track = getByTestId("mode-picker");
|
||||
const selected = getByTestId("mode-form");
|
||||
const unselected = getByTestId("mode-uri");
|
||||
|
||||
const trackStyle = getComputedStyle(track);
|
||||
const selectedStyle = getComputedStyle(selected);
|
||||
const unselectedStyle = getComputedStyle(unselected);
|
||||
|
||||
expect(trackStyle.backgroundColor).toBe("rgb(244, 244, 245)");
|
||||
expect(trackStyle.paddingTop).toBe("2px");
|
||||
expect(selectedStyle.backgroundColor).toBe("rgb(255, 255, 255)");
|
||||
expect(unselectedStyle.backgroundColor).toBe("rgba(0, 0, 0, 0)");
|
||||
expect(selected.getAttribute("aria-selected")).toBe("true");
|
||||
expect(unselected.getAttribute("aria-selected")).toBe("false");
|
||||
});
|
||||
|
||||
it("calls onValueChange only when clicking an enabled unselected segment", () => {
|
||||
const onValueChange = vi.fn();
|
||||
const { getByTestId } = render(
|
||||
<SegmentedControl
|
||||
testID="mode-picker"
|
||||
value="form"
|
||||
onValueChange={onValueChange}
|
||||
options={[
|
||||
{ value: "form", label: "Form", testID: "mode-form" },
|
||||
{ value: "uri", label: "URI", testID: "mode-uri" },
|
||||
{ value: "ssh", label: "SSH", testID: "mode-ssh", disabled: true },
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
fireEvent.click(getByTestId("mode-form"));
|
||||
expect(onValueChange).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.click(getByTestId("mode-ssh"));
|
||||
expect(onValueChange).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.click(getByTestId("mode-uri"));
|
||||
expect(onValueChange).toHaveBeenCalledTimes(1);
|
||||
expect(onValueChange).toHaveBeenCalledWith("uri");
|
||||
});
|
||||
});
|
||||
@@ -31,8 +31,6 @@ interface SegmentedControlProps<T extends string> {
|
||||
hideLabels?: boolean;
|
||||
/** Share the container's width equally between the segments, for a control that heads a surface. */
|
||||
fill?: boolean;
|
||||
/** Let the segments run onto more lines when they do not fit on one. */
|
||||
wrap?: boolean;
|
||||
style?: StyleProp<ViewStyle>;
|
||||
testID?: string;
|
||||
}
|
||||
@@ -59,7 +57,6 @@ export function SegmentedControl<T extends string>({
|
||||
size: sizeProp,
|
||||
hideLabels = false,
|
||||
fill = false,
|
||||
wrap = false,
|
||||
style,
|
||||
testID,
|
||||
}: SegmentedControlProps<T>) {
|
||||
@@ -75,8 +72,8 @@ export function SegmentedControl<T extends string>({
|
||||
const iconSize = controlIconSize[size];
|
||||
|
||||
const containerStyle = useMemo(
|
||||
() => [styles.container, containerSizeStyle, wrap && styles.containerWrap, style],
|
||||
[containerSizeStyle, style, wrap],
|
||||
() => [styles.container, containerSizeStyle, style],
|
||||
[containerSizeStyle, style],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -191,11 +188,7 @@ const styles = StyleSheet.create((theme) => {
|
||||
container: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
backgroundColor: "transparent",
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
containerWrap: {
|
||||
flexWrap: "wrap",
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
containerSm: {
|
||||
...geometry.segmentedContainerSm,
|
||||
@@ -209,6 +202,8 @@ const styles = StyleSheet.create((theme) => {
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
gap: theme.spacing[1],
|
||||
borderWidth: theme.borderWidth[1],
|
||||
borderColor: "transparent",
|
||||
},
|
||||
segmentSm: {
|
||||
...geometry.segmentedSegmentSm,
|
||||
@@ -223,10 +218,16 @@ const styles = StyleSheet.create((theme) => {
|
||||
minWidth: 0,
|
||||
},
|
||||
segmentSelected: {
|
||||
backgroundColor: theme.colors.surface3,
|
||||
backgroundColor: theme.colors.surfaceSegmentThumb,
|
||||
borderColor: theme.colors.borderSegmentThumb,
|
||||
shadowColor: theme.shadow.sm.shadowColor,
|
||||
shadowOffset: { width: 0, height: 1 },
|
||||
shadowRadius: 2,
|
||||
shadowOpacity: 1,
|
||||
elevation: 1,
|
||||
},
|
||||
segmentHover: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
backgroundColor: theme.colors.interactionHighlight,
|
||||
},
|
||||
segmentPressed: {
|
||||
backgroundColor: theme.colors.surface3,
|
||||
|
||||
@@ -40,6 +40,8 @@ const backdropColorMappings: Record<SurfaceBackdrop, (theme: Theme) => { color:
|
||||
surface0: (theme) => ({ color: theme.colors.surface0 }),
|
||||
surface1: (theme) => ({ color: theme.colors.surface1 }),
|
||||
surface2: (theme) => ({ color: theme.colors.surface2 }),
|
||||
surfaceHover: (theme) => ({ color: theme.colors.surfaceHover }),
|
||||
surfaceSelected: (theme) => ({ color: theme.colors.surfaceSelected }),
|
||||
surfaceSidebar: (theme) => ({ color: theme.colors.surfaceSidebar }),
|
||||
surfaceSidebarHover: (theme) => ({ color: theme.colors.surfaceSidebarHover }),
|
||||
surfaceSidebarSelected: (theme) => ({ color: theme.colors.surfaceSidebarSelected }),
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { createLocalFileAttachmentStore } from "@/attachments/local-file-attachment-store";
|
||||
import { garbageCollectAttachments, persistAttachmentFromBytes } from "@/attachments/service";
|
||||
import { __setAttachmentStoreForTests } from "@/attachments/store";
|
||||
import { createTestAttachmentFileSystem } from "@/attachments/test-attachment-file-system";
|
||||
import type {
|
||||
AgentAttachment,
|
||||
ForgeSearchItem,
|
||||
@@ -739,6 +743,60 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
});
|
||||
|
||||
describe("enqueueComposerAgentMessage", () => {
|
||||
it("keeps all queued images available when garbage collection runs during upload", async () => {
|
||||
const fileSystem = createTestAttachmentFileSystem();
|
||||
const store = createLocalFileAttachmentStore({
|
||||
storageType: "native-file",
|
||||
baseDirectoryName: "attachments",
|
||||
fileSystem,
|
||||
resolvePreviewUrl: async (attachment) => attachment.storageKey,
|
||||
});
|
||||
__setAttachmentStoreForTests(store);
|
||||
try {
|
||||
const first = await persistAttachmentFromBytes({
|
||||
id: "first",
|
||||
bytes: new Uint8Array([1]),
|
||||
mimeType: "image/png",
|
||||
});
|
||||
const second = await persistAttachmentFromBytes({
|
||||
id: "second",
|
||||
bytes: new Uint8Array([2]),
|
||||
mimeType: "image/png",
|
||||
});
|
||||
const client = createFakeSendClient();
|
||||
|
||||
await enqueueComposerAgentMessage({
|
||||
client: {
|
||||
...client,
|
||||
async uploadFile(input) {
|
||||
if (client.uploadCalls.length === 0) {
|
||||
// Draft has already been cleared before the queue action runs.
|
||||
await garbageCollectAttachments({ referencedIds: new Set() });
|
||||
}
|
||||
return await client.uploadFile(input);
|
||||
},
|
||||
},
|
||||
agentId: "agent",
|
||||
text: "follow up",
|
||||
attachments: [
|
||||
{ kind: "image", metadata: first },
|
||||
{ kind: "image", metadata: second },
|
||||
],
|
||||
});
|
||||
|
||||
expect(client.uploadCalls.map(({ bytes }) => Array.from(bytes))).toEqual([[1], [2]]);
|
||||
expect(client.calls[0]?.options).toMatchObject({
|
||||
activeTurnBehavior: "queue",
|
||||
attachments: [{ role: "image" }, { role: "image" }],
|
||||
});
|
||||
|
||||
await garbageCollectAttachments({ referencedIds: new Set() });
|
||||
expect(fileSystem.files.size).toBe(0);
|
||||
} finally {
|
||||
__setAttachmentStoreForTests(null);
|
||||
}
|
||||
});
|
||||
|
||||
it("hands a trimmed message to the host queue without adding a timeline row", async () => {
|
||||
const client = createFakeSendClient();
|
||||
const review = reviewWorkspaceAttachment("Queued review.");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { SelectedFile } from "@/attachments/selected-file";
|
||||
import { prepareImageAttachmentsForSend } from "@/attachments/service";
|
||||
import { prepareImageAttachmentsForSend, withRetainedAttachments } from "@/attachments/service";
|
||||
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
|
||||
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import { optimisticEnqueueAgentMessage } from "@/agent-queue";
|
||||
@@ -324,8 +324,10 @@ async function prepareImagePayload(
|
||||
input: Pick<DispatchComposerAgentMessageInput, "client" | "uploadImages">,
|
||||
images: AttachmentMetadata[],
|
||||
) {
|
||||
if (input.uploadImages) return { attachments: await input.uploadImages(images) };
|
||||
return await prepareImageAttachmentsForSend({ client: input.client, images });
|
||||
return await withRetainedAttachments(images, async () => {
|
||||
if (input.uploadImages) return { attachments: await input.uploadImages(images) };
|
||||
return await prepareImageAttachmentsForSend({ client: input.client, images });
|
||||
});
|
||||
}
|
||||
|
||||
/** Images the host already holds render as images, the way its timeline echo does. */
|
||||
|
||||
@@ -25,7 +25,8 @@ import { AgentSheetHome, type AgentSheetControls } from "./sheet-home";
|
||||
|
||||
const SERVER_ID = "srv-live-settings";
|
||||
const AGENT_ID = "agent-1";
|
||||
const SHEET_FRAME_STYLE = { width: 390, height: 640, display: "flex" } as const;
|
||||
const SHEET_FRAME_WIDTH = 390;
|
||||
const SHEET_FRAME_HEIGHT = 640;
|
||||
const GESTURE_ROOT_STYLE = { flex: 1 } as const;
|
||||
const PRESENTATION = resolveComposerControlPresentation("compact");
|
||||
const ignoreOpenSelect = () => undefined;
|
||||
@@ -147,7 +148,7 @@ function setupSession() {
|
||||
}
|
||||
|
||||
// Reads strictly from session-store — zero overlay merging in the view.
|
||||
function LiveSheet({ toast }: { toast: ToastApi }) {
|
||||
function LiveSheet({ toast, height = SHEET_FRAME_HEIGHT }: { toast: ToastApi; height?: number }) {
|
||||
const agent = useSessionStore((state) => state.sessions[SERVER_ID]?.agents.get(AGENT_ID) ?? null);
|
||||
const modeControl = useLiveAgentModeControl(SERVER_ID, AGENT_ID);
|
||||
|
||||
@@ -206,8 +207,13 @@ function LiveSheet({ toast }: { toast: ToastApi }) {
|
||||
[items.features, items.thinking, modeControl],
|
||||
);
|
||||
|
||||
const frameStyle = useMemo(
|
||||
() => ({ width: SHEET_FRAME_WIDTH, height, display: "flex" as const }),
|
||||
[height],
|
||||
);
|
||||
|
||||
return (
|
||||
<div style={SHEET_FRAME_STYLE}>
|
||||
<div style={frameStyle}>
|
||||
<AgentSheetHome
|
||||
controls={controls}
|
||||
disabled={false}
|
||||
@@ -224,14 +230,14 @@ function createToast() {
|
||||
};
|
||||
}
|
||||
|
||||
function renderSheet() {
|
||||
function renderSheet(height = SHEET_FRAME_HEIGHT) {
|
||||
const toast = createToast();
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
render(
|
||||
<GestureHandlerRootView style={GESTURE_ROOT_STYLE}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastApiProvider api={toast}>
|
||||
<LiveSheet toast={toast} />
|
||||
<LiveSheet toast={toast} height={height} />
|
||||
</ToastApiProvider>
|
||||
</QueryClientProvider>
|
||||
</GestureHandlerRootView>,
|
||||
@@ -239,6 +245,16 @@ function renderSheet() {
|
||||
return toast;
|
||||
}
|
||||
|
||||
function toViewportPoint(x: number, y: number): { x: number; y: number } {
|
||||
const frameRect = window.frameElement?.getBoundingClientRect();
|
||||
const scaleX = frameRect ? frameRect.width / window.innerWidth : 1;
|
||||
const scaleY = frameRect ? frameRect.height / window.innerHeight : 1;
|
||||
return {
|
||||
x: Math.round((frameRect?.left ?? 0) + x * scaleX),
|
||||
y: Math.round((frameRect?.top ?? 0) + y * scaleY),
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => vi.stubGlobal("React", React));
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
@@ -377,17 +393,16 @@ describe("live agent settings sheet (browser geometry & races)", () => {
|
||||
const lowStop = screen.getByTestId("agent-controls-thinking-low");
|
||||
const highStop = screen.getByTestId("agent-controls-thinking-high");
|
||||
const mediumStop = screen.getByTestId("agent-controls-thinking-medium");
|
||||
const frameRect = window.frameElement?.getBoundingClientRect();
|
||||
const scaleX = frameRect ? frameRect.width / window.innerWidth : 1;
|
||||
const scaleY = frameRect ? frameRect.height / window.innerHeight : 1;
|
||||
const toViewport = (x: number, y: number) => ({
|
||||
x: Math.round((frameRect?.left ?? 0) + x * scaleX),
|
||||
y: Math.round((frameRect?.top ?? 0) + y * scaleY),
|
||||
});
|
||||
const lowRect = lowStop.getBoundingClientRect();
|
||||
const highRect = highStop.getBoundingClientRect();
|
||||
const start = toViewport(lowRect.left + lowRect.width / 2, lowRect.top + lowRect.height / 2);
|
||||
const end = toViewport(highRect.left + highRect.width / 2, highRect.top + highRect.height / 2);
|
||||
const start = toViewportPoint(
|
||||
lowRect.left + lowRect.width / 2,
|
||||
lowRect.top + lowRect.height / 2,
|
||||
);
|
||||
const end = toViewportPoint(
|
||||
highRect.left + highRect.width / 2,
|
||||
highRect.top + highRect.height / 2,
|
||||
);
|
||||
const initialLeft = Math.round(thumb.getBoundingClientRect().left);
|
||||
const browserCdp = cdp();
|
||||
|
||||
@@ -466,7 +481,7 @@ describe("live agent settings sheet (browser geometry & races)", () => {
|
||||
|
||||
// A plain tap after the drag still selects immediately.
|
||||
const medRect = mediumStop.getBoundingClientRect();
|
||||
const med = toViewport(medRect.left + medRect.width / 2, medRect.top + medRect.height / 2);
|
||||
const med = toViewportPoint(medRect.left + medRect.width / 2, medRect.top + medRect.height / 2);
|
||||
await browserCdp.send("Input.dispatchMouseEvent", {
|
||||
type: "mousePressed",
|
||||
x: med.x,
|
||||
@@ -488,4 +503,93 @@ describe("live agent settings sheet (browser geometry & races)", () => {
|
||||
expect(mediumLeft).toBeGreaterThan(initialLeft);
|
||||
expect(mediumLeft).toBeLessThan(draggedLeft);
|
||||
});
|
||||
|
||||
it("scrolls an overflowing pills row horizontally inside the sheet and selects a clipped option while keeping vertical sheet scroll", async () => {
|
||||
const calls = setupSession();
|
||||
const sevenChoices = [
|
||||
{ value: "default", label: "Option One" },
|
||||
{ value: "opt-2", label: "Option Two" },
|
||||
{ value: "opt-3", label: "Option Three" },
|
||||
{ value: "opt-4", label: "Option Four" },
|
||||
{ value: "opt-5", label: "Option Five" },
|
||||
{ value: "opt-6", label: "Option Six" },
|
||||
{ value: "opt-7", label: "Option Seven" },
|
||||
];
|
||||
pushServerUpdate({
|
||||
controls: [
|
||||
CONTROLS[0],
|
||||
{
|
||||
type: "select",
|
||||
key: "service_tier",
|
||||
label: "Speed",
|
||||
defaultValue: "default",
|
||||
choices: sevenChoices,
|
||||
},
|
||||
],
|
||||
});
|
||||
renderSheet(240);
|
||||
|
||||
const track = await screen.findByTestId("agent-feature-service_tier");
|
||||
const firstPill = screen.getByTestId("agent-feature-service_tier-default");
|
||||
const lastPill = screen.getByTestId("agent-feature-service_tier-opt-7");
|
||||
await nextPaint();
|
||||
|
||||
// All seven pills sit on one horizontal line inside the recessed track.
|
||||
expect(Math.round(firstPill.getBoundingClientRect().top)).toBe(
|
||||
Math.round(lastPill.getBoundingClientRect().top),
|
||||
);
|
||||
|
||||
const horizontalScroller = track.parentElement?.parentElement;
|
||||
expect(horizontalScroller).toBeTruthy();
|
||||
if (!horizontalScroller) throw new Error("Missing horizontal scroller around pills control");
|
||||
expect(horizontalScroller.scrollWidth).toBeGreaterThan(horizontalScroller.clientWidth);
|
||||
expect(lastPill.getBoundingClientRect().right).toBeGreaterThan(
|
||||
horizontalScroller.getBoundingClientRect().right,
|
||||
);
|
||||
|
||||
const scrollerRect = horizontalScroller.getBoundingClientRect();
|
||||
const pillsCenter = toViewportPoint(
|
||||
scrollerRect.left + scrollerRect.width / 2,
|
||||
scrollerRect.top + scrollerRect.height / 2,
|
||||
);
|
||||
const browserCdp = cdp();
|
||||
|
||||
// Wheel horizontally over the pills row to reveal the clipped trailing option and select it.
|
||||
await browserCdp.send("Input.dispatchMouseEvent", {
|
||||
type: "mouseWheel",
|
||||
x: pillsCenter.x,
|
||||
y: pillsCenter.y,
|
||||
deltaX: horizontalScroller.scrollWidth,
|
||||
deltaY: 0,
|
||||
});
|
||||
await nextPaint();
|
||||
await nextPaint();
|
||||
expect(horizontalScroller.scrollLeft).toBeGreaterThan(0);
|
||||
expect(lastPill.getBoundingClientRect().right).toBeLessThanOrEqual(
|
||||
horizontalScroller.getBoundingClientRect().right + 2,
|
||||
);
|
||||
|
||||
fireEvent.click(lastPill);
|
||||
expect(calls.map((call) => [call.kind, call.value])).toEqual([
|
||||
["options", { service_tier: "opt-7" }],
|
||||
]);
|
||||
|
||||
// Vertical wheel input over the pills row scrolls the outer sheet to reveal controls below it.
|
||||
const sheetScroller = screen.getByTestId("agent-controls-settings-list");
|
||||
expect(sheetScroller.scrollHeight).toBeGreaterThan(sheetScroller.clientHeight);
|
||||
const modeCard = screen.getByTestId("mode-control");
|
||||
const modeTopBefore = modeCard.getBoundingClientRect().top;
|
||||
|
||||
await browserCdp.send("Input.dispatchMouseEvent", {
|
||||
type: "mouseWheel",
|
||||
x: pillsCenter.x,
|
||||
y: pillsCenter.y,
|
||||
deltaX: 0,
|
||||
deltaY: 160,
|
||||
});
|
||||
await nextPaint();
|
||||
await nextPaint();
|
||||
expect(sheetScroller.scrollTop).toBeGreaterThan(0);
|
||||
expect(modeCard.getBoundingClientRect().top).toBeLessThan(modeTopBefore);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -279,13 +279,14 @@ function PillsControl({ item, disabled }: { item: SelectItem; disabled: boolean
|
||||
const handleChange = useCallback((value: string) => run(() => item.onChange(value)), [item, run]);
|
||||
return (
|
||||
<View style={styles.pills}>
|
||||
<SegmentedControl
|
||||
options={options}
|
||||
value={item.value}
|
||||
onValueChange={handleChange}
|
||||
wrap
|
||||
testID={item.testID}
|
||||
/>
|
||||
<SheetScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.pillsScroll}>
|
||||
<SegmentedControl
|
||||
options={options}
|
||||
value={item.value}
|
||||
onValueChange={handleChange}
|
||||
testID={item.testID}
|
||||
/>
|
||||
</SheetScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -640,6 +641,9 @@ const styles = StyleSheet.create((theme) => ({
|
||||
pills: {
|
||||
padding: theme.spacing[2],
|
||||
},
|
||||
pillsScroll: {
|
||||
flexGrow: 0,
|
||||
},
|
||||
sliderCard: {
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingTop: theme.spacing[3],
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user