Compare commits

..
125 changed files with 1574 additions and 6474 deletions
-14
View File
@@ -1,14 +0,0 @@
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
+4 -4
View File
@@ -25,7 +25,7 @@ jobs:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@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@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@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@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
uses: actions/setup-node@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@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8
uses: expo/expo-github-action@v8
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
+28 -31
View File
@@ -24,9 +24,6 @@ env:
NPM_CONFIG_AUDIT: "false"
NPM_CONFIG_FUND: "false"
permissions:
contents: read
jobs:
changes:
name: changes
@@ -52,7 +49,7 @@ jobs:
with:
fetch-depth: 0
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@v4
with:
node-version: "22"
@@ -63,7 +60,7 @@ jobs:
filters: .github/ci-paths.yml
- name: Validate CI contracts
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
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
quality:
name: quality
@@ -71,9 +68,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@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
@@ -90,7 +87,7 @@ jobs:
- name: Lint lockfile
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
run: npm exec --no -- lockfile-lint --path package-lock.json --type npm --allowed-hosts npm --validate-https --validate-integrity
run: npx --yes 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') }}
@@ -151,9 +148,9 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
runs-on: windows-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
@@ -173,9 +170,9 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
@@ -211,9 +208,9 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.website != 'false') }}
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
@@ -231,7 +228,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@0057852bfaa89a56745cba8c7296529d2fc39830 # v4
uses: actions/cache@v4
with:
path: ~/website-browser-debs
key: website-browser-debs-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
@@ -255,7 +252,7 @@ jobs:
run: npm run test:e2e --workspace=@getpaseo/website
- name: Upload website test artifacts
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
uses: actions/upload-artifact@v4
if: failure()
with:
name: website-playwright-results
@@ -277,12 +274,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@11d5960a326750d5838078e36cf38b85af677262 # v4
uses: actions/checkout@v4
with:
fetch-depth: 0
- &server_node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
@@ -371,9 +368,9 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.server != 'false') }}
runs-on: macos-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
@@ -421,9 +418,9 @@ jobs:
permissions:
contents: read
steps: &desktop_test_steps
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
@@ -456,7 +453,7 @@ jobs:
PASEO_DESKTOP_LIFECYCLE_ARTIFACT_DIR: ${{ runner.temp }}/desktop-lifecycle
- name: Upload desktop lifecycle screenshots
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
uses: actions/upload-artifact@v4
if: ${{ !cancelled() && runner.os == 'Linux' }}
with:
name: desktop-lifecycle
@@ -479,7 +476,7 @@ jobs:
PASEO_DESKTOP_BROWSER_E2E_ARTIFACT_DIR: ${{ runner.temp }}/desktop-browser-e2e
- name: Upload desktop browser diagnostics
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
uses: actions/upload-artifact@v4
if: ${{ failure() && runner.os == 'Linux' }}
with:
name: desktop-browser-e2e
@@ -503,9 +500,9 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.app != 'false') }}
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
@@ -536,9 +533,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@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
@@ -570,7 +567,7 @@ jobs:
PWTEST_SHARD_WEIGHTS: "90:114:100:104:108:112:112:90"
- name: Upload test artifacts
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
uses: actions/upload-artifact@v4
if: failure()
with:
name: playwright-results-${{ env.PLAYWRIGHT_ARTIFACT }}
@@ -661,9 +658,9 @@ jobs:
PASEO_CLI_TEST_SHARD: "1"
PASEO_CLI_TEST_SHARD_TOTAL: "3"
steps: &cli_test_steps
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
+2 -2
View File
@@ -14,9 +14,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
+2 -2
View File
@@ -10,9 +10,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
+2 -2
View File
@@ -22,9 +22,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
+21 -21
View File
@@ -61,7 +61,7 @@ jobs:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
with:
sparse-checkout: scripts
ref: ${{ env.CHECKOUT_REF }}
@@ -113,7 +113,7 @@ jobs:
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@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@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
@@ -183,7 +183,7 @@ jobs:
- name: Upload packaged smoke diagnostics
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
uses: actions/upload-artifact@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@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
uses: actions/upload-artifact@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@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
uses: actions/upload-artifact@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@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@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@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
@@ -284,7 +284,7 @@ jobs:
- name: Upload packaged smoke diagnostics
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
uses: actions/upload-artifact@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@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
uses: actions/upload-artifact@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@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
uses: actions/upload-artifact@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@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@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@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
@@ -382,7 +382,7 @@ jobs:
- name: Upload packaged smoke diagnostics
if: failure()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
uses: actions/upload-artifact@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@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
uses: actions/upload-artifact@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@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
uses: actions/upload-artifact@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@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@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@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
uses: actions/setup-node@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@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
uses: actions/download-artifact@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@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
uses: actions/download-artifact@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@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
uses: actions/download-artifact@v4
with:
name: windows-manifest
path: release-manifests/windows-manifest
+2 -2
View File
@@ -26,7 +26,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@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@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
+12 -13
View File
@@ -48,7 +48,7 @@ jobs:
check_tag: ${{ steps.values.outputs.check_tag }}
publish_tags: ${{ steps.values.outputs.publish_tags }}
steps:
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
- uses: actions/checkout@v6
- id: values
env:
@@ -119,12 +119,12 @@ jobs:
permissions:
contents: read
steps:
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
- uses: actions/checkout@v6
- uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4
- uses: docker/setup-qemu-action@v4
- uses: docker/setup-buildx-action@v4
- uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
- uses: docker/build-push-action@v7
with:
context: .
file: docker/base/Dockerfile
@@ -133,8 +133,7 @@ jobs:
PASEO_VERSION=${{ needs.setup.outputs.install_version }}
tags: ${{ needs.setup.outputs.check_tag }}
push: false
# The check build does not export an image to attach attestations to.
provenance: mode=max
provenance: false
cache-from: type=gha,scope=paseo
cache-to: type=gha,scope=paseo,mode=max
@@ -146,19 +145,19 @@ jobs:
contents: read
packages: write
steps:
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
- uses: actions/checkout@v6
- uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4
- uses: docker/setup-qemu-action@v4
- uses: docker/setup-buildx-action@v4
- name: Log in to GHCR
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4
uses: docker/login-action@v4
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
- uses: docker/build-push-action@v7
with:
context: .
file: docker/base/Dockerfile
@@ -167,6 +166,6 @@ jobs:
PASEO_VERSION=${{ needs.setup.outputs.install_version }}
tags: ${{ needs.setup.outputs.publish_tags }}
push: true
provenance: mode=max
provenance: false
cache-from: type=gha,scope=paseo
cache-to: type=gha,scope=paseo,mode=max
+4 -4
View File
@@ -25,23 +25,23 @@ jobs:
update-hash:
runs-on: ubuntu-latest
steps:
- uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1
- uses: actions/create-github-app-token@v1
id: app-token
with:
app-id: ${{ secrets.PASEO_BOT_APP_ID }}
private-key: ${{ secrets.PASEO_BOT_APP_PRIVATE_KEY }}
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
with:
ref: ${{ github.ref }}
token: ${{ steps.app-token.outputs.token }}
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
- uses: cachix/install-nix-action@3dc140bfc76c49fbd4dd958429132e3746bcb086 # v31
- uses: cachix/install-nix-action@v31
with:
nix_path: nixpkgs=channel:nixos-unstable
+5 -5
View File
@@ -41,14 +41,14 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
- uses: cachix/install-nix-action@3dc140bfc76c49fbd4dd958429132e3746bcb086 # v31
- uses: cachix/install-nix-action@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@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
- uses: cachix/install-nix-action@3dc140bfc76c49fbd4dd958429132e3746bcb086 # v31
- uses: cachix/install-nix-action@v31
with:
nix_path: nixpkgs=channel:nixos-unstable
+1 -1
View File
@@ -30,7 +30,7 @@ jobs:
permissions:
contents: write
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/checkout@v4
with:
fetch-depth: 0
+1 -1
View File
@@ -1,6 +1,6 @@
# syntax=docker/dockerfile:1
ARG NODE_IMAGE=node:22-bookworm-slim@sha256:be979e5523c76fa4d5ca4ebd3099078f220aa47ec39c48ad5b5df9314debd6eb
ARG NODE_IMAGE=node:22-bookworm-slim
FROM --platform=$BUILDPLATFORM ${NODE_IMAGE} AS source-pack
ARG PASEO_VERSION
+2 -3
View File
@@ -216,17 +216,16 @@ 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` for `npm ci` (or `npm install`), Expo prebuild, and Gradle:
F-Droid builds should set `PASEO_FDROID_BUILD=1` when running Expo prebuild:
```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
```
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.
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.
For a single-ABI APK, pass React Native's architecture property to Gradle:
+2 -2
View File
@@ -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. `<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.
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.
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 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.
`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.
---
+2 -12
View File
@@ -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`, 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.
- `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.
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,17 +46,7 @@ Some fork changes are backports. A sync past the upstream version drops them in
## Engine constraints
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.
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.
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.
+3 -111
View File
@@ -38,7 +38,6 @@
"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",
@@ -14793,20 +14792,6 @@
"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",
@@ -17363,43 +17348,6 @@
"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",
@@ -25869,19 +25817,9 @@
"license": "MIT"
},
"node_modules/js-yaml": {
"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"
}
],
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
"license": "MIT",
"dependencies": {
"argparse": "^2.0.1"
@@ -26872,41 +26810,6 @@
"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",
@@ -30062,16 +29965,6 @@
"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",
@@ -37727,7 +37620,6 @@
"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",
-1
View File
@@ -144,7 +144,6 @@
"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,29 +173,6 @@ 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, `borderFocus` while focused: greys in both themes, never the accent.
// `borderAccent` at rest, `surface4` while focused: greys in both themes, never the accent.
const FRAME_BORDERS = {
dark: { rest: "rgb(47, 53, 52)", focus: "rgb(66, 70, 69)" },
light: { rest: "rgb(236, 236, 241)", focus: "rgb(208, 208, 213)" },
dark: { rest: "rgb(47, 53, 52)", focus: "rgb(89, 91, 91)" },
light: { rest: "rgb(236, 236, 241)", focus: "rgb(212, 212, 216)" },
} as const;
for (const colorScheme of ["dark", "light"] as const) {
@@ -41,9 +41,6 @@ import {
connectDirectHost,
connectDirectHostExpectingPassword,
pasteIntoDirectHost,
pasteClipboardIntoDirectField,
pasteIntoMiddleOfDirectHost,
typeDirectHostCharacters,
fillDirectHostPromptPassword,
openCompactSettings,
expectCompactSettingsList,
@@ -59,7 +56,6 @@ import {
fillDirectHostUri,
expectDirectHostFormValues,
expectDirectHostSslEnabled,
expectDirectHostSslDisabled,
fillDirectHostAddress,
toggleDirectHostSsl,
expectDirectHostUriValue,
@@ -377,110 +373,6 @@ 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);
@@ -500,11 +500,12 @@ async function sampleFramesDuring(
}
return match;
};
const findOverviewCard = (tabsEl: Element | null): Element | null => {
const findOverviewCard = (tabsEl: Element | null, stacked: boolean): Element | null => {
if (!tabsEl) return null;
const container =
tabsEl.closest('[style*="overflow"]')?.parentElement ??
tabsEl.parentElement?.parentElement?.parentElement;
const container = stacked
? (tabsEl.closest('[style*="overflow"]')?.parentElement ??
tabsEl.parentElement?.parentElement?.parentElement)
: tabsEl.parentElement?.parentElement;
if (!container) return null;
const visibleChildren = Array.from(container.children).filter(isVisible);
return visibleChildren[visibleChildren.length - 1] ?? null;
@@ -518,7 +519,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);
const overviewCard = findOverviewCard(tabsEl, stacked);
const overviewRect = roundRect(overviewCard);
samples.push({
@@ -455,46 +455,6 @@ 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();
}
-4
View File
@@ -1,5 +1 @@
declare module "*.css";
declare module "*.woff2" {
const src: string;
export default src;
}
-3
View File
@@ -17,9 +17,6 @@ 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;
+2 -3
View File
@@ -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' --tests '*MathRenderingFallbackTest' --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' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
},
"dependencies": {
"@codemirror/commands": "6.10.4",
@@ -110,7 +110,6 @@
"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",
@@ -179,7 +178,7 @@
"ws": "^8.20.0"
},
"enriched-markdown": {
"enableMath": true,
"enableMath": false,
"enableCodeHighlight": true,
"codeHighlightLanguages": [
"json",
@@ -111,7 +111,6 @@ function ThinkingField({
value={state.thinkingOptionId || null}
onValueChange={onSegmentChange}
size={controlSize}
style={styles.thinkingControl}
testID="agent-profile-thinking-trigger"
/>
</Field>
@@ -575,9 +574,6 @@ const styles = StyleSheet.create((theme) => ({
padding: theme.spacing[4],
gap: theme.spacing[4],
},
thinkingControl: {
alignSelf: "flex-start",
},
featureCardPending: {
opacity: theme.opacity[50],
},
@@ -122,26 +122,3 @@ 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,12 +1,8 @@
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 BLOCKS = ["p", "pre", "li", "td", "th", "h1", "h2", "h3", "h4", "h5", "h6"]
.flatMap((tag) => [tag, `[data-paseo-markdown-tag="${tag}"]`])
.join(",");
const IGNORED =
'[data-paseo-markdown-ignore="true"], [aria-hidden="true"], .katex-mathml, annotation, annotation-xml, button, [role="button"], svg, script, style';
'[data-paseo-markdown-ignore="true"], [aria-hidden="true"], 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[] {
@@ -1,39 +0,0 @@
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,10 +7,9 @@
// 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] *):not([role="math"]):not([role="math"] *):not(.katex):not(.katex *){font-family:var(--paseo-ui-font);}';
":is(#root, #overlay-root) *:not([data-pmono]):not([data-pmono] *){font-family:var(--paseo-ui-font);}";
export function applyRootUiFont(uiFontStack: string): void {
if (typeof document === "undefined") return;
@@ -997,11 +997,7 @@ 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,
latexMath = false,
): Promise<HTMLElement> {
async function renderMarkdown(markdown: string, lastText: string): Promise<HTMLElement> {
if (!host || !root) {
host = document.createElement("div");
document.body.append(host);
@@ -1021,7 +1017,7 @@ describe("quote copy", () => {
children: h(EnrichedMarkdownText, {
markdown,
flavor: "github",
md4cFlags: { latexMath, admonitions: true },
md4cFlags: { latexMath: false, admonitions: true },
renderers: WEB_RENDERERS,
}),
}),
@@ -1139,102 +1135,4 @@ 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 &lt; 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,7 +6,6 @@ import {
type MarkdownClipboardContent,
} from "@/utils/rich-clipboard";
import {
KATEX_MATHML_SELECTOR,
MARKDOWN_ADMONITION_TITLE_ATTRIBUTE,
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
MARKDOWN_COPY_IMAGE_SOURCES_ATTRIBUTE,
@@ -21,8 +20,6 @@ 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";
@@ -109,17 +106,6 @@ 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}~~`,
@@ -425,19 +411,12 @@ function nodeAtPath(root: Node, path: number[]): Node {
}
function removeUnselectedSemantics(range: Range, source: Element, clone: Element): void {
const selector = `[${MARKDOWN_COPY_TAG_ATTRIBUTE}], [${MARKDOWN_MATH_SOURCE_ATTRIBUTE}], a, ${SEMANTIC_TAGS}`;
const selector = `[${MARKDOWN_COPY_TAG_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) {
@@ -461,9 +440,6 @@ 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)) {
@@ -614,9 +590,7 @@ 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}], ${KATEX_MATHML_SELECTOR}`,
)) {
for (const ignored of fragment.querySelectorAll(`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}]`)) {
ignored.remove();
}
}
@@ -707,19 +681,8 @@ 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}], ${KATEX_MATHML_SELECTOR}`,
)) {
for (const ignored of container.querySelectorAll(`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}]`)) {
ignored.remove();
}
@@ -769,11 +732,7 @@ function restoreMarkdownElements(container: HTMLElement): void {
element.replaceWith(...element.childNodes);
}
restoreMathSources(container);
const presentational = Array.from(
container.querySelectorAll(`div, span:not([${MARKDOWN_MATH_SOURCE_ATTRIBUTE}])`),
);
const presentational = Array.from(container.querySelectorAll("div, span"));
for (const element of presentational.toReversed()) {
element.replaceWith(...element.childNodes);
}
@@ -13,10 +13,6 @@ 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.
@@ -12,7 +12,6 @@ import {
type NativeScrollEvent,
type NativeSyntheticEvent,
type PressableStateCallbackType,
type ScrollView as NativeScrollView,
} from "react-native";
import {
memo,
@@ -34,7 +33,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 { SPACING, type Theme } from "@/styles/theme";
import 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";
@@ -45,9 +44,7 @@ import {
EditingTextInput as TextInput,
type EditingTextInputHandle,
} from "@/components/ui/text-input";
import { Button } from "@/components/ui/button";
import { getScrollOffsetToRevealItem } from "@/components/ui/scroll-reveal";
import { ScrollView } from "@/components/ui/scroll-view";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
import { Shortcut } from "@/components/ui/shortcut";
import {
IsolatedBottomSheetModal,
@@ -1028,7 +1025,7 @@ export function CommandCenter() {
onKeyDown: handleOverlayKeyDown,
});
const tabOptions = useMemo<CommandCenterTabOption[]>(
const tabOptions = useMemo<SegmentedControlOption<CommandCenterTab>[]>(
() =>
state.tabs.map((tab) => ({
value: tab,
@@ -1038,7 +1035,13 @@ export function CommandCenter() {
[state.tabs, t],
);
const tabs = (
<CommandCenterTabPills options={tabOptions} value={state.tab} onValueChange={state.selectTab} />
<SegmentedControl
options={tabOptions}
value={state.tab}
onValueChange={state.selectTab}
size="sm"
testID="command-center-tabs"
/>
);
const placeholder = t(placeholderKey(state.tab, state.tabs));
@@ -1125,136 +1128,6 @@ 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">
@@ -1297,25 +1170,12 @@ const styles = StyleSheet.create((theme) => ({
borderBottomWidth: 1,
borderBottomColor: theme.colors.border,
},
// 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.
// 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.
tabBar: {
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,
paddingTop: COMMAND_CENTER_SECTION_GAP,
},
input: {
fontSize: theme.fontSize.base,
@@ -1,9 +1,5 @@
import { describe, expect, it } from "vitest";
import {
buildDirectConnectionUri,
normalizeDirectConnectionHost,
parseDirectConnectionPaste,
} from "./direct-connection-host";
import { buildDirectConnectionUri, normalizeDirectConnectionHost } from "./direct-connection-host";
const labels = {
hostRequired: "host required",
@@ -61,26 +57,6 @@ 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");
});
@@ -88,102 +64,5 @@ 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,297 +19,52 @@ export interface NormalizedDirectConnectionHost {
isIpv6: boolean;
}
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,
};
}
const SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(\d*))?$/;
const HOST_WITH_PORT_PATTERN = /^([^:]+):(\d+)$/;
/**
* 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 {
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 };
}
let host = input.trim().replace(SCHEME_PATTERN, "");
const suffixIndex = host.search(/[/?#]/);
if (suffixIndex !== -1) {
host = host.slice(0, suffixIndex);
}
return {
host: address.host,
port: address.port || null,
isIpv6: address.isIpv6,
};
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 };
}
export function buildDirectConnectionUri(
draft: DirectConnectionHostInput,
labels: DirectConnectionHostLabels,
): string {
const resolved = resolveDirectHostDraft(draft);
if (!resolved.host) {
const normalized = normalizeDirectConnectionHost(draft.host);
const port = Number((normalized.port ?? draft.port).trim());
if (!normalized.host) {
throw new Error(labels.hostRequired);
}
const port = parseValidPortNumber(resolved.port);
if (port === null) {
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error(labels.invalidPort);
}
return serializeConnectionUriForStorage({
host: resolved.host,
host: normalized.host,
port,
isIpv6: resolved.isIpv6,
useTls: resolved.useTls,
...(resolved.password ? { password: resolved.password } : {}),
isIpv6: normalized.isIpv6,
useTls: draft.useTls,
...(draft.password ? { password: draft.password } : {}),
});
}
@@ -1,535 +0,0 @@
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,
);
}
+2 -21
View File
@@ -4,7 +4,6 @@ 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*)>`;
@@ -56,14 +55,12 @@ 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, protectedRanges) : [];
const tableRanges = /<br/i.test(source) ? collectTableRanges(source, codeRanges) : [];
const links: (string | undefined)[] = [];
let previousTag: { name: string; end: number } | null = null;
const convert = (raw: string, offset: number): string => {
if (isOffsetInRanges(offset, protectedRanges)) return raw;
if (codeRanges.some(({ start, end }) => offset >= start && offset < end)) return raw;
if (raw.startsWith("<!--")) return "";
const summary = /^<summary\b[^>]*>([\s\S]*?)<\/summary\s*>$/i.exec(raw);
if (summary) {
@@ -264,19 +261,3 @@ 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
@@ -1,277 +0,0 @@
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}");
});
});
@@ -1,437 +0,0 @@
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 &amp; ||spoiler||",
"",
"$$",
"\\begin{pmatrix}",
"a & b \\\\",
"c & d",
"\\end{pmatrix}",
"$$",
"",
"Norm $\\|x\\| + ||y||$ and &lt;end&gt;.",
].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,37 +806,9 @@ 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",
@@ -1470,69 +1442,3 @@ 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: true, hardSoftBreaks: true, admonitions: true };
const MD4C_FLAGS = { latexMath: false, 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,11 +8,10 @@ import {
type ComponentProps,
type MouseEvent,
} from "react";
import {
registerKaTeXStyleLoader,
type CodeBlockRendererProps,
type LinkRendererProps,
type MarkdownRenderers,
import type {
CodeBlockRendererProps,
LinkRendererProps,
MarkdownRenderers,
} from "react-native-enriched-markdown";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useFileLink } from "@/assistant-file-links";
@@ -152,11 +151,6 @@ 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,
+36 -45
View File
@@ -2,7 +2,6 @@ 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";
@@ -232,8 +231,6 @@ export function prepareMarkdownSource(
} = {},
) {
source = normalizeMarkdownHtml(source);
const { source: adaptedSource, mathRanges } = adaptMarkdownMath(source);
source = adaptedSource;
const images: MarkdownImage[] = [];
let tree: Root | undefined;
const getTree = () =>
@@ -354,59 +351,53 @@ 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") 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 === "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 === "tableRow") adaptTableRow(start, end);
if (node.type === "image" || node.type === "imageReference") {
if (!isOffsetInRanges(start, mathRanges)) collectImage(node, start, end);
collectImage(node, start, end);
return;
}
if (node.type === "text") adaptTextNode(start, end);
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 ("children" in node)
node.children.forEach((child, index) => visit(child, node.children[index - 1]));
@@ -1,22 +1,3 @@
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.
@@ -34,17 +15,8 @@ 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;
}
@@ -52,9 +24,7 @@ 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;
}
@@ -140,20 +110,76 @@ 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 } {
return stripBlockquotesAt(text, 0, text.length);
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 };
}
function measureIndent(text: string, from: number): { spaces: number; offset: number } {
return measureIndentAt(text, from, text.length);
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 };
}
function matchListMarker(
text: string,
from: number,
maxIndent = Number.POSITIVE_INFINITY,
): { markerEnd: number; contentIndent: number } | null {
return matchListMarkerAt(text, from, text.length, maxIndent);
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;
}
function parseFenceOpener(
@@ -161,7 +187,17 @@ function parseFenceOpener(
from: number,
maxIndent: number,
): { char: "`" | "~"; length: number; info: string } | null {
return parseFenceOpenerAt(text, from, text.length, maxIndent);
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 };
}
function isClosingFence(
@@ -171,7 +207,16 @@ function isClosingFence(
char: "`" | "~",
minLength: number,
): boolean {
return isClosingFenceAt(text, from, text.length, maxIndent, char, minLength);
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;
}
function isPartialClosingFence(
@@ -192,191 +237,18 @@ function isPartialClosingFence(
}
function isBlankRest(text: string, from: number): boolean {
return isBlankRange(text, from, text.length);
for (let i = from; i < text.length; i++) {
if (text[i] !== " " && text[i] !== "\t") return false;
}
return true;
}
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,
@@ -386,17 +258,8 @@ function stepFenceLine(
const { quoteDepth, offset } = stripBlockquotes(text);
if (state.openFence !== null) {
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;
if (quoteDepth < state.openFence.quoteDepth) {
// Leaving the blockquote closes any fence opened inside it.
state.openFence = null;
} else if (
isClosingFence(
@@ -411,7 +274,6 @@ function stepFenceLine(
state.openFence = null;
return;
} else {
state.openFence.lastLineStart = lineStart;
const partialCloser =
isTrailingPartialLine &&
quoteDepth === state.openFence.quoteDepth &&
@@ -427,62 +289,34 @@ function stepFenceLine(
}
}
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;
}
if (isBlankRest(text, offset)) return;
let cursor = offset;
let lineIndentBase = quoteDepth === state.listQuoteDepth ? state.listContentIndent : 0;
let lineIndentBase = state.listContentIndent;
const { spaces: firstSpaces } = measureIndent(text, cursor);
if (quoteDepth === state.listQuoteDepth && firstSpaces < state.listContentIndent) {
if (firstSpaces < state.listContentIndent) {
state.listContentIndent = 0;
lineIndentBase = 0;
}
let peeledList = false;
let marker = matchListMarker(text, cursor, lineIndentBase + 3);
let marker = matchListMarker(text, cursor);
while (marker) {
const markerBase = cursor === offset ? 0 : lineIndentBase;
const totalIndent = markerBase + marker.contentIndent;
state.listContentIndent = totalIndent;
state.listQuoteDepth = quoteDepth;
lineIndentBase = totalIndent;
state.listContentIndent = marker.contentIndent;
lineIndentBase = marker.contentIndent;
cursor = marker.markerEnd;
peeledList = true;
marker = matchListMarker(text, cursor, 3);
marker = matchListMarker(text, cursor);
}
const opener = parseFenceOpener(text, cursor, peeledList ? 3 : lineIndentBase + 3);
const opener = parseFenceOpener(text, cursor, 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 {
@@ -505,28 +339,18 @@ 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 and display-math tracking across completed lines so steady-state
* Incrementally advance fence 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;
openDisplayMath: OpenDisplayMath | null;
lastClosedFenceLineStart: number;
} {
): { openFence: OpenFence | null; lastClosedFenceLineStart: number } {
const completedEnd = lastCompletedLineEnd(source);
const state: FenceStepState = {
openFence: null,
openDisplayMath: null,
listContentIndent: 0,
listQuoteDepth: 0,
lastClosedFenceLineStart: -1,
};
@@ -537,9 +361,7 @@ 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;
}
@@ -551,9 +373,7 @@ 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;
}
@@ -563,7 +383,6 @@ function resolveFenceState(
return {
openFence: state.openFence,
openDisplayMath: state.openDisplayMath,
lastClosedFenceLineStart: state.lastClosedFenceLineStart,
};
}
@@ -844,6 +663,17 @@ 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;
@@ -1031,7 +861,6 @@ interface InlineScanState {
stack: InlineStackEntry[];
openCode: { pos: number; length: number; contentStart: number } | null;
openHtmlPos: number | null;
openInlineMathPos: number | null;
trailingBackslash: boolean;
}
@@ -1324,7 +1153,7 @@ function stripPartialEmphCloser(output: string, entry: EmphEntry): string {
function unwindInlineState(source: string, state: InlineScanState): string {
let output = source;
const { openCode, openHtmlPos, openInlineMathPos, trailingBackslash, stack } = state;
const { openCode, openHtmlPos, trailingBackslash, stack } = state;
if (openCode) {
let codeContent = output.slice(openCode.contentStart);
@@ -1338,8 +1167,6 @@ 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);
}
@@ -1383,56 +1210,6 @@ 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,
@@ -1442,8 +1219,13 @@ function stepInlineScanner(
): number | null {
const ch = source[i];
if (ch === "\n") return lineContentStarts.get(i + 1) ?? i + 1;
if (ch === "\\") return scanInlineBackslashToken(source, i, state);
if (ch === "$") return scanInlineDollarToken(source, i, state);
if (ch === "\\") {
if (i + 1 === source.length) {
state.trailingBackslash = true;
return null;
}
return i + (isAsciiPunctuation(source[i + 1]) ? 2 : 1);
}
if (ch === "`") return scanBacktickToken(source, i, state);
if (ch === "<") return scanHtmlToken(source, i, state);
if (ch === "[" || (ch === "!" && source[i + 1] === "[")) {
@@ -1466,7 +1248,6 @@ function stabilizeInlineBlock(
stack: [],
openCode: null,
openHtmlPos: null,
openInlineMathPos: null,
trailingBackslash: false,
};
@@ -1478,74 +1259,42 @@ 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 & 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);
// 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;
}
// 2. Trailing GFM table — O(table rows) backwards from EOF.
@@ -1581,9 +1330,7 @@ export function createStreamingMarkdownStabilizer(): StreamingMarkdownStabilizer
const checkpoint: FenceScanCheckpoint = {
scannedPrefix: "",
openFence: null,
openDisplayMath: null,
listContentIndent: 0,
listQuoteDepth: 0,
lastClosedFenceLineStart: -1,
};
return {
@@ -544,119 +544,3 @@ 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,7 +2,6 @@ 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,
@@ -81,24 +80,12 @@ 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!;
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;
settled = open.lastIndexOf("\n", nextStart - 1) + 1;
}
if (settled === 0) return;
if (boundary - partStarts[partStarts.length - 1] >= HEAD_PART_LENGTH) partStarts.push(boundary);
@@ -103,17 +103,6 @@ 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,
},
},
};
}
@@ -251,15 +251,11 @@ describe("control geometry", () => {
}
});
it("keeps segmented controls in an inset pill track sized to match buttons", () => {
it("keeps segmented controls ghost with button-radius segments in a button-sized track", () => {
const geometry = createControlGeometry(theme);
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.segmentedContainerSm.padding).toBe(0);
expect(geometry.segmentedContainerMd.padding).toBe(0);
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,15 +462,11 @@ export function createControlGeometry(theme: Theme) {
},
segmentedContainerSm: {
minHeight: CONTROL_HEIGHTS.sm,
padding: SEGMENTED_INSET,
gap: SEGMENTED_INSET,
borderRadius: theme.borderRadius.full,
padding: 0,
},
segmentedContainerMd: {
minHeight: CONTROL_HEIGHTS.md,
padding: SEGMENTED_INSET,
gap: SEGMENTED_INSET,
borderRadius: theme.borderRadius.full,
padding: 0,
},
segmentedSegmentSm: {
minHeight: mapLayout(CONTROL_HEIGHTS.sm, (height) => height - SEGMENTED_INSET * 2),
@@ -574,7 +574,7 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surface2,
},
fieldFocused: {
borderColor: theme.colors.borderFocus,
borderColor: theme.colors.borderAccent,
},
fieldInput: {
flex: 1,
@@ -176,7 +176,7 @@ const styles = StyleSheet.create((theme) => ({
maxWidth: "100%",
},
fieldFocused: {
borderColor: theme.colors.borderFocus,
borderColor: theme.colors.borderAccent,
backgroundColor: theme.colors.surface2,
},
input: {
@@ -1,63 +0,0 @@
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,6 +31,8 @@ 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;
}
@@ -57,6 +59,7 @@ export function SegmentedControl<T extends string>({
size: sizeProp,
hideLabels = false,
fill = false,
wrap = false,
style,
testID,
}: SegmentedControlProps<T>) {
@@ -72,8 +75,8 @@ export function SegmentedControl<T extends string>({
const iconSize = controlIconSize[size];
const containerStyle = useMemo(
() => [styles.container, containerSizeStyle, style],
[containerSizeStyle, style],
() => [styles.container, containerSizeStyle, wrap && styles.containerWrap, style],
[containerSizeStyle, style, wrap],
);
return (
@@ -188,7 +191,11 @@ const styles = StyleSheet.create((theme) => {
container: {
flexDirection: "row",
alignItems: "center",
backgroundColor: theme.colors.surface2,
backgroundColor: "transparent",
gap: theme.spacing[1],
},
containerWrap: {
flexWrap: "wrap",
},
containerSm: {
...geometry.segmentedContainerSm,
@@ -202,8 +209,6 @@ const styles = StyleSheet.create((theme) => {
justifyContent: "center",
flexShrink: 0,
gap: theme.spacing[1],
borderWidth: theme.borderWidth[1],
borderColor: "transparent",
},
segmentSm: {
...geometry.segmentedSegmentSm,
@@ -218,16 +223,10 @@ const styles = StyleSheet.create((theme) => {
minWidth: 0,
},
segmentSelected: {
backgroundColor: theme.colors.surfaceSegmentThumb,
borderColor: theme.colors.borderSegmentThumb,
shadowColor: theme.shadow.sm.shadowColor,
shadowOffset: { width: 0, height: 1 },
shadowRadius: 2,
shadowOpacity: 1,
elevation: 1,
backgroundColor: theme.colors.surface3,
},
segmentHover: {
backgroundColor: theme.colors.interactionHighlight,
backgroundColor: theme.colors.surface2,
},
segmentPressed: {
backgroundColor: theme.colors.surface3,
@@ -25,8 +25,7 @@ import { AgentSheetHome, type AgentSheetControls } from "./sheet-home";
const SERVER_ID = "srv-live-settings";
const AGENT_ID = "agent-1";
const SHEET_FRAME_WIDTH = 390;
const SHEET_FRAME_HEIGHT = 640;
const SHEET_FRAME_STYLE = { width: 390, height: 640, display: "flex" } as const;
const GESTURE_ROOT_STYLE = { flex: 1 } as const;
const PRESENTATION = resolveComposerControlPresentation("compact");
const ignoreOpenSelect = () => undefined;
@@ -148,7 +147,7 @@ function setupSession() {
}
// Reads strictly from session-store — zero overlay merging in the view.
function LiveSheet({ toast, height = SHEET_FRAME_HEIGHT }: { toast: ToastApi; height?: number }) {
function LiveSheet({ toast }: { toast: ToastApi }) {
const agent = useSessionStore((state) => state.sessions[SERVER_ID]?.agents.get(AGENT_ID) ?? null);
const modeControl = useLiveAgentModeControl(SERVER_ID, AGENT_ID);
@@ -207,13 +206,8 @@ function LiveSheet({ toast, height = SHEET_FRAME_HEIGHT }: { toast: ToastApi; he
[items.features, items.thinking, modeControl],
);
const frameStyle = useMemo(
() => ({ width: SHEET_FRAME_WIDTH, height, display: "flex" as const }),
[height],
);
return (
<div style={frameStyle}>
<div style={SHEET_FRAME_STYLE}>
<AgentSheetHome
controls={controls}
disabled={false}
@@ -230,14 +224,14 @@ function createToast() {
};
}
function renderSheet(height = SHEET_FRAME_HEIGHT) {
function renderSheet() {
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} height={height} />
<LiveSheet toast={toast} />
</ToastApiProvider>
</QueryClientProvider>
</GestureHandlerRootView>,
@@ -245,16 +239,6 @@ function renderSheet(height = SHEET_FRAME_HEIGHT) {
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();
@@ -393,16 +377,17 @@ 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 = 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 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 initialLeft = Math.round(thumb.getBoundingClientRect().left);
const browserCdp = cdp();
@@ -481,7 +466,7 @@ describe("live agent settings sheet (browser geometry & races)", () => {
// A plain tap after the drag still selects immediately.
const medRect = mediumStop.getBoundingClientRect();
const med = toViewportPoint(medRect.left + medRect.width / 2, medRect.top + medRect.height / 2);
const med = toViewport(medRect.left + medRect.width / 2, medRect.top + medRect.height / 2);
await browserCdp.send("Input.dispatchMouseEvent", {
type: "mousePressed",
x: med.x,
@@ -503,93 +488,4 @@ 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,14 +279,13 @@ function PillsControl({ item, disabled }: { item: SelectItem; disabled: boolean
const handleChange = useCallback((value: string) => run(() => item.onChange(value)), [item, run]);
return (
<View style={styles.pills}>
<SheetScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.pillsScroll}>
<SegmentedControl
options={options}
value={item.value}
onValueChange={handleChange}
testID={item.testID}
/>
</SheetScrollView>
<SegmentedControl
options={options}
value={item.value}
onValueChange={handleChange}
wrap
testID={item.testID}
/>
</View>
);
}
@@ -641,9 +640,6 @@ const styles = StyleSheet.create((theme) => ({
pills: {
padding: theme.spacing[2],
},
pillsScroll: {
flexGrow: 0,
},
sliderCard: {
paddingHorizontal: theme.spacing[4],
paddingTop: theme.spacing[3],
+1 -1
View File
@@ -2492,7 +2492,7 @@ const styles = StyleSheet.create((theme: Theme) => ({
// A neutral step up from the resting `borderAccent`, never the accent. There is no hover
// step: `surface3` is fainter than the resting border in the pure black theme.
inputWrapperFocused: {
borderColor: theme.colors.borderFocus,
borderColor: theme.colors.surface4,
},
// The band the fullscreen glyph sits in is the input's own padding, so a tap
// anywhere in it (under the glyph, or where the glyph would be) is a tap on the
@@ -1,19 +1,11 @@
import { useCheckboxSpaceKey } from "@/components/ui/checkbox";
import { PressHighlight } from "@/components/ui/press-highlight";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { useCallback, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
Alert,
Text,
View,
type LayoutChangeEvent,
type NativeSyntheticEvent,
type TextInputSelectionChangeEventData,
} from "react-native";
import { Alert, Text, View, type LayoutChangeEvent } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
import { Check, Eye, EyeOff, Form, Link, Link2 } from "lucide-react-native";
import { Check, Eye, EyeOff, Link2 } from "lucide-react-native";
import type { HostProfile } from "@/types/host-connection";
import { useHosts, useHostMutations } from "@/runtime/host-runtime";
import { buildConnectionFailureCopy } from "@/components/connection-failure-copy";
@@ -35,14 +27,11 @@ import { useHardwareKeyboardPresent } from "@/keyboard/availability";
import { getConnectionHelloRejection } from "@/utils/test-daemon-connection";
import {
canSwitchToForm,
commitHost,
editForm,
editHost,
editPort,
editPromptPassword,
editUri,
openDirectConnection,
pasteDirectConnection,
promptForPassword,
resolveConnection,
switchMode,
@@ -52,7 +41,6 @@ import {
type DirectConnectionMode,
type DirectConnectionUri,
type ResolvedDirectConnection,
type TextSelection,
} from "./direct-connection";
const FLEX_ONE_STYLE = { flex: 1 } as const;
@@ -224,17 +212,11 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
{
value: "form",
label: t("pairing.direct.modes.form"),
icon: ({ color, size }) => <Form color={color} size={size} />,
testID: "direct-mode-form",
disabled: !formAvailable,
...(formAvailable ? {} : { tooltip: t("pairing.direct.modes.uriOnlyLink") }),
},
{
value: "uri",
label: t("pairing.direct.modes.uri"),
icon: ({ color, size }) => <Link color={color} size={size} />,
testID: "direct-mode-uri",
},
{ value: "uri", label: t("pairing.direct.modes.uri"), testID: "direct-mode-uri" },
],
[formAvailable, t],
);
@@ -480,22 +462,6 @@ interface FieldEvents {
onSubmit: () => void;
}
function syncTextField(
inputRef: React.RefObject<EditingTextInputHandle | null>,
selectionRef: React.RefObject<TextSelection | null> | null,
currentValue: string,
nextValue: string,
options: { collapseSelectionToEnd: boolean; forceReplace: boolean },
) {
if (!options.forceReplace && nextValue === currentValue) return;
const endSelection = { start: nextValue.length, end: nextValue.length };
inputRef.current?.replaceText(
nextValue,
options.collapseSelectionToEnd ? endSelection : undefined,
);
if (selectionRef) selectionRef.current = endSelection;
}
function DirectFormFields({
input,
isSaving,
@@ -509,13 +475,6 @@ function DirectFormFields({
}) {
const { t } = useTranslation();
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
const hostInputRef = useRef<EditingTextInputHandle | null>(null);
const portInputRef = useRef<EditingTextInputHandle | null>(null);
const passwordInputRef = useRef<EditingTextInputHandle | null>(null);
const sslToggleRef = useRef<View | null>(null);
const hostSelectionRef = useRef<TextSelection | null>(null);
const portSelectionRef = useRef<TextSelection | null>(null);
const suppressedPasteRef = useRef<{ field: "host" | "port"; text: string } | null>(null);
const hostFieldStyle = useMemo(() => [styles.field, styles.hostField], []);
const portFieldStyle = useMemo(() => [styles.field, styles.portField], []);
const passwordInputStyle = useMemo(() => [styles.input, styles.passwordInput], []);
@@ -528,188 +487,22 @@ function DirectFormFields({
[isSaving, input.useTls],
);
const syncFormInputs = useCallback(
(
previous: DirectConnectionForm,
next: DirectConnectionForm,
source:
| { kind: "paste"; field: "host" | "port" }
| { kind: "change"; field: "host" | "port" | "password"; rawText: string }
| { kind: "sync" },
) => {
syncTextField(
hostInputRef,
hostSelectionRef,
source.kind === "change" && source.field === "host" ? source.rawText : previous.host,
next.host,
{
collapseSelectionToEnd: source.kind !== "sync" && source.field === "host",
forceReplace: source.kind === "paste" && source.field === "host",
},
);
syncTextField(
portInputRef,
portSelectionRef,
source.kind === "change" && source.field === "port" ? source.rawText : previous.port,
next.port,
{
collapseSelectionToEnd: source.kind !== "sync" && source.field === "port",
forceReplace: source.kind === "paste" && source.field === "port",
},
);
syncTextField(
passwordInputRef,
null,
source.kind === "change" && source.field === "password"
? source.rawText
: previous.password,
next.password,
{ collapseSelectionToEnd: false, forceReplace: false },
);
},
[],
);
const handleNativePaste = useEffectEvent(
(field: "host" | "port", inputEl: HTMLInputElement, event: ClipboardEvent) => {
if (isSaving) return;
const pastedText = event.clipboardData?.getData("text/plain");
if (!pastedText) return;
const value = inputEl.value;
const selectionStart = inputEl.selectionStart ?? value.length;
const selectionEnd = inputEl.selectionEnd ?? value.length;
const replacesWholeField = selectionStart === 0 && selectionEnd === value.length;
if (!replacesWholeField) {
// Record the resulting single-line input value so the immediately following onChangeText
// treats a partial/mid-field paste as a literal edit rather than smart-filling the form.
const singleLinePaste = pastedText.replace(/[\r\n]/g, "");
suppressedPasteRef.current = {
field,
text: value.slice(0, selectionStart) + singleLinePaste + value.slice(selectionEnd),
};
return;
}
const next = pasteDirectConnection(input, pastedText);
if (!next) return;
event.preventDefault();
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "paste", field });
}
onChange(next);
},
);
useEffect(() => {
if (!isWeb) return;
const entries: Array<{ field: "host" | "port"; handle: EditingTextInputHandle | null }> = [
{ field: "host", handle: hostInputRef.current },
{ field: "port", handle: portInputRef.current },
];
const cleanups: Array<() => void> = [];
for (const { field, handle } of entries) {
const nativeEl = handle?.getNativeRef();
if (!(nativeEl instanceof HTMLInputElement)) continue;
const listener = (event: ClipboardEvent) => handleNativePaste(field, nativeEl, event);
nativeEl.addEventListener("paste", listener);
cleanups.push(() => nativeEl.removeEventListener("paste", listener));
}
return () => {
for (const cleanup of cleanups) cleanup();
};
}, []);
const handleHostSelectionChange = useCallback(
(event: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => {
hostSelectionRef.current = event.nativeEvent.selection;
},
[],
);
const handlePortSelectionChange = useCallback(
(event: NativeSyntheticEvent<TextInputSelectionChangeEventData>) => {
portSelectionRef.current = event.nativeEvent.selection;
},
[],
);
const handleHostBlur = useCallback(
(event: unknown) => {
fieldEvents.onBlur();
// Clicking Use SSL on web blurs Host before onPress fires. Defer committing to the checkbox
// handler so blur's scheme inference cannot flip Use SSL right before the click toggles it.
if (isWeb && sslToggleRef.current instanceof Node) {
const relatedTarget =
(event as { relatedTarget?: unknown; nativeEvent?: { relatedTarget?: unknown } } | null)
?.relatedTarget ??
(event as { nativeEvent?: { relatedTarget?: unknown } } | null)?.nativeEvent
?.relatedTarget;
if (relatedTarget instanceof Node && sslToggleRef.current.contains(relatedTarget)) {
return;
}
}
const next = commitHost(input);
if (next === input) return;
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "sync" });
}
onChange(next);
},
[fieldEvents, input, onChange, syncFormInputs],
);
const handleHostChange = useCallback(
(host: string) => {
const suppressed = suppressedPasteRef.current;
suppressedPasteRef.current = null;
const allowSmartPaste = !(suppressed?.field === "host" && suppressed.text === host);
const next = editHost(input, host, {
allowSmartPaste,
selection: hostSelectionRef.current,
});
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "change", field: "host", rawText: host });
}
onChange(next);
},
[input, onChange, syncFormInputs],
(host: string) => onChange(editHost(input, host)),
[input, onChange],
);
const handlePortChange = useCallback(
(port: string) => {
const suppressed = suppressedPasteRef.current;
suppressedPasteRef.current = null;
const allowSmartPaste = !(suppressed?.field === "port" && suppressed.text === port);
const next = editPort(input, port, {
allowSmartPaste,
selection: portSelectionRef.current,
});
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "change", field: "port", rawText: port });
}
onChange(next);
},
[input, onChange, syncFormInputs],
(port: string) => onChange(editForm(input, { port })),
[input, onChange],
);
const handlePasswordChange = useCallback(
(password: string) => {
const next = editForm(input, { password });
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "change", field: "password", rawText: password });
}
onChange(next);
},
[input, onChange, syncFormInputs],
(password: string) => onChange(editForm(input, { password })),
[input, onChange],
);
const handleToggleUseTls = useCallback(() => {
if (isSaving) return;
const next = editForm(input, { useTls: !input.useTls });
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "sync" });
}
onChange(next);
}, [input, isSaving, onChange, syncFormInputs]);
onChange(editForm(input, { useTls: !input.useTls }));
}, [input, isSaving, onChange]);
const tlsCheckboxKeyProps = useCheckboxSpaceKey(handleToggleUseTls, isSaving);
const handleTogglePasswordVisibility = useCallback(() => {
setIsPasswordVisible((current) => !current);
@@ -723,15 +516,13 @@ function DirectFormFields({
<View style={hostFieldStyle}>
<Text style={styles.label}>{t("pairing.direct.fields.host")}</Text>
<AdaptiveTextInput
ref={hostInputRef}
testID="direct-host-input"
nativeID="direct-host-input"
accessibilityLabel={t("pairing.direct.fields.host")}
initialValue={input.host}
onChangeText={handleHostChange}
onSelectionChange={handleHostSelectionChange}
onFocus={fieldEvents.onFocus}
onBlur={handleHostBlur}
onBlur={fieldEvents.onBlur}
autoFocus={fieldEvents.autoFocus}
placeholder="localhost"
style={styles.input}
@@ -745,13 +536,11 @@ function DirectFormFields({
<View style={portFieldStyle}>
<Text style={styles.label}>{t("pairing.direct.fields.port")}</Text>
<AdaptiveTextInput
ref={portInputRef}
testID="direct-port-input"
nativeID="direct-port-input"
accessibilityLabel={t("pairing.direct.fields.port")}
initialValue={input.port}
onChangeText={handlePortChange}
onSelectionChange={handlePortSelectionChange}
onFocus={fieldEvents.onFocus}
onBlur={fieldEvents.onBlur}
placeholder="6767"
@@ -767,7 +556,6 @@ function DirectFormFields({
</View>
<PressHighlight
ref={sslToggleRef}
style={styles.checkboxRow}
onPress={handleToggleUseTls}
disabled={isSaving}
@@ -792,7 +580,6 @@ function DirectFormFields({
<Text style={styles.label}>{t("pairing.direct.fields.password")}</Text>
<View style={styles.passwordRow}>
<AdaptiveTextInput
ref={passwordInputRef}
testID="direct-password-input"
nativeID="direct-password-input"
accessibilityLabel={t("pairing.direct.fields.password")}
@@ -1,14 +1,11 @@
import { describe, expect, it } from "vitest";
import {
canSwitchToForm,
commitHost,
editForm,
editHost,
editPort,
editPromptPassword,
editUri,
openDirectConnection,
pasteDirectConnection,
promptForPassword,
resolveConnection,
switchMode,
@@ -31,17 +28,7 @@ const OFFER_LINK = `https://app.paseo.sh/#offer=${Buffer.from(
function form(fields: Partial<Omit<DirectConnectionForm, "mode">>): DirectConnectionInput {
const { host = "", ...rest } = fields;
return editForm(typeHost(openDirectConnection(), host), rest);
}
function typeHost(input: DirectConnectionInput, text: string): DirectConnectionInput {
let current = input;
let value = current.mode === "form" ? current.host : "";
for (const ch of text) {
value += ch;
current = editHost(current, value);
}
return current;
return editForm(editHost(openDirectConnection(), host), rest);
}
function uri(text: string): DirectConnectionInput {
@@ -142,20 +129,6 @@ describe("switching from URI to Form", () => {
port: "7000",
useTls: true,
});
expect(switchMode(uri("https://myhost.ts.net"), "form")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "443",
useTls: true,
password: "",
});
expect(switchMode(uri("wss://myhost.ts.net:7443/ws"), "form")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "7443",
useTls: true,
password: "",
});
});
it("round-trips any form with a host", () => {
@@ -180,348 +153,18 @@ describe("switching from URI to Form", () => {
});
describe("typing in Host", () => {
it("never hijacks manual character-by-character typing for host:port, URLs, or bare IPv6", () => {
for (const text of [
"host:7000",
"http://host:7000/",
"[::1]:7000",
"::1",
"2001:1234::1",
"fe80::1",
"tcp://h:7000?password=x",
]) {
expect(typeHost(openDirectConnection(), text)).toEqual({
mode: "form",
host: text,
port: "6767",
useTls: false,
password: "",
});
it("keeps host:port and URL shapes in Host", () => {
for (const text of ["host:7000", "http://host:7000/", "[::1]:7000"]) {
expect(editHost(openDirectConnection(), text)).toMatchObject({ mode: "form", host: text });
}
});
it("does not trigger smart-fill on backspace or mid-string paste", () => {
const typedIpv6 = typeHost(openDirectConnection(), "2001:1234:");
expect(editHost(typedIpv6, "2001:1234")).toEqual({
mode: "form",
host: "2001:1234",
port: "6767",
useTls: false,
password: "",
});
const typedUrl = typeHost(openDirectConnection(), "http://example.com");
expect(editHost(typedUrl, "http://sub.example.com")).toEqual({
mode: "form",
host: "http://sub.example.com",
port: "6767",
useTls: false,
password: "",
});
const typedHostPort = typeHost(openDirectConnection(), "example.com:6768");
expect(editHost(typedHostPort, "my-example.com:6768")).toEqual({
mode: "form",
host: "my-example.com:6768",
port: "6767",
useTls: false,
password: "",
});
});
it("smart-fills Host, Port, Use SSL, and Password on paste into Host", () => {
expect(editHost(openDirectConnection(), "localhost:6768")).toEqual({
mode: "form",
host: "localhost",
port: "6768",
useTls: false,
password: "",
});
expect(editHost(openDirectConnection(), "100.91.42.18:6767")).toEqual({
mode: "form",
host: "100.91.42.18",
port: "6767",
useTls: false,
password: "",
});
expect(editHost(openDirectConnection(), "hetzner.tail8a2f.ts.net:6768")).toEqual({
mode: "form",
host: "hetzner.tail8a2f.ts.net",
port: "6768",
useTls: false,
password: "",
});
expect(editHost(openDirectConnection(), "[::1]:6768")).toEqual({
mode: "form",
host: "::1",
port: "6768",
useTls: false,
password: "",
});
expect(editHost(openDirectConnection(), "https://myhost.ts.net:6767/")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "6767",
useTls: true,
password: "",
});
expect(editHost(openDirectConnection(), "https://myhost.ts.net")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "443",
useTls: true,
password: "",
});
expect(editHost(openDirectConnection(), "http://myhost.ts.net")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "80",
useTls: false,
password: "",
});
expect(editHost(openDirectConnection(), "wss://myhost.ts.net/ws")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "443",
useTls: true,
password: "",
});
expect(editHost(openDirectConnection(), "tcp://h:7000?ssl=true&password=x")).toEqual({
mode: "form",
host: "h",
port: "7000",
useTls: true,
password: "x",
});
});
it("preserves unspecified fields and updates specified fields on paste", () => {
const existing = form({
host: "oldhost",
port: "7000",
useTls: true,
password: "saved-password",
});
// host:port without scheme or password preserves SSL and password
expect(pasteDirectConnection(existing, "localhost:6768")).toEqual({
mode: "form",
host: "localhost",
port: "6768",
useTls: true,
password: "saved-password",
});
// http:// explicitly disables SSL while keeping password
expect(pasteDirectConnection(existing, "http://localhost:6768")).toEqual({
mode: "form",
host: "localhost",
port: "6768",
useTls: false,
password: "saved-password",
});
// tcp:// without port or password keeps current port, clears stale password, and sets SSL from ?ssl=
expect(pasteDirectConnection(existing, "tcp://newhost")).toEqual({
mode: "form",
host: "newhost",
port: "7000",
useTls: false,
password: "",
});
// tcp:// with port and no password clears the previous host's password
expect(pasteDirectConnection(existing, "tcp://second.example.test:7443")).toEqual({
mode: "form",
host: "second.example.test",
port: "7443",
useTls: false,
password: "",
});
// tcp:// with password overwrites password
expect(pasteDirectConnection(existing, "tcp://newhost:8080?ssl=true&password=next")).toEqual({
mode: "form",
host: "newhost",
port: "8080",
useTls: true,
password: "next",
});
});
it("uses native selection range to distinguish full replacements from partial pastes", () => {
const existingDomain = form({ host: "home.example.test", port: "6767" });
expect(
editHost(existingDomain, "https://new.example.test", {
selection: { start: 0, end: "home.example.test".length },
}),
).toEqual({
mode: "form",
host: "new.example.test",
port: "443",
useTls: true,
password: "",
});
// Replacing only a leading word slice is a partial edit, not a full paste
expect(
editHost(existingDomain, "https://new.example.test", {
selection: { start: 0, end: 4 },
}),
).toEqual({
mode: "form",
host: "https://new.example.test",
port: "6767",
useTls: false,
password: "",
});
const existingIp = form({ host: "192.168.1.10", port: "6767" });
expect(
editHost(existingIp, "192.168.1.11:6710", {
selection: { start: 0, end: "192.168.1.10".length },
}),
).toEqual({
mode: "form",
host: "192.168.1.11",
port: "6710",
useTls: false,
password: "",
});
// Pasting `:6710` at the end of an existing host stays a literal edit
expect(
editHost(existingIp, "192.168.1.10:6710", {
selection: { start: "192.168.1.10".length, end: "192.168.1.10".length },
}),
).toEqual({
mode: "form",
host: "192.168.1.10:6710",
port: "6767",
useTls: false,
password: "",
});
});
it("preserves SSL, port, and password when submitting or switching a manually typed URI", () => {
const typedTcp = typeHost(
openDirectConnection(),
"tcp://secure.example.test:7443?ssl=true&password=example",
);
expect(resolveConnection(typedTcp, LABELS)).toEqual({
kind: "direct",
uri: "tcp://secure.example.test:7443?ssl=true",
endpoint: "secure.example.test:7443",
useTls: true,
password: "example",
});
expect(switchMode(typedTcp, "uri")).toMatchObject({
it("moves a typed or pasted URI to URI mode", () => {
expect(editHost(openDirectConnection(), "tcp://h:7000?password=x")).toEqual({
mode: "uri",
uri: "tcp://secure.example.test:7443?ssl=true&password=example",
uri: "tcp://h:7000?password=x",
prompt: null,
});
const typedHttps = typeHost(openDirectConnection(), "https://myhost.ts.net");
expect(resolveConnection(typedHttps, LABELS)).toEqual({
kind: "direct",
uri: "tcp://myhost.ts.net:443?ssl=true",
endpoint: "myhost.ts.net:443",
useTls: true,
});
expect(switchMode(typedHttps, "uri")).toMatchObject({
mode: "uri",
uri: "tcp://myhost.ts.net:443?ssl=true",
});
// Typing a tcp:// URI without SSL or password clears a previous host's SSL and password
const previousHost = form({
host: "first.example.test",
port: "6767",
useTls: true,
password: "first-password",
});
const replacedByTyping = typeHost(editHost(previousHost, ""), "tcp://second.example.test:7443");
expect(commitHost(replacedByTyping)).toEqual({
mode: "form",
host: "second.example.test",
port: "7443",
useTls: false,
password: "",
});
expect(resolveConnection(replacedByTyping, LABELS)).toEqual({
kind: "direct",
uri: "tcp://second.example.test:7443",
endpoint: "second.example.test:7443",
useTls: false,
});
// Editing Password after typing a URI with a wrong password overrides the URI password
const typedWrongPassword = typeHost(
openDirectConnection(),
"tcp://host.example.test:7000?password=wrong",
);
const corrected = editForm(typedWrongPassword, { password: "right" });
expect(corrected).toEqual({
mode: "form",
host: "host.example.test",
port: "7000",
useTls: false,
password: "right",
});
expect(resolveConnection(corrected, LABELS)).toEqual({
kind: "direct",
uri: "tcp://host.example.test:7000",
endpoint: "host.example.test:7000",
useTls: false,
password: "right",
});
});
it("smart-fills when replacing an existing host or pasting into Port", () => {
const withHost = form({ host: "localhost", port: "6767" });
expect(editHost(withHost, "localhost:6768")).toEqual({
mode: "form",
host: "localhost",
port: "6768",
useTls: false,
password: "",
});
expect(editPort(openDirectConnection(), "100.91.42.18:6767")).toEqual({
mode: "form",
host: "100.91.42.18",
port: "6767",
useTls: false,
password: "",
});
expect(editPort(openDirectConnection(), "https://myhost.ts.net:7443")).toEqual({
mode: "form",
host: "myhost.ts.net",
port: "7443",
useTls: true,
password: "",
});
expect(editPort(openDirectConnection(), "7000")).toEqual({
mode: "form",
host: "",
port: "7000",
useTls: false,
password: "",
});
});
it("leaves invalid ports and bare IPv6 untouched on paste", () => {
expect(pasteDirectConnection(openDirectConnection(), "localhost:70000")).toBeNull();
expect(pasteDirectConnection(openDirectConnection(), "localhost:0")).toBeNull();
expect(pasteDirectConnection(openDirectConnection(), "localhost:abc")).toBeNull();
expect(pasteDirectConnection(openDirectConnection(), "::1")).toBeNull();
expect(editHost(openDirectConnection(), "localhost:70000")).toMatchObject({
mode: "form",
host: "localhost:70000",
port: "6767",
});
});
it("moves a pasted pairing link to URI mode", () => {
expect(editHost(openDirectConnection(), RELAY_LINK)).toMatchObject({
mode: "uri",
uri: RELAY_LINK,
@@ -534,11 +177,6 @@ describe("typing in Host", () => {
uri: OFFER_LINK,
prompt: null,
});
expect(pasteDirectConnection(openDirectConnection(), OFFER_LINK)).toEqual({
mode: "uri",
uri: OFFER_LINK,
prompt: null,
});
});
});
@@ -1,11 +1,6 @@
import {
buildDirectConnectionUri,
defaultPortForDirectScheme,
isPairingLink,
parseDirectConnectionAddress,
parseDirectConnectionPaste,
resolveDirectHostDraft,
resolveDirectSchemeTls,
normalizeDirectConnectionHost,
type DirectConnectionHostLabels,
} from "@/components/direct-connection-host";
import { parseConnectionOfferFromUrl } from "@getpaseo/protocol/connection-offer";
@@ -43,6 +38,7 @@ export type ResolvedDirectConnection =
| { kind: "relay"; link: string; password?: string };
const DEFAULT_PORT = "6767";
const TCP_URI_PATTERN = /^tcp:\/\//i;
export function openDirectConnection(): DirectConnectionForm {
return { mode: "form", host: "", port: DEFAULT_PORT, useTls: false, password: "" };
@@ -63,97 +59,21 @@ export function canSwitchToForm(input: DirectConnectionInput): boolean {
return input.mode === "form" || !isPairingLink(input.uri);
}
/**
* Commits a manually typed `host:port`, URI, or pairing link sitting in Host into the form's
* structured fields (or URI mode for pairing links) once the user leaves Host or submits.
*/
export function commitHost(input: DirectConnectionInput): DirectConnectionInput {
if (input.mode !== "form") return input;
return pasteDirectConnection(input, input.host) ?? input;
}
function commitDirectFormHost(input: DirectConnectionForm): DirectConnectionForm {
const committed = pasteDirectConnection(input, input.host);
return committed && committed.mode === "form" ? committed : input;
}
export function editForm(
input: DirectConnectionInput,
fields: Partial<Omit<DirectConnectionForm, "mode" | "host">>,
): DirectConnectionInput {
if (input.mode !== "form") return input;
return { ...commitDirectFormHost(input), ...fields };
return { ...input, ...fields };
}
/**
* Parses a pasted host:port, URI, or pairing link into the next Direct connection state.
* Returns `null` when the text should stay a literal edit in the active field.
*/
export function pasteDirectConnection(
input: DirectConnectionInput,
text: string,
): DirectConnectionInput | null {
if (input.mode !== "form") return null;
if (isPairingLink(text)) return { mode: "uri", uri: text.trim(), prompt: null };
const parsed = parseDirectConnectionPaste(text);
if (!parsed) return null;
return {
...input,
host: parsed.host,
...(parsed.port !== undefined ? { port: parsed.port } : {}),
...(parsed.useTls !== undefined ? { useTls: parsed.useTls } : {}),
...(parsed.password !== undefined ? { password: parsed.password } : {}),
};
}
export interface TextSelection {
start: number;
end: number;
}
export interface DirectFieldEditOptions {
allowSmartPaste?: boolean;
/** The input's selection range immediately before this text change, when known. */
selection?: TextSelection | null;
}
/**
* Updates Host in Form mode. Multi-character pastes that look like a host:port, URI, or pairing
* link populate the form (or switch to URI mode for pairing links) without fighting normal typing.
*/
export function editHost(
input: DirectConnectionInput,
text: string,
options?: DirectFieldEditOptions,
): DirectConnectionInput {
/** A URI typed or pasted into Host moves to URI mode, where its query and pairing data count. */
export function editHost(input: DirectConnectionInput, text: string): DirectConnectionInput {
if (input.mode !== "form") return input;
if (
options?.allowSmartPaste !== false &&
isWholeFieldPasteChange(input.host, text, options?.selection)
) {
const pasted = pasteDirectConnection(input, text);
if (pasted) return pasted;
}
if (looksLikeUri(text)) return { mode: "uri", uri: text.trim(), prompt: null };
return { ...input, host: text };
}
/** Updates Port in Form mode, smart-filling when a full host:port or URI is pasted into Port. */
export function editPort(
input: DirectConnectionInput,
text: string,
options?: DirectFieldEditOptions,
): DirectConnectionInput {
if (input.mode !== "form") return input;
if (
options?.allowSmartPaste !== false &&
isWholeFieldPasteChange(input.port, text, options?.selection)
) {
const pasted = pasteDirectConnection(input, text);
if (pasted) return pasted;
}
return { ...commitDirectFormHost(input), port: text };
}
/** Editing the URI to point at another host drops the password typed for the previous one. */
export function editUri(input: DirectConnectionInput, text: string): DirectConnectionInput {
if (input.mode !== "uri") return input;
@@ -180,12 +100,11 @@ export function resolveConnection(
input: DirectConnectionInput,
labels: DirectConnectionHostLabels,
): ResolvedDirectConnection {
const effective = commitHost(input);
if (effective.mode === "form") {
return resolveTcpUri(buildDirectConnectionUri(effective, labels));
if (input.mode === "form") {
return resolveTcpUri(buildDirectConnectionUri(input, labels));
}
const uri = effective.uri.trim();
const promptPassword = effective.prompt?.password || undefined;
const uri = input.uri.trim();
const promptPassword = input.prompt?.password || undefined;
if (isPairingLink(uri)) {
return { kind: "relay", link: uri, ...(promptPassword ? { password: promptPassword } : {}) };
}
@@ -204,85 +123,43 @@ function resolveTcpUri(uri: string, passwordOverride?: string): ResolvedDirectCo
};
}
function hasAddressDelimiter(text: string): boolean {
return isPairingLink(text) || /[:[\]/]/.test(text);
}
function matchesSelectionEdit(previous: string, next: string, selection: TextSelection): boolean {
const start = Math.min(selection.start, selection.end);
const end = Math.max(selection.start, selection.end);
const prefix = previous.slice(0, start);
const suffix = previous.slice(end);
/** The three link formats a daemon prints for pairing: `relay://`, `#connect=`, and `#offer=`. */
function isPairingLink(uri: string): boolean {
const trimmed = uri.trim();
return (
next.length >= prefix.length + suffix.length && next.startsWith(prefix) && next.endsWith(suffix)
trimmed.toLowerCase().startsWith("relay://") ||
trimmed.includes("#connect=") ||
trimmed.includes("#offer=")
);
}
function isWholeFieldPasteChange(
previous: string,
next: string,
selection?: TextSelection | null,
): boolean {
if (next === previous) return false;
if (previous.length === 0) return next.length >= 2 && hasAddressDelimiter(next);
if (selection) {
const start = Math.min(selection.start, selection.end);
const end = Math.max(selection.start, selection.end);
if (start === 0 && end === previous.length) {
return next.length >= 2 && hasAddressDelimiter(next);
}
if (matchesSelectionEdit(previous, next, selection)) {
return false;
}
}
let prefix = 0;
const minLength = Math.min(previous.length, next.length);
while (prefix < minLength && previous[prefix] === next[prefix]) {
prefix += 1;
}
let suffix = 0;
while (
suffix < minLength - prefix &&
previous[previous.length - 1 - suffix] === next[next.length - 1 - suffix]
) {
suffix += 1;
}
const inserted = next.slice(prefix, next.length - suffix);
if (inserted.length < 2) return false;
if (prefix > 0 && suffix > 0) return false;
return isPairingLink(next) || /[:[\]/]/.test(inserted);
function looksLikeUri(text: string): boolean {
return TCP_URI_PATTERN.test(text.trim()) || isPairingLink(text);
}
// Built as text, not through the strict serializer, so an invalid port carries over and Connect
// reports it instead of the switch failing.
function formToUri(input: DirectConnectionForm): string {
const committed = commitHost(input);
if (committed.mode === "uri") return committed.uri;
const resolved = resolveDirectHostDraft(committed);
if (!resolved.host) return "";
const host = resolved.isIpv6 ? `[${resolved.host}]` : resolved.host;
const normalized = normalizeDirectConnectionHost(input.host);
if (!normalized.host) return "";
const host = normalized.isIpv6 ? `[${normalized.host}]` : normalized.host;
const port = normalized.port ?? input.port.trim();
const query = new URLSearchParams();
if (resolved.useTls) query.set("ssl", "true");
if (resolved.password) query.set("password", resolved.password);
if (input.useTls) query.set("ssl", "true");
if (input.password) query.set("password", input.password);
const search = query.toString();
return `tcp://${host}:${resolved.port}${search ? `?${search}` : ""}`;
return `tcp://${host}:${port}${search ? `?${search}` : ""}`;
}
function uriToForm(uri: string): DirectConnectionForm {
const address = parseDirectConnectionAddress(uri);
const address = splitUri(uri);
if (!address.host) return openDirectConnection();
const port =
(address.port && address.port.length > 0 ? address.port : null) ??
defaultPortForDirectScheme(address.scheme) ??
DEFAULT_PORT;
return {
mode: "form",
host: address.host,
port,
useTls: resolveDirectSchemeTls(address.scheme, address.sslParam) ?? false,
password: address.password ?? "",
port: address.port ?? DEFAULT_PORT,
useTls: address.query.get("ssl") === "true",
password: address.query.get("password") ?? "",
};
}
@@ -297,7 +174,35 @@ export function uriHostLabel(uri: string): string | null {
return null;
}
}
const address = parseDirectConnectionAddress(trimmed);
const address = splitUri(trimmed);
if (!address.host || !address.port) return null;
return address.isIpv6 ? `[${address.host}]:${address.port}` : `${address.host}:${address.port}`;
}
const SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(.*))?$/;
/** Lenient split of a typed URI. Keeps an invalid port as text instead of rejecting it. */
function splitUri(uri: string): {
host: string;
port: string | null;
isIpv6: boolean;
query: URLSearchParams;
} {
const rest = uri.trim().replace(SCHEME_PATTERN, "");
const queryIndex = rest.indexOf("?");
const query = new URLSearchParams(
queryIndex === -1 ? "" : rest.slice(queryIndex + 1).split("#")[0],
);
const authority = rest.split(/[/?#]/)[0] ?? "";
const bracketed = BRACKETED_IPV6_PATTERN.exec(authority);
if (bracketed) {
return { host: bracketed[1] ?? "", port: bracketed[2] || null, isIpv6: true, query };
}
const parts = authority.split(":");
if (parts.length === 2) {
return { host: parts[0] ?? "", port: parts[1] || null, isIpv6: false, query };
}
return { host: authority, port: null, isIpv6: parts.length > 2, query };
}
@@ -796,14 +796,15 @@ function ListedPluginLayout({
{hero}
<View style={styles.twoCol}>
<View style={styles.main}>
<ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.tabBar}>
<View style={styles.tabBar}>
<SegmentedControl
options={tabs}
value={activeTab}
onValueChange={onTabChange}
wrap
testID="plugin-page-tabs"
/>
</ScrollView>
</View>
{panel}
</View>
@@ -1085,12 +1086,7 @@ const styles = StyleSheet.create((theme) => ({
},
controls: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] },
installRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] },
tabBar: {
flexGrow: 0,
marginBottom: theme.spacing[4],
alignSelf: "flex-start",
maxWidth: "100%",
},
tabBar: { marginBottom: theme.spacing[4], alignSelf: "flex-start", maxWidth: "100%" },
compactTabScroll: { flexGrow: 0 },
description: {
color: theme.colors.foreground,
+1 -42
View File
@@ -10,14 +10,7 @@
* A ratio keeps the step equally visible on every base; a lightness delta disappears near black.
* The numbers come from the default themes: Paseo dark and Light.
*/
import {
contrastRatio,
isTranslucentHexColor,
mixHexColors,
paintHexOver,
stepContrast,
translucentStep,
} from "@/utils/color";
import { contrastRatio, mixHexColors, stepContrast, translucentStep } from "@/utils/color";
export type ColorScheme = "light" | "dark";
@@ -60,10 +53,6 @@ const NEUTRAL_FILL_MIN_STEP = 1.25;
const TERTIARY_TEXT_FADE = 0.35;
const TERTIARY_TEXT_FLOOR = 2.55;
// Focused input borders step from the resting accent border toward the foreground so focus
// stays equally legible across dark and light palettes without borrowing `surface4`.
const BORDER_FOCUS_STEP = 1.3;
function deriveStates({
surface,
foreground,
@@ -144,33 +133,3 @@ export function deriveSidebarStateText(
if (contrastRatio(tertiary, surface) >= TERTIARY_TEXT_FLOOR) return tertiary;
return stepContrast(surface, foreground, TERTIARY_TEXT_FLOOR);
}
function closestToForeground(candidates: readonly string[], foreground: string): string {
return candidates.reduce((best, candidate) =>
contrastRatio(candidate, foreground) < contrastRatio(best, foreground) ? candidate : best,
);
}
/**
* Neutral focus border stepped from `borderAccent` toward `foreground`.
*
* When `borderAccent` is translucent, the focus border stays translucent (calibrated against
* `surface1`) so it scales cleanly over both `surface1` (composer) and `surface2` (`SearchField`,
* `MenuTextField`). When `borderAccent` is opaque, stepping starts from whichever of
* `[borderAccent, surface1, surface2]` already sits closest to `foreground` so focus never lands
* on `surface2`.
*/
export function deriveBorderFocus(
borderAccent: string,
foreground: string,
surface1: string,
surface2: string,
): string {
if (isTranslucentHexColor(borderAccent)) {
const painted = paintHexOver(surface1, borderAccent);
const target = stepContrast(painted, foreground, BORDER_FOCUS_STEP);
return translucentStep(surface1, foreground, contrastRatio(surface1, target));
}
const base = closestToForeground([borderAccent, surface1, surface2], foreground);
return stepContrast(base, foreground, BORDER_FOCUS_STEP);
}
+3 -116
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { PluginThemeContribution } from "@getpaseo/plugin";
import { buildPluginTheme } from "@/plugins/themes";
import { contrastRatio, mixHexColors, paintHexOver } from "@/utils/color";
import { contrastRatio, mixHexColors } from "@/utils/color";
import { darkPureBlackTheme, THEME_OPTIONS, type Theme } from "./theme";
// Palettes of the plugin themes users run into: Catppuccin (the e2e fixture) and
@@ -70,80 +70,11 @@ const SOLARIZED_DARK: PluginThemeContribution = {
},
};
const TRANSLUCENT_DARK: PluginThemeContribution = {
id: "translucent-dark",
name: "Translucent Dark",
appearance: "dark",
colors: {
background: "#101010",
foreground: "#fafafa",
raised: "#161616",
control: "#222222",
border: "#ffffff20",
mutedForeground: "#a1a1aa",
ring: "#52525b",
},
};
const TRANSLUCENT_LIGHT: PluginThemeContribution = {
id: "translucent-light",
name: "Translucent Light",
appearance: "light",
colors: {
background: "#ffffff",
foreground: "#1a1a1e",
raised: "#fafafa",
control: "#f4f4f5",
border: "#00000018",
mutedForeground: "#71717a",
ring: "#a1a1aa",
},
};
const TRANSLUCENT_HIGH_CONTRAST_CONTROL: PluginThemeContribution = {
id: "translucent-high-contrast-control",
name: "Translucent High-Contrast Control",
appearance: "dark",
colors: {
background: "#101010",
foreground: "#fafafa",
raised: "#161616",
control: "#444444",
border: "#ffffff20",
mutedForeground: "#a1a1aa",
ring: "#52525b",
},
};
const OPAQUE_HIGH_CONTRAST_CONTROL: PluginThemeContribution = {
id: "opaque-high-contrast-control",
name: "Opaque High-Contrast Control",
appearance: "dark",
colors: {
background: "#101010",
foreground: "#fafafa",
raised: "#161616",
control: "#444444",
border: "#333333",
mutedForeground: "#a1a1aa",
ring: "#52525b",
},
};
const themes: Array<{ name: string; theme: Theme }> = [
...THEME_OPTIONS.flatMap((option) =>
"theme" in option ? [{ name: option.name, theme: option.theme as Theme }] : [],
),
...[
LATTE,
MOCHA,
SOLARIZED_LIGHT,
SOLARIZED_DARK,
TRANSLUCENT_DARK,
TRANSLUCENT_LIGHT,
TRANSLUCENT_HIGH_CONTRAST_CONTROL,
OPAQUE_HIGH_CONTRAST_CONTROL,
].map((contribution) => ({
...[LATTE, MOCHA, SOLARIZED_LIGHT, SOLARIZED_DARK].map((contribution) => ({
name: `plugin ${contribution.name}`,
theme: buildPluginTheme(contribution),
})),
@@ -168,14 +99,9 @@ const TREE_GUIDE_FLOOR = 1.18;
// The bright hues are dim on a cream or white background by design; the floor only has to catch a
// color that disappears.
const TERMINAL_COLOR_FLOOR = 1.5;
// Focus borders step 1.30x from `borderAccent` toward `foreground`; 8-bit rounding lands around 1.29x.
const BORDER_FOCUS_STEP_FLOOR = 1.28;
const BORDER_FOCUS_BAND_MIN = 1.5;
const BORDER_FOCUS_BAND_MAX = 1.95;
/** The color a translucent `rgba()` or hex token shows once painted over `surface`. */
/** The color a translucent `rgba()` token shows once painted over `surface`. */
function paintedOver(surface: string, token: string): string {
if (token.startsWith("#")) return paintHexOver(surface, token);
const [r, g, b, alpha] = (token.match(/[\d.]+/g) ?? []).map(Number);
const ink = `#${[r, g, b].map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
return mixHexColors(surface, ink, alpha);
@@ -258,33 +184,6 @@ describe.each(themes)("$name", ({ theme }) => {
expect(contrastRatio(colors.surface3, colors.surface4)).toBeGreaterThanOrEqual(1.15);
});
it("steps focus borders cleanly above resting borders and field surfaces", () => {
const fieldSurface = paintedOver(colors.surface0, colors.surface1);
const controlSurface = paintedOver(colors.surface0, colors.surface2);
const paintedBorderAccent = paintedOver(fieldSurface, colors.borderAccent);
const paintedBorderOnControl = paintedOver(controlSurface, colors.border);
const paintedFocusOnField = paintedOver(fieldSurface, colors.borderFocus);
const paintedFocusOnControl = paintedOver(controlSurface, colors.borderFocus);
const paintedFocusOnPage = paintedOver(colors.surface0, colors.borderFocus);
expect(contrastRatio(paintedBorderAccent, paintedFocusOnField)).toBeGreaterThanOrEqual(
BORDER_FOCUS_STEP_FLOOR,
);
expect(contrastRatio(colors.surface0, paintedFocusOnPage)).toBeGreaterThan(
contrastRatio(colors.surface0, paintedOver(colors.surface0, colors.borderAccent)),
);
expect(contrastRatio(colors.surface0, paintedFocusOnPage)).toBeGreaterThan(
contrastRatio(colors.surface0, paintedOver(colors.surface0, colors.border)),
);
expect(contrastRatio(controlSurface, paintedFocusOnControl)).toBeGreaterThanOrEqual(
BORDER_FOCUS_STEP_FLOOR,
);
expect(contrastRatio(controlSurface, paintedFocusOnControl)).toBeGreaterThan(
contrastRatio(controlSurface, paintedBorderOnControl),
);
expect(contrastRatio(fieldSurface, paintedFocusOnField)).toBeLessThanOrEqual(2.5);
});
it("keeps terminal text readable on the terminal background", () => {
const terminal = colors.terminal;
const { background, ...palette } = terminal;
@@ -376,16 +275,4 @@ describe("built-in themes", () => {
expect(contrastRatio(pureBlack.borderAccent, pureBlack.surface3)).toBeGreaterThanOrEqual(1.15);
expect(contrastRatio(pureBlack.surface3, pureBlack.surface4)).toBeGreaterThanOrEqual(1.35);
});
it.each(themes.filter(({ name }) => !name.startsWith("plugin ")))(
"$name holds borderFocus inside the calm contrast band",
({ theme }) => {
const vsPage = contrastRatio(theme.colors.surface0, theme.colors.borderFocus);
expect(vsPage).toBeGreaterThanOrEqual(BORDER_FOCUS_BAND_MIN);
expect(vsPage).toBeLessThanOrEqual(BORDER_FOCUS_BAND_MAX);
expect(contrastRatio(theme.colors.surface1, theme.colors.borderFocus)).toBeGreaterThanOrEqual(
1.45,
);
},
);
});
+1 -23
View File
@@ -1,13 +1,7 @@
import { Platform, type ViewStyle } from "react-native";
import { isWeb } from "@/constants/platform";
import { paintHexOver } from "@/utils/color";
import { darkHighlightColors, lightHighlightColors } from "@getpaseo/highlight";
import {
deriveBorderFocus,
derivePageSurfaceStates,
deriveSurfaceStates,
deriveTreeGuide,
} from "./derive-colors";
import { derivePageSurfaceStates, deriveSurfaceStates, deriveTreeGuide } from "./derive-colors";
export const baseColors = {
// Base colors
@@ -293,8 +287,6 @@ export function buildLightSemanticColors(tint: LightThemeConfig) {
foregroundSidebarSelected: tint.foregroundSidebarSelected ?? tint.foregroundExtraMuted,
treeGuide: deriveTreeGuide(tint.surfaceSidebar, tint.foreground, "light"),
surfaceWorkspace: tint.surface0,
surfaceSegmentThumb: tint.surface0,
borderSegmentThumb: "transparent",
interactionHighlight: "rgba(0, 0, 0, 0.06)",
foreground: tint.foreground,
@@ -303,12 +295,6 @@ export function buildLightSemanticColors(tint: LightThemeConfig) {
border: tint.border,
borderAccent: tint.borderAccent,
borderFocus: deriveBorderFocus(
tint.borderAccent,
tint.foreground,
paintHexOver(tint.surface0, tint.surface1),
paintHexOver(tint.surface0, tint.surface2),
),
accent: tint.accent,
accentBright: tint.accentBright,
@@ -439,8 +425,6 @@ export function buildDarkSemanticColors(tint: DarkThemeConfig) {
foregroundSidebarSelected: tint.foregroundSidebarSelected ?? tint.foregroundExtraMuted,
treeGuide: deriveTreeGuide(tint.surfaceSidebar, foreground, "dark"),
surfaceWorkspace: tint.surface1,
surfaceSegmentThumb: tint.surface3,
borderSegmentThumb: "rgba(255, 255, 255, 0.08)",
interactionHighlight: "rgba(255, 255, 255, 0.08)",
foreground,
@@ -449,12 +433,6 @@ export function buildDarkSemanticColors(tint: DarkThemeConfig) {
border: tint.border,
borderAccent: tint.borderAccent,
borderFocus: deriveBorderFocus(
tint.borderAccent,
foreground,
paintHexOver(tint.surface0, tint.surface1),
paintHexOver(tint.surface0, tint.surface2),
),
accent: tint.accent,
accentBright: tint.accentBright,
-14
View File
@@ -3,9 +3,7 @@ import {
contrastRatio,
desaturateHexColor,
hexColorWithAlpha,
isTranslucentHexColor,
mixHexColors,
paintHexOver,
parseHexColor,
stepContrast,
} from "./color";
@@ -120,15 +118,3 @@ describe("mixHexColors", () => {
expect(mixHexColors("#000000", "#ffffff", 0.5)).toBe("#808080");
});
});
describe("paintHexOver", () => {
it("leaves opaque hexes unchanged and composites translucent hexes over the surface", () => {
expect(isTranslucentHexColor("#2f3534")).toBe(false);
expect(isTranslucentHexColor("#45475aff")).toBe(false);
expect(isTranslucentHexColor("#ffffff20")).toBe(true);
expect(paintHexOver("#161616", "#2f3534")).toBe("#2f3534");
expect(paintHexOver("#161616", "#45475aff")).toBe("#45475aff");
expect(paintHexOver("#161616", "#ffffff20")).toBe("#333333");
expect(paintHexOver("#000000", "#fff8")).toBe("#888888");
});
});
-22
View File
@@ -184,25 +184,3 @@ export function mixHexColors(hex: string, toward: string, amount: number): strin
);
return `#${channels.join("")}`;
}
function hexAlpha(hex: string): number {
if (/^#[0-9a-fA-F]{4}$/.test(hex)) {
return Number.parseInt(`${hex[4]}${hex[4]}`, 16) / 255;
}
if (/^#[0-9a-fA-F]{8}$/.test(hex)) {
return Number.parseInt(hex.slice(7, 9), 16) / 255;
}
return 1;
}
/** Whether a hex colour carries a non-opaque alpha channel (`< 1`). */
export function isTranslucentHexColor(hex: string): boolean {
return hexAlpha(hex) < 1;
}
/** Paints a hex colour with optional alpha over an opaque `surface`. */
export function paintHexOver(surface: string, hex: string): string {
const alpha = hexAlpha(hex);
if (alpha >= 1) return hex;
return mixHexColors(surface, hex, alpha);
}
@@ -49,7 +49,6 @@ export const Folder = StubIcon;
export const FolderOpen = StubIcon;
export const FolderPlus = StubIcon;
export const FolderTree = StubIcon;
export const Form = StubIcon;
export const Gift = StubIcon;
export const GitBranch = StubIcon;
export const GitCommitHorizontal = StubIcon;
-3
View File
@@ -227,9 +227,6 @@ export default defineConfig({
// Loaded by the reanimated-web-style-helpers plugin, which the dependency scan does not see.
"react-native-web/dist/exports/StyleSheet/compiler/createReactDOMStyle",
"react-native-web/dist/exports/StyleSheet/preprocess",
// Dynamically imported by the excluded react-native-enriched-markdown package;
// pre-optimizing avoids mid-suite Vite re-optimization invalidating browser imports.
"katex",
],
exclude: [
"react-native-enriched-markdown",
@@ -338,3 +338,23 @@ it("says when a failure that waits on its retry time is retried, in list and ins
"Reason: Rate limited by Claude. Retrying at 2026-10-09T12:11:00.000Z.",
);
});
it("inspects and refreshes a target-only report absent from the host list", async () => {
const entry = reports[0]!;
const queries: Array<{ reportIds?: string[]; forceRefresh?: boolean } | undefined> = [];
const connect = async () => ({
getLastServerInfoMessage: () => ({ features: { usageSources: true } }),
listUsageReports: async (query?: (typeof queries)[number]) => {
queries.push(query);
return { requestId: "request", reports: query?.reportIds ? [entry] : [] };
},
close: async () => {},
});
const result = await runUsageCommand(
{ ...options, refresh: true },
{ kind: "inspect", id: entry.id },
connect,
);
expect(result.data).toEqual(entry);
expect(queries).toEqual([undefined, { reportIds: [entry.id], forceRefresh: true }]);
});
+2 -2
View File
@@ -47,10 +47,10 @@ export async function runUsageCommand(
// Report-ID queries only select known accounts. Discover before selecting, including on cold hosts.
const { reports } = await client.listUsageReports();
let entry = reports.find((report) => report.id === selection.id);
if (entry && options.refresh) {
if (!entry || options.refresh) {
const refreshed = await client.listUsageReports({
reportIds: [selection.id],
forceRefresh: true,
forceRefresh: options.refresh,
});
entry = refreshed.reports.find((report) => report.id === selection.id);
}
@@ -94,12 +94,6 @@ if (consumerConfig.containsKey("enableMath")) {
} else {
enableMath = true
}
if (System.getenv("PASEO_FDROID_BUILD") == "1") {
if (enableMath) {
logger.lifecycle("[ReactNativeEnrichedMarkdown] F-Droid build (PASEO_FDROID_BUILD=1); disabling native RaTeX math.")
}
enableMath = false
}
// Default grammar set derived from the single source of truth,
// vendor/grammar-versions.json (every grammar with default:true), so the compiled
@@ -931,7 +931,7 @@ object MeasurementStore {
val method = mathMeasureHelperClass.getMethod("measure", Context::class.java, List::class.java)
@Suppress("UNCHECKED_CAST")
method.invoke(null, context, requests) as List<MathMetrics>
} catch (_: Throwable) {
} catch (_: Exception) {
requests.map { estimateMathFallback(it) }
}
}
@@ -152,7 +152,7 @@ class RendererFactory(
// genuinely mid-line display math (e.g. `a $$x$$ b`); render it inline
// rather than dropping it via the TextRenderer fallback.
put(MarkdownASTNode.NodeType.LatexMathDisplay, mathInlineRenderer)
} catch (_: Throwable) {
} catch (_: Exception) {
// math not available
}
}
@@ -154,7 +154,7 @@ object SegmentViewCreators {
private val cachedMathContainerClass: Class<*>? by lazy {
try {
Class.forName("com.swmansion.enriched.markdown.segments.MathContainerView")
} catch (_: Throwable) {
} catch (_: Exception) {
null
}
}
@@ -189,7 +189,7 @@ object SegmentViewCreators {
}
resolvedClass.getMethod("applyLatex", String::class.java).invoke(view, segment.latex)
view
} catch (e: Throwable) {
} catch (e: Exception) {
Log.e(TAG, "Failed to create math view", e)
View(config.context)
}
@@ -59,7 +59,7 @@ fun Spannable.replaceMathSpansWithPlaceholders(context: Context) {
}
} catch (_: ClassNotFoundException) {
// Expected if the module isn't linked; silent return
} catch (e: Throwable) {
} catch (e: Exception) {
Log.e("MathSpan", "Failed to replace math spans", e)
}
}
@@ -2,7 +2,6 @@ package com.swmansion.enriched.markdown.renderer
import android.content.Context
import android.text.SpannableStringBuilder
import android.util.Log
import com.swmansion.enriched.markdown.parser.MarkdownASTNode
import com.swmansion.enriched.markdown.spans.MathInlineSpan
import com.swmansion.enriched.markdown.utils.text.span.SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE
@@ -15,15 +14,11 @@ class MathInlineRenderer(
override fun render(
node: MarkdownASTNode,
builder: SpannableStringBuilder,
onLinkPress: ((String, String) -> Unit)?,
onLinkPress: ((String) -> Unit)?,
onLinkLongPress: ((String) -> Unit)?,
factory: RendererFactory,
) {
try {
RaTeXFontLoader.ensureLoaded(context)
} catch (e: Throwable) {
Log.w(TAG, "Failed to load RaTeX fonts; math will fall back to raw LaTeX", e)
}
RaTeXFontLoader.ensureLoaded(context)
val latex = extractLatex(node)
if (latex.isEmpty()) return
@@ -57,8 +52,4 @@ class MathInlineRenderer(
}
}
}
private companion object {
const val TAG = "MathInlineRenderer"
}
}
@@ -59,11 +59,7 @@ class MathContainerView(
val paddingPx = mathStyle.padding.toInt()
try {
RaTeXFontLoader.ensureLoaded(context)
} catch (e: Throwable) {
Log.w(TAG, "Failed to load RaTeX fonts; math will fall back to raw LaTeX", e)
}
RaTeXFontLoader.ensureLoaded(context)
val mathLayoutParams =
FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply {
@@ -101,7 +97,7 @@ class MathContainerView(
val displayList = RaTeXEngine.parseBlocking(latex, displayMode = true, color = mathStyle.color)
mathView.renderer = RaTeXRenderer(displayList, mathStyle.fontSize) { RaTeXFontLoader.getTypeface(it) }
mathView.fallbackText = null
} catch (e: Throwable) {
} catch (e: Exception) {
Log.e(TAG, "Failed to render LaTeX", e)
mathView.renderer = null
mathView.fallbackText = "\$\$" + latex + "\$\$"
@@ -31,7 +31,6 @@ class MathInlineSpan(
if (renderFailed) return
try {
RaTeXFontLoader.ensureLoaded(context)
val displayList = RaTeXEngine.parseBlocking(latex, displayMode = false, color = textColor)
val renderer = RaTeXRenderer(displayList, fontSize) { RaTeXFontLoader.getTypeface(it) }
@@ -48,7 +47,7 @@ class MathInlineSpan(
renderer.draw(Canvas(bitmap))
cachedBitmap = bitmap
} catch (e: Throwable) {
} catch (e: Exception) {
renderFailed = true
fallbackText = "\$" + latex + "\$"
onLatexError?.report(latex, e.message, false)
@@ -14,12 +14,7 @@ object MathMeasureHelper {
): List<MathMetrics> {
if (requests.isEmpty()) return emptyList()
try {
RaTeXFontLoader.ensureLoaded(context)
} catch (e: Throwable) {
Log.w(TAG, "Failed to load RaTeX fonts; using fallback metrics", e)
return requests.map { estimateFallback(it) }
}
RaTeXFontLoader.ensureLoaded(context)
return requests.map { request ->
runCatching { measureSingle(context, request) }.getOrElse { estimateFallback(request) }
@@ -59,6 +54,4 @@ object MathMeasureHelper {
descent = h * 0.3f,
)
}
private const val TAG = "MathMeasureHelper"
}
@@ -1,88 +0,0 @@
package com.swmansion.enriched.markdown
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.view.View
import com.swmansion.enriched.markdown.parser.MarkdownASTNode
import com.swmansion.enriched.markdown.segments.MathContainerView
import com.swmansion.enriched.markdown.spans.MathInlinePlaceholderSpan
import com.swmansion.enriched.markdown.spans.MathInlineSpan
import com.swmansion.enriched.markdown.spans.MathMeasureHelper
import com.swmansion.enriched.markdown.spans.MathMeasureRequest
import com.swmansion.enriched.markdown.spans.MathRenderMode
import com.swmansion.enriched.markdown.test.MarkdownRenderTestSupport.render
import com.swmansion.enriched.markdown.test.MarkdownRenderTestSupport.styleConfig
import com.swmansion.enriched.markdown.test.TestAstFactory.latexMathDisplay
import com.swmansion.enriched.markdown.test.TestAstFactory.latexMathInline
import com.swmansion.enriched.markdown.test.TestAstFactory.paragraph
import com.swmansion.enriched.markdown.utils.text.extensions.replaceMathSpansWithPlaceholders
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
@RunWith(RobolectricTestRunner::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(manifest = Config.NONE, sdk = [34])
class MathRenderingFallbackTest {
private val context get() = RuntimeEnvironment.getApplication()
@Test fun inlineMathDegradesToRawLatexWhenNativeRatexIsUnavailable() {
val style = styleConfig()
val spannable = render(style, paragraph(latexMathInline("E = mc^2")))
val spans = spannable.getSpans(0, spannable.length, MathInlineSpan::class.java)
assertEquals(1, spans.size)
val span = spans.single()
val paint = TextPaint().apply { textSize = 16f }
val fm = Paint.FontMetricsInt()
val width = span.getSize(paint, spannable, 0, spannable.length, fm)
assertTrue("Fallback inline math width should be positive", width > 0)
assertTrue("Fallback inline math font metrics should span vertically", fm.descent - fm.ascent > 0)
val bitmap = Bitmap.createBitmap(width.coerceAtLeast(1), 64, Bitmap.Config.ARGB_8888)
span.draw(Canvas(bitmap), spannable, 0, spannable.length, 0f, 0, 32, 64, paint)
}
@Test fun displayMathContainerDegradesToRawLatexWhenNativeRatexIsUnavailable() {
val style = styleConfig()
val view = MathContainerView(context, style)
view.applyLatex("\\frac{a}{b}")
val widthSpec = View.MeasureSpec.makeMeasureSpec(300, View.MeasureSpec.AT_MOST)
val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
view.measure(widthSpec, heightSpec)
assertTrue("Fallback display math width should be positive", view.measuredWidth > 0)
assertTrue("Fallback display math height should be positive", view.measuredHeight > 0)
view.layout(0, 0, view.measuredWidth, view.measuredHeight)
val bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888)
view.draw(Canvas(bitmap))
}
@Test fun mathMeasureHelperAndPlaceholdersDegradeCleanlyWhenNativeRatexIsUnavailable() {
val request = MathMeasureRequest(fontSize = 16f, latex = "\\sum_{i=1}^n i", mode = MathRenderMode.Display)
val metrics = MathMeasureHelper.measure(context, listOf(request))
assertEquals(1, metrics.size)
assertTrue(metrics[0].width > 0)
assertTrue(metrics[0].ascent > 0f)
assertTrue(metrics[0].descent > 0f)
val style = styleConfig()
val height = MathContainerView.measureMathHeight("\\sum_{i=1}^n i", style.mathStyle, context)
assertTrue(height > 0f)
val rendered = render(style, paragraph(latexMathInline("x^2"), latexMathDisplay("y^2")))
val builder = SpannableStringBuilder(rendered)
builder.replaceMathSpansWithPlaceholders(context)
val placeholders = builder.getSpans(0, builder.length, MathInlinePlaceholderSpan::class.java)
assertEquals(2, placeholders.size)
}
}
@@ -37,26 +37,6 @@ object MarkdownRenderTestSupport {
val style = JavaOnlyMap()
listOf("paragraph", "strong", "em", "strikethrough", "code", "superscript", "subscript", "highlight")
.forEach { style.putMap(it, textElement()) }
style.putMap(
"math",
JavaOnlyMap.of(
"fontSize",
16.0,
"color",
Color.BLACK,
"backgroundColor",
Color.TRANSPARENT,
"padding",
8.0,
"marginTop",
0.0,
"marginBottom",
0.0,
"textAlign",
"center",
),
)
style.putMap("inlineMath", JavaOnlyMap.of("color", Color.BLACK))
style.putMap("link", textElement().apply { putString("fontFamily", "serif") })
style.putArray(
"linkVariants",
@@ -8,10 +8,6 @@ object TestAstFactory {
fun text(content: String): MarkdownASTNode = MarkdownASTNode(NodeType.Text, content = content)
fun latexMathInline(latex: String): MarkdownASTNode = MarkdownASTNode(NodeType.LatexMathInline, content = latex)
fun latexMathDisplay(latex: String): MarkdownASTNode = MarkdownASTNode(NodeType.LatexMathDisplay, content = latex)
/** An ordered list; [start] is the first number, as md4c reports it. */
fun orderedList(
vararg items: MarkdownASTNode,
@@ -6,10 +6,7 @@
"ref": "v0.26.3",
"tarball": "https://github.com/tree-sitter/tree-sitter/archive/refs/tags/v0.26.3.tar.gz",
"sha256": "7f4a7cf0a2cd217444063fe2a4d800bc9d21ed609badc2ac20c0841d67166550",
"abi": {
"version": 15,
"minCompatible": 13
}
"abi": { "version": 15, "minCompatible": 13 }
},
"grammars": {
"json": {
@@ -17,24 +14,21 @@
"version": "0.24.8",
"scanner": false,
"default": true,
"size": "27 KB",
"sha256": "39e96d1e4231d200562ebd69105151cd43f58dda4b18a0e9a62fe2991da35b9c"
"size": "27 KB"
},
"html": {
"package": "tree-sitter-html",
"version": "0.23.2",
"scanner": true,
"default": true,
"size": "76 KB",
"sha256": "6b024fc38fce2b4807d0ac35023487da682a15cd986ba2ee9d6c25feff9392ed"
"size": "76 KB"
},
"css": {
"package": "tree-sitter-css",
"version": "0.23.2",
"scanner": true,
"default": true,
"size": "0.5 MB",
"sha256": "7dd088805e0f206d6b15d13ce717f9be89b9ff023efcc7970ca5a9064aa45aba"
"size": "0.5 MB"
},
"markdown": {
"package": "@tree-sitter-grammars/tree-sitter-markdown",
@@ -43,141 +37,115 @@
"scanner": true,
"default": true,
"size": "1.5 MB",
"$comment": "Multi-grammar package; the block grammar (tree-sitter-markdown/) is vendored. The inline sub-grammar is not linked.",
"sha256": "f582346e65479e1d6d025e9b785421f623eb549390c550899005fd6f7f37d739"
"$comment": "Multi-grammar package; the block grammar (tree-sitter-markdown/) is vendored. The inline sub-grammar is not linked."
},
"yaml": {
"package": "@tree-sitter-grammars/tree-sitter-yaml",
"version": "0.7.1",
"scanner": true,
"default": true,
"size": "1 MB",
"sha256": "30dbdc539dcfa905252a0d1772270d457d58ceddfa3d6a4fac564f02837241ba"
"size": "1 MB"
},
"go": {
"package": "tree-sitter-go",
"version": "0.23.4",
"scanner": false,
"default": true,
"size": "1 MB",
"sha256": "8779d20d322b4319ad8c833ea72ecb6d109cf1fec8979bdcdb5315a2e511dd2c"
"size": "1 MB"
},
"java": {
"package": "tree-sitter-java",
"version": "0.23.5",
"scanner": false,
"default": true,
"size": "2.5 MB",
"sha256": "6b6c1b62605f9d8bb80efd2ebe5951a87b182faafa3eeb67c460a667818551b6"
"size": "2.5 MB"
},
"javascript": {
"package": "tree-sitter-javascript",
"version": "0.23.1",
"scanner": true,
"default": true,
"size": "2.8 MB",
"sha256": "90e80b25a67517a4daf6ad751557bee21efbda7b7a5a554897933245d1734398"
"size": "2.8 MB"
},
"python": {
"package": "tree-sitter-python",
"version": "0.23.6",
"scanner": true,
"default": true,
"size": "3.4 MB",
"sha256": "aab5b860d93dbf84b37fed532f7dacc0468ede5387d0c74911d68f964287662a"
"size": "3.4 MB"
},
"c": {
"package": "tree-sitter-c",
"version": "0.23.5",
"scanner": false,
"default": true,
"size": "3.8 MB",
"sha256": "20edb0872863769947f5c10839ca5420909a991bc79eb55666b74f0c11305c89"
"size": "3.8 MB"
},
"rust": {
"package": "tree-sitter-rust",
"version": "0.23.2",
"scanner": true,
"default": true,
"size": "6.3 MB",
"sha256": "085f2e9cedb916c466b53180d6e4287148e309593e61ea92e2c4b01904d193bb"
"size": "6.3 MB"
},
"bash": {
"package": "tree-sitter-bash",
"version": "0.23.3",
"scanner": true,
"default": true,
"size": "9.7 MB",
"sha256": "10f4d67f56e07bc6cc34c49afb34e232269c1e0a19933880dfdb5dd738a8fc7d"
"size": "9.7 MB"
},
"typescript": {
"package": "tree-sitter-typescript",
"version": "0.23.2",
"subPath": "typescript",
"scanner": true,
"sharedSrc": [
"../../common/scanner.h"
],
"inherits": [
"javascript"
],
"sharedSrc": ["../../common/scanner.h"],
"inherits": ["javascript"],
"default": true,
"size": "17 MB",
"sha256": "0fdf63c35930a75885145d75ee63cb879da2d49db9bfe454bd8e60b08ba778a1"
"size": "17 MB"
},
"tsx": {
"package": "tree-sitter-typescript",
"version": "0.23.2",
"subPath": "tsx",
"scanner": true,
"sharedSrc": [
"../../common/scanner.h"
],
"inherits": [
"javascript"
],
"sharedSrc": ["../../common/scanner.h"],
"inherits": ["javascript"],
"default": true,
"size": "17 MB",
"sha256": "0fdf63c35930a75885145d75ee63cb879da2d49db9bfe454bd8e60b08ba778a1"
"size": "17 MB"
},
"cpp": {
"package": "tree-sitter-cpp",
"version": "0.23.4",
"scanner": true,
"inherits": [
"c"
],
"inherits": ["c"],
"default": false,
"size": "17 MB",
"sha256": "615d152f70e7a6bed8f15a93c3c0c264c40dc71c1b6a1445646fff9439e776bc"
"size": "17 MB"
},
"swift": {
"package": "tree-sitter-swift",
"version": "0.7.0",
"scanner": true,
"default": false,
"size": "18 MB",
"sha256": "e0a20f341d10c0a8338c151b72abead83400945c36386def0785c6c189116e39"
"size": "18 MB"
},
"php": {
"package": "tree-sitter-php",
"version": "0.24.2",
"subPath": "php",
"scanner": true,
"sharedSrc": [
"../../common/scanner.h"
],
"sharedSrc": ["../../common/scanner.h"],
"default": false,
"size": "14 MB",
"sha256": "fdd22530d3845540ba74a1199d3f67204a608c99994bb423645d3f0cfdaead94"
"size": "14 MB"
},
"ruby": {
"package": "tree-sitter-ruby",
"version": "0.23.1",
"scanner": true,
"default": false,
"size": "15 MB",
"sha256": "1f0f0c100e31ddf650962ebb1f1fb8420bdbabccd49582f6e731ea7478db639d"
"size": "15 MB"
},
"c-sharp": {
"package": "tree-sitter-c-sharp",
@@ -185,8 +153,7 @@
"scanner": true,
"function": "tree_sitter_c_sharp",
"default": false,
"size": "29 MB",
"sha256": "19c59068a19ff74b688c0985a19382503fc16b27f2b44b392aed908106700805"
"size": "29 MB"
}
}
}
@@ -7,10 +7,6 @@ export function isMarkdownParserReady() {
export function preloadMarkdownParser() {
return Promise.resolve();
}
export function getLoadedKaTeX() {
return null;
}
export function registerKaTeXStyleLoader(_loader) {}
export { DEFAULT_ACCESSIBILITY_LABELS, resolveAccessibilityLabels } from "./accessibilityLabelDefaults.js";
export { EnrichedMarkdownTextInput } from "./EnrichedMarkdownTextInput.js";
//# sourceMappingURL=index.js.map
@@ -2,5 +2,4 @@
export { EnrichedMarkdownText, default } from "./web/EnrichedMarkdownText.js";
export { isMarkdownParserReady, preloadMarkdownParser } from "./web/parseMarkdown.js";
export { getLoadedKaTeX, registerKaTeXStyleLoader } from "./web/katex.js";
//# sourceMappingURL=index.web.js.map
@@ -6,8 +6,8 @@ import { zeroTrailingMargins, parseErrorFallbackStyle, buildStyles } from "./sty
import { parseMarkdown, parseMarkdownSync } from "./parseMarkdown.js";
import { recognizeTextLinks } from "./recognizeTextLinks.js";
import { RenderNode } from "./renderers/index.js";
import { hasMathNode, indexTaskItems, markInlineImages } from "./utils.js";
import { getLoadedKaTeX, loadKaTeX } from "./katex.js";
import { indexTaskItems, markInlineImages } from "./utils.js";
import { loadKaTeX } from "./katex.js";
import { ENRM_TEXT_CLASS, ENRM_SELECTION_BG_VAR } from "./globalStyles.js";
import { filterNativeOnlyProps } from "./nativeProps.js";
import { jsx as _jsx } from "react/jsx-runtime";
@@ -33,7 +33,7 @@ export const EnrichedMarkdownText = ({
}) => {
const normalizedStyle = useMemo(() => normalizeMarkdownStyle(markdownStyle), [markdownStyle]);
const [parsed, setParsed] = useState(null);
const [katex, setKatex] = useState(() => (md4cFlags.latexMath ?? true) ? getLoadedKaTeX() : null);
const [katex, setKatex] = useState(null);
const [parseError, setParseError] = useState(false);
const {
underline = false,
@@ -45,7 +45,6 @@ export const EnrichedMarkdownText = ({
preserveBlankLines = false,
admonitions = true
} = md4cFlags;
const activeKatex = latexMath ? katex ?? getLoadedKaTeX() : null;
// A regex literal in JSX is a new object every render; re-parse only when its text changes.
const linkRecognitionRef = useRef(linkRecognition);
@@ -84,22 +83,10 @@ export const EnrichedMarkdownText = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [markdown, underline, latexMath, superscript, subscript, highlight, hardSoftBreaks, preserveBlankLines, admonitions, textLinkKey, inlineCodeLinkKey, parsed]);
useEffect(() => {
if (immediate) {
if (!latexMath || activeKatex || !immediate.ast || !hasMathNode(immediate.ast)) {
return;
}
let cancelled = false;
loadKaTeX().then(katexInstance => {
if (!cancelled && katexInstance) {
setKatex(katexInstance);
}
});
return () => {
cancelled = true;
};
}
if (immediate && (!latexMath || katex)) return;
let cancelled = false;
parseMarkdown(markdown, {
const katexPromise = latexMath ? loadKaTeX() : Promise.resolve(null);
Promise.all([parseMarkdown(markdown, {
underline,
latexMath,
superscript,
@@ -108,21 +95,17 @@ export const EnrichedMarkdownText = ({
hardSoftBreaks,
preserveBlankLines,
admonitions
}).then(async result => {
if (cancelled) return;
indexTaskItems(result);
markInlineImages(result);
const needsKatex = latexMath && hasMathNode(result);
const katexInstance = needsKatex ? getLoadedKaTeX() ?? (await loadKaTeX()) : getLoadedKaTeX();
if (cancelled) return;
setParseError(false);
if (katexInstance) {
}), katexPromise]).then(([result, katexInstance]) => {
if (!cancelled) {
indexTaskItems(result);
markInlineImages(result);
setParseError(false);
setKatex(katexInstance);
setParsed({
markdown,
ast: recognizeTextLinks(result, linkRecognitionRef.current?.text, linkRecognitionRef.current?.inlineCode)
});
}
setParsed({
markdown,
ast: recognizeTextLinks(result, linkRecognitionRef.current?.text, linkRecognitionRef.current?.inlineCode)
});
}).catch(error => {
if (!cancelled) {
if (__DEV__) {
@@ -136,7 +119,7 @@ export const EnrichedMarkdownText = ({
return () => {
cancelled = true;
};
}, [markdown, underline, latexMath, superscript, subscript, highlight, hardSoftBreaks, preserveBlankLines, admonitions, textLinkKey, inlineCodeLinkKey, immediate, activeKatex]);
}, [markdown, underline, latexMath, superscript, subscript, highlight, hardSoftBreaks, preserveBlankLines, admonitions, textLinkKey, inlineCodeLinkKey, immediate, katex]);
const callbacks = useMemo(() => ({
onLinkPress,
onLinkLongPress,
@@ -145,10 +128,10 @@ export const EnrichedMarkdownText = ({
onCodeBlockPress
}), [onLinkPress, onLinkLongPress, onImagePress, onTaskListItemPress, onCodeBlockPress]);
const capabilities = useMemo(() => ({
katex: activeKatex,
katex,
enableTaskListItemToggle,
renderers
}), [activeKatex, enableTaskListItemToggle, renderers]);
}), [katex, enableTaskListItemToggle, renderers]);
const lastChildStyle = useMemo(() => allowTrailingMargin ? normalizedStyle : zeroTrailingMargins(normalizedStyle), [normalizedStyle, allowTrailingMargin]);
const styles = useMemo(() => buildStyles(normalizedStyle), [normalizedStyle]);
const lastChildStyles = useMemo(() => buildStyles(lastChildStyle), [lastChildStyle]);
@@ -197,4 +180,4 @@ export const EnrichedMarkdownText = ({
});
};
export default EnrichedMarkdownText;
//# sourceMappingURL=EnrichedMarkdownText.js.map
//# sourceMappingURL=EnrichedMarkdownText.js.map
@@ -1,69 +1,22 @@
"use strict";
let loadedKatex = null;
let katexLoadPromise = null;
let styleLoader = null;
let styleLoadPromise = null;
let stylesReady = true;
function ensureKaTeXStyles() {
if (!styleLoader) {
stylesReady = true;
return Promise.resolve();
}
if (!styleLoadPromise) {
styleLoadPromise = Promise.resolve()
.then(() => styleLoader())
.then(() => {
stylesReady = true;
})
.catch((error) => {
styleLoadPromise = null;
stylesReady = false;
throw error;
});
}
return styleLoadPromise;
}
/** Synchronously returns the cached KaTeX instance once loaded and styled, or null. */
export function getLoadedKaTeX() {
return loadedKatex && stylesReady ? loadedKatex : null;
}
/** Registers a lazy stylesheet loader invoked alongside KaTeX loading. */
export function registerKaTeXStyleLoader(loader) {
styleLoader = loader;
styleLoadPromise = null;
katexLoadPromise = null;
stylesReady = false;
}
/** Lazily loads KaTeX and any registered stylesheet. Resolves to null if unavailable. */
/** Lazily loads KaTeX. Resolves to null if not installed. */
export function loadKaTeX() {
if (loadedKatex && stylesReady) {
return Promise.resolve(loadedKatex);
}
if (!katexLoadPromise) {
katexLoadPromise = Promise.all([
loadedKatex ? Promise.resolve({ default: loadedKatex }) : import('katex'),
ensureKaTeXStyles(),
])
.then(([mod]) => {
const candidate = mod?.default ?? mod;
if (typeof candidate?.renderToString === 'function') {
loadedKatex = candidate;
return candidate;
}
katexLoadPromise = null;
return null;
})
.catch(() => {
// katex or its stylesheet failed to load — fall back to raw LaTeX and allow retry
katexLoadPromise = null;
return null;
});
let instance = null;
try {
const mod = require('katex');
const candidate = mod?.default ?? mod;
if (typeof candidate?.renderToString === 'function') {
instance = candidate;
}
} catch {
// katex not installed — math rendering will be skipped
}
katexLoadPromise = Promise.resolve(instance);
}
return katexLoadPromise;
}
//# sourceMappingURL=katex.js.map
//# sourceMappingURL=katex.js.map
@@ -2,43 +2,6 @@
import { useMemo } from 'react';
import { jsx as _jsx } from "react/jsx-runtime";
const KATEX_RENDER_CACHE_LIMIT = 256;
const renderCacheByInstance = new WeakMap();
function renderKaTeXHtml(katex, content, displayMode) {
let cache = renderCacheByInstance.get(katex);
if (!cache) {
cache = new Map();
renderCacheByInstance.set(katex, cache);
}
const key = `${displayMode ? 1 : 0}:${content}`;
const cached = cache.get(key);
if (cached !== undefined) {
cache.delete(key);
cache.set(key, cached);
return cached;
}
try {
const html = katex.renderToString(content, {
output: 'htmlAndMathml',
displayMode,
throwOnError: false,
trust: false,
maxSize: 20,
maxExpand: 1000,
strict: 'ignore'
});
if (cache.size >= KATEX_RENDER_CACHE_LIMIT) {
const oldestKey = cache.keys().next().value;
if (oldestKey !== undefined) {
cache.delete(oldestKey);
}
}
cache.set(key, html);
return html;
} catch {
return null;
}
}
export function KaTeXRenderer({
content,
katex,
@@ -46,28 +9,24 @@ export function KaTeXRenderer({
style
}) {
const delimiter = displayMode ? '$$' : '$';
const mathSource = displayMode ? `$$\n${content.trim()}\n$$` : `$${content}$`;
const html = useMemo(() => {
if (!katex) return null;
return renderKaTeXHtml(katex, content, displayMode);
return katex.renderToString(content, {
output: 'mathml',
displayMode,
throwOnError: false,
trust: false
});
}, [katex, content, displayMode]);
const displayStyle = displayMode ? {
...style,
display: 'block',
maxWidth: '100%',
overflowX: 'auto',
overflowY: 'hidden',
boxSizing: 'border-box',
...(html ? null : {
whiteSpace: 'pre-wrap'
})
whiteSpace: 'pre-wrap'
} : style;
if (!html) {
return /*#__PURE__*/_jsx("span", {
role: "math",
"aria-label": content,
"data-display": displayMode ? 'block' : 'inline',
"data-math-source": mathSource,
style: displayStyle,
children: `${delimiter}${content}${delimiter}`
});
@@ -75,12 +34,10 @@ export function KaTeXRenderer({
return /*#__PURE__*/_jsx("span", {
role: "math",
"aria-label": content,
"data-display": displayMode ? 'block' : 'inline',
"data-math-source": mathSource,
style: displayStyle,
dangerouslySetInnerHTML: {
__html: html
}
});
}
//# sourceMappingURL=KaTeXRenderer.js.map
//# sourceMappingURL=KaTeXRenderer.js.map
@@ -60,12 +60,4 @@ function stampInlineImages(node) {
}
node.children?.forEach(stampInlineImages);
}
/** Returns true when the parsed AST contains at least one LaTeX math node. */
export function hasMathNode(node) {
if (node.type === 'LatexMathInline' || node.type === 'LatexMathDisplay') {
return true;
}
return node.children?.some(hasMathNode) ?? false;
}
//# sourceMappingURL=utils.js.map
@@ -5,8 +5,6 @@ export type { LinkContextMenuItem, LinkRecognition, } from './types/MarkdownText
export { default as EnrichedMarkdownText } from './native/EnrichedMarkdownText';
export declare function isMarkdownParserReady(): boolean;
export declare function preloadMarkdownParser(): Promise<void>;
export declare function getLoadedKaTeX(): null;
export declare function registerKaTeXStyleLoader(_loader: () => Promise<void> | void): void;
export type { EnrichedMarkdownTextProps, StreamingConfig, MarkdownStyle, Md4cFlags, ContextMenuItem as TextContextMenuItem, SelectionMenuConfig as TextSelectionMenuConfig, SelectionMenuPluralLabels as TextSelectionMenuPluralLabels, } from './native/EnrichedMarkdownText';
export type { LinkPressEvent, LinkLongPressEvent, ImagePressEvent, TaskListItemPressEvent, CopyPressEvent, LatexErrorEvent, CodeBlockPressEvent, } from './types/events';
export type { AccessibilityLabels, ResolvedAccessibilityLabels, } from './types/AccessibilityLabels';
@@ -1,7 +1,6 @@
export type { MarkdownRenderers, CodeBlockRendererProps, BlockquoteRendererProps, LinkRendererProps, } from './types/MarkdownRenderers';
export { EnrichedMarkdownText, default } from './web/EnrichedMarkdownText';
export { isMarkdownParserReady, preloadMarkdownParser } from './web/parseMarkdown';
export { getLoadedKaTeX, registerKaTeXStyleLoader, type KaTeXInstance, type KaTeXRenderOptions } from './web/katex';
export type { EnrichedMarkdownTextProps } from './types/MarkdownTextProps.web';
export type { MarkdownStyle, Md4cFlags } from './types/MarkdownStyle';
export type { LinkPressEvent, LinkLongPressEvent, ImagePressEvent, TaskListItemPressEvent, CopyPressEvent, LatexErrorEvent, CodeBlockPressEvent, } from './types/events';
@@ -1,19 +1,11 @@
export interface KaTeXRenderOptions {
displayMode?: boolean;
throwOnError?: boolean;
trust?: boolean;
maxSize?: number;
maxExpand?: number;
strict?: boolean | 'ignore' | 'warn' | 'error';
output?: 'html' | 'mathml' | 'htmlAndMathml';
}
export interface KaTeXInstance {
renderToString(expression: string, options?: KaTeXRenderOptions): string;
renderToString(expression: string, options?: {
displayMode?: boolean;
throwOnError?: boolean;
trust?: boolean;
output?: 'html' | 'mathml' | 'htmlAndMathml';
}): string;
}
/** Synchronously returns the cached KaTeX instance once loaded, or null. */
export declare function getLoadedKaTeX(): KaTeXInstance | null;
/** Registers a lazy stylesheet loader invoked alongside KaTeX loading. */
export declare function registerKaTeXStyleLoader(loader: () => Promise<void> | void): void;
/** Lazily loads KaTeX and any registered stylesheet. Resolves to null if unavailable. */
/** Lazily loads KaTeX. Resolves to null if not installed. */
export declare function loadKaTeX(): Promise<KaTeXInstance | null>;
//# sourceMappingURL=katex.d.ts.map
//# sourceMappingURL=katex.d.ts.map
@@ -18,6 +18,4 @@ export declare function indexTaskItems(node: ASTNode, counter?: {
* Mutates the AST in-place (safe: called once on the freshly-parsed result).
*/
export declare function markInlineImages(node: ASTNode): void;
/** Returns true when the parsed AST contains at least one LaTeX math node. */
export declare function hasMathNode(node: ASTNode): boolean;
//# sourceMappingURL=utils.d.ts.map
@@ -245,7 +245,7 @@ if (enableMath === undefined && process.env.ENRICHED_MARKDOWN_ENABLE_MATH) {
}
enableCodeHighlight = enableCodeHighlight !== false;
enableMath = enableMath !== false && process.env.PASEO_FDROID_BUILD !== '1';
enableMath = enableMath !== false;
if (!enableCodeHighlight && !enableMath) {
console.log(`${LOG} both code highlighting and math are disabled via package.json ("enriched-markdown"); skipping postinstall.`);
@@ -279,9 +279,7 @@ if (enableCodeHighlight) {
}
// RaTeX XCFramework + Swift sources + fonts (iOS math)
if (process.env.PASEO_FDROID_BUILD === '1') {
console.log(`${LOG} F-Droid build (PASEO_FDROID_BUILD=1); skipping RaTeX iOS assets.`);
} else if (!enableMath) {
if (!enableMath) {
console.log(`${LOG} math disabled via package.json ("enriched-markdown".enableMath = false); skipping RaTeX.`);
} else if (fs.existsSync(ratexManifest) && fs.existsSync(vendorRatex)) {
const r2 = spawnSync(process.execPath, [
@@ -17,12 +17,6 @@ export function isMarkdownParserReady(): boolean {
export function preloadMarkdownParser(): Promise<void> {
return Promise.resolve();
}
export function getLoadedKaTeX(): null {
return null;
}
export function registerKaTeXStyleLoader(
_loader: () => Promise<void> | void
): void {}
export type {
EnrichedMarkdownTextProps,
StreamingConfig,
@@ -9,12 +9,6 @@ export {
isMarkdownParserReady,
preloadMarkdownParser,
} from './web/parseMarkdown';
export {
getLoadedKaTeX,
registerKaTeXStyleLoader,
type KaTeXInstance,
type KaTeXRenderOptions,
} from './web/katex';
export type { EnrichedMarkdownTextProps } from './types/MarkdownTextProps.web';
export type { MarkdownStyle, Md4cFlags } from './types/MarkdownStyle';
export type {
@@ -16,8 +16,8 @@ import { parseMarkdown, parseMarkdownSync } from './parseMarkdown';
import { recognizeTextLinks } from './recognizeTextLinks';
import { RenderNode } from './renderers';
import type { ASTNode, RendererCallbacks, RenderCapabilities } from './types';
import { hasMathNode, indexTaskItems, markInlineImages } from './utils';
import { getLoadedKaTeX, loadKaTeX } from './katex';
import { indexTaskItems, markInlineImages } from './utils';
import { loadKaTeX } from './katex';
import type { KaTeXInstance } from './katex';
import { ENRM_TEXT_CLASS, ENRM_SELECTION_BG_VAR } from './globalStyles';
import { filterNativeOnlyProps } from './nativeProps';
@@ -51,9 +51,7 @@ export const EnrichedMarkdownText = ({
ast: ASTNode;
markdown: string;
} | null>(null);
const [katex, setKatex] = useState<KaTeXInstance | null>(() =>
(md4cFlags.latexMath ?? true) ? getLoadedKaTeX() : null
);
const [katex, setKatex] = useState<KaTeXInstance | null>(null);
const [parseError, setParseError] = useState<boolean>(false);
const {
@@ -67,8 +65,6 @@ export const EnrichedMarkdownText = ({
admonitions = true,
} = md4cFlags;
const activeKatex = latexMath ? (katex ?? getLoadedKaTeX()) : null;
// A regex literal in JSX is a new object every render; re-parse only when its text changes.
const linkRecognitionRef = useRef(linkRecognition);
linkRecognitionRef.current = linkRecognition;
@@ -121,60 +117,40 @@ export const EnrichedMarkdownText = ({
]);
useEffect(() => {
if (immediate) {
if (
!latexMath ||
activeKatex ||
!immediate.ast ||
!hasMathNode(immediate.ast)
) {
return;
}
let cancelled = false;
loadKaTeX().then((katexInstance) => {
if (!cancelled && katexInstance) {
setKatex(katexInstance);
}
});
return () => {
cancelled = true;
};
}
if (immediate && (!latexMath || katex)) return;
let cancelled = false;
parseMarkdown(markdown, {
underline,
latexMath,
superscript,
subscript,
highlight,
hardSoftBreaks,
preserveBlankLines,
admonitions,
})
.then(async (result) => {
if (cancelled) return;
indexTaskItems(result);
markInlineImages(result);
const needsKatex = latexMath && hasMathNode(result);
const katexInstance = needsKatex
? (getLoadedKaTeX() ?? (await loadKaTeX()))
: getLoadedKaTeX();
if (cancelled) return;
const katexPromise = latexMath ? loadKaTeX() : Promise.resolve(null);
setParseError(false);
if (katexInstance) {
Promise.all([
parseMarkdown(markdown, {
underline,
latexMath,
superscript,
subscript,
highlight,
hardSoftBreaks,
preserveBlankLines,
admonitions,
}),
katexPromise,
])
.then(([result, katexInstance]) => {
if (!cancelled) {
indexTaskItems(result);
markInlineImages(result);
setParseError(false);
setKatex(katexInstance);
setParsed({
markdown,
ast: recognizeTextLinks(
result,
linkRecognitionRef.current?.text,
linkRecognitionRef.current?.inlineCode
),
});
}
setParsed({
markdown,
ast: recognizeTextLinks(
result,
linkRecognitionRef.current?.text,
linkRecognitionRef.current?.inlineCode
),
});
})
.catch((error) => {
if (!cancelled) {
@@ -204,7 +180,7 @@ export const EnrichedMarkdownText = ({
textLinkKey,
inlineCodeLinkKey,
immediate,
activeKatex,
katex,
]);
const callbacks = useMemo<RendererCallbacks>(
@@ -225,8 +201,8 @@ export const EnrichedMarkdownText = ({
);
const capabilities = useMemo<RenderCapabilities>(
() => ({ katex: activeKatex, enableTaskListItemToggle, renderers }),
[activeKatex, enableTaskListItemToggle, renderers]
() => ({ katex, enableTaskListItemToggle, renderers }),
[katex, enableTaskListItemToggle, renderers]
);
const lastChildStyle = useMemo(

Some files were not shown because too many files have changed in this diff Show More