Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 22c84c59f6 polish(app): smart-fill Direct connection form on paste (#12099)
* feat(app): smart-fill Direct connection form when pasting host:port or URI

Pasting a host:port, bracketed IPv6 address, or direct connection URI into the Direct connection form now splits and populates Host, Port, Use SSL, and Password instead of leaving the raw string in Host or kicking tcp:// URIs out of Form mode.

Unifies address parsing in direct-connection-host.ts so form normalization, URI-to-Form conversion, and smart paste share one parser. Handles web paste events directly when replacing the field (avoiding mid-string paste interference) and detects multi-character paste in onChangeText for native platforms without fighting manual typing or bare IPv6 entry.

* fix(app): preserve typed URI settings, clear password on tcp paste, and track native selection

Addresses review feedback on Direct connection smart-paste:
- Clears any previous host password when pasting a tcp:// URI without ?password=, while still preserving user-entered password on plain host:port or http(s)/ws(s) pastes.
- Resolves explicit scheme, port, ssl, and password from a manually typed URI in Host on Connect and Form-to-URI mode switching instead of dropping query settings.
- Requires decimal digits for ports in buildDirectConnectionUri so non-decimal IPv6 ports like [::1]:0x10 are rejected instead of parsed as hex.
- Tracks onSelectionChange on Host and Port so native platforms accurately distinguish full-field replacements from partial pastes.

* fix(app): commit typed Host URI into form fields on blur, edit, and connect

Eliminates conflicting sources of truth when a user manually types a URI into Host: leaving Host, editing Port/SSL/Password, switching modes, or clicking Connect now commits the parsed URI into the visible form fields so password retries and subsequent edits always control the next connection attempt.

* fix(app): sync Direct connection inputs when SSL toggle or Password commits Host

Routes handleToggleUseTls and handlePasswordChange through syncFormInputs so committing a manually typed URI in Host while Host still has focus (such as tapping Use SSL on native) updates the displayed Host, Port, and Password inputs immediately.

* fix(app): defer Host blur commit when clicking Use SSL checkbox

When clicking Use SSL while Host still holds a typed URI on web, Host blurs before the checkbox press fires. Deferring the blur commit when relatedTarget is the Use SSL toggle lets handleToggleUseTls own the single commit and toggle so clicking an unchecked Use SSL after typing an https:// URL leaves SSL enabled.
2026-12-05 13:13:54 +07:00
Mohamed Boudra d6512537f4 polish(app): unify SegmentedControl with recessed pill track and Direct connection icons (#12089)
* polish(app): unify SegmentedControl with recessed pill track and Direct connection icons

Switch SegmentedControl from a transparent ghost layout to a single recessed surface2 pill track with 2px inset padding and an elevated active thumb across all surfaces. Add surfaceSegmentThumb and borderSegmentThumb semantic theme tokens so Light themes use an elevated surface0 thumb with shadow instead of colliding with surface3/border, while Dark themes (including Pure Black) use surface3 with a subtle highlight border. Replace the two wrap call sites with horizontal scroll containers so pill tracks stay single-row, align column-hosted controls so they hug content, and add Form and Link icons to the Direct connection Form/URI switcher.

* test(app): verify horizontal overflow pills selection in agent controls sheet

* test(app): force vertical overflow and use real wheel input in pills scroll test

* Update plugin directory E2E tab container lookup for horizontal scroll wrapper

* Render Command Center filter tabs as ghost tab pills with bottom breathing room

* Use shared Button and horizontal ScrollView for Command Center tab pills

* Reveal keyboard-selected Command Center filter pills on horizontal overflow
2026-12-05 13:04:13 +07:00
Mohamed Boudra 59afa917b2 polish(app): derive borderFocus token for focused inputs (#12094)
* polish(app): derive borderFocus token for focused inputs

Composer focus previously borrowed surface4 (too bright in Default Dark, compressed in Pure Black), while SearchField and MenuTextField focused to borderAccent (fading lighter than border in Light mode). Deriving borderFocus at 1.30x contrast from borderAccent toward foreground keeps focus borders consistent across built-in and plugin themes while leaving surface4 to UsageMeter.

* fix(app): composite translucent plugin borders before deriving borderFocus

* fix(app): preserve translucency when deriving borderFocus from translucent borders

* fix(app): start opaque borderFocus step from closest surface to foreground
2026-12-05 12:58:03 +07:00
Mohamed Boudra 75f8a2597d Harden build inputs and downloaded archives (#12091)
* chore(security): harden build and model downloads

* fix(speech): invalidate partial models after verification fails

* fix(highlight): clean up failed grammar downloads

* test(speech): cover rejected cached models in library
2026-12-05 12:52:53 +07:00
Mohamed Boudra 6e6ef71913 feat(app): render LaTeX math formulas by default (#11966)
* feat(app): add LaTeX math scanner, HTML protection, and streaming safety

Phase 1 of 3 for built-in LaTeX math rendering:

- Add single-pass linear math scanner and source adapter (math.ts) with fast indexOf bail-out, currency/shell/regex guards (R1-R6), canonicalization of \(...\), \[...\], and fenced math blocks, GFM table pipe escaping, multiline TeX comment stripping/blank-line collapse, and CJK hair-space flanking.
- Protect math ranges in HTML normalization (html.ts) and preserve source.ts fast path while skipping entity/spoiler rewrites inside math.
- Keep open display math together in streaming.ts and avoid auto-closing or flashing dangling math markers in streaming-stabilize.ts.
- Keep MD4C_FLAGS.latexMath as false until Phase 2 wires KaTeX web rendering.

* feat(app): enable web KaTeX math rendering, theme styles, copy, and find

Phase 2 of built-in LaTeX math rendering across Web and Electron:
- Lazy-load KaTeX and a .woff2-only stylesheet only when a parsed AST contains math nodes, and read the module cache synchronously on mount to eliminate double-parsing and raw-TeX flashes on virtualized rows.
- Render KaTeX with output: 'htmlAndMathml', security caps (trust: false, maxSize: 20, maxExpand: 1000, strict: 'ignore'), a bounded 256-entry LRU cache, and horizontal scroll on display blocks.
- Flip MD4C_FLAGS.latexMath = true, add light/dark math and inlineMath theme styles, exclude [role="math"] and .katex subtrees from the app-wide UI font rule, restore math copy-as-LaTeX without leaking MathML, and ignore .katex-mathml/annotation in Chat Find.

* feat(app): enable native RaTeX math, F-Droid/x86 fallback, and docs

Enable native RaTeX math in packages/app/package.json while keeping F-Droid source-only builds (PASEO_FDROID_BUILD=1) and 32-bit x86 Android devices without libratex_ffi.so working cleanly via Throwable raw-LaTeX fallback. Fixes MathInlineRenderer.kt to match Paseo's ((String, String) -> Unit)? NodeRenderer signature, adds Robolectric fallback coverage, and documents the built-in math contract.

* fix(app): pre-optimize katex in vitest browser config

packages/app/vitest.config.ts excludes react-native-enriched-markdown from optimizeDeps, so Vite's upfront scan missed the dynamic import("katex") inside it. Pre-including katex avoids mid-suite Vite re-optimization invalidating in-flight browser test imports.

* fix(app): preserve nested-list/indented code blocks and recover KaTeX CSS failures

- Share CommonMark block-line classification in block-scan.ts across math.ts and streaming-stabilize.ts so list-nested code fences, 4-space/tab indented code blocks, and line starts after prose are never skipped or rewritten, while 4-space paragraph continuations still parse inline math.
- Propagate KaTeX stylesheet loader failures in katex.ts (and compiled lib/module/web/katex.js) so failed CSS loads fall back to raw LaTeX and retry instead of caching an unstyled KaTeX instance.
- Replace internal spy/call-count assertions in math.test.ts and math.browser.test.tsx with caller-facing formula accuracy, CSS recovery, and nested/indented code regression tests.
- Document PASEO_FDROID_BUILD=1 during npm ci/install in docs/android.md.

* fix(app): exit unclosed list-nested fences when enclosing list ends

Track listMinIndent on list-nested FenceLine entries and exit findClosingFence when a non-blank line at the same quote depth drops below listMinIndent, matching CommonMark/md4c so trailing math outside the list is adapted.

* fix(app): share list-fence exit check with streaming stabilizer

Extract checkFenceContainerExit into block-scan.ts and use it in both math.ts findClosingFence and streaming-stabilize.ts stepFenceLine so unclosed list-nested fences exit consistently when a non-blank line drops below listMinIndent.

* fix(app): scope streaming list indent by quote depth and move root-font test to browser
2026-12-05 12:51:43 +07:00
125 changed files with 6478 additions and 1578 deletions
+14
View File
@@ -0,0 +1,14 @@
version: 2
updates:
- package-ecosystem: npm
directory: /
schedule:
interval: weekly
cooldown:
default-days: 7
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
cooldown:
default-days: 7
+4 -4
View File
@@ -25,7 +25,7 @@ jobs:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
sparse-checkout: scripts
ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref }}
@@ -70,7 +70,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
fetch-depth: 0
ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref }}
@@ -80,7 +80,7 @@ jobs:
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
@@ -93,7 +93,7 @@ jobs:
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Setup Expo and EAS
uses: expo/expo-github-action@v8
uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
+31 -28
View File
@@ -24,6 +24,9 @@ env:
NPM_CONFIG_AUDIT: "false"
NPM_CONFIG_FUND: "false"
permissions:
contents: read
jobs:
changes:
name: changes
@@ -49,7 +52,7 @@ jobs:
with:
fetch-depth: 0
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
@@ -60,7 +63,7 @@ jobs:
filters: .github/ci-paths.yml
- name: Validate CI contracts
run: node --test scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs scripts/precompress-assets.test.mjs
run: node --test packages/react-native-enriched-markdown/vendor-grammars.test.mjs scripts/ci-workflow.test.mjs scripts/daemon-launch-contract.test.mjs scripts/changelog-utils.test.mjs scripts/release-version-utils.test.mjs scripts/publish-release-packages.test.mjs scripts/push-current-release-tag.test.mjs scripts/reconcile-release.test.mjs scripts/sync-fdroid-changelogs.test.mjs scripts/sync-release-notes-from-changelog.test.mjs scripts/upload-release-assets.test.mjs scripts/precompress-assets.test.mjs
quality:
name: quality
@@ -68,9 +71,9 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.format != 'false' || needs.changes.outputs.quality != 'false' || needs.changes.outputs.relay != 'false' || needs.changes.outputs.sdk != 'false') }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
@@ -87,7 +90,7 @@ jobs:
- name: Lint lockfile
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
run: npx --yes lockfile-lint --path package-lock.json --type npm --allowed-hosts npm --validate-https --validate-integrity
run: npm exec --no -- lockfile-lint --path package-lock.json --type npm --allowed-hosts npm --validate-https --validate-integrity
- name: Lint
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
@@ -148,9 +151,9 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
@@ -170,9 +173,9 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
@@ -208,9 +211,9 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.website != 'false') }}
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
@@ -228,7 +231,7 @@ jobs:
# sometimes serves them at under 100 kB/s, which turns a 1-minute step into 25 minutes.
# Keep the downloaded .deb files in the Actions cache so apt installs them without the mirror.
- name: Restore website browser system packages
uses: actions/cache@v4
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4
with:
path: ~/website-browser-debs
key: website-browser-debs-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
@@ -252,7 +255,7 @@ jobs:
run: npm run test:e2e --workspace=@getpaseo/website
- name: Upload website test artifacts
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
if: failure()
with:
name: website-playwright-results
@@ -274,12 +277,12 @@ jobs:
node -e "const os = require('node:os'); console.log(JSON.stringify({cpus: os.cpus().length, model: os.cpus()[0].model, ramGiB: os.totalmem() / 2 ** 30}))"
- &server_checkout
uses: actions/checkout@v4
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
fetch-depth: 0
- &server_node
uses: actions/setup-node@v4
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
@@ -368,9 +371,9 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.server != 'false') }}
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
@@ -418,9 +421,9 @@ jobs:
permissions:
contents: read
steps: &desktop_test_steps
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
@@ -453,7 +456,7 @@ jobs:
PASEO_DESKTOP_LIFECYCLE_ARTIFACT_DIR: ${{ runner.temp }}/desktop-lifecycle
- name: Upload desktop lifecycle screenshots
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
if: ${{ !cancelled() && runner.os == 'Linux' }}
with:
name: desktop-lifecycle
@@ -476,7 +479,7 @@ jobs:
PASEO_DESKTOP_BROWSER_E2E_ARTIFACT_DIR: ${{ runner.temp }}/desktop-browser-e2e
- name: Upload desktop browser diagnostics
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
if: ${{ failure() && runner.os == 'Linux' }}
with:
name: desktop-browser-e2e
@@ -500,9 +503,9 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.app != 'false') }}
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
@@ -533,9 +536,9 @@ jobs:
run: |
node -e "const os = require('node:os'); console.log(JSON.stringify({cpus: os.cpus().length, model: os.cpus()[0].model, ramGiB: os.totalmem() / 2 ** 30}))"
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
@@ -567,7 +570,7 @@ jobs:
PWTEST_SHARD_WEIGHTS: "90:114:100:104:108:112:112:90"
- name: Upload test artifacts
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
if: failure()
with:
name: playwright-results-${{ env.PLAYWRIGHT_ARTIFACT }}
@@ -658,9 +661,9 @@ jobs:
PASEO_CLI_TEST_SHARD: "1"
PASEO_CLI_TEST_SHARD_TOTAL: "3"
steps: &cli_test_steps
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
+2 -2
View File
@@ -14,9 +14,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
+2 -2
View File
@@ -10,9 +10,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
+2 -2
View File
@@ -22,9 +22,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
+21 -21
View File
@@ -61,7 +61,7 @@ jobs:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
sparse-checkout: scripts
ref: ${{ env.CHECKOUT_REF }}
@@ -113,7 +113,7 @@ jobs:
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
fetch-depth: 0
ref: ${{ env.CHECKOUT_REF }}
@@ -123,7 +123,7 @@ jobs:
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
@@ -183,7 +183,7 @@ jobs:
- name: Upload packaged smoke diagnostics
if: always()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: desktop-smoke-macos-${{ matrix.electron_arch }}
path: ${{ runner.temp }}/desktop-smoke
@@ -203,7 +203,7 @@ jobs:
- name: Upload desktop artifacts to workflow
if: env.SHOULD_PUBLISH != 'true'
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: desktop-macos-${{ matrix.electron_arch }}
path: ${{ env.DESKTOP_PACKAGE_PATH }}/release/*.dmg
@@ -211,7 +211,7 @@ jobs:
- name: Upload manifest artifact
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: mac-manifest-${{ matrix.electron_arch }}
path: ${{ env.DESKTOP_PACKAGE_PATH }}/release/${{ env.RELEASE_CHANNEL }}-mac.yml
@@ -226,7 +226,7 @@ jobs:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
fetch-depth: 0
ref: ${{ env.CHECKOUT_REF }}
@@ -236,7 +236,7 @@ jobs:
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
@@ -284,7 +284,7 @@ jobs:
- name: Upload packaged smoke diagnostics
if: always()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: desktop-smoke-linux-x64
path: ${{ runner.temp }}/desktop-smoke
@@ -304,7 +304,7 @@ jobs:
- name: Upload desktop artifacts to workflow
if: env.SHOULD_PUBLISH != 'true'
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: desktop-linux
path: ${{ env.DESKTOP_PACKAGE_PATH }}/release/*
@@ -312,7 +312,7 @@ jobs:
- name: Upload manifest artifact
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: linux-manifest
path: ${{ env.DESKTOP_PACKAGE_PATH }}/release/${{ env.RELEASE_CHANNEL }}-linux.yml
@@ -327,7 +327,7 @@ jobs:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
fetch-depth: 0
ref: ${{ env.CHECKOUT_REF }}
@@ -337,7 +337,7 @@ jobs:
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
@@ -382,7 +382,7 @@ jobs:
- name: Upload packaged smoke diagnostics
if: failure()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: desktop-smoke-windows-x64
path: ${{ runner.temp }}/desktop-smoke
@@ -402,7 +402,7 @@ jobs:
- name: Upload desktop artifacts to workflow
if: env.SHOULD_PUBLISH != 'true'
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: desktop-windows
path: ${{ env.DESKTOP_PACKAGE_PATH }}/release/*
@@ -410,7 +410,7 @@ jobs:
- name: Upload manifest artifact
if: env.SHOULD_PUBLISH == 'true' && env.IS_SMOKE_TAG != 'true'
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: windows-manifest
path: ${{ env.DESKTOP_PACKAGE_PATH }}/release/${{ env.RELEASE_CHANNEL }}.yml
@@ -427,7 +427,7 @@ jobs:
cancel-in-progress: false
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
sparse-checkout: |
package.json
@@ -440,7 +440,7 @@ jobs:
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
@@ -455,21 +455,21 @@ jobs:
- name: Download mac manifest artifacts
if: env.IS_SMOKE_TAG != 'true' && needs.publish-macos.result == 'success'
uses: actions/download-artifact@v4
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
pattern: mac-manifest-*
path: release-manifests
- name: Download Linux manifest artifact
if: env.IS_SMOKE_TAG != 'true' && needs.publish-linux.result == 'success'
uses: actions/download-artifact@v4
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: linux-manifest
path: release-manifests/linux-manifest
- name: Download Windows manifest artifact
if: env.IS_SMOKE_TAG != 'true' && needs.publish-windows.result == 'success'
uses: actions/download-artifact@v4
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: windows-manifest
path: release-manifests/windows-manifest
+2 -2
View File
@@ -26,7 +26,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
sparse-checkout: |
package.json
@@ -38,7 +38,7 @@ jobs:
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
- name: Setup Node
uses: actions/setup-node@v4
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
+13 -12
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@v6
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
- id: values
env:
@@ -119,12 +119,12 @@ jobs:
permissions:
contents: read
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
- uses: docker/setup-qemu-action@v4
- uses: docker/setup-buildx-action@v4
- uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4
- uses: docker/build-push-action@v7
- uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
with:
context: .
file: docker/base/Dockerfile
@@ -133,7 +133,8 @@ jobs:
PASEO_VERSION=${{ needs.setup.outputs.install_version }}
tags: ${{ needs.setup.outputs.check_tag }}
push: false
provenance: false
# The check build does not export an image to attach attestations to.
provenance: mode=max
cache-from: type=gha,scope=paseo
cache-to: type=gha,scope=paseo,mode=max
@@ -145,19 +146,19 @@ jobs:
contents: read
packages: write
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
- uses: docker/setup-qemu-action@v4
- uses: docker/setup-buildx-action@v4
- uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4
- name: Log in to GHCR
uses: docker/login-action@v4
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/build-push-action@v7
- uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
with:
context: .
file: docker/base/Dockerfile
@@ -166,6 +167,6 @@ jobs:
PASEO_VERSION=${{ needs.setup.outputs.install_version }}
tags: ${{ needs.setup.outputs.publish_tags }}
push: true
provenance: false
provenance: mode=max
cache-from: type=gha,scope=paseo
cache-to: type=gha,scope=paseo,mode=max
+4 -4
View File
@@ -25,23 +25,23 @@ jobs:
update-hash:
runs-on: ubuntu-latest
steps:
- uses: actions/create-github-app-token@v1
- uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1
id: app-token
with:
app-id: ${{ secrets.PASEO_BOT_APP_ID }}
private-key: ${{ secrets.PASEO_BOT_APP_PRIVATE_KEY }}
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
ref: ${{ github.ref }}
token: ${{ steps.app-token.outputs.token }}
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
- uses: cachix/install-nix-action@v31
- uses: cachix/install-nix-action@3dc140bfc76c49fbd4dd958429132e3746bcb086 # v31
with:
nix_path: nixpkgs=channel:nixos-unstable
+5 -5
View File
@@ -41,14 +41,14 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "22"
cache: "npm"
- uses: cachix/install-nix-action@v31
- uses: cachix/install-nix-action@3dc140bfc76c49fbd4dd958429132e3746bcb086 # v31
with:
nix_path: nixpkgs=channel:nixos-unstable
@@ -134,9 +134,9 @@ jobs:
if: ${{ github.event_name != 'pull_request' }}
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: cachix/install-nix-action@v31
- uses: cachix/install-nix-action@3dc140bfc76c49fbd4dd958429132e3746bcb086 # v31
with:
nix_path: nixpkgs=channel:nixos-unstable
+1 -1
View File
@@ -30,7 +30,7 @@ jobs:
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
fetch-depth: 0
+1 -1
View File
@@ -1,6 +1,6 @@
# syntax=docker/dockerfile:1
ARG NODE_IMAGE=node:22-bookworm-slim
ARG NODE_IMAGE=node:22-bookworm-slim@sha256:be979e5523c76fa4d5ca4ebd3099078f220aa47ec39c48ad5b5df9314debd6eb
FROM --platform=$BUILDPLATFORM ${NODE_IMAGE} AS source-pack
ARG PASEO_VERSION
+3 -2
View File
@@ -216,16 +216,17 @@ not change the shipped scroll view. Keep this behavior in the app's compiled nat
## F-Droid / source-only Android builds
F-Droid builds should set `PASEO_FDROID_BUILD=1` when running Expo prebuild:
F-Droid builds should set `PASEO_FDROID_BUILD=1` for `npm ci` (or `npm install`), Expo prebuild, and Gradle:
```bash
PASEO_FDROID_BUILD=1 npm ci
cd packages/app
PASEO_FDROID_BUILD=1 APP_VARIANT=production npx expo prebuild --platform android --clean --non-interactive
cd android
PASEO_FDROID_BUILD=1 ./gradlew assembleRelease --no-daemon --max-workers=1 -Dorg.gradle.parallel=false
```
The flag must be present for both prebuild and Gradle because Gradle starts Metro for the release bundle. Keep the source build serial and daemon-free as shown above: compiling every Expo module can exhaust memory when Gradle workers run in parallel. The profile enables source-built Expo modules, excludes the proprietary camera, Firebase notification, and Expo development-client native modules, disables Gradle dependency metadata, and substitutes JavaScript stubs for camera and notifications. The resulting app supports direct and pasted-link pairing but not QR scanning or push notifications.
Setting `PASEO_FDROID_BUILD=1` during install makes `packages/react-native-enriched-markdown/postinstall.mjs` skip downloading the prebuilt iOS RaTeX XCFramework into the source tree. The flag must also be present for both prebuild and Gradle because Gradle starts Metro for the release bundle. Keep the source build serial and daemon-free as shown above: compiling every Expo module can exhaust memory when Gradle workers run in parallel. The profile enables source-built Expo modules, excludes the proprietary camera, Firebase notification, and Expo development-client native modules, disables Gradle dependency metadata, and substitutes JavaScript stubs for camera and notifications. The resulting app supports direct and pasted-link pairing but not QR scanning or push notifications. Setting `PASEO_FDROID_BUILD=1` also disables native RaTeX math in `react-native-enriched-markdown` and falls back to raw LaTeX text without requiring a Rust toolchain.
For a single-ABI APK, pass React Native's architecture property to Gradle:
+2 -2
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. The selected segment is a `surface3` fill with `foreground` text, not an inverted one — inverting it inside thin chrome puts a white slab in the toolbar. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use.
Buttons are pills (`borderRadius.full`) with medium-weight labels; an icon-only button is a circle. `<Switch>` follows the same two sizes: a 34×20 track by default and in `sm`, 44×26 where controls are touch-sized, and it takes presses over its size's control height without adding that height to its row. Buttons, text fields, dropdown triggers, and `<SegmentedControl>` (`packages/app/src/components/ui/segmented-control.tsx`) share the size contract — the same size name means the same height and label size on every control kind, so controls in one row line up. Segments run tighter than a button, because the gap between segments already reads as padding. `<SegmentedControl>` sits in a recessed `surface2` pill track with an elevated active thumb (`surface3` on dark themes, `surface0` with a subtle shadow on light themes) and `foreground` text, never an inverted fill inside thin chrome. A settings row sizes the controls in its trailing slot itself, default in a card and `sm` when nested (`packages/app/src/components/ui/control-size.tsx`), so don't pass a size to a button, dropdown or field placed in a row. Code that computes with a control's height outside a stylesheet uses `controlHeightForLayout`. Never shrink a control's font or padding locally to fit a context — if the context needs a smaller control, the size tier is missing or the wrong one is in use.
A `<Pressable>` wrapping a `<Text>` is a sixth variant. It is wrong. `<Button>` accepts `style`, `textStyle`, `leftIcon`, `disabled`, `size`, and `variant`.
@@ -96,7 +96,7 @@ A list that is itself the page content — sidebar items in `sidebar-workspace-l
Pane chrome — the workspace pane header, the file-explorer header, the diff pane header — uses a single bottom border to separate the header from the content (`packages/app/src/components/git-diff-pane.tsx:2328-2331`). One border, no shadow.
`borderAccent` is reserved for the outline button. Inputs use `border`. Single-thing borders are wrong; a single bordered element is either a card with one row (use the card) or it does not need a border.
`borderAccent` is reserved for the outline button and resting frames like the composer. Inputs rest at `border` and step to `borderFocus` on focus. Single-thing borders are wrong; a single bordered element is either a card with one row (use the card) or it does not need a border.
---
+12 -2
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`. The `enriched-markdown` block in `packages/app/package.json` chooses the languages.
- `postinstall.mjs` downloads the tree-sitter grammars into the ignored `cpp/highlight/vendor/grammars` and `vendor/tree-sitter`, and downloads RaTeX into `ios/vendor` when `enableMath` is true (unless `PASEO_FDROID_BUILD=1`). The `enriched-markdown` block in `packages/app/package.json` chooses the languages and enables native math.
CI does not build native code or run the fork's Robolectric suites. Run `npm run test:android --workspace=@getpaseo/app` for Android changes. Native changes require a client rebuild; JavaScript refresh cannot enable compiled grammars.
@@ -46,7 +46,17 @@ Some fork changes are backports. A sync past the upstream version drops them in
## Engine constraints
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded. `<br>` becomes a Markdown hard break, except inside a table, where a newline would end the row. There it becomes U+2028, and `cpp/parser/MD4CParser.cpp` turns U+2028 back into a line break in table cell text, never in code.
Built-in LaTeX math is enabled by default, and video is disabled. Task lists and admonitions are enabled, and task checkboxes stay read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing, and details show their summary and body expanded. `<br>` becomes a Markdown hard break, except inside a table, where a newline would end the row. There it becomes U+2028, and `cpp/parser/MD4CParser.cpp` turns U+2028 back into a line break in table cell text, never in code.
### LaTeX math
`components/markdown/math.ts` accepts `$...$`, `$$...$$`, `\(...\)`, `\[...\]`, and closed `math` fences (` ```math ` or `~~~math`). Inline `$...$` requires non-alphanumeric outer boundaries, no inner edge spaces, and no leading currency number or shell prose. Escaped `\[1, 2\]` citations, `$PATH`, regexes, and `latex` or `tex` code fences stay literal. Non-math messages skip scanning with a fast character check and do not trigger an `mdast` parse. Adapted expressions canonicalize to `$...$` or `$$...$$` for `md4c`, escape table pipes inside table rows, and flank adjacent CJK characters with hair spaces.
On web and Electron, `react-native-enriched-markdown` loads KaTeX (`htmlAndMathml` output with `.woff2` fonts) lazily when a document contains a math node. It caches rendered HTML in a 256-entry LRU and skips root-font overrides on `.katex` elements. Selection copy restores `[data-math-source]` to `$...$` or `$$\n...\n$$` without hidden `.katex-mathml` or `annotation` nodes. Chat Find ignores `.katex-mathml`, `annotation`, and `annotation-xml` nodes as well.
On iOS and Android, native views render with RaTeX (`enableMath: true` in `packages/app/package.json`). F-Droid builds (`PASEO_FDROID_BUILD=1`) disable native RaTeX in Gradle and `postinstall.mjs`, falling back to raw LaTeX. On 32-bit `x86` Android devices without `libratex_ffi.so`, the math views catch `Throwable` and render raw LaTeX text.
While streaming, `streaming.ts` keeps open `$$`, `\[`, and `math` fences in the unsealed tail so equations never split across blocks. Incomplete inline and display math stays withheld or literal until its closing delimiter arrives.
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
+111 -3
View File
@@ -38,6 +38,7 @@
"js-yaml": "^4.1.1",
"knip": "^5.82.1",
"lefthook": "^2.1.6",
"lockfile-lint": "5.1.1",
"oxfmt": "0.46.0",
"oxlint": "1.61.0",
"oxlint-tsgolint": "^0.22.1",
@@ -14792,6 +14793,20 @@
"dev": true,
"license": "BSD-2-Clause"
},
"node_modules/@yarnpkg/parsers": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@yarnpkg/parsers/-/parsers-3.1.0.tgz",
"integrity": "sha512-WoxUM/Be4hfsX06FxsvpGgfYqwgivMV7/Ol7aFuSfSmY6rRaiju4QxOEe9RUS0iYcSHWl5i9AhB1cMoE0p+XiA==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"js-yaml": "^4.3.0",
"tslib": "^2.4.0"
},
"engines": {
"node": ">=18.12.0"
}
},
"node_modules/abab": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz",
@@ -17348,6 +17363,43 @@
"layout-base": "^1.0.0"
}
},
"node_modules/cosmiconfig": {
"version": "9.0.2",
"resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.2.tgz",
"integrity": "sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg==",
"dev": true,
"license": "MIT",
"dependencies": {
"env-paths": "^2.2.1",
"import-fresh": "^3.3.0",
"js-yaml": "^4.1.0",
"parse-json": "^5.2.0"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/sponsors/d-fischer"
},
"peerDependencies": {
"typescript": ">=4.9.5"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/cosmiconfig/node_modules/env-paths": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz",
"integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/create-jest": {
"version": "29.7.0",
"resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz",
@@ -25817,9 +25869,19 @@
"license": "MIT"
},
"node_modules/js-yaml": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
"version": "4.3.2",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz",
"integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/puzrin"
},
{
"type": "github",
"url": "https://github.com/sponsors/nodeca"
}
],
"license": "MIT",
"dependencies": {
"argparse": "^2.0.1"
@@ -26810,6 +26872,41 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/lockfile-lint": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lockfile-lint/-/lockfile-lint-5.1.1.tgz",
"integrity": "sha512-GqzPAe/DvCR23Rg6vu0be+ZvpDgeri4TkTFWAQJ0MTACvWwQXah5f9kSuKyPY9Y1JRdKpQI6QOLwfdRoQezTpg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"cosmiconfig": "^9.0.0",
"debug": "^4.3.4",
"lockfile-lint-api": "^5.10.2",
"tinyglobby": "^0.2.15",
"yargs": "^17.7.2"
},
"bin": {
"lockfile-lint": "bin/lockfile-lint.js"
},
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/lockfile-lint-api": {
"version": "5.10.2",
"resolved": "https://registry.npmjs.org/lockfile-lint-api/-/lockfile-lint-api-5.10.2.tgz",
"integrity": "sha512-m3bo4ScHsfyRzysYjhtGcyaoutbg9Xe8ttR6vtGrgOSJ6qj4ryi8vWPCYy8SeG4FxvHuFM5Mfcubz/REMzaUOw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@yarnpkg/parsers": "^3.0.0-rc.48.1",
"debug": "^4.3.4",
"object-hash": "^3.0.0"
},
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/lodash": {
"version": "4.17.23",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz",
@@ -29965,6 +30062,16 @@
"node": ">=0.10.0"
}
},
"node_modules/object-hash": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz",
"integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 6"
}
},
"node_modules/object-inspect": {
"version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
@@ -37620,6 +37727,7 @@
"fast-deep-equal": "^3.1.3",
"htmlparser2": "^12.0.0",
"i18next": "^26.3.0",
"katex": "^0.16.47",
"lucide-react-native": "^1.50.0",
"markdown-it": "^10.0.0",
"mdast-util-from-markdown": "2.0.3",
+1
View File
@@ -144,6 +144,7 @@
"js-yaml": "^4.1.1",
"knip": "^5.82.1",
"lefthook": "^2.1.6",
"lockfile-lint": "5.1.1",
"oxfmt": "0.46.0",
"oxlint": "1.61.0",
"oxlint-tsgolint": "^0.22.1",
@@ -173,6 +173,29 @@ test("command center tabs rotate with Tab and never move the header", async ({ p
await expectCommandCenterTabs(panel, ["All", "Workspaces", "Files", "Actions"]);
});
await test.step("overflowing filter tabs scroll into view on narrow viewports", async () => {
const originalViewport = page.viewportSize() ?? { width: 1280, height: 720 };
await page.setViewportSize({ width: 280, height: 640 });
try {
const tabsBar = panel.getByTestId("command-center-tabs");
const metrics = await tabsBar.evaluate((el) => ({
scrollWidth: el.scrollWidth,
clientWidth: el.clientWidth,
}));
expect(metrics.scrollWidth).toBeGreaterThan(metrics.clientWidth);
await page.keyboard.press("Shift+Tab");
await expectCommandCenterTab(panel, "Actions");
const actionsTab = panel.getByTestId("command-center-tab-actions");
await expect(actionsTab).toBeInViewport({ ratio: 1 });
await page.keyboard.press("Tab");
await expectCommandCenterTab(panel, "All");
const scrollLeft = await tabsBar.evaluate((el) => el.scrollLeft);
expect(scrollLeft).toBe(0);
} finally {
await page.setViewportSize(originalViewport);
}
});
await test.step("outside a workspace there is no Files tab, and Tab skips it", async () => {
const outside = { workspaceOpen: false };
await closeCommandCenter(page);
@@ -248,10 +248,10 @@ async function readSettledFrameBorder(page: Page): Promise<string> {
});
}
// `borderAccent` at rest, `surface4` while focused: greys in both themes, never the accent.
// `borderAccent` at rest, `borderFocus` while focused: greys in both themes, never the accent.
const FRAME_BORDERS = {
dark: { rest: "rgb(47, 53, 52)", focus: "rgb(89, 91, 91)" },
light: { rest: "rgb(236, 236, 241)", focus: "rgb(212, 212, 216)" },
dark: { rest: "rgb(47, 53, 52)", focus: "rgb(66, 70, 69)" },
light: { rest: "rgb(236, 236, 241)", focus: "rgb(208, 208, 213)" },
} as const;
for (const colorScheme of ["dark", "light"] as const) {
@@ -41,6 +41,9 @@ import {
connectDirectHost,
connectDirectHostExpectingPassword,
pasteIntoDirectHost,
pasteClipboardIntoDirectField,
pasteIntoMiddleOfDirectHost,
typeDirectHostCharacters,
fillDirectHostPromptPassword,
openCompactSettings,
expectCompactSettingsList,
@@ -56,6 +59,7 @@ import {
fillDirectHostUri,
expectDirectHostFormValues,
expectDirectHostSslEnabled,
expectDirectHostSslDisabled,
fillDirectHostAddress,
toggleDirectHostSsl,
expectDirectHostUriValue,
@@ -373,6 +377,110 @@ test.describe("Settings sidebar navigation", () => {
});
});
test("direct connection form smart-fills on paste without disrupting manual typing", async ({
page,
}) => {
await gotoAppShell(page);
await openSettings(page);
await openAddHostFlow(page);
await selectHostConnectionType(page, "direct");
await expectDirectConnectionMode(page, "Form");
await test.step("pasting localhost:port splits Host and Port", async () => {
await pasteClipboardIntoDirectField(page, "Host", "localhost:6768");
await expectDirectHostFormValues(page, { host: "localhost", port: "6768", password: "" });
await expectDirectHostSslDisabled(page);
});
await test.step("pasting an https URI populates Host, Port, and Use SSL", async () => {
await pasteClipboardIntoDirectField(page, "Host", "https://myhost.ts.net:7443/");
await expectDirectHostFormValues(page, { host: "myhost.ts.net", port: "7443", password: "" });
await expectDirectHostSslEnabled(page);
});
await test.step("pasting a full Paseo URI populates Host, Port, Use SSL, and Password", async () => {
await pasteClipboardIntoDirectField(
page,
"Host",
"tcp://100.91.42.18:6769?ssl=false&password=my%20secret",
);
await expectDirectHostFormValues(page, {
host: "100.91.42.18",
port: "6769",
password: "my secret",
});
await expectDirectHostSslDisabled(page);
});
await test.step("pasting https without a port defaults Port to 443", async () => {
await pasteClipboardIntoDirectField(page, "Host", "https://tunnel.example.test");
await expectDirectHostFormValues(page, {
host: "tunnel.example.test",
port: "443",
password: "my secret",
});
await expectDirectHostSslEnabled(page);
});
await test.step("typing bare IPv6 and pasting into the middle of Host stay literal", async () => {
await typeDirectHostCharacters(page, "2001:1234::1");
await expectDirectHostFormValues(page, {
host: "2001:1234::1",
port: "443",
password: "my secret",
});
await pasteIntoMiddleOfDirectHost(page, "example.com", 2, "sub:9000");
await expectDirectHostFormValues(page, {
host: "exsub:9000ample.com",
port: "443",
password: "my secret",
});
});
await test.step("pasting a tcp URI without password clears a previous host password", async () => {
await pasteClipboardIntoDirectField(page, "Host", "tcp://second.example.test:7443");
await expectDirectHostFormValues(page, {
host: "second.example.test",
port: "7443",
password: "",
});
await expectDirectHostSslDisabled(page);
});
await test.step("clicking Use SSL after typing an https URL keeps SSL enabled", async () => {
await expectDirectHostSslDisabled(page);
await typeDirectHostCharacters(page, "https://typed.example.test:7443");
await toggleDirectHostSsl(page);
await expectDirectHostFormValues(page, {
host: "typed.example.test",
port: "7443",
password: "",
});
await expectDirectHostSslEnabled(page);
});
await test.step("pasting a host:port into Port fills Host and Port", async () => {
await pasteClipboardIntoDirectField(page, "Port", "hetzner.tail8a2f.ts.net:6768");
await expectDirectHostFormValues(page, {
host: "hetzner.tail8a2f.ts.net",
port: "6768",
password: "",
});
});
await test.step("pasting a live daemon address connects cleanly", async () => {
await pasteClipboardIntoDirectField(page, "Host", `http://127.0.0.1:${getE2EDaemonPort()}/`);
await expectDirectHostFormValues(page, {
host: "127.0.0.1",
port: String(getE2EDaemonPort()),
password: "",
});
await expectDirectHostSslDisabled(page);
await connectDirectHost(page);
});
});
test("direct connection connects to a URI with Host blank", async ({ page }) => {
await gotoAppShell(page);
await openSettings(page);
@@ -500,12 +500,11 @@ async function sampleFramesDuring(
}
return match;
};
const findOverviewCard = (tabsEl: Element | null, stacked: boolean): Element | null => {
const findOverviewCard = (tabsEl: Element | null): Element | null => {
if (!tabsEl) return null;
const container = stacked
? (tabsEl.closest('[style*="overflow"]')?.parentElement ??
tabsEl.parentElement?.parentElement?.parentElement)
: tabsEl.parentElement?.parentElement;
const container =
tabsEl.closest('[style*="overflow"]')?.parentElement ??
tabsEl.parentElement?.parentElement?.parentElement;
if (!container) return null;
const visibleChildren = Array.from(container.children).filter(isVisible);
return visibleChildren[visibleChildren.length - 1] ?? null;
@@ -519,7 +518,7 @@ async function sampleFramesDuring(
const skeletonEl = queryVisible('[data-testid="plugin-overview-skeleton"]');
const licenseRect = roundRect(findVisibleText("License"));
const relatedRect = roundRect(findVisibleText("Related plugins"));
const overviewCard = findOverviewCard(tabsEl, stacked);
const overviewCard = findOverviewCard(tabsEl);
const overviewRect = roundRect(overviewCard);
samples.push({
@@ -455,6 +455,46 @@ export async function pasteIntoDirectHost(page: Page, text: string): Promise<voi
await page.getByRole("textbox", { name: "Host", exact: true }).fill(text);
}
export async function pasteClipboardIntoDirectField(
page: Page,
field: "Host" | "Port",
text: string,
options?: { replace?: boolean },
): Promise<void> {
const input = page.getByRole("textbox", { name: field, exact: true });
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
await page.evaluate((value) => navigator.clipboard.writeText(value), text);
await input.click();
if (options?.replace ?? true) {
await page.keyboard.press("ControlOrMeta+a");
}
await page.keyboard.press("ControlOrMeta+v");
}
export async function typeDirectHostCharacters(page: Page, text: string): Promise<void> {
const input = page.getByRole("textbox", { name: "Host", exact: true });
await input.click();
await page.keyboard.press("ControlOrMeta+a");
await page.keyboard.press("Backspace");
await input.pressSequentially(text);
}
export async function pasteIntoMiddleOfDirectHost(
page: Page,
initialHost: string,
offset: number,
pastedText: string,
): Promise<void> {
await typeDirectHostCharacters(page, initialHost);
await page.keyboard.press("Home");
for (let index = 0; index < offset; index += 1) {
await page.keyboard.press("ArrowRight");
}
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
await page.evaluate((value) => navigator.clipboard.writeText(value), pastedText);
await page.keyboard.press("ControlOrMeta+v");
}
export async function toggleDirectHostSsl(page: Page): Promise<void> {
await page.getByRole("checkbox", { name: "Use SSL", exact: true }).click();
}
+4
View File
@@ -1 +1,5 @@
declare module "*.css";
declare module "*.woff2" {
const src: string;
export default src;
}
+3
View File
@@ -17,6 +17,9 @@ const customWebPlatform = (process.env.PASEO_WEB_PLATFORM ?? "")
.toLowerCase();
const config = getDefaultConfig(projectRoot);
if (!config.resolver.assetExts.includes("woff2")) {
config.resolver.assetExts.push("woff2");
}
config.cacheVersion = isWatchdogBuild ? "watchdog" : "standard";
const defaultResolveRequest = config.resolver.resolveRequest ?? resolve;
+3 -2
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' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :expo-modules-core:testReleaseUnitTest --tests expo.modules.kotlin.activityresult.AppContextActivityResultRegistryRecreationTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*CodeBlockCopyButtonConstructionTest' --tests '*LongPressSelectionInterceptTest' --tests '*MathRenderingFallbackTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
},
"dependencies": {
"@codemirror/commands": "6.10.4",
@@ -110,6 +110,7 @@
"fast-deep-equal": "^3.1.3",
"htmlparser2": "^12.0.0",
"i18next": "^26.3.0",
"katex": "^0.16.47",
"lucide-react-native": "^1.50.0",
"markdown-it": "^10.0.0",
"mdast-util-from-markdown": "2.0.3",
@@ -178,7 +179,7 @@
"ws": "^8.20.0"
},
"enriched-markdown": {
"enableMath": false,
"enableMath": true,
"enableCodeHighlight": true,
"codeHighlightLanguages": [
"json",
@@ -111,6 +111,7 @@ function ThinkingField({
value={state.thinkingOptionId || null}
onValueChange={onSegmentChange}
size={controlSize}
style={styles.thinkingControl}
testID="agent-profile-thinking-trigger"
/>
</Field>
@@ -574,6 +575,9 @@ const styles = StyleSheet.create((theme) => ({
padding: theme.spacing[4],
gap: theme.spacing[4],
},
thinkingControl: {
alignSelf: "flex-start",
},
featureCardPending: {
opacity: theme.opacity[50],
},
@@ -122,3 +122,26 @@ it("keeps text around nested plugin blocks in separate occurrences", () => {
expect(findRenderedMatches(row, "details").map((range) => range.toString())).toEqual(["details"]);
expect(findRenderedMatches(row, "beta").map((range) => range.toString())).toEqual(["beta"]);
});
it("ignores KaTeX MathML and annotations while keeping block math as a boundary", () => {
const row = content(
[
"<p>Before ",
'<span role="math" aria-label="alpha" data-display="inline" data-math-source="$alpha$">',
'<span class="katex">',
'<span class="katex-mathml"><math><semantics><mrow><mi>alpha</mi></mrow><annotation encoding="application/x-tex">alpha</annotation><annotation-xml encoding="MathML-Content"><ci>alpha</ci></annotation-xml></semantics></math></span>',
'<span class="katex-html" aria-hidden="true"><span>alpha</span></span>',
"</span>",
"</span>",
" after</p>",
'<span role="math" aria-label="x^2" data-display="block" data-math-source="$$\nx^2\n$$">block fallback</span>',
"<p>next</p>",
].join(""),
);
expect(findRenderedMatches(row, "alpha")).toEqual([]);
expect(findRenderedMatches(row, "Before").map((range) => range.toString())).toEqual(["Before"]);
expect(findRenderedMatches(row, "after").map((range) => range.toString())).toEqual(["after"]);
expect(findRenderedMatches(row, "fallbacknext")).toEqual([]);
expect(findRenderedMatches(row, "after fallbacknext")).toEqual([]);
});
@@ -1,8 +1,12 @@
const BLOCKS = ["p", "pre", "li", "td", "th", "h1", "h2", "h3", "h4", "h5", "h6"]
.flatMap((tag) => [tag, `[data-paseo-markdown-tag="${tag}"]`])
.join(",");
const BLOCKS = [
...["p", "pre", "li", "td", "th", "h1", "h2", "h3", "h4", "h5", "h6"].flatMap((tag) => [
tag,
`[data-paseo-markdown-tag="${tag}"]`,
]),
'[role="math"][data-display="block"]',
].join(",");
const IGNORED =
'[data-paseo-markdown-ignore="true"], [aria-hidden="true"], button, [role="button"], svg, script, style';
'[data-paseo-markdown-ignore="true"], [aria-hidden="true"], .katex-mathml, annotation, annotation-xml, button, [role="button"], svg, script, style';
/** Rendered rows carrying a source message identity, in reading order. */
export function findMessageRows(root: HTMLElement | null, messageId: string): HTMLElement[] {
@@ -0,0 +1,39 @@
import { afterEach, describe, expect, it } from "vitest";
import { applyRootUiFont } from "./apply-root-font.web";
describe("applyRootUiFont", () => {
afterEach(() => {
document.getElementById("paseo-ui-font")?.remove();
document.documentElement.style.removeProperty("--paseo-ui-font");
document.body.replaceChildren();
});
it("applies the UI font to prose while excluding monospace, role=math, and KaTeX subtrees", () => {
applyRootUiFont("'Custom UI Font', sans-serif");
const root = document.createElement("div");
root.id = "root";
root.innerHTML = `
<p id="prose">Prose</p>
<code data-pmono="true" style="font-family: monospace"><span id="mono">code</span></code>
<span id="math-host" role="math" style="font-family: KaTeX_Main"><span id="katex-root" class="katex"><span id="katex-glyph">x</span></span></span>
`;
document.body.append(root);
expect(getComputedStyle(document.getElementById("prose")!).fontFamily).toContain(
"Custom UI Font",
);
expect(getComputedStyle(document.getElementById("mono")!).fontFamily).not.toContain(
"Custom UI Font",
);
expect(getComputedStyle(document.getElementById("math-host")!).fontFamily).not.toContain(
"Custom UI Font",
);
expect(getComputedStyle(document.getElementById("katex-root")!).fontFamily).not.toContain(
"Custom UI Font",
);
expect(getComputedStyle(document.getElementById("katex-glyph")!).fontFamily).not.toContain(
"Custom UI Font",
);
});
});
@@ -7,9 +7,10 @@
// beats both RN-web's base font and Unistyles' generated classes (0,1,0) — no reliance
// on stylesheet order. Code/diff/terminal surfaces carry `data-pmono` (and have their
// subtree excluded via `:not([data-pmono] *)`) so they keep their monospace font.
// KaTeX math containers carry `role="math"` and `.katex` and keep KaTeX font faces.
const STYLE_ID = "paseo-ui-font";
const RULE =
":is(#root, #overlay-root) *:not([data-pmono]):not([data-pmono] *){font-family:var(--paseo-ui-font);}";
':is(#root, #overlay-root) *:not([data-pmono]):not([data-pmono] *):not([role="math"]):not([role="math"] *):not(.katex):not(.katex *){font-family:var(--paseo-ui-font);}';
export function applyRootUiFont(uiFontStack: string): void {
if (typeof document === "undefined") return;
@@ -997,7 +997,11 @@ describe("quote copy", () => {
});
/** Renders Markdown through the web engine with the app's renderers, as a message does. */
async function renderMarkdown(markdown: string, lastText: string): Promise<HTMLElement> {
async function renderMarkdown(
markdown: string,
lastText: string,
latexMath = false,
): Promise<HTMLElement> {
if (!host || !root) {
host = document.createElement("div");
document.body.append(host);
@@ -1017,7 +1021,7 @@ describe("quote copy", () => {
children: h(EnrichedMarkdownText, {
markdown,
flavor: "github",
md4cFlags: { latexMath: false, admonitions: true },
md4cFlags: { latexMath, admonitions: true },
renderers: WEB_RENDERERS,
}),
}),
@@ -1135,4 +1139,102 @@ describe("quote copy", () => {
expect(createElementClipboardContent(quote)).toBeNull();
});
it("copies rendered inline and display math inside a quote as LaTeX", async () => {
const rendered = await renderMarkdown(
"> Inline $E = mc^2$ and:\n>\n> $$\nx^2\n$$",
"Inline",
true,
);
await vi.waitFor(() =>
expect(rendered.querySelectorAll(".katex").length).toBeGreaterThanOrEqual(2),
);
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
expect(content?.plainText).toBe("Inline $E = mc^2$ and:\n\n$$\nx^2\n$$");
});
});
describe("math selection copy", () => {
let root: Root | undefined;
let host: HTMLDivElement | undefined;
const toast: ToastApi = { show: () => () => {}, copied: () => {}, error: () => {} };
const queryClient = new QueryClient();
afterEach(() => {
const mounted = root;
if (mounted) flushSync(() => mounted.unmount());
root = undefined;
host?.remove();
host = undefined;
});
async function renderMathMarkdown(markdown: string): Promise<HTMLElement> {
host = document.createElement("div");
host.setAttribute("data-testid", "assistant-message");
document.body.append(host);
root = createRoot(host);
flushSync(() =>
root!.render(
h(
QueryClientProvider,
{ client: queryClient },
h(
I18nextProvider,
{ i18n },
h(ToastApiProvider, {
api: toast,
children: h(EnrichedMarkdownText, {
markdown,
flavor: "github",
md4cFlags: { latexMath: true, admonitions: true },
renderers: WEB_RENDERERS,
}),
}),
),
),
),
);
const rendered = host;
await vi.waitFor(() => expect(rendered.querySelector(".katex")).not.toBeNull());
return rendered;
}
it("copies inline math as $tex$ and display math as $$\\ntex\\n$$ without leaking MathML", async () => {
const rendered = await renderMathMarkdown(
"Before $a_i < b_j$ after.\n\n$$\n\\frac{1}{2}\n$$\n\nEnd.",
);
const content = createAssistantSelectionClipboardContent(selectNodeContents(rendered));
expect(content?.plainText).toBe("Before $a_i < b_j$ after.\n\n$$\n\\frac{1}{2}\n$$\n\nEnd.");
expect(content?.html).not.toContain("<em>");
expect(content?.html).toContain("$a_i &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,6 +6,7 @@ import {
type MarkdownClipboardContent,
} from "@/utils/rich-clipboard";
import {
KATEX_MATHML_SELECTOR,
MARKDOWN_ADMONITION_TITLE_ATTRIBUTE,
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
MARKDOWN_COPY_IMAGE_SOURCES_ATTRIBUTE,
@@ -20,6 +21,8 @@ import {
MARKDOWN_COPY_TAG_ATTRIBUTE,
MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE,
MARKDOWN_COPY_UNWRAP_ATTRIBUTE,
MARKDOWN_MATH_DISPLAY_ATTRIBUTE,
MARKDOWN_MATH_SOURCE_ATTRIBUTE,
TRAILING_CODE_LINE_BREAKS,
} from "./markup";
@@ -106,6 +109,17 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
return `\n\n${`[!${type}]\n${body}`.replace(/^/gm, "> ")}\n\n`;
},
});
// Rendered math copies back as `$tex$` (inline) or `$$\ntex\n$$` (block).
turndown.addRule("mathSource", {
filter: (node) => node.hasAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE),
replacement: (_content, node) => {
const element = node as Element;
const source = element.getAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE) ?? "";
const isBlock = element.getAttribute(MARKDOWN_MATH_DISPLAY_ATTRIBUTE) === "block";
const formatted = flavor === "markdown" ? turndown.escape(source) : source;
return isBlock ? `\n\n${formatted}\n\n` : formatted;
},
});
turndown.addRule("gfmStrikethrough", {
filter: ["del", "s"],
replacement: (content) => `~~${content}~~`,
@@ -411,12 +425,19 @@ function nodeAtPath(root: Node, path: number[]): Node {
}
function removeUnselectedSemantics(range: Range, source: Element, clone: Element): void {
const selector = `[${MARKDOWN_COPY_TAG_ATTRIBUTE}], a, ${SEMANTIC_TAGS}`;
const selector = `[${MARKDOWN_COPY_TAG_ATTRIBUTE}], [${MARKDOWN_MATH_SOURCE_ATTRIBUTE}], a, ${SEMANTIC_TAGS}`;
const originals = Array.from(source.querySelectorAll(selector));
const copies = Array.from(clone.querySelectorAll(selector));
originals.forEach((original, index) => {
const copy = copies[index];
if (original.hasAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE)) {
if (copy && (!range.intersectsNode(original) || !hasSelectedAllContents(range, original))) {
copy.removeAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE);
copy.removeAttribute(MARKDOWN_MATH_DISPLAY_ATTRIBUTE);
}
return;
}
if (copy) copySemanticAttributes(original, copy);
if (!copy || shouldPreserveSemanticElement(range, original)) {
if (copy) {
@@ -440,6 +461,9 @@ function shouldPreserveSemanticElement(range: Range, element: Element): boolean
if (!range.intersectsNode(element)) {
return false;
}
if (element.hasAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE)) {
return hasSelectedAllContents(range, element);
}
const tag = semanticTag(element);
// An image has no part to select, so touching it selects all of it.
if (tag === "p" || tag === "img" || isTableStructure(tag)) {
@@ -590,7 +614,9 @@ function selectsNothingOutside(range: Range, element: Element): boolean {
function hasMarkdownContent(fragment: DocumentFragment, includeIgnored: boolean): boolean {
if (!includeIgnored) {
for (const ignored of fragment.querySelectorAll(`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}]`)) {
for (const ignored of fragment.querySelectorAll(
`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}], ${KATEX_MATHML_SELECTOR}`,
)) {
ignored.remove();
}
}
@@ -681,8 +707,19 @@ function selectedMessageParts(range: Range): SelectedMessagePart[] | null {
});
}
function restoreMathSources(container: HTMLElement): void {
for (const math of container.querySelectorAll(`[${MARKDOWN_MATH_SOURCE_ATTRIBUTE}]`)) {
const source = math.getAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE);
if (source !== null) {
math.textContent = source;
}
}
}
function restoreMarkdownElements(container: HTMLElement): void {
for (const ignored of container.querySelectorAll(`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}]`)) {
for (const ignored of container.querySelectorAll(
`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}], ${KATEX_MATHML_SELECTOR}`,
)) {
ignored.remove();
}
@@ -732,7 +769,11 @@ function restoreMarkdownElements(container: HTMLElement): void {
element.replaceWith(...element.childNodes);
}
const presentational = Array.from(container.querySelectorAll("div, span"));
restoreMathSources(container);
const presentational = Array.from(
container.querySelectorAll(`div, span:not([${MARKDOWN_MATH_SOURCE_ATTRIBUTE}])`),
);
for (const element of presentational.toReversed()) {
element.replaceWith(...element.childNodes);
}
@@ -13,6 +13,10 @@ export const MARKDOWN_COPY_ALT_ATTRIBUTE = "data-paseo-markdown-alt";
/** Set by the Markdown library's web admonition renderer on the box and on its generated title. */
export const MARKDOWN_ADMONITION_TYPE_ATTRIBUTE = "data-enrm-admonition-type";
export const MARKDOWN_ADMONITION_TITLE_ATTRIBUTE = "data-enrm-admonition-title";
/** Set by the Markdown library's web KaTeX renderer on rendered math elements. */
export const MARKDOWN_MATH_SOURCE_ATTRIBUTE = "data-math-source";
export const MARKDOWN_MATH_DISPLAY_ATTRIBUTE = "data-display";
export const KATEX_MATHML_SELECTOR = ".katex-mathml, annotation, annotation-xml";
/**
* Trailing line breaks, with any indentation that followed the last one.
@@ -12,6 +12,7 @@ import {
type NativeScrollEvent,
type NativeSyntheticEvent,
type PressableStateCallbackType,
type ScrollView as NativeScrollView,
} from "react-native";
import {
memo,
@@ -33,7 +34,7 @@ import { ArchivedBadge } from "@/components/archived-badge";
import { StatusIcon } from "@/components/status-icon";
import { useWorkspaceStatus } from "@/workspace-status";
import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
import type { Theme } from "@/styles/theme";
import { SPACING, type Theme } from "@/styles/theme";
import { HighlightedText, type HighlightedTextProps } from "@/components/ui/highlighted-text";
import { findHighlightRanges } from "@/components/ui/highlighted-text-segments";
import { MaterialFileIcon } from "@/components/material-file-icon";
@@ -44,7 +45,9 @@ import {
EditingTextInput as TextInput,
type EditingTextInputHandle,
} from "@/components/ui/text-input";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
import { Button } from "@/components/ui/button";
import { getScrollOffsetToRevealItem } from "@/components/ui/scroll-reveal";
import { ScrollView } from "@/components/ui/scroll-view";
import { Shortcut } from "@/components/ui/shortcut";
import {
IsolatedBottomSheetModal,
@@ -1025,7 +1028,7 @@ export function CommandCenter() {
onKeyDown: handleOverlayKeyDown,
});
const tabOptions = useMemo<SegmentedControlOption<CommandCenterTab>[]>(
const tabOptions = useMemo<CommandCenterTabOption[]>(
() =>
state.tabs.map((tab) => ({
value: tab,
@@ -1035,13 +1038,7 @@ export function CommandCenter() {
[state.tabs, t],
);
const tabs = (
<SegmentedControl
options={tabOptions}
value={state.tab}
onValueChange={state.selectTab}
size="sm"
testID="command-center-tabs"
/>
<CommandCenterTabPills options={tabOptions} value={state.tab} onValueChange={state.selectTab} />
);
const placeholder = t(placeholderKey(state.tab, state.tabs));
@@ -1128,6 +1125,136 @@ export function CommandCenter() {
);
}
interface CommandCenterTabOption {
value: CommandCenterTab;
label: string;
testID: string;
}
function CommandCenterTabPill({
option,
selected,
onSelect,
onLayoutPill,
}: {
option: CommandCenterTabOption;
selected: boolean;
onSelect(tab: CommandCenterTab): void;
onLayoutPill(tab: CommandCenterTab, event: LayoutChangeEvent): void;
}) {
const handlePress = useCallback(() => {
if (!selected) onSelect(option.value);
}, [onSelect, option.value, selected]);
const handleLayout = useCallback(
(event: LayoutChangeEvent) => onLayoutPill(option.value, event),
[onLayoutPill, option.value],
);
const accessibilityState = useMemo(() => ({ selected }), [selected]);
return (
<Button
variant={selected ? "secondary" : "ghost"}
size="sm"
numberOfLines={1}
accessibilityState={accessibilityState}
aria-selected={selected}
testID={option.testID}
onPress={handlePress}
onLayout={handleLayout}
style={styles.tabPill}
>
{option.label}
</Button>
);
}
function CommandCenterTabPills({
options,
value,
onValueChange,
}: {
options: readonly CommandCenterTabOption[];
value: CommandCenterTab;
onValueChange(tab: CommandCenterTab): void;
}) {
const scrollRef = useRef<NativeScrollView>(null);
const viewportWidthRef = useRef(0);
const scrollOffsetRef = useRef(0);
const pillLayoutsRef = useRef<Partial<Record<CommandCenterTab, { x: number; width: number }>>>(
{},
);
const revealTab = useCallback((tab: CommandCenterTab) => {
const layout = pillLayoutsRef.current[tab];
const scroll = scrollRef.current;
const viewportWidth = viewportWidthRef.current;
if (!layout || !scroll || viewportWidth <= 0) return;
const edgeMargin = SPACING[4];
const nextOffset = getScrollOffsetToRevealItem({
currentOffset: scrollOffsetRef.current,
viewportHeight: Math.floor(viewportWidth),
itemTop: Math.max(0, Math.floor(layout.x) - edgeMargin),
itemHeight: Math.ceil(layout.width) + edgeMargin * 2,
});
const clampedOffset = Math.ceil(nextOffset);
if (Math.abs(clampedOffset - scrollOffsetRef.current) < 1) return;
scrollOffsetRef.current = clampedOffset;
scroll.scrollTo({ x: clampedOffset, animated: false });
}, []);
useEffect(() => {
revealTab(value);
}, [revealTab, value]);
const handleViewportLayout = useCallback(
(event: LayoutChangeEvent) => {
viewportWidthRef.current = event.nativeEvent.layout.width;
revealTab(value);
},
[revealTab, value],
);
const handlePillLayout = useCallback(
(tab: CommandCenterTab, event: LayoutChangeEvent) => {
const { x, width } = event.nativeEvent.layout;
pillLayoutsRef.current[tab] = { x, width };
if (tab === value) {
revealTab(tab);
}
},
[revealTab, value],
);
const handleScroll = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
scrollOffsetRef.current = event.nativeEvent.contentOffset.x;
}, []);
return (
<ScrollView
ref={scrollRef}
horizontal
showsHorizontalScrollIndicator={false}
keyboardShouldPersistTaps={KEYBOARD_SHOULD_PERSIST_TAPS}
scrollEventThrottle={16}
onLayout={handleViewportLayout}
onScroll={handleScroll}
style={styles.tabScroll}
testID="command-center-tabs"
>
<View style={styles.tabList}>
{options.map((option) => (
<CommandCenterTabPill
key={option.value}
option={option}
selected={option.value === value}
onSelect={onValueChange}
onLayoutPill={handlePillLayout}
/>
))}
</View>
</ScrollView>
);
}
function FileSearchLoadingIndicator({ loading, label }: { loading: boolean; label: string }) {
return (
<View style={styles.fileSearchStatus} testID="command-center-file-search-status">
@@ -1170,12 +1297,25 @@ const styles = StyleSheet.create((theme) => ({
borderBottomWidth: 1,
borderBottomColor: theme.colors.border,
},
// Below the divider, above the list. The first section label brings its own top gap, so the
// pills sit with equal space above and below. A fixed bar, so switching tabs never moves the
// field or the list.
// Below the divider, above the list. Adds subtle bottom room so pills never sit glued onto
// the first row or section header while keeping the bar fixed across tab switches.
tabBar: {
paddingHorizontal: theme.spacing[4],
paddingTop: COMMAND_CENTER_SECTION_GAP,
paddingBottom: theme.spacing[3],
},
tabScroll: {
flexGrow: 0,
flexShrink: 0,
},
tabList: {
flexDirection: "row",
alignItems: "center",
flexShrink: 0,
gap: theme.spacing[1],
paddingHorizontal: theme.spacing[4],
},
tabPill: {
flexShrink: 0,
},
input: {
fontSize: theme.fontSize.base,
@@ -1,5 +1,9 @@
import { describe, expect, it } from "vitest";
import { buildDirectConnectionUri, normalizeDirectConnectionHost } from "./direct-connection-host";
import {
buildDirectConnectionUri,
normalizeDirectConnectionHost,
parseDirectConnectionPaste,
} from "./direct-connection-host";
const labels = {
hostRequired: "host required",
@@ -57,6 +61,26 @@ describe("buildDirectConnectionUri", () => {
).toBe("tcp://example.test:443?ssl=true&password=secret");
});
it("honors scheme, ssl, and password from a typed URI in Host", () => {
expect(
buildDirectConnectionUri(
{
host: "tcp://secure.example.test:7443?ssl=true&password=example",
port: "6767",
useTls: false,
password: "",
},
labels,
),
).toBe("tcp://secure.example.test:7443?ssl=true&password=example");
expect(
buildDirectConnectionUri(
{ host: "https://myhost.ts.net", port: "6767", useTls: false, password: "" },
labels,
),
).toBe("tcp://myhost.ts.net:443?ssl=true");
});
it.each(["", " ", "tcp://", "http:///path"])("requires a host for %j", (host) => {
expect(() => buildUri(host)).toThrow("host required");
});
@@ -64,5 +88,102 @@ describe("buildDirectConnectionUri", () => {
it("rejects an invalid port", () => {
expect(() => buildUri("100.66.69.36", "70000")).toThrow("invalid port");
expect(() => buildUri("100.66.69.36:0")).toThrow("invalid port");
expect(() => buildUri("[::1]:0x10")).toThrow("invalid port");
expect(() => buildUri("100.66.69.36", "0x10")).toThrow("invalid port");
});
});
describe("parseDirectConnectionPaste", () => {
it.each([
["localhost:6768", { host: "localhost", port: "6768" }],
[" localhost:6768\n", { host: "localhost", port: "6768" }],
["100.91.42.18:6767", { host: "100.91.42.18", port: "6767" }],
["hetzner.tail8a2f.ts.net:6768", { host: "hetzner.tail8a2f.ts.net", port: "6768" }],
["localhost:6768/", { host: "localhost", port: "6768" }],
["localhost:6768/ws", { host: "localhost", port: "6768" }],
["[::1]:6768", { host: "::1", port: "6768" }],
["[fe80::1]:7000/", { host: "fe80::1", port: "7000" }],
["[::1]", { host: "::1" }],
["localhost/", { host: "localhost" }],
["http://localhost:6768", { host: "localhost", port: "6768", useTls: false }],
["http://localhost:6768/", { host: "localhost", port: "6768", useTls: false }],
["http://myhost.ts.net", { host: "myhost.ts.net", port: "80", useTls: false }],
["https://myhost.ts.net:6767", { host: "myhost.ts.net", port: "6767", useTls: true }],
["https://myhost.ts.net:6767/", { host: "myhost.ts.net", port: "6767", useTls: true }],
["HTTPS://MyHost.ts.net", { host: "MyHost.ts.net", port: "443", useTls: true }],
["https://myhost.ts.net/", { host: "myhost.ts.net", port: "443", useTls: true }],
["ws://localhost:6768/ws", { host: "localhost", port: "6768", useTls: false }],
["ws://myhost.ts.net/ws", { host: "myhost.ts.net", port: "80", useTls: false }],
["wss://myhost.ts.net:6767/ws", { host: "myhost.ts.net", port: "6767", useTls: true }],
["wss://myhost.ts.net/ws", { host: "myhost.ts.net", port: "443", useTls: true }],
["wss://[2001:db8::1]:7443/ws", { host: "2001:db8::1", port: "7443", useTls: true }],
["tcp://localhost:6768", { host: "localhost", port: "6768", useTls: false, password: "" }],
[
"tcp://myhost.ts.net:6767?ssl=true",
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "" },
],
[
"tcp://myhost.ts.net:6767?ssl=true&password=a%26b%3Dc+d",
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "a&b=c d" },
],
[
"tcp://[::1]:7000?ssl=true&password=secret",
{ host: "::1", port: "7000", useTls: true, password: "secret" },
],
["tcp://myhost.ts.net", { host: "myhost.ts.net", useTls: false, password: "" }],
["tcp://myhost.ts.net?ssl=true", { host: "myhost.ts.net", useTls: true, password: "" }],
[
"https://myhost.ts.net:6767?password=pw",
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "pw" },
],
[
"https://:my%20pass@myhost.ts.net:6767",
{ host: "myhost.ts.net", port: "6767", useTls: true, password: "my pass" },
],
[
"localhost:6768?ssl=true&password=pw",
{ host: "localhost", port: "6768", useTls: true, password: "pw" },
],
])("extracts fields from %j", (input, expected) => {
expect(parseDirectConnectionPaste(input)).toEqual(expected);
});
it.each([
"",
" ",
"localhost",
"100.91.42.18",
"::1",
"fe80::1",
"2001:db8::1",
"localhost:0",
"localhost:65536",
"localhost:70000",
"localhost:abc",
"localhost:",
"http://localhost:0",
"http://localhost:70000",
"http://localhost:abc",
"http://localhost:",
"tcp://localhost:abc",
"http://",
"https://",
"tcp://",
"http:///path",
":6768",
"[]:6768",
"ftp://example.com:21",
"ssh://user@host:22",
"fe80:abcd",
"my host:6768",
"line1\nlocalhost:6768",
"getpaseo/paseo",
"alice@example.com",
"alice@example.com/",
"relay://relay.paseo.test:443/srv_abc?key=k",
"https://app.paseo.sh/#connect=abc",
"https://app.paseo.sh/#offer=abc",
])("returns null for %j", (input) => {
expect(parseDirectConnectionPaste(input)).toBeNull();
});
});
@@ -19,52 +19,297 @@ export interface NormalizedDirectConnectionHost {
isIpv6: boolean;
}
const SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(\d*))?$/;
const HOST_WITH_PORT_PATTERN = /^([^:]+):(\d+)$/;
export interface ParsedDirectConnectionAddress {
/** Lowercased scheme without `://`, if present (e.g. "tcp", "http", "https", "ws", "wss"). */
scheme: string | null;
host: string;
/** Explicit port text after `:`, if present (`""` when a trailing `:` had no port). */
port: string | null;
isIpv6: boolean;
/** Path suffix starting with `/`, or empty string when omitted. */
path: string;
/** Password from `?password=` (or URL userinfo when query password is absent), if present. */
password: string | null;
/** Explicit `ssl` query flag (`"true"` / `"false"`), or null when omitted. */
sslParam: boolean | null;
}
export interface DirectConnectionPasteFields {
host: string;
port?: string;
useTls?: boolean;
password?: string;
}
const SCHEME_PATTERN = /^([a-z][a-z0-9+.-]*):\/\//i;
const BRACKETED_IPV6_PATTERN = /^\[([^\]]*)\](?::(.*))?$/;
const DIGITS_ONLY_PATTERN = /^\d+$/;
const DIRECT_CONNECTION_SCHEMES = new Set(["tcp", "http", "https", "ws", "wss"]);
export function defaultPortForDirectScheme(scheme: string | null): string | null {
if (scheme === "https" || scheme === "wss") return "443";
if (scheme === "http" || scheme === "ws") return "80";
return null;
}
export function resolveDirectSchemeTls(
scheme: string | null,
sslParam: boolean | null,
): boolean | undefined {
if (scheme === "https" || scheme === "wss") return true;
if (scheme === "http" || scheme === "ws") return false;
if (scheme === "tcp") return sslParam === true;
return sslParam ?? undefined;
}
function decodeUserinfoComponent(value: string): string {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
function parseSslParam(value: string | null): boolean | null {
if (value === "true") return true;
if (value === "false") return false;
return null;
}
function parseValidPortNumber(raw: string): number | null {
if (!DIGITS_ONLY_PATTERN.test(raw)) return null;
const port = Number(raw);
if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
return port;
}
function parseValidPort(raw: string): string | null {
const port = parseValidPortNumber(raw);
return port === null ? null : String(port);
}
function stripUserinfo(
authority: string,
hasScheme: boolean,
): { authority: string; password: string | null } {
const atIndex = hasScheme ? authority.lastIndexOf("@") : -1;
if (atIndex === -1) return { authority, password: null };
const userinfo = authority.slice(0, atIndex);
const hostPort = authority.slice(atIndex + 1);
const colonIndex = userinfo.indexOf(":");
if (colonIndex === -1) return { authority: hostPort, password: null };
const decoded = decodeUserinfoComponent(userinfo.slice(colonIndex + 1));
return { authority: hostPort, password: decoded || null };
}
function splitAuthorityHostPort(authority: string): {
host: string;
port: string | null;
isIpv6: boolean;
} {
const bracketed = BRACKETED_IPV6_PATTERN.exec(authority);
if (bracketed) {
return {
host: bracketed[1] ?? "",
port: bracketed[2] ?? null,
isIpv6: true,
};
}
const parts = authority.split(":");
if (parts.length === 2) {
return { host: parts[0] ?? "", port: parts[1] ?? "", isIpv6: false };
}
return { host: authority, port: null, isIpv6: parts.length > 2 };
}
function hasInvalidPasteHost(host: string): boolean {
return !host || /[\s[\]@]/.test(host);
}
function resolvePastePort(address: ParsedDirectConnectionAddress): string | null | undefined {
if (address.port !== null) return parseValidPort(address.port);
return defaultPortForDirectScheme(address.scheme) ?? undefined;
}
/**
* Lenient split of a direct-connection address or URI into host, port, scheme, and credentials.
* Keeps invalid port text intact so callers can decide whether to carry it as text or reject it.
*/
export function parseDirectConnectionAddress(input: string): ParsedDirectConnectionAddress {
const trimmed = input.trim();
if (!trimmed) {
return {
scheme: null,
host: "",
port: null,
isIpv6: false,
path: "",
password: null,
sslParam: null,
};
}
const schemeMatch = SCHEME_PATTERN.exec(trimmed);
const scheme = schemeMatch ? (schemeMatch[1] ?? "").toLowerCase() : null;
const rest = schemeMatch ? trimmed.slice(schemeMatch[0].length) : trimmed;
const hashIndex = rest.indexOf("#");
const beforeHash = hashIndex === -1 ? rest : rest.slice(0, hashIndex);
const queryIndex = beforeHash.indexOf("?");
const beforeQuery = queryIndex === -1 ? beforeHash : beforeHash.slice(0, queryIndex);
const query = new URLSearchParams(queryIndex === -1 ? "" : beforeHash.slice(queryIndex + 1));
const slashIndex = beforeQuery.indexOf("/");
const rawAuthority = slashIndex === -1 ? beforeQuery : beforeQuery.slice(0, slashIndex);
const path = slashIndex === -1 ? "" : beforeQuery.slice(slashIndex);
const { authority, password: userinfoPassword } = stripUserinfo(rawAuthority, scheme !== null);
const { host, port, isIpv6 } = splitAuthorityHostPort(authority);
return {
scheme,
host,
port,
isIpv6,
path,
password: query.get("password") || userinfoPassword || null,
sslParam: parseSslParam(query.get("ssl")),
};
}
/** The three link formats a daemon prints for pairing: `relay://`, `#connect=`, and `#offer=`. */
export function isPairingLink(input: string): boolean {
const trimmed = input.trim();
return (
trimmed.toLowerCase().startsWith("relay://") ||
trimmed.includes("#connect=") ||
trimmed.includes("#offer=")
);
}
function shouldNormalizeBareHostPaste(
trimmed: string,
address: ParsedDirectConnectionAddress,
): boolean {
const hasOnlyTrailingSlashes = address.path.length > 0 && /^\/+$/.test(address.path);
if (address.path.length > 0 && !hasOnlyTrailingSlashes) return false;
return hasOnlyTrailingSlashes || (address.isIpv6 && trimmed.startsWith("["));
}
/**
* Extracts structured Direct connection form fields from a pasted `host:port`, bracketed IPv6,
* or supported URI (`http`, `https`, `ws`, `wss`, `tcp`). Returns `null` when the text is a plain
* host, bare IPv6, pairing link, unsupported scheme, or contains an invalid explicit port.
*/
export function parseDirectConnectionPaste(input: string): DirectConnectionPasteFields | null {
const trimmed = input.trim();
if (!trimmed || /[\r\n]/.test(trimmed) || isPairingLink(trimmed)) return null;
const address = parseDirectConnectionAddress(trimmed);
if (address.scheme !== null && !DIRECT_CONNECTION_SCHEMES.has(address.scheme)) return null;
if (hasInvalidPasteHost(address.host)) return null;
const port = resolvePastePort(address);
if (port === null) return null;
const useTls = resolveDirectSchemeTls(address.scheme, address.sslParam);
// A pasted `tcp://` URI is a complete Paseo connection string: omitting `?password=` means no
// password and clears any credential left over from a previous host.
const password =
address.scheme === "tcp" ? (address.password ?? "") : (address.password ?? undefined);
if (
port === undefined &&
useTls === undefined &&
password === undefined &&
!shouldNormalizeBareHostPaste(trimmed, address)
) {
return null;
}
return {
host: address.host,
...(port !== undefined ? { port } : {}),
...(useTls !== undefined ? { useTls } : {}),
...(password !== undefined ? { password } : {}),
};
}
export interface ResolvedDirectHostDraft {
host: string;
port: string;
isIpv6: boolean;
useTls: boolean;
password: string;
}
/**
* Resolves a Form draft where Host may still contain a manually typed `host:port` or URI.
* Honors explicit scheme, port, `ssl`, and `password` settings from Host while preserving
* separate form fields for anything Host did not specify.
*/
export function resolveDirectHostDraft(draft: DirectConnectionHostInput): ResolvedDirectHostDraft {
const address = parseDirectConnectionAddress(draft.host);
const explicitPort = address.port !== null && address.port.length > 0 ? address.port : null;
const port = (explicitPort ?? defaultPortForDirectScheme(address.scheme) ?? draft.port).trim();
let useTls = draft.useTls;
if (address.scheme === "https" || address.scheme === "wss") {
useTls = true;
} else if (address.scheme === "http" || address.scheme === "ws") {
useTls = false;
} else if (address.sslParam !== null) {
useTls = address.sslParam;
}
return {
host: address.host,
port,
isIpv6: address.isIpv6,
useTls,
password: address.password ?? draft.password,
};
}
/**
* Users often paste `host:port` or a full URL into the host field.
* Reduce it to a bare host (plus an optional port) before building the URI.
*/
export function normalizeDirectConnectionHost(input: string): NormalizedDirectConnectionHost {
let host = input.trim().replace(SCHEME_PATTERN, "");
const suffixIndex = host.search(/[/?#]/);
if (suffixIndex !== -1) {
host = host.slice(0, suffixIndex);
const address = parseDirectConnectionAddress(input);
if (address.port !== null && !DIGITS_ONLY_PATTERN.test(address.port)) {
if (address.isIpv6 && address.port === "") {
return { host: address.host, port: null, isIpv6: true };
}
if (!address.isIpv6) {
return { host: `${address.host}:${address.port}`, port: null, isIpv6: false };
}
}
const bracketed = BRACKETED_IPV6_PATTERN.exec(host);
if (bracketed) {
return { host: bracketed[1] ?? "", port: bracketed[2] || null, isIpv6: true };
}
const hostWithPort = HOST_WITH_PORT_PATTERN.exec(host);
if (hostWithPort) {
return { host: hostWithPort[1] ?? "", port: hostWithPort[2] ?? null, isIpv6: false };
}
return { host, port: null, isIpv6: host.split(":").length > 2 };
return {
host: address.host,
port: address.port || null,
isIpv6: address.isIpv6,
};
}
export function buildDirectConnectionUri(
draft: DirectConnectionHostInput,
labels: DirectConnectionHostLabels,
): string {
const normalized = normalizeDirectConnectionHost(draft.host);
const port = Number((normalized.port ?? draft.port).trim());
if (!normalized.host) {
const resolved = resolveDirectHostDraft(draft);
if (!resolved.host) {
throw new Error(labels.hostRequired);
}
if (!Number.isInteger(port) || port < 1 || port > 65535) {
const port = parseValidPortNumber(resolved.port);
if (port === null) {
throw new Error(labels.invalidPort);
}
return serializeConnectionUriForStorage({
host: normalized.host,
host: resolved.host,
port,
isIpv6: normalized.isIpv6,
useTls: draft.useTls,
...(draft.password ? { password: draft.password } : {}),
isIpv6: resolved.isIpv6,
useTls: resolved.useTls,
...(resolved.password ? { password: resolved.password } : {}),
});
}
@@ -0,0 +1,535 @@
export interface LineEnd {
contentEnd: number;
nextLineStart: number;
}
export interface BlockquoteStrip {
quoteDepth: number;
offset: number;
}
export interface IndentMeasure {
spaces: number;
offset: number;
}
export interface ListMarkerMatch {
markerEnd: number;
contentIndent: number;
markerChar: string;
}
export interface FenceOpenerMatch {
char: "`" | "~";
length: number;
fenceOffset: number;
indent: number;
info: string;
}
export interface BlockScanState {
listIndents: number[];
listQuoteDepth: number;
inParagraph: boolean;
prevQuoteDepth: number;
inIndentedCode: boolean;
indentedCodeQuoteDepth: number;
indentedCodeMinIndent: number;
}
export type BlockLine =
| { kind: "blank"; quoteDepth: number; afterQuotes: number }
| { kind: "indented-code"; quoteDepth: number; afterQuotes: number }
| {
kind: "fence";
quoteDepth: number;
afterQuotes: number;
fenceOffset: number;
char: "`" | "~";
length: number;
info: string;
maxCloseIndent: number;
contentStripIndent: number;
inList: boolean;
listMinIndent: number;
firstLinePrefix: string;
continuationPrefix: string;
}
| { kind: "text"; quoteDepth: number; afterQuotes: number; containerIndent: number };
export function isWhitespaceChar(ch: string | undefined): boolean {
return ch === " " || ch === "\t" || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v";
}
export function isAsciiPunctuation(ch: string | undefined): boolean {
if (!ch) return false;
const code = ch.charCodeAt(0);
return (
(code >= 0x21 && code <= 0x2f) ||
(code >= 0x3a && code <= 0x40) ||
(code >= 0x5b && code <= 0x60) ||
(code >= 0x7b && code <= 0x7e)
);
}
export function isAsciiAlnum(ch: string | undefined): boolean {
if (!ch) return false;
const code = ch.charCodeAt(0);
return (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
}
export function findLineEnd(source: string, from: number): LineEnd {
let i = from;
while (i < source.length) {
const code = source.charCodeAt(i);
if (code === 10) return { contentEnd: i, nextLineStart: i + 1 };
if (code === 13) {
const next = i + 1 < source.length && source.charCodeAt(i + 1) === 10 ? i + 2 : i + 1;
return { contentEnd: i, nextLineStart: next };
}
i++;
}
return { contentEnd: source.length, nextLineStart: source.length };
}
export function stripBlockquotesAt(source: string, from: number, limit: number): BlockquoteStrip {
let offset = from;
let quoteDepth = 0;
while (offset < limit) {
let spaces = 0;
let cursor = offset;
while (cursor < limit && source[cursor] === " " && spaces < 3) {
cursor++;
spaces++;
}
if (cursor >= limit || source[cursor] !== ">") break;
quoteDepth++;
cursor++;
if (cursor < limit && (source[cursor] === " " || source[cursor] === "\t")) cursor++;
offset = cursor;
}
return { quoteDepth, offset };
}
export function measureIndentAt(source: string, from: number, limit: number): IndentMeasure {
let spaces = 0;
let offset = from;
while (offset < limit) {
const ch = source[offset];
if (ch === " ") {
spaces++;
offset++;
} else if (ch === "\t") {
spaces += 4 - (spaces % 4);
offset++;
} else {
break;
}
}
return { spaces, offset };
}
export function isBlankRange(source: string, from: number, limit: number): boolean {
for (let i = from; i < limit; i++) {
if (source[i] !== " " && source[i] !== "\t") return false;
}
return true;
}
export function isThematicBreakText(trimmed: string): boolean {
return /^(?:([-*_])(?:[ \t]*\1){2,})[ \t]*$/.test(trimmed);
}
function parseListMarkerPrefix(
source: string,
offset: number,
limit: number,
disallowOrderedNonOne: boolean,
): { markerChars: number; after: number; markerChar: string } | null {
const ch = source[offset];
if (ch === "-" || ch === "*" || ch === "+") {
if ((ch === "-" || ch === "*") && isThematicBreakText(source.slice(offset, limit))) {
return null;
}
return { markerChars: 1, after: offset + 1, markerChar: ch };
}
if (ch < "0" || ch > "9") return null;
let cursor = offset;
while (cursor < limit && source[cursor] >= "0" && source[cursor] <= "9" && cursor - offset < 9) {
cursor++;
}
if (cursor >= limit || (source[cursor] !== "." && source[cursor] !== ")")) return null;
if (disallowOrderedNonOne && Number(source.slice(offset, cursor)) !== 1) return null;
return { markerChars: cursor + 1 - offset, after: cursor + 1, markerChar: ch };
}
function measureMarkerSeparator(
source: string,
after: number,
limit: number,
startColumn: number,
): { extraSpaces: number; endPos: number } {
let col = startColumn;
let extraSpaces = 0;
let pos = after;
while (pos < limit) {
const ws = source[pos];
if (ws === " ") {
extraSpaces += 1;
col += 1;
pos++;
} else if (ws === "\t") {
const tabWidth = 4 - (col % 4);
extraSpaces += tabWidth;
col += tabWidth;
pos++;
} else {
break;
}
}
return { extraSpaces, endPos: pos };
}
export function matchListMarkerAt(
source: string,
from: number,
limit: number,
maxIndent = 3,
options?: { allowEmpty?: boolean; disallowOrderedNonOne?: boolean },
): ListMarkerMatch | null {
const { spaces, offset } = measureIndentAt(source, from, limit);
if (spaces > maxIndent || offset >= limit) return null;
const prefix = parseListMarkerPrefix(
source,
offset,
limit,
options?.disallowOrderedNonOne ?? false,
);
if (!prefix) return null;
const { extraSpaces, endPos } = measureMarkerSeparator(
source,
prefix.after,
limit,
spaces + prefix.markerChars,
);
if (extraSpaces === 0) {
if (endPos === limit && options?.allowEmpty) {
return {
markerEnd: endPos,
contentIndent: spaces + prefix.markerChars + 1,
markerChar: prefix.markerChar,
};
}
return null;
}
// CommonMark §5.2: >=5 spaces after a marker keeps 4+ spaces as an indented code block.
const consumed = extraSpaces >= 5 ? 1 : extraSpaces;
const markerEnd = extraSpaces >= 5 ? prefix.after + 1 : endPos;
return {
markerEnd,
contentIndent: spaces + prefix.markerChars + consumed,
markerChar: prefix.markerChar,
};
}
export function parseFenceOpenerAt(
source: string,
from: number,
limit: number,
maxIndent: number,
): FenceOpenerMatch | null {
const { spaces, offset } = measureIndentAt(source, from, limit);
if (spaces > maxIndent || offset >= limit) return null;
const ch = source[offset];
if (ch !== "`" && ch !== "~") return null;
let cursor = offset;
while (cursor < limit && source[cursor] === ch) cursor++;
const length = cursor - offset;
if (length < 3) return null;
const info = source.slice(cursor, limit);
if (ch === "`" && info.includes("`")) return null;
return { char: ch, length, fenceOffset: offset, indent: spaces, info };
}
export function isClosingFenceAt(
source: string,
from: number,
limit: number,
maxIndent: number,
char: "`" | "~",
minLength: number,
): boolean {
const { spaces, offset } = measureIndentAt(source, from, limit);
if (spaces > maxIndent || offset >= limit || source[offset] !== char) return false;
let cursor = offset;
while (cursor < limit && source[cursor] === char) cursor++;
if (cursor - offset < minLength) return false;
while (cursor < limit) {
if (source[cursor] !== " " && source[cursor] !== "\t") return false;
cursor++;
}
return true;
}
export function checkFenceContainerExit(
source: string,
lineStart: number,
contentEnd: number,
openQuoteDepth: number,
listMinIndent: number,
): { exited: boolean; quoteDepth: number; afterQuotes: number } {
const { quoteDepth, offset: afterQuotes } = stripBlockquotesAt(source, lineStart, contentEnd);
if (quoteDepth < openQuoteDepth) {
return { exited: true, quoteDepth, afterQuotes };
}
if (
listMinIndent > 0 &&
quoteDepth === openQuoteDepth &&
!isBlankRange(source, afterQuotes, contentEnd) &&
measureIndentAt(source, afterQuotes, contentEnd).spaces < listMinIndent
) {
return { exited: true, quoteDepth, afterQuotes };
}
return { exited: false, quoteDepth, afterQuotes };
}
export function createBlockScanState(): BlockScanState {
return {
listIndents: [],
listQuoteDepth: 0,
inParagraph: false,
prevQuoteDepth: 0,
inIndentedCode: false,
indentedCodeQuoteDepth: 0,
indentedCodeMinIndent: 0,
};
}
function syncListContainer(state: BlockScanState, quoteDepth: number, spaces: number): number {
if (quoteDepth < state.listQuoteDepth) {
state.listIndents.length = 0;
state.listQuoteDepth = quoteDepth;
}
if (quoteDepth !== state.listQuoteDepth) return 0;
while (state.listIndents.length > 0 && spaces < state.listIndents[state.listIndents.length - 1]) {
state.listIndents.pop();
}
return state.listIndents.length > 0 ? state.listIndents[state.listIndents.length - 1] : 0;
}
function peelLineListMarkers(
state: BlockScanState,
source: string,
afterQuotes: number,
contentEnd: number,
quoteDepth: number,
initialIndent: number,
): { cursor: number; containerIndent: number; peeledList: boolean } {
let cursor = afterQuotes;
let containerIndent = initialIndent;
let peeledList = false;
let marker = matchListMarkerAt(source, cursor, contentEnd, containerIndent + 3, {
allowEmpty: !state.inParagraph,
disallowOrderedNonOne: state.inParagraph,
});
while (marker) {
const markerBase = cursor === afterQuotes ? 0 : containerIndent;
const totalIndent = markerBase + marker.contentIndent;
state.listIndents.push(totalIndent);
state.listQuoteDepth = quoteDepth;
containerIndent = totalIndent;
cursor = marker.markerEnd;
peeledList = true;
marker = matchListMarkerAt(source, cursor, contentEnd, 3, { allowEmpty: true });
}
return { cursor, containerIndent, peeledList };
}
function startIndentedCode(
state: BlockScanState,
quoteDepth: number,
afterQuotes: number,
containerIndent: number,
): BlockLine {
state.inIndentedCode = true;
state.indentedCodeQuoteDepth = quoteDepth;
state.indentedCodeMinIndent = containerIndent + 4;
state.prevQuoteDepth = quoteDepth;
return { kind: "indented-code", quoteDepth, afterQuotes };
}
function isContinuationIndentedCode(
state: BlockScanState,
quoteDepth: number,
spaces: number,
): boolean {
if (!state.inIndentedCode) return false;
if (quoteDepth === state.indentedCodeQuoteDepth && spaces >= state.indentedCodeMinIndent) {
return true;
}
state.inIndentedCode = false;
return false;
}
function classifyBlankBlockLine(
state: BlockScanState,
quoteDepth: number,
afterQuotes: number,
): BlockLine {
state.inParagraph = false;
if (quoteDepth < state.listQuoteDepth) {
state.listIndents.length = 0;
state.listQuoteDepth = quoteDepth;
}
if (state.inIndentedCode && quoteDepth < state.indentedCodeQuoteDepth) {
state.inIndentedCode = false;
}
return { kind: "blank", quoteDepth, afterQuotes };
}
function classifyTextBlockLine(
state: BlockScanState,
source: string,
cursor: number,
contentEnd: number,
quoteDepth: number,
afterQuotes: number,
containerIndent: number,
peeledList: boolean,
): BlockLine {
const { spaces: trimmedSpaces, offset: trimmedOffset } = measureIndentAt(
source,
cursor,
contentEnd,
);
const relSpaces = peeledList ? trimmedSpaces : trimmedSpaces - containerIndent;
const trimmed = source.slice(trimmedOffset, contentEnd);
const endsParagraph =
relSpaces <= 3 &&
(/^#{1,6}(?:[ \t]|$)/.test(trimmed) ||
isThematicBreakText(trimmed) ||
(state.inParagraph && !peeledList && /^(?:-+|=+)[ \t]*$/.test(trimmed)));
state.inParagraph = !endsParagraph;
state.prevQuoteDepth = quoteDepth;
return { kind: "text", quoteDepth, afterQuotes, containerIndent };
}
function buildFenceBlockLine(
state: BlockScanState,
source: string,
lineStart: number,
afterQuotes: number,
quoteDepth: number,
containerIndent: number,
peeledList: boolean,
opener: FenceOpenerMatch,
): BlockLine {
state.inParagraph = false;
state.prevQuoteDepth = quoteDepth;
const quotePrefix = source.slice(lineStart, afterQuotes);
const contentStripIndent = peeledList ? containerIndent + opener.indent : opener.indent;
const inList = quoteDepth === state.listQuoteDepth && state.listIndents.length > 0;
return {
kind: "fence",
quoteDepth,
afterQuotes,
fenceOffset: opener.fenceOffset,
char: opener.char,
length: opener.length,
info: opener.info,
maxCloseIndent: containerIndent + 3,
contentStripIndent,
inList,
listMinIndent: inList ? containerIndent : 0,
firstLinePrefix: source.slice(lineStart, opener.fenceOffset),
continuationPrefix: `${quotePrefix}${" ".repeat(contentStripIndent)}`,
};
}
/**
* Classify one line in CommonMark block order (quotes -> blank -> indented code ->
* list markers -> fenced code -> ATX/Setext/thematic-break -> paragraph text) so math
* scanners skip nested-list code fences and indented code blocks identically to md4c.
*/
export function classifyBlockLine(
state: BlockScanState,
source: string,
lineStart: number,
contentEnd: number,
): BlockLine {
const { quoteDepth, offset: afterQuotes } = stripBlockquotesAt(source, lineStart, contentEnd);
if (isBlankRange(source, afterQuotes, contentEnd)) {
return classifyBlankBlockLine(state, quoteDepth, afterQuotes);
}
if (quoteDepth > state.prevQuoteDepth) {
state.inParagraph = false;
state.inIndentedCode = false;
}
const { spaces } = measureIndentAt(source, afterQuotes, contentEnd);
if (isContinuationIndentedCode(state, quoteDepth, spaces)) {
state.prevQuoteDepth = quoteDepth;
return { kind: "indented-code", quoteDepth, afterQuotes };
}
const baseIndent = syncListContainer(state, quoteDepth, spaces);
if (!state.inParagraph && spaces >= baseIndent + 4) {
return startIndentedCode(state, quoteDepth, afterQuotes, baseIndent);
}
const { cursor, containerIndent, peeledList } = peelLineListMarkers(
state,
source,
afterQuotes,
contentEnd,
quoteDepth,
baseIndent,
);
if (peeledList) {
state.inParagraph = false;
const afterMarker = measureIndentAt(source, cursor, contentEnd);
if (afterMarker.offset < contentEnd && afterMarker.spaces >= 4) {
return startIndentedCode(state, quoteDepth, afterQuotes, containerIndent);
}
if (isBlankRange(source, cursor, contentEnd)) {
state.prevQuoteDepth = quoteDepth;
return { kind: "text", quoteDepth, afterQuotes: cursor, containerIndent };
}
}
const opener = parseFenceOpenerAt(
source,
cursor,
contentEnd,
peeledList ? 3 : containerIndent + 3,
);
if (opener) {
return buildFenceBlockLine(
state,
source,
lineStart,
afterQuotes,
quoteDepth,
containerIndent,
peeledList,
opener,
);
}
return classifyTextBlockLine(
state,
source,
cursor,
contentEnd,
quoteDepth,
afterQuotes,
containerIndent,
peeledList,
);
}
+21 -2
View File
@@ -4,6 +4,7 @@ import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
import { gfmTable } from "micromark-extension-gfm-table";
import { decodeString } from "micromark-util-decode-string";
import type { Nodes } from "mdast";
import { isOffsetInRanges, scanMarkdownMath, type MathRange } from "./math";
const ATTRIBUTE = String.raw`\s+[A-Za-z_:][\w.:-]*(?:\s*=\s*(?:[^\s"'=<>\x60]+|'[^']*'|"[^"]*"))?`;
const TAG = String.raw`<(?:[A-Za-z][A-Za-z0-9-]*(?:${ATTRIBUTE})*\s*\/?|\/[A-Za-z][A-Za-z0-9-]*\s*)>`;
@@ -55,12 +56,14 @@ export function normalizeMarkdownHtml(source: string): string {
} else if ("children" in node) node.children.forEach(protectCode);
}
protectCode(tree);
const mathRanges = scanMarkdownMath(source);
const protectedRanges = mergeRanges(codeRanges, mathRanges);
// Only `<br>` reads these, so a source without one skips the extra parse.
const tableRanges = /<br/i.test(source) ? collectTableRanges(source, codeRanges) : [];
const tableRanges = /<br/i.test(source) ? collectTableRanges(source, protectedRanges) : [];
const links: (string | undefined)[] = [];
let previousTag: { name: string; end: number } | null = null;
const convert = (raw: string, offset: number): string => {
if (codeRanges.some(({ start, end }) => offset >= start && offset < end)) return raw;
if (isOffsetInRanges(offset, protectedRanges)) return raw;
if (raw.startsWith("<!--")) return "";
const summary = /^<summary\b[^>]*>([\s\S]*?)<\/summary\s*>$/i.exec(raw);
if (summary) {
@@ -261,3 +264,19 @@ function collectTableRanges(
);
return tableRanges;
}
function mergeRanges(a: readonly MathRange[], b: readonly MathRange[]): MathRange[] {
if (a.length === 0 && b.length === 0) return [];
const sorted = [...a, ...b].sort((left, right) => left.start - right.start);
const merged: MathRange[] = [{ ...sorted[0] }];
for (let i = 1; i < sorted.length; i++) {
const current = sorted[i];
const last = merged[merged.length - 1];
if (current.start <= last.end) {
if (current.end > last.end) last.end = current.end;
} else {
merged.push({ ...current });
}
}
return merged;
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,277 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { I18nextProvider } from "react-i18next";
import {
EnrichedMarkdownText,
getLoadedKaTeX,
preloadMarkdownParser,
registerKaTeXStyleLoader,
} from "react-native-enriched-markdown";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { applyRootUiFont } from "@/appearance/apply-root-font.web";
import { ToastApiProvider } from "@/contexts/toast-api-context";
import { i18n } from "@/i18n/i18next";
import { darkTheme, lightTheme } from "@/styles/theme";
import { ensureKaTeXStyles } from "./katex-styles.web";
import { MarkdownRenderer } from "./renderer";
import { createMarkdownStyles } from "./styles";
import { WEB_RENDERERS } from "./renderers.web";
let root: Root;
let container: HTMLDivElement;
const toast = { show: () => () => {}, copied: () => {}, error: () => {} };
const queryClient = new QueryClient();
const MATH_FLAGS = { latexMath: true, admonitions: true };
function wrapProviders(node: React.ReactNode) {
return (
<QueryClientProvider client={queryClient}>
<I18nextProvider i18n={i18n}>
<ToastApiProvider api={toast}>{node}</ToastApiProvider>
</I18nextProvider>
</QueryClientProvider>
);
}
beforeEach(async () => {
await i18n.changeLanguage("en");
await preloadMarkdownParser();
container = document.createElement("div");
container.id = "root";
document.body.append(container);
root = createRoot(container);
});
afterEach(() => {
flushSync(() => root.unmount());
container.remove();
document.getElementById("paseo-ui-font")?.remove();
document.documentElement.style.removeProperty("--paseo-ui-font");
});
describe("web KaTeX math rendering", () => {
it("does not load KaTeX when rendering prose without math", async () => {
expect(getLoadedKaTeX()).toBeNull();
flushSync(() => {
root.render(
wrapProviders(
<MarkdownRenderer text="Costs $5 and $10, or $100/mo, with $PATH and \[1, 2\]." />,
),
);
});
await new Promise((resolve) => setTimeout(resolve, 40));
expect(getLoadedKaTeX()).toBeNull();
expect(container.querySelector('[role="math"]')).toBeNull();
expect(container.textContent).toContain("Costs $5 and $10, or $100/mo");
expect(container.textContent).toContain("$PATH");
});
it("falls back to raw LaTeX when stylesheet loading fails and recovers on retry", async () => {
let shouldFail = true;
registerKaTeXStyleLoader(async () => {
if (shouldFail) throw new Error("Simulated KaTeX CSS chunk failure");
ensureKaTeXStyles();
});
try {
flushSync(() => {
root.render(wrapProviders(<MarkdownRenderer text="Inline $x^2 + 1$ and $$y^2$$" />));
});
await vi.waitFor(() => {
const mathNodes = container.querySelectorAll('[role="math"]');
expect(mathNodes.length).toBe(2);
});
await new Promise((resolve) => setTimeout(resolve, 40));
expect(getLoadedKaTeX()).toBeNull();
expect(container.querySelector('[role="math"] .katex')).toBeNull();
expect(container.textContent).toContain("$x^2 + 1$");
expect(container.textContent).toContain("$$y^2$$");
shouldFail = false;
flushSync(() => {
root.render(wrapProviders(<MarkdownRenderer text="Recovered $x^2 + 1$ and $$y^2$$" />));
});
await vi.waitFor(() => {
expect(container.querySelectorAll('[role="math"] .katex-html').length).toBe(2);
});
expect(getLoadedKaTeX()).not.toBeNull();
expect(document.getElementById("paseo-katex-css")).not.toBeNull();
} finally {
registerKaTeXStyleLoader(() => {
ensureKaTeXStyles();
});
}
});
it("lazily loads KaTeX and .woff2-only CSS for math, renders all 5 syntaxes, and renders synchronously on second mount", async () => {
applyRootUiFont("'Custom UI Font', sans-serif");
const markdown = [
"Inline $E = mc^2$ and \\(a^2 + b^2 = c^2\\).",
"",
"$$x^2 + y^2 = z^2$$",
"",
"\\[\\int_0^1 x^2\\,dx\\]",
"",
"```math",
"\\sum_{i=1}^n i",
"```",
].join("\n");
flushSync(() => {
root.render(wrapProviders(<MarkdownRenderer text={markdown} />));
});
await vi.waitFor(() => {
expect(container.querySelectorAll('[role="math"] .katex').length).toBe(5);
});
expect(getLoadedKaTeX()).not.toBeNull();
const styleEl = document.getElementById("paseo-katex-css");
expect(styleEl).not.toBeNull();
const css = styleEl?.textContent ?? "";
expect(css).toContain(".woff2");
expect(css).not.toContain('.woff")');
expect(css).not.toContain('.ttf")');
const mathNodes = Array.from(container.querySelectorAll<HTMLElement>('[role="math"]'));
expect(mathNodes.map((el) => el.dataset.display)).toEqual([
"inline",
"inline",
"block",
"block",
"block",
]);
expect(mathNodes[0]?.dataset.mathSource).toBe("$E = mc^2$");
expect(mathNodes[2]?.dataset.mathSource).toBe("$$\nx^2 + y^2 = z^2\n$$");
expect(mathNodes[0]?.querySelector(".katex-mathml")).not.toBeNull();
expect(mathNodes[0]?.querySelector(".katex-html")).not.toBeNull();
// KaTeX font is preserved even when applyRootUiFont is active on #root.
const mathInner = mathNodes[0]!.querySelector<HTMLElement>(".katex")!;
expect(getComputedStyle(mathInner).fontFamily).toContain("KaTeX_Main");
// Second mount renders synchronously from module cache without raw-TeX flash.
const secondHost = document.createElement("div");
document.body.append(secondHost);
const secondRoot = createRoot(secondHost);
try {
flushSync(() => {
secondRoot.render(
wrapProviders(
<EnrichedMarkdownText
markdown="Instant $x + 1$"
flavor="github"
md4cFlags={MATH_FLAGS}
renderers={WEB_RENDERERS}
/>,
),
);
});
// Immediately available after synchronous flushSync without waiting for timers.
expect(secondHost.querySelector('[role="math"] .katex')).not.toBeNull();
} finally {
flushSync(() => secondRoot.unmount());
secondHost.remove();
}
});
it.each([
["light", lightTheme],
["dark", darkTheme],
] as const)(
"renders display and inline math cleanly in %s theme with horizontal scroll",
async (_name, theme) => {
const { markdownStyle } = createMarkdownStyles(theme, { blockGap: 16 });
const wideEquation = `$$${Array.from({ length: 12 }, (_, i) => `x_{${i}}`).join(" + ")}$$`;
flushSync(() => {
root.render(
wrapProviders(
<EnrichedMarkdownText
markdown={`Inline $x$ and:\n\n${wideEquation}`}
markdownStyle={markdownStyle}
flavor="github"
md4cFlags={MATH_FLAGS}
renderers={WEB_RENDERERS}
/>,
),
);
});
await vi.waitFor(() => {
expect(container.querySelectorAll('[role="math"] .katex').length).toBe(2);
});
const blockMath = container.querySelector<HTMLElement>(
'[role="math"][data-display="block"]',
)!;
expect(blockMath.style.backgroundColor).toBe("transparent");
expect(blockMath.style.overflowX).toBe("auto");
expect(blockMath.style.textAlign).toBe("center");
},
);
it("renders accurate formula output across inline/display mode and repeated renders past cache turnover", async () => {
flushSync(() => {
root.render(
wrapProviders(
<MarkdownRenderer text={"Inline $x_0$ vs display:\n\n$$x_0$$\n\nRepeated $x_0$."} />,
),
);
});
await vi.waitFor(() => {
expect(container.querySelectorAll('[role="math"] .katex-html').length).toBe(3);
});
const htmlText = (el: HTMLElement | undefined) =>
el?.querySelector(".katex-html")?.textContent?.replace(/\u200B/g, "");
const annotationText = (el: HTMLElement | undefined) =>
el?.querySelector(".katex-mathml annotation")?.textContent;
const initialMath = Array.from(container.querySelectorAll<HTMLElement>('[role="math"]'));
expect(initialMath.map((el) => el.dataset.display)).toEqual(["inline", "block", "inline"]);
expect(initialMath[0]?.querySelector(".katex-display")).toBeNull();
expect(initialMath[1]?.querySelector(".katex-display")).not.toBeNull();
expect(htmlText(initialMath[0])).toBe("x0");
expect(htmlText(initialMath[1])).toBe("x0");
expect(htmlText(initialMath[2])).toBe("x0");
expect(annotationText(initialMath[0])).toBe("x_0");
expect(annotationText(initialMath[1])).toBe("x_0");
// Exceed the 256-entry render cache and re-render earlier formulas to verify evicted entries stay accurate.
const manyFormulas = Array.from({ length: 265 }, (_, i) => `$a_{${i}}$`).join(" ");
flushSync(() => {
root.render(
wrapProviders(<MarkdownRenderer text={`${manyFormulas} $x_0$ $$x_0$$ $a_{0}$`} />),
);
});
await vi.waitFor(() => {
expect(container.querySelectorAll('[role="math"] .katex-html').length).toBe(268);
});
const rendered = Array.from(container.querySelectorAll<HTMLElement>('[role="math"]'));
expect(htmlText(rendered[0])).toBe("a0");
expect(annotationText(rendered[0])).toBe("a_{0}");
expect(htmlText(rendered[264])).toBe("a264");
expect(annotationText(rendered[264])).toBe("a_{264}");
expect(rendered[265]?.dataset.display).toBe("inline");
expect(htmlText(rendered[265])).toBe("x0");
expect(rendered[266]?.dataset.display).toBe("block");
expect(htmlText(rendered[266])).toBe("x0");
expect(rendered[267]?.dataset.mathSource).toBe("$a_{0}$");
expect(htmlText(rendered[267])).toBe("a0");
expect(annotationText(rendered[267])).toBe("a_{0}");
});
});
@@ -0,0 +1,437 @@
import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown";
import type { ASTNode } from "react-native-enriched-markdown/src/web/types";
import { describe, expect, it } from "vitest";
import { normalizeMarkdownHtml } from "./html";
import { adaptMarkdownMath, findBlockMathSpans, scanMarkdownMath } from "./math";
import { prepareMarkdownSource } from "./source";
const MATH_FLAGS = { latexMath: true, hardSoftBreaks: true, admonitions: true };
const NO_MATH_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true };
function collectNodes(node: ASTNode, result: ASTNode[] = []): ASTNode[] {
result.push(node);
node.children?.forEach((child) => collectNodes(child, result));
return result;
}
function collectMathNodes(ast: ASTNode): { type: string; content: string }[] {
return collectNodes(ast)
.filter((node) => node.type === "LatexMathInline" || node.type === "LatexMathDisplay")
.map((node) => ({
type: node.type,
content: (node.children ?? []).map((child) => child.content ?? "").join(""),
}));
}
function collectText(node: ASTNode): string {
if (node.type === "LatexMathInline" || node.type === "LatexMathDisplay") return "";
if (node.type === "Text") return node.content ?? "";
return (node.children ?? []).map(collectText).join("");
}
describe("math source adaptation — currency, shell, regex, and literal prose", () => {
it.each([
["Costs $5 and $10.", "Costs $5 and $10."],
["Costs $5 and 10$", "Costs $5 and 10$"],
["From $100/mo to $200/mo", "From $100/mo to $200/mo"],
["Costs $100/mo (or 200$)", "Costs $100/mo (or 200$)"],
["Total: $5 ($)", "Total: $5 ($)"],
["Costs $5. Run $ ls", "Costs $5. Run $ ls"],
["Pay $10 and get $ back", "Pay $10 and get $ back"],
["I have $ 5 and $ 10", "I have $ 5 and $ 10"],
["Price is US$5 or CA$10", "Price is US$5 or CA$10"],
["Set $PATH and $HOME", "Set $PATH and $HOME"],
["Use $PATH with /^foo$/", "Use $PATH with /^foo$/"],
["Save $5 with sed s/foo$/bar/", "Save $5 with sed s/foo$/bar/"],
["Check $HOME then foo$", "Check $HOME then foo$"],
["$3$4", "$3$4"],
["Costs $50k or $10M or $2B today", "Costs $50k or $10M or $2B today"],
["Costs $5! Or $10)?", "Costs $5! Or $10)?"],
["Escaped \\$x\\$", "Escaped $x$"],
["See citation \\[1, 2\\]", "See citation [1, 2]"],
])(
"keeps %s literal when parsed with latexMath: true and latexMath: false",
async (source, expectedText) => {
const rendered = prepareMarkdownSource(source).render();
for (const flags of [MATH_FLAGS, NO_MATH_FLAGS]) {
const ast = await parseMarkdown(rendered, flags);
expect(collectMathNodes(ast)).toEqual([]);
expect(collectText(ast)).toBe(expectedText);
}
},
);
it("leaves inline code and latex/tex code fences literal", async () => {
const inlineCode = "Use `$x$` and ``$$y$$`` and `\\(z\\)`";
const preparedInline = prepareMarkdownSource(inlineCode).render();
expect(preparedInline).toBe(inlineCode);
const inlineAst = await parseMarkdown(preparedInline, MATH_FLAGS);
expect(collectMathNodes(inlineAst)).toEqual([]);
for (const lang of ["latex", "tex"]) {
const fence = `\`\`\`${lang}\n\\documentclass{article}\n$x = 1$\n\`\`\``;
const preparedFence = prepareMarkdownSource(fence).render();
expect(preparedFence).toBe(fence);
const fenceAst = await parseMarkdown(preparedFence, MATH_FLAGS);
expect(collectMathNodes(fenceAst)).toEqual([]);
expect(collectNodes(fenceAst).some((node) => node.type === "CodeBlock")).toBe(true);
}
});
it("preserves list-nested fenced code blocks containing blank lines, $, \\(, and $$ verbatim", async () => {
const nested = [
"1. Install:",
" - Run this:",
"",
" ```bash",
' export PATH="$HOME/bin:$PATH"',
"",
" grep -E '\\(foo\\)' log.txt",
" ```",
].join("\n");
const renderedNested = prepareMarkdownSource(nested).render();
expect(renderedNested).toBe(nested);
const nestedAst = await parseMarkdown(renderedNested, MATH_FLAGS);
expect(collectMathNodes(nestedAst)).toEqual([]);
const nestedCodeBlock = collectNodes(nestedAst).find((node) => node.type === "CodeBlock");
expect(nestedCodeBlock).toBeDefined();
expect(collectText(nestedCodeBlock!)).toBe(
"export PATH=\"$HOME/bin:$PATH\"\n\ngrep -E '\\(foo\\)' log.txt\n",
);
const deepNested = [
"1. Outer:",
" 1. Inner:",
" - Leaf:",
"",
" ```sh",
" echo $HOME",
"",
" printf '%s\\n' '\\(a+b\\)' '$$x^2$$'",
" ```",
].join("\n");
const renderedDeep = prepareMarkdownSource(deepNested).render();
expect(renderedDeep).toBe(deepNested);
const deepAst = await parseMarkdown(renderedDeep, MATH_FLAGS);
expect(collectMathNodes(deepAst)).toEqual([]);
const deepCodeBlock = collectNodes(deepAst).find((node) => node.type === "CodeBlock");
expect(deepCodeBlock).toBeDefined();
expect(collectText(deepCodeBlock!)).toBe(
"echo $HOME\n\nprintf '%s\\n' '\\(a+b\\)' '$$x^2$$'\n",
);
expect(scanMarkdownMath(deepNested)).toEqual([]);
expect(findBlockMathSpans(deepNested)).toEqual([]);
});
it("preserves CommonMark 4-space and tab indented code blocks verbatim", async () => {
const atStart = [
' export PATH="$HOME/bin:$PATH"',
" grep -E '\\(foo\\)' log.txt",
" echo $$x^2$$",
].join("\n");
const renderedStart = prepareMarkdownSource(atStart).render();
expect(renderedStart).toBe(atStart);
const startAst = await parseMarkdown(renderedStart, MATH_FLAGS);
expect(collectMathNodes(startAst)).toEqual([]);
const startCode = collectNodes(startAst).find((node) => node.type === "CodeBlock");
expect(startCode).toBeDefined();
expect(collectText(startCode!)).toBe(
"export PATH=\"$HOME/bin:$PATH\"\ngrep -E '\\(foo\\)' log.txt\necho $$x^2$$\n",
);
const afterBlank = [
"Run this:",
"",
" echo $HOME",
" echo \\(foo\\)",
" echo $$x^2$$",
"",
"\techo $USER",
].join("\n");
const renderedAfterBlank = prepareMarkdownSource(afterBlank).render();
expect(renderedAfterBlank).toBe(afterBlank);
const afterBlankAst = await parseMarkdown(renderedAfterBlank, MATH_FLAGS);
expect(collectMathNodes(afterBlankAst)).toEqual([]);
const afterBlankCodes = collectNodes(afterBlankAst).filter((node) => node.type === "CodeBlock");
expect(afterBlankCodes).toHaveLength(1);
expect(collectText(afterBlankCodes[0]!)).toBe(
"echo $HOME\necho \\(foo\\)\necho $$x^2$$\n\necho $USER\n",
);
expect(scanMarkdownMath(afterBlank)).toEqual([]);
expect(findBlockMathSpans(afterBlank)).toEqual([]);
});
it("preserves later non-math fences after prose", async () => {
const source = "Intro.\n\n~~~sh\necho $PATH\n~~~";
const rendered = prepareMarkdownSource(source).render();
expect(rendered).toBe(source);
const ast = await parseMarkdown(rendered, MATH_FLAGS);
expect(collectMathNodes(ast)).toEqual([]);
const codeBlock = collectNodes(ast).find((node) => node.type === "CodeBlock");
expect(collectText(codeBlock!)).toBe("echo $PATH\n");
});
it("exits an unclosed list-nested fence when the enclosing list ends and adapts later math", async () => {
const withBlank = "- ~~~sh\n echo ok\n\nOutside \\(x+1\\).";
const renderedWithBlank = prepareMarkdownSource(withBlank).render();
expect(renderedWithBlank).toBe("- ~~~sh\n echo ok\n\nOutside $x+1$.");
const astWithBlank = await parseMarkdown(renderedWithBlank, MATH_FLAGS);
expect(collectMathNodes(astWithBlank)).toEqual([{ type: "LatexMathInline", content: "x+1" }]);
const noBlank = "- ~~~sh\n echo ok\nOutside \\(x+1\\).";
const astRaw = await parseMarkdown(noBlank, MATH_FLAGS);
// Verify md4c closes the list fence immediately on unindented non-blank lines too.
expect(collectNodes(astRaw).some((node) => node.type === "CodeBlock")).toBe(true);
const renderedNoBlank = prepareMarkdownSource(noBlank).render();
const astNoBlank = await parseMarkdown(renderedNoBlank, MATH_FLAGS);
expect(collectMathNodes(astNoBlank)).toEqual([{ type: "LatexMathInline", content: "x+1" }]);
});
it("ignores escaped \\\\( and \\\\[ and HTML comments", async () => {
const source = "Literal \\\\(x\\\\) and \\\\[y\\\\] and <!-- $hidden$ -->";
const rendered = prepareMarkdownSource(source).render();
const ast = await parseMarkdown(rendered, MATH_FLAGS);
expect(collectMathNodes(ast)).toEqual([]);
expect(collectText(ast)).toContain("\\(x\\)");
expect(collectText(ast)).toContain("\\[y\\]");
});
it("protects <autolinks> containing dollar signs", async () => {
const source = "Visit <https://example.com/$5> and pay $10";
const rendered = prepareMarkdownSource(source).render();
expect(rendered).toContain("<https://example.com/$5>");
const ast = await parseMarkdown(rendered, MATH_FLAGS);
expect(collectMathNodes(ast)).toEqual([]);
const link = collectNodes(ast).find((node) => node.type === "Link");
expect(link?.attributes?.url).toBe("https://example.com/$5");
});
});
describe("math source adaptation — valid inline and display math", () => {
it.each([
["$x$", "x"],
["$a_i$", "a_i"],
["$E = mc^2$", "E = mc^2"],
["$2^k$", "2^k"],
["$3x + 1$", "3x + 1"],
["$0.5\\theta$", "0.5\\theta"],
["$1/2$", "1/2"],
["$5+2$", "5+2"],
["$10 \\times 20$", "10 \\times 20"],
["$\\theta \\in [0.5, 1.0]$", "\\theta \\in [0.5, 1.0]"],
["$k$-means", "k"],
["公式$x=1$的值", "x=1"],
["\\(a^2 + b^2 = c^2\\)", "a^2 + b^2 = c^2"],
["$x < y$ and $a > b$", "x < y"],
["$a < b > c$", "a < b > c"],
["Paragraph line\n with 4-space indented continuation $x$", "x"],
])("parses inline math %s through md4c", async (source, firstContent) => {
const rendered = prepareMarkdownSource(source).render();
const ast = await parseMarkdown(rendered, MATH_FLAGS);
const mathNodes = collectMathNodes(ast);
expect(mathNodes.length).toBeGreaterThanOrEqual(1);
expect(mathNodes[0]).toMatchObject({
type: "LatexMathInline",
content: firstContent,
});
});
it("parses both $x < y$ and $a > b$ without HTML mangling", async () => {
const source = "$x < y$ and $a > b$";
const ast = await parseMarkdown(prepareMarkdownSource(source).render(), MATH_FLAGS);
expect(collectMathNodes(ast)).toEqual([
{ type: "LatexMathInline", content: "x < y" },
{ type: "LatexMathInline", content: "a > b" },
]);
});
it("inserts hair space around CJK-flanked math and preserves surrounding CJK text", async () => {
const source = "公式$x=1$的值";
const rendered = prepareMarkdownSource(source).render();
expect(rendered).toBe("公式\u200A$x=1$\u200A的值");
const ast = await parseMarkdown(rendered, MATH_FLAGS);
expect(collectMathNodes(ast)).toEqual([{ type: "LatexMathInline", content: "x=1" }]);
expect(collectText(ast)).toBe("公式\u200A\u200A的值");
});
it("escapes GFM table pipes inside math without splitting columns", async () => {
const source = [
"| Metric | Formula | Norm |",
"| --- | --- | --- |",
"| Cond | $P(A|B)$ | $\\|x\\|$ |",
].join("\n");
const rendered = prepareMarkdownSource(source).render();
const ast = await parseMarkdown(rendered, MATH_FLAGS);
const table = collectNodes(ast).find((node) => node.type === "Table");
const bodyRow = table?.children?.find((node) => node.type === "TableBody")?.children?.[0];
expect(bodyRow?.children).toHaveLength(3);
expect(collectMathNodes(bodyRow!)).toEqual([
{ type: "LatexMathInline", content: "P(A\\vert B)" },
{ type: "LatexMathInline", content: "\\Vert x\\Vert " },
]);
});
it("keeps matrix & and || intact inside math when mdast runs", async () => {
const source = [
"Before &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,9 +806,37 @@ it.each([
color: theme.colors.accentBright,
});
expect(style.thematicBreak?.color).toBe(theme.colors.border);
expect(style.math).toMatchObject({
color: theme.colors.foreground,
backgroundColor: "transparent",
padding: 8,
marginTop: 0,
marginBottom: 16,
textAlign: "center",
});
expect(style.inlineMath).toMatchObject({
color: theme.colors.foreground,
});
},
);
it("uses muted text colour for math when compact and muted", () => {
const { markdownStyle: style } = createMarkdownStyles(darkTheme, {
compact: true,
muted: true,
blockGap: 12,
});
expect(style.math).toMatchObject({
color: darkTheme.colors.foregroundMuted,
backgroundColor: "transparent",
padding: 8,
marginTop: 0,
marginBottom: 12,
textAlign: "center",
});
expect(style.inlineMath).toEqual({ color: darkTheme.colors.foregroundMuted });
});
it.each([darkTheme, lightTheme])("supplies the theme selection colour to the renderer", (theme) => {
expect(createMarkdownStyles(theme, { blockGap: 16 })).toHaveProperty(
"selectionColor",
@@ -1442,3 +1470,69 @@ describe("web Markdown parser preload", () => {
expect(ast?.children?.map((node) => node.type)).toEqual(["Heading", "Paragraph"]);
});
});
describe("math preparation compatibility with latexMath false and true", () => {
it("renders currency literally with latexMath: false while enabling math with latexMath: true", async () => {
const source =
"Costs $5 and $10; inline $E = mc^2$, \\(a+b\\), \\[c+d\\], and:\n\n```math\nx^2\n```";
const prepared = prepareMarkdownSource(source).render();
const noMathAst = await parseMarkdown(prepared, {
latexMath: false,
hardSoftBreaks: true,
admonitions: true,
});
const noMathText = JSON.stringify(noMathAst);
expect(noMathText).toContain("Costs $5 and $10");
expect(noMathText).not.toContain("LatexMath");
const mathAst = await parseMarkdown(prepared, {
latexMath: true,
hardSoftBreaks: true,
admonitions: true,
});
const mathNodes: { type: string; content: string }[] = [];
const walk = (node: ASTNode) => {
if (node.type === "LatexMathInline" || node.type === "LatexMathDisplay") {
mathNodes.push({
type: node.type,
content: (node.children ?? []).map((child) => child.content ?? "").join(""),
});
}
node.children?.forEach(walk);
};
walk(mathAst);
expect(mathNodes.map((n) => [n.type, n.content.trim()])).toEqual([
["LatexMathInline", "E = mc^2"],
["LatexMathInline", "a+b"],
["LatexMathDisplay", "c+d"],
["LatexMathDisplay", "x^2"],
]);
});
});
describe("web KaTeX .woff2-only stylesheet sync", () => {
it("includes all 20 .woff2 fonts from katex and drops .woff/.ttf fallbacks", async () => {
const fs = await import("node:fs");
const path = await import("node:path");
const katexCssPath = require.resolve("katex/dist/katex.min.css");
const katexFontsDir = path.join(path.dirname(katexCssPath), "fonts");
const woff2Files = fs
.readdirSync(katexFontsDir)
.filter((name) => name.endsWith(".woff2"))
.sort();
expect(woff2Files).toHaveLength(20);
const katexStylesSource = fs.readFileSync(
path.resolve(__dirname, "katex-styles.web.ts"),
"utf8",
);
for (const fontFile of woff2Files) {
expect(katexStylesSource).toContain(`katex/dist/fonts/${fontFile}`);
}
expect(katexStylesSource).not.toContain('.woff")');
expect(katexStylesSource).not.toContain('.ttf")');
expect(katexStylesSource).toContain(".katex{");
expect(katexStylesSource).toContain(".enrm-text .katex-display{margin:0}");
});
});
@@ -35,7 +35,7 @@ export type { MarkdownDestinations };
export type MarkdownSoftBreaks = "break" | "join";
const ThemedMarkdown = withUnistyles(EnrichedMarkdownText);
const MD4C_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true };
const MD4C_FLAGS = { latexMath: true, hardSoftBreaks: true, admonitions: true };
const JOINED_SOFT_BREAKS_MD4C_FLAGS = { ...MD4C_FLAGS, hardSoftBreaks: false };
// Reading the breakpoint here makes Unistyles restyle the text when the layout crosses it.
@@ -8,10 +8,11 @@ import {
type ComponentProps,
type MouseEvent,
} from "react";
import type {
CodeBlockRendererProps,
LinkRendererProps,
MarkdownRenderers,
import {
registerKaTeXStyleLoader,
type CodeBlockRendererProps,
type LinkRendererProps,
type MarkdownRenderers,
} from "react-native-enriched-markdown";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useFileLink } from "@/assistant-file-links";
@@ -151,6 +152,11 @@ const styles = StyleSheet.create((theme) => ({
},
}));
registerKaTeXStyleLoader(async () => {
const mod = await import("./katex-styles.web");
mod.ensureKaTeXStyles();
});
export const WEB_RENDERERS: MarkdownRenderers = {
codeBlock: WebCodeBlock,
link: WebLink,
+45 -36
View File
@@ -2,6 +2,7 @@ import { pluginOverviewUrl } from "@getpaseo/protocol/plugin-overview";
import { classifyAssistantFileLink } from "@/assistant-file-links";
import { ASSISTANT_FILE_EXTENSIONS } from "@/assistant-file-links/extensions";
import { normalizeMarkdownHtml } from "./html";
import { adaptMarkdownMath, isOffsetInRanges } from "./math";
import { gfmTable } from "micromark-extension-gfm-table";
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
import type { AssistantFileLinkSource } from "@/assistant-file-links";
@@ -231,6 +232,8 @@ export function prepareMarkdownSource(
} = {},
) {
source = normalizeMarkdownHtml(source);
const { source: adaptedSource, mathRanges } = adaptMarkdownMath(source);
source = adaptedSource;
const images: MarkdownImage[] = [];
let tree: Root | undefined;
const getTree = () =>
@@ -351,53 +354,59 @@ export function prepareMarkdownSource(
edits.push({ start, end: labelStart, text: "" });
edits.push({ start: labelEnd, end, text: "" });
}
function adaptTableHeaderGap(start: number, previous?: Nodes, line?: number) {
if (previous?.type !== "paragraph" || previous.position?.end.line !== (line ?? -1) - 1) return;
// MD4C only recognizes a table header on the first line of a paragraph.
const lineStart =
Math.max(source.lastIndexOf("\n", start - 1), source.lastIndexOf("\r", start - 1)) + 1;
const newline = source.slice(lineStart - 2, lineStart).replace(/[^\r\n]/g, "");
const blank = source.slice(lineStart, start).replace(/[^>]/g, " ").trimEnd();
const boundary = lineStart - newline.length;
edits.push({ start: boundary, end: lineStart, text: `${newline}${blank}${newline}` });
}
function adaptTableRow(start: number, end: number) {
// MD4C's always-enabled spoiler extension otherwise consumes adjacent cell
// delimiters. Spaces keep empty GFM cells empty without producing spoilers.
const row = source.slice(start, end);
for (const match of row.matchAll(/(?<!\\)\|(?=\|)/g)) {
if (isOffsetInRanges(start + match.index, mathRanges)) continue;
edits.push({ start: start + match.index + 1, end: start + match.index + 1, text: " " });
}
}
function adaptTextNode(start: number, end: number) {
const slice = source.slice(start, end);
const text = slice.replace(
/(?<!\\)(?:(&(?:#(?:[xX][\da-fA-F]+|\d+)|[a-zA-Z][a-zA-Z\d]+);)|(\|\|))/g,
(match, entity: string | undefined, _bars: string | undefined, offset: number) => {
if (isOffsetInRanges(start + offset, mathRanges)) return match;
if (entity) return decodeString(entity).replace(/[!-/:-@[-`{-~]/g, "\\$&");
return "\\|\\|";
},
);
if (text !== slice) edits.push({ start, end, text });
}
function visit(node: Nodes, previous?: Nodes) {
const position = node.position;
if (position?.start.offset !== undefined && position.end.offset !== undefined) {
const start = position.start.offset;
const end = position.end.offset;
if (node.type === "paragraph") splitStandaloneImages(node, start, end);
if (
node.type === "table" &&
previous?.type === "paragraph" &&
previous.position?.end.line === position.start.line - 1
) {
// MD4C only recognizes a table header on the first line of a paragraph.
const lineStart =
Math.max(source.lastIndexOf("\n", start - 1), source.lastIndexOf("\r", start - 1)) + 1;
const newline = source.slice(lineStart - 2, lineStart).replace(/[^\r\n]/g, "");
const blank = source.slice(lineStart, start).replace(/[^>]/g, " ").trimEnd();
const boundary = lineStart - newline.length;
edits.push({ start: boundary, end: lineStart, text: `${newline}${blank}${newline}` });
}
if (httpsOnly) {
dropUnsafeDestination(node, start, end);
} else if (node.type === "link") {
const title = workspaceHoverTitle(node, source.slice(start, end), workspaceRoot);
if (title !== null)
edits.push({ start: end - 1, end: end - 1, text: ` ${JSON.stringify(title)}` });
}
if (node.type === "tableRow") {
// MD4C's always-enabled spoiler extension otherwise consumes adjacent cell
// delimiters. Spaces keep empty GFM cells empty without producing spoilers.
const row = source.slice(start, end);
for (const match of row.matchAll(/(?<!\\)\|(?=\|)/g)) {
edits.push({ start: start + match.index + 1, end: start + match.index + 1, text: " " });
if (node.type === "table") adaptTableHeaderGap(start, previous, position.start.line);
if (!isOffsetInRanges(start, mathRanges)) {
if (httpsOnly) {
dropUnsafeDestination(node, start, end);
} else if (node.type === "link") {
const title = workspaceHoverTitle(node, source.slice(start, end), workspaceRoot);
if (title !== null)
edits.push({ start: end - 1, end: end - 1, text: ` ${JSON.stringify(title)}` });
}
}
if (node.type === "tableRow") adaptTableRow(start, end);
if (node.type === "image" || node.type === "imageReference") {
collectImage(node, start, end);
if (!isOffsetInRanges(start, mathRanges)) collectImage(node, start, end);
return;
}
if (node.type === "text") {
const text = source
.slice(start, end)
.replace(/(?<!\\)&(?:#(?:[xX][\da-fA-F]+|\d+)|[a-zA-Z][a-zA-Z\d]+);/g, (entity) =>
decodeString(entity).replace(/[!-/:-@[-`{-~]/g, "\\$&"),
)
.replace(/(?<!\\)\|\|/g, "\\|\\|");
if (text !== source.slice(start, end)) edits.push({ start, end, text });
}
if (node.type === "text") adaptTextNode(start, end);
}
if ("children" in node)
node.children.forEach((child, index) => visit(child, node.children[index - 1]));
@@ -1,3 +1,22 @@
import {
checkFenceContainerExit,
isAsciiAlnum,
isAsciiPunctuation,
isBlankRange,
isClosingFenceAt,
matchListMarkerAt,
measureIndentAt,
parseFenceOpenerAt,
stripBlockquotesAt,
} from "./block-scan";
import {
isUnclosedInlineMathCandidate,
matchClosedBracketMath,
matchClosedDollarDisplayMath,
matchClosedInlineMath,
matchClosedParenMath,
} from "./math";
/**
* Sentinel destination for incomplete links while streaming. Web renders it as a
* non-interactive link-styled span; native styles it as a link and ignores taps.
@@ -15,8 +34,17 @@ interface OpenFence {
char: "`" | "~";
length: number;
lineStart: number;
lastLineStart: number;
quoteDepth: number;
maxCloseIndent: number;
listMinIndent: number;
hasContent: boolean;
}
interface OpenDisplayMath {
kind: "$$" | "\\[";
withholdFrom: number;
quoteDepth: number;
hasContent: boolean;
}
@@ -24,7 +52,9 @@ interface FenceScanCheckpoint {
/** Exact prefix of completed lines already scanned (ends at `\n` or `\r`, or is `""`). */
scannedPrefix: string;
openFence: OpenFence | null;
openDisplayMath: OpenDisplayMath | null;
listContentIndent: number;
listQuoteDepth: number;
/** Start offset of the most recent closing fence line, or -1 if none. */
lastClosedFenceLineStart: number;
}
@@ -110,76 +140,20 @@ function lastCompletedLineEnd(source: string): number {
return lastBreak === -1 ? 0 : lastBreak + 1;
}
/** Strip leading CommonMark blockquote markers (`> `) and return quote depth + content offset. */
function stripBlockquotes(text: string): { quoteDepth: number; offset: number } {
let offset = 0;
let quoteDepth = 0;
while (offset < text.length) {
let spaces = 0;
let cursor = offset;
while (cursor < text.length && text[cursor] === " " && spaces < 3) {
cursor++;
spaces++;
}
if (text[cursor] !== ">") break;
quoteDepth++;
cursor++;
if (text[cursor] === " " || text[cursor] === "\t") cursor++;
offset = cursor;
}
return { quoteDepth, offset };
return stripBlockquotesAt(text, 0, text.length);
}
function measureIndent(text: string, from: number): { spaces: number; offset: number } {
let spaces = 0;
let offset = from;
while (offset < text.length) {
const ch = text[offset];
if (ch === " ") {
spaces++;
offset++;
} else if (ch === "\t") {
spaces += 4 - (spaces % 4);
offset++;
} else {
break;
}
}
return { spaces, offset };
return measureIndentAt(text, from, text.length);
}
function matchListMarker(
text: string,
from: number,
maxIndent = Number.POSITIVE_INFINITY,
): { markerEnd: number; contentIndent: number } | null {
const { spaces, offset } = measureIndent(text, from);
if (offset >= text.length) return null;
const ch = text[offset];
if (ch === "-" || ch === "*" || ch === "+") {
const after = offset + 1;
if (after < text.length && (text[after] === " " || text[after] === "\t")) {
return { markerEnd: after + 1, contentIndent: spaces + 2 };
}
return null;
}
if (ch >= "0" && ch <= "9") {
let cursor = offset;
while (
cursor < text.length &&
text[cursor] >= "0" &&
text[cursor] <= "9" &&
cursor - offset < 9
) {
cursor++;
}
if (cursor < text.length && (text[cursor] === "." || text[cursor] === ")")) {
const after = cursor + 1;
if (after < text.length && (text[after] === " " || text[after] === "\t")) {
return { markerEnd: after + 1, contentIndent: spaces + (after - offset) + 1 };
}
}
}
return null;
return matchListMarkerAt(text, from, text.length, maxIndent);
}
function parseFenceOpener(
@@ -187,17 +161,7 @@ function parseFenceOpener(
from: number,
maxIndent: number,
): { char: "`" | "~"; length: number; info: string } | null {
const { spaces, offset } = measureIndent(text, from);
if (spaces > maxIndent || offset >= text.length) return null;
const ch = text[offset];
if (ch !== "`" && ch !== "~") return null;
let cursor = offset;
while (cursor < text.length && text[cursor] === ch) cursor++;
const length = cursor - offset;
if (length < 3) return null;
const info = text.slice(cursor);
if (ch === "`" && info.includes("`")) return null;
return { char: ch, length, info };
return parseFenceOpenerAt(text, from, text.length, maxIndent);
}
function isClosingFence(
@@ -207,16 +171,7 @@ function isClosingFence(
char: "`" | "~",
minLength: number,
): boolean {
const { spaces, offset } = measureIndent(text, from);
if (spaces > maxIndent || offset >= text.length || text[offset] !== char) return false;
let cursor = offset;
while (cursor < text.length && text[cursor] === char) cursor++;
if (cursor - offset < minLength) return false;
while (cursor < text.length) {
if (text[cursor] !== " " && text[cursor] !== "\t") return false;
cursor++;
}
return true;
return isClosingFenceAt(text, from, text.length, maxIndent, char, minLength);
}
function isPartialClosingFence(
@@ -237,18 +192,191 @@ function isPartialClosingFence(
}
function isBlankRest(text: string, from: number): boolean {
for (let i = from; i < text.length; i++) {
if (text[i] !== " " && text[i] !== "\t") return false;
}
return true;
return isBlankRange(text, from, text.length);
}
interface FenceStepState {
openFence: OpenFence | null;
openDisplayMath: OpenDisplayMath | null;
listContentIndent: number;
listQuoteDepth: number;
lastClosedFenceLineStart: number;
}
function hasTrailingOddBackslash(text: string): boolean {
let backslashes = 0;
for (let i = text.length - 1; i >= 0 && text[i] === "\\"; i--) backslashes++;
return backslashes % 2 === 1;
}
function hasTrailingPartialDoubleDollarCloser(text: string): boolean {
if (!text.endsWith("$")) return false;
if (text.length >= 2 && text[text.length - 2] === "$") return false;
return !hasTrailingOddBackslash(text.slice(0, -1));
}
function findSameLineBracketClose(text: string, from: number): number {
let j = from;
while (j < text.length) {
if (text[j] === "\\" && text[j + 1] === "]") return j + 2;
if (text[j] === "\\" && j + 1 < text.length) {
j += 2;
continue;
}
j++;
}
return -1;
}
function findSameLineDoubleDollarClose(text: string, from: number): number {
let j = from;
while (j < text.length) {
if (text[j] === "\\" && j + 1 < text.length) {
j += 2;
continue;
}
if (text[j] === "$" && text[j + 1] === "$") {
let closeEnd = j;
while (closeEnd < text.length && text[closeEnd] === "$") closeEnd++;
if (closeEnd - j === 2) return closeEnd;
j = closeEnd;
continue;
}
j++;
}
return -1;
}
function openDisplayMathFromLine(
kind: "$$" | "\\[",
text: string,
from: number,
openIndex: number,
restStart: number,
lineStart: number,
quoteDepth: number,
isTrailingPartialLine: boolean,
): OpenDisplayMath {
const withholdFrom = isBlankRest(text.slice(from, openIndex), 0)
? lineStart
: lineStart + openIndex;
const rest = text.slice(restStart);
const effectiveRest =
kind === "\\[" && isTrailingPartialLine && hasTrailingOddBackslash(rest)
? rest.slice(0, -1)
: rest;
return {
kind,
withholdFrom,
quoteDepth,
hasContent: !isBlankRest(effectiveRest, 0),
};
}
function scanLineForDisplayMath(
text: string,
from: number,
lineStart: number,
quoteDepth: number,
isTrailingPartialLine: boolean,
state: FenceStepState,
): void {
let k = from;
while (k < text.length) {
const ch = text[k];
if (ch === "\\") {
if (text[k + 1] === "[") {
const closeEnd = findSameLineBracketClose(text, k + 2);
if (closeEnd !== -1) {
k = closeEnd;
continue;
}
state.openDisplayMath = openDisplayMathFromLine(
"\\[",
text,
from,
k,
k + 2,
lineStart,
quoteDepth,
isTrailingPartialLine,
);
return;
}
k += k + 1 < text.length && isAsciiPunctuation(text[k + 1]) ? 2 : 1;
continue;
}
if (ch === "`") {
let runEnd = k;
while (runEnd < text.length && text[runEnd] === "`") runEnd++;
const closePos = findMatchingBacktickRun(text, runEnd, runEnd - k);
k = closePos !== -1 ? closePos + (runEnd - k) : runEnd;
continue;
}
if (ch === "$") {
let runEnd = k;
while (runEnd < text.length && text[runEnd] === "$") runEnd++;
if (runEnd - k === 2) {
const closeEnd = findSameLineDoubleDollarClose(text, runEnd);
if (closeEnd !== -1) {
k = closeEnd;
continue;
}
state.openDisplayMath = openDisplayMathFromLine(
"$$",
text,
from,
k,
runEnd,
lineStart,
quoteDepth,
isTrailingPartialLine,
);
return;
}
k = runEnd;
continue;
}
k++;
}
}
function stepOpenDisplayMathLine(
text: string,
offset: number,
lineStart: number,
quoteDepth: number,
isTrailingPartialLine: boolean,
state: FenceStepState,
): boolean {
const open = state.openDisplayMath!;
if (quoteDepth < open.quoteDepth) {
state.openDisplayMath = null;
return false;
}
const closeEnd =
open.kind === "$$"
? findSameLineDoubleDollarClose(text, offset)
: findSameLineBracketClose(text, offset);
if (closeEnd !== -1) {
state.openDisplayMath = null;
state.lastClosedFenceLineStart = lineStart;
scanLineForDisplayMath(text, closeEnd, lineStart, quoteDepth, isTrailingPartialLine, state);
return true;
}
const rest = text.slice(offset);
let effectiveRest = rest;
if (isTrailingPartialLine) {
if (open.kind === "$$" && hasTrailingPartialDoubleDollarCloser(rest)) {
effectiveRest = rest.slice(0, -1);
} else if (open.kind === "\\[" && hasTrailingOddBackslash(rest)) {
effectiveRest = rest.slice(0, -1);
}
}
if (!isBlankRest(effectiveRest, 0)) open.hasContent = true;
return true;
}
function stepFenceLine(
text: string,
lineStart: number,
@@ -258,8 +386,17 @@ function stepFenceLine(
const { quoteDepth, offset } = stripBlockquotes(text);
if (state.openFence !== null) {
if (quoteDepth < state.openFence.quoteDepth) {
// Leaving the blockquote closes any fence opened inside it.
if (
checkFenceContainerExit(
text,
0,
text.length,
state.openFence.quoteDepth,
state.openFence.listMinIndent,
).exited
) {
// Leaving the blockquote or enclosing list closes any fence opened inside it.
state.lastClosedFenceLineStart = state.openFence.lastLineStart;
state.openFence = null;
} else if (
isClosingFence(
@@ -274,6 +411,7 @@ function stepFenceLine(
state.openFence = null;
return;
} else {
state.openFence.lastLineStart = lineStart;
const partialCloser =
isTrailingPartialLine &&
quoteDepth === state.openFence.quoteDepth &&
@@ -289,34 +427,62 @@ function stepFenceLine(
}
}
if (isBlankRest(text, offset)) return;
if (
state.openDisplayMath !== null &&
stepOpenDisplayMathLine(text, offset, lineStart, quoteDepth, isTrailingPartialLine, state)
) {
return;
}
if (isBlankRest(text, offset)) {
if (quoteDepth < state.listQuoteDepth) {
state.listContentIndent = 0;
state.listQuoteDepth = quoteDepth;
}
return;
}
if (quoteDepth < state.listQuoteDepth) {
state.listContentIndent = 0;
state.listQuoteDepth = quoteDepth;
}
let cursor = offset;
let lineIndentBase = state.listContentIndent;
let lineIndentBase = quoteDepth === state.listQuoteDepth ? state.listContentIndent : 0;
const { spaces: firstSpaces } = measureIndent(text, cursor);
if (firstSpaces < state.listContentIndent) {
if (quoteDepth === state.listQuoteDepth && firstSpaces < state.listContentIndent) {
state.listContentIndent = 0;
lineIndentBase = 0;
}
let marker = matchListMarker(text, cursor);
let peeledList = false;
let marker = matchListMarker(text, cursor, lineIndentBase + 3);
while (marker) {
state.listContentIndent = marker.contentIndent;
lineIndentBase = marker.contentIndent;
const markerBase = cursor === offset ? 0 : lineIndentBase;
const totalIndent = markerBase + marker.contentIndent;
state.listContentIndent = totalIndent;
state.listQuoteDepth = quoteDepth;
lineIndentBase = totalIndent;
cursor = marker.markerEnd;
marker = matchListMarker(text, cursor);
peeledList = true;
marker = matchListMarker(text, cursor, 3);
}
const opener = parseFenceOpener(text, cursor, lineIndentBase + 3);
const opener = parseFenceOpener(text, cursor, peeledList ? 3 : lineIndentBase + 3);
if (opener) {
state.openFence = {
char: opener.char,
length: opener.length,
lineStart,
lastLineStart: lineStart,
quoteDepth,
maxCloseIndent: lineIndentBase + 3,
listMinIndent: lineIndentBase,
hasContent: false,
};
return;
}
scanLineForDisplayMath(text, offset, lineStart, quoteDepth, isTrailingPartialLine, state);
}
function advanceFenceRange(source: string, from: number, to: number, state: FenceStepState): void {
@@ -339,18 +505,28 @@ function cloneOpenFence(fence: OpenFence | null): OpenFence | null {
return fence ? { ...fence } : null;
}
function cloneOpenDisplayMath(math: OpenDisplayMath | null): OpenDisplayMath | null {
return math ? { ...math } : null;
}
/**
* Incrementally advance fence tracking across completed lines so steady-state
* Incrementally advance fence and display-math tracking across completed lines so steady-state
* streaming frames within a line scan 0 prior lines, and each newline scans 1 line.
*/
function resolveFenceState(
source: string,
checkpoint: FenceScanCheckpoint | null,
): { openFence: OpenFence | null; lastClosedFenceLineStart: number } {
): {
openFence: OpenFence | null;
openDisplayMath: OpenDisplayMath | null;
lastClosedFenceLineStart: number;
} {
const completedEnd = lastCompletedLineEnd(source);
const state: FenceStepState = {
openFence: null,
openDisplayMath: null,
listContentIndent: 0,
listQuoteDepth: 0,
lastClosedFenceLineStart: -1,
};
@@ -361,7 +537,9 @@ function resolveFenceState(
source.startsWith(checkpoint.scannedPrefix);
if (matchedPrefix && checkpoint) {
state.openFence = cloneOpenFence(checkpoint.openFence);
state.openDisplayMath = cloneOpenDisplayMath(checkpoint.openDisplayMath);
state.listContentIndent = checkpoint.listContentIndent;
state.listQuoteDepth = checkpoint.listQuoteDepth;
state.lastClosedFenceLineStart = checkpoint.lastClosedFenceLineStart;
scanFrom = checkpoint.scannedPrefix.length;
}
@@ -373,7 +551,9 @@ function resolveFenceState(
if (checkpoint && (!matchedPrefix || completedEnd !== checkpoint.scannedPrefix.length)) {
checkpoint.scannedPrefix = source.slice(0, completedEnd);
checkpoint.openFence = cloneOpenFence(state.openFence);
checkpoint.openDisplayMath = cloneOpenDisplayMath(state.openDisplayMath);
checkpoint.listContentIndent = state.listContentIndent;
checkpoint.listQuoteDepth = state.listQuoteDepth;
checkpoint.lastClosedFenceLineStart = state.lastClosedFenceLineStart;
}
@@ -383,6 +563,7 @@ function resolveFenceState(
return {
openFence: state.openFence,
openDisplayMath: state.openDisplayMath,
lastClosedFenceLineStart: state.lastClosedFenceLineStart,
};
}
@@ -663,17 +844,6 @@ function isWhitespaceChar(ch: string | undefined): boolean {
return ch === undefined || ch === " " || ch === "\t" || ch === "\n" || ch === "\r";
}
function isAsciiPunctuation(ch: string | undefined): boolean {
if (!ch) return false;
const code = ch.charCodeAt(0);
return (
(code >= 0x21 && code <= 0x2f) ||
(code >= 0x3a && code <= 0x40) ||
(code >= 0x5b && code <= 0x60) ||
(code >= 0x7b && code <= 0x7e)
);
}
function isUnicodePunctuation(ch: string | undefined): boolean {
if (!ch) return false;
if (isAsciiPunctuation(ch)) return true;
@@ -861,6 +1031,7 @@ interface InlineScanState {
stack: InlineStackEntry[];
openCode: { pos: number; length: number; contentStart: number } | null;
openHtmlPos: number | null;
openInlineMathPos: number | null;
trailingBackslash: boolean;
}
@@ -1153,7 +1324,7 @@ function stripPartialEmphCloser(output: string, entry: EmphEntry): string {
function unwindInlineState(source: string, state: InlineScanState): string {
let output = source;
const { openCode, openHtmlPos, trailingBackslash, stack } = state;
const { openCode, openHtmlPos, openInlineMathPos, trailingBackslash, stack } = state;
if (openCode) {
let codeContent = output.slice(openCode.contentStart);
@@ -1167,6 +1338,8 @@ function unwindInlineState(source: string, state: InlineScanState): string {
: output.slice(0, openCode.contentStart) + codeContent + "`".repeat(openCode.length);
} else if (openHtmlPos !== null) {
output = output.slice(0, openHtmlPos);
} else if (openInlineMathPos !== null) {
output = output.slice(0, openInlineMathPos);
} else if (trailingBackslash) {
output = output.slice(0, -1);
}
@@ -1210,6 +1383,56 @@ function scanBacktickToken(source: string, i: number, state: InlineScanState): n
return null;
}
function isOnTrailingLine(source: string, from: number): boolean {
return source.indexOf("\n", from) === -1 && source.indexOf("\r", from) === -1;
}
function scanInlineBackslashToken(
source: string,
i: number,
state: InlineScanState,
): number | null {
if (source[i + 1] === "(") {
const closedParen = matchClosedParenMath(source, i);
if (closedParen !== -1) return closedParen;
if (isOnTrailingLine(source, i + 2)) {
if (i + 2 === source.length) state.openInlineMathPos = i;
return null;
}
}
if (source[i + 1] === "[") {
const closedBracket = matchClosedBracketMath(source, i);
if (closedBracket !== -1) return closedBracket;
}
if (i + 1 === source.length) {
state.trailingBackslash = true;
return null;
}
return i + (isAsciiPunctuation(source[i + 1]) ? 2 : 1);
}
function scanInlineDollarToken(source: string, i: number, state: InlineScanState): number | null {
if (source[i + 1] === "$") {
const closedDisplay = matchClosedDollarDisplayMath(source, i);
if (closedDisplay !== -1) return closedDisplay;
let runEnd = i;
while (runEnd < source.length && source[runEnd] === "$") runEnd++;
return runEnd;
}
const closedInline = matchClosedInlineMath(source, i);
if (closedInline !== -1) return closedInline;
if (isOnTrailingLine(source, i + 1)) {
const charBefore = i > 0 ? source[i - 1] : undefined;
const validOpenerFlank = charBefore !== "\\" && charBefore !== "$" && !isAsciiAlnum(charBefore);
if (i + 1 === source.length && validOpenerFlank) {
state.openInlineMathPos = i;
return null;
}
if (isUnclosedInlineMathCandidate(source, i)) return null;
}
return i + 1;
}
function stepInlineScanner(
source: string,
i: number,
@@ -1219,13 +1442,8 @@ function stepInlineScanner(
): number | null {
const ch = source[i];
if (ch === "\n") return lineContentStarts.get(i + 1) ?? i + 1;
if (ch === "\\") {
if (i + 1 === source.length) {
state.trailingBackslash = true;
return null;
}
return i + (isAsciiPunctuation(source[i + 1]) ? 2 : 1);
}
if (ch === "\\") return scanInlineBackslashToken(source, i, state);
if (ch === "$") return scanInlineDollarToken(source, i, state);
if (ch === "`") return scanBacktickToken(source, i, state);
if (ch === "<") return scanHtmlToken(source, i, state);
if (ch === "[" || (ch === "!" && source[i + 1] === "[")) {
@@ -1248,6 +1466,7 @@ function stabilizeInlineBlock(
stack: [],
openCode: null,
openHtmlPos: null,
openInlineMathPos: null,
trailingBackslash: false,
};
@@ -1259,42 +1478,74 @@ function stabilizeInlineBlock(
const hasOpenState =
state.openCode !== null ||
state.openHtmlPos !== null ||
state.openInlineMathPos !== null ||
state.stack.length > 0 ||
state.trailingBackslash;
return hasOpenState ? unwindInlineState(source, state) : source;
}
function stabilizeOpenFence(
source: string,
openFence: OpenFence,
endsWithNewline: boolean,
): string {
if (!openFence.hasContent) {
return source.slice(0, openFence.lineStart);
}
if (!endsWithNewline) {
const last = prevLineSlice(source, source.length);
if (last) {
const lastText = lineText(source, last);
const lastQ = stripBlockquotes(lastText);
if (
lastQ.quoteDepth === openFence.quoteDepth &&
(isPartialClosingFence(
lastText,
lastQ.offset,
openFence.maxCloseIndent,
openFence.char,
openFence.length,
) ||
(openFence.quoteDepth > 0 && isBlankRest(lastText, lastQ.offset)))
) {
return source.slice(0, last.start);
}
}
}
return source;
}
function stabilizeOpenDisplayMath(
source: string,
openDisplayMath: OpenDisplayMath,
endsWithNewline: boolean,
): string {
if (!openDisplayMath.hasContent) {
return source.slice(0, openDisplayMath.withholdFrom);
}
if (!endsWithNewline) {
if (openDisplayMath.kind === "$$" && hasTrailingPartialDoubleDollarCloser(source)) {
return source.slice(0, -1);
}
if (openDisplayMath.kind === "\\[" && hasTrailingOddBackslash(source)) {
return source.slice(0, -1);
}
}
return source;
}
function stabilizeWithCheckpoint(source: string, checkpoint: FenceScanCheckpoint | null): string {
if (source.length === 0) return source;
const endsWithNewline = sourceEndsWithNewline(source);
// 1. Fenced code blocks (top-level, quoted, or inside lists) — O(new lines) when incremental.
const { openFence, lastClosedFenceLineStart } = resolveFenceState(source, checkpoint);
if (openFence !== null) {
if (!openFence.hasContent) {
return source.slice(0, openFence.lineStart);
}
if (!endsWithNewline) {
const last = prevLineSlice(source, source.length);
if (last) {
const lastText = lineText(source, last);
const lastQ = stripBlockquotes(lastText);
if (
lastQ.quoteDepth === openFence.quoteDepth &&
(isPartialClosingFence(
lastText,
lastQ.offset,
openFence.maxCloseIndent,
openFence.char,
openFence.length,
) ||
(openFence.quoteDepth > 0 && isBlankRest(lastText, lastQ.offset)))
) {
return source.slice(0, last.start);
}
}
}
return source;
// 1. Fenced code blocks & display math blocks — O(new lines) when incremental.
const { openFence, openDisplayMath, lastClosedFenceLineStart } = resolveFenceState(
source,
checkpoint,
);
if (openFence !== null) return stabilizeOpenFence(source, openFence, endsWithNewline);
if (openDisplayMath !== null) {
return stabilizeOpenDisplayMath(source, openDisplayMath, endsWithNewline);
}
// 2. Trailing GFM table — O(table rows) backwards from EOF.
@@ -1330,7 +1581,9 @@ export function createStreamingMarkdownStabilizer(): StreamingMarkdownStabilizer
const checkpoint: FenceScanCheckpoint = {
scannedPrefix: "",
openFence: null,
openDisplayMath: null,
listContentIndent: 0,
listQuoteDepth: 0,
lastClosedFenceLineStart: -1,
};
return {
@@ -544,3 +544,119 @@ describe("stabilizeStreamingMarkdown — fences, tables, HTML, and full prefix s
expect(incremental.stabilize("Plain\nCheck `inline")).toBe("Plain\nCheck `inline`");
}, 20000);
});
describe("streaming Markdown math safety", () => {
it("keeps open multiline $$, \\[, and ```math blocks in the tail without splitting mid-equation", () => {
const blocks = ["$$\na = 1\n\nb = 2\n", "\\[\na = 1\n\nb = 2\n", "```math\na = 1\n\nb = 2\n"];
for (const openMath of blocks) {
const source = `Intro.\n\n${openMath}`;
const split = splitOnce(source);
expect(split.head).toBe("Intro.\n\n");
expect(split.tail).toBe(openMath);
}
// Even after a blank-line $$ or \[ block closes, it stays together until a following block arrives.
const closedDollar = "Intro.\n\n$$\na = 1\n\nb = 2\n$$\n";
expect(splitOnce(closedDollar)).toEqual({
head: "Intro.\n\n",
tail: "$$\na = 1\n\nb = 2\n$$\n",
});
expect(splitOnce(`${closedDollar}\nAfter.\n`)).toEqual({
head: closedDollar + "\n",
tail: "After.\n",
});
const closedBracket = "Intro.\n\n\\[\na = 1\n\nb = 2\n\\]\n";
expect(splitOnce(closedBracket)).toEqual({
head: "Intro.\n\n",
tail: "Intro.\n\n\\[\na = 1\n\nb = 2\n\\]\n".slice("Intro.\n\n".length),
});
expect(splitOnce(`${closedBracket}\nAfter.\n`)).toEqual({
head: closedBracket + "\n",
tail: "After.\n",
});
});
it("withholds dangling math openers and partial closers without auto-closing partial TeX", () => {
expect(stabilizeStreamingMarkdown("Intro\n\n$$")).toBe("Intro\n\n");
expect(stabilizeStreamingMarkdown("Intro\n\n$$\n")).toBe("Intro\n\n");
expect(stabilizeStreamingMarkdown("Intro\n\n\\[")).toBe("Intro\n\n");
expect(stabilizeStreamingMarkdown("Intro\n\n\\[\n")).toBe("Intro\n\n");
expect(stabilizeStreamingMarkdown("Intro\n\n```math")).toBe("Intro\n\n");
expect(stabilizeStreamingMarkdown("Intro\n\n```math\n")).toBe("Intro\n\n");
expect(stabilizeStreamingMarkdown("Formula: $")).toBe("Formula: ");
expect(stabilizeStreamingMarkdown("Formula: \\(")).toBe("Formula: ");
// Currency/escaped trailing dollars are not math openers.
expect(stabilizeStreamingMarkdown("Price is US$")).toBe("Price is US$");
expect(stabilizeStreamingMarkdown("Escaped \\$")).toBe("Escaped \\$");
// Partial TeX content stays literal and is never auto-closed or mangled by inline emphasis/links.
expect(stabilizeStreamingMarkdown("$$\n\\frac{a}{")).toBe("$$\n\\frac{a}{");
expect(stabilizeStreamingMarkdown("\\[\n\\frac{a}{")).toBe("\\[\n\\frac{a}{");
expect(stabilizeStreamingMarkdown("```math\n\\frac{a}{")).toBe("```math\n\\frac{a}{");
expect(stabilizeStreamingMarkdown("Compute $\\alpha + *x")).toBe("Compute $\\alpha + *x");
expect(stabilizeStreamingMarkdown("Compute \\(\\alpha + [a")).toBe("Compute \\(\\alpha + [a");
// Partial closing markers inside open display math are withheld until completed.
expect(stabilizeStreamingMarkdown("$$\n\\frac{a}{b}\n$")).toBe("$$\n\\frac{a}{b}\n");
expect(stabilizeStreamingMarkdown("\\[\n\\frac{a}{b}\n\\")).toBe("\\[\n\\frac{a}{b}\n");
// Currency dollars do not suppress emphasis stabilization later on the line.
expect(stabilizeStreamingMarkdown("Costs $5 and **bold")).toBe("Costs $5 and **bold**");
// Closed inline math protects internal * / _ from emphasis stabilization.
expect(stabilizeStreamingMarkdown("Compute $a * b$ and **bold")).toBe(
"Compute $a * b$ and **bold**",
);
expect(stabilizeStreamingMarkdown("Compute \\(a * b\\) and **bold")).toBe(
"Compute \\(a * b\\) and **bold**",
);
// An unclosed list-nested fence ends once a non-blank line exits the list container.
expect(stabilizeStreamingMarkdown("- ~~~sh\n echo ok\nOutside\n$$")).toBe(
"- ~~~sh\n echo ok\nOutside\n",
);
expect(stabilizeStreamingMarkdown("- ~~~sh\n echo ok\nOutside **bo")).toBe(
"- ~~~sh\n echo ok\nOutside **bo**",
);
expect(stabilizeStreamingMarkdown("- ```sh\n echo ok\nOutside **bo")).toBe(
"- ```sh\n echo ok\nOutside **bo**",
);
expect(stabilizeStreamingMarkdown("- item\n - ```\n code\n back **bo")).toBe(
"- item\n - ```\n code\n back **bo**",
);
// Exiting a deeper quote clears stale list indent so outer quoted code stays open.
expect(stabilizeStreamingMarkdown("> > - item\n>\n> ~~~sh\n> echo **bo")).toBe(
"> > - item\n>\n> ~~~sh\n> echo **bo",
);
});
it("maintains incremental stabilizer parity and idempotence across math streaming prefixes", () => {
const sample = [
"Inline $a * b$ and \\(c_1 + d_2\\).",
"",
"$$",
"x = 1",
"",
"y = 2",
"$$",
"",
"\\[",
"\\int_0^1 x^2\\,dx",
"\\]",
"",
"```math",
"\\sum_{i=1}^n i",
"```",
"",
"Done.",
].join("\n");
const incremental = createStreamingMarkdownStabilizer();
for (let end = 0; end <= sample.length; end++) {
const prefix = sample.slice(0, end);
const stabilized = stabilizeStreamingMarkdown(prefix);
expect(incremental.stabilize(prefix), `incremental parity at ${end}`).toBe(stabilized);
expect(stabilizeStreamingMarkdown(stabilized), `idempotent at ${end}`).toBe(stabilized);
}
});
});
@@ -2,6 +2,7 @@ import { fromMarkdown } from "mdast-util-from-markdown";
import { gfmTable } from "micromark-extension-gfm-table";
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
import type { Nodes, Root } from "mdast";
import { findBlockMathSpans } from "./math";
export {
createStreamingMarkdownStabilizer,
@@ -80,12 +81,24 @@ export function createStreamingMarkdownSplitter(
partStarts = [0];
return;
}
const mathSpans = findBlockMathSpans(open);
let settled = 0;
for (let index = 0; index < tree.children.length - 1; index++) {
if (needsDocumentContext(tree.children[index])) break;
// mdast starts some nodes after their indentation; the next parser needs it too.
const nextStart = tree.children[index + 1].position!.start.offset!;
settled = open.lastIndexOf("\n", nextStart - 1) + 1;
const splitAt = open.lastIndexOf("\n", nextStart - 1) + 1;
let crossesMath = false;
let insideUnclosedMath = false;
for (const span of mathSpans) {
if (splitAt > span.start && splitAt < span.end) {
crossesMath = true;
if (span.end === Number.POSITIVE_INFINITY) insideUnclosedMath = true;
break;
}
}
if (insideUnclosedMath) break;
if (!crossesMath) settled = splitAt;
}
if (settled === 0) return;
if (boundary - partStarts[partStarts.length - 1] >= HEAD_PART_LENGTH) partStarts.push(boundary);
@@ -103,6 +103,17 @@ export function createMarkdownStyles(
inlineImage: { size: paragraph.lineHeight },
image: { ...block, height: 320, resizeMode: "contain", borderRadius: 8 },
thematicBreak: { ...block, color: theme.colors.border, height: 1 },
math: {
fontSize,
color: paragraph.color,
backgroundColor: "transparent",
padding: 8,
...block,
textAlign: "center",
},
inlineMath: {
color: paragraph.color,
},
},
};
}
@@ -251,11 +251,15 @@ describe("control geometry", () => {
}
});
it("keeps segmented controls ghost with button-radius segments in a button-sized track", () => {
it("keeps segmented controls in an inset pill track sized to match buttons", () => {
const geometry = createControlGeometry(theme);
expect(geometry.segmentedContainerSm.padding).toBe(0);
expect(geometry.segmentedContainerMd.padding).toBe(0);
expect(geometry.segmentedContainerSm.padding).toBe(2);
expect(geometry.segmentedContainerMd.padding).toBe(2);
expect(geometry.segmentedContainerSm.gap).toBe(2);
expect(geometry.segmentedContainerMd.gap).toBe(2);
expect(geometry.segmentedContainerSm.borderRadius).toBe(geometry.buttonSm.borderRadius);
expect(geometry.segmentedContainerMd.borderRadius).toBe(geometry.buttonMd.borderRadius);
expect(geometry.segmentedSegmentSm.borderRadius).toBe(geometry.buttonSm.borderRadius);
expect(geometry.segmentedSegmentMd.borderRadius).toBe(geometry.buttonMd.borderRadius);
expect(geometry.segmentedContainerSm.minHeight).toEqual(geometry.buttonSm.minHeight);
@@ -462,11 +462,15 @@ export function createControlGeometry(theme: Theme) {
},
segmentedContainerSm: {
minHeight: CONTROL_HEIGHTS.sm,
padding: 0,
padding: SEGMENTED_INSET,
gap: SEGMENTED_INSET,
borderRadius: theme.borderRadius.full,
},
segmentedContainerMd: {
minHeight: CONTROL_HEIGHTS.md,
padding: 0,
padding: SEGMENTED_INSET,
gap: SEGMENTED_INSET,
borderRadius: theme.borderRadius.full,
},
segmentedSegmentSm: {
minHeight: mapLayout(CONTROL_HEIGHTS.sm, (height) => height - SEGMENTED_INSET * 2),
@@ -574,7 +574,7 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surface2,
},
fieldFocused: {
borderColor: theme.colors.borderAccent,
borderColor: theme.colors.borderFocus,
},
fieldInput: {
flex: 1,
@@ -176,7 +176,7 @@ const styles = StyleSheet.create((theme) => ({
maxWidth: "100%",
},
fieldFocused: {
borderColor: theme.colors.borderAccent,
borderColor: theme.colors.borderFocus,
backgroundColor: theme.colors.surface2,
},
input: {
@@ -0,0 +1,63 @@
import React from "react";
import { cleanup, fireEvent, render } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { SegmentedControl } from "./segmented-control";
afterEach(cleanup);
describe("SegmentedControl", () => {
it("renders a recessed surface2 pill track with an elevated surface0 selected thumb in light theme", () => {
const { getByTestId } = render(
<SegmentedControl
testID="mode-picker"
value="form"
onValueChange={vi.fn()}
options={[
{ value: "form", label: "Form", testID: "mode-form" },
{ value: "uri", label: "URI", testID: "mode-uri" },
]}
/>,
);
const track = getByTestId("mode-picker");
const selected = getByTestId("mode-form");
const unselected = getByTestId("mode-uri");
const trackStyle = getComputedStyle(track);
const selectedStyle = getComputedStyle(selected);
const unselectedStyle = getComputedStyle(unselected);
expect(trackStyle.backgroundColor).toBe("rgb(244, 244, 245)");
expect(trackStyle.paddingTop).toBe("2px");
expect(selectedStyle.backgroundColor).toBe("rgb(255, 255, 255)");
expect(unselectedStyle.backgroundColor).toBe("rgba(0, 0, 0, 0)");
expect(selected.getAttribute("aria-selected")).toBe("true");
expect(unselected.getAttribute("aria-selected")).toBe("false");
});
it("calls onValueChange only when clicking an enabled unselected segment", () => {
const onValueChange = vi.fn();
const { getByTestId } = render(
<SegmentedControl
testID="mode-picker"
value="form"
onValueChange={onValueChange}
options={[
{ value: "form", label: "Form", testID: "mode-form" },
{ value: "uri", label: "URI", testID: "mode-uri" },
{ value: "ssh", label: "SSH", testID: "mode-ssh", disabled: true },
]}
/>,
);
fireEvent.click(getByTestId("mode-form"));
expect(onValueChange).not.toHaveBeenCalled();
fireEvent.click(getByTestId("mode-ssh"));
expect(onValueChange).not.toHaveBeenCalled();
fireEvent.click(getByTestId("mode-uri"));
expect(onValueChange).toHaveBeenCalledTimes(1);
expect(onValueChange).toHaveBeenCalledWith("uri");
});
});
@@ -31,8 +31,6 @@ interface SegmentedControlProps<T extends string> {
hideLabels?: boolean;
/** Share the container's width equally between the segments, for a control that heads a surface. */
fill?: boolean;
/** Let the segments run onto more lines when they do not fit on one. */
wrap?: boolean;
style?: StyleProp<ViewStyle>;
testID?: string;
}
@@ -59,7 +57,6 @@ export function SegmentedControl<T extends string>({
size: sizeProp,
hideLabels = false,
fill = false,
wrap = false,
style,
testID,
}: SegmentedControlProps<T>) {
@@ -75,8 +72,8 @@ export function SegmentedControl<T extends string>({
const iconSize = controlIconSize[size];
const containerStyle = useMemo(
() => [styles.container, containerSizeStyle, wrap && styles.containerWrap, style],
[containerSizeStyle, style, wrap],
() => [styles.container, containerSizeStyle, style],
[containerSizeStyle, style],
);
return (
@@ -191,11 +188,7 @@ const styles = StyleSheet.create((theme) => {
container: {
flexDirection: "row",
alignItems: "center",
backgroundColor: "transparent",
gap: theme.spacing[1],
},
containerWrap: {
flexWrap: "wrap",
backgroundColor: theme.colors.surface2,
},
containerSm: {
...geometry.segmentedContainerSm,
@@ -209,6 +202,8 @@ const styles = StyleSheet.create((theme) => {
justifyContent: "center",
flexShrink: 0,
gap: theme.spacing[1],
borderWidth: theme.borderWidth[1],
borderColor: "transparent",
},
segmentSm: {
...geometry.segmentedSegmentSm,
@@ -223,10 +218,16 @@ const styles = StyleSheet.create((theme) => {
minWidth: 0,
},
segmentSelected: {
backgroundColor: theme.colors.surface3,
backgroundColor: theme.colors.surfaceSegmentThumb,
borderColor: theme.colors.borderSegmentThumb,
shadowColor: theme.shadow.sm.shadowColor,
shadowOffset: { width: 0, height: 1 },
shadowRadius: 2,
shadowOpacity: 1,
elevation: 1,
},
segmentHover: {
backgroundColor: theme.colors.surface2,
backgroundColor: theme.colors.interactionHighlight,
},
segmentPressed: {
backgroundColor: theme.colors.surface3,
@@ -25,7 +25,8 @@ import { AgentSheetHome, type AgentSheetControls } from "./sheet-home";
const SERVER_ID = "srv-live-settings";
const AGENT_ID = "agent-1";
const SHEET_FRAME_STYLE = { width: 390, height: 640, display: "flex" } as const;
const SHEET_FRAME_WIDTH = 390;
const SHEET_FRAME_HEIGHT = 640;
const GESTURE_ROOT_STYLE = { flex: 1 } as const;
const PRESENTATION = resolveComposerControlPresentation("compact");
const ignoreOpenSelect = () => undefined;
@@ -147,7 +148,7 @@ function setupSession() {
}
// Reads strictly from session-store — zero overlay merging in the view.
function LiveSheet({ toast }: { toast: ToastApi }) {
function LiveSheet({ toast, height = SHEET_FRAME_HEIGHT }: { toast: ToastApi; height?: number }) {
const agent = useSessionStore((state) => state.sessions[SERVER_ID]?.agents.get(AGENT_ID) ?? null);
const modeControl = useLiveAgentModeControl(SERVER_ID, AGENT_ID);
@@ -206,8 +207,13 @@ function LiveSheet({ toast }: { toast: ToastApi }) {
[items.features, items.thinking, modeControl],
);
const frameStyle = useMemo(
() => ({ width: SHEET_FRAME_WIDTH, height, display: "flex" as const }),
[height],
);
return (
<div style={SHEET_FRAME_STYLE}>
<div style={frameStyle}>
<AgentSheetHome
controls={controls}
disabled={false}
@@ -224,14 +230,14 @@ function createToast() {
};
}
function renderSheet() {
function renderSheet(height = SHEET_FRAME_HEIGHT) {
const toast = createToast();
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(
<GestureHandlerRootView style={GESTURE_ROOT_STYLE}>
<QueryClientProvider client={queryClient}>
<ToastApiProvider api={toast}>
<LiveSheet toast={toast} />
<LiveSheet toast={toast} height={height} />
</ToastApiProvider>
</QueryClientProvider>
</GestureHandlerRootView>,
@@ -239,6 +245,16 @@ function renderSheet() {
return toast;
}
function toViewportPoint(x: number, y: number): { x: number; y: number } {
const frameRect = window.frameElement?.getBoundingClientRect();
const scaleX = frameRect ? frameRect.width / window.innerWidth : 1;
const scaleY = frameRect ? frameRect.height / window.innerHeight : 1;
return {
x: Math.round((frameRect?.left ?? 0) + x * scaleX),
y: Math.round((frameRect?.top ?? 0) + y * scaleY),
};
}
beforeEach(() => vi.stubGlobal("React", React));
afterEach(() => {
cleanup();
@@ -377,17 +393,16 @@ describe("live agent settings sheet (browser geometry & races)", () => {
const lowStop = screen.getByTestId("agent-controls-thinking-low");
const highStop = screen.getByTestId("agent-controls-thinking-high");
const mediumStop = screen.getByTestId("agent-controls-thinking-medium");
const frameRect = window.frameElement?.getBoundingClientRect();
const scaleX = frameRect ? frameRect.width / window.innerWidth : 1;
const scaleY = frameRect ? frameRect.height / window.innerHeight : 1;
const toViewport = (x: number, y: number) => ({
x: Math.round((frameRect?.left ?? 0) + x * scaleX),
y: Math.round((frameRect?.top ?? 0) + y * scaleY),
});
const lowRect = lowStop.getBoundingClientRect();
const highRect = highStop.getBoundingClientRect();
const start = toViewport(lowRect.left + lowRect.width / 2, lowRect.top + lowRect.height / 2);
const end = toViewport(highRect.left + highRect.width / 2, highRect.top + highRect.height / 2);
const start = toViewportPoint(
lowRect.left + lowRect.width / 2,
lowRect.top + lowRect.height / 2,
);
const end = toViewportPoint(
highRect.left + highRect.width / 2,
highRect.top + highRect.height / 2,
);
const initialLeft = Math.round(thumb.getBoundingClientRect().left);
const browserCdp = cdp();
@@ -466,7 +481,7 @@ describe("live agent settings sheet (browser geometry & races)", () => {
// A plain tap after the drag still selects immediately.
const medRect = mediumStop.getBoundingClientRect();
const med = toViewport(medRect.left + medRect.width / 2, medRect.top + medRect.height / 2);
const med = toViewportPoint(medRect.left + medRect.width / 2, medRect.top + medRect.height / 2);
await browserCdp.send("Input.dispatchMouseEvent", {
type: "mousePressed",
x: med.x,
@@ -488,4 +503,93 @@ describe("live agent settings sheet (browser geometry & races)", () => {
expect(mediumLeft).toBeGreaterThan(initialLeft);
expect(mediumLeft).toBeLessThan(draggedLeft);
});
it("scrolls an overflowing pills row horizontally inside the sheet and selects a clipped option while keeping vertical sheet scroll", async () => {
const calls = setupSession();
const sevenChoices = [
{ value: "default", label: "Option One" },
{ value: "opt-2", label: "Option Two" },
{ value: "opt-3", label: "Option Three" },
{ value: "opt-4", label: "Option Four" },
{ value: "opt-5", label: "Option Five" },
{ value: "opt-6", label: "Option Six" },
{ value: "opt-7", label: "Option Seven" },
];
pushServerUpdate({
controls: [
CONTROLS[0],
{
type: "select",
key: "service_tier",
label: "Speed",
defaultValue: "default",
choices: sevenChoices,
},
],
});
renderSheet(240);
const track = await screen.findByTestId("agent-feature-service_tier");
const firstPill = screen.getByTestId("agent-feature-service_tier-default");
const lastPill = screen.getByTestId("agent-feature-service_tier-opt-7");
await nextPaint();
// All seven pills sit on one horizontal line inside the recessed track.
expect(Math.round(firstPill.getBoundingClientRect().top)).toBe(
Math.round(lastPill.getBoundingClientRect().top),
);
const horizontalScroller = track.parentElement?.parentElement;
expect(horizontalScroller).toBeTruthy();
if (!horizontalScroller) throw new Error("Missing horizontal scroller around pills control");
expect(horizontalScroller.scrollWidth).toBeGreaterThan(horizontalScroller.clientWidth);
expect(lastPill.getBoundingClientRect().right).toBeGreaterThan(
horizontalScroller.getBoundingClientRect().right,
);
const scrollerRect = horizontalScroller.getBoundingClientRect();
const pillsCenter = toViewportPoint(
scrollerRect.left + scrollerRect.width / 2,
scrollerRect.top + scrollerRect.height / 2,
);
const browserCdp = cdp();
// Wheel horizontally over the pills row to reveal the clipped trailing option and select it.
await browserCdp.send("Input.dispatchMouseEvent", {
type: "mouseWheel",
x: pillsCenter.x,
y: pillsCenter.y,
deltaX: horizontalScroller.scrollWidth,
deltaY: 0,
});
await nextPaint();
await nextPaint();
expect(horizontalScroller.scrollLeft).toBeGreaterThan(0);
expect(lastPill.getBoundingClientRect().right).toBeLessThanOrEqual(
horizontalScroller.getBoundingClientRect().right + 2,
);
fireEvent.click(lastPill);
expect(calls.map((call) => [call.kind, call.value])).toEqual([
["options", { service_tier: "opt-7" }],
]);
// Vertical wheel input over the pills row scrolls the outer sheet to reveal controls below it.
const sheetScroller = screen.getByTestId("agent-controls-settings-list");
expect(sheetScroller.scrollHeight).toBeGreaterThan(sheetScroller.clientHeight);
const modeCard = screen.getByTestId("mode-control");
const modeTopBefore = modeCard.getBoundingClientRect().top;
await browserCdp.send("Input.dispatchMouseEvent", {
type: "mouseWheel",
x: pillsCenter.x,
y: pillsCenter.y,
deltaX: 0,
deltaY: 160,
});
await nextPaint();
await nextPaint();
expect(sheetScroller.scrollTop).toBeGreaterThan(0);
expect(modeCard.getBoundingClientRect().top).toBeLessThan(modeTopBefore);
});
});
@@ -279,13 +279,14 @@ function PillsControl({ item, disabled }: { item: SelectItem; disabled: boolean
const handleChange = useCallback((value: string) => run(() => item.onChange(value)), [item, run]);
return (
<View style={styles.pills}>
<SegmentedControl
options={options}
value={item.value}
onValueChange={handleChange}
wrap
testID={item.testID}
/>
<SheetScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.pillsScroll}>
<SegmentedControl
options={options}
value={item.value}
onValueChange={handleChange}
testID={item.testID}
/>
</SheetScrollView>
</View>
);
}
@@ -640,6 +641,9 @@ const styles = StyleSheet.create((theme) => ({
pills: {
padding: theme.spacing[2],
},
pillsScroll: {
flexGrow: 0,
},
sliderCard: {
paddingHorizontal: theme.spacing[4],
paddingTop: theme.spacing[3],
+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.surface4,
borderColor: theme.colors.borderFocus,
},
// 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,11 +1,19 @@
import { useCheckboxSpaceKey } from "@/components/ui/checkbox";
import { PressHighlight } from "@/components/ui/press-highlight";
import { useCallback, useMemo, useRef, useState } from "react";
import type { EditingTextInputHandle } from "@/components/ui/text-input";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Alert, Text, View, type LayoutChangeEvent } from "react-native";
import {
Alert,
Text,
View,
type LayoutChangeEvent,
type NativeSyntheticEvent,
type TextInputSelectionChangeEventData,
} from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
import { Check, Eye, EyeOff, Link2 } from "lucide-react-native";
import { Check, Eye, EyeOff, Form, Link, 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";
@@ -27,11 +35,14 @@ 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,
@@ -41,6 +52,7 @@ import {
type DirectConnectionMode,
type DirectConnectionUri,
type ResolvedDirectConnection,
type TextSelection,
} from "./direct-connection";
const FLEX_ONE_STYLE = { flex: 1 } as const;
@@ -212,11 +224,17 @@ 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"), testID: "direct-mode-uri" },
{
value: "uri",
label: t("pairing.direct.modes.uri"),
icon: ({ color, size }) => <Link color={color} size={size} />,
testID: "direct-mode-uri",
},
],
[formAvailable, t],
);
@@ -462,6 +480,22 @@ 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,
@@ -475,6 +509,13 @@ 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], []);
@@ -487,22 +528,188 @@ 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) => onChange(editHost(input, host)),
[input, onChange],
(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],
);
const handlePortChange = useCallback(
(port: string) => onChange(editForm(input, { port })),
[input, onChange],
(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],
);
const handlePasswordChange = useCallback(
(password: string) => onChange(editForm(input, { password })),
[input, onChange],
(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],
);
const handleToggleUseTls = useCallback(() => {
if (isSaving) return;
onChange(editForm(input, { useTls: !input.useTls }));
}, [input, isSaving, onChange]);
const next = editForm(input, { useTls: !input.useTls });
if (next.mode === "form") {
syncFormInputs(input, next, { kind: "sync" });
}
onChange(next);
}, [input, isSaving, onChange, syncFormInputs]);
const tlsCheckboxKeyProps = useCheckboxSpaceKey(handleToggleUseTls, isSaving);
const handleTogglePasswordVisibility = useCallback(() => {
setIsPasswordVisible((current) => !current);
@@ -516,13 +723,15 @@ 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={fieldEvents.onBlur}
onBlur={handleHostBlur}
autoFocus={fieldEvents.autoFocus}
placeholder="localhost"
style={styles.input}
@@ -536,11 +745,13 @@ 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"
@@ -556,6 +767,7 @@ function DirectFormFields({
</View>
<PressHighlight
ref={sslToggleRef}
style={styles.checkboxRow}
onPress={handleToggleUseTls}
disabled={isSaving}
@@ -580,6 +792,7 @@ 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,11 +1,14 @@
import { describe, expect, it } from "vitest";
import {
canSwitchToForm,
commitHost,
editForm,
editHost,
editPort,
editPromptPassword,
editUri,
openDirectConnection,
pasteDirectConnection,
promptForPassword,
resolveConnection,
switchMode,
@@ -28,7 +31,17 @@ const OFFER_LINK = `https://app.paseo.sh/#offer=${Buffer.from(
function form(fields: Partial<Omit<DirectConnectionForm, "mode">>): DirectConnectionInput {
const { host = "", ...rest } = fields;
return editForm(editHost(openDirectConnection(), host), rest);
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;
}
function uri(text: string): DirectConnectionInput {
@@ -129,6 +142,20 @@ 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", () => {
@@ -153,18 +180,348 @@ describe("switching from URI to Form", () => {
});
describe("typing in Host", () => {
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("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("moves a typed or pasted URI to URI mode", () => {
expect(editHost(openDirectConnection(), "tcp://h:7000?password=x")).toEqual({
mode: "uri",
uri: "tcp://h:7000?password=x",
prompt: null,
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({
mode: "uri",
uri: "tcp://secure.example.test:7443?ssl=true&password=example",
});
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,
@@ -177,6 +534,11 @@ describe("typing in Host", () => {
uri: OFFER_LINK,
prompt: null,
});
expect(pasteDirectConnection(openDirectConnection(), OFFER_LINK)).toEqual({
mode: "uri",
uri: OFFER_LINK,
prompt: null,
});
});
});
@@ -1,6 +1,11 @@
import {
buildDirectConnectionUri,
normalizeDirectConnectionHost,
defaultPortForDirectScheme,
isPairingLink,
parseDirectConnectionAddress,
parseDirectConnectionPaste,
resolveDirectHostDraft,
resolveDirectSchemeTls,
type DirectConnectionHostLabels,
} from "@/components/direct-connection-host";
import { parseConnectionOfferFromUrl } from "@getpaseo/protocol/connection-offer";
@@ -38,7 +43,6 @@ 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: "" };
@@ -59,21 +63,97 @@ 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 { ...input, ...fields };
return { ...commitDirectFormHost(input), ...fields };
}
/** 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 {
/**
* 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 {
if (input.mode !== "form") return input;
if (looksLikeUri(text)) return { mode: "uri", uri: text.trim(), prompt: null };
if (
options?.allowSmartPaste !== false &&
isWholeFieldPasteChange(input.host, text, options?.selection)
) {
const pasted = pasteDirectConnection(input, text);
if (pasted) return pasted;
}
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;
@@ -100,11 +180,12 @@ export function resolveConnection(
input: DirectConnectionInput,
labels: DirectConnectionHostLabels,
): ResolvedDirectConnection {
if (input.mode === "form") {
return resolveTcpUri(buildDirectConnectionUri(input, labels));
const effective = commitHost(input);
if (effective.mode === "form") {
return resolveTcpUri(buildDirectConnectionUri(effective, labels));
}
const uri = input.uri.trim();
const promptPassword = input.prompt?.password || undefined;
const uri = effective.uri.trim();
const promptPassword = effective.prompt?.password || undefined;
if (isPairingLink(uri)) {
return { kind: "relay", link: uri, ...(promptPassword ? { password: promptPassword } : {}) };
}
@@ -123,43 +204,85 @@ function resolveTcpUri(uri: string, passwordOverride?: string): ResolvedDirectCo
};
}
/** The three link formats a daemon prints for pairing: `relay://`, `#connect=`, and `#offer=`. */
function isPairingLink(uri: string): boolean {
const trimmed = uri.trim();
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);
return (
trimmed.toLowerCase().startsWith("relay://") ||
trimmed.includes("#connect=") ||
trimmed.includes("#offer=")
next.length >= prefix.length + suffix.length && next.startsWith(prefix) && next.endsWith(suffix)
);
}
function looksLikeUri(text: string): boolean {
return TCP_URI_PATTERN.test(text.trim()) || isPairingLink(text);
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);
}
// 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 normalized = normalizeDirectConnectionHost(input.host);
if (!normalized.host) return "";
const host = normalized.isIpv6 ? `[${normalized.host}]` : normalized.host;
const port = normalized.port ?? input.port.trim();
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 query = new URLSearchParams();
if (input.useTls) query.set("ssl", "true");
if (input.password) query.set("password", input.password);
if (resolved.useTls) query.set("ssl", "true");
if (resolved.password) query.set("password", resolved.password);
const search = query.toString();
return `tcp://${host}:${port}${search ? `?${search}` : ""}`;
return `tcp://${host}:${resolved.port}${search ? `?${search}` : ""}`;
}
function uriToForm(uri: string): DirectConnectionForm {
const address = splitUri(uri);
const address = parseDirectConnectionAddress(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: address.port ?? DEFAULT_PORT,
useTls: address.query.get("ssl") === "true",
password: address.query.get("password") ?? "",
port,
useTls: resolveDirectSchemeTls(address.scheme, address.sslParam) ?? false,
password: address.password ?? "",
};
}
@@ -174,35 +297,7 @@ export function uriHostLabel(uri: string): string | null {
return null;
}
}
const address = splitUri(trimmed);
const address = parseDirectConnectionAddress(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,15 +796,14 @@ function ListedPluginLayout({
{hero}
<View style={styles.twoCol}>
<View style={styles.main}>
<View style={styles.tabBar}>
<ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.tabBar}>
<SegmentedControl
options={tabs}
value={activeTab}
onValueChange={onTabChange}
wrap
testID="plugin-page-tabs"
/>
</View>
</ScrollView>
{panel}
</View>
@@ -1086,7 +1085,12 @@ const styles = StyleSheet.create((theme) => ({
},
controls: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] },
installRow: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] },
tabBar: { marginBottom: theme.spacing[4], alignSelf: "flex-start", maxWidth: "100%" },
tabBar: {
flexGrow: 0,
marginBottom: theme.spacing[4],
alignSelf: "flex-start",
maxWidth: "100%",
},
compactTabScroll: { flexGrow: 0 },
description: {
color: theme.colors.foreground,
+42 -1
View File
@@ -10,7 +10,14 @@
* 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, mixHexColors, stepContrast, translucentStep } from "@/utils/color";
import {
contrastRatio,
isTranslucentHexColor,
mixHexColors,
paintHexOver,
stepContrast,
translucentStep,
} from "@/utils/color";
export type ColorScheme = "light" | "dark";
@@ -53,6 +60,10 @@ 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,
@@ -133,3 +144,33 @@ 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);
}
+116 -3
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 } from "@/utils/color";
import { contrastRatio, mixHexColors, paintHexOver } 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,11 +70,80 @@ 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].map((contribution) => ({
...[
LATTE,
MOCHA,
SOLARIZED_LIGHT,
SOLARIZED_DARK,
TRANSLUCENT_DARK,
TRANSLUCENT_LIGHT,
TRANSLUCENT_HIGH_CONTRAST_CONTROL,
OPAQUE_HIGH_CONTRAST_CONTROL,
].map((contribution) => ({
name: `plugin ${contribution.name}`,
theme: buildPluginTheme(contribution),
})),
@@ -99,9 +168,14 @@ 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()` token shows once painted over `surface`. */
/** The color a translucent `rgba()` or hex 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);
@@ -184,6 +258,33 @@ 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;
@@ -275,4 +376,16 @@ 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,
);
},
);
});
+23 -1
View File
@@ -1,7 +1,13 @@
import { Platform, type ViewStyle } from "react-native";
import { isWeb } from "@/constants/platform";
import { paintHexOver } from "@/utils/color";
import { darkHighlightColors, lightHighlightColors } from "@getpaseo/highlight";
import { derivePageSurfaceStates, deriveSurfaceStates, deriveTreeGuide } from "./derive-colors";
import {
deriveBorderFocus,
derivePageSurfaceStates,
deriveSurfaceStates,
deriveTreeGuide,
} from "./derive-colors";
export const baseColors = {
// Base colors
@@ -287,6 +293,8 @@ 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,
@@ -295,6 +303,12 @@ 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,
@@ -425,6 +439,8 @@ 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,
@@ -433,6 +449,12 @@ 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,7 +3,9 @@ import {
contrastRatio,
desaturateHexColor,
hexColorWithAlpha,
isTranslucentHexColor,
mixHexColors,
paintHexOver,
parseHexColor,
stepContrast,
} from "./color";
@@ -118,3 +120,15 @@ 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,3 +184,25 @@ 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,6 +49,7 @@ 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,6 +227,9 @@ 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,23 +338,3 @@ 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: options.refresh,
forceRefresh: true,
});
entry = refreshed.reports.find((report) => report.id === selection.id);
}
@@ -94,6 +94,12 @@ 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 (_: Exception) {
} catch (_: Throwable) {
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 (_: Exception) {
} catch (_: Throwable) {
// 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 (_: Exception) {
} catch (_: Throwable) {
null
}
}
@@ -189,7 +189,7 @@ object SegmentViewCreators {
}
resolvedClass.getMethod("applyLatex", String::class.java).invoke(view, segment.latex)
view
} catch (e: Exception) {
} catch (e: Throwable) {
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: Exception) {
} catch (e: Throwable) {
Log.e("MathSpan", "Failed to replace math spans", e)
}
}
@@ -2,6 +2,7 @@ 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
@@ -14,11 +15,15 @@ class MathInlineRenderer(
override fun render(
node: MarkdownASTNode,
builder: SpannableStringBuilder,
onLinkPress: ((String) -> Unit)?,
onLinkPress: ((String, String) -> Unit)?,
onLinkLongPress: ((String) -> Unit)?,
factory: RendererFactory,
) {
RaTeXFontLoader.ensureLoaded(context)
try {
RaTeXFontLoader.ensureLoaded(context)
} catch (e: Throwable) {
Log.w(TAG, "Failed to load RaTeX fonts; math will fall back to raw LaTeX", e)
}
val latex = extractLatex(node)
if (latex.isEmpty()) return
@@ -52,4 +57,8 @@ class MathInlineRenderer(
}
}
}
private companion object {
const val TAG = "MathInlineRenderer"
}
}
@@ -59,7 +59,11 @@ class MathContainerView(
val paddingPx = mathStyle.padding.toInt()
RaTeXFontLoader.ensureLoaded(context)
try {
RaTeXFontLoader.ensureLoaded(context)
} catch (e: Throwable) {
Log.w(TAG, "Failed to load RaTeX fonts; math will fall back to raw LaTeX", e)
}
val mathLayoutParams =
FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply {
@@ -97,7 +101,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: Exception) {
} catch (e: Throwable) {
Log.e(TAG, "Failed to render LaTeX", e)
mathView.renderer = null
mathView.fallbackText = "\$\$" + latex + "\$\$"
@@ -31,6 +31,7 @@ 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) }
@@ -47,7 +48,7 @@ class MathInlineSpan(
renderer.draw(Canvas(bitmap))
cachedBitmap = bitmap
} catch (e: Exception) {
} catch (e: Throwable) {
renderFailed = true
fallbackText = "\$" + latex + "\$"
onLatexError?.report(latex, e.message, false)
@@ -14,7 +14,12 @@ object MathMeasureHelper {
): List<MathMetrics> {
if (requests.isEmpty()) return emptyList()
RaTeXFontLoader.ensureLoaded(context)
try {
RaTeXFontLoader.ensureLoaded(context)
} catch (e: Throwable) {
Log.w(TAG, "Failed to load RaTeX fonts; using fallback metrics", e)
return requests.map { estimateFallback(it) }
}
return requests.map { request ->
runCatching { measureSingle(context, request) }.getOrElse { estimateFallback(request) }
@@ -54,4 +59,6 @@ object MathMeasureHelper {
descent = h * 0.3f,
)
}
private const val TAG = "MathMeasureHelper"
}
@@ -0,0 +1,88 @@
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,6 +37,26 @@ 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,6 +8,10 @@ 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,7 +6,10 @@
"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": {
@@ -14,21 +17,24 @@
"version": "0.24.8",
"scanner": false,
"default": true,
"size": "27 KB"
"size": "27 KB",
"sha256": "39e96d1e4231d200562ebd69105151cd43f58dda4b18a0e9a62fe2991da35b9c"
},
"html": {
"package": "tree-sitter-html",
"version": "0.23.2",
"scanner": true,
"default": true,
"size": "76 KB"
"size": "76 KB",
"sha256": "6b024fc38fce2b4807d0ac35023487da682a15cd986ba2ee9d6c25feff9392ed"
},
"css": {
"package": "tree-sitter-css",
"version": "0.23.2",
"scanner": true,
"default": true,
"size": "0.5 MB"
"size": "0.5 MB",
"sha256": "7dd088805e0f206d6b15d13ce717f9be89b9ff023efcc7970ca5a9064aa45aba"
},
"markdown": {
"package": "@tree-sitter-grammars/tree-sitter-markdown",
@@ -37,115 +43,141 @@
"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."
"$comment": "Multi-grammar package; the block grammar (tree-sitter-markdown/) is vendored. The inline sub-grammar is not linked.",
"sha256": "f582346e65479e1d6d025e9b785421f623eb549390c550899005fd6f7f37d739"
},
"yaml": {
"package": "@tree-sitter-grammars/tree-sitter-yaml",
"version": "0.7.1",
"scanner": true,
"default": true,
"size": "1 MB"
"size": "1 MB",
"sha256": "30dbdc539dcfa905252a0d1772270d457d58ceddfa3d6a4fac564f02837241ba"
},
"go": {
"package": "tree-sitter-go",
"version": "0.23.4",
"scanner": false,
"default": true,
"size": "1 MB"
"size": "1 MB",
"sha256": "8779d20d322b4319ad8c833ea72ecb6d109cf1fec8979bdcdb5315a2e511dd2c"
},
"java": {
"package": "tree-sitter-java",
"version": "0.23.5",
"scanner": false,
"default": true,
"size": "2.5 MB"
"size": "2.5 MB",
"sha256": "6b6c1b62605f9d8bb80efd2ebe5951a87b182faafa3eeb67c460a667818551b6"
},
"javascript": {
"package": "tree-sitter-javascript",
"version": "0.23.1",
"scanner": true,
"default": true,
"size": "2.8 MB"
"size": "2.8 MB",
"sha256": "90e80b25a67517a4daf6ad751557bee21efbda7b7a5a554897933245d1734398"
},
"python": {
"package": "tree-sitter-python",
"version": "0.23.6",
"scanner": true,
"default": true,
"size": "3.4 MB"
"size": "3.4 MB",
"sha256": "aab5b860d93dbf84b37fed532f7dacc0468ede5387d0c74911d68f964287662a"
},
"c": {
"package": "tree-sitter-c",
"version": "0.23.5",
"scanner": false,
"default": true,
"size": "3.8 MB"
"size": "3.8 MB",
"sha256": "20edb0872863769947f5c10839ca5420909a991bc79eb55666b74f0c11305c89"
},
"rust": {
"package": "tree-sitter-rust",
"version": "0.23.2",
"scanner": true,
"default": true,
"size": "6.3 MB"
"size": "6.3 MB",
"sha256": "085f2e9cedb916c466b53180d6e4287148e309593e61ea92e2c4b01904d193bb"
},
"bash": {
"package": "tree-sitter-bash",
"version": "0.23.3",
"scanner": true,
"default": true,
"size": "9.7 MB"
"size": "9.7 MB",
"sha256": "10f4d67f56e07bc6cc34c49afb34e232269c1e0a19933880dfdb5dd738a8fc7d"
},
"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"
"size": "17 MB",
"sha256": "0fdf63c35930a75885145d75ee63cb879da2d49db9bfe454bd8e60b08ba778a1"
},
"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"
"size": "17 MB",
"sha256": "0fdf63c35930a75885145d75ee63cb879da2d49db9bfe454bd8e60b08ba778a1"
},
"cpp": {
"package": "tree-sitter-cpp",
"version": "0.23.4",
"scanner": true,
"inherits": ["c"],
"inherits": [
"c"
],
"default": false,
"size": "17 MB"
"size": "17 MB",
"sha256": "615d152f70e7a6bed8f15a93c3c0c264c40dc71c1b6a1445646fff9439e776bc"
},
"swift": {
"package": "tree-sitter-swift",
"version": "0.7.0",
"scanner": true,
"default": false,
"size": "18 MB"
"size": "18 MB",
"sha256": "e0a20f341d10c0a8338c151b72abead83400945c36386def0785c6c189116e39"
},
"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"
"size": "14 MB",
"sha256": "fdd22530d3845540ba74a1199d3f67204a608c99994bb423645d3f0cfdaead94"
},
"ruby": {
"package": "tree-sitter-ruby",
"version": "0.23.1",
"scanner": true,
"default": false,
"size": "15 MB"
"size": "15 MB",
"sha256": "1f0f0c100e31ddf650962ebb1f1fb8420bdbabccd49582f6e731ea7478db639d"
},
"c-sharp": {
"package": "tree-sitter-c-sharp",
@@ -153,7 +185,8 @@
"scanner": true,
"function": "tree_sitter_c_sharp",
"default": false,
"size": "29 MB"
"size": "29 MB",
"sha256": "19c59068a19ff74b688c0985a19382503fc16b27f2b44b392aed908106700805"
}
}
}
@@ -7,6 +7,10 @@ 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,4 +2,5 @@
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 { indexTaskItems, markInlineImages } from "./utils.js";
import { loadKaTeX } from "./katex.js";
import { hasMathNode, indexTaskItems, markInlineImages } from "./utils.js";
import { getLoadedKaTeX, 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(null);
const [katex, setKatex] = useState(() => (md4cFlags.latexMath ?? true) ? getLoadedKaTeX() : null);
const [parseError, setParseError] = useState(false);
const {
underline = false,
@@ -45,6 +45,7 @@ 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);
@@ -83,10 +84,22 @@ 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 && (!latexMath || katex)) return;
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;
};
}
let cancelled = false;
const katexPromise = latexMath ? loadKaTeX() : Promise.resolve(null);
Promise.all([parseMarkdown(markdown, {
parseMarkdown(markdown, {
underline,
latexMath,
superscript,
@@ -95,17 +108,21 @@ export const EnrichedMarkdownText = ({
hardSoftBreaks,
preserveBlankLines,
admonitions
}), katexPromise]).then(([result, katexInstance]) => {
if (!cancelled) {
indexTaskItems(result);
markInlineImages(result);
setParseError(false);
}).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) {
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__) {
@@ -119,7 +136,7 @@ export const EnrichedMarkdownText = ({
return () => {
cancelled = true;
};
}, [markdown, underline, latexMath, superscript, subscript, highlight, hardSoftBreaks, preserveBlankLines, admonitions, textLinkKey, inlineCodeLinkKey, immediate, katex]);
}, [markdown, underline, latexMath, superscript, subscript, highlight, hardSoftBreaks, preserveBlankLines, admonitions, textLinkKey, inlineCodeLinkKey, immediate, activeKatex]);
const callbacks = useMemo(() => ({
onLinkPress,
onLinkLongPress,
@@ -128,10 +145,10 @@ export const EnrichedMarkdownText = ({
onCodeBlockPress
}), [onLinkPress, onLinkLongPress, onImagePress, onTaskListItemPress, onCodeBlockPress]);
const capabilities = useMemo(() => ({
katex,
katex: activeKatex,
enableTaskListItemToggle,
renderers
}), [katex, enableTaskListItemToggle, renderers]);
}), [activeKatex, enableTaskListItemToggle, renderers]);
const lastChildStyle = useMemo(() => allowTrailingMargin ? normalizedStyle : zeroTrailingMargins(normalizedStyle), [normalizedStyle, allowTrailingMargin]);
const styles = useMemo(() => buildStyles(normalizedStyle), [normalizedStyle]);
const lastChildStyles = useMemo(() => buildStyles(lastChildStyle), [lastChildStyle]);
@@ -180,4 +197,4 @@ export const EnrichedMarkdownText = ({
});
};
export default EnrichedMarkdownText;
//# sourceMappingURL=EnrichedMarkdownText.js.map
//# sourceMappingURL=EnrichedMarkdownText.js.map
@@ -1,22 +1,69 @@
"use strict";
let loadedKatex = null;
let katexLoadPromise = null;
let styleLoader = null;
let styleLoadPromise = null;
let stylesReady = true;
/** Lazily loads KaTeX. Resolves to null if not installed. */
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. */
export function loadKaTeX() {
if (loadedKatex && stylesReady) {
return Promise.resolve(loadedKatex);
}
if (!katexLoadPromise) {
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);
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;
});
}
return katexLoadPromise;
}
//# sourceMappingURL=katex.js.map
//# sourceMappingURL=katex.js.map
@@ -2,6 +2,43 @@
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,
@@ -9,24 +46,28 @@ export function KaTeXRenderer({
style
}) {
const delimiter = displayMode ? '$$' : '$';
const mathSource = displayMode ? `$$\n${content.trim()}\n$$` : `$${content}$`;
const html = useMemo(() => {
if (!katex) return null;
return katex.renderToString(content, {
output: 'mathml',
displayMode,
throwOnError: false,
trust: false
});
return renderKaTeXHtml(katex, content, displayMode);
}, [katex, content, displayMode]);
const displayStyle = displayMode ? {
...style,
display: 'block',
whiteSpace: 'pre-wrap'
maxWidth: '100%',
overflowX: 'auto',
overflowY: 'hidden',
boxSizing: 'border-box',
...(html ? null : {
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}`
});
@@ -34,10 +75,12 @@ 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,4 +60,12 @@ 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,6 +5,8 @@ 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,6 +1,7 @@
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,11 +1,19 @@
export interface KaTeXInstance {
renderToString(expression: string, options?: {
displayMode?: boolean;
throwOnError?: boolean;
trust?: boolean;
output?: 'html' | 'mathml' | 'htmlAndMathml';
}): string;
export interface KaTeXRenderOptions {
displayMode?: boolean;
throwOnError?: boolean;
trust?: boolean;
maxSize?: number;
maxExpand?: number;
strict?: boolean | 'ignore' | 'warn' | 'error';
output?: 'html' | 'mathml' | 'htmlAndMathml';
}
/** Lazily loads KaTeX. Resolves to null if not installed. */
export interface KaTeXInstance {
renderToString(expression: string, options?: KaTeXRenderOptions): 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. */
export declare function loadKaTeX(): Promise<KaTeXInstance | null>;
//# sourceMappingURL=katex.d.ts.map
//# sourceMappingURL=katex.d.ts.map
@@ -18,4 +18,6 @@ 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;
enableMath = enableMath !== false && process.env.PASEO_FDROID_BUILD !== '1';
if (!enableCodeHighlight && !enableMath) {
console.log(`${LOG} both code highlighting and math are disabled via package.json ("enriched-markdown"); skipping postinstall.`);
@@ -279,7 +279,9 @@ if (enableCodeHighlight) {
}
// RaTeX XCFramework + Swift sources + fonts (iOS math)
if (!enableMath) {
if (process.env.PASEO_FDROID_BUILD === '1') {
console.log(`${LOG} F-Droid build (PASEO_FDROID_BUILD=1); skipping RaTeX iOS assets.`);
} else 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,6 +17,12 @@ 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,6 +9,12 @@ 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 { indexTaskItems, markInlineImages } from './utils';
import { loadKaTeX } from './katex';
import { hasMathNode, indexTaskItems, markInlineImages } from './utils';
import { getLoadedKaTeX, loadKaTeX } from './katex';
import type { KaTeXInstance } from './katex';
import { ENRM_TEXT_CLASS, ENRM_SELECTION_BG_VAR } from './globalStyles';
import { filterNativeOnlyProps } from './nativeProps';
@@ -51,7 +51,9 @@ export const EnrichedMarkdownText = ({
ast: ASTNode;
markdown: string;
} | null>(null);
const [katex, setKatex] = useState<KaTeXInstance | null>(null);
const [katex, setKatex] = useState<KaTeXInstance | null>(() =>
(md4cFlags.latexMath ?? true) ? getLoadedKaTeX() : null
);
const [parseError, setParseError] = useState<boolean>(false);
const {
@@ -65,6 +67,8 @@ 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;
@@ -117,40 +121,60 @@ export const EnrichedMarkdownText = ({
]);
useEffect(() => {
if (immediate && (!latexMath || katex)) return;
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;
};
}
let cancelled = false;
const katexPromise = latexMath ? loadKaTeX() : Promise.resolve(null);
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;
Promise.all([
parseMarkdown(markdown, {
underline,
latexMath,
superscript,
subscript,
highlight,
hardSoftBreaks,
preserveBlankLines,
admonitions,
}),
katexPromise,
])
.then(([result, katexInstance]) => {
if (!cancelled) {
indexTaskItems(result);
markInlineImages(result);
setParseError(false);
setParseError(false);
if (katexInstance) {
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) {
@@ -180,7 +204,7 @@ export const EnrichedMarkdownText = ({
textLinkKey,
inlineCodeLinkKey,
immediate,
katex,
activeKatex,
]);
const callbacks = useMemo<RendererCallbacks>(
@@ -201,8 +225,8 @@ export const EnrichedMarkdownText = ({
);
const capabilities = useMemo<RenderCapabilities>(
() => ({ katex, enableTaskListItemToggle, renderers }),
[katex, enableTaskListItemToggle, renderers]
() => ({ katex: activeKatex, enableTaskListItemToggle, renderers }),
[activeKatex, enableTaskListItemToggle, renderers]
);
const lastChildStyle = useMemo(

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